// Generated by CoffeeScript 1.12.7
var ez5;

ez5 = (function() {
  function ez5() {}

  ez5.FRONTEND_VERSION = "5.153.0";

  ez5.cssLoader = new CUI.CSSLoader();

  ez5.handleFrontendError = function(errorEvent, show_to_user) {
    var show_msg;
    if (show_to_user == null) {
      show_to_user = false;
    }
    show_msg = (function(_this) {
      return function(event) {
        var event_id, loca_key, ref;
        event_id = event != null ? (ref = event.event) != null ? ref._id : void 0 : void 0;
        if (event_id) {
          loca_key = 'general.frontend.error.message_with_id.md';
        } else {
          loca_key = 'general.frontend.error.message.md';
        }
        return CUI.confirm({
          "class": 'cui-alert-problem',
          text: $$(loca_key, {
            event_id: event_id
          }),
          button_text_ok: $$('general.frontend.error.button.ok'),
          button_text_cancel: $$('general.frontend.error.button.reload'),
          markdown: true
        }).fail(function() {
          return document.location.reload();
        });
      };
    })(this);
    return this.saveErrorEvent(errorEvent).always((function(_this) {
      return function(event) {
        if (show_to_user) {
          return show_msg(event);
        }
      };
    })(this));
  };

  ez5.saveErrorEvent = function(errorEvent) {
    var ref, ref1;
    return EventPoller.saveEvent({
      type: "FRONTEND_ERROR",
      info: {
        message: ((ref = errorEvent.error) != null ? ref.message : void 0) || errorEvent.message,
        navigator: navigator.userAgent,
        stack: (ref1 = errorEvent.error) != null ? ref1.stack : void 0
      }
    });
  };

  ez5.version = function(exp_version) {
    var idx, j, len1, part_exp, parts_exp, parts_v, ref, ref1, v;
    v = ((ref = ez5.settings) != null ? ref.version : void 0) || null;
    if (v) {
      v = v.replace(/^v/, "");
    } else {
      v = ((ref1 = ez5.settings) != null ? ref1.easydb_version : void 0) || null;
    }
    if (CUI.util.isEmpty(exp_version)) {
      return v;
    }
    if (v === null) {
      return false;
    }
    parts_v = v.split(".").map((function(_this) {
      return function(v) {
        return parseInt(v);
      };
    })(this));
    parts_exp = exp_version.split(".").map((function(_this) {
      return function(v) {
        return parseInt(v);
      };
    })(this));
    for (idx = j = 0, len1 = parts_exp.length; j < len1; idx = ++j) {
      part_exp = parts_exp[idx];
      if (parts_v[idx] > part_exp) {
        return true;
      }
      if (part_exp > parts_v[idx]) {
        return false;
      }
    }
    return true;
  };

  ez5.callbacks = {};

  ez5.state = "loading";

  ez5.fitRectangle = function(img_w, img_h, w, h) {
    var dest_h, dest_w, img_aspect, margin_left, margin_top, viewport_aspect;
    CUI.util.assert(img_w > 0 && img_h > 0 && w > 0 && h > 0, "ez5.fit_rectangle", "img_w, img_h, w and h need to be > 0", {
      img_w: img_w,
      img_h: img_h,
      w: w,
      h: h
    });
    img_aspect = img_w / img_h;
    viewport_aspect = w / h;
    if (img_aspect > viewport_aspect) {
      dest_w = w;
      dest_h = dest_w / img_aspect;
    } else if (img_aspect < viewport_aspect) {
      dest_h = h;
      dest_w = dest_h * img_aspect;
    } else {
      dest_w = w;
      dest_h = h;
    }
    margin_top = (h - dest_h) / 2;
    margin_left = (w - dest_w) / 2;
    return [dest_w, dest_h, margin_top, margin_left];
  };

  ez5.format_seconds = function(seconds) {
    var h, m, s;
    if (seconds === 2e308) {
      return "--:--";
    }
    h = Math.floor(seconds / 3600);
    m = Math.floor((seconds - h * 3600) / 60);
    s = Math.ceil(seconds - h * 3600 - m * 60);
    if (s < 10) {
      s = "0" + s;
    }
    if (h > 0 && m < 10) {
      m = "0" + m;
    }
    if (h > 0) {
      return h + ":" + m + ":" + s;
    } else {
      return m + ":" + s;
    }
  };

  ez5.format_date_and_time = function(date_s, include_seconds) {
    var mom;
    if (include_seconds == null) {
      include_seconds = false;
    }
    if (CUI.util.isEmpty(date_s)) {
      return "";
    }
    if (date_s instanceof Date) {
      mom = CUI.util.moment(date_s);
      date_s = mom.format(CUI.DateTimeFormats[ez5.loca.getLanguage()].formats.display_short);
    }
    if (include_seconds) {
      return CUI.DateTime.format(date_s, "display_short", "date_time_seconds");
    } else {
      return CUI.DateTime.format(date_s, "display_short", "date_time");
    }
  };

  ez5.format_date = function(date_s) {
    return CUI.DateTime.format(date_s, "display_short", "date");
  };

  ez5.dirname = function(path) {
    var _path;
    if (CUI.util.isEmpty(path)) {
      return "";
    }
    _path = path.split(/[\/]/);
    _path.pop();
    switch (_path.length) {
      case 0:
        return '';
      case 1:
        if (_path[0] === '') {
          return '/';
        }
    }
    return _path.join('/');
  };

  ez5.basename = function(path) {
    if (CUI.util.isEmpty(path)) {
      return "";
    }
    return path.split(/[\/]/).pop();
  };

  ez5.extension = function(path) {
    var _path, basename;
    basename = this.basename(path);
    if (CUI.util.isEmpty(basename)) {
      return '';
    }
    _path = basename.split(/\./);
    if (_path.length > 1) {
      return _path.pop();
    } else {
      return '';
    }
  };

  ez5.bareBasename = function(path) {
    var _path, basename;
    basename = this.basename(path);
    if (CUI.util.isEmpty(basename)) {
      return '';
    }
    _path = basename.split(/\./);
    if (_path.length > 1) {
      _path.pop();
    }
    return _path.join('.');
  };

  ez5.getAbsoluteURL = function(url, server_url) {
    var loc;
    if (server_url == null) {
      server_url = window.easydb_server_url;
    }
    loc = CUI.parseLocation(url);
    if (!loc) {
      return "";
    } else if (loc.origin) {
      return url;
    } else if (server_url) {
      return server_url + url;
    } else {
      return document.location.origin + url;
    }
  };

  ez5.format_number = function(number) {
    if (CUI.util.isEmpty(number)) {
      return "";
    }
    if (typeof number === "number") {
      return CUI.NumberInput.format(number, {
        decimalpoint: ez5.session.frontend_locale.numbers.decimal,
        separator: ez5.session.frontend_locale.numbers.grouping
      });
    } else {
      return number;
    }
  };

  ez5.format_bitrate = function(bits) {
    var gBits, kBits, mBits;
    if (typeof bits !== 'number') {
      return '';
    }
    if (bits >= 1000000000) {
      gBits = (bits / 1000000000).toFixed(2);
      return gBits + " Gbit/s";
    } else if (bits >= 1000000) {
      mBits = (bits / 1000000).toFixed(2);
      return mBits + " Mbit/s";
    } else if (bits >= 1000) {
      kBits = (bits / 1000).toFixed(2);
      return kBits + " kbit/s";
    } else {
      return (bits.toFixed(2)) + " bit/s";
    }
  };

  ez5.download_multiple_files = function(files, fylr_zip_url, zip_download_name) {
    var _files, file, form, j, json, len1;
    _files = [];
    for (j = 0, len1 = files.length; j < len1; j++) {
      file = files[j];
      _files.push({
        url: file.href,
        name: decodeURIComponent(ez5.basename(file.href))
      });
    }
    form = document.createElement("form");
    form.action = fylr_zip_url;
    form.target = '_parent';
    form.method = "POST";
    json = document.createElement("input");
    json.type = "hidden";
    json.name = "BODY";
    json.value = JSON.stringify({
      filename: zip_download_name + ".zip",
      files: _files
    });
    form.appendChild(json);
    document.body.appendChild(form);
    return form.submit();
  };

  ez5.download_files = function(files) {
    CUI.util.assert(CUI.util.isArray(files), "ez5.download_files", "Parameter 'files' needs to be an array", {
      files: files
    });
    return CUI.chunkWork.call(ez5, {
      items: files,
      chunk_size: 1,
      call: function(items) {
        var deferred;
        deferred = new CUI.Deferred();
        ez5.download_file(items[0]);
        CUI.setTimeout({
          ms: 3000,
          call: function() {
            return deferred.resolve();
          }
        });
        return deferred.promise();
      }
    });
  };

  ez5.download_file = function(file) {
    var a;
    a = CUI.dom.element("A");
    a.href = file.href;
    a.download = file.name || "";
    a.target = '_parent';
    (document.body || document.documentElement).appendChild(a);
    a.addEventListener("click", function() {
      return CUI.dom.remove(a);
    });
    return a.click();
  };

  ez5.copyToClipboard = function(text) {
    var e;
    try {
      return navigator.clipboard.writeText(text);
    } catch (error1) {
      e = error1;
      console.error("Error copying to clipboard: ", e);
      return CUI.alert({
        text: $$("general.clipboard.error")
      });
    }
  };

  ez5.format_filesize = function(bytes) {
    var base, i, sizes;
    if (isNaN(bytes)) {
      return "";
    }
    sizes = ["Bytes", "KB", "MB", "GB", "TB"];
    base = ez5.version("6") ? 1000 : 1024;
    i = parseInt(Math.floor(Math.log(bytes) / Math.log(base)));
    if (bytes === 0) {
      return "0 " + sizes[0];
    } else if (i <= 1) {
      return Math.round(bytes / Math.pow(base, i)) + " " + sizes[i];
    } else {
      return Math.round(bytes / Math.pow(base, i) * 10) / 10 + " " + sizes[i];
    }
  };

  ez5.buildObjectTree = function(_opts) {
    var __path, _object, _path, c, doOpen, fatherPool, i, idx, inputObjects, j, l, len1, len2, len3, len4, len5, len6, len7, level, max_level, n, newInstanceFunc, o, obj, object, objectCopy, objectIdKey, objectKey, object_by_path, objects, objecttype, opts, p, path, path_str, pseudoRoot, q, ref, ref1, ref2, ref3, ref4, ref5, t, u, x, y, z;
    if (_opts == null) {
      _opts = {};
    }
    opts = CUI.Element.readOpts.call(this, _opts, "ez5.buildObjectTree", {
      objects: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isArray(v);
        }
      },
      newInstanceFunc: {
        mandatory: true,
        check: Function
      },
      doOpen: {
        mandatory: true,
        "default": false,
        check: Boolean
      },
      filter: {
        mandatory: true,
        "default": false,
        check: Boolean
      },
      objectKey: {
        check: function(v) {
          return CUI.util.isString(v) || CUI.util.isFunction(v);
        }
      }
    });
    objectKey = opts.objectKey;
    newInstanceFunc = opts.newInstanceFunc;
    doOpen = opts.doOpen;
    objectIdKey = "_id";
    inputObjects = [];
    ref = opts.objects;
    for (j = 0, len1 = ref.length; j < len1; j++) {
      _object = ref[j];
      if (_object.hasOwnProperty("_path")) {
        _object.__path = _object._path;
        inputObjects.push(_object);
      } else if (_object.hasOwnProperty("_paths")) {
        if (_object._paths.length === 0) {
          objectCopy = CUI.util.copyObject(_object, true);
          objectCopy.__path = [objectCopy];
          inputObjects.push(objectCopy);
        } else {
          ref1 = _object._paths;
          for (l = 0, len2 = ref1.length; l < len2; l++) {
            __path = ref1[l];
            if (ez5.version("6.12") && (p = __path[0])) {
              if (p[p._objecttype]._id === 0) {
                objectCopy = CUI.util.copyObject(_object, true);
                objectCopy.__path = [objectCopy];
                inputObjects.push(objectCopy);
                continue;
              }
            }
            objectCopy = CUI.util.copyObject(_object, true);
            objectCopy.__path = CUI.util.copyObject(__path, true);
            objectCopy.__path.push(objectCopy);
            inputObjects.push(objectCopy);
          }
        }
      } else {
        inputObjects.push(_object);
      }
    }
    object_by_path = {};
    objects = [];
    max_level = -1;
    for (idx = n = 0, len3 = inputObjects.length; n < len3; idx = ++n) {
      o = inputObjects[idx];
      if (o._level === void 0) {
        if (o.hasOwnProperty("__path")) {
          o._level = o.__path.length;
        } else {
          o._level = 0;
        }
      }
      if (o._level > max_level) {
        max_level = o._level;
      }
    }
    for (level = q = 0, ref2 = max_level; q <= ref2; level = q += 1) {
      for (idx = t = 0, len4 = inputObjects.length; t < len4; idx = ++t) {
        o = inputObjects[idx];
        if (o._level !== level) {
          continue;
        }
        objecttype = o._basetype || o._objecttype;
        path = [objecttype];
        if (o.hasOwnProperty("__path")) {
          _path = o.__path;
        } else {
          _path = [o];
        }
        for (idx = u = 0, len5 = _path.length; u < len5; idx = ++u) {
          object = _path[idx];
          if (objectKey) {
            if (CUI.util.isFunction(objectKey)) {
              p = object[objectKey(object)][objectIdKey];
            } else {
              p = object[objectKey][objectIdKey];
            }
          } else {
            p = object[objectIdKey];
          }
          CUI.util.assert(!CUI.util.isEmpty(p), "ez5.buildObjectTree", "path element is empty", {
            objectKey: objectKey,
            objectIdKey: objectIdKey,
            object: object
          });
          path.push(p);
          path_str = path.join(".");
          if (object_by_path[path_str]) {
            continue;
          }
          if (idx === _path.length - 1) {
            obj = newInstanceFunc(o);
          } else {
            if (o._objecttype && ez5.schema.CURRENT._objecttype_by_name[o._objecttype].polyhierarchical && !object.hasOwnProperty("_paths") && idx > 0) {
              object._paths = [[]];
              for (i = x = 0, ref3 = idx - 1; 0 <= ref3 ? x <= ref3 : x >= ref3; i = 0 <= ref3 ? ++x : --x) {
                p = CUI.util.copyObjectV2(_path[i], true);
                delete p._path;
                object._paths[0].push(p);
              }
            }
            obj = newInstanceFunc(object);
            obj._build_from_path = true;
          }
          object_by_path[path_str] = obj;
          if (idx === 0) {
            objects.push(obj);
            continue;
          }
          fatherPool = object_by_path[path.slice(0, -1).join(".")];
          if (!fatherPool.children) {
            fatherPool.children = [];
            if (doOpen) {
              fatherPool.do_open = true;
            }
          }
          obj.father = fatherPool;
          fatherPool.children.push(obj);
        }
      }
    }
    if (opts.filter) {
      pseudoRoot = new CUI.ListViewTreeNode({
        children: objects
      });
      pseudoRoot.filter(function(node) {
        if (node._build_from_path) {
          return true;
        } else {
          return false;
        }
      });
      objects = [];
      ref4 = pseudoRoot.children;
      for (y = 0, len6 = ref4.length; y < len6; y++) {
        c = ref4[y];
        if (!((ref5 = c.children) != null ? ref5.length : void 0)) {
          delete c.do_open;
        }
        objects.push(c);
        c.setFather(null);
      }
    }
    for (z = 0, len7 = inputObjects.length; z < len7; z++) {
      _object = inputObjects[z];
      delete _object.__path;
      delete _object._level;
    }
    return objects;
  };

  ez5.groupTreeNodes = function(_opts) {
    var count, depth, generate_chunks, limit, nodes, opts;
    if (_opts == null) {
      _opts = {};
    }
    opts = CUI.Element.readOpts.call(this, _opts, "ez5.buildObjectTree", {
      newInstanceFunc: {
        mandatory: true,
        check: Function
      },
      limit: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isPosInt(v);
        }
      },
      nodes: {
        mandatory: true,
        check: function(v) {
          var father, idx, item, j, len1;
          if (!CUI.util.isArray(v)) {
            return false;
          }
          father = null;
          for (idx = j = 0, len1 = v.length; j < len1; idx = ++j) {
            item = v[idx];
            if (!(item instanceof CUI.ListViewTreeNode)) {
              return false;
            }
            if (idx === 0) {
              father = item.getFather();
            } else if (father !== item.getFather()) {
              return false;
            }
          }
          return true;
        }
      }
    });
    nodes = opts.nodes;
    count = nodes.length;
    limit = opts.limit;
    if (count <= limit) {
      return nodes;
    }
    depth = 0;
    while (count > Math.pow(limit, depth)) {
      depth = depth + 1;
    }
    generate_chunks = (function(_this) {
      return function(offset, count, depth, father_node) {
        var chunk, from, group_nodes, idx, j, node, ref, to;
        chunk = Math.pow(limit, depth - 1);
        group_nodes = [];
        for (idx = j = 0, ref = Math.floor((count - 1) / chunk); 0 <= ref ? j <= ref : j >= ref; idx = 0 <= ref ? ++j : --j) {
          from = idx * chunk + offset;
          to = Math.min(count, (idx + 1) * chunk) + offset - 1;
          node = opts.newInstanceFunc(from, to, nodes);
          group_nodes.push(node);
          if (depth > 2) {
            generate_chunks(from, to - from + 1, depth - 1, node);
          } else {
            node.setChildren(nodes.slice(from, to + 1));
          }
        }
        if (father_node != null) {
          father_node.setChildren(group_nodes);
        }
        return group_nodes;
      };
    })(this);
    return generate_chunks(0, count, depth);
  };

  ez5.error_handler = function(xhr, serverRequest) {
    var allow_cancel, choices, content, description, dfr, error, markdown, offer_reload, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, server, server_url, text, title, uuid, valueID;
    if (xhr == null) {
      xhr = {};
    }
    if (serverRequest == null) {
      serverRequest = null;
    }
    dfr = new CUI.Deferred();
    error = xhr.responseJSON;
    allow_cancel = true;
    if (ez5.version("6") && error) {
      if (error.code === "validation.plugin.error") {
        return dfr.resolve();
      }
    }
    if (serverRequest) {
      server_url = serverRequest.getServerUrl();
      if (server_url === document.location.origin) {
        server_url = null;
      }
    } else {
      server_url = window.easydb_server_url;
    }
    console.warn("ez5.error_handler", xhr.readyState, xhr.status, error, xhr.CUI_statusText);
    if (xhr.readyState < 4 || !((error != null ? error.code : void 0) && (error != null ? error.realm : void 0))) {
      server = server_url || document.location.origin;
      offer_reload = true;
      if (xhr.status === 500) {
        text = $$("base.error.generic", {
          server: server
        });
        allow_cancel = false;
      } else if (xhr.CUI_statusText === "timeout") {
        text = $$("base.error.timeout", {
          server: server
        });
        offer_reload = false;
      } else if (xhr.readyState < 4 || xhr.status === 0) {
        text = $$("base.error.network", {
          server: server
        });
        allow_cancel = false;
      } else {
        console.error("easydb-server returned an unparsable error. xhr: ", xhr);
        text = $$("base.error.generic", {
          server: server
        });
      }
      markdown = true;
      choices = [
        offer_reload && server_url ? {
          text: $$("ez5.error_handler.reset_server", {
            server: server
          }),
          tooltip: {
            text: server
          },
          choice: "reset_server"
        } : void 0, offer_reload ? {
          text: $$("base.reload", {
            server: server
          }),
          choice: "reload"
        } : void 0, {
          text: $$("base.retry", {
            server: server
          }),
          choice: "retry"
        }
      ];
    } else {
      choices = [];
      title = $$("base.error.realm." + error.realm);
      if (ez5.loca.has(error.code)) {
        text = $$(error.code, error.parameters);
        markdown = true;
      } else {
        text = error.error || error.code;
        markdown = false;
      }
      allow_cancel = false;
      if ((ref = error.realm) === "transition_reject") {
        if (CUI.util.isEmpty((ref1 = error.parameters) != null ? ref1.messages : void 0)) {
          text = $$("base.error.transition_reject");
        }
      }
      if ((ref2 = error.realm) === "api" || ref2 === "server") {
        description = error.description;
      }
      if (((ref3 = error.realm) === "server") && error.uuid) {
        uuid = $$("base.error.uuid", {
          uuid: error.uuid
        });
      }
      if (ez5.version("6") && error.code === "UniqueKeyViolation" && ((ref4 = error.parameters) != null ? ref4.valuelinkedstandard : void 0) && ((ref5 = error.parameters) != null ? ref5.valuelinkedsystemobjectid : void 0)) {
        valueID = error.parameters.valuelinkedsystemobjectid;
        text = text.replace(new RegExp(valueID, "g"), error.parameters.valuelinkedstandard + " (ID: " + valueID + ")");
      }
      if (uuid && ((ref6 = ez5.session) != null ? ref6.hasSystemRight("root", "server.error.uuid_detail", "server.error.self_uuid_detail") : void 0)) {
        choices = [
          {
            text: $$("base.error.uuid.modal.btn"),
            choice: "show_error"
          }, {
            text: $$("base.ok"),
            primary: true
          }
        ];
      } else if ((ref7 = error.realm) === "user") {
        return CUI.problem({
          text: text
        });
      }
    }
    content = new CUI.Template({
      name: "error",
      map: {
        text: true,
        description: true,
        uuid: true
      }
    });
    content.replace(new CUI.Label({
      multiline: true,
      text: text,
      markdown: markdown
    }), "text");
    if (description) {
      content.replace(new CUI.Label({
        multiline: true,
        text: description
      }), "description");
    }
    if (uuid) {
      content.replace(new CUI.Label({
        multiline: true,
        text: uuid
      }), "uuid");
    }
    CUI.problem({
      title: title,
      choices: choices.length > 0 ? choices : void 0,
      content: content,
      cancel: allow_cancel
    }).fail(dfr.resolve).done((function(_this) {
      return function(choice) {
        var ref8;
        switch (choice.choice) {
          case "reload":
            document.location.reload();
            break;
          case "reset_server":
            CUI.setSessionStorage("server", void 0);
            if ((ref8 = ez5.session) != null) {
              ref8.saveCookiePref("easydb_server_url", null);
            }
            document.location.assign(window.easydb_base_prefix + "/");
            break;
          case "retry":
            dfr.reject();
            return;
          case "show_error":
            (new ServerErrorModal(error)).show();
        }
        return dfr.resolve();
      };
    })(this));
    return dfr.promise();
  };

  ez5.renderFormPopoverInfo = function(info) {
    var div, inf, j, len1;
    if (!(info != null ? info.length : void 0)) {
      return;
    }
    div = CUI.dom.div("ez5-form-popover-info");
    for (j = 0, len1 = info.length; j < len1; j++) {
      inf = info[j];
      div.appendChild(new CUI.Label({
        "class": "ez5-form-popover-info-item",
        text: inf
      }).DOM);
    }
    return div;
  };

  ez5.replaceMap = function(_value, rec, repl_default) {
    var k, map, map2, match, re, v, value;
    if (repl_default == null) {
      repl_default = "";
    }
    value = _value;
    map = {};
    re = new RegExp("%([\-\._\:a-z0-9]+)%", "g");
    while (match = re.exec(value)) {
      map[match[0]] = repl_default;
    }
    if (!CUI.util.isEmptyObject(map)) {
      map2 = {};
      for (k in rec) {
        v = rec[k];
        if (CUI.util.isArray(v)) {
          map2["%" + k + "%"] = v.join(", ");
        } else {
          map2["%" + k + "%"] = v;
        }
      }
      value = CUI.util.stringMapReplace(value, map2);
      value = CUI.util.stringMapReplace(value, map);
      console.error("REPLACED:", _value, value, map, map2);
    }
    return value;
  };

  ez5.weekdays = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];

  ez5.generateUUID = function() {
    var d;
    d = Date.now();
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r;
      r = (d + Math.random() * 16) % 16 | 0;
      d = Math.floor(d / 16);
      return (c === 'x' ? r : r & 0x3 | 0x8).toString(16);
    });
  };

  ez5.setDefaults = function() {
    ez5.defaults = {
      focusClass: "ez-focus",
      "class": {
        User: User,
        Group: Group,
        SystemGroup: SystemGroup,
        CustomGroup: CustomGroup,
        AnonymousUser: AnonymousUser,
        SystemUser: SystemUser,
        CollectionWorkfolder: CollectionWorkfolder,
        SearchCollection: SearchCollection,
        DownloadManager: DownloadManager,
        AdminMessage: AdminMessage,
        WebDVDPlayer: WebDVDPlayer
      }
    };
    return ez5.getLabelForCount = function(loca_key, count) {
      switch (count) {
        case 0:
          return new CUI.EmptyLabel({
            text: $$(loca_key + ".none", {
              count: count
            })
          });
        case 1:
          return new CUI.Label({
            text: $$(loca_key + ".one", {
              count: count
            })
          });
        default:
          return new CUI.Label({
            text: $$(loca_key, {
              count: count
            })
          });
      }
    };
  };

  ez5.add_ellipsis = function(str, len) {
    var chars;
    if (str.length <= len) {
      return str;
    }
    chars = str.split("");
    chars.splice(len / 2, str.length - len, "…");
    return chars.join("");
  };

  ez5.chunked_work = function(items, chunk_size, func) {
    var dfr, idx, len, next_chunk;
    CUI.util.assert(this !== ez5, "ez5.chunked_work", "Cannot call ez5.chunked_work with 'this' not set to the caller.");
    dfr = new CUI.Deferred();
    idx = 0;
    len = items.length;
    next_chunk = (function(_this) {
      return function() {
        var progress;
        progress = (idx + 1) + " - " + Math.min(len, idx + chunk_size) + " / " + len;
        dfr.notify({
          progress: progress,
          idx: idx,
          len: len,
          chunk_size: chunk_size
        });
        return func.call(_this, items.slice(idx, idx + chunk_size)).fail(dfr.reject).done(function() {
          if (idx + chunk_size >= len) {
            return dfr.resolve();
          } else {
            idx = idx + chunk_size;
            return CUI.setTimeout({
              ms: 10,
              call: next_chunk
            });
          }
        });
      };
    })(this);
    CUI.setTimeout({
      ms: 10,
      call: next_chunk
    });
    return dfr.promise();
  };

  ez5.splash = {
    show: function(loca_key, loca_key_attrs) {
      var ref;
      if ((ref = ez5.splash.__toaster) != null) {
        ref.destroy();
      }
      return ez5.splash.__toaster = CUI.toaster({
        show_ms: 0,
        content: new LocaLabel({
          loca_key: loca_key,
          loca_key_attrs: loca_key_attrs,
          ui: loca_key
        })
      });
    },
    done: function(loca_key, loca_key_attrs) {
      if (!ez5.splash.__toaster) {
        return;
      }
      if (loca_key) {
        ez5.splash.__toaster.setContent(new LocaLabel({
          loca_key: loca_key,
          loca_key_attrs: loca_key_attrs,
          ui: loca_key
        }));
      }
      return CUI.setTimeout({
        ms: 1000,
        call: function() {
          return ez5.splash.hide();
        }
      });
    },
    hide: function() {
      var ref;
      if ((ref = ez5.splash.__toaster) != null) {
        ref.destroy();
      }
      return ez5.splash.__toaster = null;
    }
  };

  return ez5;

})();

(function() {
  var fn, index_version, j, k, len1, ref, ref1;
  index_version = ((ref = document.getElementById("index-version")) != null ? ref.getAttribute("data-version") : void 0) || "1";
  if (index_version !== "2" && !window.headless_mode) {
    if (window.sessionStorage.getItem("index-version") === index_version) {
      console.warn("Accepting too old index.html after reload.");
    } else {
      console.warn("Reloading too old index.html.");
      try {
        window.sessionStorage.setItem("index-version", index_version);
        document.location.reload();
      } catch (error1) {}
    }
  } else {
    console.info("Index version is current.");
  }
  ref1 = ["session_ready", "defaults_done", "load_defaults"];
  fn = function(k) {
    return ez5[k] = function(callback) {
      var announceError, cb, e, l, len2, prm, promises, ref2;
      if (callback == null) {
        callback = null;
      }
      if (callback === null) {
        console.timeLog("Start", k + "...");
        promises = [];
        announceError = false;
        ref2 = ez5.callbacks[k];
        for (l = 0, len2 = ref2.length; l < len2; l++) {
          cb = ref2[l];
          try {
            prm = cb();
            if (CUI.util.isPromise(prm)) {
              console.timeLog("Start", "promise during " + k);
              prm.always((function(_this) {
                return function() {
                  return console.timeLog("Start", "promise done " + k);
                };
              })(this));
              prm.fail((function(_this) {
                return function() {
                  return console.warn(k, "was rejected");
                };
              })(this));
              promises.push(prm);
            }
          } catch (error1) {
            e = error1;
            announceError = true;
            console.error(k, "threw exception", e);
          }
        }
        if (announceError) {
          promises.push(CUI.problem({
            text: $$("start.error.unexpected")
          }));
        }
        return CUI.whenAll(promises).always(function() {
          return console.timeLog("Start", k + " done");
        });
      }
      CUI.util.assert(callback instanceof Function, "ez5." + k, "Parameter needs to be Function", {
        callback: callback
      });
      return ez5.callbacks[k].push(callback);
    };
  };
  for (j = 0, len1 = ref1.length; j < len1; j++) {
    k = ref1[j];
    ez5.callbacks[k] = [];
    fn(k);
  }
})();

CUI.ready((function(_this) {
  return function() {
    var renderer;
    renderer = new CUI.util.marked.Renderer();
    renderer.link = function(href, title, text) {
      var a_node;
      a_node = CUI.dom.element("A", {
        target: "_blank",
        href: href,
        title: title
      });
      a_node.innerHTML = text;
      return a_node.outerHTML;
    };
    CUI.defaults.marked_opts.renderer = renderer;
    CUI.defaults.asserts_alert = 'off';
    return CUI.Events.listen({
      node: window,
      type: 'error',
      call: function(ev) {
        ez5.handleFrontendError(ev.getNativeEvent(), ez5.session.isDebug() || CUI.__in_error);
      }
    });
  };
})(this));
// Generated by CoffeeScript 1.12.7
var SplashScreen,
  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;

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

  function SplashScreen(opts) {
    var template;
    SplashScreen.__super__.constructor.call(this, opts);
    template = new CUI.Template({
      name: "splash-screen"
    });
    this.registerTemplate(template);
  }

  SplashScreen.prototype.start = function() {
    var asset, bodyEl, customLogoEl, logo, splashScreen, version;
    bodyEl = document.querySelector("body");
    if (bodyEl != null) {
      bodyEl.classList.add("has-root-layout-visible");
    }
    splashScreen = document.querySelector(".cui-splash-screen");
    if (ez5.session.config.base.system.config.appearance.welcome_splash === "custom_logo") {
      logo = ez5.session.getConfigPicture("logo");
      if (logo) {
        customLogoEl = splashScreen.querySelector(".custom-logo");
        if (customLogoEl) {
          asset = new AssetPlain({
            value: logo
          });
          version = Asset.getBestImageForViewport(asset, 1000, 1000);
          CUI.dom.prepend(customLogoEl, asset.getImgElement(null, version.version));
        }
      }
    }
    if (splashScreen != null) {
      splashScreen.classList.add("animate");
    }
    CUI.Events.listen({
      type: "animationend",
      node: splashScreen,
      call: function(ev) {
        if (ev.getNativeEvent().target === ev.getNativeEvent().currentTarget) {
          return CUI.dom.remove(splashScreen);
        }
      }
    });
    return this;
  };

  return SplashScreen;

})(CUI.DOMElement);
// Generated by CoffeeScript 1.12.7
var arrayUnique, urlParameterByName;

arrayUnique = function(arr) {
  return arr.filter(function(val, i, arr) {
    return i <= arr.indexOf(val);
  });
};

urlParameterByName = function(name) {
  var match;
  match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
  return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
};
// Generated by CoffeeScript 1.12.7
var SchemaPlugin,
  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;

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

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

  SchemaPlugin.prototype.getCustomSettings = function(data) {
    return [];
  };

  SchemaPlugin.prototype.getCustomSettingsLabel = function(data) {
    return "";
  };

  SchemaPlugin.prototype.getCustomSettingsDisplay = function(data) {
    return [];
  };

  SchemaPlugin.prototype.getName = function() {
    return "";
  };

  return SchemaPlugin;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var Schema,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  Schema.STORE_FORMAT_VERSION = 1;

  Schema.prototype.apis = {
    schema: "/schema/user/{version}",
    mask: "/mask/{version}",
    all_fields_mask: "/mask/{version}/_all_fields"
  };

  Schema.__plugins = [];

  Schema.registerPlugin = function(plugin) {
    CUI.util.assert(plugin instanceof SchemaPlugin, 'Schema.registerPlugin', 'Plugin needs to be instance of SchemaPlugin.');
    return this.__plugins.push(plugin);
  };

  Schema.prototype.api = function(key, version) {
    return this.apis[key].replace(/{version}/, version);
  };

  Schema.prototype.initOpts = function() {
    Schema.__super__.initOpts.call(this);
    return this.addOpts({
      remoteEasydb: {
        check: function(v) {
          return v instanceof RemoteEasydb;
        }
      }
    });
  };

  Schema.prototype.getForStore = function(version) {
    var dfr, store;
    if (version == null) {
      version = 'HEAD';
    }
    dfr = new CUI.Deferred();
    store = {};
    this.load(null, store, [version], ['schema', 'mask']).done((function(_this) {
      return function() {
        return ez5.api.l10n({
          api: '/user/' + version,
          withCredentials: true
        }).done(function(data) {
          var key, value;
          for (key in store) {
            value = store[key];
            store[key] = value[version];
          }
          store.keys = data;
          store.version = store.schema.version;
          store.format_version = Schema.STORE_FORMAT_VERSION;
          return dfr.resolve(store);
        });
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  Schema.prototype.sendToServer = function(store) {
    var dfr;
    dfr = new CUI.Deferred();
    ez5.api.schema({
      type: 'POST',
      api: '/user/HEAD',
      json_data: store.schema
    }).fail(dfr.reject).done((function(_this) {
      return function() {
        return ez5.api.mask({
          type: 'POST',
          api: '/HEAD',
          json_data: store.mask
        }).fail(dfr.reject).done(function() {
          return ez5.api.l10n({
            api: '/user/HEAD',
            type: 'POST',
            withCredentials: true,
            json_data: store.keys
          }).done(function() {
            return dfr.resolve();
          });
        });
      };
    })(this));
    dfr.fail((function(_this) {
      return function() {
        return CUI.problem({
          text: $$('schema.send_to_server.problem')
        });
      };
    })(this));
    return dfr.promise();
  };

  Schema.prototype.getSchema = function(version, store) {
    if (store == null) {
      store = ez5;
    }
    return store.schema[version];
  };

  Schema.prototype.load = function(x_easydb, store, _versions, _keys) {
    var cache_sec, cache_ver, fn, i, j, key, keys, len, len1, promises, version, versions;
    if (store == null) {
      store = ez5;
    }
    promises = [];
    if (_versions) {
      versions = _versions;
    } else {
      versions = ['CURRENT'];
      if (Datamodel.getLevel()) {
        versions.push("HEAD");
      }
    }
    if (_keys) {
      keys = _keys;
    } else {
      keys = ["schema", "mask"];
      keys.push("all_fields_mask");
    }
    if (x_easydb) {
      cache_ver = x_easydb.base + "-" + x_easydb.user;
      cache_sec = 3600 * 24 * 100;
    }
    for (i = 0, len = keys.length; i < len; i++) {
      key = keys[i];
      store[key] = store[key] || {};
      fn = (function(_this) {
        return function(key, version) {
          var url_data;
          if (version === "CURRENT" && !ez5.version("6")) {
            url_data = {
              cache_version: cache_ver,
              cache_seconds: cache_sec
            };
          } else {
            url_data = ez5.session.fylrCacheParams();
          }
          url_data.format = "json";
          return promises.push(ez5.server({
            api: _this.api(key, version),
            remoteEasydb: _this._remoteEasydb,
            error: _this._remoteEasydb ? function() {
              return true;
            } : void 0,
            data: url_data
          }).done(function(data) {
            if (key === "mask") {
              _this.checkMaskData(data);
            }
            return store[key][version] = data;
          }));
        };
      })(this);
      for (j = 0, len1 = versions.length; j < len1; j++) {
        version = versions[j];
        store[key][version] = null;
        fn(key, version);
      }
    }
    if (indexOf.call(versions, "CURRENT") >= 0) {
      ez5.defaults_done((function(_this) {
        return function() {
          return _this.mergeObjecttypes();
        };
      })(this));
    }
    promises.push(ez5.loca.load_user_keys(x_easydb).always((function(_this) {
      return function() {
        return console.timeLog("Start", "schema user keys loaded");
      };
    })(this)));
    return CUI.when(promises).done((function(_this) {
      return function() {
        var k, l, len2, len3, m, ref;
        if (store !== ez5) {
          return;
        }
        ez5.all_fields_mask_preferred = {};
        for (k = 0, len2 = versions.length; k < len2; k++) {
          version = versions[k];
          ez5.schema.enrich_schema(ez5.schema[version], version);
          ez5.schema.enrich_mask_schema(ez5.mask[version], version);
          if (indexOf.call(keys, "all_fields_mask") >= 0) {
            ref = ez5.all_fields_mask[version].masks;
            for (l = 0, len3 = ref.length; l < len3; l++) {
              m = ref[l];
              m.name = "_all_fields";
            }
            ez5.all_fields_mask_preferred[version] = CUI.util.copyObject(ez5.all_fields_mask[version], true);
            ez5.schema.enrich_mask_schema(ez5.all_fields_mask_preferred[version], version, true, true);
            ez5.schema.enrich_mask_schema(ez5.all_fields_mask[version], version, true);
          }
        }
        _this.initPreferredMask("CURRENT");
        _this.initMaskInstances("CURRENT");
      };
    })(this));
  };

  Schema.prototype.checkMaskData = function(data) {
    var _field, field, i, idx, j, len, len1, mask, maxSplitterIdx, next_field, opts, ref, ref1, ref2, splitter;
    ref = data.masks;
    for (i = 0, len = ref.length; i < len; i++) {
      mask = ref[i];
      idx = 0;
      while (idx < mask.fields.length - 1) {
        field = mask.fields[idx];
        next_field = mask.fields[idx + 1];
        if (!(field.kind === "splitter" && field.type === "tabs-begin")) {
          idx++;
          continue;
        }
        if (next_field.kind === "splitter" && ((ref1 = next_field.type) === "tab" || ref1 === "tabs-end")) {
          idx++;
          continue;
        }
        maxSplitterIdx = -1;
        ref2 = mask.fields;
        for (j = 0, len1 = ref2.length; j < len1; j++) {
          _field = ref2[j];
          if (_field.kind === "splitter") {
            opts = JSON.parse(_field.options);
            if (opts.splitterIdx > maxSplitterIdx) {
              maxSplitterIdx = opts.splitterIdx;
            }
          }
        }
        splitter = {
          kind: "splitter",
          type: "tabs-begin",
          options: JSON.stringify({
            splitterIdx: maxSplitterIdx + 1
          })
        };
        mask.fields.splice(idx, 0, splitter);
        field.type = "tab";
        idx++;
      }
    }
  };

  Schema.prototype.initPreferredMask = function(version, store) {
    var i, len, mask, ref;
    if (store == null) {
      store = ez5;
    }
    ref = store.mask[version].masks;
    for (i = 0, len = ref.length; i < len; i++) {
      mask = ref[i];
      if (mask.is_preferred) {
        store.schema[version]._table_by_id[mask.table_id]._preferred_mask = mask;
      }
    }
    return this;
  };

  Schema.prototype.initMaskInstances = function(version, store) {
    var i, len, mask, ref;
    if (store == null) {
      store = ez5;
    }
    ref = store.mask[version].masks;
    for (i = 0, len = ref.length; i < len; i++) {
      mask = ref[i];
      if (store.mask[version]._mask_instance_by_name[mask.name]) {
        CUI.util.assert(!store.mask[version]._mask_instance_by_name[mask.name], "Schema.initMaskInstances", "@mask." + version + "._mask_instance_by_name: \"" + mask.name + " already exists.", {
          mask: mask
        });
      }
      store.mask[version]._mask_instance_by_name[mask.name] = new Mask(version, null, mask);
    }
    return this;
  };

  Schema.prototype.getDatatypeLocalized = function(type, version) {
    if (CUI.util.isEmpty(type)) {
      return;
    }
    if (type.match("^link_")) {
      return $$("datamodel.type.link", [ez5.schema[version]._table_by_id[type.substring(5)]._name_localized]);
    } else if (type.match("^custom:")) {
      return CustomDataType.get(type).getCustomDataTypeNameLocalized();
    } else {
      return $$("datamodel.type." + type);
    }
  };

  Schema.prototype.mergeObjecttypes = function() {
    var i, j, len, len1, ot, ref, ref1, tb;
    ref = ez5.schema.CURRENT.tables;
    for (i = 0, len = ref.length; i < len; i++) {
      tb = ref[i];
      ref1 = ez5.objecttypes.getObjecttypes();
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        ot = ref1[j];
        if (ot.objecttype._id === tb.table_id) {
          tb._objecttype = ot;
        }
      }
    }
  };

  Schema.prototype.getCustomSettings = function(data) {
    var fields, fieldsP, i, len, p, ref;
    fields = [];
    ref = Schema.__plugins;
    for (i = 0, len = ref.length; i < len; i++) {
      p = ref[i];
      fieldsP = p.getCustomSettings(data);
      if (!fieldsP) {
        continue;
      }
      fields.push({
        type: CUI.Form,
        render_as_block: true,
        form: {
          label: p.getCustomSettingsLabel(data)
        },
        fields: fieldsP
      });
    }
    return fields;
  };

  Schema.prototype.getCustomSettingsDisplay = function(data) {
    var i, info, infoP, len, p, ref;
    info = [];
    ref = Schema.__plugins;
    for (i = 0, len = ref.length; i < len; i++) {
      p = ref[i];
      infoP = p.getCustomSettingsDisplay(data);
      if (!infoP) {
        continue;
      }
      info.push.apply(info, infoP);
    }
    return info;
  };

  return Schema;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var $$, $empty$, $span$, Localization,
  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;

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

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

  Localization.prototype.init = function() {
    this.__multiInputControl = new LanguageControl();
    this.__multiInputControlDetail = new LanguageControl();
    return this.__multiInputControlAdmin = new LanguageControlAdmin();
  };

  Localization.prototype.getPreferredDatabaseLanguage = function() {
    return ez5.session.getPref("database_languages")[0];
  };

  Localization.prototype.getLanguageControl = function() {
    return this.__multiInputControl;
  };

  Localization.prototype.getLanguageControlDetail = function() {
    return this.__multiInputControlDetail;
  };

  Localization.prototype.getLanguageControlAdmin = function() {
    return this.__multiInputControlAdmin;
  };

  Localization.prototype.getFirstStandardText = function(standard) {
    var ref;
    return (ref = standard["1"] || standard["2"] || standard["3"]) != null ? ref.text : void 0;
  };

  Localization.prototype.getDatabaseLanguages = function() {
    return ez5.session.getPref("database_languages");
  };

  Localization.prototype.getSearchLanguages = function() {
    return ez5.session.getPref("search_languages");
  };

  Localization.prototype.getBestFrontendValue = function(data, html, html_only) {
    if (html == null) {
      html = false;
    }
    if (html_only == null) {
      html_only = false;
    }
    return this.__getBestValue(data, html, html_only, true);
  };

  Localization.prototype.getBestDatabaseValue = function(data, html, html_only) {
    if (html == null) {
      html = false;
    }
    if (html_only == null) {
      html_only = false;
    }
    return this.__getBestValue(data, html, html_only, false);
  };

  Localization.sid_match = new RegExp("(^|>)#[1-9][0-9]*($|<)");

  Localization.prototype.__getBestValue = function(data, html, html_only, frontend) {
    var i, j, k, lang, len, len1, sid_v, try_languages, v;
    if (!data) {
      return;
    }
    try_languages = [];
    if (frontend) {
      try_languages.push(this.getLanguage());
      try_languages.push.apply(try_languages, ez5.session.getConfigFrontendLanguages());
    } else {
      try_languages.push.apply(try_languages, ez5.session.getPref("database_languages"));
      try_languages.push.apply(try_languages, ez5.session.getConfigDatabaseLanguages());
    }
    if (html) {
      for (i = 0, len = try_languages.length; i < len; i++) {
        lang = try_languages[i];
        v = data[lang + ":highlight"];
        if (CUI.util.isEmpty(v)) {
          continue;
        }
        if (Localization.sid_match.exec(v)) {
          continue;
        }
        return v;
      }
    }
    if (!html_only) {
      for (j = 0, len1 = try_languages.length; j < len1; j++) {
        lang = try_languages[j];
        v = data[lang];
        if (CUI.util.isEmpty(v)) {
          continue;
        }
        if (Localization.sid_match.exec(v)) {
          continue;
        }
        if (html) {
          return CUI.util.toHtml(v);
        } else {
          return v;
        }
      }
    }
    sid_v = void 0;
    if (html) {
      for (k in data) {
        v = data[k];
        if (k === "_comment") {
          continue;
        }
        if (CUI.util.isEmpty(v)) {
          continue;
        }
        if (Localization.sid_match.exec(v)) {
          sid_v = v;
          continue;
        }
        if (k.match(/:highlight$/)) {
          return v;
        }
      }
      if (html_only) {
        return sid_v;
      }
    }
    for (k in data) {
      v = data[k];
      if (k === "_comment") {
        continue;
      }
      if (CUI.util.isEmpty(v)) {
        continue;
      }
      if (Localization.sid_match.exec(v)) {
        sid_v = v;
        continue;
      }
      if (html) {
        return CUI.util.toHtml(v);
      } else {
        return v;
      }
    }
    if (sid_v !== void 0) {
      if (html) {
        return CUI.util.toHtml(sid_v);
      } else {
        return sid_v;
      }
    }
  };

  Localization.prototype.setLanguage = function(culture) {
    var ref;
    CUI.util.assert((culture != null ? culture.length : void 0) >= 5, "Localization.setLanguage", "Culture needs to be set");
    if (culture === this.culture) {
      return CUI.resolvedPromise();
    }
    this.culture = culture;
    CUI.DateTime.setLocale(this.culture);
    document.documentElement.setAttribute("lang", this.culture.split('-')[0]);
    return CUI.when(this.load_keys().done((function(_this) {
      return function() {
        var iconColors, icons, k, key, ref, results;
        CUI.defaults["class"].Select.defaults.not_found = $$("cui.select.not_found");
        CUI.defaults["class"].Button.defaults.confirm_ok = $$("base.ok");
        CUI.defaults["class"].Button.defaults.confirm_cancel = $$("base.cancel");
        CUI.defaults["class"].Button.defaults.confirm_title = $$("base.confirm");
        CUI.defaults["class"].Label.defaults.manage_overflow.text_inactive = ez5.loca.text("label.manage_overflow|text_inactive");
        CUI.defaults["class"].Label.defaults.manage_overflow.text_active = ez5.loca.text("label.manage_overflow|text_active");
        CUI.defaults["class"].Label.defaults.manage_overflow.icon_inactive = "fa-plus-square-o";
        CUI.defaults["class"].Label.defaults.manage_overflow.icon_active = "fa-minus-square-o";
        CUI.Modal.defaults.cancel_tooltip = {
          text: $$("base.cancel.tooltip")
        };
        CUI.Pane.defaults.button_tooltip = {
          text: $$("base.pane.tooltip")
        };
        CUI.DateTime.defaults.button_tooltip = ez5.loca.text("cui.date.time.button_tooltip");
        CUI.DateTime.defaults.bc_appendix = (ref = ez5.loca.text("cui.date.time.bc_appendix")) != null ? ref.trim().split(";") : void 0;
        if (!CUI.DateTime.defaults.bc_appendix_output) {
          CUI.DateTime.defaults.bc_appendix_output = CUI.DateTime.defaults.bc_appendix[0];
        }
        CUI.DataTable.defaults.plus_button_tooltip = ez5.loca.text("cui.data.table.plus_button_tooltip");
        CUI.DataTable.defaults.minus_button_tooltip = ez5.loca.text("cui.data.table.minus_button_tooltip");
        CUI.ListView.defaults.row_move_handle_tooltip = ez5.loca.text("cui.list.view.row_move_handle_tooltip");
        CUI.Tabs.defaults.overflow_button_tooltip = ez5.loca.text("cui.tabs.overflow_button_tooltip");
        CUI.MapInput.defaults.labels.placeholder = ez5.loca.text("cui.map.input.placeholder");
        CUI.MapInput.defaults.labels.iconButtonTooltip = ez5.loca.text("cui.map.input.icon.button.tooltip");
        CUI.MapInput.defaults.labels.mapButtonTooltip = ez5.loca.text("cui.map.input.map.button.tooltip");
        CUI.MapInput.defaults.labels.iconLabel = ez5.loca.text("cui.map.input.map.popover.icon.label");
        CUI.MapInput.defaults.labels.colorLabel = ez5.loca.text("cui.map.input.map.popover.color.label");
        icons = ez5.loca.text("cui.map.input.map.popover.icons");
        iconColors = ez5.loca.text("cui.map.input.map.popover.icons-colors");
        if (icons) {
          CUI.MapInput.defaults.icons = icons.split(",");
        }
        if (iconColors) {
          CUI.MapInput.defaults.iconColors = iconColors.split(",");
        }
        CUI.Map.defaults.buttons.zoom.plus.icon = ez5.loca.text("cui.map.buttons.zoom.plus.icon");
        CUI.Map.defaults.buttons.zoom.plus.tooltip = ez5.loca.text("cui.map.buttons.zoom.plus.tooltip");
        CUI.Map.defaults.buttons.zoom.reset.icon = ez5.loca.text("cui.map.buttons.zoom.reset.icon");
        CUI.Map.defaults.buttons.zoom.reset.tooltip = ez5.loca.text("cui.map.buttons.zoom.reset.tooltip");
        CUI.Map.defaults.buttons.zoom.minus.icon = ez5.loca.text("cui.map.buttons.zoom.minus.icon");
        CUI.Map.defaults.buttons.zoom.minus.tooltip = ez5.loca.text("cui.map.buttons.zoom.minus.tooltip");
        CUI.Map.defaults.buttons.fullscreen.open.icon = ez5.loca.text("cui.map.buttons.fullscreen.open.icon");
        CUI.Map.defaults.buttons.fullscreen.open.tooltip = ez5.loca.text("cui.map.buttons.fullscreen.open.tooltip");
        CUI.Map.defaults.buttons.fullscreen.close.icon = ez5.loca.text("cui.map.buttons.fullscreen.close.icon");
        CUI.Map.defaults.buttons.fullscreen.close.tooltip = ez5.loca.text("cui.map.buttons.fullscreen.close.tooltip");
        results = [];
        for (k in CUI.ConfirmationChoice.defaults) {
          key = "cui.confirmation.choice." + k;
          if (_this.has(key)) {
            results.push(CUI.ConfirmationChoice.defaults[k] = _this.get_key(key));
          } else {
            results.push(void 0);
          }
        }
        return results;
      };
    })(this)), null, (ref = ez5.pluginManager) != null ? ref.loadKeys() : void 0);
  };

  Localization.prototype.getLanguage = function() {
    return this.culture;
  };

  Localization.prototype.str_span = function(key, attrs, culture) {
    var span;
    span = CUI.dom.span("loca-key loca-key-" + key.replace(/[\.]/g, "-"));
    span.textContent = this.str(key, attrs, culture);
    return span;
  };

  Localization.prototype.str_default = function(key, _default, attrs, culture) {
    if (_default == null) {
      _default = null;
    }
    return this.str(key, attrs, culture, _default);
  };

  Localization.prototype.html = function(key, attrs, culture, _default) {
    var html;
    if (culture == null) {
      culture = this.culture;
    }
    if (_default == null) {
      _default = void 0;
    }
    return html = this.str(key, attrs, culture, _default, true);
  };

  Localization.prototype.str = function(key, attrs, culture, _default, as_html) {
    var _str, matches, r, s, str;
    if (culture == null) {
      culture = this.culture;
    }
    if (CUI.util.isUndef(key)) {
      return "";
    }
    str = this.get_key(key, culture);
    if (str === "-") {
      return "";
    }
    if (CUI.util.isEmpty(str)) {
      if (_default !== void 0) {
        if (_default === null) {
          return null;
        }
        str = _default;
      } else {
        str = culture + ":" + key;
      }
      if (as_html) {
        return CUI.util.toHtml(str);
      } else {
        return str;
      }
    }
    if (as_html) {
      str = CUI.util.toHtml(str);
    }
    if (str.indexOf("$(") > -1) {
      r = /\$\((.*?)\)/g;
      s = "" + str;
      while (matches = r.exec(str)) {
        _str = this.get_key(matches[1], culture);
        if (CUI.util.isEmpty(_str)) {
          _str = culture + ":" + matches[1];
        }
        s = s.split(matches[0]).join(_str);
      }
      str = s;
    }
    if (attrs) {
      return this.replAttr(str, attrs);
    } else {
      if (ez5.session.getPref("debug_locakeys")) {
        return key;
      }
      return str;
    }
  };

  Localization.replRegex = /%(?:([1-9][0-9]*)(i)|\(([^]+?)\)([a-zA-Z]))/g;

  Localization.prototype.replAttr = function(s, attrs, level) {
    var _key, append, getFormattedValue, getValue, key, matches, modifier, parts, prepend, repl, value, values;
    if (level == null) {
      level = 0;
    }
    while (matches = Localization.replRegex.exec(s)) {
      prepend = null;
      append = null;
      if (matches[1]) {
        key = parseInt(matches[1]) - 1;
        modifier = matches[2];
      } else {
        _key = matches[3];
        modifier = matches[4];
        if (_key.indexOf("|") === -1) {
          key = _key;
        } else {
          parts = _key.split("|");
          switch (parts.length) {
            case 3:
              prepend = parts[0];
              key = parts[1];
              append = parts[2];
              break;
            case 2:
              if (attrs[parts[0]]) {
                prepend = "";
                key = parts[0];
                append = parts[1];
              } else if (attrs[parts[1]]) {
                prepend = parts[0];
                key = parts[1];
                append = "";
              } else {
                key = _key;
              }
              break;
            default:
              key = _key;
          }
        }
      }
      getValue = (function(_this) {
        return function(attrs, key) {
          return eval("attrs." + key);
        };
      })(this);
      if ((typeof key.indexOf === "function" ? key.indexOf(".") : void 0) > -1) {
        repl = getValue(attrs, key);
      } else {
        repl = attrs[key];
      }
      if (CUI.util.isNull(repl)) {
        repl = "(attrs." + (matches[1] || matches[2]) + " missing)";
      } else {
        getFormattedValue = (function(_this) {
          return function(value) {
            var column, formattedValue, table, unknownModifierText;
            formattedValue = (function() {
              var ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8;
              switch (modifier) {
                case "c":
                  ref = value.split("."), table = ref[0], column = ref[1];
                  return ((ref1 = ez5.schema.CURRENT._table_by_name) != null ? (ref2 = ref1[table]) != null ? (ref3 = ref2._column_by_name[column]) != null ? ref3._name_localized : void 0 : void 0 : void 0) || value;
                case "t":
                  return ((ref4 = ez5.schema.CURRENT._table_by_name) != null ? (ref5 = ref4[value]) != null ? ref5._name_localized : void 0 : void 0) || value;
                case "i":
                case "s":
                  return value;
                case "D":
                  return ez5.format_date(value);
                case "d":
                  return ez5.format_date_and_time(value);
                case "p":
                  return ((ref6 = ez5.pools.findPoolById(value)) != null ? ref6.getDisplayText() : void 0) || value;
                case "g":
                  return ((ref7 = ez5.groupManager.getGroupById(value)) != null ? ref7.getDisplayText() : void 0) || value;
                case "m":
                  return ((ref8 = ez5.mask.CURRENT._mask_by_id[value]) != null ? ref8._name_localized : void 0) || value;
                case "r":
                  key = "server.right." + value;
                  if (this.has(key)) {
                    return $$(key);
                  } else {
                    return value;
                  }
                  break;
                case "o":
                  return "#" + value;
                default:
                  modifier = matches[3];
                  key = matches[2];
                  unknownModifierText = "('" + key + "': UNKNOWN MODIFIER '" + modifier + "')";
                  return unknownModifierText;
              }
            }).call(_this);
            if (prepend || append) {
              return prepend + formattedValue + append;
            } else {
              return formattedValue;
            }
          };
        })(this);
        if (CUI.util.isArray(repl)) {
          values = (function() {
            var i, len, results;
            results = [];
            for (i = 0, len = repl.length; i < len; i++) {
              value = repl[i];
              results.push(getFormattedValue(value));
            }
            return results;
          })();
          if (prepend === null && append === null) {
            repl = values.join(", ");
          } else {
            repl = values.join("");
          }
        } else {
          repl = getFormattedValue(repl);
        }
      }
      s = s.split(matches[0]).join(repl);
    }
    if (level < 2) {
      return this.replAttr(s, attrs, level + 1);
    } else {
      return s;
    }
  };

  Localization.prototype.get_complete_key = function(key, culture) {
    var _key;
    if (culture == null) {
      culture = this.culture;
    }
    _key = {};
    _key[this.culture] = this.get_key(key, culture);
    return _key;
  };

  Localization.prototype.get_key = function(key, culture) {
    var ref, v;
    if (culture == null) {
      culture = this.culture;
    }
    if (!this.strings) {
      return void 0;
    }
    if (!this.strings[culture]) {
      return void 0;
    }
    v = this.strings[culture][key + "[" + ((ref = ez5.cssLoader.getActiveCSS()) != null ? ref.theme : void 0) + "]"];
    if (!CUI.util.isUndef(v)) {
      return v;
    }
    return this.strings[culture][key];
  };

  Localization.prototype.has = function(key) {
    return !CUI.util.isUndef(this.get_key(key));
  };

  Localization.prototype.clean_keys = function(map) {
    var _map, culture, found, k, v, value;
    for (k in map) {
      v = map[k];
      _map = {};
      found = false;
      for (culture in v) {
        value = v[culture];
        if (!CUI.util.isEmpty(value)) {
          _map[culture] = value;
          found = true;
        }
      }
      if (found) {
        map[k] = _map;
      } else {
        delete map[k];
      }
    }
    return map;
  };

  Localization.prototype.get_valid_user_key_prefixes = function(version) {
    var i, j, len, len1, mask, prefixes, ref, ref1, table;
    prefixes = [];
    ref = ez5.schema[version].tables;
    for (i = 0, len = ref.length; i < len; i++) {
      table = ref[i];
      prefixes.push("schema." + table.name + ".");
    }
    ref1 = ez5.mask[version].masks;
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      mask = ref1[j];
      if (mask.name) {
        prefixes.push("mask." + mask.table_id + "." + mask.name + ".");
      } else {
        prefixes.push("mask." + mask.table_id + "._new_.");
      }
    }
    return prefixes;
  };

  Localization.prototype.update = function(opts) {
    var delete_prefix, delete_prefixes, i, idx, key, len, ref, ref1, ref2, ref3, value;
    CUI.util.assert((ref = opts.realm) === "HEAD" || ref === "CURRENT", "Localization.update", "opts.realm needs to be \"HEAD\" or \"CURRENT\" but is \"" + opts.realm + "\".", {
      opts: opts
    });
    if (!this.user_keys || !this.user_keys[opts.realm]) {
      console.debug("ez5.loca.update: user_keys for realm '" + opts.realm + "' not loaded, cannot update.");
      return;
    }
    if (CUI.util.isArray(opts.delete_prefixes)) {
      delete_prefixes = opts.delete_prefixes.slice(0);
    } else {
      delete_prefixes = [];
    }
    if (CUI.util.isString(opts.delete_prefix)) {
      delete_prefixes.push(opts.delete_prefix);
    }
    for (i = 0, len = delete_prefixes.length; i < len; i++) {
      delete_prefix = delete_prefixes[i];
      ref1 = this.user_keys[opts.realm];
      for (key in ref1) {
        value = ref1[key];
        if (delete_prefix === key.substr(0, delete_prefix.length)) {
          delete this.user_keys[opts.realm][key];
        }
      }
    }
    if (CUI.util.isArray(opts.valid_prefixes)) {
      ref2 = this.user_keys[opts.realm];
      for (key in ref2) {
        value = ref2[key];
        if (!this.user_keys[opts.realm].hasOwnProperty(key)) {
          continue;
        }
        idx = CUI.util.idxInArray(key, opts.valid_prefixes, function(prefix) {
          return prefix === key.substr(0, prefix.length);
        });
        if (idx === -1) {
          console.warn("Localization.update: Removing not protected invalid key:", key);
          delete this.user_keys[opts.realm][key];
        }
      }
    }
    ref3 = opts.keys;
    for (key in ref3) {
      value = ref3[key];
      if (!CUI.util.isNull(value)) {
        this.user_keys[opts.realm][key] = value;
      }
    }
    return ez5.api.l10n({
      type: "POST",
      api: "/user/" + opts.realm,
      withCredentials: true,
      json_data: this.user_keys[opts.realm]
    });
  };

  Localization.prototype.__getDefaultStrings = function() {
    return {
      "en-US": {
        "l10n.error.fallback": "An error occurred.",
        "base.abort": "Cancel",
        "base.activate": "Activate",
        "base.alert.connection_lost": "Connection to server lost, retrying...",
        "base.apply": "Apply",
        "base.cancel": "Cancel",
        "base.cancel.tooltip": "Close",
        "base.close": "Close",
        "base.config.manager.unsaved_changes.button_cancel": "Cancel",
        "base.config.manager.unsaved_changes.button_ok": "Ok",
        "base.config.plugin_type.right_preset_collection.option.none": "- Right Preset-",
        "base.config.require_system_right_hint.md": "This data can only be seen by users with system right *%(system_right)s*.",
        "base.config.unknown_plugin_type": "Unknown plugin type %(type)s.",
        "base.confirm": "Confirmation",
        "base.copy": "Copy",
        "base.created_column.name": "Created",
        "base.debug.to.console|icon": "fa-terminal",
        "base.debug.to.console|text": "Debug to Console%(more)s",
        "base.delete": "Delete",
        "base.delete|icon": "fa-warning",
        "base.done": "Done",
        "base.earlier": "Earlier",
        "base.edit": "Edit",
        "base.empty_value": "Empty",
        "base.error": "Error",
        "base.error.generic": "A general server error has occurred. Please try again. If the error persists, contact your system administrator.",
        "base.error.network": "A network error occurred. The easydb server %(server)s is unreachable. It's possible you are not allowed to access the easydb server from your origin.",
        "base.error.realm.api": "API-Error",
        "base.error.realm.server": "Server-Error",
        "base.error.realm.transition_reject": "Saving Rejected",
        "base.error.realm.user": "Error",
        "base.error.timeout": "Connection timed out. Try again later. If the problem persists, contact your system adminitrator.",
        "base.error.transition_reject": "Saving was rejected due to a configured workflow. Please talk to your administrator.",
        "base.error.uuid.modal.title": "Server-Error detail information",
        "base.error.uuid.modal.uuid": "UUID",
        "base.modal.confirm": "Confirmation",
        "base.modal.error": "Error",
        "base.nested_uuid.name": "Nested Element-UUID",
        "base.next": "Next",
        "base.no_entry": "Without \"%1i\"",
        "base.object.owner": "Owner",
        "base.objecttyp.attribute-table": "Attribute table",
        "base.objecttyp.aux-attribute-table": "Attribute type",
        "base.objecttyp.aux-table": "Attribute type",
        "base.objecttyp.main-table": "Main type",
        "base.objecttype.name": "Object Type",
        "base.ok": "Ok",
        "base.pane.tooltip": "Maximize /minimize",
        "base.parent_child_idx_column.name": "Parent child index",
        "base.path_column.name": "Path",
        "base.path_column.root": "Virtual Top Level",
        "base.path_column.root.hint": "Select to additionally show record at top level",
        "base.path_column.root.standard.hint": "-",
        "base.paths_column.name": "Paths",
        "base.previous": "Previous",
        "base.primary_key_column.name": "Object ID",
        "base.reload": "Reload",
        "base.retry": "Try Again",
        "base.save": "Save",
        "base.session_expired.text": "Your session information has expired, you will be logged into a new session.",
        "base.session_expired.title": "Session expired",
        "base.system_object_id_column.name": "System-ID",
        "base.system_object_id_parent_column.name": "System object id parent",
        "base.top_hierarchy_level": "Topmost level",
        "session.load_theme_error": "Error while loading CSS: **%(path)s**. Theme: **%(theme)s**. Mode: **%(mode)s**.",
        "base.error.user.read_only_mode": "Read Only Mode"
      }
    };
  };

  Localization.prototype.load_keys = function(language) {
    var base, frontendLocaKeysData, serverLocaKeysData;
    if (language == null) {
      language = this.culture;
    }
    CUI.util.assert(language, "Localization.load_keys", "language is not set");
    if (this.strings == null) {
      this.strings = this.__getDefaultStrings();
    }
    if ((base = this.strings)[language] == null) {
      base[language] = {};
    }
    if (this.__loadingKeys == null) {
      this.__loadingKeys = new Map();
    }
    serverLocaKeysData = null;
    frontendLocaKeysData = null;
    this.__loadingKeys.set(language, CUI.when(ez5.server({
      local_url: window.easydb_base_prefix + "/web/l10n/" + language + ".json",
      data: ez5.session.fylrCacheParams(),
      add_token: false,
      error: (function(_this) {
        return function() {
          return true;
        };
      })(this)
    }).done((function(_this) {
      return function(data) {
        frontendLocaKeysData = data;
      };
    })(this)), ez5.api.l10n({
      api: "/static/" + language + ".json",
      add_token: false,
      withCredentials: ez5.version("6"),
      data: ez5.session.fylrCacheParams()
    }).done((function(_this) {
      return function(data) {
        if (!CUI.util.isPlainObject(data)) {
          console.warn("Localization: load_keys", language, "no data returned.");
          return;
        }
        serverLocaKeysData = data;
      };
    })(this))).fail((function(_this) {
      return function(xhr) {
        delete _this.strings[language];
        return console.error("error retrieving language", language, xhr);
      };
    })(this)).done((function(_this) {
      return function() {
        _this.__addKeys(frontendLocaKeysData, language);
        if (serverLocaKeysData) {
          _this.__addKeys(serverLocaKeysData, language);
        }
      };
    })(this)).always((function(_this) {
      return function() {
        return _this.__loadingKeys["delete"](language);
      };
    })(this)));
    return this.__loadingKeys.get(language);
  };

  Localization.prototype.__replaceValue = function(v) {
    return v.replace(/\\n/g, "\n").replace(/~/g, '\u00AD');
  };

  Localization.prototype.__addKeys = function(data, language) {
    var k, ref, v;
    if (!(data != null ? data[language] : void 0)) {
      return;
    }
    ref = data[language];
    for (k in ref) {
      v = ref[k];
      this.strings[language][k] = this.__replaceValue(v);
    }
  };

  Localization.prototype.load_more_keys = function(url) {
    var dfr;
    dfr = new CUI.Deferred();
    ez5.server({
      local_url: url,
      add_token: false,
      withCredentials: ez5.version("6"),
      handle_error: (function(_this) {
        return function(xhr) {
          return true;
        };
      })(this)
    }).done((function(_this) {
      return function(data) {
        var _data, i, len;
        if (CUI.util.isArray(data)) {
          for (i = 0, len = data.length; i < len; i++) {
            _data = data[i];
            if (_data._error) {
              console.error(_data._error);
              continue;
            }
            _this.__addKeys(_data, _this.getLanguage());
          }
        } else {
          _this.__addKeys(data, _this.getLanguage());
        }
        dfr.resolve(data);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  Localization.prototype.set_user_keys = function(version, data) {
    var info, key, lang, value;
    this.user_keys[version] = {};
    for (key in data) {
      info = data[key];
      this.user_keys[version][key] = {};
      for (lang in info) {
        value = info[lang];
        if (lang === '_comment') {
          this.user_keys[version][key][lang] = value;
        } else {
          this.user_keys[version][key][lang] = Localization.prototype.__replaceValue.call(this, value);
        }
      }
    }
  };

  Localization.prototype.load_user_keys = function(x_easydb) {
    var cdata, loads;
    this.user_keys = {};
    if (x_easydb) {
      if (ez5.version("6")) {
        cdata = ez5.session.fylrCacheParams();
      } else {
        cdata = {
          cache_version: x_easydb.base + "-" + x_easydb.user,
          cache_seconds: 3600 * 24 * 100
        };
      }
    }
    loads = [
      ez5.api.l10n({
        api: "/user/CURRENT",
        withCredentials: true,
        data: cdata
      }).done((function(_this) {
        return function(data) {
          return _this.set_user_keys('CURRENT', data);
        };
      })(this))
    ];
    if (Datamodel.getLevel()) {
      loads.push(ez5.api.l10n({
        api: "/user/HEAD",
        withCredentials: true,
        data: ez5.session.fylrCacheParams()
      }).done((function(_this) {
        return function(data) {
          return _this.set_user_keys('HEAD', data);
        };
      })(this)));
    }
    return CUI.when(loads).fail(function(xhr) {
      return console.error("error loading user keys", this.culture, xhr);
    }).done(function() {});
  };

  Localization.prototype.has_user_key = function(realm, key) {
    var ref, ref1;
    return !CUI.util.isEmpty((ref = this.user_keys) != null ? (ref1 = ref[realm]) != null ? ref1[key] : void 0 : void 0);
  };

  Localization.prototype.get_user_key = function(realm, key) {
    if (key.indexOf('@') > -1) {
      return ez5.connector.get_user_key(realm, key);
    }
    if (!this.has_user_key(realm, key)) {
      return {};
    }
    return this.user_keys[realm][key];
  };

  Localization.prototype.has_user_key_localized = function(realm, key) {
    var keys;
    keys = this.get_user_key(realm, key);
    return !CUI.util.isEmpty(this.get_user_key_localized(realm, key));
  };

  Localization.prototype.get_user_key_localized = function(realm, key, _default) {
    var v;
    if (key.indexOf('@') > -1) {
      return ez5.connector.get_user_key_localized(realm, key, _default);
    }
    v = this.getBestFrontendValue(this.get_user_key(realm, key));
    if (CUI.util.isEmpty(v)) {
      return _default;
    } else {
      return v;
    }
  };

  Localization.prototype.text = function(key, attrs) {
    if (this.has(key + "|text")) {
      return this.str(key + "|text", attrs);
    } else if (this.has(key)) {
      return this.str(key, attrs);
    } else {
      return void 0;
    }
  };

  Localization.prototype.tooltip = function(key, attrs) {
    if (this.has(key + "|tooltip")) {
      return this.str(key + "|tooltip", attrs);
    } else {
      return null;
    }
  };

  Localization.prototype.formatNumber = function(int, fixed) {
    if (fixed == null) {
      fixed = 2;
    }
    return (int / Math.pow(10, fixed)).toFixed(fixed).replace("\.", ez5.session.frontend_locale.numbers.decimal);
  };

  Localization.prototype.setLocaKeys = function(div) {
    var el, i, len, loca_key, prefix, prefix_el, ref;
    ref = CUI.dom.matchSelector(div, "[data-loca-key]");
    for (i = 0, len = ref.length; i < len; i++) {
      el = ref[i];
      loca_key = el.getAttribute("data-loca-key");
      prefix_el = CUI.dom.closest(el, "[data-loca-key-prefix]");
      if (prefix_el) {
        prefix = prefix_el.getAttribute("data-loca-key-prefix");
      } else {
        prefix = "";
      }
      el.textContent = $$(prefix + loca_key);
    }
  };

  Localization.prototype.getLanguageTag = function(culture) {
    var ref, tag;
    if (culture == null) {
      culture = ez5.loca.culture;
    }
    if (ez5.loca.has("base.culture." + culture + ".tag")) {
      return $$("base.culture." + culture + ".tag");
    } else {
      tag = (ref = ("" + culture).split("-")[1]) != null ? ref.toUpperCase() : void 0;
      if (!tag) {
        tag = culture;
      }
      return tag;
    }
  };

  Localization.prototype.getLanguageLabel = function(culture) {
    if (culture == null) {
      culture = ez5.loca.culture;
    }
    if (ez5.version("6")) {
      return $$("language." + culture);
    } else {
      return $$("base.culture." + culture);
    }
  };

  return Localization;

})(CUI.Element);

ez5.loca = new Localization();

$$ = function() {
  return ez5.loca.str.apply(ez5.loca, arguments);
};

$span$ = function() {
  return ez5.loca.str_span.apply(ez5.loca, arguments);
};

$empty$ = function() {
  return CUI.dom.addClass(ez5.loca.str_span.apply(ez5.loca, arguments), "italic");
};

ez5.session_ready((function(_this) {
  return function() {
    return ez5.loca.init();
  };
})(this));
// Generated by CoffeeScript 1.12.7
var Plugin,
  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;

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

  function Plugin(opts) {
    var ref, replaceValue, url1, webapp_url;
    this.opts = opts != null ? opts : {};
    if (this.opts.base_url) {
      if (this.opts.base_url.endsWith("/")) {
        this.__bare_base_url = this.opts.base_url;
      } else {
        this.__bare_base_url = this.opts.base_url + "/";
      }
    }
    this.__plugin_url = ez5.getAbsoluteURL(this.opts.plugin_url, this.opts.remote_url);
    this.__name = this.opts.name;
    if (this.opts.load_from_remote) {
      this.__load_from_remote = true;
      this.__base_url = this.replaceOrigin(this.__bare_base_url, this.opts.remote_url);
      this.__load_with_creds = ez5.version("6");
    } else {
      if (window.easydb_server_url && this.__bare_base_url.match("/extension/")) {
        url1 = this.__bare_base_url;
        replaceValue = window.fylr_server ? "" : "/base/";
        this.__bare_base_url = this.__bare_base_url.replace("/extension/", replaceValue);
        console.info("Rewrote plugin URL for cross-server use: " + url1 + " to: " + this.__bare_base_url + ".");
      }
      if (window.fylr_server && !ez5.version("6")) {
        url1 = this.__bare_base_url;
        this.__bare_base_url = "/api/v1/plugin/static/" + this.__name + "/";
        console.info("Rewrote plugin URL for cross-server use: " + url1 + " to: " + this.__bare_base_url + ".");
      }
      webapp_url = window.fylr_server || "";
      this.__base_url = this.replaceOrigin(this.__bare_base_url, webapp_url);
      this.__load_from_remote = false;
      this.__load_with_creds = !!window.fylr_server;
    }
    while ((ref = this.__plugin_url) != null ? ref.endsWith("/") : void 0) {
      this.__plugin_url = this.__plugin_url.substr(0, this.__plugin_url.length - 1);
    }
    this.__webfrontend = this.opts.webfrontend || {};
  }

  Plugin.prototype.replaceOrigin = function(url, origin) {
    var u1, u2;
    if (origin == null) {
      origin = window.easydb_server_url;
    }
    if (url.startsWith("/")) {
      url = document.location.origin + url;
    }
    u1 = new URL(url);
    if (!origin) {
      return u1.toString();
    }
    u2 = new URL(origin);
    u1.protocol = u2.protocol;
    u1.hostname = u2.hostname;
    u1.port = u2.port;
    return u1.toString();
  };

  Plugin.prototype.getWebfrontend = function() {
    return this.__webfrontend;
  };

  Plugin.prototype.getName = function() {
    return this.__name;
  };

  Plugin.prototype.loadFromRemote = function() {
    return this.__load_from_remote;
  };

  Plugin.prototype.getInfo = function() {
    var content, displayname, href, info, infoButton, infoContent, infos, isGitHub, ref, tooltip;
    infos = [ez5.loca.getBestFrontendValue(this.opts.info) || ""];
    infos.push("\n\n");
    if (ez5.version("6")) {
      displayname = this.__name;
    } else {
      displayname = ez5.loca.getBestFrontendValue(this.opts.displayname);
      if (displayname) {
        infos.push($$("plugin.info.name.md", {
          name: this.__name
        }));
      } else {
        displayname = this.__name;
      }
    }
    if (this.__load_from_remote) {
      displayname = displayname + "(R)";
    }
    if (this.opts.version) {
      infos.push($$("plugin.info.version.md", {
        version: this.opts.version
      }));
    }
    info = infos.join("\n").trim();
    if (info.length > 0) {
      tooltip = {
        text: info,
        markdown: true
      };
    } else {
      tooltip = void 0;
    }
    isGitHub = function(url) {
      var u;
      try {
        u = new URL(url);
        return u.hostname.toLowerCase().includes("github.com");
      } catch (error) {
        return false;
      }
    };
    href = (this.opts.url != null) && isGitHub(this.opts.url) && ((ref = this.opts.build_info) != null ? ref.rev : void 0) ? this.opts.url + "/commits/" + this.opts.build_info.rev : this.opts.url != null ? this.opts.url : void 0;
    if (href) {
      infoContent = new CUI.ButtonHref({
        text: displayname,
        appearance: "link",
        href: href,
        target: "_blank",
        tooltip: tooltip
      });
    } else {
      infoContent = new CUI.Label({
        text: displayname,
        multiline: true,
        tooltip: tooltip
      });
    }
    if (!CUI.util.isPlainObject(this.opts.build_info)) {
      return infoContent;
    }
    infoButton = new LocaButton({
      loca_key: "plugin.info.build_info.button",
      "class": "ez5-path-info-button",
      appearance: "flat",
      onClick: (function(_this) {
        return function() {
          var key, label, popover, ref1, value, values;
          values = [];
          ref1 = _this.opts.build_info;
          for (key in ref1) {
            value = ref1[key];
            if (CUI.util.isEmpty(value)) {
              continue;
            }
            values.push($$("plugin.info.build_info." + key, {
              value: value
            }));
          }
          label = new CUI.Label({
            text: $$("plugin.info.build_info.md", {
              values: values
            }),
            markdown: true
          });
          popover = new ez5.HintPopover({
            element: infoButton,
            content: label
          });
          popover.show();
        };
      })(this)
    });
    content = new CUI.HorizontalList({
      content: [infoContent, CUI.dom.space(), infoButton]
    });
    return content;
  };

  Plugin.prototype.getOpts = function() {
    return this.opts;
  };

  Plugin.prototype.getBareBaseURL = function() {
    return this.__bare_base_url;
  };

  Plugin.prototype.getBaseURL = function() {
    return this.__base_url;
  };

  Plugin.prototype.getPluginURL = function() {
    return this.__plugin_url;
  };

  Plugin.prototype.loadCss = function() {
    var css_url, loader;
    css_url = this.getWebfrontend().css;
    if (!css_url) {
      return CUI.resolvedPromise();
    }
    loader = new CUI.CSSLoader({
      cssName: "plugin-" + this.getName()
    });
    loader.load({
      url: this.getBaseURL() + css_url
    });
    return CUI.resolvedPromise();
  };

  Plugin.prototype.loadKeys = function() {
    var dfr, l10n, more_keys_url;
    if (!this.getWebfrontend().l10n) {
      return CUI.resolvedPromise();
    }
    dfr = new CUI.Deferred();
    l10n = this.getBaseURL() + this.getWebfrontend().l10n;
    if (!l10n.endsWith("/")) {
      l10n = l10n + "/";
    }
    more_keys_url = l10n + ez5.loca.getLanguage() + ".json";
    ez5.loca.load_more_keys(more_keys_url, this.__load_with_creds).done(dfr.resolve).fail((function(_this) {
      return function(xhr) {
        var ref;
        if ((ref = xhr.status) === 403 || ref === 404) {
          return dfr.resolve();
        } else {
          return dfr.reject();
        }
      };
    })(this));
    return dfr.promise();
  };

  Plugin.prototype.getMaskTypeExtension = function(type) {
    var ref, ref1, ref2;
    return (ref = this.getWebfrontend()) != null ? (ref1 = ref.type_extension) != null ? (ref2 = ref1.mask) != null ? ref2[type] : void 0 : void 0 : void 0;
  };

  return Plugin;

})(CUI.Dummy);
// Generated by CoffeeScript 1.12.7
var PluginManager,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  PluginManager.prototype.readOpts = function() {
    var loc;
    PluginManager.__super__.readOpts.call(this);
    if (this._load_from_remote) {
      this.__remote_url = window.easydb_server_url;
      if (this._remote_url) {
        loc = CUI.parseLocation(this._remote_url);
        if (loc) {
          this.__remote_url = loc.href;
        }
      }
      if (this.__remote_url) {
        this.__load_from_remote = true;
      } else {
        this.__load_from_remote = false;
      }
      if (this.__load_from_remote) {
        console.info("Loading plugins from: " + this.__remote_url);
      }
    }
    return this.__plugins = {};
  };

  PluginManager.prototype.initOpts = function() {
    PluginManager.__super__.initOpts.call(this);
    return this.addOpts({
      load_from_remote: {
        mandatory: true,
        "default": true,
        check: Boolean
      },
      remote_url: {
        check: String
      }
    });
  };

  PluginManager.prototype.getPluginNames = function() {
    var names;
    names = Object.keys(this.__plugins);
    names.sort();
    return names;
  };

  PluginManager.prototype.getPlugin = function(name) {
    return this.__plugins[name] || void 0;
  };

  PluginManager.prototype.loadKeys = function() {
    var l10nUrl, name, plugin, promises, ref;
    if (window.headless_mode) {
      return CUI.resolvedPromise();
    }
    if (Object.values(this.__plugins).length === 0) {
      return CUI.resolvedPromise();
    }
    console.timeLog("Start", "loading plugin keys");
    promises = [];
    if (this.info.bundle) {
      l10nUrl = this.info.bundle.l10n + "/" + ez5.loca.getLanguage() + ".json";
      promises.push(ez5.loca.load_more_keys(l10nUrl));
    } else {
      ref = this.__plugins;
      for (name in ref) {
        plugin = ref[name];
        promises.push(plugin.loadKeys());
      }
    }
    return CUI.when(promises).always((function(_this) {
      return function() {
        return console.timeLog("Start", "loaded plugin keys");
      };
    })(this));
  };

  PluginManager.prototype.loadFromRemote = function() {
    return this.__load_from_remote;
  };

  PluginManager.prototype.loadPluginInfo = function(timeout) {
    var dfr;
    if (timeout == null) {
      timeout = 15000;
    }
    console.timeLog("Start", "loadPluginInfo...");
    dfr = new CUI.Deferred();
    ez5.api.plugin({
      data: ez5.session.fylrCacheParams(),
      withCredentials: true,
      timeout: timeout,
      handle_error: (function(_this) {
        return function(xhr) {
          return true;
        };
      })(this)
    }).always((function(_this) {
      return function() {
        return console.timeLog("Start", "plugin info loaded");
      };
    })(this)).done((function(_this) {
      return function(info) {
        var ref;
        _this.info = info;
        if (!_this.__load_from_remote && _this.info.bundle && window.easydb_server_url !== document.location.origin) {
          _this.info.bundle = void 0;
        }
        if (!CUI.util.isArray((ref = _this.info) != null ? ref.plugins : void 0)) {
          console.error("PluginManager.load: Plugins could not be loaded. Server did not return a JSON Array: ", _this.info);
          dfr.reject();
          return;
        }
        dfr.resolve();
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  PluginManager.prototype.loadPlugins = function() {
    var _plugin, cssLoader, file, i, j, k, l, len, len1, len2, len3, loads, plugin, plugins, pluginsMap, promises, setDependencies, url;
    console.timeLog("Start", "load plugins...");
    plugins = this.info.plugins;
    promises = [];
    if (this.info.bundle) {
      for (i = 0, len = plugins.length; i < len; i++) {
        _plugin = plugins[i];
        plugin = new Plugin(_plugin);
        this.__plugins[plugin.getName()] = plugin;
      }
      if (this.info.bundle.html) {
        promises.push(CUI.chainedCall(CUI.Template.loadTemplateFile(this.info.bundle.html), CUI.loadScript(this.info.bundle.javascript)));
      } else {
        promises.push(CUI.loadScript(this.info.bundle.javascript));
      }
      promises.push(this.loadKeys());
      if (!window.headless_mode) {
        cssLoader = new CUI.CSSLoader({
          cssName: "plugin-all"
        });
        promises.push(cssLoader.load({
          url: this.info.bundle.css
        }));
      }
    } else {
      pluginsMap = {};
      for (j = 0, len1 = plugins.length; j < len1; j++) {
        plugin = plugins[j];
        plugin.order = 0;
        pluginsMap[plugin.name] = plugin;
      }
      setDependencies = function(plugin, parentPlugins) {
        var dependencyPlugin, k, len2, name, ref, ref1, ref2;
        if (parentPlugins == null) {
          parentPlugins = [];
        }
        if (!((ref = plugin.webfrontend) != null ? (ref1 = ref.dependencies) != null ? ref1.length : void 0 : void 0)) {
          return;
        }
        ref2 = plugin.webfrontend.dependencies;
        for (k = 0, len2 = ref2.length; k < len2; k++) {
          name = ref2[k];
          dependencyPlugin = pluginsMap[name];
          if (!dependencyPlugin) {
            plugin.ignore = true;
            console.error("PluginManager.load :: Skipping plugin '" + plugin.name + "' :: Missing dependency '" + name + "'");
            return;
          }
          dependencyPlugin.order++;
          if (indexOf.call(parentPlugins, name) >= 0) {
            plugin.ignore = true;
            console.error("PluginManager.load :: Skipping plugin '" + plugin.name + "' :: Circular dependency ::  -> " + (parentPlugins.join(' -> ')));
            return;
          }
          setDependencies(dependencyPlugin, parentPlugins.concat(plugin.name));
        }
      };
      for (k = 0, len2 = plugins.length; k < len2; k++) {
        plugin = plugins[k];
        setDependencies(plugin);
      }
      plugins = plugins.sort(function(a, b) {
        return b.order - a.order;
      }).filter(function(_plugin) {
        return !_plugin.ignore;
      });
      for (l = 0, len3 = plugins.length; l < len3; l++) {
        _plugin = plugins[l];
        if (!_plugin.hasOwnProperty("load_from_remote")) {
          _plugin.load_from_remote = this.loadFromRemote();
          _plugin.remote_url = this.__remote_url;
        }
        plugin = new Plugin(_plugin);
        CUI.util.assert(!this.getPlugin(plugin.getName()), "PluginManager.load", "Plugin " + (plugin.getName()) + " already loaded.", {
          plugin: plugin
        });
        if (plugin.getWebfrontend().url && plugin.getBaseURL()) {
          url = plugin.getBaseURL() + plugin.getWebfrontend().url;
          loads = [];
          if (plugin.getWebfrontend().html && plugin.getBaseURL()) {
            file = plugin.getBaseURL() + plugin.getWebfrontend().html;
            loads.push(CUI.Template.loadTemplateFile(file));
          }
          loads.push(CUI.loadScript(url));
          promises.push(CUI.chainedCall.apply(CUI, loads));
        }
        promises.push(plugin.loadKeys());
        promises.push(plugin.loadCss());
        this.__plugins[plugin.getName()] = plugin;
      }
    }
    return CUI.whenAllReject(promises);
  };

  PluginManager.prototype.getMaskTypeExtensions = function(type) {
    var config, i, j, len, len1, maskTypeExtensionField, maskTypeExtensionFields, maskTypeExtensionsMergedArray, maskTypeExtensionsMergedMap, name, pluginName, ref;
    maskTypeExtensionsMergedMap = {};
    ref = this.getPluginNames();
    for (i = 0, len = ref.length; i < len; i++) {
      pluginName = ref[i];
      maskTypeExtensionFields = this.getPlugin(pluginName).getMaskTypeExtension(type);
      if (maskTypeExtensionFields) {
        for (j = 0, len1 = maskTypeExtensionFields.length; j < len1; j++) {
          maskTypeExtensionField = maskTypeExtensionFields[j];
          if (!maskTypeExtensionsMergedMap[maskTypeExtensionField.name]) {
            maskTypeExtensionsMergedMap[maskTypeExtensionField.name] = {
              parameters: {},
              group: maskTypeExtensionField.group
            };
          }
          CUI.util.mergeMap(maskTypeExtensionsMergedMap[maskTypeExtensionField.name].parameters, maskTypeExtensionField.parameters);
        }
      }
    }
    maskTypeExtensionsMergedArray = [];
    for (name in maskTypeExtensionsMergedMap) {
      config = maskTypeExtensionsMergedMap[name];
      maskTypeExtensionsMergedArray.push({
        name: name,
        parameters: config.parameters,
        group: config.group
      });
    }
    return maskTypeExtensionsMergedArray;
  };

  return PluginManager;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var UserError,
  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;

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

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

  UserError.prototype.initOpts = function() {
    UserError.__super__.initOpts.call(this);
    return this.addOpts({
      label: {
        check: String
      },
      label_attrs: {
        check: (function(_this) {
          return function(v) {
            return CUI.util.isPlainObject(v) || CUI.util.isArray(v);
          };
        })(this)
      },
      text: {
        check: String
      }
    });
  };

  UserError.prototype.readOpts = function() {
    UserError.__super__.readOpts.call(this);
    if (this._label) {
      this.__text = $$(this._label, this._label_attrs);
    } else {
      this.__text = this._text;
    }
    return this;
  };

  UserError.prototype.getError = function() {
    return this.__text;
  };

  UserError.prototype.presentError = function(opts) {
    if (opts == null) {
      opts = {};
    }
    CUI.util.assert(!CUI.util.isEmpty(this.getError()), "new UserError", "opts.label or opts.text needs to be set.", {
      userError: this
    });
    return CUI.problem({
      text: this.getError()
    });
  };

  return UserError;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var InvalidSaveDataException,
  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;

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

  function InvalidSaveDataException(opts) {
    this.opts = opts != null ? opts : {};
    console.error("InvalidSaveDataException", arguments);
    InvalidSaveDataException.__super__.constructor.call(this, this.opts);
  }

  InvalidSaveDataException.prototype.getError = function() {
    var err;
    err = InvalidSaveDataException.__super__.getError.call(this);
    if (!CUI.util.isEmpty(err)) {
      return err;
    } else {
      return $$("invalid.save.data.exception.error");
    }
  };

  return InvalidSaveDataException;

})(UserError);
// Generated by CoffeeScript 1.12.7
var ServerRequest,
  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;

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

  function ServerRequest(opts1) {
    var err;
    this.opts = opts1 != null ? opts1 : {};
    ServerRequest.__super__.constructor.call(this, this.opts);
    err = "One of opts.api, opts.url, or opts.local_url must be set";
    this.__type = this._type || "GET";
    if (this._api) {
      CUI.util.assert(!this._url && !this._local_url, "new ServerRequest", err, {
        opts: this.opts
      });
      CUI.util.assert(this._api.startsWith("/"), "new ServerRequest", "opts.api needs to start with /", {
        opts: this.opts
      });
      if (window.secondary_server_url) {
        if (window.serverSwapIndex == null) {
          window.serverSwapIndex = 0;
        }
        if (window.serverSwapIndex % 2 === 0) {
          this.__server_url = window.secondary_server_url;
        } else {
          this.__server_url = window.easydb_server_url;
        }
        window.serverSwapIndex++;
      }
      this.__url = ez5.api.base(this.__server_url || "") + this._api;
      if (window.headless_mode) {
        this.__url = window.easydb_server_url + this._api;
      }
      if (!this.opts.hasOwnProperty("withCredentials")) {
        this._withCredentials = true;
      }
    }
    if (this._url) {
      CUI.util.assert(!this._local_url, "new ServerRequest", err, {
        opts: this.opts
      });
      this.__url = this._url;
    }
    if (this._local_url) {
      this.__url = this._local_url;
    }
    if (this.__server_url && !this._local_url && this.__url.startsWith("/")) {
      this.__url = this.__server_url + this.__url;
    }
    this.__headers = CUI.util.copyObject(this._headers, true);
    this.__prepareRequest();
  }

  ServerRequest.prototype.readOpts = function() {
    var ref;
    ServerRequest.__super__.readOpts.call(this);
    if (this._remoteEasydb) {
      this.__server_url = this._remoteEasydb.getServerUrl();
      this.__server_token = this._remoteEasydb.getServerToken();
    } else {
      this.__server_url = window.easydb_server_url;
      this.__server_token = (ref = ez5.session) != null ? ref.token : void 0;
    }
    if (this.__server_url) {
      CUI.util.assert(this.__server_url.startsWith("http://") || this.__server_url.startsWith("https://"), "new ServerRequest", "server_url needs to start with http:// or https://");
    }
  };

  ServerRequest.prototype.initOpts = function() {
    ServerRequest.__super__.initOpts.call(this);
    return this.addOpts({
      success: {
        check: Function
      },
      error: {
        check: Function
      },
      cache: {
        deprecated: true,
        check: Boolean
      },
      handle_error: {
        check: Function
      },
      async: {
        deprecated: true,
        check: Boolean
      },
      api: {
        check: String
      },
      dataType: {
        check: String
      },
      json_data: {},
      body: {},
      headers: {
        "default": {},
        check: "PlainObject"
      },
      data: {},
      url: {
        check: String
      },
      local_url: {
        check: String
      },
      timeout: {
        check: function(v) {
          return v >= 0;
        }
      },
      type: {
        check: ["POST", "GET", "PUT", "DELETE", "HEAD", "PATCH"]
      },
      remoteEasydb: {
        check: function(v) {
          return v instanceof RemoteEasydb;
        }
      },
      add_token: {
        "default": true,
        check: Boolean
      },
      skip_connector: {
        check: Boolean
      },
      dump_only: {
        "default": false,
        check: Boolean
      },
      dump_only_promise_policy: {
        "default": "reject",
        check: ["reject", "resolve"]
      },
      withCredentials: {
        mandatory: true,
        "default": false,
        check: Boolean
      }
    });
  };

  ServerRequest.prototype.getServerUrl = function() {
    return this.__server_url;
  };

  ServerRequest.prototype.start = function() {
    var dfr, fn, i, k, len, promise, ref;
    dfr = new CUI.Deferred();
    if (this._success) {
      dfr.done((function(_this) {
        return function(data, status, statusText) {
          return _this._success(data, status, _this.__xhr.getXHR());
        };
      })(this));
    }
    if (this._error) {
      dfr.fail((function(_this) {
        return function(data, status, statusText) {
          return _this._error(_this.__xhr.getXHR(), statusText);
        };
      })(this));
    }
    if (this._dump_only) {
      console.debug("ServerRequest", this.req);
      console.debug(this.req.method, this.req.url);
      if (this.req.json_data) {
        console.debug(CUI.util.dump(this.req.json_data));
      }
      dfr[this._dump_only_promise_policy]();
      return dfr.promise();
    }
    this.__doRequest(dfr);
    promise = dfr.promise();
    ref = ["abort"];
    fn = (function(_this) {
      return function(k) {
        return promise[k] = function() {
          return _this.__xhr[k].apply(_this.__xhr, arguments);
        };
      };
    })(this);
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      fn(k);
    }
    return promise;
  };

  ServerRequest.prototype.handle202 = function(dfr, data) {
    var form_data, show_task_modal;
    form_data = {};
    show_task_modal = function(task_idx, tasks_dfr) {
      var btn, buttons, f, field, fields, fn, form, get_text, i, index, j, l, len, len1, len2, mod, opt, ref, ref1, ref2, set_buttons_state, task;
      if (tasks_dfr == null) {
        tasks_dfr = new CUI.Deferred();
      }
      if (!(task = data.tasks[task_idx])) {
        tasks_dfr.resolve();
        return;
      }
      dfr.notify("start", task_idx, data.tasks.length);
      fields = [];
      get_text = (function(_this) {
        return function(obj) {
          if (CUI.util.isPlainObject(obj)) {
            return $$(obj.code, obj.parameters);
          }
          return "" + obj;
        };
      })(this);
      if (task.form) {
        ref = task.form;
        for (i = 0, len = ref.length; i < len; i++) {
          f = ref[i];
          if (f.name) {
            form_data[f.name] = void 0;
          }
          field = {
            form: {
              label: get_text(f.label)
            }
          };
          switch (f.type) {
            case "options":
              field.undo_and_changed_support = false;
              field.type = CUI.Options;
              field.name = f.name;
              field.ui = "task.modal.field:" + f.name;
              field.radio = true;
              field.horizontal = f.horizontal;
              ref1 = f.options;
              for (index = j = 0, len1 = ref1.length; j < len1; index = ++j) {
                opt = ref1[index];
                if (opt.text) {
                  opt.text = get_text(opt.text);
                  opt.ui = "task.modal.field:" + f.name + ":" + index;
                }
              }
              field.options = f.options;
              break;
            default:
              CUI.util.assert(false, "ServerRequest.handle202", "Unknown field in task.form", {
                task: task
              });
          }
          fields.push(field);
        }
        form = new CUI.Form({
          onDataChanged: function() {
            return set_buttons_state();
          },
          "class": "server-request-handle-202-form",
          ui: "task.modal",
          data: form_data,
          fields: fields
        });
        form.start();
      } else {
        form = null;
      }
      buttons = [];
      if (task.buttons) {
        ref2 = task.buttons;
        fn = function(btn) {
          return buttons.push(new CUI.Button({
            text: get_text(btn.text),
            ui: "task.modal.button:" + (btn.name || index),
            primary: btn.name === "confirm" || btn.name === "confirmTransition",
            onClick: function() {
              if (btn.name) {
                form_data[btn.name] = btn.value;
              }
              mod.destroy();
              dfr.notify("confirmed", task_idx, data.tasks.length);
              show_task_modal(task_idx + 1, tasks_dfr);
            }
          }));
        };
        for (index = l = 0, len2 = ref2.length; l < len2; index = ++l) {
          btn = ref2[index];
          if (btn.hidden) {
            CUI.util.assert(btn.name && btn.hasOwnProperty("value"), "ServerRequest.handle202", "btn.hidden needs button name and btn.value to be set.", {
              button: btn
            });
            form_data[btn.name] = btn.value;
            continue;
          }
          fn(btn);
        }
      } else {
        CUI.util.assert(false, "ServerRequest.handle202", "Task did not provide a button", {
          task: task
        });
      }
      set_buttons_state = function() {
        var df, form_ok, len3, len4, m, n, o, ref3;
        if (!form) {
          form_ok = true;
        } else {
          form_ok = true;
          ref3 = form.getDataFields();
          for (m = 0, len3 = ref3.length; m < len3; m++) {
            df = ref3[m];
            if (n = df.getName()) {
              if (CUI.util.isFalse(form_data[n])) {
                form_ok = false;
                break;
              }
            }
          }
        }
        for (o = 0, len4 = buttons.length; o < len4; o++) {
          btn = buttons[o];
          if (form_ok) {
            btn.enable();
          } else {
            btn.disable();
          }
        }
      };
      mod = new CUI.ConfirmationDialog({
        "class": "ez5-server-request-handle-202",
        title: get_text(task.title),
        cancel: true,
        onCancel: function() {
          tasks_dfr.reject(task_idx);
        },
        content: function() {
          var div202Content, div202Message;
          div202Content = CUI.dom.div("server-request-handle-202-content");
          div202Message = CUI.dom.div("server-202-message");
          CUI.dom.append(div202Message, new CUI.Label({
            markdown: true,
            multiline: true,
            text: get_text(task.message)
          }));
          CUI.dom.append(div202Content, div202Message);
          if (form) {
            CUI.dom.append(div202Content, form);
          }
          return div202Content;
        },
        buttons: buttons
      });
      set_buttons_state();
      mod.show();
      return tasks_dfr.promise();
    };
    return show_task_modal(0).done((function(_this) {
      return function() {
        var k, v;
        dfr.notify("done");
        CUI.util.assert(!CUI.util.isEmptyObject(form_data), "ServerRequest.handle202", "Server did not provide at least one \"name\" field or button.", {
          form_data: form_data
        });
        _this.req.url = _this.__url;
        _this.req.url_data = _this._data || {};
        for (k in form_data) {
          v = form_data[k];
          _this.req.url_data[k] = v;
        }
        return _this.__doRequest(dfr);
      };
    })(this)).fail(function(task_idx) {
      return dfr.reject("cancelled", task_idx, data.tasks.length);
    });
  };

  ServerRequest.prototype.handle502 = function(dfr) {
    if (!ServerRequest.bad_gateway_modal) {
      ServerRequest.bad_gateway_modal = new CUI.AlertProblem({
        choices: [],
        title: $$("server.error.bad_gateway.title"),
        text: $$("server.error.bad_gateway.text")
      });
      ServerRequest.bad_gateway_modal.open();
    }
    if (!this.__502_in_progress) {
      this.__502_in_progress = true;
      dfr.done((function(_this) {
        return function() {
          var ref;
          if ((ref = ServerRequest.bad_gateway_modal) != null) {
            ref.destroy();
          }
          delete ServerRequest.bad_gateway_modal;
          return delete _this.__502_in_progress;
        };
      })(this));
    }
    CUI.setTimeout((function(_this) {
      return function() {
        return _this.__doRequest(dfr);
      };
    })(this), 2500);
  };

  ServerRequest.__active = 0;

  ServerRequest.hasRequests = function() {
    return this.__active > 0;
  };

  ServerRequest.prototype.__doRequest = function(dfr) {
    var handleRefreshToken;
    handleRefreshToken = (function(_this) {
      return function() {
        _this.__server_token = ez5.session.token;
        if (ez5.version("6.1")) {
          _this.__headers["Authorization"] = "Bearer " + _this.__server_token;
        } else {
          _this.__headers["X-Easydb-Token"] = _this.__server_token;
        }
        return _this.__doRequest(dfr);
      };
    })(this);
    this.__xhr = new CUI.XHR(this.req);
    this.__xhr.start().done((function(_this) {
      return function(data, status, statusText) {
        if (status === 202) {
          _this.handle202(dfr, data);
          return;
        }
        return dfr.resolve(data, status, _this.__xhr.getXHR());
      };
    })(this)).fail((function(_this) {
      return function(data, status, statusText) {
        var error_args, ref;
        if (ez5.version("6") && window.easydb_refreshing_token && !((ref = _this.__xhr._json_data) != null ? ref.refresh_token : void 0)) {
          window.easydb_refreshing_token.done(function() {
            return handleRefreshToken();
          }).fail(function() {
            ez5.login.redirectToOAUTH2Login();
          });
          return;
        }
        if (ez5.version("6") && status === 401 && CUI.getSessionStorage("token")) {
          if (!window.easydb_refreshing_token) {
            window.easydb_refreshing_token = ez5.session.refresh().done(function() {
              handleRefreshToken();
            }).fail(function() {
              ez5.login.redirectToOAUTH2Login();
            }).always(function() {
              return window.easydb_refreshing_token = null;
            });
          }
          return;
        }
        error_args = [_this.__xhr.getXHR(), statusText];
        switch (typeof _this._handle_error === "function" ? _this._handle_error(_this.__xhr.getXHR()) : void 0) {
          case true:
            dfr.reject.apply(dfr, error_args);
            return;
        }
        if (status === 502) {
          _this.handle502(dfr);
          return;
        }
        if (!_this._error && statusText !== "abort") {
          return ez5.error_handler(_this.__xhr.getXHR(), _this).done(function() {
            return dfr.reject.apply(dfr, error_args);
          }).fail(function() {
            return _this.__doRequest(dfr);
          });
        } else {
          return dfr.reject.apply(dfr, error_args);
        }
      };
    })(this)).progress(function() {
      return dfr.notify.apply(dfr, arguments);
    });
    return this;
  };

  ServerRequest.prototype.__prepareRequest = function() {
    var useBearerToken;
    useBearerToken = (function(_this) {
      return function() {
        var ref;
        if (ez5.version("6.1") && !_this._remoteEasydb) {
          return true;
        }
        if ((ref = _this._remoteEasydb) != null ? typeof ref.isFylr === "function" ? ref.isFylr() : void 0 : void 0) {
          return true;
        }
        return false;
      };
    })(this);
    this.req = {
      method: this.__type,
      url: this.__url,
      url_data: this._data,
      body: this._body,
      timeout: this._timeout,
      json_data: this._json_data,
      json_pretty: false,
      responseType: this._dataType,
      headers: this.__headers,
      withCredentials: this._withCredentials
    };
    if (this._add_token && this.__server_token) {
      if (useBearerToken()) {
        this.__headers["Authorization"] = "Bearer " + this.__server_token;
        return this.__headers["X-Fylr-Authorization"] = "Bearer " + this.__server_token;
      } else {
        return this.__headers["X-Easydb-Token"] = this.__server_token;
      }
    }
  };

  ServerRequest.prototype.getRequest = function() {
    return this.req;
  };

  return ServerRequest;

})(CUI.Element);

ez5.server = function(opts) {
  return (new ServerRequest(opts)).start();
};
// Generated by CoffeeScript 1.12.7
var ServerRequestApi,
  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;

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

  function ServerRequestApi(opts1) {
    var api, defaults, fn, ref;
    this.opts = opts1 != null ? opts1 : {};
    ServerRequestApi.__super__.constructor.call(this, this.opts);
    ref = ServerRequestApi.apis;
    fn = (function(_this) {
      return function(api, defaults) {
        return _this[api] = function(opts) {
          if (opts == null) {
            opts = {};
          }
          CUI.util.mergeMap(opts, defaults);
          return _this.__call(api, opts);
        };
      };
    })(this);
    for (api in ref) {
      defaults = ref[api];
      fn(api, defaults);
    }
    return;
  }

  ServerRequestApi.prototype.base = function(server) {
    if (server) {
      return server + "/api/v1";
    }
    return window.easydb_base_prefix + "/api/v1";
  };

  ServerRequestApi.getXEasydbHeaders = function(xhr) {
    var x_easydb;
    if (ez5.version("6")) {
      return {
        fylrCacheId: xhr.getResponseHeader("X-Fylr-Cache-Id"),
        readonly: xhr.getResponseHeader("X-Fylr-Read-Only-Mode")
      };
    }
    x_easydb = {
      base: xhr.getResponseHeader("X-Easydb-Base-Schema-Version"),
      user: xhr.getResponseHeader("X-Easydb-User-Schema-Version"),
      solution: xhr.getResponseHeader("X-Easydb-Solution"),
      readonly: xhr.getResponseHeader("X-Easydb-Read-Only-Mode")
    };
    if (!x_easydb.base) {
      return;
    }
    return x_easydb;
  };

  ServerRequestApi.prototype.getFullBase = function() {
    if (window.easydb_server_url) {
      return this.base(window.easydb_server_url);
    }
    return this.base();
  };

  ServerRequestApi.prototype.__call = function(api, opts) {
    if (opts.api) {
      CUI.util.assert(opts.api.startsWith("/"), "ez5.api." + api, "opts.api needs to start with /", {
        opts: opts
      });
      opts.api = "/" + api + opts.api;
    } else {
      opts.api = "/" + api;
    }
    return (new ServerRequest(opts)).start().done((function(_this) {
      return function(_1, _2, xhr) {
        var x_easydb;
        x_easydb = ServerRequestApi.getXEasydbHeaders(xhr);
        if (x_easydb) {
          ez5.session.__x_easydb = x_easydb;
        }
      };
    })(this));
  };

  ServerRequestApi.prototype.search_no_limit = function(_req) {
    var data, debug, dfr, limit, load_next_chunk, offset, req, ret_promise;
    if (_req == null) {
      _req = {};
    }
    limit = _req.json_data.limit || 0;
    if ((_req.json_data.limit || 0) <= 1000) {
      return this.search(_req);
    }
    req = CUI.util.copyObject(_req, true);
    if (!req.data) {
      req.data = {};
    }
    if (!req.data.debug) {
      req.data.debug = "";
    }
    if (req.data.debug) {
      debug = req.data.debug + "--";
    } else {
      debug = "";
    }
    offset = req.json_data.offset || 0;
    data = null;
    req.json_data.limit = 1000;
    dfr = new CUI.Deferred();
    load_next_chunk = (function(_this) {
      return function() {
        var chunk_promise;
        req.json_data.offset = offset;
        req.data.debug = debug + (offset + "-" + limit);
        delete req.api;
        chunk_promise = _this.search(req).fail(dfr.reject).done(function(_data) {
          var i, len, obj, ref;
          if (data === null) {
            data = _data;
          } else {
            data.limit = _data.limit + data.limit;
            ref = _data.objects;
            for (i = 0, len = ref.length; i < len; i++) {
              obj = ref[i];
              data.objects.push(obj);
            }
          }
          if (_data.offset + 1000 < Math.min(_data.count, limit)) {
            offset = offset + 1000;
            return load_next_chunk();
          } else {
            return dfr.resolve(data);
          }
        });
        return ret_promise.abort = function() {
          return chunk_promise.abort();
        };
      };
    })(this);
    ret_promise = dfr.promise();
    load_next_chunk();
    return ret_promise;
  };

  ServerRequestApi.apis = {
    search: {
      type: "POST",
      data: {
        pretty: 0
      }
    },
    db: {
      type: "POST"
    },
    settings: {},
    publish: {
      type: "POST"
    },
    "export": {},
    schema: {},
    objects: {},
    objecttype: {},
    collection: {},
    config: {},
    suggest: {},
    eas: {},
    settings: {},
    system: {},
    tags: {},
    transitions: {},
    mask: {},
    l10n: {},
    plugin: {},
    db_info: {
      type: "POST"
    },
    session: {},
    event: {},
    right: {},
    message: {},
    xmlmapping: {},
    user: {},
    group: {},
    pool: {},
    task: {}
  };

  return ServerRequestApi;

})(CUI.Element);

ez5.api = new ServerRequestApi();
// Generated by CoffeeScript 1.12.7
var ServerErrorModal;

ServerErrorModal = (function() {
  function ServerErrorModal(error) {
    this.error = error;
  }

  ServerErrorModal.prototype.show = function() {
    return ez5.server({
      api: "/plugin/base/server/error/" + this.error.uuid
    }).done((function(_this) {
      return function(data) {
        var mod;
        return mod = new CUI.Modal({
          "class": "uuid-error-detail",
          cancel: true,
          pane: {
            header_left: new CUI.Label({
              text: $$("base.error.uuid.modal.title")
            }),
            content: function() {
              return _this.renderError(data);
            },
            footer_right: [
              {
                text: $$("base.ok"),
                onClick: function(df) {
                  return mod.destroy();
                }
              }
            ]
          }
        }).show();
      };
    })(this));
  };

  ServerErrorModal.prototype.renderError = function(d) {
    var app, table;
    table = CUI.dom.table("uuid-error");
    app = function(key, content) {
      if (CUI.util.isEmpty(content.innerHTML)) {
        content = $span$("base.empty_value");
      }
      return table.append(CUI.dom.tr_one_row($$("base.error.uuid.modal." + key), content));
    };
    app("uuid", CUI.dom.text(this.error.uuid));
    app("error", $span$(d.code));
    app("description", CUI.dom.text(d.description));
    app("timestamp", CUI.dom.text(ez5.format_date_and_time(d.timestamp)));
    app("session.token", CUI.dom.text(d.session.token));
    app("session.created", CUI.dom.text(ez5.format_date_and_time(d.session.created)));
    app("request.method", CUI.dom.text(d.request.method));
    app("request.url", CUI.dom.text(d.request.url));
    app("request.header", CUI.dom.append(CUI.dom.pre(), CUI.dom.htmlToNodes(d.request.header)));
    if (d.request.method !== "GET") {
      app("request.body", CUI.dom.append(CUI.dom.pre(), CUI.dom.htmlToNodes(d.request.body)));
    }
    return table;
  };

  return ServerErrorModal;

})();
// Generated by CoffeeScript 1.12.7
var EventPoller,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  EventPoller.prototype.readOpts = function() {
    EventPoller.__super__.readOpts.call(this);
    this.stopped = true;
    this.last_poll_id = ez5.session.data.current_max_event_id;
    if (!(this.last_poll_id > 0 || this.last_poll_id === 0)) {
      return console.error("EventPoller.readOpts: session.current_max_event_id not set, unable to poll.");
    }
  };

  EventPoller.saveEvent = function(event_json_data, remoteEasydb, ignore_errors) {
    var e, log, type;
    if (event_json_data == null) {
      event_json_data = {};
    }
    if (ignore_errors == null) {
      ignore_errors = false;
    }
    if (!ez5.session.isAuthenticated()) {
      console.error("EventPoller.saveEvent: Unable to save event, session not authenticated.");
      return CUI.rejectedPromise();
    }
    CUI.Element.readOpts(event_json_data, "EventPoller.saveEvent", {
      basetype: function() {
        return {
          check: String
        };
      },
      objecttype: function() {
        return {
          check: String
        };
      },
      object_version: function() {
        return {
          check: String
        };
      },
      object_id: function() {
        return {
          check: String
        };
      },
      schema: function() {
        return {
          check: String
        };
      },
      pollable: function() {
        return {
          check: Boolean
        };
      },
      type: {
        check: String
      },
      info: {
        check: "PlainObject"
      }
    });
    if (remoteEasydb) {
      log = remoteEasydb.getSession().getBaseConfig().log;
    } else {
      log = ez5.session.getBaseConfig().log;
    }
    type = event_json_data.type.toLowerCase();
    if ((log != null ? log[type] : void 0) !== false) {
      if (ez5.version("6")) {
        if (!remoteEasydb || (remoteEasydb != null ? typeof remoteEasydb.isFylr === "function" ? remoteEasydb.isFylr() : void 0 : void 0)) {
          event_json_data = {
            event: event_json_data
          };
        }
      } else {
        if (remoteEasydb && (remoteEasydb != null ? typeof remoteEasydb.isFylr === "function" ? remoteEasydb.isFylr() : void 0 : void 0)) {
          event_json_data = {
            event: event_json_data
          };
        }
      }
      try {
        return ez5.api.event({
          type: "POST",
          remoteEasydb: remoteEasydb,
          json_data: event_json_data,
          handle_error: (function(_this) {
            return function() {
              return ignore_errors;
            };
          })(this)
        }).done((function(_this) {
          return function(data) {};
        })(this));
      } catch (error) {
        e = error;
        return console.warn("Error when trying to save an event on the eventlog: ", e);
      }
    } else {
      return CUI.resolvedPromise();
    }
  };

  EventPoller.prototype.start = function() {
    var poll_config;
    if (!(this.last_poll_id > 0 || this.last_poll_id === 0)) {
      return;
    }
    this.stopped = false;
    poll_config = ez5.session.getPref("event_poll");
    if (ez5.version("6.3") && (poll_config === "auto" || poll_config === true)) {
      console.log("Opening Stream for server Events.");
      return this.startStream();
    } else {
      console.log("Starting request poller for server Events.");
      return this.poll();
    }
  };

  EventPoller.prototype.startStream = function() {
    return this.__openStream().fail((function(_this) {
      return function(e) {
        console.warn("Event Stream creation failed. Using legacy poller.");
        delete _this.__pollSocket;
        return _this.poll();
      };
    })(this));
  };

  EventPoller.prototype.__destroyRetryConnectionAlert = function() {
    if (this.__retryConnectionAlert) {
      CUI.dom.removeClass(this.__retryConnectionAlert, "is-on-screen");
      this.__retryConnectionAlert.destroy();
      delete this.__retryConnectionAlert;
    }
  };

  EventPoller.MAX_STREAM_RETRIES = 10;

  EventPoller.prototype.restartStream = function() {
    if (!this.__pollSocket) {
      return;
    }
    if (this.__streamRestartTries == null) {
      this.__streamRestartTries = 0;
    }
    if (this.__streamRestartTries++ > EventPoller.MAX_STREAM_RETRIES) {
      delete this.__pollSocket;
      console.log("Max Tries to reconnect to stream reached, using legacy poller...");
      this.__destroyRetryConnectionAlert();
      this.poll();
      return;
    }
    if (!this.__retryConnectionAlert) {
      this.__retryConnectionAlert = new CUI.Alert({
        choices: [],
        "class": "ez5-alert-connection",
        content: new CUI.MultilineLabel({
          text: $$("base.alert.connection_lost"),
          centered: true
        }),
        button_text_ok: $$("editor.modal.new.upload-progress-abort-button"),
        backdrop: false
      });
      setTimeout((function(_this) {
        return function() {
          if (!_this.__retryConnectionAlert) {
            return;
          }
          _this.__retryConnectionAlert.open();
          return CUI.dom.addClass(_this.__retryConnectionAlert, "is-on-screen");
        };
      })(this), 3000);
    }
    return setTimeout((function(_this) {
      return function() {
        console.log("Retrying event stream connection");
        _this.__openStream().fail(function(e) {
          return ez5.api.user({
            api: "/session",
            type: "GET",
            handle_error: function() {
              return true;
            }
          }).fail(function(e) {
            var ref;
            if (((ref = e.response) != null ? ref.code : void 0) === "InvalidToken") {
              return ez5.session.refresh().fail(function() {
                return document.location.reload();
              });
            }
          });
        });
      };
    })(this), 3000);
  };

  EventPoller.prototype.__openStream = function() {
    this.__pollSocket = new CUI.Socket({
      url: Session.addToken((ez5.api.getFullBase()) + "/event/stream"),
      onmessage: (function(_this) {
        return function(ev, data) {
          return _this.__onStreamMessage(ev, data);
        };
      })(this),
      onclose: (function(_this) {
        return function() {
          return _this.restartStream();
        };
      })(this),
      onopen: (function(_this) {
        return function() {
          return _this.__destroyRetryConnectionAlert();
        };
      })(this)
    });
    return this.__pollSocket.open();
  };

  EventPoller.prototype.__onStreamMessage = function(event, data) {
    var callBatchDone, checkEventsBatch;
    callBatchDone = (function(_this) {
      return function() {
        _this.__streamBatchingCount = 0;
        clearTimeout(_this.__streamBatching);
        delete _this.__streamBatching;
        CUI.Events.trigger({
          type: "event-poller",
          info: {
            batch_done: true
          }
        });
      };
    })(this);
    checkEventsBatch = (function(_this) {
      return function() {
        if (_this.__streamBatchingCount == null) {
          _this.__streamBatchingCount = 0;
        }
        _this.__streamBatchingCount++;
        if (_this.__streamBatchingCount >= ResultDynamicLoading.loadingChunkSize) {
          callBatchDone();
          return;
        }
        if (_this.__streamBatching) {
          return;
        }
        _this.__streamBatching = setTimeout(function() {
          delete _this.__streamBatching;
          return callBatchDone();
        }, 500);
      };
    })(this);
    event = data.event;
    CUI.Events.trigger({
      type: "event-poller",
      info: {
        event: event,
        user: data.user
      }
    });
    checkEventsBatch();
  };

  EventPoller.prototype.stop = function() {
    return this.stopped = true;
  };

  EventPoller.prototype.isStopped = function() {
    return this.stopped;
  };

  EventPoller.prototype.poll = function() {
    if (this.isStopped()) {
      return;
    }
    return this.__poll();
  };

  EventPoller.prototype.pollOnce = function() {
    return this.__poll(true);
  };

  EventPoller.prototype.__schedulePoll = function() {
    return this.__pollTimeout = CUI.setTimeout({
      ms: EventPoller.interval,
      track: false,
      call: (function(_this) {
        return function() {
          return _this.poll();
        };
      })(this)
    });
  };

  EventPoller.prototype.__poll = function(one_only) {
    if (one_only == null) {
      one_only = false;
    }
    CUI.clearTimeout(this.__pollTimeout);
    if (CUI.dom.find(".ez5-event-poller").length === 0 || CUI.dom.find(".ez5-admin-message--maintenance").length > 0) {
      this.__schedulePoll();
      return;
    }
    ez5.api.event({
      type: "GET",
      handle_error: function(xhr) {
        return true;
      },
      api: "/poll/" + this.last_poll_id
    }).done((function(_this) {
      return function(events, status, jqXHR) {
        var _event, event, i, len;
        if (!ez5.session.checkSchemaVersions(jqXHR)) {
          return;
        }
        for (i = 0, len = events.length; i < len; i++) {
          _event = events[i];
          event = _event.event;
          if (ez5.session.isDebug()) {
            console.info("Event #" + event._id + ": " + event.type, event);
          }
          CUI.Events.trigger({
            type: "event-poller",
            info: {
              event: event,
              user: _event.user
            }
          });
          _this.last_poll_id = event._id;
        }
        if (events.length > 0) {
          CUI.Events.trigger({
            type: "event-poller",
            info: {
              batch_done: true
            }
          });
        }
        if (one_only) {
          return;
        }
        return _this.__schedulePoll();
      };
    })(this)).fail((function(_this) {
      return function(xhr) {
        var ref, ref1;
        if (one_only) {
          return;
        }
        if (!ez5.version("6") && ((ref = (ref1 = xhr.responseJSON) != null ? ref1.code : void 0) === 'error.user.session_not_found' || ref === 'error.api.cookie_check_failed' || ref === 'error.user.session_expired')) {
          document.location.reload();
        }
        return _this.__schedulePoll();
      };
    })(this));
    return this;
  };

  EventPoller.interval = 3000;

  EventPoller.listen = function(_opts) {
    var events, mypoll, opts;
    opts = CUI.Element.readOpts(_opts, "EventPoller.listen", {
      filter: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isPlainObject(v) || CUI.util.isFunction(v);
        }
      },
      instance: {
        mandatory: true,
        check: function(v) {
          return v instanceof CUI.Element;
        }
      },
      node: {
        check: function(v) {
          return CUI.dom.isNode(v);
        }
      },
      call: {
        mandatory: true,
        check: Function
      }
    });
    events = [];
    mypoll = CUI.Events.listen({
      type: "event-poller",
      instance: opts.instance,
      node: opts.node,
      call: (function(_this) {
        return function(ev, info) {
          var event, k, ref, ref1, v;
          if (info.batch_done) {
            if (events.length === 0) {
              return;
            }
            opts.call.call(opts.instance, events);
            events = [];
          }
          event = info.event;
          if (!event) {
            return;
          }
          if (CUI.util.isFunction(opts.filter)) {
            if (!opts.filter.call(opts.instance, event)) {
              return;
            }
          } else {
            ref = opts.filter;
            for (k in ref) {
              v = ref[k];
              if (CUI.util.isArray(v)) {
                if (ref1 = event[k], indexOf.call(v, ref1) < 0) {
                  return;
                }
              } else if (event[k] !== v) {
                return;
              }
            }
          }
          return events.push(event);
        };
      })(this)
    });
    return mypoll;
  };

  return EventPoller;

})(CUI.Element);

CUI.ready(function() {
  return CUI.Events.registerEvent({
    type: "event-poller",
    sink: true
  });
});

ez5.session_ready(function() {
  var pl;
  if (window.headless_mode) {
    return;
  }
  ez5.eventPoller = pl = new EventPoller();
  if (ez5.session.getPref("event_poll")) {
    return pl.start();
  } else {
    return pl.stop();
  }
});
// Generated by CoffeeScript 1.12.7
var OnlyYearSchemaPlugin,
  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;

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

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

  OnlyYearSchemaPlugin.prototype.getCustomSettings = function(data) {
    var fields, ref, ref1;
    if (((ref = data != null ? (ref1 = data.column) != null ? ref1.type : void 0 : void 0) !== "date" && ref !== "daterange") || !ez5.version("6")) {
      return [];
    }
    if (!data.custom_settings) {
      data.custom_settings = {};
    }
    fields = [
      {
        type: CUI.Checkbox,
        name: "only_years",
        text: $$("admin.datamodel.col.extra_options.only_years"),
        data: data.custom_settings,
        form: {
          hint: $$("admin.datamodel.col.extra_options.only_years.hint")
        }
      }
    ];
    return fields;
  };

  OnlyYearSchemaPlugin.prototype.getCustomSettingsLabel = function(data) {
    var ref, ref1;
    if ((ref = data != null ? (ref1 = data.column) != null ? ref1.type : void 0 : void 0) !== "date" && ref !== "daterange") {
      return;
    }
    return $$("admin.datamodel.col.extra_options.label");
  };

  OnlyYearSchemaPlugin.prototype.getCustomSettingsDisplay = function(data) {
    var ref;
    if ((ref = data.custom_settings) != null ? ref.only_years : void 0) {
      return [$$("admin.datamodel.col.extra_options.only_years.display")];
    }
    return [];
  };

  return OnlyYearSchemaPlugin;

})(SchemaPlugin);

Schema.registerPlugin(new OnlyYearSchemaPlugin());
/**
*
*  MD5 (Message-Digest Algorithm)
*  http://www.webtoolkit.info/
*
**/

var MD5 = function (string) {

	function RotateLeft(lValue, iShiftBits) {
		return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
	}

	function AddUnsigned(lX,lY) {
		var lX4,lY4,lX8,lY8,lResult;
		lX8 = (lX & 0x80000000);
		lY8 = (lY & 0x80000000);
		lX4 = (lX & 0x40000000);
		lY4 = (lY & 0x40000000);
		lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
		if (lX4 & lY4) {
			return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
		}
		if (lX4 | lY4) {
			if (lResult & 0x40000000) {
				return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
			} else {
				return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
			}
		} else {
			return (lResult ^ lX8 ^ lY8);
		}
 	}

 	function F(x,y,z) { return (x & y) | ((~x) & z); }
 	function G(x,y,z) { return (x & z) | (y & (~z)); }
 	function H(x,y,z) { return (x ^ y ^ z); }
	function I(x,y,z) { return (y ^ (x | (~z))); }

	function FF(a,b,c,d,x,s,ac) {
		a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
		return AddUnsigned(RotateLeft(a, s), b);
	};

	function GG(a,b,c,d,x,s,ac) {
		a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
		return AddUnsigned(RotateLeft(a, s), b);
	};

	function HH(a,b,c,d,x,s,ac) {
		a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
		return AddUnsigned(RotateLeft(a, s), b);
	};

	function II(a,b,c,d,x,s,ac) {
		a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
		return AddUnsigned(RotateLeft(a, s), b);
	};

	function ConvertToWordArray(string) {
		var lWordCount;
		var lMessageLength = string.length;
		var lNumberOfWords_temp1=lMessageLength + 8;
		var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
		var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
		var lWordArray=Array(lNumberOfWords-1);
		var lBytePosition = 0;
		var lByteCount = 0;
		while ( lByteCount < lMessageLength ) {
			lWordCount = (lByteCount-(lByteCount % 4))/4;
			lBytePosition = (lByteCount % 4)*8;
			lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
			lByteCount++;
		}
		lWordCount = (lByteCount-(lByteCount % 4))/4;
		lBytePosition = (lByteCount % 4)*8;
		lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
		lWordArray[lNumberOfWords-2] = lMessageLength<<3;
		lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
		return lWordArray;
	};

	function WordToHex(lValue) {
		var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
		for (lCount = 0;lCount<=3;lCount++) {
			lByte = (lValue>>>(lCount*8)) & 255;
			WordToHexValue_temp = "0" + lByte.toString(16);
			WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
		}
		return WordToHexValue;
	};

	function Utf8Encode(string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	};

	var x=Array();
	var k,AA,BB,CC,DD,a,b,c,d;
	var S11=7, S12=12, S13=17, S14=22;
	var S21=5, S22=9 , S23=14, S24=20;
	var S31=4, S32=11, S33=16, S34=23;
	var S41=6, S42=10, S43=15, S44=21;

	string = Utf8Encode(string);

	x = ConvertToWordArray(string);

	a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;

	for (k=0;k<x.length;k+=16) {
		AA=a; BB=b; CC=c; DD=d;
		a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
		d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
		c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
		b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
		a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
		d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
		c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
		b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
		a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
		d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
		c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
		b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
		a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
		d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
		c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
		b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
		a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
		d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
		c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
		b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
		a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
		d=GG(d,a,b,c,x[k+10],S22,0x2441453);
		c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
		b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
		a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
		d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
		c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
		b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
		a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
		d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
		c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
		b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
		a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
		d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
		c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
		b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
		a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
		d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
		c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
		b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
		a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
		d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
		c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
		b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
		a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
		d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
		c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
		b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
		a=II(a,b,c,d,x[k+0], S41,0xF4292244);
		d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
		c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
		b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
		a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
		d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
		c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
		b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
		a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
		d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
		c=II(c,d,a,b,x[k+6], S43,0xA3014314);
		b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
		a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
		d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
		c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
		b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
		a=AddUnsigned(a,AA);
		b=AddUnsigned(b,BB);
		c=AddUnsigned(c,CC);
		d=AddUnsigned(d,DD);
	}

	var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);

	return temp.toLowerCase();
}


ez5.bind_schema_funcs = function (bind) {

	// schema and mask relevant stuff
	bind.clean_schema = function (schema) {
		delete (schema._table_by_id);
		delete (schema._table_by_name);
		delete (schema._objecttypes);
		delete (schema._objecttype_by_name);
		schema.tables.forEach(function (table, idx) {
			delete (table._column_by_id);
			delete (table._column_by_name);
			delete (table._column_by_name_localized);
			delete (table._name_localized);
			if (table._owned_by) {
				delete (table._owned_by._column);
			}
			delete (table._name_localized);
			delete (table._l10n_key);
			// delete(table._primary_key_column);
			delete (table._preferred_mask);
			// delete(table._all_fields_mask);
			table.columns.forEach(function (column, idx2) {
				delete (column._system_type);
				delete (column._foreign_key);
				delete (column._unique_keys);
				delete (column._l10n_key);
				delete (column._name_localized);
			});
		});
	}

	bind.enrich_schema = function (schema, version) {
		schema._table_by_id = {};
		schema._table_by_name = {};
		schema._objecttypes = [];
		schema._objecttype_by_name = {};

		var nested_columns = [];
		var reverse_nested_columns = [];
		var col;

		var table_name_localized = function (name) {
			return ez5.loca.get_user_key_localized(version, "schema." + name + ".name", name);
		}

		schema.tables.forEach(function (table, idx) {
			table._column_by_id = {}
			table._column_by_name = {}
			table._column_by_name_localized = {}

			table.columns.forEach(function (column, idx2) {
				/*
				  if (table.primary_key.columns[0].column_id === column.column_id) {
				  table._primary_key_column = column;
				  column._system_type = "primary-key-field";
				  } else if (table.owned_by && table.owned_by.column_id === column.column_id) {
				  column._system_type = "linked-table-field";
				  }
				*/
				if (table.bidirectional) {
					table.bidirectional.forEach(function (bidi, idx3) {
						bidi.columns.forEach(function (bidi_column, idx4) {
							if (column.column_id === bidi_column.column_id) {
								column.bidirectional = true;
							}
						});
					});
				}
				switch (column.kind) {
					case "column":
						table._column_by_id[column.column_id] = column;
						column._l10n_key = "schema." + table.name + ".column." + column.name;
						column._name_localized =
							ez5.loca.get_user_key_localized(version, column._l10n_key, column.name);
						break;
					case "link": // this is a nested_table
						column._other_table_id = column.other_table_id;
						column._other_column_id = column.other_column_id;
						column._l10n_key = "schema." + table.name + ".column." + column.other_table_name_hint;
						column._name_localized =
							ez5.loca.get_user_key_localized(version, column._l10n_key,
								column.other_table_name_hint.substr((table.name + "__").length));
						nested_columns.push(column);
						break;
					case "reverse_link": // this is a reverse_link
						if (!column.is_hierarchical) {
							column._other_table_id = column.other_table_id;
							column._other_column_id = column.other_column_id;
							column._l10n_key = "schema." + table.name + ".column.reverse:" + column.other_table_name_hint + "." + column.other_column_id;
							column._l10n_key_old = "schema." + table.name + ".column.reverse:" + column.other_table_name_hint;
							reverse_nested_columns.push(column);
						} else {
							column._l10n_key = "schema." + table.name + ".column.reverse:" + table.name;
							column._name_localized =
								ez5.loca.get_user_key_localized(version, column._l10n_key,
									table_name_localized(table.name));
						}
				}

				table._column_by_name[column.name] = column;
				if (table._column_by_name_localized[column._name_localized]) {
					// the column name already exists, we need to create a unique name
					var idx = 1, new_name; // we start at 1 so that the first visible index is 2
					do {
						idx++;
						new_name = column._name_localized + " [" + idx + "]";
					} while (table._column_by_name_localized[new_name]);
					column._name_localized = new_name;
				}
				table._column_by_name_localized[column._name_localized] = column;
			});

			table._l10n_key = "schema." + table.name + ".name";
			table._name_localized = table_name_localized(table.name);
			schema._table_by_id[table.table_id] = table;
			schema._table_by_name[table.name] = table;
			if (!table.owned_by) {
				schema._objecttypes.push(table);
				schema._objecttype_by_name[table.name] = table;
			}
			// link foreign keys to their columns
			table.foreign_keys.forEach(function (foreign_key, idx) {
				if (foreign_key.columns.length === 1) {
					table._column_by_id[foreign_key.columns[0].column_id]._foreign_key = foreign_key;
				}
			});

			// link unique keys to their columns
			table.unique_keys.forEach(function (unique_key, idx) {
				unique_key.columns.forEach(function (column, idx) {
					if (!column.column_id) {
						// this is true for the auto_column_uplink
						return;
					}
					if (!table._column_by_id[column.column_id]._unique_keys) {
						table._column_by_id[column.column_id]._unique_keys = [];
					}
					table._column_by_id[column.column_id]._unique_keys.push(unique_key);
				})
			});
		});

		for (var idx in nested_columns) {
			col = nested_columns[idx];
			schema._table_by_id[col.other_table_id].owned_by._column = col;
			// Add a flag 'in_nested' to each column within the nested field.
			schema._table_by_id[col.other_table_id].columns.forEach((_column) => _column._in_nested = true)
		}

		for (var idx in reverse_nested_columns) {
			col = reverse_nested_columns[idx];
			// column._l10n_key = "schema."+table.name+".column.reverse:"+column.other_table_name_hint;
			var tb = schema._table_by_id[col.other_table_id];

			default_name = table_name_localized(tb.name) + ' / ' + tb._column_by_id[col.other_column_id]._name_localized;
			// console.debug("l10n key", col._l10n_key, default_name);

			// col._l10n_key_old contains the old key before the fix in #51099.
			col._name_localized = ez5.loca.get_user_key_localized(version, col._l10n_key_old);
			if (CUI.util.isEmpty(col._name_localized)) {
				col._name_localized = ez5.loca.get_user_key_localized(version, col._l10n_key, default_name);
			}
		}

		schema._objecttypes.sort(function (a, b) {
			return a._name_localized.localeCompare(b._name_localized);
		});


		// ---------------------------------------------------------------------------------------------------------------//
		// This part removes all invalid reverse-link columns/fields caused by the copy feature of objecttypes (fixed).
		// It checks whether the reverse column is valid or not, if it is not valid the column is removed from the table and
		// all its masks.
		// It only removes them in HEAD version.
		if (version == "HEAD" &&
			(ez5.session.getSystemRight("root") || ez5.session.getSystemRight("datamodel")?.level in ["development", "commit"])) {

			// for reverse_link column cleanup warning
			var warnings = [];

			schema.tables.forEach(function (table) {
				var columnsToRemove = []; // Invalid columns.
				table.columns.forEach(function (column) {
					if (column.kind == "reverse_link" && !column.is_hierarchical) {
						var idOtherTable = column.other_table_id;
						var otherTable = schema._table_by_id[idOtherTable];
						if (!otherTable) {
							return;
						}
						var otherColumn = otherTable._column_by_id[column.other_column_id]
						if (!otherColumn) {
							return
						}
						if (otherColumn.type != "link" || otherColumn._foreign_key.referenced_table.table_id != table.table_id) {
							console.debug("removing column", table, column, otherColumn);

							warnings.push("reverse link column in table **"+table.name+"** linked to **"+column.other_table_name_hint+"."+
							column.other_table_name_hint+"** which points to **"+otherColumn._foreign_key.referenced_table.name_hint+"**");

							columnsToRemove.push(column);
						}
					}
				});

				if (columnsToRemove.length > 0) {
					columnsToRemove.forEach(function(column) {

						var masks = ez5.all_fields_mask[version].masks.concat(ez5.mask[version].masks);
						masks.forEach(function (mask) {
							if (mask.table_id != table.table_id) {
								return;
							}
							CUI.util.removeFromArray(null, mask.fields, function(field){
								return column._other_table_id === field.other_table_id && column._other_column_id === field.other_column_id
							});
						});

						CUI.util.removeFromArray(column, table.columns);
						CUI.util.removeFromArray(column, reverse_nested_columns);
						delete table._column_by_name_localized[column._name_localized];
						delete table._column_by_name[column.name];
						delete table._column_by_id[column.column_id]
					});
				}
			});

			if (warnings.length > 0) {
				schema.__warnings = warnings;
			}
		// -------------------------------------------------------------------------------------------------------------//
		}
	};

	bind.clean_mask_schema = function (mask_schema) {
		function delete_loca_keys(_mask) {
			_mask.fields.forEach(function (field, idx) {
				delete (field._other_table);
				delete (field._column);
				delete (field._user_hint_loca_key);
				delete (field._user_output_hint_loca_key);
				delete (field._user_search_hint_loca_key);
				if (field.mask) {
					delete_loca_keys(field.mask);
				}
			})
		}

		delete (mask_schema._masks_by_table_id);
		delete (mask_schema._mask_by_id);
		delete (mask_schema._mask_instance_by_name);
		delete (mask_schema._mask_by_name);

		for (var mask_idx = 0; mask_idx < mask_schema.masks.length; mask_idx++) {
			var mask = mask_schema.masks[mask_idx];
			delete (mask._version);
			delete (mask._name_loca_key);
			delete (mask._user_hint_loca_key);
			delete (mask._user_output_hint_loca_key);
			delete (mask._user_search_hint_loca_key);
			delete (mask._l10n_prefix);
			delete (mask._name_localized);
			delete_loca_keys(mask);
		}
		;
	};

	bind.addLocaFunctions = function (mask) {
		// TODO: We should refactor this. It is not nice adding functions to the objects like this.
		mask._l10n_prefix = function () {
			if (mask.name) {
				return "mask." + mask.table_id + "." + mask.name + ".";
			} else {
				return "mask." + mask.table_id + "._new_.";
			}
		};

		mask._name_loca_key = function () {
			return mask._l10n_prefix() + "name";
		};

		mask._user_hint_loca_key = function () {
			return mask._l10n_prefix() + "user_hint";
		};

		mask._user_output_hint_loca_key = function () {
			return mask._l10n_prefix() + "user_detail_hint";
		};

		mask._user_search_hint_loca_key = function () {
			return mask._l10n_prefix() + "user_search_hint";
		};
	};

	bind.enrich_mask_schema = function (mask_schema, version, is_all_fields, set_link_preferred) {
		mask_schema._masks_by_table_id = {};
		bind[version]._objecttypes.forEach(function (table, idx) {
			mask_schema._masks_by_table_id[table.table_id] = [];
		});

		if (!is_all_fields) {
			mask_schema._mask_by_id = {}
			mask_schema._mask_by_name = {}
			mask_schema._mask_instance_by_name = {}
		}

		mask_schema.masks.forEach(function (mask, mask_idx) {
			mask._version = version;
			mask._is_all_fields = is_all_fields

			// FIXME: once #29102 is done on the server, this is not needed any more
			if (!mask.system_fields.owner) {
				mask.system_fields.owner = CUI.util.copyObject(mask.system_fields.acl, true);
			}

			bind.addLocaFunctions(mask);

			function set_loca_keys(_mask, mask_stack) {
				if (!mask_stack) {
					mask_stack = [];
				}
				var l10n_prefix_arr = [];
				var l10n_prefix = "";
				var name_arr = [];
				var name_prefix = "";
				mask_stack.forEach(function (mask, idx) {
					l10n_prefix_arr.push("mask_" + mask.table_id);
					name_arr.push(mask.table_name_hint);
				});
				if (l10n_prefix_arr.length > 0) {
					l10n_prefix = l10n_prefix_arr.join(".") + ".";
				}
				var mask_stack_next = mask_stack.slice(0);
				mask_stack_next.push(_mask);

				name_arr.push(_mask.table_name_hint);
				name_prefix = name_arr.join(".");

				var table = bind[version]._table_by_id[_mask.table_id];
				_mask.fields.forEach(function (field, idx) {
					switch (field.kind) {
						case "link": // this is schema kind == "column" and type == "link"
							field._other_table = bind[version]._table_by_id[field.other_table_id];
							if (is_all_fields && set_link_preferred) {
								if (field.mask_id == 'ALL_FIELDS') {
									field.mask_id = 'PREFERRED';
								}
							}
						// no break here, continue to set _column
						case "field":
							field._column = table._column_by_id[field.column_id];
							break;
						case "linked-table": // this is schema kind == "link" / nested table
							field._other_table = bind[version]._table_by_id[field.other_table_id];
							// console.debug("Name localized:", field, field._other_table._name_localized);
							field._name_localized = field._other_table._name_localized;
							field._other_column = field._other_table.owned_by._column;
							break;
						case "reverse-linked-table": // this is schema kind == "link"
							if (field.is_hierarchical) {
								field._name_localized = table._name_localized;
								// Since this field has no column id, we need to find to set the correct localized name (if set)
								for (var _column of table.columns) {
									if (_column._name_localized && _column.is_hierarchical && _column.kind == "reverse_link") {
										field._name_localized = _column._name_localized;
									}
								}
								field._other_table = table;
							} else {
								field._other_table = bind[version]._table_by_id[field.other_table_id];
								var current_table = bind[version]._table_by_id[_mask.table_id];
								var matched_column = null;
								for (var i = 0; i < current_table.columns.length; i++) {
									var c = current_table.columns[i];
									switch (c.kind) {
										case "reverse_link":
											if (c._other_table_id === field.other_table_id &&
												c._other_column_id === field.other_column_id) {

												matched_column = c;
												var other_table = bind[version]._table_by_id[c._other_table_id];
												for (var ii = 0; ii < other_table.columns.length; ii++) {
													var cc = other_table.columns[ii];
													if (cc.column_id == c._other_column_id) {
														matched_column._other_column = cc;
														break;
													}
												}
											}
									}
								}
								if (!matched_column) {
									var txt = "bind.enrich_mask_schema: No matching column for " + field.kind + " found. This is a known problem, pls try to revert datamodel to CURRENT or contact support.";
									CUI.problem({text: txt});
									console.error(txt, "current_table", current_table, "field", field)
									break;
								}
								field._reverse_link_column = matched_column;
								field._name_localized = matched_column._name_localized;
							}
					}

					switch (field.kind) {
						case "field":
						case "link":
							field._user_hint_loca_key = function () {
								return mask._l10n_prefix() + _mask.table_id + "." + l10n_prefix + field.kind + "."
									+ field._column.column_id + ".edit_user_hint";
							};

							field._user_output_hint_loca_key = function () {
								return mask._l10n_prefix() + _mask.table_id + "." + l10n_prefix + field.kind + "."
									+ field._column.column_id + ".output_user_hint";
							};

							field._user_search_hint_loca_key = function () {
								return mask._l10n_prefix() + _mask.table_id + "." + l10n_prefix + field.kind + "."
									+ field._column.column_id + ".search_user_hint";
							}
							break;
						case "linked-table":
							field._user_hint_loca_key = function () {
								return mask._l10n_prefix() + _mask.table_id + l10n_prefix + ".linked-table."
									+ field._other_table.table_id + ".edit_user_hint";
							};

							field._user_output_hint_loca_key = function () {
								return mask._l10n_prefix() + _mask.table_id + l10n_prefix + ".linked-table."
									+ field._other_table.table_id + ".output_user_hint";
							};

							field._user_search_hint_loca_key = function () {
								return mask._l10n_prefix() + _mask.table_id + l10n_prefix + ".linked-table."
									+ field._other_table.table_id + ".search_user_hint";
							};
							set_loca_keys(field.mask, mask_stack_next);
							break;
						case "reverse-linked-table":
							if (field.is_hierarchical) {
								field._user_hint_loca_key = function () {
									return mask._l10n_prefix() + _mask.table_id + l10n_prefix + ".reverse-linked-table."
										+ mask.table_id + ".edit_user_hint";
								}
								field._user_output_hint_loca_key = function () {
									return mask._l10n_prefix() + _mask.table_id + l10n_prefix + ".reverse-linked-table."
										+ mask.table_id + ".output_user_hint";
								}
								field._user_search_hint_loca_key = function () {
									return mask._l10n_prefix() + _mask.table_id + l10n_prefix + ".reverse-linked-table."
										+ mask.table_id + ".search_user_hint";
								}
							} else {
								field._user_hint_loca_key = function () {
									return mask._l10n_prefix() + _mask.table_id + l10n_prefix + ".reverse-linked-table."
										+ field._other_table.table_id + ".edit_user_hint";
								}
								field._user_output_hint_loca_key = function () {
									return mask._l10n_prefix() + _mask.table_id + l10n_prefix + ".reverse-linked-table."
										+ field._other_table.table_id + ".output_user_hint";
								}
								field._user_search_hint_loca_key = function () {
									return mask._l10n_prefix() + _mask.table_id + l10n_prefix + ".reverse-linked-table."
										+ field._other_table.table_id + ".search_user_hint";
								}
							}
							if (field.mask) {
								set_loca_keys(field.mask, mask_stack_next);
							}
							break;
					}

					if (field.column_name_hint) {
						field._full_name = name_prefix + "." + field.column_name_hint;
					} else if (field._other_table) {
						field._full_name = name_prefix + "." + field._other_table.name;
					} else {
						// skip, this can be a "splitter"
					}

				});
				// FIXME: remove system columns
				for (var i = 0; i < _mask.fields.length; i++) {
					if (_mask.fields[i]._column && _mask.fields[i]._column._system_type) {
						// console.debug ("MASK:"+_mask.name+" DISCARDING FIELD: "+_mask.fields[i]._column.name+"["+_mask.fields[i]._column._system_type+"]");
						_mask.fields.splice(i, 1);
						i--;
					}
				}

			};

			mask._version = version;

			if (mask.name == "_all_fields") {
				mask._name_localized = $$("base.all_fields_mask");
			} else {
				mask._name_localized = ez5.loca.get_user_key_localized(version, "mask." + mask.table_id + "." + mask.name + ".name", mask.name);
			}

			if (!is_all_fields) {
				mask_schema._mask_by_id[mask.mask_id] = mask;
				mask_schema._mask_by_name[mask.name] = mask;
			}

			if (mask_schema._masks_by_table_id[mask.table_id]) {
				mask_schema._masks_by_table_id[mask.table_id].push(mask);
			} else {
				console.error("Schema problem: Mask says it belongs to table " + mask.table_id + " which doesn't exist in schema.", mask)
			}

			set_loca_keys(mask);
		});
	}
}

ez5.schema = {}
ez5.bind_schema_funcs(ez5.schema);

ez5.schema_inst = new Schema()

ez5.schema.load_schema = function () {
	return ez5.schema_inst.load(ez5.session.getXEasydb());
}
// Generated by CoffeeScript 1.12.7
var SystemListManagerItem,
  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;

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

  function SystemListManagerItem() {
    this.moveNodeConfirm = bind(this.moveNodeConfirm, this);
    this.moveNodeBack = bind(this.moveNodeBack, this);
    this.moveNodeAfter = bind(this.moveNodeAfter, this);
    this.moveNodeBefore = bind(this.moveNodeBefore, this);
    this.allowRowMove = bind(this.allowRowMove, this);
    this._save = bind(this._save, this);
    this.save = bind(this.save, this);
    this._loadData = bind(this._loadData, this);
    this.get = bind(this.get, this);
    return SystemListManagerItem.__super__.constructor.apply(this, arguments);
  }

  SystemListManagerItem.prototype.initOpts = function() {
    SystemListManagerItem.__super__.initOpts.call(this);
    return this.addOpts({
      manager: {
        check: this.managerInstance()
      }
    });
  };

  SystemListManagerItem.prototype.readOpts = function() {
    SystemListManagerItem.__super__.readOpts.call(this);
    if (this._manager) {
      return this.manager = this._manager;
    }
  };

  SystemListManagerItem.prototype.setFather = function(father) {
    return SystemListManagerItem.__super__.setFather.call(this, father);
  };

  SystemListManagerItem.prototype.newText = function() {
    return $$(this.newKey);
  };

  SystemListManagerItem.prototype.managerInstance = function() {
    return SystemListManager;
  };

  SystemListManagerItem.prototype.newKey = "undefined.newKey";

  SystemListManagerItem.prototype.isDataIncomplete = function() {
    return null;
  };

  SystemListManagerItem.prototype.renderContent = function() {
    if (this.getId()) {
      return new CUI.Label({
        multiline: true,
        content: this.getContent()
      });
    } else {
      return new CUI.EmptyLabel({
        multiline: true,
        text: this.newText()
      });
    }
  };

  SystemListManagerItem.prototype.get = function(key, html) {
    var data;
    if (html == null) {
      html = false;
    }
    data = this.data[this.data._basetype];
    if (CUI.util.isPlainObject(data[key])) {
      return ez5.loca.getBestFrontendValue(data[key], html);
    }
    if (data[key + ":highlight"] && html) {
      return data[key + ":highlight"];
    } else if (data[key]) {
      if (html) {
        return CUI.util.toHtml(data[key]);
      } else {
        return data[key];
      }
    } else {
      return null;
    }
  };

  SystemListManagerItem.prototype.getApi = function() {
    return CUI.util.assert(false, (CUI.util.getObjectClass(this)) + ".getApi needs to be implemented");
  };

  SystemListManagerItem.prototype.getEndpoint = function() {
    return "/" + this.getId();
  };

  SystemListManagerItem.prototype.load = function(ignore_400) {
    var dfr;
    if (ignore_400 == null) {
      ignore_400 = false;
    }
    dfr = new CUI.Deferred();
    if (this.getId()) {
      ez5.api[this.getApi()]({
        api: this.getEndpoint(),
        handle_error: (function(_this) {
          return function(xhr) {
            if ((xhr.status === 400 || xhr.status === 403) && ignore_400) {
              return true;
            }
            return false;
          };
        })(this)
      }).done((function(_this) {
        return function(data) {
          _this._loadData(data);
          return dfr.resolve(data);
        };
      })(this)).fail(function() {
        return dfr.reject();
      });
    } else {
      dfr.resolve();
    }
    dfr.done((function(_this) {
      return function() {
        return dfr.done(function() {
          return _this.update();
        });
      };
    })(this));
    return dfr.promise();
  };

  SystemListManagerItem.prototype.remove = function() {
    return SystemListManagerItem.__super__.remove.call(this).done((function(_this) {
      return function() {
        return _this.manager.setStatus();
      };
    })(this));
  };

  SystemListManagerItem.prototype._loadData = function(data) {
    return this.loadData(data[0]);
  };

  SystemListManagerItem.prototype.loadData = function(data1) {
    this.data = data1;
    this.__origData = CUI.util.copyObject(this.data, true);
    this.id = this.data[this.data._basetype]._id;
    return this;
  };

  SystemListManagerItem.prototype.getData = function() {
    return this.data;
  };

  SystemListManagerItem.prototype.getDeleteConfirmLocaKey = function() {
    if (!this.getId()) {
      return "system.list.manager.item.delete_confirm_new";
    } else {
      return "system.list.manager.item.delete_confirm";
    }
  };

  SystemListManagerItem.prototype.getDeleteConfirmOpts = function() {
    var opts;
    opts = {
      text: $$(this.getDeleteConfirmLocaKey()),
      button_primary: "cancel"
    };
    return opts;
  };

  SystemListManagerItem.prototype["delete"] = function() {
    var e;
    if (!this.getId()) {
      try {
        if (!this.hasChanges()) {
          return this.remove();
        }
      } catch (error) {
        e = error;
        if (!(e instanceof InvalidSaveDataException)) {
          throw e;
        }
      }
    }
    return CUI.confirm(this.getDeleteConfirmOpts()).done((function(_this) {
      return function() {
        if (!_this.getId()) {
          return _this.remove();
        }
        return _this.deleteOnServer().done(function() {
          return _this.remove();
        });
      };
    })(this));
  };

  SystemListManagerItem.prototype.deleteOnServer = function() {
    return ez5.api[this.getApi()]({
      api: this.getEndpoint(),
      type: "DELETE"
    });
  };

  SystemListManagerItem.prototype.getTabs = function() {
    return CUI.util.assert(false, this.__cls + ".getTabs", "Needs implementation.");
  };

  SystemListManagerItem.prototype.isWritable = function() {
    return false;
  };

  SystemListManagerItem.prototype.isDeletable = function() {
    return false;
  };

  SystemListManagerItem.prototype.canBeCopied = function() {
    return false;
  };

  SystemListManagerItem.prototype.getPaneContent = function() {
    var buttons;
    buttons = [
      this.getCancelButton(), this.canBeCopied() ? this.copyButton = new LocaButton({
        loca_key: "system.list.manager.item.button.copy",
        secondary: true,
        text: $$("base.copy"),
        onClick: (function(_this) {
          return function(ev) {
            var new_node;
            if (ev.hasModifierKey()) {
              new_node = _this.copyAsNew();
              console.debug(CUI.util.getObjectClass(_this), "node:", _this, "copied node:", new_node);
              return;
            }
            return _this.check_deselect(ev).done(function() {
              new_node = _this.copyAsNew();
              return _this.getFather().addChild(new_node).done(function() {
                return new_node.select().fail(function() {
                  return new_node["delete"]();
                });
              }).fail(function() {
                return new_node["delete"]();
              });
            });
          };
        })(this)
      }) : void 0, this.isWritable() ? this.saveButton = new LocaButton({
        ui: "system-list-manager-item-save-button",
        disabled: true,
        loca_key: "system.list.manager.item.button.save",
        primary: true,
        text: $$("base.save"),
        onClick: (function(_this) {
          return function(ev) {
            return _this.save(ev);
          };
        })(this)
      }) : void 0
    ];
    buttons.unshift.apply(buttons, this.getExtraButtons());
    this.__tabs = new CUI.Tabs({
      "class": "ez5-system-list-manager-item-tabs",
      maximize: true,
      absolute: true,
      padded: true,
      active_idx: this.getActiveTabIdx(),
      tabs: this.getTabs(),
      footer_right: buttons,
      onActivate: (function(_this) {
        return function(tabs, tab) {
          var idx;
          if (_this.manager) {
            idx = CUI.dom.getAttribute(tabs.DOM, "active-tab-idx") || 0;
            return _this.manager.__active_tab_idx = parseInt(idx);
          }
        };
      })(this),
      footer_left: (function(_this) {
        return function() {
          var ref;
          if (ez5.session.isDebug()) {
            return AclRight.getDisplayForGeneratedRights("pool", (ref = _this.data) != null ? ref._generated_rights : void 0);
          }
        };
      })(this)
    });
    return this.__tabs;
  };

  SystemListManagerItem.prototype.getActiveTabIdx = function() {
    var ref;
    return ((ref = this.manager) != null ? ref.__active_tab_idx : void 0) || 0;
  };

  SystemListManagerItem.prototype.getId = function() {
    return this.id;
  };

  SystemListManagerItem.prototype.getCancelButton = function() {
    return new LocaButton({
      text: $$("base.cancel"),
      ui: "system-list-manager-item-cancel-button",
      loca_key: "system.list.manager.item.button.cancel",
      secondary: true,
      onClick: (function(_this) {
        return function(ev) {
          _this.deselect(ev).done(function() {
            if (!_this.getId()) {
              return _this.remove();
            }
          });
        };
      })(this)
    });
  };

  SystemListManagerItem.prototype.getExtraButtons = function() {
    return [];
  };

  SystemListManagerItem.prototype.show = function() {
    var cnt, pane;
    cnt = this.manager.getContainer();
    pane = this.getEditorPane();
    CUI.dom.replace(cnt, pane);
    this.registerDataChangedListener(pane.DOM);
    return this;
  };

  SystemListManagerItem.prototype.getEditorPane = function() {
    var ref, title;
    title = (ref = this.manager) != null ? ref.getCenterTitle() : void 0;
    return new CUI.SimplePane({
      "class": title ? "cui-pane--window" : void 0,
      title: title,
      content: this.getPaneContent()
    });
  };

  SystemListManagerItem.prototype.getInitialData = function() {
    return this.getSaveData();
  };

  SystemListManagerItem.prototype.hasChanges = function() {
    if (!this.initialData) {
      return false;
    }
    if (CUI.util.isEqual(this.initialData, this.getSaveData())) {
      return false;
    } else {
      return true;
    }
  };

  SystemListManagerItem.prototype.registerDataChangedListener = function(div) {
    var e;
    try {
      this.initialData = this.getInitialData();
    } catch (error) {
      e = error;
      this.initialData = "__invalid__";
      if (!(e instanceof InvalidSaveDataException)) {
        throw e;
      }
    }
    CUI.Events.listen({
      type: ["data-changed", "editor-changed", "editor-update-asset-browser"],
      node: div,
      call: (function(_this) {
        return function(ev, info) {
          return _this.setStatus();
        };
      })(this)
    });
    return div;
  };

  SystemListManagerItem.prototype.setStatus = function() {
    var e, ref, ref1, ref2, ref3, ref4, ref5, ref6;
    try {
      if (this.hasChanges()) {
        if ((ref = this.saveButton) != null) {
          ref.enable();
        }
        if ((ref1 = this.copyButton) != null) {
          ref1.disable();
        }
      } else {
        if ((ref2 = this.saveButton) != null) {
          ref2.disable();
        }
        if ((ref3 = this.copyButton) != null) {
          ref3.enable();
        }
      }
    } catch (error) {
      e = error;
      if (e instanceof InvalidSaveDataException) {
        if ((ref4 = this.saveButton) != null) {
          ref4.disable();
        }
        if ((ref5 = this.copyButton) != null) {
          ref5.disable();
        }
      } else {
        throw e;
      }
    }
    if ((ref6 = this.manager) != null) {
      ref6.setStatus();
    }
    return this;
  };

  SystemListManagerItem.prototype.resetDataChangedListener = function(div) {
    var ref;
    this.initialData = this.getSaveData();
    return (ref = this.saveButton) != null ? ref.disable() : void 0;
  };

  SystemListManagerItem.prototype.getUnsavedChangesMsg = function() {
    return $$("general.frontend.unsaved_changes.message");
  };

  SystemListManagerItem.prototype.getUnsavedChangesOkText = function() {
    return $$("general.frontend.unsaved_changes.confirm");
  };

  SystemListManagerItem.prototype.check_deselect = function() {
    var allow, e;
    allow = true;
    try {
      if (this.hasChanges()) {
        allow = false;
      }
    } catch (error) {
      e = error;
      if (e instanceof InvalidSaveDataException) {
        allow = false;
      } else {
        throw e;
      }
    }
    if (!allow) {
      return CUI.confirm({
        text: this.getUnsavedChangesMsg(),
        button_text_ok: this.getUnsavedChangesOkText(),
        button_primary: "cancel"
      });
    } else {
      return CUI.resolvedPromise();
    }
  };

  SystemListManagerItem.prototype.select = function(ev) {
    var dfr, wb;
    if (ev != null) {
      ev.stopPropagation();
    }
    wb = this.getTree().____waitBlock = new CUI.WaitBlock({
      element: this.manager.getContainer()
    });
    wb.show();
    dfr = new CUI.Deferred();
    dfr.fail((function(_this) {
      return function() {
        return _this.moveNodeBack();
      };
    })(this));
    dfr.always((function(_this) {
      return function() {
        delete (_this.getTree().____waitBlock);
        wb.destroy();
        return wb = null;
      };
    })(this));
    SystemListManagerItem.__super__.select.call(this, ev).done((function(_this) {
      return function() {
        return _this.load().done(function() {
          var ref, ret;
          if ((ref = _this.manager) != null) {
            ref.__active_tab_idx = null;
          }
          if (!_this.isSelected()) {
            dfr.reject();
            return;
          }
          ret = _this.show();
          _this.setStatus();
          if (CUI.util.isPromise(ret)) {
            return ret.done(dfr.resolve).fail(dfr.reject);
          } else {
            return dfr.resolve();
          }
        }).fail(function() {
          _this.deselect();
          return dfr.reject();
        });
      };
    })(this)).fail(function() {
      return dfr.reject();
    });
    return dfr.promise();
  };

  SystemListManagerItem.prototype.revertData = function() {
    if (!this.__origData) {
      return;
    }
    this.loadData(this.__origData);
    this.update();
  };

  SystemListManagerItem.prototype.deselect = function(ev) {
    return SystemListManagerItem.__super__.deselect.call(this, ev).done((function(_this) {
      return function() {
        _this.revertData();
        _this.manager.setStatus();
        if (!_this.getTree().____waitBlock) {
          _this.manager.empty();
        }
        delete _this.saveButton;
        return delete _this.copyButton;
      };
    })(this));
  };

  SystemListManagerItem.prototype.getSaveData = function() {
    return CUI.util.assert(false, (CUI.util.getObjectClass(this)) + ".getSaveData needs to be implemented");
  };

  SystemListManagerItem.prototype.save = function(ev) {
    var ref, save_data;
    if ((ref = this.saveButton) != null) {
      ref.disable();
    }
    save_data = this.getSaveData();
    ez5.splash.show('system.list.manager.item.saving');
    return this._save(ev, save_data).done((function(_this) {
      return function(data) {
        _this.moveNodeConfirm();
        _this._loadData(data);
        return _this.load().done(function() {
          _this.show();
          _this.onSave();
          return ez5.splash.done('system.list.manager.item.saved');
        }).fail(function() {
          return ez5.splash.hide();
        });
      };
    })(this)).fail((function(_this) {
      return function() {
        var ref1;
        if ((ref1 = _this.saveButton) != null) {
          ref1.enable();
        }
        return ez5.splash.hide();
      };
    })(this));
  };

  SystemListManagerItem.prototype._save = function(ev, save_data) {
    if (this.getId()) {
      save_data[save_data._basetype]._version = this.data[this.data._basetype]._version + 1;
    } else {
      save_data[save_data._basetype]._version = 1;
    }
    if (ev != null ? ev.hasModifierKey() : void 0) {
      console.debug(CUI.util.getObjectClass(this), CUI.util.dump(save_data));
      return new CUI.rejectedPromise();
    }
    return ez5.api[this.getApi()]({
      type: this.getId() ? "POST" : "PUT",
      json_data: [save_data]
    });
  };

  SystemListManagerItem.prototype.onSave = function() {};

  SystemListManagerItem.prototype.isMovable = function() {
    return false;
  };

  SystemListManagerItem.prototype.allowRowMove = function(to_node, new_father, after) {
    if (new_father) {
      return true;
    } else {
      return false;
    }
  };

  SystemListManagerItem.prototype.moveNodeBefore = function(to_node, new_father, after) {
    var p;
    p = SystemListManagerItem.__super__.moveNodeBefore.call(this);
    if (!this.origFather) {
      this.origFather = {
        father: this.father,
        childIdx: this.getChildIdx()
      };
    }
    return p;
  };

  SystemListManagerItem.prototype.moveNodeAfter = function(to_node, new_father, after) {
    return this.hasMoved = true;
  };

  SystemListManagerItem.prototype.moveNodeBack = function() {
    if (this.hasMoved) {
      this.moveToNewFather(this.origFather.father, this.origFather.childIdx);
      delete this.hasMoved;
      delete this.origFather;
    }
    return this;
  };

  SystemListManagerItem.prototype.moveNodeConfirm = function() {
    delete this.hasMoved;
    return delete this.origFather;
  };

  SystemListManagerItem.prototype.getGroupsTab = function(type_prefixes, user) {
    return {
      ui: "system-list-manager-item-tab",
      name: "groups",
      text: $$("admin.system-list.tab.groups"),
      content: (function(_this) {
        return function() {
          return new CUI.Form({
            data: _this.data,
            fields: Group.getGroupFields(type_prefixes, user)
          }).start();
        };
      })(this)
    };
  };

  SystemListManagerItem.prototype.loadGroups = function() {
    var grp, i, len, ref;
    this.data.__group_ids = [];
    if (!this.data._groups) {
      return;
    }
    ref = this.data._groups;
    for (i = 0, len = ref.length; i < len; i++) {
      grp = ref[i];
      if (grp._automatic_auth) {
        continue;
      }
      this.data.__group_ids.push(grp.group._id);
    }
    return this.data.__group_ids;
  };

  SystemListManagerItem.prototype.getGroupsSaveData = function() {
    var _groups, group_id, grp, i, j, len, len1, ref, ref1;
    _groups = [];
    ref = this.data.__group_ids;
    for (i = 0, len = ref.length; i < len; i++) {
      group_id = ref[i];
      _groups.push({
        _basetype: "group",
        group: {
          _id: group_id
        }
      });
    }
    ref1 = this.data._groups || [];
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      grp = ref1[j];
      if (!grp._automatic_auth) {
        continue;
      }
      _groups.push({
        _basetype: "group",
        _automatic_auth: grp._automatic_auth,
        group: {
          _id: grp.group._id
        }
      });
    }
    return _groups;
  };

  return SystemListManagerItem;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var SystemListManagerHierarchyItem,
  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;

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

  function SystemListManagerHierarchyItem() {
    this.moveNodeAfter = bind(this.moveNodeAfter, this);
    return SystemListManagerHierarchyItem.__super__.constructor.apply(this, arguments);
  }

  SystemListManagerHierarchyItem.prototype.moveNodeAfter = function(to_node, new_father, after) {
    var pId;
    pId = new_father.id;
    this.data[this.data._basetype]._id_parent = pId;
    return this.hasMoved = true;
  };

  SystemListManagerHierarchyItem.prototype.isMovable = function() {
    return this.selected;
  };

  SystemListManagerHierarchyItem.prototype.isCreateChildAllowed = function() {
    return false;
  };

  return SystemListManagerHierarchyItem;

})(SystemListManagerItem);
// Generated by CoffeeScript 1.12.7
var SplashLayer,
  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;

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

  function SplashLayer(opts) {
    var lr, sl;
    this.opts = opts != null ? opts : {};
    SplashLayer.__super__.constructor.call(this, this.opts);
    sl = new CUI.Template({
      name: "splash-layer"
    });
    lr = this.getLayerRoot();
    lr.addClass("ez5-splash-layer");
    this.__lbl = new CUI.Label({
      "class": "ez5-splash-layer-server",
      text: ""
    });
    lr.append(this.__lbl);
    this.append(sl);
  }

  SplashLayer.prototype.update = function() {
    var hostname, ref, solution;
    if (window.easydb_server_url) {
      hostname = CUI.parseLocation(window.easydb_server_url).hostname;
    } else {
      hostname = document.location.hostname;
    }
    solution = (ref = ez5.session.getInstance()) != null ? ref.solution : void 0;
    if (solution) {
      this.__lbl.setText(hostname + ' / ' + solution);
    } else {
      this.__lbl.setText(hostname);
    }
    return this;
  };

  SplashLayer.prototype.readOpts = function() {
    this.opts.backdrop = {
      policy: "modal",
      add_bounce_class: false
    };
    this.opts.placement = "c";
    return SplashLayer.__super__.readOpts.call(this);
  };

  SplashLayer.prototype.disappear = function() {
    CUI.Events.wait({
      type: "transitionend",
      maxWait: 3000,
      node: this.getLayerRoot()
    }).always((function(_this) {
      return function() {
        _this.getLayerRoot().removeClass("ez5-splash-layer-disappear");
        return _this.hide();
      };
    })(this));
    return this.getLayerRoot().addClass("ez5-splash-layer-disappear");
  };

  return SplashLayer;

})(CUI.Layer);
// Generated by CoffeeScript 1.12.7
var AdminMessage,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function AdminMessage() {
    this.renderContent = bind(this.renderContent, this);
    return AdminMessage.__super__.constructor.apply(this, arguments);
  }

  AdminMessage.prototype.initOpts = function() {
    AdminMessage.__super__.initOpts.call(this);
    return this.addOpts({
      message: {
        mandatory: true,
        "default": {
          _groups: [],
          message: {}
        },
        check: "PlainObject"
      },
      remoteEasydb: {
        check: function(v) {
          if (!RemoteEasydb) {
            return;
          }
          return v instanceof RemoteEasydb;
        }
      },
      manager: {
        check: AdminMessagesManager
      }
    });
  };

  AdminMessage.prototype.readOpts = function() {
    AdminMessage.__super__.readOpts.call(this);
    if (this._manager) {
      this.manager = this._manager;
    }
    return this.setData(this._message);
  };

  AdminMessage.prototype.getStringifiedMessage = function() {
    return JSON.stringify(this._message);
  };

  AdminMessage.prototype.newKey = "admin.msg.list.title.new";

  AdminMessage.prototype.getId = function() {
    return this.id;
  };

  AdminMessage.prototype.setData = function(data1) {
    var client, i, ids, len, msg, ref, ref1, ref2;
    this.data = data1;
    this.data._basetype = "message";
    msg = this.data[this.data._basetype];
    this.sanitizeMessageData(msg);
    msg.start_time = (ref = msg.start_time) != null ? ref.value : void 0;
    msg.end_time = (ref1 = msg.end_time) != null ? ref1.value : void 0;
    if (!this.data.message.webfrontend_props) {
      this.data.message.webfrontend_props = {};
    }
    this.data.message.icon = this.data.message.webfrontend_props.icon || "";
    this.data.message.pools = this.data.message.webfrontend_props.pools || {};
    this.id = msg._id;
    if (this.data.message.client_ids && this.data.message.client_ids.length > 0) {
      ids = [];
      ref2 = this.data.message.client_ids;
      for (i = 0, len = ref2.length; i < len; i++) {
        client = ref2[i];
        ids.push({
          id: client
        });
      }
      this.data.message.client_ids = ids;
    }
    return this.data;
  };

  AdminMessage.prototype.sanitizeMessageData = function(msg) {
    var k, ref, v;
    ref = msg.message;
    for (k in ref) {
      v = ref[k];
      if (CUI.util.isString(v)) {
        msg.message[k] = this.sanitizeHtml(v);
      }
    }
  };

  AdminMessage.prototype.sanitizeHtml = function(html) {
    if (!html) {
      return html;
    }
    html = html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "");
    html = html.replace(/\s+on\w+\s*=\s*["'][^"']*["']/gi, "");
    html = html.replace(/\s+on\w+\s*=\s*[^\s>]+/gi, "");
    html = html.replace(/href\s*=\s*["']javascript:[^"']*["']/gi, 'href=""');
    html = html.replace(/src\s*=\s*["']javascript:[^"']*["']/gi, 'src=""');
    return html;
  };

  AdminMessage.prototype.getStartDate = function() {
    var ref, ref1, start_time;
    start_time = (ref = this.data) != null ? (ref1 = ref.message) != null ? ref1.start_time : void 0 : void 0;
    if (start_time) {
      return new Date(start_time);
    } else {
      return null;
    }
  };

  AdminMessage.prototype.loadData = function(data) {
    AdminMessage.__super__.loadData.call(this, data);
    this.setData(data);
    return this.loadGroups();
  };

  AdminMessage.prototype.getContent = function() {
    return this.get("title", true);
  };

  AdminMessage.prototype.getApi = function() {
    return "message";
  };

  AdminMessage.prototype.getWebfrontendType = function() {
    return this.data.message.webfrontend_type;
  };

  AdminMessage.prototype.getWebfrontendProps = function() {
    return this.data.message.webfrontend_props;
  };

  AdminMessage.prototype.getTitleLocalized = function() {
    return ez5.loca.getBestFrontendValue(this.data.message.title) || "";
  };

  AdminMessage.prototype.getLabel = function() {
    return this.data.message.title;
  };

  AdminMessage.prototype.getMessageLocalized = function() {
    return ez5.loca.getBestFrontendValue(this.data.message.message);
  };

  AdminMessage.prototype.getConfirmationLocalized = function() {
    return ez5.loca.getBestFrontendValue(this.data.message.confirmation);
  };

  AdminMessage.prototype.getTagfilter = function() {
    return this.data.message.webfrontend_props.tagfilter;
  };

  AdminMessage.prototype.getPools = function() {
    return this.data.message.webfrontend_props.pools;
  };

  AdminMessage.prototype.renderContent = function() {
    var type;
    if (!this.id) {
      this.addColumn(new CUI.ListViewColumnEmpty());
    } else {
      if (this.getWebfrontendType()) {
        type = $$("admin.message.webfrontend_type." + this.getWebfrontendType());
      } else {
        type = $$("admin.message.system_message");
      }
      this.addColumn(new CUI.ListViewColumn({
        element: new CUI.Label({
          text: type
        })
      }));
    }
    return AdminMessage.__super__.renderContent.call(this);
  };

  AdminMessage.prototype.isWritable = function() {
    return true;
  };

  AdminMessage.prototype.isDeletable = function() {
    return true;
  };

  AdminMessage.prototype.getSaveData = function() {
    var i, info, k, len, msg, props, ref, save_data;
    msg = this.data.message;
    if (!this.__isDataValid(msg)) {
      throw new InvalidSaveDataException();
    }
    props = CUI.util.copyObject(msg.webfrontend_props, true);
    props.icon = msg.icon;
    props.pools = msg.pools;
    if (msg.webfrontend_type) {
      info = ez5.defaults["class"].AdminMessage.getWebfrontendType(msg.webfrontend_type);
      if (!(info != null ? info.tagfilter : void 0)) {
        delete props.tagfilter;
      }
    } else {
      delete props.tagfilter;
    }
    save_data = {
      _basetype: "message",
      message: {
        _id: this.id,
        webfrontend_props: props,
        webfrontend_type: msg.webfrontend_type,
        confirm_every_version: !!msg.confirm_every_version,
        show_always: !!msg.show_always,
        title: msg.title,
        reference: msg.reference || null,
        message: msg.message,
        confirmation: msg.confirmation
      }
    };
    ref = ["start_time", "end_time"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      if (msg[k] || ez5.version("6")) {
        save_data.message[k] = {
          value: msg[k]
        };
      } else {
        save_data.message[k] = null;
      }
    }
    if (ez5.version("6") && msg.client_ids && msg.client_ids.length > 0) {
      save_data.message.client_ids = msg.client_ids.map((function(_this) {
        return function(client) {
          return client.id;
        };
      })(this)).filter((function(_this) {
        return function(id) {
          return id;
        };
      })(this));
    }
    save_data._groups = this.getGroupsSaveData();
    return save_data;
  };

  AdminMessage.prototype.__isDataValid = function(message) {
    var loca, messageValue, messages, titleValue, titles;
    messages = message.message;
    titles = message.title;
    if (message.start_time && message.end_time) {
      if (message.start_time > message.end_time) {
        return false;
      }
    }
    for (loca in messages) {
      messageValue = messages[loca];
      titleValue = titles[loca];
      if (!CUI.util.isEmpty(messageValue) && !CUI.util.isEmpty(titleValue)) {
        return true;
      }
    }
    return false;
  };

  AdminMessage.prototype.getTabs = function() {
    this.__confirmationTab = this.__getConfirmationTab();
    return [
      {
        name: "general",
        ui: "admin-message-general-tab",
        text: $$("admin.group.tab.general"),
        onFirstActivate: this.update,
        content: (function(_this) {
          return function() {
            _this.__generalForm = new CUI.Form({
              ui: "admin-message-general-tab-content-form",
              fields: _this.getGeneralFields(),
              data: _this.data.message,
              onDataInit: function() {
                return _this.setStatusGeneralForm();
              },
              onDataChanged: function() {
                return _this.update();
              }
            });
            _this.__generalForm.start();
            return _this.__generalForm;
          };
        })(this)
      }, this.__confirmationTab, this.getGroupsTab(["easydb", "system"])
    ];
  };

  AdminMessage.prototype.deselect = function(ev) {
    return AdminMessage.__super__.deselect.call(this, ev).done((function(_this) {
      return function() {
        var ref, ref1, ref2;
        if ((ref = _this.__generalForm) != null) {
          ref.destroy();
        }
        if ((ref1 = _this.__confirmationForm) != null) {
          ref1.destroy();
        }
        if ((ref2 = _this.__tagfilterField) != null) {
          ref2.destroy();
        }
        delete _this.__generalForm;
        delete _this.__confirmationForm;
        return delete _this.__tagfilterField;
      };
    })(this));
  };

  AdminMessage.prototype.update = function() {
    AdminMessage.__super__.update.call(this);
    this.setStatusGeneralForm();
    return this;
  };

  AdminMessage.prototype.setStatusGeneralForm = function() {
    var checkFieldsVisibility, disableFields, hideFields, info, ref, ref1, wt;
    if (!this.__generalForm) {
      return;
    }
    wt = this.__generalForm.getFieldsByName("webfrontend_type")[0].getValue();
    info = ez5.defaults["class"].AdminMessage.getWebfrontendType(wt);
    disableFields = (info != null ? info.disable_fields : void 0) || ["pools"];
    hideFields = (info != null ? info.hide_fields : void 0) || ["confirm_message_hint", "choice_forms", "event_send_confirmation", "event_confirmation_identifier"];
    checkFieldsVisibility = function(form) {
      var field, i, len, ref, ref1, ref2;
      ref = form.getFields();
      for (i = 0, len = ref.length; i < len; i++) {
        field = ref[i];
        if (ref1 = field.getName(), indexOf.call(hideFields, ref1) >= 0) {
          field.hide(true);
          continue;
        } else {
          field.show(true);
        }
        if (ref2 = field.getName(), indexOf.call(disableFields, ref2) >= 0) {
          field.disable();
        } else {
          field.enable();
        }
        if (field instanceof CUI.Form && !(field instanceof CUI.FormPopover)) {
          checkFieldsVisibility(field);
          if (field.getFields().every((function(_this) {
            return function(field) {
              return field.isHidden() || field.isDisabled();
            };
          })(this))) {
            field.hide(true);
          }
        }
      }
    };
    checkFieldsVisibility(this.__generalForm);
    checkFieldsVisibility(this.__confirmationForm);
    if (this.__confirmationForm.getFields().every((function(_this) {
      return function(field) {
        return field.isHidden() || field.isDisabled();
      };
    })(this))) {
      if ((ref = this.__confirmationTab.getButton()) != null) {
        ref.hide();
      }
    } else {
      if ((ref1 = this.__confirmationTab.getButton()) != null) {
        ref1.show();
      }
    }
    if (info != null ? info.tagfilter : void 0) {
      this.__tagfilterField.enable();
    } else {
      this.__tagfilterField.disable();
    }
  };

  AdminMessage.prototype.getExtraButtons = function() {
    return [
      new LocaButton({
        ui: "admin-message-show-preview-button",
        loca_key: "admin.message.show_preview",
        secondary: true,
        onClick: (function(_this) {
          return function() {
            return _this.showMessage(null, true, true);
          };
        })(this)
      })
    ];
  };

  AdminMessage.prototype.showMessage = function(msg, ok_button, preview, info) {
    var ref, title, url;
    if (msg == null) {
      msg = this.getMessageLocalized();
    }
    if (ok_button == null) {
      ok_button = true;
    }
    if (preview == null) {
      preview = false;
    }
    if (info == null) {
      info = {};
    }
    if ((ref = this.getWebfrontendType()) === "permanent_tray" || ref === "permanent") {
      try {
        url = new URL(msg);
        if (!CUI.util.isEmpty(url)) {
          window.open(url, "_blank");
          return;
        }
      } catch (error) {}
    }
    title = this.getTitleLocalized();
    if (this._remoteEasydb) {
      title = this._remoteEasydb.getDisplayname() + ": " + title;
    }
    return ez5.defaults["class"].AdminMessage.showMessageDialog({
      confirm: this.getConfirmationLocalized(),
      title: title,
      message: msg || "",
      webfrontend_type: this.getWebfrontendType(),
      ok_button: ok_button,
      webfrontend_props: this.getWebfrontendProps(),
      preview: preview,
      extra_info: info
    });
  };

  AdminMessage.prototype.getGeneralFields = function() {
    var fields, i, info, len, ref, tf, webfrontend_types;
    webfrontend_types = [
      {
        value: null,
        text: $$("admin.message.system_message")
      }
    ];
    ref = ez5.defaults["class"].AdminMessage.getWebfrontendTypes();
    for (i = 0, len = ref.length; i < len; i++) {
      info = ref[i];
      webfrontend_types.push({
        value: info.type,
        text: $$("admin.message.webfrontend_type." + info.type),
        disabled: info.disabled || false
      });
    }
    tf = new TagFilter({
      tagForm: ez5.tagForm,
      data: this.data.message.webfrontend_props,
      name: "tagfilter"
    });
    this.__tagfilterField = CUI.DataField["new"](tf.getField({
      form: {
        label: $$("admin.msg.form.tagfilter")
      }
    }));
    fields = [
      {
        type: CUI.Select,
        name: "webfrontend_type",
        options: webfrontend_types,
        form: {
          label: $$("admin.msg.form.webfrontend_type"),
          hint: $$("admin.msg.form.type|hint")
        }
      }, {
        type: CUI.DateTime,
        form: {
          label: $$("admin.msg.form.start_time")
        },
        name: "start_time",
        input_types: ["date_time"],
        calendar_locale: ez5.session.getLanguage()
      }, {
        type: CUI.DateTime,
        form: {
          label: $$("admin.msg.form.end_time")
        },
        name: "end_time",
        input_types: ["date_time"],
        calendar_locale: ez5.session.getLanguage()
      }, {
        type: CUI.MultiInput,
        control: ez5.loca.getLanguageControlAdmin(),
        user_selectable: ez5.session.getPref("languages_user_selection"),
        form: {
          label: $$("admin.msg.form.title")
        },
        name: "title"
      }, {
        type: CUI.MultiInput,
        control: ez5.loca.getLanguageControlAdmin(),
        user_selectable: ez5.session.getPref("languages_user_selection"),
        maximize_horizontal: true,
        textarea: true,
        form: {
          label: $$("admin.msg.form.message"),
          hint: $$("admin.msg.form.message|hint")
        },
        name: "message"
      }, {
        type: CUI.IconInput,
        placeholder: $$("admin.message.icon|placeholder"),
        form: {
          label: $$("admin.message.icon|label"),
          hint: $$("admin.message.icon|hint")
        },
        name: "icon"
      }, {
        type: CUI.Input,
        form: {
          label: $$("admin.msg.form.reference")
        },
        name: "reference"
      }, this.__getPoolsForm(), this.__tagfilterField, ez5.version("6") ? {
        type: CUI.DataTable,
        no_header: true,
        name: "client_ids",
        "class": "client-ids-table",
        form: {
          label: $$("admin.msg.form.client_ids")
        },
        fields: [
          {
            form: {
              label: "Client ID"
            },
            type: CUI.Input,
            name: "id"
          }
        ]
      } : void 0, {
        type: CUI.Output,
        form: {
          label: $$("admin.msg.form.deep_link")
        },
        name: "deep_link",
        getValue: function(_, data) {
          var url;
          if (!data._id) {
            return new CUI.Label({
              text: $$("admin.msg.form.deep_link.empty"),
              appearance: "secondary"
            });
          }
          url = document.location.origin + ("/#/messages/" + data._id);
          return new CUI.Label({
            text: url,
            markdown: true
          });
        }
      }
    ];
    if (ez5.version("6")) {
      fields.push({
        type: CUI.Output,
        name: "_created_at",
        data: this.data,
        form: {
          label: $$("admin.msg.form.created_at")
        },
        getValue: (function(_this) {
          return function(v) {
            if (!v) {
              return new CUI.Label({
                text: $$("admin.msg.form.date.empty"),
                appearance: "secondary"
              });
            }
            return ez5.format_date_and_time(v, true);
          };
        })(this)
      }, {
        type: CUI.Output,
        name: "_updated_at",
        data: this.data,
        form: {
          label: $$("admin.msg.form.updated_at")
        },
        getValue: (function(_this) {
          return function(v) {
            if (!v) {
              return new CUI.Label({
                text: $$("admin.msg.form.date.empty"),
                appearance: "secondary"
              });
            }
            return ez5.format_date_and_time(v, true);
          };
        })(this)
      });
    }
    return fields;
  };

  AdminMessage.prototype.__getPoolsForm = function() {
    var buttonText, form, poolsSelected, ref, ref1;
    poolsSelected = ((ref = this.data.message.pools) != null ? (ref1 = ref.ids) != null ? ref1.length : void 0 : void 0) > 0;
    buttonText = poolsSelected ? $$("admin.message.pools.button.selected", {
      count: this.data.message.pools.ids.length
    }) : $$("admin.message.pools.button");
    this.__poolSelectorButton = new CUI.FormButton({
      text: buttonText,
      active: poolsSelected,
      onClick: (function(_this) {
        return function() {
          return _this.__showPoolSelector();
        };
      })(this)
    });
    CUI.Events.listen({
      node: this.__poolSelectorButton,
      type: "data-changed",
      call: (function(_this) {
        return function(ev) {
          var ref2, ref3, text;
          if (((ref2 = _this.data.message.pools) != null ? (ref3 = ref2.ids) != null ? ref3.length : void 0 : void 0)) {
            text = $$("admin.message.pools.button.selected", {
              count: _this.data.message.pools.ids.length
            });
            _this.__poolSelectorButton.activate();
          } else {
            _this.__poolSelectorButton.deactivate();
            text = $$("admin.message.pools.button");
          }
          return _this.__poolSelectorButton.setText(text);
        };
      })(this)
    });
    form = new CUI.Form({
      name: "pools",
      data: this.data.message,
      form: {
        label: "Pools"
      },
      fields: [this.__poolSelectorButton]
    });
    return form;
  };

  AdminMessage.prototype.__showPoolSelector = function(onClose) {
    var cancelButton, doneButton, poolFormModal, temporalData;
    temporalData = CUI.util.copyObject(this.data.message.pools, true);
    this.__pools_form = new PoolsForm({
      data: temporalData,
      treeOpts: {
        "class": 'cui-lv--has-datafields',
        maximize: false,
        rowMove: false,
        cols: ["auto"]
      }
    });
    doneButton = new CUI.Button({
      text: $$("base.done"),
      primary: true,
      onClick: (function(_this) {
        return function(ev) {
          _this.data.message.pools = _this.__pools_form.getSaveData();
          CUI.Events.trigger({
            node: _this.__poolSelectorButton,
            type: "data-changed",
            info: {
              element: _this.__poolSelectorButton
            }
          });
          return poolFormModal.destroy();
        };
      })(this)
    });
    cancelButton = new CUI.Button({
      text: $$("base.abort"),
      onClick: (function(_this) {
        return function(ev) {
          return poolFormModal.destroy();
        };
      })(this)
    });
    poolFormModal = new CUI.Modal({
      "class": "cui-pools-form",
      cancel: true,
      pane: {
        header_left: new CUI.Label({
          text: $$("admin.message.pools.pools_form.title")
        }),
        content: this.__pools_form.renderForm(),
        footer_right: [cancelButton, doneButton]
      },
      onDestroy: (function(_this) {
        return function() {
          if (typeof onClose === "function") {
            onClose();
          }
        };
      })(this)
    });
    return poolFormModal.show();
  };

  AdminMessage.prototype.__getConfirmationTab = function() {
    var tab;
    this.__confirmationForm = new CUI.Form({
      name: "confirmation",
      onDataChanged: (function(_this) {
        return function() {
          return _this.update();
        };
      })(this),
      fields: [
        {
          type: CUI.Form,
          form: {
            label: $$("admin.msg.form.confirmation.title")
          },
          render_as_block: true,
          maximize_horizontal: true,
          fields: [
            {
              type: CUI.Checkbox,
              data: this.data.message,
              name: "confirm_every_version",
              form: {
                label: $$("admin.msg.form.confirm_every_version")
              }
            }, ez5.version("6") ? {
              type: CUI.Checkbox,
              data: this.data.message,
              name: "show_always",
              form: {
                label: $$("admin.msg.form.show_always")
              }
            } : void 0, {
              type: CUI.MultiInput,
              data: this.data.message,
              control: ez5.loca.getLanguageControlAdmin(),
              user_selectable: ez5.session.getPref("languages_user_selection"),
              name: "confirmation",
              form: {
                label: $$("admin.msg.form.confirmation")
              }
            }, {
              type: CUI.MultiInput,
              control: ez5.loca.getLanguageControlAdmin(),
              user_selectable: ez5.session.getPref("languages_user_selection"),
              maximize_horizontal: true,
              form: {
                label: $$("admin.msg.form.confirm-message-hint"),
                hint: $$("admin.msg.form.confirm-message-hint|hint")
              },
              name: "confirm_message_hint",
              data: this.data.message.webfrontend_props
            }
          ]
        }, this.__getChoicesForm(), {
          type: CUI.Form,
          form: {
            label: $$("admin.msg.form.event.title")
          },
          render_as_block: true,
          maximize_horizontal: true,
          fields: [
            {
              type: CUI.Checkbox,
              name: "event_send_confirmation",
              form: {
                label: $$("admin.msg.form.event.send-confirmation")
              },
              data: this.data.message.webfrontend_props
            }, {
              type: CUI.Input,
              form: {
                label: $$("admin.msg.form.event.confirmation-identifier")
              },
              name: "event_confirmation_identifier",
              data: this.data.message.webfrontend_props
            }
          ]
        }
      ]
    });
    this.__confirmationForm.start();
    tab = new CUI.Tab({
      name: "confirmation_tab",
      text: $$("admin.group.tab.confirmation"),
      content: this.__confirmationForm
    });
    return tab;
  };

  AdminMessage.prototype.__getChoicesForm = function() {
    var form;
    form = {
      type: CUI.Form,
      form: {
        label: $$("admin.msg.form.choices.title")
      },
      render_as_block: true,
      name: "choice_forms",
      data: this.data.message.webfrontend_props,
      fields: [
        {
          type: CUI.MultiInput,
          control: ez5.loca.getLanguageControlAdmin(),
          user_selectable: ez5.session.getPref("languages_user_selection"),
          maximize_horizontal: true,
          textarea: true,
          form: {
            label: $$("admin.msg.form.choice-forms.main-header")
          },
          name: "header"
        }, {
          type: CUI.DataForm,
          form: {
            label: $$("admin.msg.form.choice-forms")
          },
          maximize_horizontal: true,
          rowMove: true,
          has_add_button: true,
          name: "forms",
          fields: [
            {
              type: CUI.MultiInput,
              control: ez5.loca.getLanguageControlAdmin(),
              user_selectable: ez5.session.getPref("languages_user_selection"),
              maximize_horizontal: true,
              textarea: true,
              form: {
                label: $$("admin.msg.form.choice-forms.header")
              },
              name: "header"
            }, {
              type: CUI.Select,
              form: {
                label: $$("admin.msg.form.choice-forms.type")
              },
              name: "type",
              options: [
                {
                  text: $$("admin.msg.form.choice-forms.type.checkbox"),
                  value: "checkbox"
                }, {
                  text: $$("admin.msg.form.choice-forms.type.radio"),
                  value: "radio"
                }
              ]
            }, {
              type: CUI.NumberInput,
              form: {
                label: $$("admin.msg.form.choice-forms.min-checked")
              },
              name: "min_checked",
              store_as_integer: true,
              decimals: 0,
              min: 0,
              onDataInit: function(field, data) {
                if (!CUI.util.isNull(data.min_checked)) {
                  return;
                }
                return field.setValue(0);
              }
            }, {
              type: CUI.NumberInput,
              form: {
                label: $$("admin.msg.form.choice-forms.max-checked")
              },
              name: "max_checked",
              store_as_integer: true,
              decimals: 0,
              min: 0
            }, {
              type: CUI.DataTable,
              "class": "cui-border",
              maximize: true,
              chunk_size: 5,
              name: "choices",
              form: {
                label: $$("admin.msg.form.choice-forms.choices")
              },
              fields: [
                {
                  type: CUI.MultiInput,
                  control: ez5.loca.getLanguageControlAdmin(),
                  user_selectable: ez5.session.getPref("languages_user_selection"),
                  form: {
                    label: $$("admin.msg.form.choice-forms.choices.text"),
                    column: "maximize"
                  },
                  name: "text"
                }, {
                  type: CUI.Input,
                  form: {
                    label: $$("admin.msg.form.choice-forms.choices.reference")
                  },
                  name: "reference"
                }, {
                  type: CUI.Checkbox,
                  form: {
                    label: $$("admin.msg.form.choice-forms.choices.disabled")
                  },
                  name: "disabled"
                }
              ]
            }, {
              type: CUI.MultiInput,
              control: ez5.loca.getLanguageControlAdmin(),
              user_selectable: ez5.session.getPref("languages_user_selection"),
              maximize_horizontal: true,
              textarea: true,
              form: {
                label: $$("admin.msg.form.choice-forms.footer")
              },
              name: "footer"
            }
          ]
        }, {
          type: CUI.MultiInput,
          control: ez5.loca.getLanguageControlAdmin(),
          user_selectable: ez5.session.getPref("languages_user_selection"),
          maximize_horizontal: true,
          textarea: true,
          form: {
            label: $$("admin.msg.form.choice-forms.main-footer"),
            hint: $$("admin.msg.form.choice-forms.main-footer|hint")
          },
          name: "footer"
        }
      ]
    };
    return form;
  };

  AdminMessage.showMessageDialog = function(_opts) {
    var allowCancel, center, changeOkButtonStatus, choiceForms, choiceFormsLayout, choice_forms, cls, confirm, confirmCheckbox, confirmMessageHint, content, dfr, enableButton, icon, info, modal, ok_button, opts, renderChoiceForm, text;
    opts = CUI.Element.readOpts(_opts, "new AdminMessage", {
      confirm: {
        check: String
      },
      message: {
        check: String,
        "default": ""
      },
      title: {
        check: String,
        "default": ""
      },
      webfrontend_type: {
        check: String
      },
      ok_button: {
        "default": true
      },
      webfrontend_props: {
        check: "PlainObject",
        "default": {}
      },
      preview: {
        check: Boolean,
        "default": false
      },
      extra_info: {
        check: "PlainObject",
        "default": {}
      }
    });
    allowCancel = false;
    info = ez5.defaults["class"].AdminMessage.getWebfrontendType(opts.webfrontend_type);
    if (indexOf.call((info != null ? info.disable_fields : void 0) || [], "confirmation") >= 0) {
      confirm = null;
    } else {
      confirm = opts.confirm;
    }
    choiceForms = [];
    changeOkButtonStatus = function() {
      var checkedFields, choiceForm, form, i, len, ref, ref1;
      if (!ok_button) {
        return;
      }
      ok_button.disable();
      CUI.dom.showElement(confirmMessageHint);
      for (i = 0, len = choiceForms.length; i < len; i++) {
        ref = choiceForms[i], choiceForm = ref.choiceForm, form = ref.form;
        if (form.type === "radio") {
          checkedFields = choiceForm.getFields()[0].getData().choice ? 1 : 0;
        } else {
          checkedFields = ((ref1 = choiceForm.getFields()[0].getData().choice) != null ? ref1.length : void 0) || 0;
        }
        if (checkedFields < form.min_checked) {
          return;
        }
        if (!CUI.util.isNull(form.max_checked) && checkedFields > form.max_checked) {
          return;
        }
      }
      if (!confirmCheckbox || confirmCheckbox.isActive()) {
        ok_button.enable();
        CUI.dom.hideElement(confirmMessageHint);
      }
    };
    renderChoiceForm = function(form, formIndex) {
      var choiceForm, data, fields, layout, options;
      data = {};
      options = form.choices.map(function(choice, index) {
        var text;
        text = ez5.loca.getBestFrontendValue(choice.text) || "...";
        return {
          value: choice.reference || (text != null ? text.replace(/ /g, "-") : void 0) || ("checkbox-" + index),
          text: text,
          disabled: choice.disabled
        };
      });
      fields = [
        {
          type: CUI.Options,
          name: "choice",
          title: ez5.loca.getBestFrontendValue(form.header),
          options: options,
          hint: ez5.loca.getBestFrontendValue(form.footer),
          radio: form.type === "radio" ? formIndex.toString() : false,
          horizontal: false
        }
      ];
      if (form.choices.length === 0) {
        choiceForm = CUI.dom.div();
      } else {
        if (!allowCancel) {
          allowCancel = true;
        }
        choiceForm = new CUI.Form({
          data: data,
          fields: fields,
          onDataChanged: function() {
            return changeOkButtonStatus();
          }
        });
        choiceForm.start();
        choiceForms.push({
          choiceForm: choiceForm,
          form: form
        });
      }
      layout = new CUI.VerticalLayout({
        center: {
          content: choiceForm
        }
      });
      return layout;
    };
    if (confirm) {
      confirmCheckbox = new CUI.Checkbox({
        text: confirm,
        multiline: true,
        disabled: true,
        onActivate: function() {
          return changeOkButtonStatus();
        },
        onDeactivate: function() {
          return changeOkButtonStatus();
        }
      }).start();
      allowCancel = true;
    } else {
      confirmCheckbox = null;
      allowCancel = false;
    }
    info = ez5.defaults["class"].AdminMessage.getWebfrontendType(opts.webfrontend_type);
    if (!(info != null ? info.hide_fields : void 0) || indexOf.call(info.hide_fields, "choice_forms") < 0) {
      if (choice_forms = opts.webfrontend_props.choice_forms) {
        choiceFormsLayout = new CUI.VerticalLayout({
          "class": "ez5-confirmation-choice-form",
          top: {
            content: new CUI.Label({
              text: ez5.loca.getBestFrontendValue(choice_forms.header)
            })
          },
          center: {
            content: (function(_this) {
              return function() {
                var div, ref;
                div = CUI.dom.div("ez5-confirmation-choice-groups");
                if ((ref = choice_forms.forms) != null) {
                  ref.forEach(function(form, index) {
                    return CUI.dom.append(div, renderChoiceForm(form, index));
                  });
                }
                return div;
              };
            })(this)
          },
          bottom: {
            content: new CUI.Label({
              text: ez5.loca.getBestFrontendValue(choice_forms.footer),
              markdown: true
            })
          }
        });
      }
    }
    if (opts.webfrontend_props.confirm_message_hint) {
      text = ez5.loca.getBestFrontendValue(opts.webfrontend_props.confirm_message_hint);
      confirmMessageHint = new CUI.Label({
        text: text,
        icon: "warning",
        "class": "cui-label-danger",
        multiline: true
      });
    }
    if (opts.ok_button) {
      ok_button = new CUI.Button({
        text: opts.webfrontend_type !== "self_register" ? $$("base.ok") : $$("admin.message.button.self_register_accept"),
        disabled: !!confirmCheckbox,
        primary: true,
        onClick: function() {
          var choiceForm, choices, data, eventOpts, eventType, i, len, optionsField;
          choices = [];
          for (i = 0, len = choiceForms.length; i < len; i++) {
            choiceForm = choiceForms[i].choiceForm;
            optionsField = choiceForm.getFields()[0];
            data = optionsField.getData();
            if (data && CUI.util.isString(data.choice)) {
              choices.push({
                reference: data.choice,
                text: optionsField.__getOptionByValue(data.choice).text
              });
            } else if (data && CUI.util.isArray(data.choice)) {
              data.choice.forEach(function(value) {
                var option;
                option = optionsField.__getOptionByValue(value);
                return choices.push({
                  reference: option.value,
                  text: option.text
                });
              });
            }
          }
          eventType = AdminMessage.getEventType(opts.webfrontend_type);
          if (opts.webfrontend_props.event_send_confirmation && eventType) {
            info = {
              identifier: opts.webfrontend_props.event_confirmation_identifier,
              choices: choices
            };
            eventOpts = {
              type: eventType,
              basetype: "message",
              info: info
            };
            if (eventType === "ASSET_DOWNLOAD_CONFIRMATION_MESSAGE") {
              eventOpts.info.assets = opts.extra_info.assets;
              eventOpts.info.global_object_ids = opts.extra_info.object_ids;
            }
            EventPoller.saveEvent(eventOpts);
          }
          modal.destroy();
          return dfr.resolve();
        }
      });
      changeOkButtonStatus();
    }
    content = [
      new CUI.Label({
        text: opts.message,
        multiline: true,
        markdown: true
      })
    ];
    if (opts.webfrontend_type !== "self_register") {
      content.push(confirmCheckbox);
    }
    if (choiceFormsLayout) {
      content.push(choiceFormsLayout);
    }
    switch (opts.webfrontend_type) {
      case "download":
        cls = "ez5-admin-message--dialog";
        break;
      case "permanent":
        cls = "ez5-admin-message--page";
        break;
      default:
        cls = "ez5-admin-message--dialog";
    }
    cls = cls + " ez5-admin-message--" + opts.webfrontend_type;
    switch (opts.webfrontend_type) {
      case "maintenance_warning":
      case "maintenance":
        icon = "warning";
        break;
      default:
        if (!CUI.util.isEmpty(opts.webfrontend_props.icon)) {
          icon = opts.webfrontend_props.icon;
        } else {
          icon = "info";
        }
    }
    if (opts.preview) {
      allowCancel = true;
    }
    modal = new CUI.Modal({
      "class": "cui-confirmation-dialog ez5-admin-message " + cls,
      cancel: allowCancel,
      onCancel: function() {
        modal.destroy();
        return dfr.reject();
      },
      pane: {
        header_left: new CUI.Label({
          icon: icon,
          text: opts.title
        }),
        content: new CUI.VerticalList({
          "class": "ez5-admin-message-content",
          content: content
        }),
        footer_right: ok_button,
        footer_left: confirmMessageHint
      }
    }).show();
    if (opts.webfrontend_type === "self_register" || confirmCheckbox) {
      enableButton = (function(_this) {
        return function(div) {
          var dimensions;
          dimensions = CUI.dom.getDimensions(div);
          if ((dimensions.offsetHeight + dimensions.scrollTop) + 10 >= dimensions.scrollHeight) {
            if (opts.webfrontend_type === "self_register") {
              ok_button.enable();
              return CUI.dom.hideElement(confirmMessageHint);
            } else {
              return confirmCheckbox.enable();
            }
          }
        };
      })(this);
      center = modal.getPane().get("center");
      enableButton(center);
      if (!ok_button.isEnabled()) {
        CUI.Events.listen({
          type: "scroll",
          instance: modal,
          node: center,
          call: (function(_this) {
            return function(event) {
              return enableButton(center);
            };
          })(this)
        });
      }
    }
    dfr = new CUI.Deferred();
    return dfr.promise();
  };

  AdminMessage.getEventType = function(type) {
    if (type === "download") {
      return "ASSET_DOWNLOAD_CONFIRMATION_MESSAGE";
    }
    return null;
  };

  AdminMessage.getWebfrontendTypes = function() {
    var fields;
    fields = [
      {
        type: "download",
        disable_fields: ["confirm_every_version", "show_always"],
        hide_fields: [],
        tagfilter: true
      }, {
        type: "self_register",
        disable_fields: ["confirm_every_version", "show_always", "pools"],
        hide_fields: ["confirm_every_version", "show_always", "confirm_message_hint", "choice_forms", "event_send_confirmation", "event_confirmation_identifier", "client_ids"],
        tagfilter: false
      }, {
        type: "search_welcome",
        disable_fields: ["confirmation", "confirm_every_version", "show_always", "icon", "pools"],
        hide_fields: ["confirm_message_hint", "choice_forms", "event_send_confirmation", "event_confirmation_identifier"],
        tagfilter: false
      }, {
        type: "permanent",
        disable_fields: ["confirmation", "confirm_every_version", "show_always", "pools"],
        hide_fields: ["confirm_message_hint", "choice_forms", "event_send_confirmation", "event_confirmation_identifier"],
        tagfilter: false
      }, {
        type: "permanent_tray",
        disable_fields: ["confirmation", "confirm_every_version", "show_always", "pools"],
        hide_fields: ["confirm_message_hint", "choice_forms", "event_send_confirmation", "event_confirmation_identifier"],
        tagfilter: false
      }, ez5.version("6") ? {
        type: "login_page",
        disable_fields: ["confirmation", "confirm_every_version", "show_always", "pools"],
        hide_fields: ["confirm_message_hint", "choice_forms", "event_send_confirmation", "event_confirmation_identifier", "client_ids"],
        tagfilter: false
      } : void 0, {
        type: "maintenance_warning",
        disable_fields: ["confirmation", "confirm_every_version", "show_always", "icon", "pools"],
        hide_fields: ["confirm_message_hint", "choice_forms", "event_send_confirmation", "event_confirmation_identifier"],
        tagfilter: false,
        disabled: !ez5.session.hasSystemRight("system.root")
      }, {
        type: "maintenance",
        disable_fields: ["confirmation", "confirm_every_version", "show_always", "icon", "pools"],
        hide_fields: ["confirm_message_hint", "choice_forms", "event_send_confirmation", "event_confirmation_identifier"],
        tagfilter: false,
        disabled: !ez5.session.hasSystemRight("system.root")
      }
    ];
    return fields.filter(function(f) {
      return !!f;
    });
  };

  AdminMessage.getWebfrontendType = function(type) {
    var i, info, len, ref;
    ref = this.getWebfrontendTypes();
    for (i = 0, len = ref.length; i < len; i++) {
      info = ref[i];
      if (info.type === type) {
        return info;
      }
    }
    return null;
  };

  AdminMessage.load = function(webfrontend_type, remoteEasydb, include_start_time) {
    var dfr, now, search;
    if (include_start_time == null) {
      include_start_time = true;
    }
    dfr = new CUI.Deferred();
    now = new Date(Date.now()).toISOString();
    search = [
      {
        type: "in",
        "in": [webfrontend_type],
        fields: ["message.webfrontend_type"]
      }, {
        type: "complex",
        search: [
          {
            bool: "should",
            type: "in",
            fields: ["message.end_time"],
            "in": [null]
          }, {
            bool: "should",
            type: "range",
            field: "message.end_time",
            from: now
          }
        ]
      }
    ];
    if (include_start_time) {
      search.push({
        type: "complex",
        search: [
          {
            bool: "should",
            type: "in",
            fields: ["message.start_time"],
            "in": [null]
          }, {
            bool: "should",
            type: "range",
            field: "message.start_time",
            to: now
          }
        ]
      });
    }
    search.push({
      type: "in",
      fields: ["_groups.group._id"],
      "in": ez5.session.getGroupIds()
    });
    ez5.api.search({
      remoteEasydb: remoteEasydb,
      data: {
        debug: "AdminMessage:" + webfrontend_type
      },
      json_data: {
        type: "message",
        search: search,
        sort: [
          {
            field: "message.start_time"
          }, {
            field: "message.title"
          }
        ]
      }
    }).done((function(_this) {
      return function(messages) {
        var adminMessages, fn, i, len, msg, ref, ref1;
        adminMessages = [];
        ref = messages.objects;
        fn = function(msg) {
          return adminMessages.push(new ez5.defaults["class"].AdminMessage({
            message: msg,
            remoteEasydb: remoteEasydb
          }));
        };
        for (i = 0, len = ref.length; i < len; i++) {
          msg = ref[i];
          if (((ref1 = msg.message.client_ids) != null ? ref1.length : void 0) && !msg.message.client_ids.includes(ez5.session.data.authenticated.client_id)) {
            continue;
          }
          fn(msg);
        }
        return dfr.resolve(adminMessages);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  AdminMessage.loadById = function(id, handleError, remoteEasydb) {
    var deferred;
    id = parseInt(id);
    if (!CUI.util.isNumber(id)) {
      return CUI.rejectedPromise();
    }
    deferred = new CUI.Deferred();
    ez5.api.message({
      api: "/" + id,
      remoteEasydb: remoteEasydb,
      handle_error: handleError
    }).done((function(_this) {
      return function(messages) {
        var adminMessage, message;
        if (messages.length === 0) {
          return deferred.reject();
        }
        message = messages[0];
        adminMessage = new ez5.defaults["class"].AdminMessage({
          message: message,
          remoteEasydb: remoteEasydb
        });
        return deferred.resolve(adminMessage);
      };
    })(this)).fail(deferred.reject);
    return deferred.promise();
  };

  return AdminMessage;

})(SystemListManagerItem);
// Generated by CoffeeScript 1.12.7
var Group,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

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

  Group.prototype.readOpts = function() {
    Group.__super__.readOpts.call(this);
    if (this._group) {
      return this.loadData(this._group);
    } else {
      return this.loadData({
        _basetype: "group",
        group: {}
      });
    }
  };

  Group.prototype.newKey = "admin.group.list.name.new";

  Group.prototype.managerInstance = function() {
    return GroupManager;
  };

  Group.prototype.getId = function() {
    return this.id;
  };

  Group.prototype.getAutomaticAuth = function() {
    return this.data._automatic_auth || void 0;
  };

  Group.prototype.isDataComplete = function() {
    return false;
  };

  Group.prototype.getName = function() {
    return this._group.group.name;
  };

  Group.prototype.getDisplayOption = function() {
    var auth, txt;
    txt = this.getDisplayText();
    auth = this.getAutomaticAuth();
    if (!auth) {
      return txt;
    }
    return txt + " " + $$("group.fields.option.automatic", {
      type: auth.type,
      timestamp: auth.timestamp
    });
  };

  Group.prototype.getDisplayText = function() {
    return this.get("displayname", false) || ("Group #" + this.id);
  };

  Group.prototype.getContent = function() {
    return CUI.dom.htmlToNodes(this.getDisplayText());
  };

  Group.prototype.canEditSystemRights = function() {
    if (!this.getId()) {
      return this.isWritable() && (ez5.session.hasSystemRight("group[create_system_rights]") || ez5.session.hasSystemRight("root"));
    } else {
      return this.isWritable() && (ez5.session.hasSystemRight("group[edit_system_rights]") || ez5.session.hasSystemRight("root"));
    }
  };

  Group.prototype.canEditAcl = function() {
    if (!this.getId()) {
      return this.isWritable() && (ez5.session.hasSystemRight("group[create_acl]") || ez5.session.hasSystemRight("root"));
    } else {
      return this.isWritable() && (ez5.session.hasSystemRight("group[edit_acl]") || ez5.session.hasSystemRight("root"));
    }
  };

  Group.prototype.isWritable = function() {
    var ref1;
    if (!this.getId() || ((ref1 = this.data._generated_rights) != null ? ref1.bag_write : void 0)) {
      return true;
    } else {
      return false;
    }
  };

  Group.prototype.isDeletable = function() {
    var ref1;
    if (!this.getId() || ((ref1 = this.data._generated_rights) != null ? ref1.bag_delete : void 0)) {
      return true;
    } else {
      return false;
    }
  };

  Group.prototype.loadData = function(data1) {
    var i, key, len, ref1;
    this.data = data1;
    Group.__super__.loadData.call(this, this.data);
    if (!this.data._system_rights) {
      this.data._system_rights = {};
    }
    if (!this.data._auth_method_group_maps) {
      this.data._auth_method_group_maps = {};
    }
    ref1 = Group.authMethodKeys;
    for (i = 0, len = ref1.length; i < len; i++) {
      key = ref1[i];
      if (!this.data._auth_method_group_maps[key]) {
        this.data._auth_method_group_maps[key] = [];
      }
    }
    if (ez5.version("6.7")) {
      if (!this.data._auth_method_group_maps["system"]) {
        this.data._auth_method_group_maps["system"] = [];
      }
      if (this.data._ip_subnet_filter_exclude) {
        this.data.group._ip_subnet_filter_exclude = this.data._ip_subnet_filter_exclude;
      }
    }
    if (!this.data.group.frontend_prefs) {
      this.data.group.frontend_prefs = {};
    }
    if (ez5.version("6")) {
      if (this.data._ip_subnet_filter) {
        this.data.group._ip_subnet_filter = this.data._ip_subnet_filter.map(function(ip) {
          return {
            ip: ip
          };
        });
      }
      if (this.data._created_at) {
        this.data.group.created_timestamp = this.data._created_at;
      }
      if (this.data._updated_at) {
        this.data.group.last_updated_timestamp = this.data._updated_at;
      }
    } else {
      if (this.data._ipv4_subnet_filter) {
        this.data.group._ipv4_subnet_filter = this.data._ipv4_subnet_filter.map(function(ipv4) {
          return {
            ipv4: ipv4
          };
        });
      }
    }
    if (!this.data._pseudonymization) {
      this.data._pseudonymization = {
        user: {}
      };
    }
    return this;
  };

  Group.prototype.canBeCopied = function() {
    var ref1;
    if (this.getId()) {
      return ((ref1 = ez5.session.getSystemRight("group")) != null ? ref1.create : void 0) || ez5.session.hasSystemRight("root");
    } else {
      return false;
    }
  };

  Group.prototype.getCopyAsNewData = function() {
    var acl, i, len, new_data, ref1;
    new_data = this.getSaveData();
    new_data.group = {};
    ref1 = new_data._acl || [];
    for (i = 0, len = ref1.length; i < len; i++) {
      acl = ref1[i];
      delete acl._id;
    }
    return new_data;
  };

  Group.prototype.copyAsNew = function() {
    var new_data, new_group;
    new_data = this.getCopyAsNewData();
    new_group = new window[CUI.util.getObjectClass(this)]({
      manager: this._manager,
      group: new_data
    });
    return new_group;
  };

  Group.prototype.getType = function() {
    return this.data.group.type;
  };

  Group.prototype.renderContent = function() {
    this.addColumn(new CUI.ListViewColumn({
      text: this.getType()
    }));
    return Group.__super__.renderContent.call(this);
  };

  Group.prototype.getApi = function() {
    return "group";
  };

  Group.authMethodKeys = ["sso", "ldap"];

  Group.prototype.headlessSave = function(ev) {
    return this._save(ev, this.getSaveData());
  };

  Group.prototype.getSaveData = function() {
    var groupRef, i, ip, j, k, key, l, len, len1, len2, len3, len4, m, mask_id, owner_id, ref1, ref10, ref11, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, save_data, sso, templates;
    save_data = {
      _basetype: "group",
      group: {
        _id: this.id,
        displayname: this.data.group.displayname,
        name: this.data.group.name,
        frontend_prefs: CUI.util.copyObject(this.data.group.frontend_prefs, true),
        comment: this.data.group.comment,
        reference: this.data.group.reference
      },
      _pseudonymization: {
        user: CUI.util.copyObject(this.data._pseudonymization.user)
      }
    };
    if (this.canChangeOwner()) {
      owner_id = (ref1 = this.data._owner) != null ? (ref2 = ref1.user) != null ? ref2._id : void 0 : void 0;
      if (owner_id) {
        save_data._owner = {
          _basetype: "user",
          user: {
            _id: owner_id
          }
        };
      }
    }
    if (ez5.version("6")) {
      save_data._ip_subnet_filter = ((ref3 = this.data.group._ip_subnet_filter) != null ? ref3.map(function(_data) {
        return _data.ip;
      }) : void 0) || [];
      ref4 = save_data._ip_subnet_filter;
      for (i = 0, len = ref4.length; i < len; i++) {
        ip = ref4[i];
        if (!this.__isValidIpV4V6(ip)) {
          throw new InvalidSaveDataException();
        }
      }
    } else {
      save_data._ipv4_subnet_filter = ((ref5 = this.data.group._ipv4_subnet_filter) != null ? ref5.map(function(_data) {
        return _data.ipv4;
      }) : void 0) || [];
      ref6 = save_data._ipv4_subnet_filter;
      for (j = 0, len1 = ref6.length; j < len1; j++) {
        ip = ref6[j];
        if (!this.__isValidIpV4(ip)) {
          throw new InvalidSaveDataException();
        }
      }
    }
    if (ez5.version("6.7")) {
      save_data._ip_subnet_filter_exclude = this.data.group._ip_subnet_filter_exclude;
    }
    if (ez5.version("6.18")) {
      save_data.group.category_a = this.data.group.category_a;
      save_data.group.category_b = this.data.group.category_b;
      save_data.group.category_c = this.data.group.category_c;
    }
    if (this.aclManager) {
      save_data._acl = this.aclManager.getSaveData();
    }
    if (this.systemAclManager) {
      save_data._system_rights = this.systemAclManager.getSaveData();
    }
    if (this.__authMapping) {
      save_data._auth_method_group_maps = {};
      ref7 = Group.authMethodKeys;
      for (k = 0, len2 = ref7.length; k < len2; k++) {
        key = ref7[k];
        save_data._auth_method_group_maps[key] = [];
        ref8 = this.data._auth_method_group_maps[key];
        for (l = 0, len3 = ref8.length; l < len3; l++) {
          sso = ref8[l];
          if (CUI.util.isEmpty(sso.value.trim())) {
            throw new InvalidSaveDataException();
          }
          save_data._auth_method_group_maps[key].push(CUI.util.copyObject(sso, true));
        }
      }
      if (ez5.version("6.7")) {
        save_data._auth_method_group_maps.system = [];
        ref9 = this.data._auth_method_group_maps.system;
        for (m = 0, len4 = ref9.length; m < len4; m++) {
          groupRef = ref9[m];
          save_data._auth_method_group_maps.system.push({
            value: groupRef.value,
            method: "eq"
          });
        }
      }
    }
    if (this.hasShaedTemplatesTab()) {
      ref10 = this.data.group.frontend_prefs.webfrontend.shared_templates;
      for (mask_id in ref10) {
        templates = ref10[mask_id];
        if (templates.length === 0) {
          delete this.data.group.frontend_prefs.webfrontend.shared_templates[mask_id];
        }
      }
    }
    if (this.hasSharedExportTemplatesTab()) {
      if (((ref11 = this.data.group.frontend_prefs.webfrontend.shared_export_templates) != null ? ref11.length : void 0) === 0) {
        delete this.data.group.frontend_prefs.webfrontend.shared_export_templates;
      }
    }
    return save_data;
  };

  Group.prototype.getTabs = function() {
    var aclTab, authMappingTab, systemAclTab, usersTab;
    authMappingTab = this.renderAuthMappingTab();
    if (this.canEditSystemRights()) {
      systemAclTab = this.renderSystemAclTab();
    }
    if (this.canEditAcl()) {
      aclTab = this.renderAclTab();
    }
    if (this.data.group._id) {
      usersTab = this.renderUsersTab();
    }
    return [
      {
        name: "general",
        text: $$("admin.group.tab.general"),
        content: (function(_this) {
          return function() {
            return new CUI.Form({
              fields: _this.getGeneralFields(),
              data: _this.data.group,
              onDataChanged: function(data, field) {
                return _this.update();
              }
            }).start();
          };
        })(this)
      }, systemAclTab ? {
        name: "system_rights",
        text: $$("admin.group.tab.system_rights"),
        content: (function(_this) {
          return function() {
            return _this.renderSystemAclTab();
          };
        })(this)
      } : void 0, aclTab ? {
        name: "acl",
        padded: false,
        text: $$("admin.group.tab.acl"),
        content: (function(_this) {
          return function() {
            return _this.renderAclTab();
          };
        })(this)
      } : void 0, {
        name: "pseudonymization",
        text: $$("admin.group.tab.pseudonymization"),
        content: (function(_this) {
          return function() {
            return new CUI.Form({
              fields: _this.__getPseudonymizationFields(),
              data: _this.data._pseudonymization,
              render_as_block: true,
              name: "user",
              onDataChanged: function() {
                return _this.update();
              }
            }).start();
          };
        })(this)
      }, authMappingTab ? {
        name: "auth_mapping",
        padded: false,
        text: $$("admin.group.tab.auth_mapping"),
        content: authMappingTab
      } : void 0, usersTab ? {
        name: "users",
        padded: false,
        text: $$("admin.group.tab.users"),
        content: usersTab
      } : void 0, this.hasShaedTemplatesTab() ? {
        name: "shared_templates",
        load_on_show: true,
        padded: false,
        text: $$("admin.group.tab.shared_templates"),
        content: (function(_this) {
          return function() {
            return _this.renderSharedTemplatesTab();
          };
        })(this)
      } : void 0, this.hasSharedExportTemplatesTab() ? {
        name: "shared_export_templates",
        load_on_show: true,
        padded: false,
        text: $$("admin.group.tab.shared_export_templates"),
        content: (function(_this) {
          return function() {
            return _this.renderSharedExportTemplatesTab();
          };
        })(this)
      } : void 0
    ];
  };

  Group.prototype.renderSystemAclTab = function() {
    if (!this.isWritable()) {
      return null;
    }
    this.systemAclManager = new AclRightManager({
      data: this.data,
      context: "SystemAclRight",
      name: "_system_rights"
    });
    return this.systemAclManager.getForm().start();
  };

  Group.prototype.hasShaedTemplatesTab = function() {
    var ref1, ref2, shared_templates;
    if (!ez5.version("6")) {
      return false;
    }
    shared_templates = (ref1 = this.data.group.frontend_prefs) != null ? (ref2 = ref1.webfrontend) != null ? ref2.shared_templates : void 0 : void 0;
    if (CUI.util.isEmpty(shared_templates)) {
      return false;
    }
    return true;
  };

  Group.prototype.renderSharedTemplatesTab = function() {
    var deselect_all, dts, editBtn, fn, getOutputTemplateFields, getRowEditButton, hintText, mask_id, panels, ref1, ref2, selected_template, shared_template_dt, shared_templates, templates, users_data, users_ids;
    shared_templates = (ref1 = this.data.group.frontend_prefs) != null ? (ref2 = ref1.webfrontend) != null ? ref2.shared_templates : void 0 : void 0;
    shared_template_dt = null;
    selected_template = null;
    dts = [];
    users_ids = new Set();
    users_data = [];
    deselect_all = (function(_this) {
      return function(new_selected_row) {
        var dt, i, len, results;
        results = [];
        for (i = 0, len = dts.length; i < len; i++) {
          dt = dts[i];
          results.push(dt.listView.getSelectedRows().forEach(function(row) {
            if (row === new_selected_row) {
              return;
            }
            return row.deselect();
          }));
        }
        return results;
      };
    })(this);
    getOutputTemplateFields = (function(_this) {
      return function(mask_name) {
        return [
          {
            type: CUI.Output,
            name: "name",
            form: {
              label: $$("editor.templates.customize.data_table.name"),
              column: "auto"
            }
          }, {
            type: CUI.Output,
            name: "user",
            form: {
              label: $$("editor.templates.customize.data_table.user")
            },
            getValue: function(value) {
              var ref3;
              return ((ref3 = users_data.find((function(_this) {
                return function(u) {
                  return u.user._id === value;
                };
              })(this))) != null ? ref3.user._generated_displayname : void 0) || value;
            }
          }, {
            type: CUI.Output,
            name: "user",
            form: {
              label: $$("editor.templates.customize.data_table.mask"),
              column: "auto"
            },
            getValue: function(value) {
              return mask_name;
            }
          }, {
            type: CUI.Output,
            name: "comment",
            form: {
              label: $$("editor.templates.customize.data_table.comment"),
              column: "maximize"
            }
          }, {
            type: CUI.Output,
            name: "create_date",
            form: {
              label: $$("editor.templates.customize.data_table.create_date")
            },
            getValue: function(value) {
              return ez5.format_date_and_time(value);
            }
          }, {
            type: CUI.OutputContent,
            name: "data",
            getValue: function(templateData) {
              return new CUI.Button({
                icon: "fa-eye",
                onClick: (function(_this) {
                  return function(ev, btn) {
                    var pop, previewData, ro;
                    previewData = CUI.util.copyObject(templateData, true);
                    previewData._mapped_metadata_created = true;
                    ro = new ResultObject();
                    ro.setData(previewData);
                    pop = new CUI.Popover({
                      size: "m",
                      "class": "ez5-editor-templates-customize-preview-popover",
                      element: btn,
                      placement: "n",
                      pane: {
                        content: ro.renderDetail("detail", "detail-header", {}),
                        padded: true,
                        maximize_horizontal: true,
                        maximize_vertical: true
                      }
                    });
                    return pop.show();
                  };
                })(this)
              });
            },
            form: {
              label: "Preview"
            }
          }
        ];
      };
    })(this);
    getRowEditButton = (function(_this) {
      return function() {
        return new LocaButton({
          icon: "fa-pencil",
          ui: "editor.templates.customize.edit.button",
          disabled: true,
          onClick: function(ev, btn) {
            var dt, editPopover, original_data, rows, selected_data;
            dt = btn._data_table;
            if (!dt) {
              return;
            }
            rows = dt.listView.getSelectedRows();
            if (rows.length === 0) {
              return;
            }
            selected_data = rows[0].getData();
            original_data = CUI.util.copyObject(selected_data, true);
            editPopover = new CUI.Modal({
              cancel: true,
              onCancel: function() {
                return CUI.confirm({
                  text: $$("editor.templates.customize.confirm_unsaved")
                }).done(function() {
                  Object.assign(selected_data, original_data);
                  return editPopover.destroy();
                });
              },
              pane: {
                title: $$("editor.templates.customize.edit.title"),
                padded: true,
                footer_right: [
                  new LocaButton({
                    loca_key: "editor.templates.customize.save",
                    primary: true,
                    onClick: function(ev) {
                      CUI.Events.trigger({
                        type: "data-changed",
                        node: dt.listView
                      });
                      dt.loadPage();
                      return editPopover.destroy();
                    }
                  })
                ],
                content: function() {
                  return new CUI.Form({
                    data: selected_data,
                    fields: [
                      {
                        type: CUI.Input,
                        name: "name",
                        form: {
                          label: $$("editor.templates.customize.data_table.name")
                        },
                        ui: "editor.templates.customize.data_table.name.input"
                      }, {
                        type: CUI.Output,
                        name: "create_date",
                        form: {
                          label: $$("editor.templates.customize.data_table.create_date")
                        },
                        ui: "editor.templates.customize.data_table.create_date",
                        getValue: function(value) {
                          return ez5.format_date_and_time(value);
                        }
                      }, {
                        type: CUI.Output,
                        name: "user",
                        form: {
                          label: $$("editor.templates.customize.data_table.user")
                        },
                        ui: "editor.templates.customize.data_table.user",
                        getValue: function(value) {
                          var ref3;
                          return ((ref3 = users_data.find((function(_this) {
                            return function(u) {
                              return u.user._id === value;
                            };
                          })(this))) != null ? ref3.user._generated_displayname : void 0) || value;
                        }
                      }, {
                        type: CUI.Input,
                        name: "comment",
                        form: {
                          label: $$("editor.templates.customize.data_table.comment")
                        },
                        ui: "editor.templates.customize.data_table.comment",
                        textarea: true
                      }
                    ]
                  }).start();
                }
              }
            });
            return editPopover.show();
          }
        });
      };
    })(this);
    panels = [];
    fn = (function(_this) {
      return function(editBtn) {
        var i, len, mask, mask_name, objecttype_name, panel, t;
        mask = ez5.mask.CURRENT._mask_by_id[mask_id];
        if (mask) {
          mask_name = mask._name_localized || mask.name;
          objecttype_name = ez5.loca.getBestFrontendValue(mask.table_name_localized) || mask.table_name_hint;
          if (!objecttype_name) {
            objecttype_name = "Unknown objecttype from mask with id: " + mask._id;
          }
        } else {
          objecttype_name = "Unknown mask with id: " + mask_id;
        }
        for (i = 0, len = templates.length; i < len; i++) {
          t = templates[i];
          users_ids.add(t.user);
        }
        shared_template_dt = new CUI.DataTable({
          data: shared_templates,
          name: mask_id,
          rowMove: true,
          maximize: true,
          new_rows: "remove_only",
          buttons: [editBtn],
          onRowDeselect: function() {
            shared_template_dt = null;
            return editBtn.disable();
          },
          onRowSelect: function(ev, info) {
            deselect_all(info.row);
            editBtn.enable();
            return selected_template = info.row.getData();
          },
          onBeforeRowRemove: function(data, ev) {
            return CUI.confirm({
              text: $$("editor.templates.customize.confirm_remove_shared"),
              markdown: true
            });
          },
          onRowRemove: function(data, ev) {
            return shared_template_dt = null;
          },
          onDataChanged: function() {},
          fields: getOutputTemplateFields(mask_name)
        });
        dts.push(shared_template_dt);
        panel = new CUI.Panel({
          text: objecttype_name,
          radio: true,
          closed: false,
          content: function() {
            return shared_template_dt.start();
          }
        });
        return panels.push(panel);
      };
    })(this);
    for (mask_id in shared_templates) {
      templates = shared_templates[mask_id];
      editBtn = getRowEditButton();
      fn(editBtn);
    }
    this.__searchUsersById(Array.from(users_ids)).done((function(_this) {
      return function(data) {
        var dt, i, len, results;
        users_data = data.objects;
        results = [];
        for (i = 0, len = dts.length; i < len; i++) {
          dt = dts[i];
          CUI.Events.trigger({
            type: "data-changed",
            node: dt.listView
          });
          results.push(dt.loadPage());
        }
        return results;
      };
    })(this));
    hintText = new CUI.Label({
      text: $$("admin.group.tab.shared_templates.hint"),
      icon: "fa-info"
    });
    return [hintText, panels];
  };

  Group.prototype.hasSharedExportTemplatesTab = function() {
    var ref1, ref2, shared_export_templates;
    if (!ez5.version("6")) {
      return false;
    }
    shared_export_templates = (ref1 = this.data.group.frontend_prefs) != null ? (ref2 = ref1.webfrontend) != null ? ref2.shared_export_templates : void 0 : void 0;
    if (CUI.util.isEmpty(shared_export_templates)) {
      return false;
    }
    return true;
  };

  Group.prototype.renderSharedExportTemplatesTab = function() {
    var editBtn, exportTemplateDt, getRowEditButton, hintText, i, len, shared_export_templates, t, users_data, users_ids;
    shared_export_templates = this.data.group.frontend_prefs.webfrontend.shared_export_templates;
    users_ids = new Set();
    users_data = [];
    for (i = 0, len = shared_export_templates.length; i < len; i++) {
      t = shared_export_templates[i];
      if (t.user) {
        users_ids.add(t.user);
      }
    }
    getRowEditButton = (function(_this) {
      return function() {
        return new LocaButton({
          icon: "fa-pencil",
          disabled: true,
          onClick: function(ev, btn) {
            var dt, editPopover, original_data, rows, selected_data;
            dt = btn._data_table;
            if (!dt) {
              return;
            }
            rows = dt.listView.getSelectedRows();
            if (rows.length === 0) {
              return;
            }
            selected_data = rows[0].getData();
            original_data = CUI.util.copyObject(selected_data, true);
            editPopover = new CUI.Modal({
              cancel: true,
              onCancel: function() {
                return CUI.confirm({
                  text: $$("export.templates.customize.confirm_unsaved")
                }).done(function() {
                  Object.assign(selected_data, original_data);
                  return editPopover.destroy();
                });
              },
              pane: {
                title: $$("export.templates.customize.edit.title"),
                padded: true,
                footer_right: [
                  new LocaButton({
                    loca_key: "export.templates.customize.save",
                    primary: true,
                    onClick: function(ev) {
                      CUI.Events.trigger({
                        type: "data-changed",
                        node: dt.listView
                      });
                      dt.loadPage();
                      return editPopover.destroy();
                    }
                  })
                ],
                content: function() {
                  return new CUI.Form({
                    data: selected_data,
                    fields: [
                      {
                        type: CUI.Input,
                        name: "name",
                        form: {
                          label: $$("export.template.save_as_template.name.label")
                        }
                      }, {
                        type: CUI.Output,
                        name: "create_date",
                        form: {
                          label: $$("export.templates.customize.data_table.create_date")
                        },
                        getValue: function(value) {
                          return ez5.format_date_and_time(value);
                        }
                      }, {
                        type: CUI.Output,
                        name: "user",
                        form: {
                          label: $$("export.templates.customize.data_table.user")
                        },
                        getValue: function(value) {
                          var ref1;
                          return ((ref1 = users_data.find((function(_this) {
                            return function(u) {
                              return u.user._id === value;
                            };
                          })(this))) != null ? ref1.user._generated_displayname : void 0) || value;
                        }
                      }, {
                        type: CUI.Input,
                        name: "comment",
                        form: {
                          label: $$("export.template.save_as_template.comment.label")
                        },
                        textarea: true
                      }
                    ]
                  }).start();
                }
              }
            });
            return editPopover.show();
          }
        });
      };
    })(this);
    editBtn = getRowEditButton();
    exportTemplateDt = new CUI.DataTable({
      data: this.data.group.frontend_prefs.webfrontend,
      name: "shared_export_templates",
      rowMove: true,
      maximize: true,
      new_rows: "remove_only",
      buttons: [editBtn],
      onRowDeselect: (function(_this) {
        return function() {
          return editBtn.disable();
        };
      })(this),
      onRowSelect: (function(_this) {
        return function(ev, info) {
          return editBtn.enable();
        };
      })(this),
      onBeforeRowRemove: (function(_this) {
        return function(data, ev) {
          return CUI.confirm({
            text: $$("export.templates.customize.confirm_remove_shared")
          });
        };
      })(this),
      fields: [
        {
          type: CUI.Output,
          name: "name",
          form: {
            label: $$("export.template.save_as_template.name.label"),
            column: "auto"
          }
        }, {
          type: CUI.Output,
          name: "user",
          form: {
            label: $$("export.templates.customize.data_table.user")
          },
          getValue: function(value) {
            var ref1;
            return ((ref1 = users_data.find((function(_this) {
              return function(u) {
                return u.user._id === value;
              };
            })(this))) != null ? ref1.user._generated_displayname : void 0) || value;
          }
        }, {
          type: CUI.Output,
          name: "comment",
          form: {
            label: $$("export.template.save_as_template.comment.label"),
            column: "maximize"
          }
        }, {
          type: CUI.Output,
          name: "create_date",
          form: {
            label: $$("export.templates.customize.data_table.create_date")
          },
          getValue: function(value) {
            return ez5.format_date_and_time(value);
          }
        }
      ]
    });
    if (users_ids.size > 0) {
      this.__searchUsersById(Array.from(users_ids)).done((function(_this) {
        return function(data) {
          users_data = data.objects;
          CUI.Events.trigger({
            type: "data-changed",
            node: exportTemplateDt.listView
          });
          return exportTemplateDt.loadPage();
        };
      })(this));
    }
    hintText = new CUI.Label({
      text: $$("admin.group.tab.shared_export_templates.hint"),
      icon: "fa-info"
    });
    return [hintText, exportTemplateDt.start()];
  };

  Group.prototype.renderAclTab = function() {
    if (!this.isWritable()) {
      return null;
    }
    this.aclManager = new AclManager({
      data: this.data._acl,
      context: this,
      right: true
    });
    return this.aclManager.getTree();
  };

  Group.__usersPerPage = 50;

  Group.prototype.renderUsersTab = function() {
    var navigationToolbar, update, updateNavigationToolbar, updateUsers, usersData, usersDataTable, waitBlock;
    if (this.__usersTabContent) {
      return this.__usersTabContent;
    }
    this.__usersTabContent = CUI.dom.div();
    usersData = {
      users: []
    };
    usersDataTable = new CUI.DataTable({
      data: usersData,
      name: "users",
      maximize_vertical: true,
      chunk_size: this.__usersPerPage,
      new_rows: "none",
      fields: [
        {
          form: {
            label: $$("admin.group.tab.users.table.row.user")
          },
          type: CUI.Output,
          name: "user"
        }, {
          type: CUI.Output,
          form: {
            label: $$("admin.group.tab.users.table.row.type")
          },
          name: "type"
        }
      ]
    });
    usersDataTable.start();
    updateUsers = function(data) {
      var i, len, ref1, user;
      usersData.users = [];
      ref1 = data.objects;
      for (i = 0, len = ref1.length; i < len; i++) {
        user = ref1[i];
        usersData.users.push({
          user: user.user._generated_displayname || user.user.login,
          type: user.user.type
        });
      }
      return usersDataTable.displayValue();
    };
    waitBlock = new CUI.WaitBlock({
      element: usersDataTable
    });
    updateNavigationToolbar = function(data) {
      return navigationToolbar.update({
        count: data.count,
        offset: data.offset,
        limit: Group.__usersPerPage
      });
    };
    update = (function(_this) {
      return function(data) {
        waitBlock.hide();
        updateUsers(data);
        return updateNavigationToolbar(data);
      };
    })(this);
    navigationToolbar = new NavigationToolbar({
      short: true,
      onLoadPage: (function(_this) {
        return function(page) {
          waitBlock.show();
          return _this.__searchUsers(page * Group.__usersPerPage).done(function(nextPageData) {
            return update(nextPageData);
          });
        };
      })(this)
    });
    waitBlock.show();
    this.__searchUsers(0).done((function(_this) {
      return function(data) {
        return update(data);
      };
    })(this));
    this.__usersTabContent = [usersDataTable, navigationToolbar];
    return this.__usersTabContent;
  };

  Group.prototype.__searchUsersById = function(ids) {
    return this.__searchUsersByIdRequest = ez5.api.search({
      json_data: {
        type: "user",
        search: [
          {
            type: "in",
            bool: "must",
            fields: ["user._id"],
            "in": ids
          }
        ],
        limit: ids.length
      }
    });
  };

  Group.prototype.__searchUsers = function(offset) {
    return this.__searchUsersRequest = ez5.api.search({
      json_data: {
        type: "user",
        search: [
          {
            type: "in",
            bool: "must",
            fields: ["_groups.group._id"],
            "in": [this.data.group._id]
          }
        ],
        sort: [
          {
            field: "user._generated_displayname",
            order: "ASC"
          }
        ],
        limit: Group.__usersPerPage,
        offset: offset
      }
    });
  };

  Group.prototype.deselect = function(ev) {
    return Group.__super__.deselect.call(this, ev).done((function(_this) {
      return function() {
        var element, i, len, ref1, ref2, ref3, ref4;
        if ((ref1 = _this.aclManager) != null) {
          ref1.destroy();
        }
        if ((ref2 = _this.systemAclManager) != null) {
          ref2.destroy();
        }
        delete _this.aclManager;
        delete _this.systemAclManager;
        if ((ref3 = _this.__searchUsersRequest) != null) {
          ref3.abort();
        }
        if (CUI.util.isArray(_this.__usersTabContent)) {
          ref4 = _this.__usersTabContent;
          for (i = 0, len = ref4.length; i < len; i++) {
            element = ref4[i];
            element.destroy();
          }
        }
        return delete _this.__usersTabContent;
      };
    })(this));
  };

  Group.prototype.getGeneralFields = function() {
    return [
      {
        type: CUI.Output,
        name: "_id",
        form: {
          label: $$("admin.group._id")
        },
        placeholder: $$("admin.group._id.new")
      }, this.canChangeOwner() ? {
        type: UserGroupSelector,
        form: {
          label: $$("admin.group._owner")
        },
        name: "_owner",
        data: this.data,
        aclWhoManager: new AclWhoManager({
          who_filter: ["user"],
          filter_system_groups: true
        })
      } : {
        type: CUI.Output,
        data: this.data,
        name: "_owner",
        form: {
          label: $$("admin.group._owner")
        },
        getValue: function(v) {
          var ref1;
          return v != null ? (ref1 = v[v._basetype]) != null ? ref1._generated_displayname : void 0 : void 0;
        },
        placeholder: $$("admin.group._owner.new")
      }, {
        type: CUI.Output,
        name: "type",
        form: {
          label: $$("admin.group.type")
        },
        placeholder: $$("admin.group.type.new")
      }, {
        type: CUI.MultiInput,
        control: ez5.loca.getLanguageControlAdmin(),
        user_selectable: ez5.session.getPref("languages_user_selection"),
        form: {
          label: $$("admin.group.displayname")
        },
        name: "displayname"
      }, this.getNameField(), {
        type: CUI.Input,
        form: {
          label: $$("admin.group.comment")
        },
        textarea: true,
        name: "comment"
      }, {
        type: CUI.Input,
        name: "reference",
        form: {
          label: $$("admin.group.reference")
        }
      }, ez5.version("6.18") ? {
        type: UserGroupCategorySelector,
        category: "category_a",
        name: "category_a",
        form: {
          label: $$("admin.group.category_a")
        }
      } : void 0, ez5.version("6.18") ? {
        type: UserGroupCategorySelector,
        category: "category_b",
        name: "category_b",
        form: {
          label: $$("admin.group.category_b")
        }
      } : void 0, ez5.version("6.18") ? {
        type: UserGroupCategorySelector,
        category: "category_c",
        name: "category_c",
        form: {
          label: $$("admin.group.category_c")
        }
      } : void 0, ez5.version("6") ? {
        type: CUI.DataForm,
        form: {
          label: $$("admin.group.ip_subnet_filter")
        },
        name: "_ip_subnet_filter",
        maximize_horizontal: true,
        fields: [
          {
            type: CUI.Input,
            name: "ip",
            placeholder: $$("admin.group.ip_subnet_filter.placeholder"),
            checkInput: (function(_this) {
              return function(value) {
                return _this.__isValidIpV4V6(value);
              };
            })(this)
          }
        ]
      } : {
        type: CUI.DataForm,
        form: {
          label: $$("admin.group.ipv4_subnet_filter")
        },
        name: "_ipv4_subnet_filter",
        maximize_horizontal: true,
        fields: [
          {
            type: CUI.Input,
            name: "ipv4",
            placeholder: $$("admin.group.ipv4_subnet_filter.placeholder"),
            checkInput: this.__isValidIpV4
          }
        ]
      }, ez5.version("6.7") ? {
        type: CUI.Checkbox,
        name: "_ip_subnet_filter_exclude",
        form: {
          label: $$("admin.group.ip_subnet_filter_exclude")
        }
      } : void 0, this.__getUserPreferencesField(), {
        type: CUI.Output,
        form: {
          label: $$("admin.group.created_timestamp")
        },
        name: "created_timestamp",
        placeholder: $$("admin.group.created_timestamp.new"),
        getValue: (function(_this) {
          return function(v) {
            return ez5.format_date_and_time(v, true);
          };
        })(this)
      }, {
        type: CUI.Output,
        form: {
          label: $$("admin.group.last_updated_timestamp")
        },
        name: "last_updated_timestamp",
        placeholder: $$("admin.group.last_updated_timestamp.new"),
        getValue: (function(_this) {
          return function(v) {
            return ez5.format_date_and_time(v, true);
          };
        })(this)
      }
    ];
  };

  Group.prototype.canChangeOwner = function() {
    if (!ez5.version("6.4")) {
      return false;
    }
    if (!this.getId()) {
      return false;
    } else if (!ez5.session.hasSystemRight("system.root")) {
      return false;
    } else {
      return true;
    }
  };

  Group.prototype.__getPseudonymizationFields = function() {
    var clearOption, keepOption, randomOption;
    keepOption = {
      value: "keep",
      text: $$("admin.group.form.pseudonymization.option.keep|text")
    };
    randomOption = {
      value: "random",
      text: $$("admin.group.form.pseudonymization.option.random|text")
    };
    clearOption = {
      value: "clear",
      text: $$("admin.group.form.pseudonymization.option.clear|text")
    };
    return [
      {
        form: {
          label: $$("admin.group.form.pseudonymization.select.login|label")
        },
        type: CUI.Select,
        name: "login",
        options: [keepOption, randomOption]
      }, {
        form: {
          label: $$("admin.group.form.pseudonymization.select.first_name|label")
        },
        type: CUI.Select,
        name: "first_name",
        options: [keepOption, randomOption, clearOption]
      }, {
        form: {
          label: $$("admin.group.form.pseudonymization.select.last_name|label")
        },
        type: CUI.Select,
        name: "last_name",
        options: [keepOption, randomOption, clearOption]
      }, {
        form: {
          label: $$("admin.group.form.pseudonymization.select.displayname|label")
        },
        type: CUI.Select,
        name: "displayname",
        options: [keepOption, randomOption, clearOption]
      }, !ez5.version("6") ? {
        form: {
          label: $$("admin.group.form.pseudonymization.select.department|label")
        },
        type: CUI.Select,
        name: "department",
        options: [keepOption, randomOption, clearOption]
      } : {
        form: {
          label: $$("admin.group.form.pseudonymization.select.additional_info|label"),
          hint: $$("admin.group.form.pseudonymization.select.additional_info|hint")
        },
        type: CUI.Select,
        name: "additional_info",
        options: [keepOption, randomOption, clearOption]
      }, {
        form: {
          label: $$("admin.group.form.pseudonymization.select.emails|label")
        },
        type: CUI.Select,
        name: "_emails",
        options: [keepOption, clearOption]
      }
    ];
  };

  Group.prototype.hasCategory = function() {
    if (!ez5.version("6")) {
      return false;
    }
    return !CUI.util.isEmpty(this.data.group.category_a) || !CUI.util.isEmpty(this.data.group.category_b) || !CUI.util.isEmpty(this.data.group.category_c);
  };

  Group.prototype.getCategories = function() {
    if (!this.hasCategory()) {
      return null;
    }
    return {
      category_a: this.data.group.category_a,
      category_b: this.data.group.category_b,
      category_c: this.data.group.category_c
    };
  };

  Group.prototype.__getUserPreferencesField = function() {
    var aclData, aclWhoManager, buttonRemove, getPreferencesContent, preferencesDivContent, waitBlock, whoField;
    preferencesDivContent = CUI.dom.div();
    waitBlock = null;
    aclData = {};
    aclWhoManager = new AclWhoManager({
      who_filter: ["user"]
    });
    whoField = new UserGroupSelector({
      form: {
        label: $$("admin.group.autocomplete-preferences-new-user")
      },
      name: "who",
      aclWhoManager: aclWhoManager,
      data: aclData,
      onDataChanged: (function(_this) {
        return function(data, field) {
          var idUser;
          if (!data["who"]) {
            return;
          }
          idUser = aclData["who"].user._id;
          field.setValue();
          waitBlock.show();
          ez5.api.user({
            api: "/" + idUser
          }).done(function(responseData) {
            var i, key, len, ref1, ref2, ref3;
            waitBlock.hide();
            if (!_this.data.group.frontend_prefs.webfrontend) {
              _this.data.group.frontend_prefs.webfrontend = {};
            }
            _this.data.group.frontend_prefs.webfrontend.preferences_new_users = ((ref1 = responseData[0].user) != null ? (ref2 = ref1.frontend_prefs) != null ? ref2.webfrontend : void 0 : void 0) || {};
            if (responseData[0].user) {
              ref3 = ["database_languages", "search_languages"];
              for (i = 0, len = ref3.length; i < len; i++) {
                key = ref3[i];
                if (responseData[0].user[key]) {
                  _this.data.group.frontend_prefs.webfrontend.preferences_new_users[key] = responseData[0].user[key];
                }
              }
            }
            _this.data.group.frontend_prefs.webfrontend.preferences_new_users.copied_from_user_id = idUser;
            CUI.dom.replace(preferencesDivContent, getPreferencesContent(true));
            return _this.setStatus();
          });
        };
      })(this)
    });
    buttonRemove = new CUI.Button({
      text: $$("admin.group.preferences.remove-preferences"),
      appearance: "link",
      onClick: (function(_this) {
        return function() {
          if (!_this.initialData.group.frontend_prefs.webfrontend) {
            delete _this.data.group.frontend_prefs.webfrontend;
          } else if (!_this.initialData.group.frontend_prefs.webfrontend.preferences_new_users) {
            delete _this.data.group.frontend_prefs.webfrontend.preferences_new_users;
          } else {
            _this.data.group.frontend_prefs.webfrontend.preferences_new_users = {};
          }
          CUI.dom.replace(preferencesDivContent, getPreferencesContent());
          _this.setStatus();
        };
      })(this)
    });
    getPreferencesContent = (function(_this) {
      return function(calledByWhoField) {
        var i, id, j, k, key, len, len1, len2, name, objectType, objectsNameSelected, poolsNameSelected, preferences_new_users, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, row, rows, table, value, viewData, viewIndex, viewKey;
        if (calledByWhoField == null) {
          calledByWhoField = false;
        }
        rows = [];
        preferences_new_users = (ref1 = _this.data.group.frontend_prefs.webfrontend) != null ? ref1.preferences_new_users : void 0;
        for (key in preferences_new_users) {
          value = preferences_new_users[key];
          switch (key) {
            case "search_type_selector":
              if (((ref2 = value.objecttypes) != null ? ref2.length : void 0) !== 0) {
                objectsNameSelected = [];
                ref3 = value.objecttypes;
                for (i = 0, len = ref3.length; i < len; i++) {
                  objectType = ref3[i];
                  if (name = (ref4 = ez5.schema.CURRENT._table_by_name[objectType]) != null ? ref4._name_localized : void 0) {
                    objectsNameSelected.push(name);
                  }
                }
                if (!CUI.util.isEmpty(objectsNameSelected)) {
                  rows.push([$$("admin.group.preferences.field.search.selector.objecttypes"), objectsNameSelected.join(", ")]);
                }
              }
              if (((ref5 = value.pool_ids) != null ? ref5.length : void 0) !== 0) {
                poolsNameSelected = [];
                ref6 = value.pool_ids;
                for (j = 0, len1 = ref6.length; j < len1; j++) {
                  id = ref6[j];
                  if (name = (ref7 = ez5.pools.findPoolById(id)) != null ? ref7.getDisplayText() : void 0) {
                    poolsNameSelected.push(name);
                  }
                }
                if (!CUI.util.isEmpty(poolsNameSelected)) {
                  rows.push([$$("admin.group.preferences.field.search.selector.pools"), poolsNameSelected.join(", ")]);
                }
              }
              break;
            case "search.main.filter":
              rows.push([$$("admin.group.preferences.field.search.filter-enabled"), $$("admin.group.preferences.field.search.filter-enabled." + value)]);
              break;
            case "quick_access_open":
              rows.push([$$("admin.group.preferences.field.quick_access_open"), $$("admin.group.preferences.field.quick_access_open." + value)]);
              break;
            case "root_menu_open":
              rows.push([$$("admin.group.preferences.field.root_menu_open"), $$("admin.group.preferences.field.root_menu_open." + value)]);
              break;
            case "skip_new_modal_upload_step":
              rows.push([$$("admin.group.preferences.field.skip_new_modal_upload_step"), $$("admin.group.preferences.field.skip_new_modal_upload_step." + value)]);
              break;
            case "search_main_view_data":
              viewIndex = 0;
              ref8 = value.view_data;
              for (viewKey in ref8) {
                viewData = ref8[viewKey];
                if (viewIndex === value.view_select) {
                  rows.push([$$("admin.group.preferences.field.search.view"), ($$("main.search.view." + (viewKey.toLowerCase()))) + " " + ($$("admin.group.preferences.field.search.view.hint"))]);
                  break;
                }
                viewIndex++;
              }
              break;
            case "database_languages":
            case "search_languages":
              value = value.map(function(language) {
                return ez5.loca.getLanguageLabel(language);
              });
              rows.push([$$("admin.group.preferences.field." + key), value.join(", ")]);
          }
        }
        if (CUI.util.isEmpty(rows)) {
          if (calledByWhoField) {
            CUI.alert({
              text: $$("admin.group.user-without-preferences")
            });
          }
          return new CUI.EmptyLabel({
            text: $$("admin.group.preferences.no-preferences")
          });
        }
        table = CUI.dom.table("ez5-group-manager-preferences-field");
        for (k = 0, len2 = rows.length; k < len2; k++) {
          row = rows[k];
          CUI.dom.append(table, CUI.dom.tr_one_row(row));
        }
        CUI.dom.append(table, buttonRemove);
        return table;
      };
    })(this);
    return new CUI.Form({
      fields: [
        {
          type: CUI.DataFieldProxy,
          maximize_horizontal: true,
          form: {
            label: $$("admin.group.preferences-new-user")
          },
          element: (function(_this) {
            return function() {
              CUI.dom.replace(preferencesDivContent, getPreferencesContent());
              waitBlock = new CUI.WaitBlock({
                element: preferencesDivContent
              });
              return preferencesDivContent;
            };
          })(this)
        }, whoField
      ]
    });
  };

  Group.prototype.getNameField = function() {
    return {
      type: CUI.Input,
      form: {
        label: $$("admin.group.name")
      },
      name: "name"
    };
  };

  Group.prototype.renderAuthMappingTab = function() {
    var blocks, description, dt, group, i, j, k, key, len, len1, len2, opts_method, ref, ref1, ref2, ref3, ref4, ref5, system_group_refs;
    this.__authMapping = true;
    opts_method = [];
    ref1 = ["eq", "regexp"];
    for (i = 0, len = ref1.length; i < len; i++) {
      key = ref1[i];
      opts_method.push({
        value: key,
        text: $$("group.auth_mapping.form.method." + key)
      });
    }
    blocks = [];
    ref2 = Group.authMethodKeys;
    for (j = 0, len1 = ref2.length; j < len1; j++) {
      key = ref2[j];
      if (ez5.loca.has("group.auth_mapping.block." + key + ".description")) {
        description = $$("group.auth_mapping.block." + key + ".description");
      } else {
        description = null;
      }
      dt = new CUI.DataTable({
        data: this.data._auth_method_group_maps,
        name: key,
        maximize_horizontal: true,
        fields: [
          {
            undo_and_changed_support: false,
            form: {
              label: $$("group.auth_mapping.form.method")
            },
            type: CUI.Select,
            options: opts_method,
            name: "method"
          }, {
            undo_and_changed_support: false,
            type: CUI.Input,
            form: {
              label: $$("group.auth_mapping.form.value")
            },
            name: "value"
          }
        ]
      });
      dt.start();
      blocks.push(new CUI.Block({
        description: description,
        text: $$("group.auth_mapping.block." + key + ".title"),
        content: dt
      }));
    }
    if (ez5.version("6.7")) {
      if (ez5.loca.has("group.auth_mapping.block.system.description")) {
        description = $$("group.auth_mapping.block." + key + ".description");
      } else {
        description = null;
      }
      system_group_refs = [];
      ref3 = ez5.groupManager.getGroups();
      for (k = 0, len2 = ref3.length; k < len2; k++) {
        group = ref3[k];
        if (group instanceof SystemGroup) {
          ref = (ref4 = group.getData()) != null ? (ref5 = ref4.group) != null ? ref5.reference : void 0 : void 0;
          if (ref) {
            system_group_refs.push({
              value: ref,
              text: group.getDisplayText()
            });
          }
        }
      }
      blocks.push(new CUI.Block({
        text: $$("group.auth_mapping.block.system.title"),
        description: description,
        content: new CUI.DataTable({
          data: this.data._auth_method_group_maps,
          name: "system",
          "class": "ez5-group-manager-auth-mapping-system-table",
          maximize_horizontal: true,
          fields: [
            {
              undo_and_changed_support: false,
              type: CUI.Select,
              form: {
                label: $$("group.auth_mapping.form.reference")
              },
              name: "value",
              options: system_group_refs
            }
          ]
        }).start()
      }));
    }
    return blocks;
  };

  Group.prototype.getAuthUrl = function() {
    return "login";
  };

  Group.getGroupFields = function(type_prefixes, user) {
    var custom_filter_ids, fields, group, group_ids, groups, i, j, k, l, len, len1, len2, len3, opt, options, pkey, ref1, ref2, ref3, type_prefix;
    if (type_prefixes == null) {
      type_prefixes = ["easydb"];
    }
    if (user == null) {
      user = null;
    }
    fields = [];
    options = {};
    for (i = 0, len = type_prefixes.length; i < len; i++) {
      type_prefix = type_prefixes[i];
      CUI.util.assert(type_prefix === "easydb" || type_prefix === "custom" || type_prefix === "system" || type_prefix === "automatic", "Group.getGroupFields", "type prefix needs to be easydb, custom, or system.", {
        type_prefixes: type_prefixes
      });
      options[type_prefix] = [];
      if (type_prefix === "custom" || type_prefix === "automatic") {
        pkey = "group.fields.label.placeholder." + type_prefix;
      } else {
        pkey = "group.fields.label.placeholder";
      }
      fields.push({
        form: {
          label: $$("group.fields.label." + type_prefix)
        },
        type: CUI.Options,
        horizontal: false,
        name: type_prefix !== "automatic" ? "__group_ids" : void 0,
        placeholder: $$(pkey),
        options: options[type_prefix]
      });
    }
    groups = ez5.groupManager.getGroups().slice(0);
    group_ids = (function() {
      var j, len1, results;
      results = [];
      for (j = 0, len1 = groups.length; j < len1; j++) {
        group = groups[j];
        results.push(group.getId());
      }
      return results;
    })();
    if (user) {
      custom_filter_ids = [];
      ref1 = user.getGroups();
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        group = ref1[j];
        custom_filter_ids.push(group.getId());
        if ((ref2 = group.getId(), indexOf.call(group_ids, ref2) < 0) || group.getAutomaticAuth()) {
          groups.push(group);
        }
      }
    } else {
      custom_filter_ids = null;
    }
    groups.sort(function(a, b) {
      return a.getDisplayText().localeCompare(b.getDisplayText());
    });
    for (k = 0, len2 = groups.length; k < len2; k++) {
      group = groups[k];
      for (l = 0, len3 = type_prefixes.length; l < len3; l++) {
        type_prefix = type_prefixes[l];
        if (type_prefix !== "automatic" && group.getAutomaticAuth()) {
          continue;
        }
        if (type_prefix === "automatic") {
          if (!group.getAutomaticAuth()) {
            continue;
          }
        } else {
          if (!group.getType().startsWith(type_prefix)) {
            continue;
          }
        }
        if (type_prefix === "custom" && custom_filter_ids && (ref3 = group.getId(), indexOf.call(custom_filter_ids, ref3) < 0)) {
          continue;
        }
        opt = {
          text: group.getDisplayOption(),
          value: group.getId()
        };
        if (type_prefix === "custom") {
          opt.disabled = true;
        }
        if (group.getAutomaticAuth()) {
          opt.disabled = true;
          opt.active = true;
        }
        options[type_prefix].push(opt);
      }
    }
    return fields;
  };

  Group.newInstance = function(opts) {
    switch (opts.group.group.type) {
      case "easydb":
        return new ez5.defaults["class"].Group(opts);
      case "system":
        return new ez5.defaults["class"].SystemGroup(opts);
      default:
        return new ez5.defaults["class"].CustomGroup(opts);
    }
  };

  Group.ipV4Regex = new RegExp("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])(?:\\.(?:[01]?\\d\\d?|2[0-4]\\d|25[0-5])){3}(?:\\/[1-9]|\\/[0-9]\\d|\\/[0-1][0-2][0-8])?$");

  Group.ipV4V6Regex = new RegExp("^\\s*((([0-9A-Fa-f]{1,4}:){7}(([0-9A-Fa-f]{1,4})|:))|(([0-9A-Fa-f]{1,4}:){6}(:|((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})|(:[0-9A-Fa-f]{1,4})))|(([0-9A-Fa-f]{1,4}:){5}((:((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){4}(:[0-9A-Fa-f]{1,4}){0,1}((:((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){3}(:[0-9A-Fa-f]{1,4}){0,2}((:((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}((:((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)(:[0-9A-Fa-f]{1,4}){0,4}((:((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(:(:[0-9A-Fa-f]{1,4}){0,5}((:((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})))(%.+)?\\s*(?:\\/[1-9]|\\/[0-9]\\d|\\/[0-1][0-2][0-8])?$");

  Group.prototype.__isValidIpV4 = function(value) {
    return Group.ipV4Regex.test(value);
  };

  Group.prototype.__isValidIpV4V6 = function(value) {
    return this.__isValidIpV4(value) || Group.ipV4V6Regex.test(value);
  };

  return Group;

})(SystemListManagerItem);
// Generated by CoffeeScript 1.12.7
var SystemGroup,
  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;

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

  function SystemGroup() {
    this.getGeneralFields = bind(this.getGeneralFields, this);
    return SystemGroup.__super__.constructor.apply(this, arguments);
  }

  SystemGroup.prototype.getGeneralFields = function() {
    return [
      {
        type: CUI.Output,
        name: "_id",
        form: {
          label: $$("admin.group._id")
        }
      }, {
        type: CUI.Output,
        form: {
          label: $$("admin.group.type")
        },
        name: "type",
        placeholder: $$("admin.group.type.new")
      }, {
        type: CUI.MultiOutput,
        control: ez5.loca.getLanguageControlAdmin(),
        name: "displayname",
        form: {
          label: $$("admin.group.displayname")
        },
        user_selectable: ez5.session.getPref("languages_user_selection")
      }, this.getNameField(), {
        type: CUI.Output,
        name: "reference",
        form: {
          label: $$("admin.group.reference")
        }
      }, this.__getUserPreferencesField()
    ];
  };

  SystemGroup.prototype.getSaveData = function() {
    var saveData;
    saveData = SystemGroup.__super__.getSaveData.call(this);
    delete saveData.group.reference;
    return saveData;
  };

  SystemGroup.prototype.renderAuthMappingTab = function() {
    return null;
  };

  SystemGroup.prototype.renderUsersTab = function() {
    return null;
  };

  SystemGroup.prototype.canBeCopied = function() {
    return false;
  };

  SystemGroup.prototype.isDeletable = function() {
    return false;
  };

  SystemGroup.prototype.getNameField = function() {
    return null;
  };

  SystemGroup.prototype.getAuthUrl = function() {
    var ref, ref1;
    switch ((ref = this.getData()) != null ? (ref1 = ref.group) != null ? ref1.reference : void 0 : void 0) {
      case "system::anonymous":
      case "system::all":
        return "anonymous";
    }
    return null;
  };

  return SystemGroup;

})(Group);
// Generated by CoffeeScript 1.12.7
var CustomGroup,
  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;

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

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

  CustomGroup.prototype.getNameField = function() {
    return {
      type: CUI.Output,
      form: {
        label: $$("admin.group.name")
      },
      name: "name"
    };
  };

  CustomGroup.prototype.renderAuthMappingTab = function() {
    return Group.prototype.renderAuthMappingTab.call(this);
  };

  CustomGroup.prototype.renderUsersTab = function() {
    return Group.prototype.renderUsersTab.call(this);
  };

  return CustomGroup;

})(SystemGroup);
// Generated by CoffeeScript 1.12.7
var User,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

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

  User.prototype.readOpts = function() {
    User.__super__.readOpts.call(this);
    if (this._user) {
      this.loadData(this._user);
    } else {
      this.loadData({
        _basetype: "user",
        _groups: [],
        _system_rights: {},
        _emails: [],
        _collection_pin_codes: [],
        user: {
          type: "easydb",
          custom_data: {}
        }
      });
    }
    this.__plugins = User.plugins.newPlugins({
      user: this
    });
    this.__plugins = this.__plugins.filter(function(plugin) {
      return plugin.isAllowed();
    });
  };

  User.defaultPicName = "user_avatar";

  User.prototype.setStatus = function() {
    var ref, ref1;
    User.__super__.setStatus.call(this);
    if (ez5.version("6") && !this.data.user.login && !this.data.user.email) {
      if ((ref = this.saveButton) != null) {
        ref.disable();
      }
    }
    if (this.data._archived_at) {
      if ((ref1 = this.saveButton) != null) {
        ref1.disable();
      }
    }
  };

  User.prototype.managerInstance = function() {
    return UserManager;
  };

  User.prototype.getExtraButtons = function() {
    var buttons;
    buttons = User.__super__.getExtraButtons.call(this);
    if (ez5.version("6") && this.data._archived_at) {
      this.unarchiveButton = new CUI.Button({
        primary: true,
        text: $$("admin.user.unarchive"),
        onClick: (function(_this) {
          return function(ev) {
            _this.unarchiveButton.disable();
            return _this.unarchive(ev);
          };
        })(this)
      });
      buttons.push(this.unarchiveButton);
    }
    return buttons;
  };

  User.prototype.unarchive = function() {
    return CUI.confirm({
      title: $$("admin.user.unarchive.title"),
      markdown: true,
      button_primary: "cancel",
      text: $$("admin.user.unarchive.message")
    }).done((function(_this) {
      return function() {
        return ez5.api.user({
          type: "DELETE",
          api: "/" + _this.data.user._id + "?delete_policy=unarchive&confirm=delete"
        }).done(function(data) {
          try {
            return _this.remove();
          } catch (error) {}
        });
      };
    })(this)).fail((function(_this) {
      return function() {
        return _this.unarchiveButton.enable();
      };
    })(this));
  };

  User.prototype.getPrimaryEmail = function() {
    var email, j, len, ref;
    if (!this.data._emails) {
      return "";
    }
    ref = this.data._emails;
    for (j = 0, len = ref.length; j < len; j++) {
      email = ref[j];
      if (email.is_primary) {
        return email.email;
      }
    }
    return "";
  };

  User.prototype.getCollectionReference = function() {
    if (!CUI.util.isEmpty(this.data.user.reference)) {
      return "user:ref:" + this.data.user.reference;
    } else {
      return "user:id:" + this.data.user._id;
    }
  };

  User.prototype.getData = function() {
    return this.data;
  };

  User.prototype.getCSVDataRow = function() {
    var _groups, _grp, add_data, dfr, email, emails, groups, groups_by_type, grp, idx, j, k, key, l, len, len1, ref, ref1, ref2, row, type, v;
    row = [];
    add_data = function(key, value) {
      row.push({
        key: key,
        value: value
      });
    };
    ref = this.data.user;
    for (k in ref) {
      v = ref[k];
      if (CUI.util.isPlainObject(v)) {
        add_data("user." + k, JSON.stringify(v));
      } else {
        add_data("user." + k, v);
      }
    }
    groups = [];
    groups_by_type = {};
    ref1 = this.data._groups;
    for (j = 0, len = ref1.length; j < len; j++) {
      grp = ref1[j];
      groups.push(grp.group._id);
      _grp = ez5.groupManager.getGroupById(grp.group._id);
      if (!_grp || _grp instanceof SystemGroup) {
        continue;
      }
      type = _grp.getType();
      if (!groups_by_type[type]) {
        groups_by_type[type] = [];
      }
      groups_by_type[type].push(_grp.getDisplayText());
    }
    for (type in groups_by_type) {
      _groups = groups_by_type[type];
      _groups.sort(function(a, b) {
        return a.localeCompare(b);
      });
      add_data("_groups#" + type, _groups.join(", "));
    }
    add_data("_groups#find", groups.join(","));
    if (!ez5.version("6")) {
      emails = {};
      ref2 = this.data._emails;
      for (idx = l = 0, len1 = ref2.length; l < len1; idx = ++l) {
        email = ref2[idx];
        for (k in email) {
          v = email[k];
          key = "_emails[]." + k;
          if (emails[key] === void 0) {
            emails[key] = [];
          }
          emails[key][idx] = [v];
        }
      }
      for (key in emails) {
        v = emails[key];
        add_data(key, new CUI.CSVData({
          rows: v
        }).toText({
          always_quote: false
        }));
      }
    }
    dfr = new CUI.Deferred();
    dfr.resolve(row);
    return dfr.promise();
  };

  User.prototype.getTrayItems = function(sessionTrayApp) {
    var items;
    return items = [
      {
        text: $$("session.tray.settings.menu"),
        _menu: "settings",
        onClick: (function(_this) {
          return function() {
            return ez5.sessionTray.userSettingsModal();
          };
        })(this)
      }, {
        text: $$("session.tray.change_password"),
        _menu: "change_password",
        hidden: function() {
          return !(ez5.session.hasSystemRight("root", "user.change_password"));
        },
        onClick: (function(_this) {
          return function() {
            return ez5.session.passwordChangeModal();
          };
        })(this)
      }, {
        divider: true
      }, {
        text: $$("session.tray.logout"),
        onClick: (function(_this) {
          return function() {
            return ez5.session.logout();
          };
        })(this)
      }
    ];
  };

  User.prototype.setData = function(data1) {
    this.data = data1;
  };

  User.prototype.getFrontendLanguage = function() {
    return this.data.user.frontend_language;
  };

  User.prototype.copy = function(remove_id) {
    var new_data;
    if (remove_id == null) {
      remove_id = false;
    }
    new_data = CUI.util.copyObject(this.data, true);
    if (remove_id) {
      delete new_data.user._id;
      delete new_data.user._version;
      delete new_data.user._archived_at;
    }
    return new window[CUI.util.getObjectClass(this)]({
      user: new_data
    });
  };

  User.prototype.canBeCopied = function() {
    var ref;
    if (this.getId()) {
      return ((ref = ez5.session.getSystemRight("user")) != null ? ref.create : void 0) || ez5.session.hasSystemRight("root");
    } else {
      return false;
    }
  };

  User.prototype.getCopyAsNewData = function() {
    var group, grp, j, l, len, len1, len2, m, new_data, ref, ref1, ref2, right, sd;
    sd = this.getSaveData();
    new_data = {
      _basetype: "user",
      _emails: [],
      user: {
        type: sd.user.type
      },
      _groups: sd._groups,
      _acl: sd._acl,
      _system_rights: sd._system_rights
    };
    ref = new_data._groups;
    for (j = 0, len = ref.length; j < len; j++) {
      group = ref[j];
      ref1 = this.data._groups;
      for (l = 0, len1 = ref1.length; l < len1; l++) {
        grp = ref1[l];
        if (grp.group._id === group.group._id) {
          group.group = CUI.util.copyObject(grp.group, true);
        }
      }
    }
    if (new_data._acl) {
      ref2 = new_data._acl;
      for (m = 0, len2 = ref2.length; m < len2; m++) {
        right = ref2[m];
        delete right._id;
      }
    }
    return new_data;
  };

  User.prototype.copyAsNew = function() {
    var new_data, new_user;
    new_data = this.getCopyAsNewData();
    new_user = new window[CUI.util.getObjectClass(this)]({
      manager: this._manager,
      user: new_data
    });
    return new_user;
  };

  User.prototype.load = function(ignore_400) {
    var dfr;
    if (ignore_400 == null) {
      ignore_400 = false;
    }
    dfr = User.__super__.load.call(this);
    dfr.fail((function(_this) {
      return function() {
        _this.update();
        _this.manager.empty();
        delete _this.saveButton;
        delete _this.copyButton;
        return delete _this.initialData;
      };
    })(this));
    return dfr;
  };

  User.prototype.loadData = function(data1) {
    var ref;
    this.data = data1;
    User.__super__.loadData.call(this, this.data);
    this.loadGroups();
    if (!this.data.user.frontend_prefs) {
      this.data.user.frontend_prefs = {};
    }
    if (!this.data._collection_pin_codes) {
      this.data._collection_pin_codes = [];
    }
    if (!this.data.user.mail_schedule) {
      this.data.user.mail_schedule = {};
    }
    if (!this.data.user.custom_data) {
      this.data.user.custom_data = {};
    }
    this.id = (ref = this.data) != null ? ref.user._id : void 0;
    return this;
  };

  User.prototype.setDataOfPrefs = function(prefs) {
    var k, uprefs, v;
    uprefs = {};
    for (k in prefs) {
      v = prefs[k];
      if (k === "_undo") {
        continue;
      }
      if (indexOf.call(ez5.session.getCookieOnlyPrefs(), k) >= 0) {
        continue;
      }
      if (k === "database_languages" || k === "search_languages" || k === "frontend_language") {
        this.data.user[k] = v;
      } else if (!CUI.util.isNull(v)) {
        uprefs[k] = v;
      }
    }
    this.data.user.frontend_prefs.webfrontend = uprefs;
    return this;
  };

  User.prototype.newKey = "admin.user.list.name.new";

  User.prototype.renderContent = function() {
    var column, columns, content, firstColumn, getColumnContent, j, len;
    columns = this._manager.getColumns();
    firstColumn = columns.shift();
    getColumnContent = (function(_this) {
      return function(columnName) {
        var id, login, ref;
        switch (columnName) {
          case "name":
            return User.__super__.renderContent.call(_this);
          case "first_name":
            return _this.data.user.first_name || "";
          case "last_name":
            return _this.data.user.last_name || "";
          case "login":
            if (login = _this.getLogin()) {
              return login;
            } else {
              return _this.getEmail() || "";
            }
            break;
          case "type":
            return _this.getType() || "";
          case "id":
            id = _this.getId() || "";
            return "" + id;
          case "_last_seen_at":
            return ez5.format_date_and_time((ref = _this.data) != null ? ref._last_seen_at : void 0) || "";
          case "company":
            return _this.data.user.company || "";
          case "department":
            return _this.data.user.department || "";
          case "town":
            return _this.data.user.town || "";
          case "state":
            return _this.data.user.state || "";
          case "country":
            return _this.data.user.country || "";
        }
      };
    })(this);
    for (j = 0, len = columns.length; j < len; j++) {
      column = columns[j];
      content = getColumnContent(column);
      if (CUI.util.isString(content)) {
        this.addColumn(new CUI.ListViewColumn({
          text: content
        }));
      } else {
        this.addColumn(new CUI.ListViewColumn({
          element: content
        }));
      }
    }
    content = getColumnContent(firstColumn);
    if (!CUI.util.isString(content)) {
      return content;
    }
    return new CUI.Label({
      text: content
    });
  };

  User.prototype.getType = function() {
    return this.data.user.type;
  };

  User.prototype.getEmail = function() {
    if (ez5.version("6")) {
      return this.data.user.email;
    } else {
      return this.data.user._primary_email;
    }
  };

  User.prototype.getLogin = function() {
    return this.data.user.login;
  };

  User.prototype.getAuthUrl = function() {
    switch (this.getType()) {
      case "collection":
        return encodeURIComponent(this.getType()) + "=" + encodeURIComponent(this.getLogin());
      default:
        return "login";
    }
  };

  User.prototype.getId = function() {
    var ref;
    return (ref = this.data.user) != null ? ref._id : void 0;
  };

  User.prototype.getApi = function() {
    return "user";
  };

  User.prototype.getDisplayText = function() {
    return this.get("_generated_displayname", false) || "" + this.id;
  };

  User.prototype.getContent = function(include_email) {
    var dn, email;
    if (include_email == null) {
      include_email = false;
    }
    dn = this.get("_generated_displayname", true);
    if (dn && include_email) {
      email = this.getEmail();
      if (email && email !== dn) {
        dn += " <span class='addon'>" + email + "</span>";
      }
    }
    if (CUI.util.isEmpty(dn)) {
      return this.id + "";
    } else {
      return CUI.dom.htmlToNodes(dn);
    }
  };

  User.prototype.getLimitedSaveData = function(mode) {
    var fields, j, k, len, sd, sd_filtered;
    if (mode == null) {
      mode = "settings";
    }
    CUI.util.assert(mode === "settings" || mode === "register", "User.getLimitedSaveData", "mode needs to be settings or register.", {
      mode: mode
    });
    sd = this.getSaveData();
    sd.user._new_primary_email = this.data.user._new_primary_email;
    sd_filtered = {
      _basetype: sd._basetype,
      _collection_pin_codes: sd._collection_pin_codes,
      user: {}
    };
    fields = ["login", "frontend_prefs", "first_name", "last_name", "displayname", "frontend_language", "database_languages", "search_languages", "company", "department", "address_supplement", "street", "house_number", "postal_code", "town", "country", "phone", "reference", "picture", "mail_schedule", "_new_primary_email", "_password", "_id", "_version"];
    if (ez5.version("6")) {
      fields.push("state");
    }
    for (j = 0, len = fields.length; j < len; j++) {
      k = fields[j];
      if (!((k === "_id" || k === "_version") || this.isAllowedLimited(k, mode))) {
        continue;
      }
      if (sd.user.hasOwnProperty(k)) {
        sd_filtered.user[k] = sd.user[k];
      } else if (sd.hasOwnProperty(k)) {
        sd_filtered[k] = sd[k];
      }
    }
    return sd_filtered;
  };

  User.prototype.isAllowedLimited = function(name, mode) {
    var addressFields, sr;
    CUI.util.assert(mode === "settings" || mode === "register", "User.isAllowedLimited", "mode needs to be settings or register.", {
      mode: mode
    });
    if (name === "theme" || name === "frontend_prefs" || name === "frontend_language" || name === "database_languages" || name === "search_languages") {
      return true;
    }
    if (name === "type") {
      return false;
    }
    if (mode === "settings") {
      if (name === 'login' || name === '_password') {
        return false;
      }
      if (ez5.session.hasSystemRight("root")) {
        return true;
      }
      sr = "user.write_self";
    } else if (mode === "register") {
      sr = "user.create_new";
    }
    if (ez5.session.hasSystemRight(sr)) {
      addressFields = ["address_supplement", "state", "street", "house_number", "postal_code", "town", "country"];
      if (ez5.version("6") && addressFields.includes(name)) {
        name = "address";
      }
      return !!ez5.session.getSystemRight(sr)[name];
    }
    return false;
  };

  User.prototype.saveLimited = function(ev, mode) {
    CUI.util.assert(mode === "settings" || mode === "register", "User.saveLimited", "mode needs to be settings or register.", {
      mode: mode
    });
    return this._save(ev, this.getLimitedSaveData(mode)).done((function(_this) {
      return function(data) {
        if (CUI.util.isArray(data)) {
          return _this.loadData(data[0]);
        } else {
          return _this.loadData(data);
        }
      };
    })(this));
  };

  User.prototype.onSave = function() {
    if (ez5.session.user && this.getId() === ez5.session.user.getId()) {
      ez5.session.reload();
    }
  };

  User.prototype.getSaveData = function() {
    var _email, j, k, keys, l, len, len1, len2, len3, len4, m, mom, n, o, plugin, pw1, pw2, ref, ref1, ref2, ref3, ref4, ref5, ref6, save_data;
    save_data = {
      _basetype: "user",
      user: {
        _id: this.id,
        custom_data: {}
      }
    };
    keys = ["login", "last_name", "type", "frontend_language", "database_languages", "search_languages", "first_name", "displayname", "mail_schedule", "company", "department", "phone", "reference", "remarks", "address_supplement", "street", "house_number", "postal_code", "town", "country"];
    if (ez5.version("6")) {
      keys.push("email");
      keys.push("state");
    }
    for (j = 0, len = keys.length; j < len; j++) {
      k = keys[j];
      if (CUI.util.isEmpty(this.data.user[k])) {
        if (ez5.version("6")) {
          if (k === "database_languages" || k === "search_languages") {
            save_data.user[k] = [];
          } else {
            save_data.user[k] = this.data.user[k];
          }
        } else {
          save_data.user[k] = null;
        }
      } else {
        save_data.user[k] = CUI.util.copyObject(this.data.user[k], true);
      }
    }
    keys = ["login_disabled", "require_password_change"];
    if (ez5.version("6")) {
      keys.push("welcome_email", "confirm_email");
    }
    for (l = 0, len1 = keys.length; l < len1; l++) {
      k = keys[l];
      save_data.user[k] = !!this.data.user[k];
    }
    ref = ["login_valid_from", "login_valid_to"];
    for (m = 0, len2 = ref.length; m < len2; m++) {
      k = ref[m];
      if (!this.data.user[k]) {
        save_data.user[k] = null;
      } else {
        mom = CUI.DateTime.toMoment(this.data.user[k]);
        if (k === "login_valid_to") {
          mom.add(1, "day").subtract(1, "second");
        }
        save_data.user[k] = mom.toISOString();
      }
    }
    if (save_data.user.login && save_data.user.type === "email" && !CUI.EmailInput.regexp.exec(save_data.user.login)) {
      throw new InvalidSaveDataException();
    }
    if (!ez5.version("6")) {
      save_data._emails = CUI.util.copyObject(this.data._emails, true) || [];
      CUI.util.removeFromArray(null, save_data._emails, function(_email) {
        return _email.email.trim() === "";
      });
      ref1 = save_data._emails;
      for (n = 0, len3 = ref1.length; n < len3; n++) {
        _email = ref1[n];
        if (!CUI.EmailInput.regexp.exec(_email.email)) {
          throw new InvalidSaveDataException();
        }
      }
    }
    save_data.user.frontend_prefs = CUI.util.copyObject(this.data.user.frontend_prefs, true);
    if ((ref2 = this.data.user.picture) != null ? ref2._id : void 0) {
      save_data.user.picture = {
        _id: this.data.user.picture._id,
        frontend_prefs: CUI.util.copyObject(this.data.user.picture.frontend_prefs, true)
      };
    } else {
      save_data.user.picture = null;
    }
    if (this.data.set_password) {
      if (this.data.server_set_password) {
        save_data._password = true;
      } else if (CUI.util.isEmpty((ref3 = this.data.password) != null ? ref3.trim() : void 0)) {
        save_data._password = false;
      } else {
        save_data._password = this.data.password.trim();
      }
    }
    if (this.data.user._password1) {
      pw1 = this.data.user._password1.trim();
      pw2 = this.data.user._password2.trim();
      if (pw1 === pw2 && pw1.length > 0) {
        save_data._password = pw1;
      }
    }
    save_data._groups = this.getGroupsSaveData();
    if (this.aclManager) {
      save_data._acl = this.aclManager.getSaveData();
    }
    if (this.systemAclManager) {
      save_data._system_rights = this.systemAclManager.getSaveData();
    }
    if (this.data._collection_pin_codes) {
      save_data._collection_pin_codes = CUI.util.copyObject(this.data._collection_pin_codes, true);
    } else {
      this.data._collection_pin_codes = [];
    }
    ref4 = this.__plugins;
    for (o = 0, len4 = ref4.length; o < len4; o++) {
      plugin = ref4[o];
      plugin.getSaveData(save_data);
    }
    if ((ref5 = this.data.user.type) === "sso" || ref5 === "ldap") {
      delete save_data.user.require_password_change;
      delete save_data.user._password;
    }
    if (((ref6 = this.data.user.mail_schedule) != null ? ref6._preset : void 0) === "none") {
      save_data.user.mail_schedule = {};
    }
    return save_data;
  };

  User.prototype.setPinCode = function(collection_id, pin) {
    var cpc, j, len, ref;
    ref = this.data._collection_pin_codes || [];
    for (j = 0, len = ref.length; j < len; j++) {
      cpc = ref[j];
      if (cpc.collection_id === collection_id) {
        cpc.pin_code = pin;
        return;
      }
    }
    this.data._collection_pin_codes.push({
      collection_id: collection_id,
      pin_code: pin
    });
  };

  User.prototype.getPinCode = function(collection_id) {
    var cpc, j, len, ref;
    ref = this.data._collection_pin_codes || [];
    for (j = 0, len = ref.length; j < len; j++) {
      cpc = ref[j];
      if (cpc.collection_id === collection_id) {
        return cpc.pin_code;
      }
    }
    return "";
  };

  User.prototype.getTabs = function() {
    var j, len, plugin, ref, tabs;
    tabs = [
      {
        ui: "admin-user-general-tab",
        name: "general",
        text: $$("admin.user.tab.general"),
        content: (function(_this) {
          return function() {
            return new CUI.Form({
              fields: _this.getGeneralFields(),
              data: _this.data.user
            }).start();
          };
        })(this)
      }, {
        ui: "admin-user-address-tab",
        name: "address",
        text: $$("admin.user.tab.address"),
        disabled: User.fieldHidden("address"),
        content: (function(_this) {
          return function() {
            return new CUI.Form({
              fields: _this.getAddressFields(),
              data: _this.data.user
            }).start();
          };
        })(this)
      }, {
        ui: "admin-user-management-tab",
        name: "management",
        text: $$("admin.user.tab.management"),
        content: (function(_this) {
          return function() {
            _this.data.user.needs_confirmation = false;
            return new CUI.Form({
              fields: _this.getManagementFields(),
              data: _this.data.user
            }).start();
          };
        })(this)
      }, {
        ui: "admin-user-password-tab",
        name: "password",
        text: $$("admin.user.tab.password"),
        onFirstActivate: (function(_this) {
          return function() {
            return _this.updatePasswordForm();
          };
        })(this),
        content: (function(_this) {
          return function() {
            return _this.password_form = new CUI.Form({
              fields: _this.getPasswordFields(),
              data: _this.data,
              onDataChanged: function() {
                return _this.updatePasswordForm();
              }
            }).start();
          };
        })(this)
      }, this.getGroupsTab(["easydb", "custom", "automatic"], this), this.getSystemRightsTab(), this.getAclTab()
    ];
    ref = this.__plugins;
    for (j = 0, len = ref.length; j < len; j++) {
      plugin = ref[j];
      plugin.getTabs(tabs);
    }
    return tabs;
  };

  User.prototype.getAclTab = function() {
    if (!this.canEditAcl()) {
      return null;
    }
    return {
      ui: "admin-user-acl-tab",
      name: "acl",
      padded: false,
      text: $$("admin.user.tab.acl"),
      content: (function(_this) {
        return function() {
          return _this.renderAclTab();
        };
      })(this)
    };
  };

  User.prototype.getSystemRightsTab = function(checkRights) {
    if (checkRights == null) {
      checkRights = true;
    }
    if (checkRights && !this.canEditSystemRights()) {
      return null;
    }
    return {
      ui: "admin-user-system-acl-tab",
      name: "system_acl",
      text: $$("admin.user.tab.system_acl"),
      content: (function(_this) {
        return function() {
          return _this.renderSystemAclTab();
        };
      })(this)
    };
  };

  User.prototype.renderSystemAclTab = function() {
    this.systemAclManager = new AclRightManager({
      data: this.data,
      name: "_system_rights",
      context: "SystemAclRight"
    });
    return this.systemAclManager.getForm().start();
  };

  User.prototype.renderAclTab = function() {
    this.aclManager = new AclManager({
      data: this.data._acl,
      context: this,
      right: true,
      onUpdate: this.update
    });
    return this.aclManager.getTree();
  };

  User.prototype.deselect = function(ev) {
    return User.__super__.deselect.call(this, ev).done((function(_this) {
      return function() {
        var ref, ref1;
        delete _this.password_form;
        if ((ref = _this.aclManager) != null) {
          ref.destroy();
        }
        if ((ref1 = _this.systemAclManager) != null) {
          ref1.destroy();
        }
        delete _this.aclManager;
        return delete _this.systemAclManager;
      };
    })(this));
  };

  User.prototype.renderPicture = function() {
    var asset, icon, pic, ref, version;
    CUI.util.assert((ref = this.data) != null ? ref.user : void 0, "User.renderPicture", "data.user not found.", {
      data: this.data,
      user: this
    });
    pic = this.data.user.picture;
    if (!pic) {
      pic = ez5.session.getDefaultPicture(User.defaultPicName);
      version = "original";
    } else {
      version = Asset.getStandardVersionName(pic);
    }
    if (pic) {
      asset = new AssetPlain({
        value: pic
      });
      return CUI.dom.append(CUI.dom.div("user-picture"), asset.getImgElement(null, version));
    } else {
      icon = new CUI.Icon({
        "class": "fa-user"
      });
      return CUI.dom.append(icon);
    }
  };

  User.prototype.getGroups = function() {
    var group, groups, j, len, ref;
    groups = [];
    ref = this.data._groups;
    for (j = 0, len = ref.length; j < len; j++) {
      group = ref[j];
      groups.push(Group.newInstance({
        group: group
      }));
    }
    return groups;
  };

  User.prototype.getSystemRights = function() {
    var sr, srs;
    srs = [];
    for (sr in this.data._system_rights) {
      srs.push(ez5.aclRights.byName("SystemAclRight", sr));
    }
    return srs;
  };

  User.prototype.__getGeneralFields = function(mode) {
    var eas_field, f, field, fields, j, k, l, len, len1, len2, m, opts, pluginNames, ref, ref1, sel_field;
    eas_field = new EASField({
      name: "picture",
      "class": "user-picture",
      scale_and_position: true
    });
    if (this.getType() !== "system") {
      opts = [
        {
          text: "easydb",
          value: "easydb"
        }, {
          text: "easydb_self_register",
          value: "easydb_self_register"
        }, {
          text: "email",
          value: "email"
        }
      ];
      pluginNames = ez5.pluginManager.getPluginNames();
      ref = ["sso", "ldap"];
      for (j = 0, len = ref.length; j < len; j++) {
        k = ref[j];
        if (indexOf.call(pluginNames, k) >= 0 || (ref1 = "easydb-" + k + "-plugin", indexOf.call(pluginNames, ref1) >= 0) || ez5.version("6")) {
          opts.push({
            text: k,
            value: k
          });
        }
      }
      sel_field = {
        type: CUI.Select,
        name: "type",
        options: opts,
        onDataChanged: function(_, dataField) {
          return dataField.getForm().getFieldsByName("login")[0].reload();
        }
      };
    } else {
      sel_field = {
        type: CUI.Output,
        name: "type"
      };
    }
    fields = [
      {
        type: CUI.Output,
        name: "_id"
      }, {
        type: CUI.Output,
        data: this.data,
        name: "_owner",
        getValue: function(v) {
          var ref2;
          return v != null ? (ref2 = v[v._basetype]) != null ? ref2._generated_displayname : void 0 : void 0;
        },
        placeholder: $$("admin.user._owner.new")
      }, sel_field, {
        type: CUI.Input,
        name: "login",
        autocomplete: "username",
        placeholder: (function(_this) {
          return function() {
            if (mode === "register") {
              return void 0;
            } else {
              if (ez5.version("6")) {
                return $$("admin.user.fylr_login_placeholder");
              } else {
                return $$("admin.user.login_placeholder");
              }
            }
          };
        })(this),
        checkInput: (function(_this) {
          return function(login) {
            if (_this.data.user.type !== "email") {
              return true;
            }
            return !!CUI.EmailInput.regexp.exec(login);
          };
        })(this)
      }, {
        type: CUI.Input,
        name: "first_name",
        autocomplete: "given-name"
      }, {
        type: CUI.Input,
        name: "last_name",
        autocomplete: "family-name"
      }, {
        type: CUI.Input,
        name: "displayname",
        autocomplete: "nickname"
      }, {
        type: CUI.Input,
        name: "company",
        autocomplete: "organization"
      }, {
        type: CUI.Input,
        name: "department"
      }, {
        type: CUI.Input,
        name: "phone",
        autocomplete: "tel"
      }, {
        type: CUI.DataFieldProxy,
        name: "picture",
        element: eas_field.renderEditorInput(this.data.user, User.defaultPicName)
      }, {
        type: CUI.Input,
        textarea: true,
        name: "remarks"
      }, {
        type: this.getReferenceFieldType(),
        name: "reference"
      }
    ];
    if (ez5.version("6")) {
      fields.push({
        type: CUI.Output,
        data: this.data,
        name: "_created_at",
        getValue: (function(_this) {
          return function(v) {
            return ez5.format_date_and_time(v, true);
          };
        })(this)
      }, {
        type: CUI.Output,
        data: this.data,
        name: "_updated_at",
        getValue: (function(_this) {
          return function(v) {
            return ez5.format_date_and_time(v, true);
          };
        })(this)
      }, {
        type: CUI.Output,
        data: this.data,
        name: "_last_seen_at",
        getValue: (function(_this) {
          return function(v) {
            return ez5.format_date_and_time(v, true);
          };
        })(this)
      });
    } else {
      fields.push({
        type: CUI.Output,
        name: "created_timestamp",
        getValue: (function(_this) {
          return function(v) {
            return ez5.format_date_and_time(v, true);
          };
        })(this)
      }, {
        type: CUI.Output,
        name: "last_updated_timestamp",
        getValue: (function(_this) {
          return function(v) {
            return ez5.format_date_and_time(v, true);
          };
        })(this)
      });
    }
    if (this.data._archived_at) {
      fields.push({
        type: CUI.Output,
        data: this.data,
        name: "_archived_at",
        getValue: (function(_this) {
          return function(v) {
            return ez5.format_date_and_time(v, true);
          };
        })(this)
      });
    }
    if (mode !== "register") {
      for (l = 0, len1 = fields.length; l < len1; l++) {
        field = fields[l];
        if (field.hasOwnProperty("autocomplete")) {
          delete field.autocomplete;
        }
      }
    }
    for (m = 0, len2 = fields.length; m < len2; m++) {
      f = fields[m];
      if (User.fieldHidden(f.name)) {
        f.hidden = true;
      }
    }
    return fields;
  };

  User.prototype.getReferenceFieldType = function() {
    return CUI.Input;
  };

  User.prototype.getUserSelfManagementFields = function(mode) {
    var check_pw, currentEmailKey, em, email_input_hint, f, fields, j, l, len, len1, loca_key, newEmailKey, policy_txt, ref, ref1;
    if (mode == null) {
      mode = "settings";
    }
    fields = [];
    CUI.util.assert(mode === "settings" || mode === "register", "User.getUserSelfManagementFields", "mode needs to be settings or register.", {
      mode: mode
    });
    if (!CUI.util.isEmpty(this.data.user.login)) {
      fields.push({
        type: CUI.Output,
        name: "login"
      });
    }
    ref = this.__getGeneralFields(mode);
    for (j = 0, len = ref.length; j < len; j++) {
      f = ref[j];
      if (this.isAllowedLimited(f.name, mode)) {
        fields.push(f);
      }
    }
    ref1 = this.__getAddressFields(mode);
    for (l = 0, len1 = ref1.length; l < len1; l++) {
      f = ref1[l];
      if (this.isAllowedLimited(f.name, mode)) {
        fields.push(f);
      }
    }
    if (ez5.version("6")) {
      currentEmailKey = "email";
    } else {
      newEmailKey = "_new_primary_email";
      currentEmailKey = "_primary_email";
    }
    if (mode === "settings") {
      fields.push({
        type: CUI.Output,
        name: currentEmailKey,
        form: {
          grid: "1/1"
        },
        placeholder: $$("admin.user._primary_email.placeholder")
      });
    }
    if (newEmailKey && this.isAllowedLimited(newEmailKey, mode)) {
      em = this.data.user._new_primary_email;
      if (!CUI.util.isEmpty(em)) {
        email_input_hint = $$("admin.user._new_primary_email_requested", {
          email: em
        });
      }
      this.data.user._new_primary_email = "";
      if (CUI.util.isEmpty(this.data.user._primary_email)) {
        loca_key = "admin.user._new_primary_email.create";
      } else {
        loca_key = "admin.user._new_primary_email";
      }
      fields.push({
        type: CUI.EmailInput,
        form: {
          loca_key: loca_key,
          hint: email_input_hint,
          grid: "1/1"
        },
        placeholder: em,
        name: newEmailKey
      });
    }
    if (this.isAllowedLimited("mail_schedule", mode)) {
      fields.push({
        type: CUI.Form,
        name: "mail_schedule",
        fields: ScheduleEditor.getFields()
      });
    }
    if (this.isAllowedLimited("_password", mode)) {
      check_pw = (function(_this) {
        return function(data, df) {
          var hint, pw1, pw2;
          pw1 = data._password1.trim();
          pw2 = data._password2.trim();
          if (pw1 !== pw2 && pw1.length > 0 && pw2.length > 0) {
            hint = $$("auth.error.passwords_dont_match");
          } else {
            hint = "";
          }
          return df.getForm().updateHint("_password2", hint, !window.bowser.msie);
        };
      })(this);
      policy_txt = ez5.loca.getBestFrontendValue(ez5.session.getBaseConfig()["login.password_policy"].hint);
      fields.push.apply(fields, [
        {
          type: CUI.Password,
          undo_and_changed_support: false,
          name: "_password1",
          form: {
            hint: policy_txt
          }
        }, {
          type: CUI.Password,
          undo_and_changed_support: false,
          name: "_password2",
          onDataChanged: check_pw,
          form: {
            hint: ""
          }
        }
      ]);
    }
    if (mode === "settings") {
      fields.push({
        type: CUI.DataFieldProxy,
        name: "_groups",
        form: {
          label: $$("admin.user.groups.label"),
          grid: "1/1"
        },
        element: (function(_this) {
          return function() {
            var group, len2, m, ref2, rows, table;
            rows = [];
            ref2 = ez5.session.getGroups();
            for (m = 0, len2 = ref2.length; m < len2; m++) {
              group = ref2[m];
              rows.push([group.getDisplayText(), group.getType()]);
            }
            table = new CUI.Table({
              rows: rows,
              bordered: true,
              "class": "user-settings-group-table",
              columns: [
                {
                  name: $$("admin.group.list.name")
                }, {
                  name: $$("admin.group.list.type")
                }
              ]
            });
            return table;
          };
        })(this)
      });
    }
    return User.initFields(fields, {
      grid: "1/2"
    });
  };

  User.prototype.getUserSelfManagementFieldsNotOk = function(mode, data) {
    var field_names, j, k, keys, len, ref;
    keys = [];
    if (mode === 'register') {
      keys.push.apply(keys, ["login", "_new_primary_email", "_password"]);
    }
    field_names = [];
    for (j = 0, len = keys.length; j < len; j++) {
      k = keys[j];
      switch (k) {
        case "_password":
          if (CUI.util.isEmpty(data != null ? data[k] : void 0)) {
            field_names.push("_password1");
            field_names.push("_password2");
          }
          break;
        default:
          if (CUI.util.isEmpty(data != null ? (ref = data.user) != null ? ref[k] : void 0 : void 0)) {
            field_names.push(k);
          }
      }
    }
    return field_names;
  };

  User.prototype.getGeneralFields = function(mode) {
    return User.initFields(this.__getGeneralFields(mode));
  };

  User.prototype.getAddressFields = function(mode) {
    return User.initFields(this.__getAddressFields(mode));
  };

  User.prototype.__getAddressFields = function() {
    var autocompleteNames, fields, i, j, k, len, names;
    fields = [];
    names = ["address_supplement", "street", "house_number", "postal_code", "town"];
    autocompleteNames = ["address-line2", "address-line1", "address-line3", "postal-code", "address-level1"];
    if (ez5.version("6")) {
      names.push("state");
      autocompleteNames.push("address-level2");
    }
    names.push("country");
    autocompleteNames.push("country");
    for (i = j = 0, len = names.length; j < len; i = ++j) {
      k = names[i];
      fields.push({
        type: CUI.Input,
        name: k,
        autocomplete: autocompleteNames[i]
      });
    }
    return fields;
  };

  User.prototype.updatePasswordForm = function() {
    var fields, j, k, len, placeholder, ref, ref1;
    if ((ref = this.data.user.type) === "ldap" || ref === "sso") {
      return;
    }
    fields = {};
    ref1 = ["server_set_password", "password"];
    for (j = 0, len = ref1.length; j < len; j++) {
      k = ref1[j];
      fields[k] = this.password_form.getFieldsByName(k)[0];
    }
    placeholder = "";
    if (this.data.set_password) {
      fields.server_set_password.enable();
      if (!this.data.server_set_password) {
        fields.password.enable();
        placeholder = "hint_delete";
      } else {
        fields.password.disable();
        placeholder = "hint_server";
      }
    } else {
      fields.server_set_password.disable();
      fields.password.disable();
    }
    if (placeholder) {
      placeholder = $$("admin.user.password." + placeholder);
    }
    fields.password.getElement().setAttribute("placeholder", placeholder);
    if (ez5.version("6")) {
      fields.server_set_password.disable();
      fields.server_set_password.hide();
    }
    return this;
  };

  User.prototype.isWritable = function() {
    var ref;
    if (!this.getId() || ((ref = this.data._generated_rights) != null ? ref.write : void 0)) {
      return true;
    } else {
      return false;
    }
  };

  User.prototype.canEditSystemRights = function() {
    if (!this.getId()) {
      return this.isWritable() && (ez5.session.hasSystemRight("user[create_system_rights]") || ez5.session.hasSystemRight("root"));
    } else {
      return this.isWritable() && (ez5.session.hasSystemRight("user[edit_system_rights]") || ez5.session.hasSystemRight("root"));
    }
  };

  User.prototype.canEditAcl = function() {
    if (!this.getId()) {
      return this.isWritable() && (ez5.session.hasSystemRight("user[create_acl]") || ez5.session.hasSystemRight("root"));
    } else {
      return this.isWritable() && (ez5.session.hasSystemRight("user[edit_acl]") || ez5.session.hasSystemRight("root"));
    }
  };

  User.prototype.isDeletable = function() {
    var ref;
    if (!this.getId() || ((ref = this.data._generated_rights) != null ? ref["delete"] : void 0)) {
      return true;
    } else {
      return false;
    }
  };

  User.prototype.getEmailFields = function() {
    if (!this.data.user.mail_schedule.timezone) {
      this.data.user.mail_schedule.timezone = CUI.Timezone.getTimezone();
    }
    return User.initFields([
      {
        type: CUI.EmailInput,
        name: "email"
      }, {
        type: CUI.Checkbox,
        name: "confirm_email"
      }, {
        type: CUI.Output,
        name: "confirm_email_sent_at",
        getValue: function(v) {
          if (!v) {
            this.addClass("cui-empty-label");
            return $$("admin.user.confirm_email_sent_at.empty");
          }
          return ez5.format_date_and_time(v, true);
        }
      }, {
        type: CUI.Output,
        name: "email_confirmed_at",
        getValue: function(v) {
          if (!v) {
            this.addClass("cui-empty-label");
            return $$("admin.user.email_confirmed_at.empty");
          }
          return ez5.format_date_and_time(v, true);
        }
      }, {
        type: CUI.Checkbox,
        name: "welcome_email"
      }, {
        type: CUI.Output,
        name: "welcome_email_sent_at",
        getValue: function(v) {
          if (!v) {
            this.addClass("cui-empty-label");
            return $$("admin.user.welcome_email_sent_at.empty");
          }
          return ez5.format_date_and_time(v, true);
        }
      }, {
        type: CUI.Form,
        name: "mail_schedule",
        form: {
          label: $$("admin.user.schedule")
        },
        fields: ScheduleEditor.getFields({
          show_minutes: ez5.session.isDebug()
        })
      }
    ]);
  };

  User.prototype.getManagementFields = function() {
    if (ez5.version("6")) {
      return this.getEmailFields();
    }
    if (!this.data.user.mail_schedule.timezone) {
      this.data.user.mail_schedule.timezone = CUI.Timezone.getTimezone();
    }
    return User.initFields([
      {
        type: CUI.DataTable,
        name: "_emails",
        maximize_horizontal: true,
        data: this.data,
        fields: [
          {
            type: CUI.EmailInput,
            name: "email",
            maximize_horizontal: true
          }, {
            type: CUI.DataFieldProxy,
            name: "requested_confirmation_date",
            element: (function(_this) {
              return function(field) {
                var checkbox, data, label;
                data = field.getData();
                if (!data.requested_confirmation_date) {
                  return new CUI.EmptyLabel();
                }
                label = new CUI.Label({
                  text: ez5.format_date_and_time(data.requested_confirmation_date)
                });
                if (data.confirmed_date) {
                  return label;
                }
                checkbox = new CUI.Checkbox({
                  data: {},
                  text: $$("admin.user._emails.cancel_confirmation"),
                  name: "cancel_confirmation",
                  onDataChanged: function(checkboxData) {
                    return data.cancel_confirmation = checkboxData.cancel_confirmation;
                  }
                });
                return new CUI.VerticalList({
                  content: [label, checkbox]
                });
              };
            })(this)
          }, {
            type: CUI.Output,
            name: "confirmed_date",
            getValue: function(v) {
              return ez5.format_date_and_time(v);
            }
          }, {
            type: CUI.Checkbox,
            name: "needs_confirmation",
            form: {
              rotate_90: true
            }
          }, {
            type: CUI.Checkbox,
            name: "use_for_login",
            form: {
              rotate_90: true
            }
          }, {
            type: CUI.Checkbox,
            name: "use_for_email",
            form: {
              rotate_90: true
            }
          }, {
            type: CUI.Checkbox,
            name: "send_email",
            form: {
              rotate_90: true
            }
          }, {
            type: CUI.Checkbox,
            name: "send_email_include_password",
            form: {
              rotate_90: true
            }
          }, {
            type: CUI.Checkbox,
            name: "send_email_welcome_now",
            form: {
              rotate_90: true
            }
          }, {
            type: CUI.Checkbox,
            name: "is_primary",
            form: {
              rotate_90: true
            }
          }, {
            type: CUI.Checkbox,
            name: "intended_primary",
            form: {
              rotate_90: true
            }
          }
        ]
      }, {
        type: CUI.Form,
        name: "mail_schedule",
        form: {
          label: $$("admin.user.schedule")
        },
        undo_support: false,
        fields: ScheduleEditor.getFields()
      }
    ]);
  };

  User.prototype.getPasswordFields = function() {
    var fields, ref;
    fields = [
      {
        type: CUI.DateTime,
        name: "login_valid_from",
        display_type: "short",
        input_types: ["date", "year_month", "year"],
        data: this.data.user,
        disabled: this.data.user.reference === "system:root"
      }, {
        type: CUI.DateTime,
        name: "login_valid_to",
        display_type: "short",
        input_types: ["date", "year_month", "year"],
        data: this.data.user,
        disabled: this.data.user.reference === "system:root"
      }, {
        type: CUI.Checkbox,
        name: "login_disabled",
        data: this.data.user,
        disabled: this.data.user.reference === "system:root" && !ez5.version("6")
      }
    ];
    if ((ref = this.data.user.type) !== "ldap" && ref !== "sso") {
      fields = fields.concat([
        {
          type: CUI.Checkbox,
          name: "set_password"
        }, {
          type: CUI.Checkbox,
          name: "server_set_password"
        }, {
          type: CUI.Input,
          name: "password",
          autocomplete: "new-password"
        }, {
          type: CUI.Checkbox,
          name: "require_password_change",
          data: this.data.user
        }
      ]);
    }
    return User.initFields(fields);
  };

  User.prototype.renderCard = function() {
    var name, uc;
    uc = new CUI.Template({
      name: "user-card",
      map_prefix: "ez5-user-card",
      map: {
        avatar: true,
        name: true,
        email: true
      }
    });
    uc.replace(this.renderPicture(), "avatar");
    name = ((this.get("first_name") || "") + " " + (this.get("last_name") || "")).trim();
    if (name === "") {
      name = this.getDisplayText();
    }
    uc.replace(CUI.util.toHtml(name), "name");
    uc.replace(CUI.util.toHtml(this.getPrimaryEmail()), "email");
    return uc;
  };

  User.prototype.hasFlatTrayItems = function() {
    return false;
  };

  User.initFields = function(fields, form_opts) {
    var _f, f, j, l, len, len1, ref, set_label;
    if (form_opts == null) {
      form_opts = {};
    }
    set_label = function(field, default_label) {
      var k, label, v;
      if (!field.form) {
        if (field.type === CUI.Checkbox) {
          if (!field.text) {
            field.text = $$(default_label);
          }
          return;
        }
        field.form = {};
      }
      for (k in form_opts) {
        v = form_opts[k];
        if (!field.form.hasOwnProperty(k)) {
          field.form[k] = v;
        }
      }
      if (field.form.use_field_as_label) {
        return;
      }
      if (field.form.loca_key) {
        label = field.form.loca_key;
      } else {
        label = default_label;
      }
      if (field.form.label === void 0) {
        field.form.label = $$(label);
      }
      if (ez5.loca.has(label + "|hint")) {
        field.form.hint = $$(label + "|hint");
      }
      if (ez5.loca.has(label + "|hint_icon")) {
        return field.form.hint_icon = $$(label + "|hint_icon");
      }
    };
    for (j = 0, len = fields.length; j < len; j++) {
      f = fields[j];
      set_label(f, "admin.user." + f.name);
      if (f.fields) {
        ref = f.fields;
        for (l = 0, len1 = ref.length; l < len1; l++) {
          _f = ref[l];
          set_label(_f, "admin.user." + f.name + "." + _f.name);
        }
      }
    }
    return fields;
  };

  User.getUserClassByData = function(data) {
    switch (data.user.type) {
      case "system":
        return ez5.defaults["class"].SystemUser;
      case "anonymous":
        return ez5.defaults["class"].AnonymousUser;
      default:
        return ez5.defaults["class"].User;
    }
  };

  User.newInstance = function(opts) {
    var cls;
    cls = ez5.defaults["class"].User.getUserClassByData(opts.user);
    return new cls(opts);
  };

  User.fieldHidden = function(field) {
    var ref, ref1;
    if (!ez5.version("6")) {
      return false;
    }
    if (!((ref = ez5.session.getBaseConfig()["register"]) != null ? (ref1 = ref.form) != null ? ref1.use_in_user_manager : void 0 : void 0)) {
      return false;
    }
    if (field === "name") {
      return User.fieldHidden("displayname");
    }
    return ez5.session.getBaseConfig()["register"].form[field] === "hide";
  };

  return User;

})(SystemListManagerItem);
// Generated by CoffeeScript 1.12.7
var AnonymousUser,
  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;

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

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

  AnonymousUser.prototype.getTrayItems = function() {
    var ref, showRegister;
    if (ez5.version("6")) {
      showRegister = (ref = ez5.session.getBaseConfig().register) != null ? ref.enable : void 0;
    } else {
      showRegister = ez5.session.hasSystemRight("user.create_new");
    }
    return [
      {
        loca_key: "session.tray.login",
        onClick: (function(_this) {
          return function() {
            return ez5.session.loginAgain();
          };
        })(this)
      }, showRegister ? {
        loca_key: "session.tray.register",
        onClick: (function(_this) {
          return function() {
            if (ez5.version("6")) {
              return document.location.href = ez5.getAbsoluteURL("/api/page/register?redirect=" + encodeURIComponent(document.location.href));
            } else {
              return ez5.sessionTray.userRegisterModal();
            }
          };
        })(this)
      } : void 0
    ];
  };

  AnonymousUser.prototype.hasFlatTrayItems = function() {
    return true;
  };

  return AnonymousUser;

})(User);
// Generated by CoffeeScript 1.12.7
var SystemUser,
  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;

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

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

  SystemUser.prototype.isDeletable = function() {
    return false;
  };

  SystemUser.prototype.getSaveData = function() {
    var save_data;
    save_data = SystemUser.__super__.getSaveData.call(this);
    delete save_data.user.login;
    delete save_data._acl;
    delete save_data._groups;
    delete save_data.user.reference;
    return save_data;
  };

  SystemUser.prototype.getReferenceFieldType = function() {
    return CUI.Output;
  };

  SystemUser.prototype.getCollectionReference = function() {
    if (CUI.util.isEmpty(this.data.user.reference)) {
      return "user:ref:system:" + this.data.user.login;
    } else {
      return "user:ref:" + this.data.user.reference;
    }
  };

  SystemUser.prototype.getGroupsTab = function() {
    return null;
  };

  SystemUser.prototype.getAclTab = function() {
    return null;
  };

  SystemUser.prototype.getSystemRightsTab = function() {
    if (ez5.session.hasSystemRight("root") && this.getId() !== 1 && ez5.version("6.5")) {
      return SystemUser.__super__.getSystemRightsTab.call(this, false);
    } else {
      return null;
    }
  };

  SystemUser.prototype.canBeCopied = function() {
    return false;
  };

  return SystemUser;

})(User);
// Generated by CoffeeScript 1.12.7
var Pool, PoolForPoolManagerPoolField,
  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;

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

  function Pool() {
    this.renderTransitionsTab = bind(this.renderTransitionsTab, this);
    this.initTagData = bind(this.initTagData, this);
    this.getChildren = bind(this.getChildren, this);
    this.hasChildren = bind(this.hasChildren, this);
    return Pool.__super__.constructor.apply(this, arguments);
  }

  Pool.prototype.initOpts = function() {
    Pool.__super__.initOpts.call(this);
    return this.addOpts({
      pool: {
        check: "PlainObject"
      },
      id_parent: {
        check: function(v) {
          return v > 0;
        }
      },
      copy: {
        "default": false,
        check: Boolean
      }
    });
  };

  Pool.prototype.readOpts = function() {
    Pool.__super__.readOpts.call(this);
    this.__plugins = Pool.plugins.newPlugins({
      pool: this
    });
    if (this._pool) {
      return this.setData(this._pool);
    } else {
      return this.setData({
        pool: {
          _id: null,
          _id_parent: this.opts.id_parent,
          mapping_dc_export: "parent",
          mapping_image_export: "parent",
          mapping_image_import: "parent",
          custom_data: {},
          janitor_policy: {}
        },
        _standard_masks: []
      });
    }
  };

  Pool.prototype.setData = function(data1) {
    this.data = data1;
    this.data._basetype = "pool";
    this.id = this.data.pool._id;
    if (!this.data.pool) {
      this.data.pool = {};
    }
    if (!this.data.pool.custom_data) {
      this.data.pool.custom_data = {};
    }
    if (ez5.version("6")) {
      if (!this.data.pool.janitor_policy) {
        this.data.pool.janitor_policy = {};
        this.data.pool.janitor_policy.override_parent = false;
      } else {
        if (!this.data.pool.janitor_policy.hasOwnProperty("override_parent")) {
          this.data.pool.janitor_policy.override_parent = true;
        }
      }
    }
  };

  Pool.prototype.getData = function() {
    return this.data;
  };

  Pool.prototype.getShortname = function() {
    return this.data.pool.shortname;
  };

  Pool.prototype.getId = function() {
    return this.id;
  };

  Pool.prototype.isRootPool = function() {
    var ref;
    if (!((ref = this.data) != null ? ref.pool : void 0)) {
      return false;
    } else if (this.data.pool._id_parent) {
      return false;
    } else {
      return true;
    }
  };

  Pool.prototype.managerInstance = function() {
    return PoolManager;
  };

  Pool.prototype.hasChildren = function() {
    return this.data._has_children;
  };

  Pool.prototype.getSortName = function() {
    var parts;
    parts = [];
    parts.push(ez5.loca.getBestFrontendValue(this.data.pool.name).toLocaleUpperCase());
    if (this.father) {
      parts.push(this.father.getSortName());
    }
    return parts.join("||");
  };

  Pool.prototype.getChildren = function() {
    CUI.util.assertInstanceOf("manager", PoolManager, this._manager);
    return this.manager.loadList(null, {
      parentId: this.id
    });
  };

  Pool.prototype.newKey = "admin.pool.list.name.new";

  Pool.prototype.getDisplayText = function() {
    return this.get("name", false);
  };

  Pool.prototype.getEventInfo = function() {
    var ref;
    return {
      id: this.getId() || void 0,
      shortname: this.getShortname() || void 0,
      name: ((ref = this.getData().pool) != null ? ref.name : void 0) || ""
    };
  };

  Pool.prototype.getContent = function() {
    var content;
    content = CUI.dom.append(CUI.dom.span("ez-pool"), CUI.dom.htmlToNodes(this.get("name", true)));
    CUI.dom.setAttribute(content, "ui", "pool.item.content");
    return content;
  };

  Pool.prototype.isWritable = function() {
    if (!this.getId() || this.data._generated_rights.bag_write) {
      return true;
    } else {
      return false;
    }
  };

  Pool.prototype.canWriteAcl = function() {
    if (!this.getId() || this.data._generated_rights.bag_acl) {
      return true;
    } else {
      return false;
    }
  };

  Pool.prototype.isCreateChildAllowed = function() {
    var ref;
    if ((ref = this.data._generated_rights) != null ? ref.bag_create : void 0) {
      return true;
    } else {
      return false;
    }
  };

  Pool.prototype.isDeletable = function() {
    if (!this.getId() || this.data._generated_rights.bag_delete) {
      return true;
    } else {
      return false;
    }
  };

  Pool.prototype.canChangeParent = function() {
    if (!ez5.version("6.8")) {
      return false;
    }
    if (this.isSystemPool()) {
      return false;
    }
    if (!ez5.session.hasSystemRight("system.root")) {
      return false;
    }
    if (!this.canWriteAcl()) {
      return false;
    }
    return true;
  };

  Pool.prototype.canChangeOwner = function() {
    if (this.isSystemPool()) {
      return false;
    } else if (!this.getId()) {
      return false;
    } else if (!ez5.session.hasSystemRight("system.root")) {
      return false;
    } else {
      return true;
    }
  };

  Pool.prototype.isStandardPool = function() {
    return this.isSystemPool() && !this.isRootPool();
  };

  Pool.prototype.isSystemPool = function() {
    return this.data.pool.is_system_pool;
  };

  Pool.prototype.copyAsNew = function() {
    var acl, i, k, len, new_data, ref, ref1, v;
    new_data = this.getSaveData();
    ref = new_data.pool.name;
    for (k in ref) {
      v = ref[k];
      if (!CUI.util.isEmpty(v)) {
        new_data.pool.name[k] = $$("pool.copy_as_new", {
          name: v
        });
      }
    }
    new_data.pool._id_parent = this.data.pool._id_parent;
    delete new_data.pool._id;
    delete new_data.pool._version;
    if (new_data.pool.reference) {
      delete new_data.pool.reference;
    }
    if (new_data._acl) {
      ref1 = new_data._acl;
      for (i = 0, len = ref1.length; i < len; i++) {
        acl = ref1[i];
        delete acl._id;
      }
    }
    return new Pool({
      manager: this.manager,
      pool: new_data,
      copy: true
    });
  };

  Pool.prototype.canHaveChildren = function() {
    return !this.isRoot();
  };

  Pool.prototype.canBeCopied = function() {
    return !this.isRootPool() && !this.isRoot() && this.getId() && this.father.isCreateChildAllowed();
  };

  Pool.prototype.isSelectable = function() {
    return Pool.__super__.isSelectable.call(this);
  };

  Pool.prototype.canSetParent = function() {
    return !this.data.pool.is_system_pool;
  };

  Pool.prototype.getNewChild = function() {
    CUI.util.assertInstanceOf("manager", PoolManager, this._manager);
    return new Pool({
      manager: this.manager,
      id_parent: this.id
    });
  };

  Pool.prototype.newText = function() {
    var ref, txt;
    txt = ez5.loca.getBestFrontendValue((ref = this.data) != null ? ref.pool.name : void 0);
    if (CUI.util.isEmpty(txt)) {
      return Pool.__super__.newText.call(this);
    } else {
      return txt;
    }
  };

  Pool.prototype.getContact = function() {
    var ref;
    if ((ref = this.data) != null ? ref.pool.contact : void 0) {
      return User.newInstance({
        user: this.data.pool.contact
      });
    } else {
      return null;
    }
  };

  Pool.prototype.getDescription = function() {
    var ref;
    return ez5.loca.getBestFrontendValue((ref = this.data) != null ? ref.pool.description : void 0);
  };

  Pool.prototype.getInfoDiv = function() {
    var arr, contact, i, j, len, len1, p, pool_ids, ref, ref1, rows, share_url;
    arr = [];
    rows = [];
    if (!CUI.util.isEmpty(this.getDescription())) {
      arr.push(new CUI.MultilineLabel({
        "class": "ez5-hint-popover-description",
        markdown: true,
        text: this.getDescription()
      }));
      this.addClass("ez5-has-description");
    }
    pool_ids = (function() {
      var i, len, ref, results;
      ref = this.find();
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        p = ref[i];
        results.push(p.getId());
      }
      return results;
    }).call(this);
    contact = this.getContact();
    if (contact) {
      rows.push({
        key: new CUI.Label({
          text: $$("pool.info.contact")
        }),
        value: new CUI.Label({
          text: contact.getDisplayText()
        })
      });
    }
    if (this.getShortname()) {
      share_url = document.location.origin + "/pool/" + this.getShortname();
      if (window.easydb_server_url) {
        share_url += "?server=" + encodeURI(window.easydb_server_url);
      }
    } else {
      share_url = document.location.origin + "/search?p=" + pool_ids.join(",");
      if (window.easydb_server_url) {
        share_url += "&server=" + encodeURI(window.easydb_server_url);
      }
    }
    rows.push({
      key: new CUI.Label({
        text: $$("pool.info.link")
      }),
      value: new CUI.ButtonHref({
        href: share_url,
        appearance: "link",
        text: share_url,
        target: "_blank"
      })
    });
    ref = this.__plugins;
    for (i = 0, len = ref.length; i < len; i++) {
      p = ref[i];
      p.getInfoDivRows(rows);
    }
    arr.push(new CUI.Table({
      rows: rows,
      key_value: true
    }));
    ref1 = this.__plugins;
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      p = ref1[j];
      p.getInfoDiv(arr);
    }
    return new CUI.VerticalList({
      content: arr
    });
  };

  Pool.prototype.deselect = function(ev) {
    return Pool.__super__.deselect.call(this, ev).done((function(_this) {
      return function() {
        var ref, ref1, ref2, ref3;
        if ((ref = _this.tagForm) != null) {
          ref.destroy();
        }
        if ((ref1 = _this.transitionForm) != null) {
          ref1.destroy();
        }
        if ((ref2 = _this.aclManager) != null) {
          ref2.destroy();
        }
        if ((ref3 = _this.systemAclManager) != null) {
          ref3.destroy();
        }
        delete _this.tagForm;
        delete _this.transitionForm;
        delete _this.aclManager;
        return delete _this.systemAclManager;
      };
    })(this));
  };

  Pool.prototype.load = function() {
    var dfr, promise;
    dfr = new CUI.Deferred();
    promise = Pool.__super__.load.call(this);
    promise.done((function(_this) {
      return function() {
        var __isConfigEmpty, base, base1, base2, config, fieldName, i, j, k, len, len1, objecttype, oid, padding_str, ref, ref1, ref2, ref3, ref4, ref5, ref6, size_str, standard_masks, table;
        _this.data.standard_masks = {};
        if (CUI.util.isPlainObject(_this.data._standard_masks)) {
          ref = _this.data._standard_masks;
          for (oid in ref) {
            standard_masks = ref[oid];
            if (standard_masks) {
              _this.data.standard_masks[oid] = {
                standard_masks: standard_masks,
                standard_mask_from_objecttype: false
              };
            } else {
              _this.data.standard_masks[oid] = {
                standard_masks: [],
                standard_mask_from_objecttype: true
              };
            }
          }
        }
        ref1 = ez5.schema.CURRENT._objecttypes;
        for (i = 0, len = ref1.length; i < len; i++) {
          table = ref1[i];
          if (table._instance) {
            continue;
          }
          if (!table.pool_link) {
            continue;
          }
          objecttype = new Objecttype(table);
          oid = objecttype.table.id();
          if (_this.data.standard_masks[oid]) {
            continue;
          }
          _this.data.standard_masks[oid] = {
            standard_masks: [],
            standard_mask_from_objecttype: true
          };
        }
        __isConfigEmpty = function(config) {
          var k, v;
          if (CUI.util.isEmpty(config)) {
            return true;
          }
          for (k in config) {
            v = config[k];
            if (!CUI.util.isEmpty(v)) {
              return false;
            }
          }
          return true;
        };
        if ((_this.data.pool.watermark == null) && !((ref2 = _this.father) != null ? ref2.isRoot() : void 0)) {
          _this.data.pool.watermark = {};
          _this.data.pool.watermark.watermark_state = "parent";
        } else if (__isConfigEmpty(_this.data.pool.watermark)) {
          if ((base = _this.data.pool).watermark == null) {
            base.watermark = {};
          }
          _this.data.pool.watermark.watermark_state = "none";
        } else {
          _this.data.pool.watermark.watermark_state = "enabled";
        }
        if (ez5.version("6")) {
          if ((_this.data.pool.caption == null) && !((ref3 = _this.father) != null ? ref3.isRoot() : void 0)) {
            _this.data.pool.caption = {};
            _this.data.pool.caption.caption_state = "parent";
          } else if (__isConfigEmpty(_this.data.pool.caption)) {
            if ((base1 = _this.data.pool).caption == null) {
              base1.caption = {};
            }
            _this.data.pool.caption.caption_state = "none";
          } else {
            if ((base2 = _this.data.pool).caption == null) {
              base2.caption = {};
            }
            _this.data.pool.caption.caption_state = "enabled";
            ref4 = _this.data.pool.caption;
            for (fieldName in ref4) {
              config = ref4[fieldName];
              if (fieldName === "caption_state") {
                continue;
              }
              if (config && typeof config === "object") {
                if (config.size) {
                  size_str = String(config.size);
                  if (/^\d+(\.\d+)?$/.test(size_str)) {
                    config.size = size_str + "px";
                  }
                }
                if (config.padding) {
                  padding_str = String(config.padding);
                  if (/^\d+$/.test(padding_str)) {
                    config.padding = padding_str + "px";
                  }
                }
              }
            }
          }
          if (!_this.data.pool.janitor_policy) {
            _this.data.pool.janitor_policy = {};
            _this.data.pool.janitor_policy.override_parent = false;
          } else {
            if (!_this.data.pool.janitor_policy.hasOwnProperty("override_parent")) {
              _this.data.pool.janitor_policy.override_parent = true;
            }
          }
          _this.__cached_janitor_values = null;
          if (_this.data.pool.janitor_policy.override_parent) {
            if (!_this.data.pool.janitor_policy.object_purge) {
              _this.data.pool.janitor_policy.object_purge = {};
            }
            if (!_this.data.pool.janitor_policy.file_link_delete) {
              _this.data.pool.janitor_policy.file_link_delete = {};
            }
          }
        }
        ref5 = ["_tags", "_transitions", "_acl"];
        for (j = 0, len1 = ref5.length; j < len1; j++) {
          k = ref5[j];
          if (!_this.data[k]) {
            _this.data[k] = [];
          }
        }
        if (_this.data.pool._id_parent && _this.canChangeParent()) {
          _this.data._parent_pool = (ref6 = ez5.pools.findPoolById(_this.data.pool._id_parent)) != null ? ref6.getData() : void 0;
        }
        return _this.initTagForm().done(function() {
          return dfr.resolve();
        }).fail(dfr.reject);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  Pool.prototype.initTagForm = function() {
    var privateTagsCheckboxEmptyLabel, tree, updateEditor;
    this.tagForm = new TagFormForManager({
      context: this
    });
    tree = this.tagForm.getTree;
    this.__tagFormPane = new CUI.SimplePane({
      content: tree,
      footer_right: new CUI.Checkbox({
        data: this.data,
        name: "_private_tags",
        text: $$("admin.pool.private_tags"),
        onDataChanged: (function(_this) {
          return function() {
            if (!_this.data._private_tags) {
              _this.data._tags.splice(0);
            }
            return updateEditor();
          };
        })(this)
      }).start()
    });
    privateTagsCheckboxEmptyLabel = new CUI.EmptyLabel({
      centered: true,
      text: $$("admin.pool.private_tags.individual-checkbox.hint")
    });
    updateEditor = (function(_this) {
      return function() {
        var promise;
        if (!_this.tagForm) {
          return;
        }
        if (!_this.father.isRoot()) {
          promise = CUI.chainedCall(function() {
            var dfr2;
            dfr2 = new CUI.Deferred();
            SystemListManagerItem.prototype.load.call(_this.father, true).always(dfr2.resolve);
            return dfr2.promise();
          }, function() {
            var ref;
            return (ref = _this.tagForm) != null ? ref.load() : void 0;
          });
        } else {
          promise = _this.tagForm.load();
        }
        promise.done(function() {
          var div;
          if (_this.tagForm) {
            _this.tagForm.setInactive(!_this.data._private_tags);
            div = _this.data._private_tags ? tree : privateTagsCheckboxEmptyLabel;
            return _this.__tagFormPane.replace(div, "center");
          }
        });
        return promise;
      };
    })(this);
    return updateEditor();
  };

  Pool.prototype.initTagData = function(tag) {
    var enabled, i, is_default, len, ref, sticky, tag_data, td;
    enabled = void 0;
    td = tag.getData();
    if (this.father.isRoot() || !this.father.data._compiled_tags) {
      sticky = td.sticky;
      enabled = td.enabled;
      is_default = td.is_default;
    } else {
      ref = this.father.data._compiled_tags;
      for (i = 0, len = ref.length; i < len; i++) {
        tag_data = ref[i];
        if (tag_data._id === tag.getId()) {
          enabled = tag_data.enabled;
          sticky = tag_data.sticky;
          is_default = tag_data.is_default;
          break;
        }
      }
      CUI.util.assert(!CUI.util.isUndef(enabled), "Pool.loadTag", "tag not found in available tags", {
        tagId: tag.getId(),
        availableTags: CUI.util.dump(this.father.data._available_tags)
      });
    }
    this.setTagDefault(tag, enabled, sticky, is_default);
    return this;
  };

  Pool.prototype.setTagDefault = function(tag, enabled, sticky, is_default) {
    var i, len, ref, tag_data, td;
    td = tag.getData();
    if (!this.data._private_tags || sticky) {
      tag.tagDisabled = true;
      td.sticky = sticky;
      td.enabled = enabled;
      td.is_default = is_default;
    } else {
      td.enabled = false;
      td.sticky = false;
      td.is_default = false;
      ref = this.data._tags;
      for (i = 0, len = ref.length; i < len; i++) {
        tag_data = ref[i];
        if (tag.getId() === tag_data._id) {
          td.enabled = tag_data.enabled;
          td.sticky = tag_data.sticky;
          td.is_default = tag_data.is_default;
          break;
        }
      }
    }
  };

  Pool.prototype.renderAclTab = function() {
    this.aclManager = new AclManager({
      data: this.data._acl,
      check_who_readable: ez5.version("6"),
      context: this,
      right: true,
      sticky: true,
      valid_from: ez5.version("6"),
      valid_to: ez5.version("6"),
      active: true,
      footer_right: new CUI.Checkbox({
        name: "_private_acl",
        text: $$("admin.pool.private_acl"),
        data: this.data
      }).start(),
      tagfilter: true,
      tagForm: this.tagForm
    });
    return this.aclManager.getTree();
  };

  Pool.prototype.renderExtraOptionsTab = function() {
    var ownerSharingForm, owner_sharing_block, owner_ship_block, ownershipTagForm, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9;
    ownershipTagForm = new CUI.Form({
      name: "ownership_tag",
      data: this.data.pool.custom_data,
      fields: [
        {
          type: CUI.Checkbox,
          name: "enabled",
          text: $$("admin.pool.extra.ownertag.enabled|hint"),
          onDataChanged: (function(_this) {
            return function() {
              var i, j, k, len, len1, ref, ref1, ref2, ref3, results, results1;
              if ((ref = _this.data.pool.custom_data) != null ? (ref1 = ref.ownership_tag) != null ? ref1.enabled : void 0 : void 0) {
                ref2 = ["text_with_owner", "text_without_owner", "color", "icon"];
                results = [];
                for (i = 0, len = ref2.length; i < len; i++) {
                  k = ref2[i];
                  results.push(ownershipTagForm.getFieldsByName(k)[0].enable());
                }
                return results;
              } else {
                ref3 = ["text_with_owner", "text_without_owner", "color", "icon"];
                results1 = [];
                for (j = 0, len1 = ref3.length; j < len1; j++) {
                  k = ref3[j];
                  results1.push(ownershipTagForm.getFieldsByName(k)[0].disable());
                }
                return results1;
              }
            };
          })(this)
        }, {
          type: CUI.MultiInput,
          form: {
            label: $$("admin.pool.extra.ownertag.text_with_owner"),
            hint: $$("admin.pool.extra.ownertag.text_with_owner|hint")
          },
          name: "text_with_owner",
          disabled: !((ref = this.data.pool.custom_data) != null ? (ref1 = ref.ownership_tag) != null ? ref1.enabled : void 0 : void 0),
          control: ez5.loca.getLanguageControlAdmin(),
          user_selectable: ez5.session.getPref("languages_user_selection")
        }, {
          type: CUI.MultiInput,
          form: {
            label: $$("admin.pool.extra.ownertag.text_without_owner"),
            hint: $$("admin.pool.extra.ownertag.text_without_owner|hint")
          },
          name: "text_without_owner",
          disabled: !((ref2 = this.data.pool.custom_data) != null ? (ref3 = ref2.ownership_tag) != null ? ref3.enabled : void 0 : void 0),
          control: ez5.loca.getLanguageControlAdmin(),
          user_selectable: ez5.session.getPref("languages_user_selection")
        }, {
          type: CUI.Select,
          form: {
            label: $$("admin.pool.extra.ownertag.color")
          },
          name: "color",
          disabled: !((ref4 = this.data.pool.custom_data) != null ? (ref5 = ref4.ownership_tag) != null ? ref5.enabled : void 0 : void 0),
          options: Tag.getTagColorsSelectorOp5ionw()
        }, {
          type: CUI.Select,
          form: {
            label: $$("admin.pool.extra.ownertag.icon")
          },
          name: "icon",
          disabled: !((ref6 = this.data.pool.custom_data) != null ? (ref7 = ref6.ownership_tag) != null ? ref7.enabled : void 0 : void 0),
          options: Tag.getTagIconsSelectorOptions()
        }
      ]
    });
    ownerSharingForm = new CUI.Form({
      name: "owner_sharing",
      data: this.data.pool.custom_data,
      fields: [
        {
          type: CUI.Checkbox,
          text: $$("admin.pool.extra.ownersharing.enable"),
          name: "enabled",
          onDataChanged: (function(_this) {
            return function() {
              var i, j, k, len, len1, ref10, ref11, ref8, ref9, results, results1;
              if ((ref8 = _this.data.pool.custom_data) != null ? (ref9 = ref8.owner_sharing) != null ? ref9.enabled : void 0 : void 0) {
                ref10 = ["sharing_users"];
                results = [];
                for (i = 0, len = ref10.length; i < len; i++) {
                  k = ref10[i];
                  results.push(ownerSharingForm.getFieldsByName(k)[0].enable());
                }
                return results;
              } else {
                ref11 = ["sharing_users"];
                results1 = [];
                for (j = 0, len1 = ref11.length; j < len1; j++) {
                  k = ref11[j];
                  results1.push(ownerSharingForm.getFieldsByName(k)[0].disable());
                }
                return results1;
              }
            };
          })(this)
        }, {
          type: CUI.DataTable,
          form: {
            label: $$("admin.pool.extra.ownersharing.sharing_users"),
            hint: $$("admin.pool.extra.ownersharing.sharing_users|hint")
          },
          name: "sharing_users",
          disabled: !((ref8 = this.data.pool.custom_data) != null ? (ref9 = ref8.owner_sharing) != null ? ref9.enabled : void 0 : void 0),
          no_header: true,
          fields: [
            {
              type: UserGroupSelector,
              name: "user",
              aclWhoManager: new AclWhoManager({
                allowEmailUser: true,
                allowPoolUser: true,
                filter_system_groups: true,
                filter_system_users: true
              })
            }
          ]
        }
      ]
    });
    owner_ship_block = new CUI.Block({
      text: $$("admin.pool.extra.ownertag.block"),
      content: (function(_this) {
        return function() {
          return ownershipTagForm.start();
        };
      })(this)
    });
    owner_sharing_block = new CUI.Block({
      text: $$("admin.pool.extra.ownersharing.block"),
      content: (function(_this) {
        return function() {
          return ownerSharingForm.start();
        };
      })(this)
    });
    return new CUI.VerticalList({
      content: [owner_ship_block, owner_sharing_block]
    });
  };

  Pool.prototype.renderTransitionsTab = function(has_objecttypes) {
    var privateTransitionsCheckboxEmptyLabel, transitionForm, transitionsPane, updateEditor;
    if (has_objecttypes == null) {
      has_objecttypes = true;
    }
    privateTransitionsCheckboxEmptyLabel = new CUI.EmptyLabel({
      centered: true,
      text: $$("admin.pool.private_transitions.individual-checkbox.hint")
    });
    updateEditor = (function(_this) {
      return function() {
        if (_this.data._private_transitions) {
          _this.transitionForm.setInactive(false);
          return transitionsPane.replace(transitionForm, "center");
        } else {
          _this.transitionForm.setInactive(true);
          return transitionsPane.replace(privateTransitionsCheckboxEmptyLabel, "center");
        }
      };
    })(this);
    this.transitionForm = new TransitionFormForManager({
      objecttypes: has_objecttypes,
      tagForm: this.tagForm
    });
    this.transitionForm.loadTransitions(this.data._transitions);
    transitionForm = this.transitionForm.renderEditor();
    transitionsPane = new CUI.SimplePane({
      content: transitionForm,
      footer_right: new CUI.Checkbox({
        name: "_private_transitions",
        text: $$("admin.pool.private_transitions"),
        onDataChanged: updateEditor,
        data: this.data
      }).start()
    });
    updateEditor();
    return transitionsPane;
  };

  Pool.prototype.renderJanitorTab = function() {
    var fileLinkDeleteBlock, fileLinkDeleteForm, getPlaceholder, objectPurgeBlock, objectPurgeForm, overrideCheckbox, overrideText, ref, ref1, ref2, updatePlaceholders;
    if (!this.data.pool.janitor_policy) {
      this.data.pool.janitor_policy = {};
      this.data.pool.janitor_policy.override_parent = false;
    }
    if (!this.data.pool.janitor_policy.hasOwnProperty("override_parent")) {
      this.data.pool.janitor_policy.override_parent = true;
    }
    overrideText = this.isRootPool() ? $$("admin.pool.janitor.override_base_config") : $$("admin.pool.janitor.override_parent");
    overrideCheckbox = new CUI.Checkbox({
      name: "override_parent",
      text: overrideText,
      data: this.data.pool.janitor_policy,
      onDataChanged: (function(_this) {
        return function() {
          var ref, ref1, ref10, ref11, ref12, ref13, ref14, ref15, ref16, ref17, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9;
          if ((ref = _this.data) != null ? (ref1 = ref.pool) != null ? (ref2 = ref1.janitor_policy) != null ? ref2.override_parent : void 0 : void 0 : void 0) {
            if (_this.__cached_janitor_values) {
              if ((ref3 = _this.data.pool.janitor_policy) != null) {
                if ((ref4 = ref3.object_purge) != null) {
                  ref4.min_deleted_days = (ref5 = _this.__cached_janitor_values.object_purge) != null ? ref5.min_deleted_days : void 0;
                }
              }
              if ((ref6 = _this.data.pool.janitor_policy) != null) {
                if ((ref7 = ref6.file_link_delete) != null) {
                  ref7.keep_count_history_versions = (ref8 = _this.__cached_janitor_values.file_link_delete) != null ? ref8.keep_count_history_versions : void 0;
                }
              }
              if ((ref9 = _this.data.pool.janitor_policy) != null) {
                if ((ref10 = ref9.file_link_delete) != null) {
                  ref10.keep_days_history_versions = (ref11 = _this.__cached_janitor_values.file_link_delete) != null ? ref11.keep_days_history_versions : void 0;
                }
              }
            }
          } else {
            _this.__cached_janitor_values = CUI.util.copyObjectV2(_this.data.pool.janitor_policy, true);
            if ((ref12 = _this.data.pool.janitor_policy) != null) {
              if ((ref13 = ref12.object_purge) != null) {
                ref13.min_deleted_days = null;
              }
            }
            if ((ref14 = _this.data.pool.janitor_policy) != null) {
              if ((ref15 = ref14.file_link_delete) != null) {
                ref15.keep_count_history_versions = null;
              }
            }
            if ((ref16 = _this.data.pool.janitor_policy) != null) {
              if ((ref17 = ref16.file_link_delete) != null) {
                ref17.keep_days_history_versions = null;
              }
            }
          }
          _this.__updateJanitorFormsState();
          return updatePlaceholders();
        };
      })(this)
    });
    getPlaceholder = (function(_this) {
      return function(category, field_name) {
        var getBaseConfigValue, parent_pool, parent_pool_id, ref, ref1, ref2, ref3, ref4, value;
        if ((ref = _this.data) != null ? (ref1 = ref.pool) != null ? (ref2 = ref1.janitor_policy) != null ? ref2.override_parent : void 0 : void 0 : void 0) {
          return $$("admin.pool.janitor.override.deactivated_placeholder");
        } else {
          getBaseConfigValue = function() {
            var value;
            value = ez5.session.getBaseConfig().janitor.object_and_file_removal[category][field_name];
            if (!value && value !== 0) {
              return $$("admin.pool.janitor.override.deactivated_placeholder");
            }
            return value;
          };
          parent_pool_id = _this.data.pool._id_parent;
          if (!parent_pool_id) {
            return "" + getBaseConfigValue();
          }
          value = null;
          while (!value && value !== 0) {
            parent_pool = ez5.pools.findPoolById(parent_pool_id);
            if (!parent_pool.data.pool.janitor_policy || !parent_pool.data.pool.janitor_policy.override_parent) {
              if (parent_pool.isRoot()) {
                value = getBaseConfigValue();
              } else {
                parent_pool_id = parent_pool.data.pool._id_parent;
              }
            } else {
              value = (ref3 = parent_pool.data.pool.janitor_policy) != null ? (ref4 = ref3[category]) != null ? ref4[field_name] : void 0 : void 0;
              if (!value && value !== 0) {
                return $$("admin.pool.janitor.override.deactivated_placeholder");
              }
            }
          }
          return "" + value;
        }
      };
    })(this);
    updatePlaceholders = (function(_this) {
      return function() {
        var i, k, keep_count_history_versions_field, keep_days_history_versions_field, len, ref, ref1, ref2, ref3;
        ref = ["keep_count_history_versions", "keep_days_history_versions"];
        for (i = 0, len = ref.length; i < len; i++) {
          k = ref[i];
          fileLinkDeleteForm.getFieldsByName(k)[0].setPlaceholder(getPlaceholder("file_link_delete", k));
        }
        objectPurgeForm.getFieldsByName("min_deleted_days")[0].setPlaceholder(getPlaceholder("object_purge", "min_deleted_days"));
        if ((ref1 = _this.data) != null ? (ref2 = ref1.pool) != null ? (ref3 = ref2.janitor_policy) != null ? ref3.override_parent : void 0 : void 0 : void 0) {
          keep_count_history_versions_field = fileLinkDeleteForm.getFieldsByName("keep_count_history_versions")[0];
          if (!CUI.util.isEmpty(_this.data.pool.janitor_policy.file_link_delete.keep_days_history_versions) && CUI.util.isEmpty(_this.data.pool.janitor_policy.file_link_delete.keep_count_history_versions)) {
            keep_count_history_versions_field.setPlaceholder("0");
          } else {
            keep_count_history_versions_field.setPlaceholder(getPlaceholder("file_link_delete", "keep_count_history_versions"));
          }
          keep_days_history_versions_field = fileLinkDeleteForm.getFieldsByName("keep_days_history_versions")[0];
          if (!CUI.util.isEmpty(_this.data.pool.janitor_policy.file_link_delete.keep_count_history_versions) && CUI.util.isEmpty(_this.data.pool.janitor_policy.file_link_delete.keep_days_history_versions)) {
            return keep_days_history_versions_field.setPlaceholder("0");
          } else {
            return keep_days_history_versions_field.setPlaceholder(getPlaceholder("file_link_delete", "keep_days_history_versions"));
          }
        }
      };
    })(this);
    fileLinkDeleteForm = new CUI.Form({
      name: "file_link_delete",
      data: this.data.pool.janitor_policy,
      onDataChanged: (function(_this) {
        return function() {
          updatePlaceholders();
        };
      })(this),
      fields: [
        {
          type: CUI.NumberInput,
          form: {
            label: $$("admin.pool.janitor.file_link_delete.keep_days_history_versions"),
            hint: $$("admin.pool.janitor.file_link_delete.keep_days_history_versions.hint")
          },
          name: "keep_days_history_versions",
          placeholder: getPlaceholder("file_link_delete", "keep_days_history_versions"),
          disabled: !((ref = this.data.pool.janitor_policy) != null ? ref.override_parent : void 0),
          min: 0
        }, {
          type: CUI.NumberInput,
          form: {
            label: $$("admin.pool.janitor.file_link_delete.keep_count_history_versions"),
            hint: $$("admin.pool.janitor.file_link_delete.keep_count_history_versions.hint")
          },
          name: "keep_count_history_versions",
          placeholder: getPlaceholder("file_link_delete", "keep_count_history_versions"),
          disabled: !((ref1 = this.data.pool.janitor_policy) != null ? ref1.override_parent : void 0),
          min: 0
        }
      ]
    });
    objectPurgeForm = new CUI.Form({
      name: "object_purge",
      data: this.data.pool.janitor_policy,
      fields: [
        {
          type: CUI.NumberInput,
          form: {
            label: $$("admin.pool.janitor.object_purge.min_deleted_days"),
            hint: $$("admin.pool.janitor.object_purge.min_deleted_days.hint")
          },
          name: "min_deleted_days",
          placeholder: getPlaceholder("object_purge", "min_deleted_days"),
          disabled: !((ref2 = this.data.pool.janitor_policy) != null ? ref2.override_parent : void 0),
          min: 0
        }
      ]
    });
    this.__fileLinkDeleteForm = fileLinkDeleteForm;
    this.__objectPurgeForm = objectPurgeForm;
    fileLinkDeleteBlock = new CUI.Block({
      text: $$("admin.pool.janitor.file_link_delete.block"),
      content: (function(_this) {
        return function() {
          return fileLinkDeleteForm.start();
        };
      })(this)
    });
    objectPurgeBlock = new CUI.Block({
      text: $$("admin.pool.janitor.object_purge.block"),
      content: (function(_this) {
        return function() {
          return objectPurgeForm.start();
        };
      })(this)
    });
    return new CUI.VerticalList({
      content: [overrideCheckbox.start(), objectPurgeBlock, fileLinkDeleteBlock]
    });
  };

  Pool.prototype.__updateJanitorFormsState = function() {
    var field, i, isOverrideParent, j, len, len1, ref, ref1, ref2, results;
    isOverrideParent = (ref = this.data.pool.janitor_policy) != null ? ref.override_parent : void 0;
    if (this.__fileLinkDeleteForm) {
      ref1 = this.__fileLinkDeleteForm.getFields();
      for (i = 0, len = ref1.length; i < len; i++) {
        field = ref1[i];
        if (isOverrideParent) {
          field.enable();
        } else {
          field.disable();
        }
        field.reload();
      }
    }
    if (this.__objectPurgeForm) {
      ref2 = this.__objectPurgeForm.getFields();
      results = [];
      for (j = 0, len1 = ref2.length; j < len1; j++) {
        field = ref2[j];
        if (isOverrideParent) {
          field.enable();
        } else {
          field.disable();
        }
        results.push(field.reload());
      }
      return results;
    }
  };

  Pool.prototype.renderStatisticsTab = function() {
    var loadStats, showEmptyStats, vl;
    vl = new CUI.SimplePane({
      "class": "cui-pane--window",
      content: []
    });
    this.__statFormData = {
      totalSizeOfPool: 0,
      fileCount: 0,
      includeSubpools: true
    };
    showEmptyStats = (function(_this) {
      return function() {
        return vl.replace(new CUI.EmptyLabel({
          centered: true,
          text: $$("admin.pool.statistics.empty")
        }), "center");
      };
    })(this);
    loadStats = (function(_this) {
      return function() {
        var apiUrl, stats, waitBlock;
        apiUrl = "/" + _this.id + "/stats";
        if (_this.__statFormData.includeSubpools) {
          apiUrl += "?include_subpools=1";
        }
        waitBlock = new CUI.WaitBlock({
          text: $$("admin.pool.statistics.loading"),
          element: vl
        });
        waitBlock.show();
        return stats = ez5.api.pool({
          type: "GET",
          api: apiUrl
        }).fail(function(err) {
          showEmptyStats();
          return waitBlock.destroy();
        }).done(function(data) {
          var statsForm, statsTable;
          if (!(data != null ? data.files : void 0)) {
            showEmptyStats();
            waitBlock.destroy();
            return;
          }
          _this.__statFormData.totalSizeOfPool = data.files.size;
          _this.__statFormData.fileCount = data.files.count;
          statsTable = new StatsTable({
            data: data
          });
          statsForm = new CUI.Form({
            ui: "pool.form.fields.statistics",
            data: _this.__statFormData,
            fields: [
              {
                type: CUI.Output,
                form: {
                  label: $$("admin.pool.statistics.total_size_of_pool")
                },
                name: "totalSizeOfPool",
                getValue: function(v) {
                  return ez5.format_filesize(v) + (" (" + _this.__statFormData.fileCount + " files)");
                }
              }, {
                type: CUI.Checkbox,
                name: "includeSubpools",
                form: {
                  label: $$("admin.pool.statistics.include_subpools")
                },
                onDataChanged: function(v) {
                  _this.__statFormData.totalSizeOfPool = 0;
                  return loadStats();
                }
              }
            ]
          });
          vl.replace([statsForm.start(), _this.__statFormData.totalSizeOfPool !== 0 ? statsTable.render() : void 0], "center");
          return waitBlock.destroy();
        });
      };
    })(this);
    loadStats();
    return vl;
  };

  Pool.prototype.save = function(ev) {
    var ref;
    if (this.canChangeParent() && ((ref = this.data._parent_pool.pool) != null ? ref._id : void 0) !== this.data[this.data._basetype]._id_parent) {
      return CUI.confirm({
        text: $$("admin.pool.change_parent.confirm")
      }).done((function(_this) {
        return function() {
          return Pool.__super__.save.call(_this, ev);
        };
      })(this));
    } else {
      return Pool.__super__.save.call(this, ev);
    }
  };

  Pool.prototype.getSaveData = function() {
    var caption_config, config, dissolve_int, fieldName, hasFileLinkDeleteValues, hasObjectPurgeValue, hasValidConfig, i, info, janitorData, janitor_policy, len, oid, owner_id, p, padding_str, padding_val, pool, ref, ref1, ref10, ref11, ref12, ref13, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, save_data, size_str, size_val;
    pool = CUI.util.copyObject(this.data[this.data._basetype], true);
    save_data = {
      _basetype: "pool",
      pool: {
        _id: this.id,
        _id_parent: pool._id_parent,
        name: pool.name,
        reference: !this.isSystemPool() ? pool.reference : void 0,
        comment: pool.comment,
        shortname: pool.shortname,
        contact: pool.contact || null,
        description: pool.description,
        mapping_dc_export: CUI.util.getIntOrString(pool.mapping_dc_export),
        mapping_image_export: CUI.util.getIntOrString(pool.mapping_image_export),
        mapping_image_import: CUI.util.getIntOrString(pool.mapping_image_import),
        custom_data: {},
        janitor_policy: {}
      },
      _standard_masks: {},
      _private_tags: !!this.data._private_tags,
      _private_transitions: !!this.data._private_transitions
    };
    if (ez5.version("6")) {
      save_data.pool.mapping_image_import_recipe_configs = this.data.pool.mapping_image_import_recipe_configs || null;
    }
    if (ez5.version("6") && this.data.pool.janitor_policy) {
      if (!this.data.pool.janitor_policy.override_parent) {
        save_data.pool.janitor_policy = null;
      } else {
        janitor_policy = {};
        janitorData = this.data.pool.janitor_policy;
        hasFileLinkDeleteValues = !CUI.util.isEmpty(janitorData.file_link_delete.keep_days_history_versions) || !CUI.util.isEmpty(janitorData.file_link_delete.keep_count_history_versions);
        if (hasFileLinkDeleteValues) {
          janitor_policy.file_link_delete = {
            keep_days_history_versions: janitorData.file_link_delete.keep_days_history_versions,
            keep_count_history_versions: janitorData.file_link_delete.keep_count_history_versions
          };
        } else {
          janitor_policy.file_link_delete = null;
        }
        hasObjectPurgeValue = !CUI.util.isEmpty(janitorData.object_purge.min_deleted_days);
        if (hasObjectPurgeValue) {
          janitor_policy.object_purge = {
            min_deleted_days: janitorData.object_purge.min_deleted_days
          };
        } else {
          janitor_policy.object_purge = null;
        }
        save_data.pool.janitor_policy = CUI.util.copyObjectV2(janitor_policy, true);
      }
    }
    if (CUI.util.isEmpty(ez5.loca.getBestFrontendValue(pool.name))) {
      throw new InvalidSaveDataException();
    }
    if (this.canChangeOwner()) {
      owner_id = (ref = this.data._owner) != null ? (ref1 = ref.user) != null ? ref1._id : void 0 : void 0;
      if (owner_id) {
        save_data._owner = {
          _basetype: "user",
          user: {
            _id: owner_id
          }
        };
      }
    }
    if (this.canChangeParent()) {
      if (!CUI.util.isEmpty(this.data._parent_pool)) {
        save_data.pool._id_parent = ((ref2 = this.data._parent_pool.pool) != null ? ref2._id : void 0) || pool._id_parent;
      } else {
        throw new InvalidSaveDataException();
      }
    }
    if (!this.canSetParent()) {
      delete save_data.pool._id_parent;
    }
    if (ez5.version("6")) {
      switch (pool.watermark.watermark_state) {
        case "enabled":
          if ((ref3 = pool.watermark) != null ? (ref4 = ref3.image) != null ? ref4._id : void 0 : void 0) {
            save_data.pool.watermark = {
              image: pool.watermark.image,
              gravity: pool.watermark.gravity,
              size: pool.watermark.size,
              tile: pool.watermark.tile
            };
            dissolve_int = parseInt(pool.watermark.dissolve);
            if (dissolve_int >= 0) {
              save_data.pool.watermark.dissolve = dissolve_int;
            }
          } else {
            save_data.pool.watermark = {};
          }
          break;
        case "none":
          save_data.pool.watermark = {};
          break;
        case "parent":
          save_data.pool.watermark = null;
      }
    } else if ((ref5 = pool.watermark) != null ? (ref6 = ref5.image) != null ? ref6._id : void 0 : void 0) {
      save_data.pool.watermark = {
        image: pool.watermark.image,
        gravity: pool.watermark.gravity,
        size: pool.watermark.size,
        tile: pool.watermark.tile
      };
      dissolve_int = parseInt(pool.watermark.dissolve);
      if (dissolve_int >= 0) {
        save_data.pool.watermark.dissolve = dissolve_int;
      }
    } else {
      save_data.pool.watermark = null;
    }
    if (ez5.version("6")) {
      switch (pool.caption.caption_state) {
        case "enabled":
          caption_config = {};
          hasValidConfig = false;
          ref7 = pool.caption;
          for (fieldName in ref7) {
            config = ref7[fieldName];
            if (fieldName === "_rows" || fieldName === "caption_state") {
              continue;
            }
            if (!config || !fieldName) {
              continue;
            }
            if (!config.text || !/^\s*\S+.*$/.test(String(config.text))) {
              continue;
            }
            size_str = null;
            if (config.size) {
              size_val = String(config.size);
              if (size_val.endsWith("%")) {
                size_str = size_val;
              } else {
                size_str = size_val.replace(/[^\d.]/g, "");
              }
            }
            padding_str = null;
            if (config.padding) {
              padding_val = String(config.padding);
              padding_str = padding_val.replace(/\D/g, "");
            }
            caption_config[fieldName] = {
              text: config.text,
              size: size_str,
              padding: padding_str,
              multiline: config.multiline,
              overlay: config.overlay
            };
            hasValidConfig = true;
          }
          if (hasValidConfig) {
            save_data.pool.caption = caption_config;
          } else {
            save_data.pool.caption = {};
          }
          break;
        case "none":
          if (this.isRootPool()) {
            save_data.pool.caption = null;
          } else {
            save_data.pool.caption = {};
          }
          break;
        case "parent":
          save_data.pool.caption = null;
      }
    }
    ref8 = this.data.standard_masks;
    for (oid in ref8) {
      info = ref8[oid];
      save_data._standard_masks[oid] = ObjecttypeListViewItem.prototype.getSaveDataStandardMasks(info);
    }
    if (save_data._private_tags) {
      if (this.tagForm) {
        save_data._tags = this.tagForm.getSaveData();
      } else {
        save_data._tags = [];
      }
    }
    if (this.transitionForm) {
      save_data._transitions = this.transitionForm.getSaveData();
    } else {
      save_data._transitions = [];
    }
    if (this.aclManager) {
      save_data._acl = this.aclManager.getSaveData();
      save_data._private_acl = !!this.data._private_acl;
    }
    ref9 = this.__plugins;
    for (i = 0, len = ref9.length; i < len; i++) {
      p = ref9[i];
      p.getSaveData(save_data);
    }
    if (ez5.version("6")) {
      if ((ref10 = this.data.pool.custom_data) != null ? ref10.ownership_tag : void 0) {
        save_data.pool.custom_data.ownership_tag = CUI.util.copyObject((ref11 = this.data.pool.custom_data) != null ? ref11.ownership_tag : void 0, true);
      }
      if ((ref12 = this.data.pool.custom_data) != null ? ref12.owner_sharing : void 0) {
        save_data.pool.custom_data.owner_sharing = CUI.util.copyObject((ref13 = this.data.pool.custom_data) != null ? ref13.owner_sharing : void 0, true);
      }
    }
    return save_data;
  };

  Pool.prototype.getInitialData = function() {
    if (this._copy) {
      return {};
    }
    return this.getSaveData();
  };

  Pool.prototype.getApi = function() {
    return "pool";
  };

  Pool.prototype.__getMappingImageImportField = function(opts) {
    var configButton, container, selectField;
    if (!ez5.version("6") || ez5.metadata.getMetadataRecipesWithParams().length === 0) {
      return {
        type: CUI.Select,
        form: {
          label: $$("admin.pool.profile_for_images_import")
        },
        name: "mapping_image_import",
        ui: "pool.form.fields.mapping_image_import.select",
        options: ez5.metadata.getMappingOpts(opts, {
          exiftool_import: true
        })
      };
    }
    configButton = ez5.metadata.getMappingRecipeConfigButton(this.data.pool, {
      name: "mapping_image_import_recipe_configs",
      popover_placement: "w",
      getMappingId: (function(_this) {
        return function() {
          return _this.data.pool.mapping_image_import;
        };
      })(this),
      onDataChanged: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            type: "data-changed",
            node: configButton
          });
        };
      })(this)
    });
    ez5.metadata.updateRecipeConfigButtonState(configButton, this.data.pool.mapping_image_import);
    selectField = new CUI.Select({
      data: this.data.pool,
      name: "mapping_image_import",
      ui: "pool.form.fields.mapping_image_import.select",
      maximize_horizontal: true,
      options: ez5.metadata.getMappingOpts(opts, {
        exiftool_import: true
      }),
      onDataChanged: (function(_this) {
        return function() {
          return ez5.metadata.updateRecipeConfigButtonState(configButton, _this.data.pool.mapping_image_import);
        };
      })(this)
    });
    container = CUI.dom.div("ez5-mapping-field-with-config");
    container.appendChild(selectField.DOM);
    container.appendChild(configButton.DOM);
    return new CUI.DataFieldProxy({
      form: {
        label: $$("admin.pool.profile_for_images_import")
      },
      element: container
    });
  };

  Pool.prototype.general_fields = function() {
    var opts, ref;
    opts = [
      {
        text: $$("admin.pool.asset_profile.none"),
        value: "none",
        ui: "pool.form.fields.mapping.option:none"
      }, {
        text: $$("admin.pool.asset_profile.objecttype"),
        value: "objecttype",
        ui: "pool.form.fields.mapping.option:objecttype"
      }
    ];
    if (!((ref = this.father) != null ? ref.isRoot() : void 0)) {
      opts.push({
        text: $$("admin.pool.asset_profile.parent", {
          pool: this.father.getDisplayText()
        }),
        value: "parent",
        ui: "pool.form.fields.mapping.option:parent"
      });
    }
    return [
      {
        type: CUI.Output,
        ui: "pool.form.fields.id.output",
        form: {
          label: $$("pool.form.id")
        },
        name: "_id",
        placeholder: $$("admin.pool._id.new")
      }, this.canChangeParent() ? {
        type: PoolSelector,
        form: {
          label: $$("admin.pool._id_parent")
        },
        ui: "pool.form.fields.id_parent.selector",
        name: "_parent_pool",
        data: this.data,
        omit_root_pool: false
      } : void 0, this.canChangeOwner() ? {
        type: UserGroupSelector,
        form: {
          label: $$("admin.pool._owner")
        },
        ui: "pool.form.fields.owner.selector",
        name: "_owner",
        data: this.data,
        aclWhoManager: new AclWhoManager({
          who_filter: ["user"],
          filter_system_groups: true,
          placeholder: "-"
        })
      } : {
        type: CUI.Output,
        data: this.data,
        ui: "pool.form.fields.owner.output",
        name: "_owner",
        form: {
          label: $$("admin.pool._owner")
        },
        getValue: function(v) {
          var ref1;
          return v != null ? (ref1 = v[v._basetype]) != null ? ref1._generated_displayname : void 0 : void 0;
        },
        placeholder: $$("admin.pool._owner.new")
      }, {
        type: UserGroupSelector,
        form: {
          label: $$("admin.pool.contact")
        },
        ui: "pool.form.fields.contact.output",
        aclWhoManager: new AclWhoManager({
          who_filter: ["user"],
          placeholder: "-"
        }),
        name: "contact",
        data: this.data.pool
      }, {
        type: CUI.MultiInput,
        form: {
          label: $$("admin.pool.name")
        },
        ui: "pool.form.fields.name.input",
        name: "name",
        control: ez5.loca.getLanguageControlAdmin(),
        user_selectable: ez5.session.getPref("languages_user_selection")
      }, {
        type: CUI.MultiInput,
        textarea: true,
        form: {
          label: $$("admin.pool.description")
        },
        ui: "pool.form.fields.description.input",
        name: "description",
        control: ez5.loca.getLanguageControlAdmin(),
        user_selectable: ez5.session.getPref("languages_user_selection")
      }, {
        type: CUI.Input,
        textarea: true,
        form: {
          label: $$("pool.form.comment")
        },
        name: "comment",
        ui: "pool.form.fields.comment.input"
      }, {
        type: this.isSystemPool() ? CUI.Output : CUI.Input,
        form: {
          label: $$("pool.form.reference")
        },
        name: "reference",
        ui: "pool.form.fields.reference." + (this.isSystemPool() ? "output" : "input")
      }, {
        type: CUI.Input,
        form: {
          label: $$("pool.form.shortname")
        },
        name: "shortname",
        ui: "pool.form.fields.shortname.input"
      }, this.__getMappingImageImportField(opts), {
        type: CUI.Select,
        form: {
          label: $$("admin.pool.profile_for_images_export")
        },
        name: "mapping_image_export",
        ui: "pool.form.fields.mapping_image_export.select",
        options: ez5.metadata.getMappingOpts(opts, {
          exiftool_export: true
        })
      }, {
        type: CUI.Select,
        form: {
          label: $$("admin.pool.profile_for_dc_export")
        },
        name: "mapping_dc_export",
        ui: "pool.form.fields.mapping_dc_export.select",
        options: ez5.metadata.getMappingOpts(opts, {
          dc_export: true
        })
      }, {
        type: CUI.Output,
        form: {
          label: $$("admin.pool.created_timestamp")
        },
        name: "created_timestamp",
        ui: "pool.form.fields.created_timestamp.output",
        getValue: (function(_this) {
          return function(v) {
            return ez5.format_date_and_time(v, true);
          };
        })(this),
        placeholder: $$("admin.pool.created_timestamp.new")
      }, {
        type: CUI.Output,
        form: {
          label: $$("admin.pool.last_updated_timestamp")
        },
        name: "last_updated_timestamp",
        ui: "pool.form.fields.last_updated_timestamp.output",
        getValue: (function(_this) {
          return function(v) {
            return ez5.format_date_and_time(v, true);
          };
        })(this),
        placeholder: $$("admin.pool.last_updated_timestamp.new")
      }
    ];
  };

  Pool.prototype.watermark_fields = function() {
    var eas_field, g, gravity_opts, i, len, ref, ref1, ref2, watermark_state_opts;
    gravity_opts = [];
    ref = ["n", "e", "s", "w", "ne", "nw", "se", "sw", "c"];
    for (i = 0, len = ref.length; i < len; i++) {
      g = ref[i];
      gravity_opts.push({
        value: g,
        text: $$("admin.pool.watermark.gravity." + g)
      });
    }
    eas_field = new EASField({
      name: "image"
    });
    watermark_state_opts = [
      {
        value: "none",
        text: $$("admin.pool.watermark.state.none")
      }, {
        value: "enabled",
        text: $$("admin.pool.watermark.state.enabled")
      }
    ];
    if (!((ref1 = this.father) != null ? ref1.isRoot() : void 0)) {
      watermark_state_opts.splice(1, 0, {
        value: "parent",
        text: $$("admin.pool.watermark.state.parent", {
          pool: ((ref2 = this.father) != null ? ref2.getDisplayText() : void 0) || ""
        })
      });
    }
    return [
      ez5.version("6") ? {
        type: CUI.Select,
        name: "watermark_state",
        form: {
          label: $$("admin.pool.watermark.state")
        },
        options: watermark_state_opts,
        onDataChanged: (function(_this) {
          return function(data, field) {
            var f, j, len1, ref3;
            ref3 = field.getForm().getFields();
            for (j = 0, len1 = ref3.length; j < len1; j++) {
              f = ref3[j];
              if (f === field) {
                continue;
              }
              if (_this.data.pool.watermark.watermark_state === "enabled") {
                f.enable();
              } else {
                f.disable();
              }
            }
          };
        })(this)
      } : void 0, {
        form: {
          label: $$("admin.pool.watermark.picture")
        },
        type: CUI.DataFieldProxy,
        element: eas_field.renderEditorInput(this.data.pool.watermark),
        disabled: this.data.pool.watermark.watermark_state !== "enabled" && ez5.version("6")
      }, {
        type: CUI.Input,
        placeholder: "0-100",
        form: {
          label: $$("admin.pool.watermark.dissolve")
        },
        name: "dissolve",
        disabled: this.data.pool.watermark.watermark_state !== "enabled" && ez5.version("6")
      }, {
        type: CUI.Select,
        options: gravity_opts,
        empty_text: "0-100",
        form: {
          label: $$("admin.pool.watermark.gravity")
        },
        name: "gravity",
        disabled: this.data.pool.watermark.watermark_state !== "enabled" && ez5.version("6")
      }, {
        type: CUI.Input,
        placeholder: $$("admin.pool.watermark.size|placeholder"),
        form: {
          label: $$("admin.pool.watermark.size")
        },
        name: "size",
        disabled: this.data.pool.watermark.watermark_state !== "enabled" && ez5.version("6")
      }, {
        type: CUI.Checkbox,
        form: {
          label: $$("admin.pool.watermark.tile")
        },
        name: "tile",
        disabled: this.data.pool.watermark.watermark_state !== "enabled" && ez5.version("6")
      }
    ];
  };

  Pool.prototype.caption_fields = function() {
    var all_eas_fields, caption_state_opts, fields, getEASFieldOption, otm, ref, ref1, showReplacementsButton;
    caption_state_opts = [
      {
        value: "none",
        text: $$("admin.pool.caption.state.none")
      }, {
        value: "enabled",
        text: $$("admin.pool.caption.state.enabled")
      }
    ];
    if (!((ref = this.father) != null ? ref.isRoot() : void 0)) {
      caption_state_opts.splice(1, 0, {
        value: "parent",
        text: $$("admin.pool.caption.state.parent", {
          pool: ((ref1 = this.father) != null ? ref1.getDisplayText() : void 0) || ""
        })
      });
    }
    otm = new ObjecttypeManager();
    otm.addObjecttypes(function(table, mask) {
      if (table.schema.pool_link) {
        return true;
      }
      return false;
    });
    all_eas_fields = otm.getEASFields("all", null, false);
    all_eas_fields = all_eas_fields.filter(function(field) {
      var ref2, ref3;
      if (((ref2 = field.mask) != null ? ref2.nestedTableField : void 0) instanceof ReverseLinkedTable) {
        return false;
      }
      if ((ref3 = field.fullName()) != null ? ref3.includes("_reverse_nested:") : void 0) {
        return false;
      }
      return true;
    });
    getEASFieldOption = (function(_this) {
      return function() {
        var easField, field_options, i, isDisabled, len;
        isDisabled = function() {
          var eas_configured, ref2;
          eas_configured = Object.keys((ref2 = _this.data.pool) != null ? ref2.caption : void 0);
          if (!eas_configured || eas_configured.length === 0) {
            return false;
          }
          return eas_configured.some(function(f) {
            return f === easField.fullName();
          });
        };
        field_options = [
          {
            value: null,
            text: $$("admin.pool.caption.field.empty_text")
          }
        ];
        for (i = 0, len = all_eas_fields.length; i < len; i++) {
          easField = all_eas_fields[i];
          field_options.push({
            text: easField.fullName(),
            value: easField.fullName(),
            disabled: isDisabled()
          });
        }
        return field_options;
      };
    })(this);
    showReplacementsButton = (function(_this) {
      return function(field) {
        return new CUI.Button({
          icon: "question",
          appearance: "flat",
          onClick: function(ev, btn) {
            var caption_help, i, k, len, ot, pop, ref2, ref3, ref4, ref5, targetFieldName, v;
            caption_help = "";
            targetFieldName = field != null ? (ref2 = field.getForm()) != null ? (ref3 = ref2.getData()) != null ? ref3.field : void 0 : void 0 : void 0;
            if (!targetFieldName) {
              return;
            }
            ref4 = ez5.objecttypes.getObjecttypes() || [];
            for (i = 0, len = ref4.length; i < len; i++) {
              ot = ref4[i];
              ref5 = ot._filename_replacements || {};
              for (k in ref5) {
                v = ref5[k];
                if (k === targetFieldName && (v != null ? v.length : void 0) > 0) {
                  caption_help += v.join("\n");
                }
              }
            }
            pop = new ez5.HintPopover({
              element: btn,
              content: new CUI.Label({
                multiline: true,
                text: caption_help
              }),
              padded: true
            });
            return pop.show();
          }
        });
      };
    })(this);
    fields = [
      {
        type: CUI.Select,
        name: "caption_state",
        form: {
          label: $$("admin.pool.caption.state")
        },
        options: caption_state_opts,
        onDataChanged: (function(_this) {
          return function(data, field) {
            var f, i, len, ref2;
            ref2 = field.getForm().getFields();
            for (i = 0, len = ref2.length; i < len; i++) {
              f = ref2[i];
              if (f === field) {
                continue;
              }
              if (_this.data.pool.caption.caption_state === "enabled") {
                f.enable();
              } else {
                f.disable();
              }
            }
          };
        })(this)
      }, {
        type: CUI.DataTable,
        name: "_rows",
        new_rows: "append",
        form: {
          label: $$("admin.pool.caption.fields")
        },
        fields: [
          {
            type: CUI.Select,
            form: {
              label: $$("admin.pool.caption.field")
            },
            name: "field",
            options: getEASFieldOption
          }, {
            type: CUI.Input,
            form: {
              label: $$("admin.pool.caption.text"),
              hint: $$("admin.pool.caption.text.hint")
            },
            name: "text",
            placeholder: $$("admin.pool.caption.text.placeholder"),
            "class": "ez5-pool-caption-text",
            controlElement: showReplacementsButton
          }, {
            type: CUI.Input,
            form: {
              label: $$("admin.pool.caption.size"),
              hint: $$("admin.pool.caption.size.hint")
            },
            name: "size",
            regexp: "^\\d+(\\.\\d+)?(%|px)?$",
            placeholder: $$("admin.pool.caption.size.placeholder")
          }, {
            type: CUI.Input,
            form: {
              label: $$("admin.pool.caption.padding"),
              hint: $$("admin.pool.caption.padding.hint")
            },
            name: "padding",
            regexp: "^\\d+(px)?$",
            placeholder: $$("admin.pool.caption.padding.placeholder")
          }, {
            type: CUI.Checkbox,
            form: {
              label: $$("admin.pool.caption.multiline")
            },
            name: "multiline"
          }, {
            type: CUI.Checkbox,
            form: {
              label: $$("admin.pool.caption.overlay")
            },
            name: "overlay"
          }
        ],
        onDataInit: (function(_this) {
          return function(dataField, data) {
            var config, fieldName, rows;
            if (!data._rows) {
              rows = [];
              for (fieldName in data) {
                config = data[fieldName];
                if (fieldName === "_rows" || fieldName === "caption_state") {
                  continue;
                }
                if (config && typeof config === "object") {
                  rows.push({
                    field: fieldName,
                    text: config.text,
                    size: config.size,
                    padding: config.padding,
                    multiline: config.multiline,
                    overlay: config.overlay
                  });
                }
              }
              return data._rows = rows;
            }
          };
        })(this),
        onDataChanged: (function(_this) {
          return function(data, element, field) {
            var caption_state, i, key, len, results, row, rows;
            if (data._rows) {
              caption_state = data.caption_state;
              rows = data._rows;
              for (key in data) {
                if (key !== "caption_state" && key !== "_rows") {
                  delete data[key];
                }
              }
              results = [];
              for (i = 0, len = rows.length; i < len; i++) {
                row = rows[i];
                if (row.field) {
                  results.push(data[row.field] = {
                    text: row.text,
                    size: row.size,
                    padding: row.padding,
                    multiline: row.multiline,
                    overlay: row.overlay
                  });
                } else {
                  results.push(void 0);
                }
              }
              return results;
            }
          };
        })(this),
        disabled: this.data.pool.caption.caption_state !== "enabled"
      }
    ];
    return fields;
  };

  Pool.prototype.standard_mask_fields = function(opts) {
    var i, j, len, len1, mask, mask_fields, options, ref, ref1, table;
    if (opts == null) {
      opts = {};
    }
    mask_fields = [];
    ref = ez5.schema.CURRENT._objecttypes;
    for (i = 0, len = ref.length; i < len; i++) {
      table = ref[i];
      if (table._instance) {
        continue;
      }
      if (opts.forObjecttype) {
        if (opts.forObjecttype !== true && opts.forObjecttype.table.id() !== table.table_id) {
          continue;
        }
      } else if (!table.pool_link) {
        continue;
      }
      if (!opts.forObjecttype) {
        options = [
          {
            value: "standard"
          }
        ];
        if (opts.forPoolAcl) {
          options[0].text = $$("admin.standard.mask.from_datamodel.pool");
        } else {
          if (this.father.isRoot()) {
            options[0].text = $$("admin.standard.mask.from_datamodel.pool_root");
          } else {
            options[0].text = $$("admin.standard.mask.from_datamodel.pool_parent");
          }
        }
      } else {
        options = [
          {
            value: "standard",
            text: $$("admin.standard.mask.from_datamodel.pool_root")
          }
        ];
      }
      ref1 = ez5.mask.CURRENT._masks_by_table_id[table.table_id];
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        mask = ref1[j];
        options.push({
          text: mask._name_localized,
          value: mask.mask_id
        });
      }
      mask_fields.push({
        type: CUI.Options,
        horizontal: 3,
        form: {
          label: table._name_localized
        },
        name: "objecttype_" + table.table_id,
        options: options
      });
    }
    return mask_fields;
  };

  Pool.prototype.standard_mask_order_fields = function() {
    var fields, i, label_from_datamodel, len, objecttype, oid, ref, table;
    fields = [];
    ref = ez5.schema.CURRENT._objecttypes;
    for (i = 0, len = ref.length; i < len; i++) {
      table = ref[i];
      if (table._instance) {
        continue;
      }
      if (!table.pool_link) {
        continue;
      }
      objecttype = new Objecttype(table);
      oid = objecttype.table.id();
      if (this.father.isRoot()) {
        label_from_datamodel = "admin.standard_mask.from_datamodel.pool_root";
      } else {
        label_from_datamodel = "admin.standard_mask.from_datamodel.pool_parent";
      }
      fields.push(ObjecttypeListViewItem.prototype.getStandardMaskFieldsForm.call(this, objecttype, this.data.standard_masks[oid], $$(label_from_datamodel), objecttype.nameLocalized()));
    }
    return fields;
  };

  Pool.prototype.getTabs = function() {
    var i, len, p, ref, tabs;
    if (ez5.version("6")) {
      this.data.pool.created_timestamp = this.data._created_at;
      if (this.data._updated_at === "0001-01-01T00:00:00Z") {
        this.data._updated_at = this.data._created_at;
      }
      this.data.pool.last_updated_timestamp = this.data._updated_at;
    }
    tabs = [
      {
        name: "general",
        text: $$("admin.pool.tab.general"),
        content: (function(_this) {
          return function() {
            return new CUI.Form({
              onDataChanged: function(data, field) {
                return _this.update();
              },
              fields: _this.general_fields(),
              data: _this.data.pool
            }).start();
          };
        })(this)
      }, {
        name: "watermark",
        text: $$("admin.pool.tab.watermark"),
        content: (function(_this) {
          return function() {
            var captionBlock, captionForm, watermarkBlock, watermarkForm, watermarkInformationLabel;
            watermarkForm = new CUI.Form({
              fields: _this.watermark_fields(),
              data: _this.data.pool.watermark
            });
            if (ez5.version("6")) {
              captionForm = new CUI.Form({
                "class": "ez5-pool-list-view-item-caption",
                fields: _this.caption_fields(),
                data: _this.data.pool.caption
              });
            }
            watermarkBlock = new CUI.Block({
              text: $$("admin.pool.watermark.block"),
              content: function() {
                return watermarkForm.start();
              }
            });
            captionBlock = null;
            if (ez5.version("6")) {
              captionBlock = new CUI.Block({
                text: $$("admin.pool.caption.block"),
                content: function() {
                  return captionForm.start();
                }
              });
            }
            watermarkInformationLabel = new CUI.Label({
              multiline: true,
              markdown: true,
              text: $$("admin.pool.watermark.information.md"),
              "class": "cui-label-description"
            });
            return new CUI.VerticalList({
              content: [watermarkInformationLabel, watermarkBlock, captionBlock]
            });
          };
        })(this)
      }, {
        name: "masks",
        text: $$("admin.pool.tab.masks"),
        content: (function(_this) {
          return function() {
            return new CUI.Form({
              fields: _this.standard_mask_order_fields(),
              data: _this.data.standard_masks
            }).start();
          };
        })(this)
      }, {
        name: "tags",
        text: $$("admin.pool.tab.tags"),
        padded: false,
        content: (function(_this) {
          return function() {
            return _this.__tagFormPane;
          };
        })(this)
      }, {
        name: "transitions",
        text: $$("admin.pool.tab.transitions"),
        padded: false,
        content: (function(_this) {
          return function() {
            return _this.renderTransitionsTab();
          };
        })(this)
      }
    ];
    if (this.canWriteAcl()) {
      tabs.push({
        name: "acl",
        padded: false,
        text: $$("admin.pool.tab.system_rights"),
        content: (function(_this) {
          return function() {
            return _this.renderAclTab();
          };
        })(this)
      });
    }
    ref = this.__plugins;
    for (i = 0, len = ref.length; i < len; i++) {
      p = ref[i];
      p.getTabs(tabs);
    }
    if (ez5.version("6")) {
      tabs.push({
        name: "sharing",
        text: $$("admin.pool.extra.tab"),
        content: (function(_this) {
          return function() {
            return _this.renderExtraOptionsTab();
          };
        })(this)
      });
      if (this.hasJanitorSettings()) {
        tabs.push({
          name: "janitor",
          text: $$("admin.pool.tab.janitor"),
          content: (function(_this) {
            return function() {
              return _this.renderJanitorTab();
            };
          })(this)
        });
      }
      tabs.push({
        name: "statistics",
        text: $$("admin.pool.tab.stats"),
        load_on_show: true,
        content: (function(_this) {
          return function() {
            return _this.renderStatisticsTab();
          };
        })(this)
      });
    }
    return tabs;
  };

  Pool.prototype.hasJanitorSettings = function() {
    var ref, ref1, ref2;
    if (ez5.version("6") && ((ref = ez5.session.getBaseConfig()) != null ? (ref1 = ref.janitor) != null ? (ref2 = ref1.object_and_file_removal) != null ? ref2.allow_overwrite : void 0 : void 0 : void 0)) {
      return true;
    }
    return false;
  };

  Pool.prototype.getVirtualTags = function(data) {
    var displyName, k, ownerShipTag, ref, ref1, ref2, tagData, v, who;
    if (!(data != null ? data._generated_rights : void 0)) {
      return null;
    }
    if ((ref = data._generated_rights) != null ? ref.owner : void 0) {
      return null;
    }
    if ((ref1 = this.data.pool.custom_data) != null ? (ref2 = ref1.ownership_tag) != null ? ref2.enabled : void 0 : void 0) {
      if (data._owner) {
        displyName = this.data.pool.custom_data.ownership_tag.text_with_owner;
        who = AclWho.newInstance(data._owner);
        if (!who) {
          displyName = this.data.pool.custom_data.ownership_tag.text_without_owner;
        } else {
          for (k in displyName) {
            v = displyName[k];
            if (v.indexOf("%owner%") > -1) {
              displyName[k] = v.replace("%owner%", who.getDisplayText());
            }
          }
        }
      } else {
        displyName = this.data.pool.custom_data.ownership_tag.text_without_owner;
      }
      tagData = {
        _id: "ownership_tag",
        _basetype: "tag",
        tag: {
          _id: "ownership_tag",
          displayname: displyName,
          frontend_prefs: {
            webfrontend: {
              icon: this.data.pool.custom_data.ownership_tag.icon,
              color: this.data.pool.custom_data.ownership_tag.color
            }
          }
        }
      };
      ownerShipTag = new TagSimple({
        data: tagData
      });
      return [ownerShipTag];
    } else {
      return null;
    }
  };

  Pool.prototype.allowSharing = function(data) {
    var groups, i, len, match, owner_sharing, ref, ref1, ref2, sharingUser, who;
    owner_sharing = (ref = this.data.pool.custom_data) != null ? ref.owner_sharing : void 0;
    if ((owner_sharing != null ? owner_sharing.enabled : void 0) && ((ref1 = owner_sharing.sharing_users) != null ? ref1.length : void 0) > 0) {
      if (data._generated_rights.owner) {
        return true;
      }
      groups = ez5.session.getGroups();
      ref2 = owner_sharing.sharing_users;
      for (i = 0, len = ref2.length; i < len; i++) {
        sharingUser = ref2[i];
        match = false;
        who = AclWho.newInstance(sharingUser.user);
        if (!who) {
          continue;
        }
        if (who instanceof AclWhoGroup) {
          if (groups.find((function(_this) {
            return function(g) {
              return g.getId() === who.getGroup().getId();
            };
          })(this))) {
            return false;
          }
        } else if (who instanceof AclWhoUser) {
          if (who.getId() === ez5.session.user.getId()) {
            return false;
          }
        }
      }
    }
    return true;
  };

  Pool.prototype.destroy = function() {
    var i, len, p, ref;
    Pool.__super__.destroy.call(this);
    ref = this.__plugins || [];
    for (i = 0, len = ref.length; i < len; i++) {
      p = ref[i];
      p.destroy();
    }
  };

  Pool.renderPoolPath = function(pool_path) {
    var i, idx, len, p, path_els;
    if (!pool_path) {
      return;
    }
    path_els = [];
    for (idx = i = 0, len = pool_path.length; i < len; idx = ++i) {
      p = pool_path[idx];
      if (idx === 0) {
        continue;
      }
      path_els.push(ez5.loca.getBestFrontendValue(p.pool.name));
    }
    return ResultObject.renderPath(path_els);
  };

  Pool.renderPlainPoolPath = function(pool_path, separator) {
    var i, idx, len, p, path_els;
    if (separator == null) {
      separator = "/";
    }
    if (!pool_path) {
      return null;
    }
    path_els = [];
    for (idx = i = 0, len = pool_path.length; i < len; idx = ++i) {
      p = pool_path[idx];
      if (idx === 0) {
        continue;
      }
      path_els.push(ez5.loca.getBestFrontendValue(p.pool.name));
    }
    return path_els.join(" " + separator + " ");
  };

  return Pool;

})(SystemListManagerHierarchyItem);

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

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

  PoolForPoolManagerPoolField.prototype.select = function(ev) {
    return CUI.ListViewTreeNode.prototype.select.call(this, ev);
  };

  return PoolForPoolManagerPoolField;

})(Pool);
// Generated by CoffeeScript 1.12.7
var TagFilter,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function TagFilter() {
    this.findTagFormTag = bind(this.findTagFormTag, this);
    return TagFilter.__super__.constructor.apply(this, arguments);
  }

  TagFilter.prototype.initOpts = function() {
    TagFilter.__super__.initOpts.call(this);
    return this.addOpts({
      tagForm: {
        check: TagFormSimple
      },
      name: {
        mandatory: true,
        check: String
      },
      data: {
        check: "PlainObject"
      },
      ui: {
        check: String
      },
      conditionTypes: {
        mandatory: true,
        "default": ["any", "all", "not"],
        check: function(v) {
          return (v != null ? v.length : void 0) > 0;
        }
      }
    });
  };

  TagFilter.prototype.readOpts = function() {
    TagFilter.__super__.readOpts.call(this);
    if (this._data) {
      return this.initData(this._data);
    }
  };

  TagFilter.prototype.initData = function(data) {
    if (!data[this._name]) {
      data[this._name] = {};
    }
    return CUI.util.assert(CUI.util.isPlainObject(data[this._name]), "TagFilter.initData", "data[" + this._name + "] needs to be PlainObject", {
      data: data
    });
  };

  TagFilter.prototype.getDataFieldProxy = function(_opts) {
    var opts;
    if (_opts == null) {
      _opts = {};
    }
    opts = CUI.Element.readOpts(_opts, "TagFilter.getDataFieldProxy", {
      data: {
        "default": this._data,
        mandatory: true,
        check: "PlainObject"
      },
      onDataChanged: {
        check: Function
      }
    });
    this.initData(opts.data);
    return new CUI.DataFieldProxy({
      maximize_horizontal: true,
      onDataChanged: (function(_this) {
        return function(data, df) {
          return typeof opts.onDataChanged === "function" ? opts.onDataChanged(data, df) : void 0;
        };
      })(this),
      element: (function(_this) {
        return function() {
          return _this.__getTagFormField(opts.data[_this._name], _this._conditionTypes);
        };
      })(this)
    });
  };

  TagFilter.prototype.__getTagFormField = function(data, conditionTypes) {
    return this._tagForm.renderAsFilterEditor(data, conditionTypes);
  };

  TagFilter.prototype.__getPopoverTitle = function() {
    return this._tagForm.renderFilterEditorTitle();
  };

  TagFilter.prototype.getField = function(_opts) {
    var field, opts;
    if (_opts == null) {
      _opts = {};
    }
    opts = CUI.Element.readOpts(_opts, "TagFilter.getField", {
      onDataChanged: {
        check: Function
      },
      form: {}
    });
    return field = {
      ui: this._ui,
      type: CUI.FormPopover,
      data: this._data,
      form: opts.form,
      onDataInit: (function(_this) {
        return function(df, _data) {
          _this.initData(_data);
        };
      })(this),
      button: {
        text: $$("tag.filter.button")
      },
      onDataChanged: (function(_this) {
        return function(data, df) {
          return typeof opts.onDataChanged === "function" ? opts.onDataChanged(data, df) : void 0;
        };
      })(this),
      popover: {
        "class": "ez5-tag-filter-popup",
        pane: {
          padded: false,
          header_left: this.__getPopoverTitle()
        }
      },
      fields: (function(_this) {
        return function(df) {
          var _data;
          if (!_this._data) {
            _data = df.getData();
          } else {
            _data = void 0;
          }
          return [
            _this.getDataFieldProxy({
              data: _data
            })
          ];
        };
      })(this),
      renderDisplayContent: (function(_this) {
        return function(df) {
          return _this.__renderDisplayContent(df);
        };
      })(this)
    };
  };

  TagFilter.prototype.__renderDisplayContent = function(dataField) {
    var c, condition, conds, content, div, i, j, len, len1, ref, tag, tag_id, tag_ids;
    content = [];
    conds = {};
    ref = dataField.getData()[this._name];
    for (condition in ref) {
      tag_ids = ref[condition];
      for (i = 0, len = tag_ids.length; i < len; i++) {
        tag_id = tag_ids[i];
        if (!conds[condition]) {
          conds[condition] = CUI.dom.div("ez5-tag-filter-condition ez5-tag-filter-condition-" + condition);
          content.push(conds[condition]);
          CUI.dom.append(conds[condition], new LocaLabel({
            "class": "ez5-tag-filter-condition-block",
            loca_key: "tag.filter.condition.block." + condition,
            multiline: true
          }).DOM);
        }
        tag = this._tagForm.findTagByAnyId(tag_id);
        if (!tag) {
          CUI.dom.append(conds[condition], tag_id + "?");
        } else {
          CUI.dom.append(conds[condition], tag.getLabel(true, true).DOM);
        }
      }
    }
    div = CUI.dom.div("ez5-tag-filter-conditions");
    if (content.length) {
      for (j = 0, len1 = content.length; j < len1; j++) {
        c = content[j];
        CUI.dom.append(div, c);
      }
    } else {
      CUI.dom.append(div, new CUI.EmptyLabel({
        text: $$("tag.filter.no_filter_defined")
      }).DOM);
    }
    return div;
  };

  TagFilter.prototype.findTagFormTag = function(tagFormTag) {
    var c, i, len, ref;
    ref = this.conditions;
    for (i = 0, len = ref.length; i < len; i++) {
      c = ref[i];
      if (c.findTagFormTag(tagFormTag)) {
        return tagFormTag;
      }
    }
    return null;
  };

  TagFilter.prototype.getData = function() {
    return this._data[this._name];
  };

  TagFilter.prototype.getSaveData = function() {
    var sd;
    sd = this.getData();
    if (CUI.util.isEmptyObject(sd)) {
      return null;
    } else {
      return CUI.util.copyObject(sd, true);
    }
  };

  TagFilter.matchesTags = function(tagfilter, tags) {
    var tagfilter_ok;
    if (tagfilter) {
      tagfilter_ok = false;
      (function() {
        var all, any, i, j, k, len, len1, len2, ref, ref1, ref2, ref3, tag, tag_ids;
        tag_ids = (function() {
          var i, len, ref, results;
          ref = tags || [];
          results = [];
          for (i = 0, len = ref.length; i < len; i++) {
            tag = ref[i];
            results.push(tag._id);
          }
          return results;
        })();
        if (((ref = tagfilter.any) != null ? ref.length : void 0) > 0) {
          tagfilter_ok = false;
          ref1 = tagfilter.any;
          for (i = 0, len = ref1.length; i < len; i++) {
            any = ref1[i];
            if (indexOf.call(tag_ids, any) >= 0) {
              tagfilter_ok = true;
              break;
            }
          }
          if (!tagfilter_ok) {
            return;
          }
        }
        if (tagfilter.all) {
          tagfilter_ok = true;
          ref2 = tagfilter.all;
          for (j = 0, len1 = ref2.length; j < len1; j++) {
            all = ref2[j];
            if (indexOf.call(tag_ids, all) < 0) {
              tagfilter_ok = false;
              break;
            }
          }
          if (!tagfilter_ok) {
            return;
          }
        }
        if (tagfilter.not) {
          tagfilter_ok = true;
          ref3 = tagfilter.not;
          for (k = 0, len2 = ref3.length; k < len2; k++) {
            all = ref3[k];
            if (indexOf.call(tag_ids, all) >= 0) {
              tagfilter_ok = false;
              break;
            }
          }
        }
        if (!(tagfilter.any || tagfilter.all || tagfilter.not)) {
          tagfilter_ok = true;
        }
      })();
    } else {
      tagfilter_ok = true;
    }
    return tagfilter_ok;
  };

  return TagFilter;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var TagSetUnset,
  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;

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

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

  TagSetUnset.prototype.initOpts = function() {
    TagSetUnset.__super__.initOpts.call(this);
    return this.addOpts({
      conditionTypes: {
        mandatory: true,
        "default": ["set", "unset"],
        check: function(v) {
          return (v != null ? v.length : void 0) > 0;
        }
      }
    });
  };

  TagSetUnset.prototype.__getTagFormField = function(data, conditionTypes) {
    return this._tagForm.renderAsSetUnsetEditor(data);
  };

  TagSetUnset.prototype.__getPopoverTitle = function() {
    return new LocaLabel({
      loca_key: "tag.form.editor.set_unset.title"
    }).DOM;
  };

  TagSetUnset.prototype.__renderDisplayContent = function(dataField) {
    var c, condition, conditionElements, content, div, i, j, k, len, len1, len2, ref, ref1, tag, tagData;
    content = [];
    conditionElements = {};
    ref = ["set", "unset"];
    for (i = 0, len = ref.length; i < len; i++) {
      condition = ref[i];
      conditionElements[condition] = CUI.dom.div("ez5-tag-filter-condition ez5-tag-filter-condition-" + condition);
      content.push(conditionElements[condition]);
      CUI.dom.append(conditionElements[condition], new LocaLabel({
        "class": "ez5-tag-filter-condition-block",
        loca_key: "tag.filter.condition.block." + condition,
        multiline: true
      }).DOM);
    }
    ref1 = dataField.getData()[this._name].tags || [];
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      tagData = ref1[j];
      tag = this._tagForm.findTagByAnyId(tagData._id);
      condition = tagData.set ? "set" : "unset";
      if (!tag) {
        CUI.dom.append(conditionElements[condition], tagData._id + "?");
      } else {
        CUI.dom.append(conditionElements[condition], tag.getLabel(true, true).DOM);
      }
    }
    div = CUI.dom.div("ez5-tag-filter-conditions");
    if (content.length) {
      for (k = 0, len2 = content.length; k < len2; k++) {
        c = content[k];
        CUI.dom.append(div, c);
      }
    } else {
      CUI.dom.append(div, new CUI.EmptyLabel({
        text: $$("tag.filter.no_filter_defined")
      }).DOM);
    }
    return div;
  };

  return TagSetUnset;

})(TagFilter);
// Generated by CoffeeScript 1.12.7
var ObjecttypeListViewItem,
  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;

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

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

  ObjecttypeListViewItem.prototype.initOpts = function() {
    ObjecttypeListViewItem.__super__.initOpts.call(this);
    return this.addOpts({
      objecttype: {
        mandatory: true,
        check: Objecttype
      }
    });
  };

  ObjecttypeListViewItem.prototype.readOpts = function() {
    ObjecttypeListViewItem.__super__.readOpts.call(this);
    this.__plugins = Objecttype.plugins.newPlugins({
      objecttypeListViewItem: this
    });
    this.objecttype = this._objecttype;
    return this.id = this.objecttype.table.id();
  };

  ObjecttypeListViewItem.prototype.managerInstance = function() {
    return ObjecttypeAdminManager;
  };

  ObjecttypeListViewItem.prototype.getApi = function() {
    return 'objecttype';
  };

  ObjecttypeListViewItem.prototype.getObjecttype = function() {
    return this.objecttype;
  };

  ObjecttypeListViewItem.prototype.remove = function() {
    return this.manager.setStatus();
  };

  ObjecttypeListViewItem.prototype.load = function() {
    var dfr;
    dfr = new CUI.Deferred();
    ObjecttypeListViewItem.__super__.load.call(this).done((function(_this) {
      return function() {
        var config, fieldName, i, j, k, l, len1, len2, len3, padding_str, plugin, promises, ref, ref1, ref2, ref3, ref4, ref5, ref6, size_str;
        ref = ["_tags", "_transitions", "_acl", '_columnfilters'];
        for (i = 0, len1 = ref.length; i < len1; i++) {
          k = ref[i];
          if (!_this.data[k]) {
            _this.data[k] = [];
          }
        }
        ref1 = ['_maskfilters'];
        for (j = 0, len2 = ref1.length; j < len2; j++) {
          k = ref1[j];
          if (!_this.data[k]) {
            _this.data[k] = {};
          }
        }
        _this.data.objecttype.standard_mask_from_objecttype = !_this.data._standard_masks;
        _this.data.objecttype.standard_masks = _this.data._standard_masks || [];
        _this.data._export_asset_filenames = _this.data._export_asset_filenames || {};
        _this.data.objecttype.display_name = (ref2 = ez5.schema.CURRENT._table_by_name) != null ? ref2[_this.data.objecttype.name]._name_localized : void 0;
        promises = [];
        _this.tagForm = new TagFormForManager({
          context: _this
        });
        _this.tagFormMaskfilter = new TagForm({
          context: _this
        });
        promises.push(_this.tagForm.load());
        promises.push(_this.tagFormMaskfilter.load());
        if (ez5.version("6")) {
          if (!_this.data.objecttype.janitor_policy) {
            _this.data.objecttype.janitor_policy = {};
            _this.data.objecttype.janitor_policy.override_base_config = false;
          } else {
            if (!_this.data.objecttype.janitor_policy.hasOwnProperty("override_base_config")) {
              _this.data.objecttype.janitor_policy.override_base_config = true;
            }
          }
          _this.__cached_janitor_values = null;
          if (_this.data.objecttype.janitor_policy.override_base_config) {
            if (!_this.data.objecttype.janitor_policy.object_purge) {
              _this.data.objecttype.janitor_policy.object_purge = {};
            }
            if (!_this.data.objecttype.janitor_policy.file_link_delete) {
              _this.data.objecttype.janitor_policy.file_link_delete = {};
            }
          }
          if (!_this.objecttype.poolLink()) {
            if (!_this.data.objecttype.watermark) {
              _this.data.objecttype.watermark = {};
            } else {
              _this.data.objecttype.watermark.watermark_enabled = !!((ref3 = _this.data.objecttype.watermark.image) != null ? ref3._id : void 0);
            }
          }
          if (!_this.objecttype.poolLink()) {
            if (!_this.data.objecttype.caption) {
              _this.data.objecttype.caption = {};
            } else if (typeof _this.data.objecttype.caption === "object") {
              ref4 = _this.data.objecttype.caption;
              for (fieldName in ref4) {
                config = ref4[fieldName];
                if (config && typeof config === "object") {
                  if (config.size) {
                    size_str = String(config.size);
                    if (/^\d+(\.\d+)?$/.test(size_str)) {
                      config.size = size_str + "px";
                    }
                  }
                  if (config.padding) {
                    padding_str = String(config.padding);
                    if (/^\d+$/.test(padding_str)) {
                      config.padding = padding_str + "px";
                    }
                  }
                }
              }
            }
          }
        }
        if (!((ref5 = _this.data.objecttype.custom_data) != null ? ref5.webfrontend : void 0)) {
          _this.data.objecttype.custom_data = {
            webfrontend: {}
          };
        }
        if (!_this.data.objecttype.custom_data.webfrontend.linkedObjectsFilters) {
          _this.data.objecttype.custom_data.webfrontend.linkedObjectsFilters = [];
        }
        ref6 = _this.__plugins;
        for (l = 0, len3 = ref6.length; l < len3; l++) {
          plugin = ref6[l];
          plugin.onLoad();
        }
        return CUI.when(promises).done(dfr.resolve).fail(dfr.reject);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  ObjecttypeListViewItem.prototype.deselect = function(ev) {
    return ObjecttypeListViewItem.__super__.deselect.call(this, ev).done((function(_this) {
      return function() {
        var ref, ref1, ref2, ref3;
        if ((ref = _this.tagForm) != null) {
          ref.destroy();
        }
        if ((ref1 = _this.aclManager) != null) {
          ref1.destroy();
        }
        if ((ref2 = _this.maskTree) != null) {
          ref2.destroy();
        }
        if ((ref3 = _this.tagFormMaskfilter) != null) {
          ref3.destroy();
        }
        delete _this.tagForm;
        delete _this.aclManager;
        delete _this.maskTree;
        return delete _this.tagFormMaskfilter;
      };
    })(this));
  };

  ObjecttypeListViewItem.prototype.save = function(ev) {
    return ObjecttypeListViewItem.__super__.save.call(this, ev).done((function(_this) {
      return function() {
        return ez5.objecttypes.load().done(function() {
          ez5.objecttypes.init();
          return ez5.ObjecttypeMainList.reloadIcons(_this.needsUserReloadPrompt());
        });
      };
    })(this));
  };

  ObjecttypeListViewItem.prototype.isWritable = function() {
    return true;
  };

  ObjecttypeListViewItem.prototype.needsUserReloadPrompt = function() {
    var initialMainMenuIcon, newMainMenuIcon;
    initialMainMenuIcon = CUI.util.copyObject(this.initialData.objecttype.show_in_main_menu_with_icon);
    newMainMenuIcon = this.data.objecttype.show_in_main_menu_with_icon;
    return (CUI.util.isEmpty(initialMainMenuIcon) && !CUI.util.isEmpty(newMainMenuIcon)) || (!CUI.util.isEmpty(initialMainMenuIcon) && CUI.util.isEmpty(newMainMenuIcon));
  };

  ObjecttypeListViewItem.prototype.getDisplayName = function() {
    return this.objecttype.nameLocalized();
  };

  ObjecttypeListViewItem.prototype.getDescription = function() {
    var ref;
    return ez5.loca.getBestFrontendValue((ref = this.data) != null ? ref.objecttype.description : void 0);
  };

  ObjecttypeListViewItem.prototype.getContact = function() {
    if (this.data.objecttype.contact) {
      return User.newInstance({
        user: this.data.objecttype.contact
      });
    } else {
      return null;
    }
  };

  ObjecttypeListViewItem.prototype.renderContent = function() {
    return [
      new CUI.Label({
        "class": "ez5-objecttype-name",
        text: this.getDisplayName()
      }), new CUI.Label({
        "class": "ez5-objecttype-table-name",
        text: this.objecttype.name(),
        size: "mini",
        appearance: "secondary"
      }), new CUI.Label({
        "class": "ez5-objecttype-display-types",
        text: this.objecttype.getDisplayType(),
        size: "mini",
        appearance: "secondary",
        multiline: true
      })
    ];
  };

  ObjecttypeListViewItem.prototype.initTagData = function(tag) {
    var enabled, sticky, td;
    td = tag.getData();
    sticky = td.sticky;
    enabled = td.enabled;
    return Pool.prototype.setTagDefault.call(this, tag, enabled, sticky);
  };

  ObjecttypeListViewItem.prototype.renderTagsTab = function() {
    var privateTagsCheckboxEmptyLabel, tagFormPane, tree, updateEditor;
    if (!this.objecttype.hasTags()) {
      return;
    }
    if (this.hasOwnTags()) {
      tree = this.tagForm.getTree();
      tagFormPane = new CUI.SimplePane({
        content: tree,
        footer_right: new CUI.Checkbox({
          name: "_private_tags",
          text: $$("admin.objecttype.private_tags"),
          data: this.data,
          onDataChanged: (function(_this) {
            return function() {
              if (!_this.data._private_tags) {
                _this.data._tags.splice(0);
              }
              return updateEditor();
            };
          })(this)
        }).start()
      });
      privateTagsCheckboxEmptyLabel = new CUI.EmptyLabel({
        centered: true,
        text: $$("admin.objecttypemanager.tags.individual-checkbox.hint")
      });
      updateEditor = (function(_this) {
        return function() {
          if (_this.data._private_tags) {
            _this.tagForm.setInactive(false);
            tagFormPane.replace(tree, "center");
          } else {
            _this.tagForm.setInactive(true);
            tagFormPane.replace(privateTagsCheckboxEmptyLabel, "center");
          }
          return _this.tagForm.load(_this);
        };
      })(this);
      updateEditor();
      return tagFormPane;
    } else {
      return new CUI.EmptyLabel({
        centered: true,
        text: $$("admin.objecttypemanager.tags.not.available.hint")
      });
    }
  };

  ObjecttypeListViewItem.prototype.renderTransitionsTab = function() {
    if (!this.objecttype.hasTags()) {
      return;
    }
    if (this.hasOwnTransitions()) {
      return Pool.prototype.renderTransitionsTab.call(this, false);
    } else {
      return new CUI.EmptyLabel({
        centered: true,
        text: $$("admin.objecttypemanager.transition.not.available.hint")
      });
    }
  };

  ObjecttypeListViewItem.prototype.renderColumnRightsTab = function() {
    var colfilter, colfilters, cols, div, fields, i, len1, minusButton, plusButton, ref, set_status, trigger_changed;
    trigger_changed = (function(_this) {
      return function() {
        return CUI.Events.trigger({
          type: "data-changed",
          node: _this.columns_right_tree
        });
      };
    })(this);
    set_status = (function(_this) {
      return function() {
        if (_this.columns_right_tree.getSelectedNode()) {
          return minusButton.enable();
        } else {
          return minusButton.disable();
        }
      };
    })(this);
    minusButton = new LocaButton({
      icon: "minus",
      loca_key: "objecttype.list.view.item.column_rights.button.minus",
      group: "plus-minus",
      onClick: (function(_this) {
        return function() {
          var ref;
          if ((ref = _this.columns_right_tree.getSelectedNode()) != null) {
            ref.remove();
          }
          trigger_changed();
          return set_status();
        };
      })(this)
    });
    plusButton = new LocaButton({
      icon: "plus",
      loca_key: "objecttype.list.view.item.column_rights.button.plus",
      group: "plus-minus",
      onClick: (function(_this) {
        return function() {
          var cr, new_data;
          new_data = {};
          cr = new ColumnRightItem({
            tagForm: _this.tagForm,
            data: new_data,
            objecttype: _this._objecttype
          });
          _this.columns_right_tree.addNode(cr);
          trigger_changed();
          cr.select();
          return set_status();
        };
      })(this)
    });
    fields = [
      {
        th_label: "objecttype.list.view.item.colum_rights.tab.title.name"
      }, {
        th_label: "objecttype.list.view.item.colum_rights.tab.title.columns"
      }
    ];
    cols = ['auto', 'maximize'];
    if (this._objecttype.hasTags()) {
      fields.push({
        th_label: "objecttype.list.view.item.colum_rights.tab.title.tagfilter"
      });
      cols.push('auto');
    }
    fields.push({
      th_label: "objecttype.list.view.item.colum_rights.tab.title.who"
    });
    cols.push('auto');
    this.columns_right_tree = new ListViewEditTree({
      "class": 'cui-lv--has-datafields',
      cols: cols,
      fields: fields,
      rowMove: false,
      no_hierarchy: true,
      selectableRows: true,
      onSelect: set_status,
      onDeselect: set_status,
      footer_left: [plusButton, minusButton]
    });
    div = this.columns_right_tree.render();
    colfilters = [];
    ref = this.data._columnfilters || [];
    for (i = 0, len1 = ref.length; i < len1; i++) {
      colfilter = ref[i];
      colfilters.push(new ColumnRightItem({
        tagForm: this.tagForm,
        data: colfilter,
        objecttype: this._objecttype
      }));
    }
    this.columns_right_tree.load_data(colfilters);
    set_status();
    return div;
  };

  ObjecttypeListViewItem.prototype.renderLinkedObjectsFiltersTab = function() {
    var cols, fields, i, len1, linkedObjectColumns, linkedObjectFilter, minusButton, plusButton, ref, renderedTree, setButtonStatus, triggerChange;
    triggerChange = (function(_this) {
      return function() {
        CUI.Events.trigger({
          type: "data-changed",
          node: _this.__linkedObjectsFiltersTree
        });
      };
    })(this);
    setButtonStatus = (function(_this) {
      return function() {
        if (_this.__linkedObjectsFiltersTree.getSelectedNode()) {
          minusButton.enable();
        } else {
          minusButton.disable();
        }
      };
    })(this);
    minusButton = new LocaButton({
      icon: "minus",
      loca_key: "objecttype.list.view.item.linked_objects_filters.button.minus",
      group: "plus-minus",
      onClick: (function(_this) {
        return function() {
          var ref;
          if ((ref = _this.__linkedObjectsFiltersTree.getSelectedNode()) != null) {
            ref.remove();
          }
          triggerChange();
          return setButtonStatus();
        };
      })(this)
    });
    plusButton = new LocaButton({
      icon: "plus",
      loca_key: "objecttype.list.view.item.linked_objects_filters.button.plus",
      group: "plus-minus",
      onClick: (function(_this) {
        return function() {
          var node;
          node = new LinkedObjectFilterTreeNode({
            tagForm: _this.tagForm,
            data: {},
            objecttype: _this._objecttype
          });
          _this.__linkedObjectsFiltersTree.addNode(node);
          triggerChange();
          node.select();
          return setButtonStatus();
        };
      })(this)
    });
    fields = [
      {
        th_label: "objecttype.list.view.item.linked_objects_filters.tab.title.name"
      }, {
        th_label: "objecttype.list.view.item.linked_objects_filters.tab.title.fields"
      }, {
        th_label: "objecttype.list.view.item.linked_objects_filters.tab.title.only_allow_select_last_children"
      }, {
        th_label: "objecttype.list.view.item.linked_objects_filters.tab.title.filter"
      }
    ];
    cols = ['auto', 'maximize', 'auto', 'auto'];
    this.__linkedObjectsFiltersTree = new ListViewEditTree({
      "class": 'cui-lv--has-datafields',
      cols: cols,
      fields: fields,
      rowMove: false,
      no_hierarchy: true,
      selectableRows: true,
      onSelect: setButtonStatus,
      onDeselect: setButtonStatus,
      footer_left: [plusButton, minusButton]
    });
    linkedObjectColumns = [];
    ref = this.data.objecttype.custom_data.webfrontend.linkedObjectsFilters;
    for (i = 0, len1 = ref.length; i < len1; i++) {
      linkedObjectFilter = ref[i];
      linkedObjectColumns.push(new LinkedObjectFilterTreeNode({
        data: linkedObjectFilter,
        objecttype: this._objecttype
      }));
    }
    renderedTree = this.__linkedObjectsFiltersTree.render();
    this.__linkedObjectsFiltersTree.load_data(linkedObjectColumns);
    setButtonStatus();
    return renderedTree;
  };

  ObjecttypeListViewItem.prototype.renderAclTab = function() {
    this.aclManager = null;
    return new CUI.EmptyLabel({
      centered: true,
      text: $$("admin.objecttypemanager.acl_manager.not.available.hint")
    });
  };

  ObjecttypeListViewItem.prototype.renderMaskfilterTab = function() {
    var div, i, len1, mask, ref;
    this.maskfilters = [];
    if (this.getMasks().length < 2) {
      return;
    }
    this.maskTree = new ListViewEditTree({
      "class": 'cui-lv--has-datafields',
      no_hierarchy: true,
      fields: [
        {
          th_label: "admin.easydb.objecttype.mask.name"
        }, {
          th_label: "admin.easydb.objecttype.mask.tagfilter"
        }
      ],
      rowMove: false,
      selectableRows: false
    });
    ref = this.getMasks();
    for (i = 0, len1 = ref.length; i < len1; i++) {
      mask = ref[i];
      this.maskfilters.push(new ObjecttypeAdminManagerMaskItem({
        mask: mask,
        data: this.data._maskfilters,
        tagForm: this.tagFormMaskfilter,
        objecttypeListViewItem: this
      }));
    }
    div = this.maskTree.render();
    this.maskTree.load_data(this.maskfilters);
    return div;
  };

  ObjecttypeListViewItem.prototype.generalFields = function() {
    var _fieldName, _filename, base_help, differentTableCheck, easField, eas_field, eas_fields, exportAssetFilenames, f, fields, fn, form_fields, i, j, l, len1, len2, len3, len4, len5, linkedEas, m, n, o, opts, ref, ref1, ref2, ref3, ref4, ref5, replacements, top_fields;
    opts = [
      {
        text: $$("admin.objecttype.asset_profile.none"),
        value: "none"
      }
    ];
    top_fields = [
      {
        type: CUI.Output,
        form: {
          label: $$("admin.objecttype.id")
        },
        name: "_id"
      }, {
        type: CUI.Output,
        form: {
          label: $$("admin.objecttype.internal_name")
        },
        name: "name"
      }, {
        type: CUI.Output,
        form: {
          label: $$("admin.objecttype.display_name")
        },
        name: "display_name"
      }, {
        type: UserGroupSelector,
        form: {
          label: $$("admin.objecttype.contact")
        },
        name: "contact",
        aclWhoManager: new AclWhoManager({
          who_filter: ["user"]
        }),
        data: this.data.objecttype
      }, {
        type: CUI.MultiInput,
        user_selectable: ez5.session.getPref("languages_user_selection"),
        textarea: true,
        form: {
          label: $$("admin.objecttype.description")
        },
        name: "description",
        control: ez5.loca.getLanguageControlAdmin()
      }, ez5.version("6") ? {
        type: CUI.IconInput,
        placeholder: $$("admin.objecttype.show_in_main_menu_with_icon|placeholder"),
        form: {
          label: $$("admin.objecttype.empty_placeholder_icon|label"),
          hint: $$("admin.objecttype.show_in_main_menu_with_icon|hint")
        },
        name: "empty_placeholder_icon"
      } : void 0
    ];
    top_fields.push({
      type: ez5.version("6") ? CUI.IconInput : CUI.Input,
      placeholder: $$("admin.objecttype.show_in_main_menu_with_icon|placeholder"),
      form: {
        label: $$("admin.objecttype.show_in_main_menu_with_icon|label"),
        hint: $$("admin.objecttype.show_in_main_menu_with_icon|hint")
      },
      name: "show_in_main_menu_with_icon"
    });
    this.objecttype.removeAllMasks();
    ref = this.getMasks();
    for (i = 0, len1 = ref.length; i < len1; i++) {
      m = ref[i];
      this.objecttype.addMask(m);
    }
    fields = [
      {
        type: CUI.Form,
        form: {
          label: $$("objecttype.list.view.tag.general.title")
        },
        fields: top_fields
      }
    ];
    eas_fields = [];
    ref1 = this.objecttype.getEASFields("all");
    for (j = 0, len2 = ref1.length; j < len2; j++) {
      easField = ref1[j];
      if (easField instanceof LinkedObject) {
        differentTableCheck = false;
        ref2 = easField.linkMask().getEASFields("all");
        for (l = 0, len3 = ref2.length; l < len3; l++) {
          linkedEas = ref2[l];
          if (linkedEas.table._id !== this.objecttype.table._id) {
            if (!(((ref3 = linkedEas.mask) != null ? ref3.nestedTableField : void 0) instanceof ReverseLinkedTable)) {
              differentTableCheck = true;
              break;
            }
          }
        }
        if (!differentTableCheck) {
          continue;
        }
      }
      eas_fields.push(easField);
    }
    if (ez5.version("6.12") && eas_fields.length === 0) {
      top_fields.push({
        type: CUI.Select,
        form: {
          label: $$("admin.objecttype.profile_for_dc_export")
        },
        data: this.data.objecttype,
        name: "mapping_dc_export",
        options: ez5.metadata.getMappingOpts(opts, {
          dc_export: true
        })
      });
    }
    if (eas_fields.length > 0) {
      base_help = "";
      ref4 = this.objecttype.getFields("all", false, function(f) {
        if (!(f instanceof Field)) {
          return;
        }
        if (f instanceof NestedTable) {
          return;
        }
        if (!f.id()) {
          return;
        }
        return true;
      });
      for (n = 0, len4 = ref4.length; n < len4; n++) {
        f = ref4[n];
        if (f instanceof CustomDataType) {
          continue;
        }
        if (f instanceof LinkedObject) {
          base_help += "%" + f.fullName() + "._standard.1.text%\n";
        } else if (f instanceof LocaTextColumn) {
          base_help += "%" + f.fullName() + ".<lang>%\n";
        } else {
          base_help += "%" + f.fullName() + "%\n";
        }
      }
      base_help += "%_export.name%\n";
      base_help += "%_system.easydb.name%\n";
      base_help += "%_global_object_id%\n";
      base_help += "%_system_object_id%\n";
      base_help += "%_pool.name.<lang>%\n";
      base_help += "%_asset.original_filename%\n";
      base_help += "%_asset.version%\n";
      base_help += "%_asset.class%\n";
      base_help += "%_asset.extension%\n";
      base_help += "%_asset.technical_metadata.width%\n";
      base_help += "%_asset.technical_metadata.height%\n";
      base_help += "%_asset.technical_metadata.max_dimension%\n";
      top_fields.push(this.__getMappingImageImportField(opts));
      top_fields.push({
        type: CUI.Select,
        form: {
          label: $$("admin.objecttype.profile_for_images_export")
        },
        data: this.data.objecttype,
        name: "mapping_image_export",
        options: ez5.metadata.getMappingOpts(opts, {
          exiftool_export: true
        })
      });
      top_fields.push({
        type: CUI.Select,
        form: {
          label: $$("admin.objecttype.profile_for_dc_export")
        },
        data: this.data.objecttype,
        name: "mapping_dc_export",
        options: ez5.metadata.getMappingOpts(opts, {
          dc_export: true
        })
      });
      form_fields = [];
      for (o = 0, len5 = eas_fields.length; o < len5; o++) {
        eas_field = eas_fields[o];
        fn = eas_field.fullName();
        form_fields.push({
          form: {
            label: eas_field.fullNameLocalized()
          },
          undo_support: false,
          type: CUI.MultiInput,
          name: fn,
          control: ez5.loca.getLanguageControlAdmin(),
          user_selectable: ez5.session.getPref("languages_user_selection"),
          textarea: true
        });
        if (ez5.version("6")) {
          replacements = this.data._filename_replacements[fn];
          if (!replacements || replacements.length === 0) {
            form_fields.pop();
            continue;
          }
          (function(_this) {
            return (function(replacements) {
              var replacementsPopoverButton;
              replacementsPopoverButton = new CUI.FormButton({
                text: $$("objecttype.list.view.item.export_asset_filenames.help"),
                appearance: "flat",
                onClick: function() {
                  var pop;
                  pop = new ez5.HintPopover({
                    element: replacementsPopoverButton,
                    content: new CUI.Label({
                      multiline: true,
                      text: replacements.join("\n")
                    }),
                    padded: true
                  });
                  return pop.show();
                }
              });
              return form_fields.push(replacementsPopoverButton);
            });
          })(this)(replacements);
        }
      }
      if (!ez5.version("6") || (ez5.version("6") && ez5.session.isDebug())) {
        exportAssetFilenames = new CUI.FormButton({
          text: $$("objecttype.list.view.item.export_asset_filenames.help"),
          appearance: "flat",
          onClick: (function(_this) {
            return function() {
              var pop;
              pop = new ez5.HintPopover({
                element: exportAssetFilenames,
                content: new CUI.Label({
                  multiline: true,
                  text: base_help
                }),
                padded: true
              });
              return pop.show();
            };
          })(this)
        });
        form_fields.push(exportAssetFilenames);
      }
      ref5 = this.data._export_asset_filenames;
      for (_fieldName in ref5) {
        _filename = ref5[_fieldName];
        if (form_fields.some((function(_this) {
          return function(f) {
            return f.name === _fieldName;
          };
        })(this))) {
          continue;
        }
        console.log("ObjecttypeListViewItem: We have stored data for a field that does not exist anymore, we skip it", _fieldName, _filename);
        delete this.data._export_asset_filenames[_fieldName];
      }
      fields.push({
        type: CUI.Form,
        data: this.data,
        name: "_export_asset_filenames",
        undo_support: false,
        form: {
          label: $$("objecttype.list.view.item.export_asset_filenames")
        },
        fields: form_fields
      });
    }
    if (!this._objecttype.inMainSearch()) {
      top_fields.push({
        type: CUI.Checkbox,
        form: {
          label: $$("admin.objecttype.show_in_collections")
        },
        name: "show_in_collections"
      });
    }
    top_fields.push({
      type: CUI.Checkbox,
      form: {
        label: $$("admin.objecttype.show_in_facet_grouping")
      },
      name: "show_in_facet_grouping"
    });
    top_fields.push(this.getStandardMaskFieldsForm(this.objecttype, this.data.objecttype, $$("admin.standard_mask.from_datamodel"), $$("admin.standard_mask")));
    return fields;
  };

  ObjecttypeListViewItem.prototype.watermarkFields = function() {
    var eas_field, g, gravity_opts, i, len1, ref, ref1, ref2, ref3, ref4, ref5;
    gravity_opts = [];
    ref = ["n", "e", "s", "w", "ne", "nw", "se", "sw", "c"];
    for (i = 0, len1 = ref.length; i < len1; i++) {
      g = ref[i];
      gravity_opts.push({
        value: g,
        text: $$("admin.pool.watermark.gravity." + g)
      });
    }
    eas_field = new EASField({
      name: "image",
      data_changed: (function(_this) {
        return function(data, field) {
          return console.debug("data_changed on watermark field", field, data);
        };
      })(this)
    });
    return [
      {
        type: CUI.Checkbox,
        name: "watermark_enabled",
        text: $$("admin.pool.watermark.enabled"),
        onDataChanged: (function(_this) {
          return function(data, field) {
            var f, j, len2, ref1, ref2;
            ref1 = field.getForm().getFields();
            for (j = 0, len2 = ref1.length; j < len2; j++) {
              f = ref1[j];
              if (f === field) {
                continue;
              }
              if ((ref2 = _this.data.objecttype.watermark) != null ? ref2.watermark_enabled : void 0) {
                f.enable();
              } else {
                f.disable();
              }
            }
          };
        })(this)
      }, {
        form: {
          label: $$("admin.pool.watermark.picture")
        },
        type: CUI.DataFieldProxy,
        element: eas_field.renderEditorInput(this.data.objecttype.watermark),
        disabled: !((ref1 = this.data.objecttype.watermark) != null ? ref1.watermark_enabled : void 0)
      }, {
        type: CUI.Input,
        placeholder: "0-100",
        form: {
          label: $$("admin.pool.watermark.dissolve")
        },
        name: "dissolve",
        disabled: !((ref2 = this.data.objecttype.watermark) != null ? ref2.watermark_enabled : void 0)
      }, {
        type: CUI.Select,
        options: gravity_opts,
        empty_text: "0-100",
        form: {
          label: $$("admin.pool.watermark.gravity")
        },
        name: "gravity",
        disabled: !((ref3 = this.data.objecttype.watermark) != null ? ref3.watermark_enabled : void 0)
      }, {
        type: CUI.Input,
        placeholder: $$("admin.pool.watermark.size|placeholder"),
        form: {
          label: $$("admin.pool.watermark.size")
        },
        name: "size",
        disabled: !((ref4 = this.data.objecttype.watermark) != null ? ref4.watermark_enabled : void 0)
      }, {
        type: CUI.Checkbox,
        form: {
          label: $$("admin.pool.watermark.tile")
        },
        name: "tile",
        disabled: !((ref5 = this.data.objecttype.watermark) != null ? ref5.watermark_enabled : void 0)
      }
    ];
  };

  ObjecttypeListViewItem.prototype.getEASFields = function() {
    var differentTableCheck, easField, eas_fields, i, j, l, len1, len2, len3, linkedEas, m, ref, ref1, ref2, ref3, ref4, ref5;
    this.objecttype.removeAllMasks();
    ref = this.getMasks();
    for (i = 0, len1 = ref.length; i < len1; i++) {
      m = ref[i];
      this.objecttype.addMask(m);
    }
    eas_fields = [];
    ref1 = this.objecttype.getEASFields("all", null, false);
    for (j = 0, len2 = ref1.length; j < len2; j++) {
      easField = ref1[j];
      if ((ref2 = easField.mask) != null ? ref2.nestedTableField : void 0) {
        continue;
      }
      if (((ref3 = easField.mask) != null ? ref3.nestedTableField : void 0) instanceof ReverseLinkedTable) {
        continue;
      }
      if (easField instanceof LinkedObject) {
        differentTableCheck = false;
        ref4 = easField.linkMask().getEASFields("all");
        for (l = 0, len3 = ref4.length; l < len3; l++) {
          linkedEas = ref4[l];
          if (linkedEas.table._id !== this.objecttype.table._id) {
            if (!(((ref5 = linkedEas.mask) != null ? ref5.nestedTableField : void 0) instanceof ReverseLinkedTable)) {
              differentTableCheck = true;
              break;
            }
          }
        }
        if (!differentTableCheck) {
          continue;
        }
      }
      eas_fields.push(easField);
    }
    return eas_fields;
  };

  ObjecttypeListViewItem.prototype.hasWatermarkSettings = function() {
    if (!ez5.version("6")) {
      return false;
    }
    return !this.objecttype.poolLink() && this.getEASFields().length > 0;
  };

  ObjecttypeListViewItem.prototype.captionFields = function() {
    var differentTableCheck, easField, eas_fields, fields, getEASFieldOption, i, j, len1, len2, linkedEas, ref, ref1, ref2, ref3, showReplacementsButton;
    eas_fields = [];
    ref = this.objecttype.getEASFields("all", null, false);
    for (i = 0, len1 = ref.length; i < len1; i++) {
      easField = ref[i];
      if ((ref1 = easField.fullName()) != null ? ref1.includes("_reverse_nested:") : void 0) {
        continue;
      }
      if (easField instanceof LinkedObject) {
        differentTableCheck = false;
        ref2 = easField.linkMask().getEASFields("all");
        for (j = 0, len2 = ref2.length; j < len2; j++) {
          linkedEas = ref2[j];
          if (linkedEas.table._id !== this.objecttype.table._id) {
            if (!(((ref3 = linkedEas.mask) != null ? ref3.nestedTableField : void 0) instanceof ReverseLinkedTable)) {
              differentTableCheck = true;
              break;
            }
          }
        }
        if (!differentTableCheck) {
          continue;
        }
      }
      eas_fields.push(easField);
    }
    getEASFieldOption = (function(_this) {
      return function() {
        var field_options, isDisabled, l, len3;
        isDisabled = function() {
          var eas_configured, ref4;
          eas_configured = Object.keys((ref4 = _this.data.objecttype) != null ? ref4.caption : void 0);
          if (!eas_configured || eas_configured.length === 0) {
            return false;
          }
          return eas_configured.some(function(f) {
            return f === easField.fullName();
          });
        };
        field_options = [
          {
            value: null,
            text: $$("admin.pool.caption.field.empty_text")
          }
        ];
        for (l = 0, len3 = eas_fields.length; l < len3; l++) {
          easField = eas_fields[l];
          field_options.push({
            text: easField.fullName(),
            value: easField.fullName(),
            disabled: isDisabled()
          });
        }
        return field_options;
      };
    })(this);
    showReplacementsButton = (function(_this) {
      return function(field) {
        return new CUI.Button({
          icon: "question",
          appearance: "flat",
          onClick: function(ev, btn) {
            var caption_help, k, l, len3, ot, pop, ref4, ref5, ref6, ref7, targetFieldName, v;
            caption_help = "";
            targetFieldName = field != null ? (ref4 = field.getForm()) != null ? (ref5 = ref4.getData()) != null ? ref5.field : void 0 : void 0 : void 0;
            if (!targetFieldName) {
              return;
            }
            ref6 = ez5.objecttypes.getObjecttypes() || [];
            for (l = 0, len3 = ref6.length; l < len3; l++) {
              ot = ref6[l];
              ref7 = ot._filename_replacements || {};
              for (k in ref7) {
                v = ref7[k];
                if (k === targetFieldName && (v != null ? v.length : void 0) > 0) {
                  caption_help += v.join("\n");
                }
              }
            }
            pop = new ez5.HintPopover({
              element: btn,
              content: new CUI.Label({
                multiline: true,
                text: caption_help
              }),
              padded: true
            });
            return pop.show();
          }
        });
      };
    })(this);
    fields = [
      {
        type: CUI.DataTable,
        name: "_rows",
        new_rows: "append",
        rowMove: false,
        onDataInit: (function(_this) {
          return function(dataField, data) {
            var config, fieldName, rows;
            if (!data._rows) {
              rows = [];
              for (fieldName in data) {
                config = data[fieldName];
                if (fieldName === "_rows") {
                  continue;
                }
                if (config && typeof config === "object") {
                  rows.push({
                    field: fieldName,
                    text: config.text,
                    size: config.size,
                    padding: config.padding,
                    multiline: config.multiline,
                    overlay: config.overlay
                  });
                }
              }
              return data._rows = rows;
            }
          };
        })(this),
        onDataChanged: (function(_this) {
          return function(data, dataField) {
            var key, l, len3, ref4, results, row;
            if (CUI.util.isArray(data._rows)) {
              for (key in data) {
                if (key !== "_rows") {
                  delete data[key];
                }
              }
              ref4 = data._rows;
              results = [];
              for (l = 0, len3 = ref4.length; l < len3; l++) {
                row = ref4[l];
                if (row.field) {
                  results.push(data[row.field] = {
                    text: row.text,
                    size: row.size,
                    padding: row.padding,
                    multiline: row.multiline,
                    overlay: row.overlay
                  });
                } else {
                  results.push(void 0);
                }
              }
              return results;
            }
          };
        })(this),
        fields: [
          {
            type: CUI.Select,
            form: {
              label: $$("admin.pool.caption.field")
            },
            name: "field",
            options: getEASFieldOption
          }, {
            type: CUI.Input,
            form: {
              label: $$("admin.pool.caption.text"),
              hint: $$("admin.pool.caption.text.hint")
            },
            name: "text",
            placeholder: $$("admin.pool.caption.text.placeholder"),
            "class": "ez5-objecttype-list-view-item-caption-text",
            controlElement: showReplacementsButton
          }, {
            type: CUI.Input,
            form: {
              label: $$("admin.pool.caption.size"),
              hint: $$("admin.pool.caption.size.hint")
            },
            name: "size",
            regexp: "^\\d+(\\.\\d+)?(%|px)?$",
            placeholder: $$("admin.pool.caption.size.placeholder")
          }, {
            type: CUI.Input,
            form: {
              label: $$("admin.pool.caption.padding"),
              hint: $$("admin.pool.caption.padding.hint")
            },
            name: "padding",
            regexp: "^\\d+(px)?$",
            placeholder: $$("admin.pool.caption.padding.placeholder")
          }, {
            type: CUI.Checkbox,
            form: {
              label: $$("admin.pool.caption.multiline")
            },
            name: "multiline"
          }, {
            type: CUI.Checkbox,
            form: {
              label: $$("admin.pool.caption.overlay")
            },
            name: "overlay"
          }
        ]
      }
    ];
    return fields;
  };

  ObjecttypeListViewItem.prototype.getStandardMaskFieldsForm = function(objecttype, data, text_for_checkbox, label_for_checkbox) {
    var descriptionLabel, dividerHeader, dividerHeaderLabel, divider_added, fields, i, idx, j, len1, len2, m, mask, masks;
    CUI.util.assert(CUI.util.isPlainObject(data), (CUI.util.getObjectClass(this)) + ".getStandardMaskFields", "data needs to be PlainObject", {
      objecttype: objecttype,
      data: data
    });
    CUI.util.assert(CUI.util.isArray(data.standard_masks), (CUI.util.getObjectClass(this)) + ".getStandardMaskFields", "data.standard_masks needs to be Array", {
      objecttype: objecttype,
      data: data
    });
    CUI.util.assert(CUI.util.isBoolean(data.standard_mask_from_objecttype), (CUI.util.getObjectClass(this)) + ".getStandardMaskFields", "data.standard_mask_from_objecttype.set needs to be Boolean", {
      objecttype: objecttype,
      data: data
    });
    descriptionLabel = new LocaLabel({
      loca_key: "objecttype.list.view.item.mask_select.hint",
      "class": "cui-label-description",
      multiline: true
    });
    dividerHeader = CUI.dom.div("ez5-objecttype-list-view-item-mask-select-divider");
    dividerHeaderLabel = new LocaLabel({
      loca_key: "objecttype.list.view.mask_select.header_activated"
    });
    CUI.dom.append(dividerHeader, dividerHeaderLabel);
    fields = [
      {
        type: CUI.Checkbox,
        text: text_for_checkbox,
        data: data,
        name: "standard_mask_from_objecttype",
        onDataChanged: function(data, field) {
          if (data.standard_mask_from_objecttype) {
            return field.getOtherField("standard_masks_internal").disable();
          } else {
            return field.getOtherField("standard_masks_internal").enable();
          }
        }
      }, {
        type: CUI.DataTable,
        name: "standard_masks_internal",
        "class": "ez5-objecttype-list-view-item-mask-select",
        data: data,
        new_rows: "none",
        no_header: true,
        rowMove: true,
        onRender: (function(_this) {
          return function(table) {
            return CUI.dom.prepend(table, [dividerHeader, descriptionLabel]);
          };
        })(this),
        onNodeAdd: (function(_this) {
          return function(node) {
            if (node.getData().divider) {
              node.setClass("ez5-objecttype-list-view-item-mask-select-divider");
              node.setSelectable(false);
              node.isMovable = function() {
                return false;
              };
            }
          };
        })(this),
        disabled: data.standard_mask_from_objecttype,
        fields: [
          {
            type: CUI.Output,
            name: "name"
          }
        ]
      }
    ];
    masks = ObjecttypeListViewItem.prototype.getMasks.call(this, objecttype);
    for (idx = i = 0, len1 = masks.length; i < len1; idx = ++i) {
      m = masks[idx];
      m.__idx = idx;
    }
    masks.sort(function(a, b) {
      var a_id, a_idx, b_id, b_idx, len;
      a_id = a.id();
      b_id = b.id();
      len = data.standard_masks.length;
      a_idx = data.standard_masks.indexOf(a_id);
      b_idx = data.standard_masks.indexOf(b_id);
      if (a_idx > -1) {
        a_id = a_idx - len;
      } else {
        a_id = a.__idx;
      }
      if (b_idx > -1) {
        b_id = b_idx - len;
      } else {
        b_id = b.__idx;
      }
      return CUI.util.compareIndex(a_id, b_id);
    });
    data.standard_masks_internal = [];
    divider_added = false;
    for (idx = j = 0, len2 = masks.length; j < len2; idx = ++j) {
      mask = masks[idx];
      if (idx === data.standard_masks.length && !data.standard_mask_from_objecttype) {
        data.standard_masks_internal.push({
          divider: true,
          name: $$("objecttype.list.view.mask_select.header_deactivated")
        });
        divider_added = true;
      }
      data.standard_masks_internal.push({
        name: mask.nameLocalized() + " (" + mask.id() + ")",
        mask_id: mask.id()
      });
    }
    if (data.standard_mask_from_objecttype || !divider_added) {
      data.standard_masks_internal.push({
        divider: true,
        name: $$("objecttype.list.view.mask_select.header_deactivated")
      });
    }
    return new CUI.Form({
      form: {
        label: label_for_checkbox
      },
      fields: fields
    });
  };

  ObjecttypeListViewItem.prototype.getMasks = function(objecttype) {
    var i, len1, m, masks, ref;
    if (objecttype == null) {
      objecttype = this.objecttype;
    }
    masks = [];
    ref = ez5.mask.CURRENT._masks_by_table_id[objecttype.table.id()];
    for (i = 0, len1 = ref.length; i < len1; i++) {
      m = ref[i];
      masks.push(ez5.mask.CURRENT._mask_instance_by_name[m.name]);
    }
    return masks;
  };

  ObjecttypeListViewItem.prototype.getSaveDataStandardMasks = function(data) {
    var i, len1, mask, ref, save_data;
    save_data = null;
    if (!data.standard_masks_internal) {
      return save_data;
    }
    if (!data.standard_mask_from_objecttype) {
      save_data = [];
      ref = data.standard_masks_internal;
      for (i = 0, len1 = ref.length; i < len1; i++) {
        mask = ref[i];
        if (mask.divider) {
          break;
        }
        save_data.push(mask.mask_id);
      }
      if (save_data.length === 0) {
        throw new InvalidSaveDataException();
      }
    }
    return save_data;
  };

  ObjecttypeListViewItem.prototype.loadDataStandardMasks = function(data) {};

  ObjecttypeListViewItem.prototype.__getMappingImageImportField = function(opts) {
    var configButton, container, selectField;
    if (!ez5.version("6") || ez5.metadata.getMetadataRecipesWithParams().length === 0) {
      return {
        type: CUI.Select,
        form: {
          label: $$("admin.objecttype.profile_for_images_import")
        },
        data: this.data.objecttype,
        name: "mapping_image_import",
        options: ez5.metadata.getMappingOpts(opts, {
          exiftool_import: true
        })
      };
    }
    configButton = ez5.metadata.getMappingRecipeConfigButton(this.data.objecttype, {
      name: "mapping_image_import_recipe_configs",
      popover_placement: "w",
      getMappingId: (function(_this) {
        return function() {
          return _this.data.objecttype.mapping_image_import;
        };
      })(this),
      onDataChanged: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            type: "data-changed",
            node: configButton
          });
        };
      })(this)
    });
    ez5.metadata.updateRecipeConfigButtonState(configButton, this.data.objecttype.mapping_image_import);
    selectField = new CUI.Select({
      data: this.data.objecttype,
      name: "mapping_image_import",
      maximize_horizontal: true,
      options: ez5.metadata.getMappingOpts(opts, {
        exiftool_import: true
      }),
      onDataChanged: (function(_this) {
        return function() {
          return ez5.metadata.updateRecipeConfigButtonState(configButton, _this.data.objecttype.mapping_image_import);
        };
      })(this)
    });
    container = CUI.dom.div("ez5-mapping-field-with-config");
    container.appendChild(selectField.DOM);
    container.appendChild(configButton.DOM);
    return new CUI.DataFieldProxy({
      form: {
        label: $$("admin.objecttype.profile_for_images_import")
      },
      element: container
    });
  };

  ObjecttypeListViewItem.prototype.getSaveData = function() {
    var caption_config, config, dissolve_int, fieldName, hasFileLinkDeleteValues, hasObjectPurgeValue, hasValidConfig, i, j, janitorData, janitor_policy, l, len1, len2, len3, len4, linkedObjectsFilters, mf, n, node, padding_str, padding_val, plugin, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, save_data, size_str, size_val;
    save_data = {
      _basetype: "objecttype",
      objecttype: {
        _id: this.id,
        standard_mask: this.data.objecttype.standard_mask,
        mapping_dc_export: CUI.util.getIntOrString(this.data.objecttype.mapping_dc_export),
        mapping_image_export: CUI.util.getIntOrString(this.data.objecttype.mapping_image_export),
        mapping_image_import: CUI.util.getIntOrString(this.data.objecttype.mapping_image_import),
        description: CUI.util.copyObject(this.data.objecttype.description, true),
        show_in_collections: this.data.objecttype.show_in_collections,
        show_in_facet_grouping: this.data.objecttype.show_in_facet_grouping,
        show_in_main_menu_with_icon: this.data.objecttype.show_in_main_menu_with_icon,
        contact: this.data.objecttype.contact
      },
      _export_asset_filenames: CUI.util.copyObject(this.data._export_asset_filenames)
    };
    if (ez5.version("6")) {
      save_data.objecttype.empty_placeholder_icon = this.data.objecttype.empty_placeholder_icon;
      save_data.objecttype.mapping_image_import_recipe_configs = this.data.objecttype.mapping_image_import_recipe_configs || null;
      if (this.data.objecttype.janitor_policy) {
        if (!this.data.objecttype.janitor_policy.override_base_config) {
          save_data.objecttype.janitor_policy = null;
        } else {
          janitor_policy = {};
          janitorData = this.data.objecttype.janitor_policy;
          hasFileLinkDeleteValues = !CUI.util.isEmpty(janitorData.file_link_delete.keep_days_history_versions) || !CUI.util.isEmpty(janitorData.file_link_delete.keep_count_history_versions);
          if (hasFileLinkDeleteValues) {
            janitor_policy.file_link_delete = {
              keep_days_history_versions: janitorData.file_link_delete.keep_days_history_versions,
              keep_count_history_versions: janitorData.file_link_delete.keep_count_history_versions
            };
          } else {
            janitor_policy.file_link_delete = null;
          }
          hasObjectPurgeValue = !CUI.util.isEmpty(janitorData.object_purge.min_deleted_days);
          if (hasObjectPurgeValue) {
            janitor_policy.object_purge = {
              min_deleted_days: janitorData.object_purge.min_deleted_days
            };
          } else {
            janitor_policy.object_purge = null;
          }
          save_data.objecttype.janitor_policy = CUI.util.copyObjectV2(janitor_policy, true);
        }
      }
      if (this.hasWatermarkSettings()) {
        if (((ref = this.data.objecttype.watermark) != null ? ref.watermark_enabled : void 0) && ((ref1 = this.data.objecttype.watermark) != null ? (ref2 = ref1.image) != null ? ref2._id : void 0 : void 0)) {
          save_data.objecttype.watermark = {
            image: this.data.objecttype.watermark.image,
            gravity: this.data.objecttype.watermark.gravity,
            size: this.data.objecttype.watermark.size,
            tile: this.data.objecttype.watermark.tile
          };
          dissolve_int = parseInt(this.data.objecttype.watermark.dissolve);
          if (dissolve_int >= 0) {
            save_data.objecttype.watermark.dissolve = dissolve_int;
          }
        } else {
          save_data.objecttype.watermark = null;
        }
        if (this.data.objecttype.caption && typeof this.data.objecttype.caption === "object" && !CUI.util.isEmpty(this.data.objecttype.caption)) {
          caption_config = {};
          hasValidConfig = false;
          ref3 = this.data.objecttype.caption;
          for (fieldName in ref3) {
            config = ref3[fieldName];
            if (fieldName === "_rows") {
              continue;
            }
            if (!config || !fieldName) {
              continue;
            }
            if (!config.text || !/^\s*\S+.*$/.test(String(config.text))) {
              continue;
            }
            size_str = null;
            if (config.size) {
              size_val = String(config.size);
              if (size_val.endsWith("%")) {
                size_str = size_val;
              } else {
                size_str = size_val.replace(/[^\d.]/g, "");
              }
            }
            padding_str = null;
            if (config.padding) {
              padding_val = String(config.padding);
              padding_str = padding_val.replace(/\D/g, "");
            }
            caption_config[fieldName] = {
              text: config.text,
              size: size_str,
              padding: padding_str,
              multiline: config.multiline,
              overlay: config.overlay
            };
            hasValidConfig = true;
          }
          if (hasValidConfig) {
            save_data.objecttype.caption = caption_config;
          } else {
            save_data.objecttype.caption = null;
          }
        } else {
          save_data.objecttype.caption = null;
        }
      }
    }
    save_data._standard_masks = this.getSaveDataStandardMasks(this.data.objecttype);
    if (this.hasOwnTags()) {
      save_data._private_tags = !!this.data._private_tags;
      if (save_data._private_tags) {
        save_data._tags = this.tagForm.getSaveData();
      }
    }
    if (this.transitionForm) {
      save_data._private_transitions = !!this.data._private_transitions;
      save_data._transitions = this.transitionForm.getSaveData();
    }
    if (this.aclManager) {
      save_data._acl = this.aclManager.getSaveData();
    }
    if (this.maskfilters) {
      save_data._maskfilters = {};
      ref4 = this.maskfilters;
      for (i = 0, len1 = ref4.length; i < len1; i++) {
        mf = ref4[i];
        mf.getSaveData(save_data._maskfilters);
      }
    }
    if (this.columns_right_tree) {
      save_data._columnfilters = [];
      ref5 = this.columns_right_tree.root.children;
      for (j = 0, len2 = ref5.length; j < len2; j++) {
        node = ref5[j];
        if (!(node instanceof ColumnRightItem)) {
          continue;
        }
        save_data._columnfilters.push(node.getSaveData());
      }
    }
    save_data.objecttype.custom_data = {
      webfrontend: {}
    };
    if (this.__linkedObjectsFiltersTree) {
      linkedObjectsFilters = [];
      ref6 = this.__linkedObjectsFiltersTree.root.children;
      for (l = 0, len3 = ref6.length; l < len3; l++) {
        node = ref6[l];
        if (!(node instanceof LinkedObjectFilterTreeNode)) {
          continue;
        }
        linkedObjectsFilters.push(node.getSaveData());
      }
      save_data.objecttype.custom_data.webfrontend.linkedObjectsFilters = linkedObjectsFilters;
    }
    ref7 = this.__plugins;
    for (n = 0, len4 = ref7.length; n < len4; n++) {
      plugin = ref7[n];
      plugin.getSaveData(save_data);
    }
    return save_data;
  };

  ObjecttypeListViewItem.prototype.renderJanitorTab = function() {
    var fileLinkDeleteBlock, fileLinkDeleteForm, getPlaceholder, objectPurgeBlock, objectPurgeForm, overrideBaseConfigCheckbox, ref, ref1, ref2, updatePlaceholders;
    if (this.objecttype.poolLink()) {
      return new CUI.EmptyLabel({
        centered: true,
        text: $$("admin.objecttypemanager.janitor.not.available.hint")
      });
    }
    if (!this.data.objecttype.janitor_policy) {
      this.data.objecttype.janitor_policy = {};
      this.data.objecttype.janitor_policy.override_base_config = false;
    }
    if (!this.data.objecttype.janitor_policy.hasOwnProperty("override_base_config")) {
      this.data.objecttype.janitor_policy.override_base_config = true;
    }
    overrideBaseConfigCheckbox = new CUI.Checkbox({
      name: "override_base_config",
      text: $$("admin.pool.janitor.override_base_config"),
      data: this.data.objecttype.janitor_policy,
      onDataChanged: (function(_this) {
        return function() {
          var ref, ref1, ref10, ref11, ref12, ref13, ref14, ref15, ref16, ref17, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9;
          if ((ref = _this.data) != null ? (ref1 = ref.objecttype) != null ? (ref2 = ref1.janitor_policy) != null ? ref2.override_base_config : void 0 : void 0 : void 0) {
            if (_this.__cached_janitor_values) {
              if ((ref3 = _this.data.objecttype.janitor_policy) != null) {
                if ((ref4 = ref3.object_purge) != null) {
                  ref4.min_deleted_days = (ref5 = _this.__cached_janitor_values.object_purge) != null ? ref5.min_deleted_days : void 0;
                }
              }
              if ((ref6 = _this.data.objecttype.janitor_policy) != null) {
                if ((ref7 = ref6.file_link_delete) != null) {
                  ref7.keep_count_history_versions = (ref8 = _this.__cached_janitor_values.file_link_delete) != null ? ref8.keep_count_history_versions : void 0;
                }
              }
              if ((ref9 = _this.data.objecttype.janitor_policy) != null) {
                if ((ref10 = ref9.file_link_delete) != null) {
                  ref10.keep_days_history_versions = (ref11 = _this.__cached_janitor_values.file_link_delete) != null ? ref11.keep_days_history_versions : void 0;
                }
              }
            }
          } else {
            _this.__cached_janitor_values = CUI.util.copyObjectV2(_this.data.objecttype.janitor_policy, true);
            if ((ref12 = _this.data.objecttype.janitor_policy) != null) {
              if ((ref13 = ref12.object_purge) != null) {
                ref13.min_deleted_days = null;
              }
            }
            if ((ref14 = _this.data.objecttype.janitor_policy) != null) {
              if ((ref15 = ref14.file_link_delete) != null) {
                ref15.keep_count_history_versions = null;
              }
            }
            if ((ref16 = _this.data.objecttype.janitor_policy) != null) {
              if ((ref17 = ref16.file_link_delete) != null) {
                ref17.keep_days_history_versions = null;
              }
            }
          }
          _this.__updateJanitorFormsState();
          return updatePlaceholders();
        };
      })(this)
    });
    getPlaceholder = (function(_this) {
      return function(category, field_name) {
        var ref, ref1, ref2, value;
        if ((ref = _this.data) != null ? (ref1 = ref.objecttype) != null ? (ref2 = ref1.janitor_policy) != null ? ref2.override_base_config : void 0 : void 0 : void 0) {
          return $$("admin.pool.janitor.override.deactivated_placeholder");
        } else {
          value = ez5.session.getBaseConfig().janitor.object_and_file_removal[category][field_name];
          if (!value && value !== 0) {
            return $$("admin.pool.janitor.override.deactivated_placeholder");
          }
          return "" + value;
        }
      };
    })(this);
    updatePlaceholders = (function(_this) {
      return function() {
        var i, k, keep_count_history_versions_field, keep_days_history_versions_field, len1, ref, ref1, ref2, ref3;
        ref = ["keep_count_history_versions", "keep_days_history_versions"];
        for (i = 0, len1 = ref.length; i < len1; i++) {
          k = ref[i];
          fileLinkDeleteForm.getFieldsByName(k)[0].setPlaceholder(getPlaceholder("file_link_delete", k));
        }
        objectPurgeForm.getFieldsByName("min_deleted_days")[0].setPlaceholder(getPlaceholder("object_purge", "min_deleted_days"));
        if ((ref1 = _this.data) != null ? (ref2 = ref1.objecttype) != null ? (ref3 = ref2.janitor_policy) != null ? ref3.override_base_config : void 0 : void 0 : void 0) {
          keep_count_history_versions_field = fileLinkDeleteForm.getFieldsByName("keep_count_history_versions")[0];
          if (!CUI.util.isEmpty(_this.data.objecttype.janitor_policy.file_link_delete.keep_days_history_versions) && CUI.util.isEmpty(_this.data.objecttype.janitor_policy.file_link_delete.keep_count_history_versions)) {
            keep_count_history_versions_field.setPlaceholder("0");
          } else {
            keep_count_history_versions_field.setPlaceholder(getPlaceholder("file_link_delete", "keep_count_history_versions"));
          }
          keep_days_history_versions_field = fileLinkDeleteForm.getFieldsByName("keep_days_history_versions")[0];
          if (!CUI.util.isEmpty(_this.data.objecttype.janitor_policy.file_link_delete.keep_count_history_versions) && CUI.util.isEmpty(_this.data.objecttype.janitor_policy.file_link_delete.keep_days_history_versions)) {
            return keep_days_history_versions_field.setPlaceholder("0");
          } else {
            return keep_days_history_versions_field.setPlaceholder(getPlaceholder("file_link_delete", "keep_days_history_versions"));
          }
        }
      };
    })(this);
    fileLinkDeleteForm = new CUI.Form({
      name: "file_link_delete",
      data: this.data.objecttype.janitor_policy,
      onDataChanged: (function(_this) {
        return function() {
          updatePlaceholders();
        };
      })(this),
      fields: [
        {
          type: CUI.NumberInput,
          form: {
            label: $$("admin.pool.janitor.file_link_delete.keep_days_history_versions"),
            hint: $$("admin.pool.janitor.file_link_delete.keep_days_history_versions.hint")
          },
          name: "keep_days_history_versions",
          placeholder: getPlaceholder("file_link_delete", "keep_days_history_versions"),
          disabled: !((ref = this.data.objecttype.janitor_policy) != null ? ref.override_base_config : void 0),
          min: 0
        }, {
          type: CUI.NumberInput,
          form: {
            label: $$("admin.pool.janitor.file_link_delete.keep_count_history_versions"),
            hint: $$("admin.pool.janitor.file_link_delete.keep_count_history_versions.hint")
          },
          name: "keep_count_history_versions",
          placeholder: getPlaceholder("file_link_delete", "keep_count_history_versions"),
          disabled: !((ref1 = this.data.objecttype.janitor_policy) != null ? ref1.override_base_config : void 0),
          min: 0
        }
      ]
    });
    objectPurgeForm = new CUI.Form({
      name: "object_purge",
      data: this.data.objecttype.janitor_policy,
      fields: [
        {
          type: CUI.NumberInput,
          form: {
            label: $$("admin.pool.janitor.object_purge.min_deleted_days"),
            hint: $$("admin.pool.janitor.object_purge.min_deleted_days.hint")
          },
          name: "min_deleted_days",
          placeholder: getPlaceholder("object_purge", "min_deleted_days"),
          disabled: !((ref2 = this.data.objecttype.janitor_policy) != null ? ref2.override_base_config : void 0),
          min: 0
        }
      ]
    });
    this.__fileLinkDeleteForm = fileLinkDeleteForm;
    this.__objectPurgeForm = objectPurgeForm;
    fileLinkDeleteBlock = new CUI.Block({
      text: $$("admin.pool.janitor.file_link_delete.block"),
      content: (function(_this) {
        return function() {
          return fileLinkDeleteForm.start();
        };
      })(this)
    });
    objectPurgeBlock = new CUI.Block({
      text: $$("admin.pool.janitor.object_purge.block"),
      content: (function(_this) {
        return function() {
          return objectPurgeForm.start();
        };
      })(this)
    });
    return new CUI.VerticalList({
      content: [overrideBaseConfigCheckbox.start(), objectPurgeBlock, fileLinkDeleteBlock]
    });
  };

  ObjecttypeListViewItem.prototype.__updateJanitorFormsState = function() {
    var field, i, isOverrideBaseConfig, j, len1, len2, ref, ref1, ref2, results;
    isOverrideBaseConfig = (ref = this.data.objecttype.janitor_policy) != null ? ref.override_base_config : void 0;
    if (this.__fileLinkDeleteForm) {
      ref1 = this.__fileLinkDeleteForm.getFields();
      for (i = 0, len1 = ref1.length; i < len1; i++) {
        field = ref1[i];
        if (isOverrideBaseConfig) {
          field.enable();
        } else {
          field.disable();
        }
        field.reload();
      }
    }
    if (this.__objectPurgeForm) {
      ref2 = this.__objectPurgeForm.getFields();
      results = [];
      for (j = 0, len2 = ref2.length; j < len2; j++) {
        field = ref2[j];
        if (isOverrideBaseConfig) {
          field.enable();
        } else {
          field.disable();
        }
        results.push(field.reload());
      }
      return results;
    }
  };

  ObjecttypeListViewItem.prototype.getTabs = function() {
    var i, len1, plugin, ref, tabs;
    tabs = [
      {
        name: "general",
        text: $$("admin.pool.tab.general"),
        onActivate: this.update,
        content: (function(_this) {
          return function() {
            return new CUI.Form({
              onDataChanged: function() {
                return _this.update();
              },
              fields: _this.generalFields(),
              data: _this.data.objecttype
            }).start();
          };
        })(this)
      }
    ];
    if (this.hasOwnTags() || this.objecttype.hasTags()) {
      tabs.push({
        padded: false,
        name: "tags",
        text: $$("admin.pool.tab.tags"),
        content: (function(_this) {
          return function() {
            return _this.renderTagsTab();
          };
        })(this)
      });
    }
    if (this.hasOwnTransitions() || this.objecttype.hasTags()) {
      tabs.push({
        padded: false,
        name: "transitions",
        text: $$("admin.pool.tab.transitions"),
        content: (function(_this) {
          return function() {
            return _this.renderTransitionsTab();
          };
        })(this)
      });
    }
    tabs.push({
      name: "acl",
      padded: false,
      text: $$("admin.pool.tab.system_rights"),
      content: (function(_this) {
        return function() {
          return _this.renderAclTab();
        };
      })(this)
    });
    if (this.getMasks().length >= 2) {
      tabs.push({
        padded: false,
        name: "maskfilter",
        text: $$("admin.rights.objecttype.tab.maskfilter"),
        content: (function(_this) {
          return function() {
            return _this.renderMaskfilterTab();
          };
        })(this)
      });
    }
    tabs.push({
      padded: false,
      name: "column_rights",
      text: $$("admin.pool.tab.column_rights"),
      content: (function(_this) {
        return function() {
          return _this.renderColumnRightsTab();
        };
      })(this)
    });
    tabs.push({
      padded: false,
      name: "linked_objects_filters",
      text: $$("admin.objecttype.tab.linked_objects_filters"),
      content: (function(_this) {
        return function() {
          return _this.renderLinkedObjectsFiltersTab();
        };
      })(this)
    });
    ref = this.__plugins;
    for (i = 0, len1 = ref.length; i < len1; i++) {
      plugin = ref[i];
      plugin.addToTabs(tabs);
    }
    if (ez5.version("6")) {
      if (this.hasWatermarkSettings()) {
        tabs.push({
          name: "watermark",
          text: $$("admin.pool.tab.watermark"),
          content: (function(_this) {
            return function() {
              var captionBlock, captionForm, watermarkBlock, watermarkForm, watermarkInformationLabel;
              watermarkForm = new CUI.Form({
                fields: _this.watermarkFields(),
                data: _this.data.objecttype.watermark
              });
              captionForm = new CUI.Form({
                "class": "ez5-objecttype-list-view-item-caption",
                fields: _this.captionFields(),
                data: _this.data.objecttype.caption
              });
              watermarkBlock = new CUI.Block({
                text: $$("admin.pool.watermark.block"),
                content: function() {
                  return watermarkForm.start();
                }
              });
              captionBlock = new CUI.Block({
                text: $$("admin.objecttype.caption.block"),
                content: function() {
                  return captionForm.start();
                }
              });
              watermarkInformationLabel = new CUI.Label({
                multiline: true,
                markdown: true,
                text: $$("admin.pool.watermark.information.md"),
                "class": "cui-label-description"
              });
              return new CUI.VerticalList({
                content: [watermarkInformationLabel, watermarkBlock, captionBlock]
              });
            };
          })(this)
        });
      }
    }
    if (this.hasJanitorSettings()) {
      tabs.push({
        name: "janitor",
        text: $$("admin.pool.tab.janitor"),
        content: (function(_this) {
          return function() {
            return _this.renderJanitorTab();
          };
        })(this)
      });
    }
    if (ez5.version("6")) {
      tabs.push({
        name: "statistics",
        text: $$("admin.objecttype.tab.stats"),
        load_on_show: true,
        content: (function(_this) {
          return function() {
            return _this.renderStatisticsTab();
          };
        })(this)
      });
    }
    return tabs;
  };

  ObjecttypeListViewItem.prototype.hasJanitorSettings = function() {
    var ref, ref1, ref2;
    if (ez5.version("6") && ((ref = ez5.session.getBaseConfig()) != null ? (ref1 = ref.janitor) != null ? (ref2 = ref1.object_and_file_removal) != null ? ref2.allow_overwrite : void 0 : void 0 : void 0)) {
      return true;
    }
    return false;
  };

  ObjecttypeListViewItem.prototype.hasOwnTags = function() {
    if (ez5.version("6")) {
      return this.objecttype.hasTags();
    }
    return this.objecttype.hasTags() && !this.objecttype.poolLink();
  };

  ObjecttypeListViewItem.prototype.hasOwnTransitions = function() {
    return this.objecttype.hasTags() && !this.objecttype.poolLink();
  };

  ObjecttypeListViewItem.prototype.renderStatisticsTab = function() {
    var loadStats, showEmptyStats, vl;
    vl = new CUI.SimplePane({
      "class": "cui-pane--window",
      content: []
    });
    this.__statFormData = {
      totalSizeOfObjecttype: 0,
      fileCount: 0
    };
    showEmptyStats = (function(_this) {
      return function() {
        return vl.replace(new CUI.EmptyLabel({
          centered: true,
          text: $$("admin.objecttype.statistics.empty")
        }), "center");
      };
    })(this);
    loadStats = (function(_this) {
      return function() {
        var apiUrl, stats, waitBlock;
        apiUrl = "/" + _this.id + "/stats";
        waitBlock = new CUI.WaitBlock({
          text: $$("admin.objecttype.statistics.loading"),
          element: vl
        });
        waitBlock.show();
        return stats = ez5.api.objecttype({
          type: "GET",
          api: apiUrl
        }).fail(function(err) {
          showEmptyStats();
          return waitBlock.destroy();
        }).done(function(data) {
          var statsForm, statsTable;
          if (!(data != null ? data.files : void 0)) {
            showEmptyStats();
            waitBlock.destroy();
            return;
          }
          _this.__statFormData.totalSizeOfObjecttype = data.files.size;
          _this.__statFormData.fileCount = data.files.count;
          statsTable = new StatsTable({
            data: data
          });
          statsForm = new CUI.Form({
            ui: "pool.form.fields.statistics",
            data: _this.__statFormData,
            fields: [
              {
                type: CUI.Output,
                form: {
                  label: $$("admin.pool.statistics.total_size_of_pool")
                },
                name: "totalSizeOfObjecttype",
                getValue: function(v) {
                  return ez5.format_filesize(v) + (" (" + _this.__statFormData.fileCount + " files)");
                }
              }
            ]
          });
          vl.replace([statsForm.start(), _this.__statFormData.totalSizeOfObjecttype !== 0 ? statsTable.render() : void 0], "center");
          return waitBlock.destroy();
        });
      };
    })(this);
    loadStats();
    return vl;
  };

  return ObjecttypeListViewItem;

})(SystemListManagerItem);
// Generated by CoffeeScript 1.12.7
var ObjecttypeWithoutPoolListViewItem,
  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;

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

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

  ObjecttypeWithoutPoolListViewItem.prototype.renderAclTab = function() {
    var easFields;
    easFields = this.getObjecttype().getEASFields("all");
    this.aclManager = new AclManager({
      data: this.data._acl,
      context: this,
      right: true,
      active: true,
      tagfilter: true,
      onUpdate: this.update,
      tagForm: this.tagForm,
      right_filter: (function(_this) {
        return function(field) {
          if (field.name.startsWith("asset_") && easFields.length === 0) {
            return false;
          }
          return true;
        };
      })(this)
    });
    return this.aclManager.getTree();
  };

  return ObjecttypeWithoutPoolListViewItem;

})(ObjecttypeListViewItem);
// Generated by CoffeeScript 1.12.7
var Table,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function Table(version, id_or_schema) {
    var ref;
    this.version = version;
    if (CUI.util.isPlainObject(id_or_schema)) {
      this.schema = id_or_schema;
      this._id = this.schema.table_id;
    } else {
      this._id = id_or_schema;
      this.schema = (ref = ez5.schema[this.version]) != null ? ref._table_by_id[this._id] : void 0;
    }
    CUI.util.assert(this.schema && this._id, "new Table", "version and id/schema must be set and schema found", {
      version: this.version,
      id_or_schema: id_or_schema
    });
  }

  Table.prototype.name = function() {
    return this.schema.name;
  };

  Table.prototype.preferredMask = function() {
    return ez5.mask[this.version]._mask_instance_by_name[this.schema._preferred_mask.name];
  };

  Table.prototype.nameLocalized = function() {
    if (this.isLocal()) {
      return this.schema._name_localized;
    } else {
      return this.schema._name_localized + '@' + ez5.connector.displaynameByInstance(this.getInstance());
    }
  };

  Table.prototype.nameLocalizedWithoutInstance = function() {
    return this.schema._name_localized;
  };

  Table.prototype.isLocal = function() {
    return !this.schema._instance;
  };

  Table.prototype.getInstance = function() {
    return this.schema._instance;
  };

  Table.prototype.id = function() {
    return this._id;
  };

  Table.prototype.hasHierarchicalReverse = function() {
    return this.getSchema().columns.some(function(col) {
      return col.kind === "reverse_link" && col.is_hierarchical;
    });
  };

  Table.prototype.getSchema = function() {
    return this.schema;
  };

  Table.prototype.isHierarchy = function() {
    if (this.schema.is_hierarchical) {
      return true;
    } else {
      return false;
    }
  };

  Table.prototype.isPolyhierarchy = function() {
    if (this.schema.polyhierarchical) {
      return true;
    } else {
      return false;
    }
  };

  Table.prototype.aclTable = function() {
    return this.schema.acl_table;
  };

  Table.prototype.inMainSearch = function() {
    return this.schema.in_main_search;
  };

  Table.prototype.hasTags = function() {
    return this.schema.has_tags;
  };

  Table.prototype.poolLink = function() {
    return this.schema.pool_link;
  };

  Table.prototype.getInstance = function() {
    return this.schema._instance;
  };

  Table.prototype.getDisplayType = function() {
    var cap, easFieldsCount, i, len, locaKey, mask_count, ref, ref1, types;
    types = [];
    ref = this.getCapabilities();
    for (i = 0, len = ref.length; i < len; i++) {
      cap = ref[i];
      types.push($$("table.capability." + cap));
    }
    if ((mask_count = (ref1 = ez5.mask[this.version]._masks_by_table_id[this.id()]) != null ? ref1.length : void 0) > 1) {
      types.push($$("table.capability.masks", {
        count: mask_count
      }));
    }
    easFieldsCount = this.getEASColumns().length;
    if (easFieldsCount > 0) {
      locaKey = easFieldsCount > 1 ? "table.capability.eas_fields" : "table.capability.eas_field";
      types.push($$(locaKey, {
        count: easFieldsCount
      }));
    }
    return types.join(", ");
  };

  Table.prototype.getCapabilities = function() {
    var caps;
    caps = [];
    if (this.inMainSearch()) {
      caps.push("main-search");
    }
    if (this.hasTags()) {
      caps.push("tags");
    }
    if (this.poolLink()) {
      caps.push("pool");
    }
    if (this.aclTable()) {
      caps.push("acl");
    }
    if (this.isHierarchy()) {
      caps.push("hierarchy");
    }
    if (this.isPolyhierarchy()) {
      caps.push("polyhierarchy");
    }
    return caps;
  };

  Table.prototype.getEASColumns = function(eas_cols, table_ids_checked, strictMode) {
    var col, i, len, ref, ref1, ref2, tb;
    if (eas_cols == null) {
      eas_cols = [];
    }
    if (table_ids_checked == null) {
      table_ids_checked = [];
    }
    if (strictMode == null) {
      strictMode = false;
    }
    ref = this.schema.columns;
    for (i = 0, len = ref.length; i < len; i++) {
      col = ref[i];
      if (col.name) {
        if (col.type === "eas") {
          eas_cols.push(col);
        }
      } else if ((ref1 = col.kind) === "link" || ref1 === "reverse_link") {
        if (col.is_hierarchical || strictMode) {
          continue;
        }
        if (ref2 = col.other_table_id, indexOf.call(table_ids_checked, ref2) >= 0) {
          continue;
        }
        table_ids_checked.push(col.other_table_id);
        tb = new Table(this.version, col.other_table_id);
        tb.getEASColumns(eas_cols, table_ids_checked);
      } else {
        console.error("Unknown column type:", col);
      }
    }
    return eas_cols;
  };

  Table.prototype.getCapabilityClasses = function(prefix) {
    var cap;
    if (prefix == null) {
      prefix = "";
    }
    return ((function() {
      var i, len, ref, results;
      ref = this.getCapabilities();
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        cap = ref[i];
        results.push(prefix + cap);
      }
      return results;
    }).call(this)).join(" ");
  };

  return Table;

})(CUI.Dummy);
// Generated by CoffeeScript 1.12.7
var Request,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

window.BaseRequest = Request;

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

  function Request(opts) {
    var k, v;
    if (CUI.util.isString(opts)) {
      return new window.BaseRequest(opts);
    }
    this.__allowedKeys = Object.keys(this.__map);
    this.__allowedKeys.push.apply(this.__allowedKeys, ["debug", "page_request", "has_user_input", "searchManagers", "exclusive", "exclusive_show", "counter", "for_export", "update", "scroll_into_view_offset", "ignore_hierarchy", "show_hierarchy"]);
    for (k in opts) {
      v = opts[k];
      CUI.util.assert(indexOf.call(this.__allowedKeys, k) >= 0, "new Request", ("Key " + k + " not allowed, supported are: ") + this.__allowedKeys.join(", "));
      this[k] = v;
    }
  }

  Request.prototype.copy = function() {
    var copy, k, ref, v;
    copy = {};
    ref = this;
    for (k in ref) {
      v = ref[k];
      if (indexOf.call(this.__allowedKeys, k) < 0) {
        continue;
      }
      switch (typeof v) {
        case "number":
        case "boolean":
        case "object":
        case "string":
          copy[k] = CUI.util.copyObject(v, true);
      }
    }
    return new Request(copy);
  };

  Request.prototype.__map = {
    offset: "offset",
    limit: "limit",
    aggregations: "aggregations",
    generate_rights: "generate_rights",
    type: "type",
    search: "search",
    fields: "fields",
    exclude_fields: "exclude_fields",
    include_fields: "include_fields",
    best_mask_filter: "best_mask_filter",
    format: "format",
    sort: "sort",
    ids_only: "ids_only",
    tokens: "tokens",
    highlight: "highlight",
    objecttypes: "objecttypes",
    timezone: "timezone",
    include_deleted: "include_deleted"
  };

  Request.prototype.cleanRequestForSearch = function() {
    var k, req;
    req = {};
    for (k in this.__map) {
      if (this.hasOwnProperty(k)) {
        req[this.__map[k]] = this[k];
      }
    }
    if (req.limit === -1) {
      req.limit = 1000000000;
    }
    return req;
  };

  Request.prototype.merge = function(request) {
    var i, j, k, len, len1, ref, ref1;
    CUI.util.assert(request instanceof Request, "Request.merge: request needs to be instance of Request", {
      request: request
    });
    ref = ["search", "aggregations", "objecttypes", "fields", "sort"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      if (request[k]) {
        if (!this[k]) {
          this[k] = [];
        }
        this[k].push.apply(this[k], request[k]);
      }
    }
    ref1 = ["offset", "type", "best_mask_filter", "ids_only", "limit"];
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      k = ref1[j];
      if (request.hasOwnProperty(k)) {
        this[k] = request[k];
      }
    }
    return this;
  };

  return Request;

})(CUI.Dummy);
// Generated by CoffeeScript 1.12.7
var Objecttype,
  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;

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

  function Objecttype(mask_or_table) {
    if (!isNaN(parseInt(mask_or_table != null ? mask_or_table.table_id : void 0))) {
      mask_or_table = new Table("CURRENT", mask_or_table.table_id);
    }
    this.masks = [];
    CUI.util.assert(mask_or_table instanceof Mask || mask_or_table instanceof Table, "new Objecttype", "mask_or_table must be instance of Mask or Table", {
      mask_or_table: mask_or_table
    });
    if (mask_or_table instanceof Mask) {
      this.addMask(mask_or_table);
      this.table = mask_or_table.table;
    } else {
      this.table = mask_or_table;
    }
    this.__dbg_name = this.name();
  }

  Objecttype.prototype.addAllMasks = function() {
    var found, i, j, len, len1, m, mask, ref, ref1;
    ref = ez5.mask.CURRENT._masks_by_table_id[this.id()];
    for (i = 0, len = ref.length; i < len; i++) {
      mask = ref[i];
      found = false;
      ref1 = this.masks;
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        m = ref1[j];
        if (m.name() === mask.name) {
          found = true;
        }
      }
      if (found) {
        continue;
      }
      this.addMask(ez5.mask.CURRENT._mask_instance_by_name[mask.name]);
    }
    return this;
  };

  Objecttype.prototype.getMask = function() {
    var ref;
    return (ref = this.masks) != null ? ref[0] : void 0;
  };

  Objecttype.prototype.id = function() {
    return this.table.id();
  };

  Objecttype.prototype.getTable = function() {
    return this.table;
  };

  Objecttype.prototype.name = function() {
    return this.table.name();
  };

  Objecttype.prototype.removeAllMasks = function() {
    return this.masks = [];
  };

  Objecttype.prototype.nameLocalized = function() {
    return this.table.nameLocalized();
  };

  Objecttype.prototype.addMask = function(mask) {
    CUI.util.assert(mask instanceof Mask, "Objecttype.addMask", "mask needs to be instance of Mask.", {
      mask: mask
    });
    if (this.masks.length > 0 && this.name() !== mask.table.name()) {
      throw "Cannot addMask of type " + (mask.table.name()) + " to Objecttype with type " + (masks[0].table.name());
    }
    mask.objecttype = this;
    this.masks.push(mask);
    return this;
  };

  Objecttype.prototype.isHierarchy = function() {
    return this.table.isHierarchy();
  };

  Objecttype.prototype.isPolyhierarchy = function() {
    return this.table.isPolyhierarchy();
  };

  Objecttype.prototype.getDisplayType = function() {
    return this.table.getDisplayType();
  };

  Objecttype.prototype.getCapabilities = function() {
    return this.table.getCapabilities();
  };

  Objecttype.prototype.getCapabilityClasses = function(prefix) {
    return this.table.getCapabilityClasses(prefix + "objecttype-is-");
  };

  Objecttype.prototype.inMainSearch = function() {
    return this.table.inMainSearch();
  };

  Objecttype.prototype.isLocal = function() {
    return this.table.isLocal();
  };

  Objecttype.prototype.getInstance = function() {
    return this.table.getInstance();
  };

  Objecttype.prototype.hasTags = function() {
    return this.table.hasTags();
  };

  Objecttype.prototype.aclTable = function() {
    return this.table.aclTable();
  };

  Objecttype.prototype.poolLink = function() {
    return this.table.poolLink();
  };

  Objecttype.prototype.getEASFields = function(mode, eas_fields, include_linked) {
    var func;
    if (mode == null) {
      mode = "all";
    }
    if (eas_fields == null) {
      eas_fields = [];
    }
    if (include_linked == null) {
      include_linked = true;
    }
    func = (function(_this) {
      return function(f) {
        var check_linked_eas;
        check_linked_eas = function() {
          if (!include_linked) {
            return false;
          }
          if (!(f instanceof LinkedObject)) {
            return false;
          }
          if (!f.getOutputStandardEAS()) {
            return false;
          }
          return f.linkMask().hasStandardEASFields();
        };
        return f instanceof EASColumn || check_linked_eas();
      };
    })(this);
    return this.getFields(mode, true, func, eas_fields);
  };

  Objecttype.prototype.getAllFields = function(mode, fields) {
    if (mode == null) {
      mode = "all";
    }
    if (fields == null) {
      fields = [];
    }
    return this.getFields(mode, true, (function(f) {
      return f instanceof Field;
    }), fields);
  };

  Objecttype.prototype.getAllFieldsFromAllMasks = function(mode, fields) {
    if (mode == null) {
      mode = "all";
    }
    if (fields == null) {
      fields = [];
    }
    return this.getFields(mode, true, (function(f) {
      return f instanceof Field;
    }), fields, true);
  };

  Objecttype.prototype.getFields = function(mode, dive, filter_func, fields, allowDup) {
    var i, len, m, ref;
    if (mode == null) {
      mode = "all";
    }
    if (dive == null) {
      dive = true;
    }
    if (filter_func == null) {
      filter_func = (function(f) {
        return f instanceof Field;
      });
    }
    if (fields == null) {
      fields = [];
    }
    if (allowDup == null) {
      allowDup = false;
    }
    CUI.util.assert(this.masks.length > 0, "Objecttype.getFields", "This objecttype instance has not been initialized with masks, so no fields can be found.", {
      table: this.table,
      masks: this.masks
    });
    ref = this.masks;
    for (i = 0, len = ref.length; i < len; i++) {
      m = ref[i];
      m.invokeOnFields(mode, dive, (function(_this) {
        return function(f) {
          var f2, j, len1;
          if (filter_func(f)) {
            if (!allowDup) {
              for (j = 0, len1 = fields.length; j < len1; j++) {
                f2 = fields[j];
                if (f2.identifier() === f.identifier()) {
                  return;
                }
              }
            }
            return fields.push(f);
          }
        };
      })(this));
    }
    return fields;
  };

  Objecttype.prototype.getInfoDiv = function() {
    var dfr, ot;
    dfr = new CUI.Deferred();
    ot = new ObjecttypeListViewItem({
      objecttype: this
    });
    ot.load().done((function(_this) {
      return function() {
        var arr, contact, rows, share_url;
        arr = [];
        rows = [];
        if (!CUI.util.isEmpty(ot.getDescription())) {
          arr.push(new CUI.MultilineLabel({
            "class": "ez5-hint-popover-description",
            markdown: true,
            text: ot.getDescription()
          }));
          ot.addClass("ez5-has-description");
        }
        contact = ot.getContact();
        if (contact) {
          rows.push({
            key: new CUI.Label({
              text: $$("objecttype.info.contact")
            }),
            value: new CUI.Label({
              text: contact.getDisplayText()
            })
          });
        }
        share_url = document.location.origin + "/search?ot=" + encodeURI(_this.table.name());
        if (window.easydb_server_url) {
          share_url += "&server=" + encodeURI(window.easydb_server_url);
        }
        rows.push({
          key: new CUI.Label({
            text: $$("objecttype.info.link")
          }),
          value: new CUI.ButtonHref({
            href: share_url,
            appearance: "link",
            text: share_url,
            target: "_blank"
          })
        });
        arr.push(new CUI.Table({
          rows: rows,
          key_value: true
        }));
        return dfr.resolve(arr);
      };
    })(this)).fail((function(_this) {
      return function() {
        return dfr.reject();
      };
    })(this));
    return dfr.promise();
  };

  Objecttype.getIncludeFieldsForEASFields = function(ot_name) {
    var eas_fields, f, i, len, ot, ref;
    ot = new Objecttype(ez5.schema.CURRENT._objecttype_by_name[ot_name]);
    ot.addAllMasks();
    eas_fields = ['_objecttype', '_mask', '_tags', '_system_object_id', '_global_object_id', '_standard', '_pool'];
    ref = ot.getEASFields();
    for (i = 0, len = ref.length; i < len; i++) {
      f = ref[i];
      eas_fields.push(f.fullName());
    }
    return eas_fields;
  };

  return Objecttype;

})(CUI.Dummy);
// Generated by CoffeeScript 1.12.7
var LocaLabel,
  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;

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

  function LocaLabel(opts) {
    this.opts = opts != null ? opts : {};
    LocaLabel.__super__.constructor.call(this, this.opts);
    this.addClass("cui-label");
    if (this._loca_key) {
      CUI.dom.setAttribute(this.DOM, "ez5-loca-key", this._loca_key);
    }
  }

  LocaLabel.prototype.initOpts = function() {
    LocaLabel.__super__.initOpts.call(this);
    return this.addOpts(LocaLabel.opts);
  };

  LocaLabel.prototype.readOpts = function() {
    if (this.opts.loca_key) {
      if (this.opts.loca_key.endsWith(".md")) {
        this.opts.markdown = true;
      }
      if (ez5.loca.has(this.opts.loca_key)) {
        this.opts.text = ez5.loca.str(this.opts.loca_key, this.opts.loca_key_attrs);
      }
    }
    this.initLocaOpts(["text", "icon"]);
    if (!this.opts.text && !this.opts.icon && this.opts.loca_key) {
      this.opts.text = $$(this.opts.loca_key + "|text", this.opts.loca_key_attrs);
    }
    LocaLabel.__super__.readOpts.call(this);
    return this.initTooltip();
  };

  LocaLabel.prototype.initTooltip = function() {
    var tooltip;
    if (!this._loca_key) {
      return;
    }
    tooltip = ez5.loca.str(this._loca_key + "|tooltip", this._loca_key_attrs, ez5.loca.culture, null);
    if (tooltip) {
      if (!this._tooltip) {
        this._tooltip = {};
      }
      if (!this._tooltip.text && !this._tooltip.content) {
        this._tooltip.text = tooltip;
      }
    }
    return this;
  };

  LocaLabel.prototype.initLocaOpts = function(keys) {
    var data, i, k, len, loca_key;
    if (!this.opts.loca_key) {
      return;
    }
    if (ez5.session.isDebug()) {
      this.__title = this.opts.loca_key;
    }
    for (i = 0, len = keys.length; i < len; i++) {
      k = keys[i];
      if (this.opts.loca_key_preferred === false && this.opts[k] !== void 0) {
        continue;
      }
      loca_key = this.opts.loca_key + "|" + k;
      data = ez5.loca.get_key(loca_key);
      if (CUI.util.isEmpty(data) || data === "-") {
        continue;
      }
      this.opts[k] = ez5.loca.str(loca_key, this.opts.loca_key_attrs);
    }
    return this;
  };

  LocaLabel.prototype.initTitle = function() {
    if (this.__title) {
      return CUI.dom.setAttribute(this.DOM, "title", this.__title);
    }
  };

  LocaLabel.prototype.setText = function(txt) {
    LocaLabel.__super__.setText.call(this, txt);
    return this.initTitle();
  };

  LocaLabel.opts = {
    loca_key_preferred: {
      check: Boolean
    },
    loca_key: {
      check: String
    },
    loca_key_attrs: {
      check: function(v) {
        return CUI.util.isArray(v) || CUI.util.isPlainObject(v);
      }
    }
  };

  LocaLabel.getStandardOpts = function(loca_key, keys) {
    var caller, i, key, len, set_keys;
    if (keys == null) {
      keys = ["text", "icon"];
    }
    if (ez5.loca.has(loca_key)) {
      return {
        text: $$(loca_key)
      };
    } else {
      caller = {
        opts: {
          loca_key: loca_key
        }
      };
      LocaLabel.prototype.initLocaOpts.call(caller, keys);
      set_keys = {};
      for (i = 0, len = keys.length; i < len; i++) {
        key = keys[i];
        if (caller.opts.hasOwnProperty(key)) {
          set_keys[key] = caller.opts[key];
        }
      }
      return set_keys;
    }
  };

  return LocaLabel;

})(CUI.Label);

CUI.defaults["class"].Label = LocaLabel;

CUI.ConfirmationChoice.choiceOpts.text.mandatory = false;

CUI.ready(function() {
  var k, ref, results, v;
  ref = LocaLabel.opts;
  results = [];
  for (k in ref) {
    v = ref[k];
    results.push(CUI.ConfirmationChoice.choiceOpts[k] = v);
  }
  return results;
});
// 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;

CUI.Plugin = (function(superClass) {
  extend(Plugin, superClass);

  function Plugin(opts) {
    this.opts = opts;
    if (arguments.length === 0) {
      return;
    }
    Plugin.__super__.constructor.call(this, this.opts);
  }

  return Plugin;

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

CUI.PluginRegistry = (function(superClass) {
  extend(PluginRegistry, superClass);

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

  PluginRegistry.prototype.initOpts = function() {
    PluginRegistry.__super__.initOpts.call(this);
    this.addOpts({
      "class": {
        mandatory: true,
        check: (function(_this) {
          return function(v) {
            return (new v()) instanceof CUI.Element;
          };
        })(this)
      }
    });
    return this.__plugins = [];
  };

  PluginRegistry.prototype.readOpts = function() {
    PluginRegistry.__super__.readOpts.call(this);
    return this.__funcName = new this._class();
  };

  PluginRegistry.prototype.newPlugins = function(opts) {
    var i, inst, len, plugin, ref;
    inst = [];
    ref = this.__plugins;
    for (i = 0, len = ref.length; i < len; i++) {
      plugin = ref[i];
      inst.push(new plugin(opts));
    }
    return inst;
  };

  PluginRegistry.prototype.registerPlugin = function(plugin) {
    CUI.util.assert(new plugin() instanceof this._class, "PluginRegistry", "Plugin needs to be instance of:", this.__funcName);
    return this.__plugins.push(plugin);
  };

  PluginRegistry.prototype.getPlugins = function() {
    return this.__plugins;
  };

  return PluginRegistry;

})(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.HintPopover = (function(superClass) {
  extend(HintPopover, superClass);

  function HintPopover(opts) {
    this.opts = opts;
    HintPopover.__super__.constructor.call(this, this.opts);
    if (this._content) {
      this.append(this._content);
    } else {
      this.DOM.textContent = this._text;
    }
    if (this._padded) {
      this.addClass("cui-hint-popover--padded");
    }
    this.getLayerRoot().addClass("ez5-hint-popover");
  }

  HintPopover.prototype.initOpts = function() {
    HintPopover.__super__.initOpts.call(this);
    this.addOpts({
      content: {
        check: function(v) {
          return CUI.util.isContent(v);
        }
      },
      text: {
        check: function(v) {
          return CUI.util.isString(v);
        }
      },
      padded: {
        check: Boolean,
        "default": true
      }
    });
    this.mergeOpt("backdrop", {
      "default": {
        policy: "click"
      }
    });
    return this.mergeOpt("pointer", {
      "default": "arrow"
    });
  };

  HintPopover.prototype.readOpts = function() {
    HintPopover.__super__.readOpts.call(this);
    return CUI.util.assert(this._content || this._text, "new ez5.HintPopover", "opts.content or opts.text need to be set.", {
      opts: this.opts
    });
  };

  return HintPopover;

})(CUI.Layer);
// Generated by CoffeeScript 1.12.7
var EmptyLocaLabel,
  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;

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

  function EmptyLocaLabel(opts) {
    this.opts = opts != null ? opts : {};
    EmptyLocaLabel.__super__.constructor.call(this, this.opts);
    this.addClass("cui-empty-label");
  }

  EmptyLocaLabel.prototype.readOpts = function() {
    CUI.EmptyLabel.prototype.readOpts.call(this);
    return EmptyLocaLabel.__super__.readOpts.call(this);
  };

  return EmptyLocaLabel;

})(LocaLabel);
// Generated by CoffeeScript 1.12.7
var LocaButton,
  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;

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

  function LocaButton(opts) {
    this.opts = opts != null ? opts : {};
    LocaButton.__super__.constructor.call(this, this.opts);
    this.addClass("cui-button");
    if (this._loca_key) {
      CUI.dom.setAttribute(this.DOM, "ez5-loca-key", this._loca_key);
    }
  }

  LocaButton.prototype.initOpts = function() {
    LocaButton.__super__.initOpts.call(this);
    this.addOpts(LocaLabel.opts);
    return this.addOpts({
      tooltip_active: {
        check: String
      },
      tooltip_inactive: {
        check: String
      },
      tooltip_disabled: {
        check: String
      }
    });
  };

  LocaButton.prototype.readOpts = function() {
    LocaLabel.prototype.initLocaOpts.call(this, ["text", "text_active", "text_inactive", "icon", "size", "icon_active", "icon_inactive"]);
    if (!this.opts.text && !this.opts.icon && !this.opts.icon_active && !this.opts.icon_inactive && this.opts.loca_key) {
      this.opts.text = ez5.loca.getLanguage() + ":" + this.opts.loca_key + "|text";
    }
    LocaButton.__super__.readOpts.call(this);
    this.initTooltip();
    return this;
  };

  LocaButton.prototype.initTooltip = function() {
    var has_tooltip, i, k, key, len, ref, tooltip, tooltip_txt;
    if (this._tooltip) {
      return;
    }
    tooltip_txt = ez5.loca.str(this._loca_key + "|tooltip", this._loca_key_attrs, ez5.loca.culture, null);
    has_tooltip = false;
    tooltip = {};
    ref = ["active", "inactive", "disabled"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      key = "tooltip_" + k;
      if (this._loca_key) {
        tooltip[k] = ez5.loca.str(this._loca_key + "|" + key, this._loca_key_attrs, ez5.loca.culture, null);
      }
      if (CUI.util.isEmpty(tooltip[k])) {
        tooltip[k] = this["_" + key];
      }
      if (CUI.util.isEmpty(tooltip[k])) {
        tooltip[k] = tooltip_txt;
      }
      if (!CUI.util.isEmpty(tooltip[k])) {
        has_tooltip = true;
      }
    }
    if (has_tooltip) {
      this._tooltip = {
        text: (function(_this) {
          return function() {
            if (_this.isDisabled()) {
              return tooltip.disabled;
            } else if (_this.isActive()) {
              return tooltip.active;
            } else {
              return tooltip.inactive;
            }
          };
        })(this)
      };
    }
    return this;
  };

  LocaButton.prototype.setText = function(txt) {
    LocaButton.__super__.setText.call(this, txt);
    return LocaLabel.prototype.initTitle.call(this);
  };

  return LocaButton;

})(CUI.Button);

CUI.defaults["class"].Button = LocaButton;
// Generated by CoffeeScript 1.12.7
var LocaButtonHref,
  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;

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

  function LocaButtonHref(opts) {
    this.opts = opts != null ? opts : {};
    LocaButtonHref.__super__.constructor.call(this, this.opts);
    this.addClass("cui-button-href");
  }

  LocaButtonHref.prototype.initOpts = function() {
    LocaButtonHref.__super__.initOpts.call(this);
    return LocaButton.prototype.initOpts.call(this);
  };

  LocaButtonHref.prototype.readOpts = function() {
    LocaLabel.prototype.initLocaOpts.call(this, ["text", "icon"]);
    LocaButtonHref.__super__.readOpts.call(this);
    return LocaButton.prototype.initTooltip.call(this);
  };

  LocaButtonHref.prototype.setText = function(txt) {
    return LocaButton.prototype.setText.call(this, txt);
  };

  return LocaButtonHref;

})(CUI.ButtonHref);
// 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;

CUI.CheckboxButton = (function(superClass) {
  extend(CheckboxButton, superClass);

  CheckboxButton.prototype.initOpts = function() {
    CheckboxButton.__super__.initOpts.call(this);
    return this.addOpts({
      checkbox_opts: {
        check: "PlainObject",
        mandatory: true
      }
    });
  };

  function CheckboxButton(opts) {
    CheckboxButton.__super__.constructor.call(this, opts);
    this.addClass("cui-button");
    if (this._icon_left) {
      return;
    }
    this.__checkbox = new CUI.Checkbox(this._checkbox_opts);
    this.__checkbox.start();
    this.__box.append(this.__checkbox, "left");
    return this;
  }

  CheckboxButton.prototype.getCheckbox = function() {
    return this.__checkbox;
  };

  CheckboxButton.prototype.startSpinner = function() {
    if (this.__hasSpinner) {
      return;
    }
    this.__hasSpinner = true;
    this.setIcon("spinner");
    return this;
  };

  CheckboxButton.prototype.stopSpinner = function() {
    this.__box.replace(this.__checkbox, "left");
    this.__hasSpinner = false;
    return this;
  };

  return CheckboxButton;

})(CUI.Button);
// Generated by CoffeeScript 1.12.7
var DataFieldProxy,
  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;

CUI.DataFieldProxy = (function(superClass) {
  extend(DataFieldProxy, superClass);

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

  DataFieldProxy.prototype.readOpts = function() {
    DataFieldProxy.__super__.readOpts.call(this);
    return this.__element = null;
  };

  DataFieldProxy.prototype.initOpts = function() {
    DataFieldProxy.__super__.initOpts.call(this);
    return this.addOpts({
      call_others: {
        "default": true,
        check: Boolean
      },
      element: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isContent(v);
        }
      },
      getDefaultValue: {
        check: Function
      }
    });
  };

  DataFieldProxy.prototype.getFields = function() {
    var _el, df, el, fields, i, len, ref, search_el;
    fields = [];
    if (!this._call_others) {
      return fields;
    }
    if (!this.__element) {
      if (CUI.util.isFunction(this._element)) {
        return fields;
      }
      search_el = this._element;
    } else {
      search_el = this.__element;
    }
    if (search_el instanceof CUI.DOMElement) {
      if (search_el.isDestroyed()) {
        return fields;
      }
      _el = search_el.DOM;
    } else {
      _el = search_el;
    }
    ref = CUI.dom.matchSelector(_el, "[cui-data-field-name],.cui-form");
    for (i = 0, len = ref.length; i < len; i++) {
      el = ref[i];
      df = CUI.dom.data(el, "element");
      if (!df) {
        continue;
      }
      if (df.getForm()) {
        continue;
      }
      fields.push(df);
    }
    return fields;
  };

  DataFieldProxy.prototype.remove = function() {
    this.__detach();
    return DataFieldProxy.__super__.remove.call(this);
  };

  DataFieldProxy.prototype.__detach = function() {
    if (!this.__element) {
      return this;
    }
    CUI.Events.ignore({
      type: "data-changed",
      node: this.__element
    });
    if (this.__element.DOM) {
      CUI.dom.remove(this.__element.DOM);
    } else {
      CUI.dom.remove(this.__element);
    }
    this.__element = null;
    return this;
  };

  DataFieldProxy.prototype.destroy = function() {
    this.__detach();
    return DataFieldProxy.__super__.destroy.call(this);
  };

  DataFieldProxy.prototype.render = function() {
    if (CUI.util.isFunction(this._element)) {
      this.__element = this._element.call(this, this);
    } else {
      this.__element = this._element;
    }
    this.replace(this.__element);
    CUI.Events.listen({
      type: "data-changed",
      node: this.__element,
      call: (function(_this) {
        return function(ev, info) {
          ev.stopImmediatePropagation();
          info.element = _this;
          return CUI.Events.trigger({
            type: "data-changed",
            node: _this.DOM,
            info: info
          });
        };
      })(this)
    });
    DataFieldProxy.__super__.render.call(this);
    return this;
  };

  DataFieldProxy.prototype.setCheckChangedValue = function() {};

  DataFieldProxy.prototype.initData = function() {};

  return DataFieldProxy;

})(CUI.DataField);

DataFieldProxy = CUI.DataFieldProxy;
// Generated by CoffeeScript 1.12.7
var FormPanel,
  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;

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

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

  FormPanel.prototype.readOpts = function() {
    var ref, ref1;
    FormPanel.__super__.readOpts.call(this);
    if ((ref = this._form) != null) {
      ref.label = null;
    }
    if ((ref1 = this._form) != null ? ref1.hint : void 0) {
      this._panel_hint = this._form.hint;
      return this._form.hint = null;
    }
  };

  FormPanel.prototype.initOpts = function() {
    FormPanel.__super__.initOpts.call(this);
    return this.addOpts({
      fields: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isFunction(v) || CUI.util.isArray(v);
        }
      },
      panel_label: {
        mandatory: true,
        check: String
      },
      closed: {
        check: Boolean,
        "default": true
      },
      padded: {
        check: Boolean,
        "default": true
      },
      element: {
        mandatory: true,
        "default": (function(_this) {
          return function(dfProxy) {
            var content, fields, form, hint_div, panel;
            fields = CUI.util.isFunction(_this._fields) ? _this._fields() : _this._fields;
            form = new CUI.Form({
              padded: _this._padded,
              data: dfProxy.getData(),
              name: _this._name,
              fields: fields,
              onDataChanged: function(data, element, ev) {
                return CUI.Events.trigger({
                  type: "data-changed",
                  node: _this.DOM,
                  info: {
                    element: _this
                  }
                });
              }
            });
            if (_this._panel_hint) {
              hint_div = CUI.dom.element("DIV", {
                "class": "cui-form-hint"
              });
              hint_div.appendChild(new CUI.Label({
                "class": "cui-form-hint-label",
                text: _this._panel_hint,
                multiline: true,
                markdown: true
              }).DOM);
              content = new CUI.VerticalLayout({
                top: {
                  content: hint_div
                },
                center: {
                  content: form
                }
              });
            } else {
              content = form;
            }
            panel = new CUI.Panel({
              text: _this._panel_label,
              closed: _this._closed,
              "class": "ez5-form-panel",
              content: content
            });
            return panel;
          };
        })(this)
      }
    });
  };

  return FormPanel;

})(CUI.DataFieldProxy);

CUI.FormPanel = FormPanel;
// Generated by CoffeeScript 1.12.7
var ActionList,
  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;

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

  ActionList.prototype.initOpts = function() {
    ActionList.__super__.initOpts.call(this);
    this.removeOpt("content");
    this.addOpts({
      onClick: {
        check: Function
      },
      content: {
        check: Array,
        "default": []
      }
    });
    return this.__listeners = [];
  };

  function ActionList(opts) {
    var element, i, index, len, ref;
    this.opts = opts != null ? opts : {};
    ActionList.__super__.constructor.call(this, this.opts);
    if (this._onClick) {
      ref = this._content;
      for (index = i = 0, len = ref.length; i < len; index = ++i) {
        element = ref[index];
        this.__initOnClickListener(element, index);
      }
    }
  }

  ActionList.prototype.__initOnClickListener = function(element, index) {
    var listener;
    listener = CUI.Events.listen({
      type: "click",
      node: element.DOM,
      call: (function(_this) {
        return function(event) {
          return _this._onClick(event, index);
        };
      })(this)
    });
    return this.__listeners.push(listener);
  };

  ActionList.prototype.destroy = function() {
    delete this.__listeners;
    return ActionList.__super__.destroy.call(this);
  };

  return ActionList;

})(CUI.VerticalList);
// 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.ObjecttypeSelector = (function(superClass) {
  extend(ObjecttypeSelector, superClass);

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

  ObjecttypeSelector.prototype.initOpts = function() {
    ObjecttypeSelector.__super__.initOpts.call(this);
    this.addOpts({
      filter: {
        check: Function
      },
      store_value: {
        check: ["fullname", "objecttype", "id"],
        "default": "id"
      },
      show_name: {
        check: Boolean,
        "default": false
      },
      placeholder: {
        check: String,
        "default": $$("objecttype.selector.placeholder")
      }
    });
    return this.opts.options = [];
  };

  ObjecttypeSelector.prototype.readOpts = function() {
    ObjecttypeSelector.__super__.readOpts.call(this);
    this._options = this.__getOptions();
    return this._empty_text = this._empty_text || this._placeholder;
  };

  ObjecttypeSelector.prototype.setData = function(data) {
    ObjecttypeSelector.__super__.setData.call(this, data);
    if (!this._options.some((function(_this) {
      return function(option) {
        return option.value === data[_this.getName()];
      };
    })(this))) {
      return data[this.getName()] = null;
    }
  };

  ObjecttypeSelector.prototype.__getOptions = function() {
    var i, len, objectType, options, ot, ref, text, value;
    options = [
      {
        text: this._placeholder,
        value: null
      }
    ];
    ref = ez5.schema.CURRENT._objecttypes;
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      objectType = new Objecttype(new Table("CURRENT", ot.table_id));
      if (this._filter && !this._filter(objectType)) {
        continue;
      }
      switch (this._store_value) {
        case "objecttype":
          value = ot;
          break;
        case "fullname":
          value = ot.name;
          break;
        case "id":
          value = ot.table_id;
      }
      text = objectType.nameLocalized();
      if (this._show_name) {
        text += " [" + (objectType.name()) + "]";
      }
      options.push({
        text: text,
        value: value
      });
    }
    return options;
  };

  return ObjecttypeSelector;

})(CUI.Select);
// 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.FieldSelector = (function(superClass) {
  extend(FieldSelector, superClass);

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

  FieldSelector.prototype.initOpts = function() {
    FieldSelector.__super__.initOpts.call(this);
    this.addOpts({
      objecttype_data_key: {
        check: String
      },
      filter: {
        check: Function
      },
      store_value: {
        check: ["fullname", "name", "id"],
        "default": "id"
      },
      show_name: {
        check: Boolean,
        "default": false
      },
      deep_linked_objects: {
        check: Boolean,
        "default": false
      },
      placeholder: {
        check: String,
        "default": $$("field.selector.placeholder")
      },
      objecttype_id: {
        check: "Integer"
      },
      schema: {
        check: ["CURRENT", "HEAD"],
        "default": "CURRENT"
      },
      sort: {
        check: Function
      },
      getFieldOptions: {
        check: Function
      }
    });
    return this.opts.options = [];
  };

  FieldSelector.prototype.setData = function(data) {
    this._options = this.__getOptions;
    return FieldSelector.__super__.setData.call(this, data);
  };

  FieldSelector.prototype.render = function() {
    var _options, data;
    data = this.getData();
    if (CUI.util.isFunction(this._options)) {
      _options = this._options();
    } else {
      _options = this._options;
    }
    if (data && !_options.some((function(_this) {
      return function(option) {
        return option.value === data[_this.getName()];
      };
    })(this))) {
      data[this.getName()] = null;
    }
    FieldSelector.__super__.render.call(this);
    return CUI.Events.listen({
      node: this.getForm(),
      type: "data-changed",
      call: (function(_this) {
        return function() {
          data = _this.getData();
          if (!data) {
            return;
          }
          if (_this.__currentObjectTypeId === _this.__getObjectType(data)) {
            return;
          }
          data[_this.getName()] = null;
          _this._options = _this.__getOptions;
          _this._empty_text = _this._empty_text || _this._placeholder;
          return _this.reload();
        };
      })(this)
    });
  };

  FieldSelector.prototype.__getOptions = function() {
    var addOption, data, field, fieldInLinkedObject, i, idTable, j, len, len1, mask, objectType, objecttype, options, ref, ref1, table;
    data = this.getData();
    objecttype = this.__getObjectType(data);
    if (!objecttype) {
      return [
        {
          text: $$("field.selector.objecttype-not-selected"),
          value: null
        }
      ];
    }
    if (CUI.util.isString(objecttype)) {
      table = ez5.schema.CURRENT._table_by_name[objecttype];
      if (!table) {
        return [
          {
            text: $$("field.selector.objecttype-not-exists", {
              objecttype: this.__getObjectType(data)
            }),
            value: null
          }
        ];
      }
      idTable = table.table_id;
    } else if (objecttype.table_id) {
      idTable = objecttype.table_id;
    } else {
      idTable = objecttype;
    }
    if (this.__currentObjectTypeId !== objecttype) {
      this.__currentObjectTypeId = objecttype;
      objectType = new Objecttype(new Table(this._schema, idTable));
      if (!objectType) {
        return [
          {
            text: $$("field.selector.objecttype-not-exists", {
              objecttype: this.__getObjectType(data)
            }),
            value: null
          }
        ];
      }
      mask = Mask.getMaskByMaskName("_all_fields", idTable, this._schema);
      objectType.addMask(mask);
      this.__optionFields = objectType.getAllFields();
    }
    options = [];
    addOption = (function(_this) {
      return function(_field, parentField) {
        var _option, _options, i, len, text, value;
        if (_field instanceof NestedTable) {
          return;
        }
        if (_this._filter && !_this._filter(_field, data, parentField)) {
          return;
        }
        switch (_this._store_value) {
          case "fullname":
            if (parentField instanceof LinkedObject) {
              value = parentField.fullName() + "." + _field.name();
            } else {
              value = _field.fullName();
            }
            break;
          case "name":
            value = _field.name();
            break;
          case "id":
            value = "" + (_field.id());
        }
        if (parentField instanceof LinkedObject) {
          text = parentField.fullNameLocalized() + " / " + _field.fullNameLocalized();
        } else {
          text = _field.fullNameLocalized();
        }
        if (_this._show_name) {
          text += " [" + (_field.name()) + "]";
        }
        _options = typeof _this._getFieldOptions === "function" ? _this._getFieldOptions(_field, text, value) : void 0;
        if (!_options) {
          options.push({
            text: text,
            value: value
          });
          return;
        }
        if (CUI.util.isArray(_options)) {
          for (i = 0, len = _options.length; i < len; i++) {
            _option = _options[i];
            options.push(_option);
          }
        } else {
          options.push(_options);
        }
      };
    })(this);
    ref = this.__optionFields;
    for (i = 0, len = ref.length; i < len; i++) {
      field = ref[i];
      if (this._deep_linked_objects && field instanceof LinkedObject) {
        ref1 = field.linkMask().getFields("all");
        for (j = 0, len1 = ref1.length; j < len1; j++) {
          fieldInLinkedObject = ref1[j];
          addOption(fieldInLinkedObject, field);
        }
        continue;
      }
      addOption(field, field.getFatherField());
    }
    if (this._sort) {
      options.sort(this._sort);
    }
    options.unshift({
      text: this._placeholder,
      value: null
    });
    return options;
  };

  FieldSelector.prototype.__getObjectType = function(data) {
    return (data != null ? data[this._objecttype_data_key] : void 0) || this._objecttype_id;
  };

  return FieldSelector;

})(CUI.Select);
// Generated by CoffeeScript 1.12.7
var SearchSelector,
  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;

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

  function SearchSelector() {
    this.__executeSearch = bind(this.__executeSearch, this);
    return SearchSelector.__super__.constructor.apply(this, arguments);
  }

  SearchSelector.prototype.initOpts = function() {
    SearchSelector.__super__.initOpts.call(this);
    return this.addOpts({
      bottom: {
        check: "PlainObject"
      },
      top: {
        check: "PlainObject"
      },
      inputType: {
        check: String,
        "default": "text"
      }
    });
  };

  SearchSelector.prototype.readOpts = function() {
    SearchSelector.__super__.readOpts.call(this);
    this.__contentLayout = new CUI.HorizontalLayout({
      center: {
        content: new CUI.HorizontalLayout({
          "class": "search-selector-input-container",
          center: {
            content: void 0
          },
          right: {
            content: void 0
          }
        })
      }
    });
    return this;
  };

  SearchSelector.prototype.render = function() {
    var buttonUI, horizontalLayout, idButton, inputUI, opts, tooltipText, verticalLayout;
    SearchSelector.__super__.render.call(this);
    this.addClass('cui-search-selector');
    idButton = "search-selector-button-" + (this._id || "");
    buttonUI = null;
    inputUI = null;
    if (this._ui) {
      buttonUI = this._ui + ":button";
      inputUI = this._ui + ":input";
    }
    this.__button = new LocaButton({
      appearance: "normal",
      loca_key: this.__getButtonLocaKey(),
      id: idButton,
      ui: buttonUI,
      onClick: (function(_this) {
        return function() {
          if (_this.__autocompletion.isShown()) {
            _this.__autocompletion.hide();
          } else {
            _this.__showAll();
          }
        };
      })(this)
    });
    this.__input = CUI.dom.$element("input", null, {
      type: this._inputType,
      spellcheck: "false",
      placeholder: this.__getInputPlaceholder(),
      id: this._id,
      ui: inputUI,
      "aria-labelledby": idButton
    });
    this.__contentLayout._center.content.replace(this.__input, "center");
    horizontalLayout = new CUI.HorizontalLayout({
      maximize: false,
      right: {
        content: this.__button
      },
      center: {
        content: this.__contentLayout
      }
    });
    opts = this.__getAutocompletionOpts();
    if (this._ui) {
      opts.ui = this._ui + ":autocompletion_popup";
    }
    CUI.util.mergeMap(opts, {
      element: horizontalLayout,
      onHide: (function(_this) {
        return function() {
          return _this.focus();
        };
      })(this)
    });
    this.__autocompletion = new AutocompletionPopup(opts);
    verticalLayout = new CUI.VerticalLayout({
      top: this._top,
      center: {
        content: horizontalLayout
      },
      bottom: this._bottom
    });
    this.append(verticalLayout);
    tooltipText = this.__getInputTooltip();
    if (!CUI.util.isEmpty(tooltipText)) {
      new CUI.Tooltip({
        element: this.__input,
        text: tooltipText
      });
    }
    this.__initData = this.getValue();
    this.__initValue = this.__getDisplayText();
    this.__initIcon = this.__getIcon();
    this.__initEvents();
    return this;
  };

  SearchSelector.prototype.__showAll = function() {
    var value;
    value = this.__input.value;
    this.__input.value = "";
    this.search();
    this.__input.value = value;
    return this.focus();
  };

  SearchSelector.prototype.search = function() {
    if (this.__showSpinnerOnSearch()) {
      this.__startSpinner();
    }
    return this.__search().always((function(_this) {
      return function() {
        if (_this.__showSpinnerOnSearch()) {
          return _this.__stopSpinner();
        }
      };
    })(this));
  };

  SearchSelector.prototype.__executeSearch = function() {
    var inputValue;
    inputValue = this.__input.value;
    if (this.__lastInputValue === inputValue) {
      return;
    }
    this.__lastInputValue = inputValue;
    this.search();
  };

  SearchSelector.prototype.__setInputDisplayValue = function(val, icon) {
    this.__input.value = val;
    this.__setIcon(icon);
    return val;
  };

  SearchSelector.prototype.__setIcon = function(icon) {
    if (icon) {
      CUI.dom.addClass(this.__contentLayout, "has-search-selector-input-icon");
      this.__contentLayout._center.content.replace(new CUI.Icon({
        icon: icon
      }), "right");
    } else {
      CUI.dom.removeClass(this.__contentLayout, "has-search-selector-input-icon");
      this.__contentLayout._center.content.empty("right");
    }
  };

  SearchSelector.prototype.displayValue = function() {
    SearchSelector.__super__.displayValue.call(this);
    if (this.getValue()) {
      this.__setInputDisplayValue(this.__getDisplayText(), this.__getIcon());
    } else {
      this.__setInputDisplayValue("");
    }
    return this;
  };

  SearchSelector.prototype.__initEvents = function() {
    CUI.Events.listen({
      node: this.__button,
      type: "keydown",
      call: (function(_this) {
        return function(ev) {
          if (ev.getKeyboard() === "Tab") {
            _this.__autocompletion.hide();
          }
        };
      })(this)
    });
    CUI.Events.listen({
      node: this.__input,
      type: "keydown",
      call: (function(_this) {
        return function(ev) {
          var value;
          if (ev.getKeyboard() === "Tab" || ev.getKeyboard() === "Shift+Tab") {
            _this.__autocompletion.hide();
            ev.stopPropagation();
          }
          _this.__autocompletion.keydown(ev);
          if (ev.isPropagationStopped()) {
            return;
          }
          value = _this.__input.value;
          CUI.scheduleCallback({
            call: function() {
              if (_this.getValue() && value !== _this.__input.value) {
                _this.storeValue();
                _this.__setIcon();
                return _this.focus();
              }
            }
          });
        };
      })(this)
    });
    CUI.Events.listen({
      node: this.__input,
      type: "keyup",
      call: (function(_this) {
        return function(ev) {
          _this.__autocompletion.keyup(ev);
          if (ev.isPropagationStopped()) {
            return;
          }
          ev.stopPropagation();
          if (ev.getKeyboardKey() === "Esc") {
            if (_this.__autocompletion.isShown()) {
              _this.__autocompletion.hide();
            } else if (_this.__input.value.length > 0) {
              _this.setValue();
              _this.__executeSearch();
            } else if (_this.__input === document.activeElement) {
              _this.__setInputDisplayValue(_this.__initValue, _this.__initIcon);
              _this.storeValue(_this.__initData, {
                no_trigger: false
              });
              _this.__input.blur();
              return;
            }
            ev.preventDefault();
            return;
          }
          CUI.scheduleCallback({
            ms: 200,
            call: _this.__executeSearch
          });
        };
      })(this)
    });
  };

  SearchSelector.prototype.focus = function() {
    return this.__input.focus();
  };

  SearchSelector.prototype.__startSpinner = function() {
    return this.__button.startSpinner();
  };

  SearchSelector.prototype.__stopSpinner = function() {
    return this.__button.stopSpinner();
  };

  SearchSelector.prototype.__getIcon = function() {};

  SearchSelector.prototype.__getInputTooltip = function() {};

  SearchSelector.prototype.__showSpinnerOnSearch = function() {
    return false;
  };

  SearchSelector.prototype.__getDisplayText = function() {
    console.warn("SearchSelector :: __getDisplayText not implemented", this);
    return "Display text not implemented";
  };

  SearchSelector.prototype.__search = function() {
    console.error("SearchSelector :: __search not implemented", this);
    return CUI.resolvedPromise();
  };

  SearchSelector.prototype.__getInputPlaceholder = function() {
    return "";
  };

  SearchSelector.prototype.__getButtonLocaKey = function() {
    console.warn("SearchSelector :: __getButtonLocaKey not implemented", this);
    return "";
  };

  SearchSelector.prototype.__getAutocompletionOpts = function() {
    return {};
  };

  SearchSelector.prototype.checkValue = function(val) {
    return val === null;
  };

  SearchSelector.prototype.setValue = function(data) {
    if (data == null) {
      data = null;
    }
    return SearchSelector.__super__.setValue.call(this, data, {
      no_trigger: false
    });
  };

  return SearchSelector;

})(CUI.DataFieldInput);
// Generated by CoffeeScript 1.12.7
var UserGroupCategorySelector,
  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;

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

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

  UserGroupCategorySelector.prototype.initOpts = function() {
    UserGroupCategorySelector.__super__.initOpts.call(this);
    return this.addOpts({
      category: {
        check: String,
        mandatory: true
      }
    });
  };

  UserGroupCategorySelector.prototype.__search = function() {
    var inputValue, phrase, ref, sopts, str;
    inputValue = this.__input.value;
    this.setValue(inputValue);
    ref = Search.getPhrase(inputValue), str = ref[0], phrase = ref[1];

    /*
                search: [
                    type: "match"
                    bool: "must"
                    mode: "wildcard"
                    string: "*#{str}*"
                    fields: ["group.category_a", "group.category_b", "group.category_c"]
                ,
                    bool: "must"
                    type: "in"
                    fields: [ "_basetype" ]
                    in: [ "group" ]
                ]
     */
    sopts = {
      type: "group",
      search: [
        {
          bool: "must",
          type: "in",
          fields: ["_basetype"],
          "in": ["group"]
        }
      ],
      generate_rights: false,
      limit: 100,
      offset: 0,
      aggregations: {
        _groups: {
          field: "group.type",
          type: "term",
          limit: 10000
        }
      }
    };
    sopts.aggregations[this._category] = {
      field: "group." + this._category,
      type: "term",
      limit: 10000
    };
    this.__searchRequest = ez5.api.search({
      data: {
        systemListManager: "GroupManager"
      },
      json_data: sopts
    }).always((function(_this) {
      return function() {
        return delete _this.__searchRequest;
      };
    })(this)).done((function(_this) {
      return function(data) {
        if (data.count > 0) {
          return _this.__show(data);
        }
      };
    })(this));
    return this.__searchRequest;
  };

  UserGroupCategorySelector.prototype.render = function() {
    UserGroupCategorySelector.__super__.render.call(this);
    return this.__autocompletion.addContainer("all");
  };

  UserGroupCategorySelector.prototype.__getInputPlaceholder = function() {
    return $$("admin.group.category.field.placeholder");
  };

  UserGroupCategorySelector.prototype.__getButtonLocaKey = function() {
    return "admin.group.category.field.button";
  };

  UserGroupCategorySelector.prototype.__show = function(searchData) {
    var anyOption, cat, i, inputValue, len, ref, ref1, term, terms;
    inputValue = this.__input.value;
    terms = searchData != null ? (ref = searchData.aggregations) != null ? (ref1 = ref[this._category]) != null ? ref1.terms : void 0 : void 0 : void 0;
    if (CUI.util.isEmpty(terms)) {
      return;
    }
    this.__autocompletion.emptyContainer();
    anyOption = false;
    for (i = 0, len = terms.length; i < len; i++) {
      term = terms[i];
      cat = term.term;
      if (CUI.util.isEmpty(cat)) {
        continue;
      }
      if (cat.toLowerCase().includes(inputValue.toLowerCase()) || inputValue.length === 0) {
        (function(_this) {
          return (function(cat) {
            var item;
            anyOption = true;
            item = _this.__autocompletion.appendItem("all", new CUI.VerticalList({
              content: [cat]
            }));
            return CUI.Events.listen({
              type: "click",
              node: item,
              call: function() {
                _this.setValue(cat);
                _this.__autocompletion.hide();
              }
            });
          });
        })(this)(cat);
      }
    }
    if (anyOption) {
      this.__autocompletion.show();
    } else {
      this.__autocompletion.hide();
    }
  };

  UserGroupCategorySelector.prototype.__getDisplayText = function() {
    return this.getValue();
  };

  return UserGroupCategorySelector;

})(SearchSelector);
// Generated by CoffeeScript 1.12.7
var ComboBox,
  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;

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

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

  ComboBox.prototype.initOpts = function() {
    ComboBox.__super__.initOpts.call(this);
    return this.addOpts({
      options: {
        check: "Array",
        mandatory: true
      },
      disableKeyEvents: {
        "default": false,
        check: Boolean
      },
      placeholder: {
        check: String,
        "default": ""
      },
      showDisplayValue: {
        "default": false,
        check: Boolean
      },
      valueConverter: {
        check: "PlainObject"
      },
      customValueLabel: {
        check: "PlainObject"
      }
    });
  };

  ComboBox.prototype.readOpts = function() {
    ComboBox.__super__.readOpts.call(this);
    if (this._showDisplayValue) {
      return this._inputType = "text";
    }
  };

  ComboBox.prototype.render = function() {
    ComboBox.__super__.render.call(this);
    this.__autocompletion.addContainer("all");
    return this;
  };

  ComboBox.prototype.__search = function() {
    var anyOption, fn, i, inputValue, len, option, ref;
    inputValue = this.__input.value;
    this.__autocompletion.emptyContainer();
    if (this._options != null) {
      anyOption = false;
      ref = this._options;
      fn = (function(_this) {
        return function(option) {
          var item;
          if (option.text.toLowerCase().includes(inputValue.toLowerCase()) || inputValue.length === 0) {
            anyOption = true;
            item = _this.__autocompletion.appendItem("all", new CUI.VerticalList({
              content: [option.text]
            }));
            return CUI.Events.listen({
              type: "click",
              node: item,
              call: function() {
                _this.setValue(option.value);
                if (_this._showDisplayValue) {
                  _this.__setInputDisplayValue(option.text, null);
                } else {
                  _this.__setInputDisplayValue(option.value, null);
                }
                return _this.__autocompletion.hide();
              }
            });
          }
        };
      })(this);
      for (i = 0, len = ref.length; i < len; i++) {
        option = ref[i];
        fn(option);
      }
      if (anyOption) {
        this.__autocompletion.show();
      } else {
        this.__autocompletion.hide();
      }
    } else {
      this.__autocompletion.hide();
    }
    return CUI.resolvedPromise();
  };

  ComboBox.prototype.__getDisplayText = function() {
    var displayValue, i, len, option, ref, value;
    value = this.getValue();
    if ((value != null) && this._showDisplayValue) {
      ref = this._options;
      for (i = 0, len = ref.length; i < len; i++) {
        option = ref[i];
        if (option.value === value) {
          return option.text;
        }
      }
    }
    if (value != null) {
      displayValue = this.__convertToDisplay(value);
      return "" + displayValue + this.__getCustomValueSuffix(displayValue);
    }
    return "";
  };

  ComboBox.prototype.__getCustomValueSuffix = function(displayValue) {
    if (!this._customValueLabel) {
      return "";
    }
    if (displayValue === 1 || displayValue === -1) {
      return " " + this._customValueLabel.singular;
    }
    return " " + this._customValueLabel.plural;
  };

  ComboBox.prototype.__getInputPlaceholder = function() {
    return this._placeholder;
  };

  ComboBox.prototype.__getButtonLocaKey = function() {
    return "admin.group.category.field.button";
  };

  ComboBox.prototype.__convertToStored = function(val) {
    var ref;
    if ((ref = this._valueConverter) != null ? ref.toStoredValue : void 0) {
      return this._valueConverter.toStoredValue(val);
    }
    return val;
  };

  ComboBox.prototype.__convertToDisplay = function(val) {
    var ref;
    if ((ref = this._valueConverter) != null ? ref.toDisplayValue : void 0) {
      return this._valueConverter.toDisplayValue(val);
    }
    return val;
  };

  ComboBox.prototype.__initEvents = function() {
    if (this._disableKeyEvents) {
      this.__input.addEventListener("input", (function(_this) {
        return function() {
          var inputValue, parsedValue;
          inputValue = _this.__input.value;
          if (inputValue.length > 0) {
            parsedValue = parseInt(inputValue, 10);
            if (!isNaN(parsedValue)) {
              _this.storeValue(_this.__convertToStored(parsedValue));
            }
          } else {
            _this.storeValue(null);
          }
          _this.search();
        };
      })(this));
      if (this._showDisplayValue) {
        this.__input.addEventListener("focus", (function(_this) {
          return function() {
            var value;
            value = _this.getValue();
            if (value != null) {
              _this.__input.value = "" + _this.__convertToDisplay(value);
            }
          };
        })(this));
        this.__input.addEventListener("blur", (function(_this) {
          return function() {
            _this.__setInputDisplayValue(_this.__getDisplayText(), null);
          };
        })(this));
      }
      return;
    }
    return ComboBox.__super__.__initEvents.call(this);
  };

  return ComboBox;

})(SearchSelector);
// Generated by CoffeeScript 1.12.7
var PoolSelector,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  PoolSelector.prototype.initOpts = function() {
    PoolSelector.__super__.initOpts.call(this);
    return this.addOpts({
      pool_ids: {
        check: Array
      },
      omit_root_pool: {
        check: Boolean,
        "default": true
      },
      reverse: {
        check: Boolean,
        "default": false
      },
      placeholder: {
        check: String
      }
    });
  };

  PoolSelector.prototype.__getInputTooltip = function() {
    return $$("pool.field.select.tooltip");
  };

  PoolSelector.prototype.__getInputPlaceholder = function() {
    if (this._placeholder) {
      return this._placeholder;
    }
    if (!this._reverse) {
      return $$("pool.field.placeholder");
    } else {
      return $$("pool.field.reverse_pool_auto_if_no_value");
    }
  };

  PoolSelector.prototype.__getButtonLocaKey = function() {
    return "pool.field.input.search.button.open_search";
  };

  PoolSelector.prototype.__getDisplayText = function() {
    var path, ref, ref1, ref2;
    if (!this.__forceSimpleDisplay) {
      path = Pool.renderPlainPoolPath((ref = this.getValue()) != null ? ref._path : void 0, ">");
    }
    return path || ez5.loca.getBestFrontendValue((ref1 = this.getValue()) != null ? (ref2 = ref1.pool) != null ? ref2.name : void 0 : void 0) || "";
  };

  PoolSelector.prototype.__getAutocompletionOpts = function() {
    return {
      "class": "ez5-pool-field-autocompletion-popup"
    };
  };

  PoolSelector.prototype.__showSpinnerOnSearch = function() {
    return true;
  };

  PoolSelector.prototype.render = function() {
    var treeElement;
    PoolSelector.__super__.render.call(this);
    this.__poolManager = new PoolManagerPoolField({
      isPoolSelectable: (function(_this) {
        return function(pool) {
          var ref;
          if (!_this._pool_ids) {
            return true;
          }
          if (ref = pool.id, indexOf.call(_this._pool_ids, ref) >= 0) {
            return true;
          }
          return false;
        };
      })(this),
      onSelect: (function(_this) {
        return function(ev, info) {
          if (!ev) {
            return;
          }
          _this.setValue(info.node.data);
          _this.__lastInputValue = _this.__input.value;
          _this.__input.focus();
          return _this.__autocompletion.hide();
        };
      })(this)
    });
    treeElement = this.__poolManager.getTree().render();
    CUI.dom.append(this.__autocompletion.DOM, treeElement);
    CUI.Events.listen({
      type: "focus",
      node: this.__input,
      call: (function(_this) {
        return function() {
          _this.__forceSimpleDisplay = true;
          _this.displayValue();
          _this.__forceSimpleDisplay = false;
        };
      })(this)
    });
    CUI.Events.listen({
      type: "blur",
      node: this.__input,
      call: (function(_this) {
        return function() {
          _this.displayValue();
        };
      })(this)
    });
    return this;
  };

  PoolSelector.prototype.__search = function() {
    var inputValue, opts, search;
    search = [];
    if (this._pool_ids) {
      if (this._pool_ids.length === 0) {
        this.__loadPools([]);
        return CUI.resolvedPromise();
      }
      search.push({
        type: "in",
        bool: "must",
        fields: ["pool._id"],
        "in": this._pool_ids
      });
    }
    opts = {
      searchOpts: {
        search: search
      },
      doOpen: false,
      buildTree: true
    };
    inputValue = this.__input.value;
    if (!CUI.util.isEmpty(inputValue)) {
      if (ez5.version("6")) {
        inputValue = inputValue.replace(/^(\s*\**\*[\s*]*)/, '*');
        inputValue = inputValue.replace(/[\s*]+$/, '');
        if (!CUI.util.isEmpty(inputValue)) {
          search.push({
            bool: "should",
            type: "match",
            mode: "wildcard",
            string: inputValue + SearchUtil.ASTERISK
          });
        }
      } else {
        search.push({
          type: "match",
          bool: "must",
          mode: "fulltext",
          string: inputValue
        });
      }
      opts.doOpen = true;
    }
    return this.__poolManager.loadList(null, opts).done((function(_this) {
      return function(pools) {
        return _this.__loadPools(pools);
      };
    })(this));
  };

  PoolSelector.prototype.__loadPools = function(_pools) {
    var inputValue, promise;
    if (_pools.length === 0) {
      promise = this.__poolManager.tree.load_data([]);
      this.__autocompletion.hide();
    } else {
      if (this._omit_root_pool) {
        promise = this.__poolManager.tree.load_data(_pools[0].children);
      } else {
        promise = this.__poolManager.tree.load_data(_pools);
      }
    }
    inputValue = this.__input.value;
    if (!CUI.util.isEmpty(inputValue)) {
      promise.done((function(_this) {
        return function() {
          var pools, ref, value;
          value = _this.getValue();
          pools = _this.__poolManager.tree.root.find(function(pool) {
            var ref;
            return pool instanceof Pool && pool.getId() === (value != null ? (ref = value.pool) != null ? ref._id : void 0 : void 0);
          });
          return (ref = pools[0]) != null ? ref.select().done(function() {
            return CUI.Events.trigger({
              type: "content-resize",
              node: _this.__autocompletion
            });
          }) : void 0;
        };
      })(this));
    }
    promise.done((function(_this) {
      return function() {
        return _this.__autocompletion.show();
      };
    })(this));
    return promise;
  };

  PoolSelector.prototype.setValue = function(data) {
    var old_pool, ref;
    if (data == null) {
      data = null;
    }
    old_pool = this.getValue();
    if ((old_pool != null ? old_pool.pool._id : void 0) === (data != null ? (ref = data.pool) != null ? ref._id : void 0 : void 0)) {
      return;
    }
    return PoolSelector.__super__.setValue.call(this, data, {
      no_trigger: false
    });
  };

  PoolSelector.prototype.checkValue = function(val) {
    return PoolSelector.__super__.checkValue.call(this) || CUI.util.isPlainObject(val);
  };

  return PoolSelector;

})(SearchSelector);
// Generated by CoffeeScript 1.12.7
var UserGroupSelector,
  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;

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

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

  UserGroupSelector.prototype.initOpts = function() {
    UserGroupSelector.__super__.initOpts.call(this);
    return this.addOpts({
      aclWhoManager: {
        mandatory: true,
        check: AclWhoManager
      },
      filterData: {
        check: Function
      },
      generate_rights: {
        "default": false,
        check: Boolean
      }
    });
  };

  UserGroupSelector.prototype.__getAutocompletionOpts = function() {
    var opts;
    opts = {
      "class": "acl-who-manager"
    };
    return opts;
  };

  UserGroupSelector.prototype.__getButtonLocaKey = function() {
    return "query.element.input.search.button.open_search";
  };

  UserGroupSelector.prototype.__getInputPlaceholder = function() {
    return this._aclWhoManager.getPlaceholderText();
  };

  UserGroupSelector.prototype.__getDisplayText = function() {
    var ref;
    return (ref = this.__getAclWhoInstance()) != null ? ref.getDisplayText() : void 0;
  };

  UserGroupSelector.prototype.__getIcon = function() {
    var ref;
    return (ref = this.__getAclWhoInstance()) != null ? ref.getIcon() : void 0;
  };

  UserGroupSelector.prototype.render = function() {
    var aclWhoInstance, collectionLabel;
    UserGroupSelector.__super__.render.call(this);
    aclWhoInstance = this.__getAclWhoInstance();
    if (aclWhoInstance instanceof AclWhoCollection) {
      collectionLabel = new CUI.Label({
        text: aclWhoInstance.getDisplayText()
      });
      this.replace(collectionLabel);
      return this;
    }
    this.__autocompletion.addContainer("system_groups");
    this.__autocompletion.addContainer("groups");
    this.__autocompletion.addContainer("system_users");
    this.__autocompletion.addContainer("owner");
    this.__autocompletion.addContainer("users");
    this.__autocompletion.addContainer("empty");
    return this;
  };

  UserGroupSelector.prototype.__search = function() {
    var filterUserTypes, inputValue, phrase, ref, search, str;
    filterUserTypes = ["anonymous", "collection"];
    if (this._aclWhoManager._filter_system_users) {
      filterUserTypes.push("system");
    }
    search = [
      {
        bool: "must",
        type: "in",
        fields: ["_basetype"],
        "in": this._aclWhoManager._who_filter
      }, {
        type: "in",
        bool: "must_not",
        fields: ["user.type"],
        "in": filterUserTypes
      }
    ];
    if (!this._aclWhoManager._allowEmailUser) {
      search.push({
        type: "in",
        bool: "must_not",
        fields: ["user.type"],
        "in": ["email"]
      });
    }
    if (this._aclWhoManager._filter_system_groups) {
      search.push({
        bool: "must_not",
        type: "in",
        fields: ["group.type"],
        "in": ["system"]
      });
    }
    if (this._aclWhoManager._filter_groups) {
      search.push({
        bool: this._aclWhoManager._filter_groups_bool,
        type: "in",
        fields: ["group.type"],
        "in": this._aclWhoManager._filter_groups
      });
    }
    inputValue = this.__input.value;
    if (!CUI.util.isEmpty(inputValue)) {
      ref = Search.getPhrase(inputValue), str = ref[0], phrase = ref[1];
      search.push({
        type: "match",
        phrase: phrase,
        string: str + "*",
        bool: "should",
        mode: "wildcard"
      });
    }
    search.push({
      type: "in",
      bool: "must",
      fields: ["_archived_at"],
      "in": [null]
    });
    return ez5.api.search({
      json_data: {
        type: "acl",
        search: search,
        limit: 500,
        generate_rights: this._generate_rights,
        highlight: {},
        sort: [
          {
            field: "_basetype",
            order: "ASC"
          }, {
            field: "group.displayname",
            order: "ASC"
          }, {
            field: "user._generated_displayname",
            order: "ASC"
          }
        ]
      }
    }).done((function(_this) {
      return function(data) {
        return _this.__showSearchResult(data, inputValue);
      };
    })(this));
  };

  UserGroupSelector.prototype.__showSearchResult = function(data, searchInput) {
    var aclWho, aclWhoPool, button, container, containerKey, fn, group, i, inputValue, item, j, label, len, len1, object, ref, ref1, user;
    this.__autocompletion.emptyContainer();
    this.__autocompletion.show();
    inputValue = this.__input.value;
    if (this._aclWhoManager._allowEmailUser && CUI.EmailInput.regexp.exec(inputValue) && ez5.session.hasSystemRight("root", "frontend_features[acl_manager][create_email_user]") && !data.objects.some(function(object) {
      var ref;
      return ((ref = object.user) != null ? ref.email : void 0) === inputValue;
    })) {
      this.__autocompletion.addClass("acl-who-manager-not-found");
      container = this.__autocompletion.getContainer("empty");
      container.append(new CUI.EmptyLabel({
        text: $$("acl.who.manager.not_found", {
          search: inputValue
        })
      }).DOM);
      button = new LocaButton({
        loca_key: "acl.who.manager.create_email_user.button",
        loca_key_attrs: {
          search: inputValue
        },
        onClick: (function(_this) {
          return function() {
            var aclWhoEmail;
            _this.__autocompletion.hide();
            _this.__input.blur();
            aclWhoEmail = new AclWhoEmail({
              _basetype: "user",
              user: {
                login: inputValue.toLocaleLowerCase(),
                type: "email"
              }
            });
            return aclWhoEmail.showCreateModal().done(function() {
              return _this.__onWhoSelected(aclWhoEmail);
            });
          };
        })(this)
      });
      container.append(button.DOM);
      console.debug("AclWhoManager.showSearchResult: EMAIL!", inputValue);
    } else {
      this.__autocompletion.removeClass("acl-who-manager-not-found");
    }
    if (this._aclWhoManager._allowPoolUser && (searchInput === "" || /^pool.*/.test(searchInput))) {
      this.__autocompletion.removeClass("acl-who-manager-not-found");
      aclWhoPool = new AclWhoPool();
      item = this.__autocompletion.appendItem("owner", aclWhoPool.getAutocompletionItem());
      CUI.Events.listen({
        type: "click",
        node: item,
        call: (function(_this) {
          return function() {
            _this.__onWhoSelected(aclWhoPool);
            _this.__autocompletion.hide();
          };
        })(this)
      });
    }
    if (this._aclWhoManager._allowMatchAny) {
      data.objects.splice(0, 0, new AclWhoMatchAny());
    }
    if (this._aclWhoManager._allowOwner) {
      data.objects.splice(0, 0, new AclWhoOwner());
    }
    if (this._filterData) {
      data.objects = data.objects.filter(this._filterData);
    }
    ref = data.objects;
    fn = (function(_this) {
      return function(aclWho) {
        return CUI.Events.listen({
          type: "click",
          node: item,
          call: function() {
            _this.__onWhoSelected(aclWho);
            _this.__autocompletion.hide();
          }
        });
      };
    })(this);
    for (i = 0, len = ref.length; i < len; i++) {
      object = ref[i];
      if (object instanceof AclWhoMatchAny || object instanceof AclWhoOwner) {
        aclWho = object;
      } else {
        aclWho = AclWho.newInstance(object);
      }
      if (aclWho instanceof AclWhoGroup) {
        group = aclWho.getGroup();
        if (group instanceof SystemGroup) {
          containerKey = "system_groups";
        } else {
          containerKey = "groups";
        }
      } else {
        user = typeof aclWho.getUser === "function" ? aclWho.getUser() : void 0;
        if (user && user.getType() === "system" || aclWho instanceof AclWhoOwner) {
          containerKey = "system_users";
        } else {
          containerKey = "users";
        }
      }
      item = this.__autocompletion.appendItem(containerKey, aclWho.getAutocompletionItem());
      fn(aclWho);
    }
    ref1 = ["system_groups", "groups", "system_users", "users", "owner"];
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      containerKey = ref1[j];
      container = this.__autocompletion.getContainer(containerKey);
      if (container.isEmpty()) {
        continue;
      }
      label = new LocaLabel({
        loca_key: "acl.who.manager.container." + containerKey + ".label",
        appearance: "secondary",
        size: "mini"
      });
      container.prepend(label);
    }
    if (CUI.util.isEmpty(data.objects)) {
      container = this.__autocompletion.getContainer("empty");
      if (container.isEmpty()) {
        label = new LocaLabel({
          loca_key: "acl.who.manager.container.empty.label"
        });
        container.prepend(label);
      }
    }
    this.__autocompletion.autoSize();
    return this;
  };

  UserGroupSelector.prototype.__onWhoSelected = function(who) {
    var base, data;
    if (who == null) {
      who = null;
    }
    if (who instanceof AclWhoGroup) {
      ez5.groupManager.addGroupToAllGroups(who.getGroup());
    }
    data = this.__getAclWhoData(who);
    this.setValue(data);
    if (typeof (base = this._aclWhoManager)._onUpdate === "function") {
      base._onUpdate(this.__data, this._aclWhoManager);
    }
    this.triggerDataChanged({
      action: "store"
    });
  };

  UserGroupSelector.prototype.__getAclWhoInstance = function() {
    var aclWhoData, data;
    data = this.getValue();
    if (this.__aclWhoInstance) {
      aclWhoData = this.__getAclWhoData(this.__aclWhoInstance);
      if (CUI.util.isEqual(data, aclWhoData)) {
        return this.__aclWhoInstance;
      }
    }
    this.__aclWhoInstance = null;
    if (data) {
      this.__aclWhoInstance = AclWho.newInstance(data);
    } else if (this._aclWhoManager._allowMatchAny) {
      this.__aclWhoInstance = new AclWhoMatchAny();
    }
    return this.__aclWhoInstance;
  };

  UserGroupSelector.prototype.__getAclWhoData = function(aclWhoInstance) {
    var data;
    data = null;
    if (aclWhoInstance) {
      if (this._aclWhoManager._store_full_data) {
        data = aclWhoInstance.getData();
      } else {
        data = aclWhoInstance.getSaveData();
      }
    }
    return data;
  };

  return UserGroupSelector;

})(SearchSelector);
// 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.ObjecttypePlugin = (function(superClass) {
  extend(ObjecttypePlugin, superClass);

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

  ObjecttypePlugin.prototype.initOpts = function() {
    ObjecttypePlugin.__super__.initOpts.call(this);
    this.addOpts({
      objecttypeListViewItem: {
        mandatory: true,
        check: ObjecttypeListViewItem
      }
    });
  };

  ObjecttypePlugin.prototype.addToTabs = function(tabs) {
    var tab;
    tab = this.getTab();
    if (!tab) {
      return;
    }
    tabs.push(tab);
  };

  ObjecttypePlugin.prototype.onLoad = function() {};

  ObjecttypePlugin.prototype.getTab = function() {};

  ObjecttypePlugin.prototype.getSaveData = function(saveData) {};

  ObjecttypePlugin.prototype.destroy = function() {
    return ObjecttypePlugin.__super__.destroy.call(this);
  };

  ObjecttypePlugin.prototype.__getData = function() {
    return this._objecttypeListViewItem.data;
  };

  return ObjecttypePlugin;

})(CUI.Plugin);

Objecttype.plugins = new CUI.PluginRegistry({
  "class": ez5.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.PoolPlugin = (function(superClass) {
  extend(PoolPlugin, superClass);

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

  PoolPlugin.prototype.initOpts = function() {
    PoolPlugin.__super__.initOpts.call(this);
    this.addOpts({
      pool: {
        check: Pool,
        mandatory: true
      }
    });
  };

  PoolPlugin.prototype.getTabs = function(tabs) {};

  PoolPlugin.prototype.getSaveData = function(save_data) {};

  PoolPlugin.prototype.getInfoDivRows = function(rows) {};

  PoolPlugin.prototype.getInfoDiv = function(nodes) {};

  PoolPlugin.prototype.destroy = function() {
    return PoolPlugin.__super__.destroy.call(this);
  };

  return PoolPlugin;

})(CUI.Plugin);

Pool.plugins = new CUI.PluginRegistry({
  "class": ez5.PoolPlugin
});
// 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.UserPlugin = (function(superClass) {
  extend(UserPlugin, superClass);

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

  UserPlugin.prototype.initOpts = function() {
    UserPlugin.__super__.initOpts.call(this);
    this.addOpts({
      user: {
        check: User,
        mandatory: true
      }
    });
  };

  UserPlugin.prototype.getTabs = function(tabs) {};

  UserPlugin.prototype.getSaveData = function(saveData) {};

  UserPlugin.prototype.isAllowed = function() {
    return true;
  };

  return UserPlugin;

})(CUI.Plugin);

User.plugins = new CUI.PluginRegistry({
  "class": ez5.UserPlugin
});
// 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.UserPreferencesPlugin = (function(superClass) {
  extend(UserPreferencesPlugin, superClass);

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

  UserPreferencesPlugin.prototype.getTabs = function(tabs) {
    tabs.push({
      name: "preferences",
      text: $$("admin.user.tab.preferences"),
      content: (function(_this) {
        return function() {
          return _this.renderPreferencesForm();
        };
      })(this)
    });
  };

  UserPreferencesPlugin.prototype.renderPreferencesForm = function() {
    var currentPrefs, form, formData, ref;
    currentPrefs = ((ref = this._user.data.user.frontend_prefs) != null ? ref.webfrontend : void 0) || {};
    formData = {
      use_fullscreen: currentPrefs.use_fullscreen || false,
      avoid_insert_today: currentPrefs.avoid_insert_today || false
    };
    form = new CUI.Form({
      data: formData,
      "class": "ez5-user-preferences-form cui-form--has-checkbox-labels",
      fields: [
        {
          type: CUI.Checkbox,
          name: "use_fullscreen",
          text: $$("admin.user.preferences.use_fullscreen.label"),
          form: {
            hint: $$("admin.user.preferences.use_fullscreen.hint")
          }
        }, {
          type: CUI.Checkbox,
          name: "avoid_insert_today",
          value: false,
          value_unchecked: true,
          text: $$("admin.user.preferences.avoid_insert_today.label"),
          form: {
            hint: $$("admin.user.preferences.avoid_insert_today.hint")
          }
        }
      ],
      onDataChanged: (function(_this) {
        return function() {
          return _this._updatePreferences(formData);
        };
      })(this)
    });
    return form.start();
  };

  UserPreferencesPlugin.renderPreferencesFormForUser = function(userData, onDataChanged) {
    var currentPrefs, form, formData, ref;
    currentPrefs = ((ref = userData.user.frontend_prefs) != null ? ref.webfrontend : void 0) || {};
    formData = {
      use_fullscreen: currentPrefs.use_fullscreen || false,
      avoid_insert_today: currentPrefs.avoid_insert_today || false
    };
    form = new CUI.Form({
      data: formData,
      "class": "ez5-user-preferences-form cui-form--has-checkbox-labels",
      fields: [
        {
          type: CUI.Checkbox,
          name: "use_fullscreen",
          text: $$("admin.user.preferences.use_fullscreen.label"),
          form: {
            hint: $$("admin.user.preferences.use_fullscreen.hint")
          }
        }, {
          type: CUI.Checkbox,
          name: "avoid_insert_today",
          text: $$("admin.user.preferences.avoid_insert_today.label"),
          value: false,
          value_unchecked: true,
          form: {
            hint: $$("admin.user.preferences.avoid_insert_today.hint")
          }
        }
      ],
      onDataChanged: (function(_this) {
        return function() {
          if (!userData.user.frontend_prefs) {
            userData.user.frontend_prefs = {};
          }
          if (!userData.user.frontend_prefs.webfrontend) {
            userData.user.frontend_prefs.webfrontend = {};
          }
          userData.user.frontend_prefs.webfrontend.use_fullscreen = formData.use_fullscreen;
          userData.user.frontend_prefs.webfrontend.avoid_insert_today = formData.avoid_insert_today;
          return typeof onDataChanged === "function" ? onDataChanged(formData) : void 0;
        };
      })(this)
    });
    return form.start();
  };

  UserPreferencesPlugin.renderEmailScheduleFormForUser = function(userData, onDataChanged) {
    var form;
    if (!userData.user.mail_schedule) {
      userData.user.mail_schedule = {};
    }
    if (!userData.user.mail_schedule.timezone) {
      userData.user.mail_schedule.timezone = CUI.Timezone.getTimezone();
    }
    form = new CUI.Form({
      data: userData.user,
      fields: [
        {
          type: CUI.Form,
          name: "mail_schedule",
          form: {
            label: $$("admin.user.schedule")
          },
          fields: ScheduleEditor.getFields({
            show_minutes: ez5.session.isDebug()
          })
        }
      ],
      onDataChanged: (function(_this) {
        return function() {
          return typeof onDataChanged === "function" ? onDataChanged(userData.user.mail_schedule) : void 0;
        };
      })(this)
    });
    return form.start();
  };

  UserPreferencesPlugin.prototype._updatePreferences = function(formData) {
    if (!this._user.data.user.frontend_prefs) {
      this._user.data.user.frontend_prefs = {};
    }
    if (!this._user.data.user.frontend_prefs.webfrontend) {
      this._user.data.user.frontend_prefs.webfrontend = {};
    }
    this._user.data.user.frontend_prefs.webfrontend.use_fullscreen = formData.use_fullscreen;
    this._user.data.user.frontend_prefs.webfrontend.avoid_insert_today = formData.avoid_insert_today;
  };

  UserPreferencesPlugin.prototype.getSaveData = function(saveData) {
    var ref, ref1, ref2, ref3;
    if (!saveData.user.frontend_prefs) {
      saveData.user.frontend_prefs = {};
    }
    if (!saveData.user.frontend_prefs.webfrontend) {
      saveData.user.frontend_prefs.webfrontend = {};
    }
    if (((ref = this._user.data.user.frontend_prefs) != null ? (ref1 = ref.webfrontend) != null ? ref1.use_fullscreen : void 0 : void 0) != null) {
      saveData.user.frontend_prefs.webfrontend.use_fullscreen = this._user.data.user.frontend_prefs.webfrontend.use_fullscreen;
    }
    if (((ref2 = this._user.data.user.frontend_prefs) != null ? (ref3 = ref2.webfrontend) != null ? ref3.avoid_insert_today : void 0 : void 0) != null) {
      saveData.user.frontend_prefs.webfrontend.avoid_insert_today = this._user.data.user.frontend_prefs.webfrontend.avoid_insert_today;
    }
  };

  UserPreferencesPlugin.prototype.isAllowed = function() {
    var ref;
    if (!ez5.version("6")) {
      return false;
    }
    return (ref = this._user.data.user.type) === "easydb" || ref === "system";
  };

  return UserPreferencesPlugin;

})(ez5.UserPlugin);

User.plugins.registerPlugin(ez5.UserPreferencesPlugin);
// Generated by CoffeeScript 1.12.7
var App,
  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;

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

  function App(opts) {
    this.opts = opts != null ? opts : {};
    CUI.util.assert(CUI.util.getObjectClass(this) !== "App", "new App()", "Cannot call directly, only from subclasses");
    App.__super__.constructor.call(this, this.opts);
    this.loaded = false;
    this.__initialized = false;
  }

  App.prototype.register = function(appManager, idxInAppManager) {
    this.appManager = appManager;
    this.idxInAppManager = idxInAppManager;
    return this;
  };

  App.prototype.getIdxInAppManager = function() {
    return this.idxInAppManager;
  };

  App.prototype.is_allowed = function() {
    return true;
  };

  App.is_allowed = function() {
    return true;
  };

  App.prototype.isLoaded = function() {
    return this.__loaded;
  };

  App.prototype.update_path = function(path) {
    return CUI.resolvedPromise();
  };

  App.prototype.load = function(path) {
    this.__loaded = true;
    return CUI.resolvedPromise();
  };

  App.prototype.allow_unload = function() {
    return CUI.resolvedPromise();
  };

  App.prototype.unload = function() {
    this.__loaded = false;
    return CUI.resolvedPromise();
  };

  App.prototype.reload = function() {
    return CUI.resolvedPromise();
  };

  return App;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var AppManager,
  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;

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

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

  AppManager.prototype.readOpts = function() {
    AppManager.__super__.readOpts.call(this);
    this.__apps = [];
    return this.__allowed_apps = null;
  };

  AppManager.prototype.loadApps = function() {
    return this.loadAvailableApps();
  };

  AppManager.prototype.loadAvailableApps = function() {
    var allowed, app, dfr, fn, i, idx, len, promises, ref;
    dfr = new CUI.Deferred();
    idx = -1;
    allowed = {};
    promises = [];
    ref = this.__apps;
    fn = (function(_this) {
      return function(idx) {
        var decision;
        decision = _this.__apps[idx].is_allowed();
        if (CUI.util.isPromise(decision)) {
          promises.push(decision);
          return decision.done(function() {
            return allowed[idx] = idx;
          });
        } else if (decision) {
          return allowed[idx] = true;
        }
      };
    })(this);
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      app = ref[idx];
      fn(idx);
    }
    CUI.when(promises).always((function(_this) {
      return function() {
        var j, len1, ref1;
        _this.__allowed_apps = [];
        ref1 = _this.__apps;
        for (idx = j = 0, len1 = ref1.length; j < len1; idx = ++j) {
          app = ref1[idx];
          if (allowed[idx]) {
            _this.__allowed_apps.push(_this.__apps[idx]);
          }
        }
        return dfr.resolve();
      };
    })(this));
    return dfr.promise();
  };

  AppManager.prototype.getAllowedApps = function() {
    CUI.util.assert(this.hasAllowedApps(), "AppManager.getAllowedApps", "init wasnt be called.");
    return this.__allowed_apps.slice(0);
  };

  AppManager.prototype.hasAllowedApps = function() {
    return this.__allowed_apps !== null;
  };

  AppManager.prototype.getApps = function() {
    return this.__apps;
  };

  AppManager.prototype.checkApp = function(app) {
    return CUI.util.assert(app instanceof App, (CUI.util.getObjectClass(this)) + ".registerApp", "app needs to be instance of App", {
      app: app
    });
  };

  AppManager.prototype.registerApp = function(app) {
    this.checkApp(app);
    this.__apps.push(app);
    if (app instanceof App) {
      app.register(this, this.__apps.length - 1);
    }
    return app;
  };

  return AppManager;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var Tray,
  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;

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

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

  Tray.prototype.readOpts = function() {
    Tray.__super__.readOpts.call(this);
    return this.trayDiv = CUI.dom.div("tray");
  };

  Tray.prototype.checkApp = function(app) {
    return CUI.util.assert(app instanceof TrayApp, (CUI.util.getObjectClass(this)) + ".registerApp", "app needs to be instance of TrayApp", {
      app: app
    });
  };

  Tray.prototype.reloadApps = function() {
    return this.loadApps();
  };

  Tray.prototype.loadApps = function() {
    var apps, sort_value;
    apps = null;
    CUI.dom.empty(this.trayDiv);
    sort_value = (function(_this) {
      return function(app) {
        var sort;
        sort = app.getSortValue();
        if (CUI.util.isNull(sort)) {
          sort = 0;
        } else {
          CUI.util.assert(CUI.util.isInteger(sort), "Tray.init", ".getSortValue needs to return an integer", {
            app: app
          });
        }
        return sort += apps.length - app.getIdxInAppManager() - 1;
      };
    })(this);
    return this.loadAvailableApps().done((function(_this) {
      return function() {
        var app, i;
        apps = _this.getAllowedApps();
        apps.sort(function(a, b) {
          return CUI.util.compareIndex(sort_value(a), sort_value(b));
        });
        for (i = apps.length - 1; i >= 0; i += -1) {
          app = apps[i];
          CUI.dom.prepend(_this.trayDiv, app.getDisplay());
        }
        _this.findAppByLocation(document.location, apps).done(function(start_app) {
          return start_app.app.load(start_app.path);
        });
      };
    })(this));
  };

  Tray.prototype.getDisplay = function() {
    return this.trayDiv;
  };

  Tray.prototype.findAppByLocation = function(location, apps) {
    var app, app_path, dfr, i, idx, len, newUrl, pathname;
    dfr = new CUI.Deferred();
    pathname = location.pathname;
    if (CUI.util.isEmpty(pathname)) {
      return dfr.reject();
    }
    for (idx = i = 0, len = apps.length; i < len; idx = ++i) {
      app = apps[idx];
      app_path = typeof app.getPathName === "function" ? app.getPathName() : void 0;
      if (CUI.util.isEmpty(app_path)) {
        continue;
      }
      if (pathname.startsWith(app_path)) {
        newUrl = window.location.origin + "/" + window.location.search + window.location.hash;
        history.replaceState(null, "", newUrl);
        return dfr.resolve({
          app: app,
          path: pathname
        });
      }
    }
    return dfr.reject();
  };

  return Tray;

})(AppManager);
// Generated by CoffeeScript 1.12.7
var TrayApp,
  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;

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

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

  TrayApp.prototype.getDisplay = function() {
    return this.display = CUI.dom.div("tray-item");
  };

  TrayApp.prototype.getSortValue = function() {};

  return TrayApp;

})(App);
// Generated by CoffeeScript 1.12.7
var RootMenu,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  RootMenu.prototype.readOpts = function() {
    RootMenu.__super__.readOpts.call(this);
    CUI.Events.listen({
      type: "keyup",
      node: document,
      call: (function(_this) {
        return function(ev) {
          if (ev.keyCode() !== 27 || !_this.isMenuOpen()) {
            return;
          }
          ev.stopPropagation();
          ev.preventDefault();
          _this.closeMenu();
          return false;
        };
      })(this)
    });
    CUI.Events.listen({
      type: "popstate",
      node: window,
      call: (function(_this) {
        return function(ev) {
          _this.findAppByLocation(document.location).done(function(app) {
            var ref;
            if (((ref = _this.__activeApp) != null ? ref.__app_function : void 0) === app) {
              _this.__activeApp.update_path(_this.getLocationPath());
              return;
            }
            return _this.loadApp(app).fail(function(active_app) {
              return active_app != null ? active_app.pushState() : void 0;
            });
          });
        };
      })(this)
    });
    this.menuBtn = new LocaButton({
      icon: "menu",
      loca_key: "root.menu.button.open_close_menu",
      "class": "ez5-main-menu-button",
      onClick: (function(_this) {
        return function() {
          _this.toggleMenu();
          if (_this.root_menu_button) {
            return _this.root_menu_button.setActive(true);
          }
        };
      })(this)
    });
    this.__title = CUI.dom.div("ez5-title");
    return this.adjust_title_color();
  };

  RootMenu.prototype.adjust_title_color = function() {
    var b, c, char, g, header_background, luma, r, rgb;
    header_background = getComputedStyle(document.documentElement).getPropertyValue('--top-header-background');
    c = header_background.trim().substring(1);
    if (c.length === 3) {
      char = c.split('');
      c = char[0] + char[0] + char[1] + char[1] + char[2] + char[2];
    }
    rgb = parseInt(c, 16);
    r = (rgb >> 16) & 0xff;
    g = (rgb >> 8) & 0xff;
    b = (rgb >> 0) & 0xff;
    luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
    return CUI.dom.setClass(this.__title, "ez5-title--on-dark", luma < 100);
  };

  RootMenu.prototype.findAppByLocation = function(location) {
    var apps, dfr, get_apps, idx, load_app, try_next;
    dfr = new CUI.Deferred();
    get_apps = (function(_this) {
      return function() {
        var apps;
        apps = _this.getAllowedApps();
        return apps.sort(function(a, b) {
          return CUI.util.compareIndex((typeof b.getPathname === "function" ? b.getPathname().length : void 0) || 0, (typeof a.getPathname === "function" ? a.getPathname().length : void 0) || 0);
        });
      };
    })(this);
    load_app = (function(_this) {
      return function() {
        var app, app_path, i, idx, len, pathname, ref;
        pathname = location.pathname;
        if (pathname.startsWith(window.easydb_base_prefix)) {
          pathname = pathname.slice(window.easydb_base_prefix.length);
        }
        ref = get_apps();
        for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
          app = ref[idx];
          app_path = typeof app.getPathname === "function" ? app.getPathname() : void 0;
          if (CUI.util.isEmpty(app_path)) {
            continue;
          }
          if (app_path === pathname.substring(0, app_path.length)) {
            dfr.resolve(app);
            return;
          }
        }
        dfr.reject();
      };
    })(this);
    apps = get_apps();
    idx = -1;
    try_next = (function(_this) {
      return function() {
        idx = idx + 1;
        if (idx === _this.__appLoader.length) {
          load_app();
          return;
        }
        _this.__appLoader[idx].findAppByLocation(location, apps).done(function(app) {
          return dfr.resolve(app);
        }).fail(function() {
          return try_next();
        });
      };
    })(this);
    try_next();
    return dfr.promise();
  };

  RootMenu.prototype.findFirstStartApp = function() {
    var app, i, len, ref;
    ref = this.getAllowedApps();
    for (i = 0, len = ref.length; i < len; i++) {
      app = ref[i];
      if (app.isStartApp()) {
        return app;
      }
    }
    return null;
  };

  RootMenu.prototype.checkApp = function(app) {
    return CUI.util.assert(app instanceof Function, (CUI.util.getObjectClass(this)) + ".registerApp", "app needs to be Function", {
      app: app
    });
  };

  RootMenu.prototype.getAppInstance = function(_app) {
    var app;
    app = new _app();
    app.__app_function = _app;
    app.register(this, CUI.util.idxInArray(app, this.getApps()));
    CUI.util.assert(app instanceof RootMenuApp, "RootMenu.getAppInstance", "Function for App did not return instanceof RootMenuApp.", {
      app: app
    });
    return app;
  };

  RootMenu.prototype.getActiveApp = function() {
    return this.__activeApp;
  };

  RootMenu.prototype.loadAppFromPath = function() {
    var dfr, load_app;
    dfr = new CUI.Deferred();
    load_app = (function(_this) {
      return function(start_app) {
        return _this.loadApp(start_app).done(dfr.resolve).fail(dfr.reject);
      };
    })(this);
    this.findAppByLocation(document.location).fail((function(_this) {
      return function() {
        var start_app;
        start_app = _this.findFirstStartApp();
        if (start_app) {
          return load_app(start_app);
        } else {
          return dfr.reject();
        }
      };
    })(this)).done((function(_this) {
      return function(start_app) {
        return load_app(start_app);
      };
    })(this));
    return dfr.promise();
  };

  RootMenu.prototype.getLocationPath = function() {
    var i, idx, len, part, path, ref;
    path = [];
    ref = document.location.pathname.split("/");
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      part = ref[idx];
      if (idx === 0) {
        continue;
      }
      if (part.length === 0) {
        continue;
      }
      path.push(part);
    }
    return path;
  };

  RootMenu.prototype.loadApp = function(app, pushState) {
    var appInst, dfr, load, path, promise;
    if (pushState == null) {
      pushState = false;
    }
    CUI.util.assert(app instanceof Function, "RootMenu.loadApp", "Can only load dynamic App, app needs to be instanceof Function.");
    if (this.__load_dfr) {
      console.warn("already loading an app... ignoring click");
      return CUI.rejectedPromise();
    }
    path = this.getLocationPath();
    dfr = this.__load_dfr = new CUI.Deferred();
    appInst = null;
    dfr.done((function(_this) {
      return function() {
        var documentTitle;
        _this.__activeApp = appInst;
        documentTitle = appInst.documentTitle();
        ez5.session.setDocumentTitle(documentTitle);
      };
    })(this));
    dfr.always((function(_this) {
      return function() {
        _this.__load_dfr = null;
      };
    })(this));
    load = (function(_this) {
      return function() {
        var promise;
        appInst = _this.getAppInstance(app);
        if (pushState) {
          appInst.pushState();
        }
        promise = appInst.load(path);
        CUI.util.assert(CUI.util.isPromise(promise), "RootMenu.loadApp", appInst.__cls + ".load() needs to return CUI.Promise.", {
          promise: promise
        });
        return promise.done(function() {
          return dfr.resolve(app, appInst);
        }).fail(function() {
          return dfr.reject();
        });
      };
    })(this);
    if (this.__activeApp) {
      promise = this.__activeApp.allow_unload();
      CUI.util.assert(CUI.util.isPromise(promise), "RootMenu.loadApp", this.__activeApp.__cls + ".allow_unload() needs to return CUI.Promise.", {
        promise: promise
      });
      promise.done((function(_this) {
        return function() {
          return _this.__unloadActiveApp().always(function() {
            return load();
          });
        };
      })(this)).fail((function(_this) {
        return function() {
          _this.closeMenu();
          return dfr.reject(_this.__activeApp);
        };
      })(this));
    } else {
      load();
    }
    return dfr.promise();
  };

  RootMenu.prototype.loadApps = function() {
    var dfr, load;
    if (this.__loadingApps) {
      return this.loadAvailableApps();
    }
    this.__loadingApps = true;
    dfr = new CUI.Deferred();
    dfr.always((function(_this) {
      return function() {
        return _this.__loadingApps = false;
      };
    })(this));
    dfr.fail((function(_this) {
      return function() {
        var hint;
        hint = new CUI.EmptyLabel({
          text: $$("root.menu.no_app_allowed"),
          centered: true,
          multiline: true
        });
        return ez5.rootLayout.replace(hint, "center");
      };
    })(this));
    load = (function(_this) {
      return function() {
        return _this.loadAvailableApps().done(function() {
          console.timeLog("Start", "load app from path");
          return _this.loadAppFromPath().always(function() {
            return console.timeLog("Start", "load app from path done");
          }).done(dfr.resolve).fail(dfr.reject);
        }).fail(function() {
          return dfr.reject();
        });
      };
    })(this);
    if (this.__activeApp) {
      this.__unloadActiveApp().always((function(_this) {
        return function() {
          _this.__activeApp = null;
          return load();
        };
      })(this));
    } else {
      load();
    }
    return dfr.promise();
  };

  RootMenu.prototype.unloadActiveApp = function() {
    if (!this.__activeApp) {
      return CUI.resolvedPromise();
    }
    return this.__unloadActiveApp();
  };

  RootMenu.prototype.__unloadActiveApp = function() {
    var promise;
    promise = this.__activeApp.unload();
    CUI.util.assert(CUI.util.isPromise(promise), "RootMenu.loadApp", this.__activeApp.__cls + ".unload() needs to return CUI.Promise.", {
      promise: promise
    });
    return promise.always((function(_this) {
      return function() {
        return _this.__activeApp = null;
      };
    })(this));
  };

  RootMenu.prototype.loadAvailableApps = function() {
    console.timeLog("Start", "loading available apps");
    return RootMenu.__super__.loadAvailableApps.call(this).done((function(_this) {
      return function() {
        var app, apps, apps_per_group, bottom_apps, fn, fylrHomepageURL, fylrLink, get_bottom_app_items, get_itemList_bottom, get_itemList_top, get_items, group, groups, i, icon, itemList, j, k, len, len1, len2, pref, ref, regular_apps, root_items, submenu, submenus;
        console.timeLog("Start", "loading available apps - super done");
        apps = _this.getAllowedApps();
        _this.__submenu_buttons = [];
        _this.__app_button_by_unique_id = {};
        regular_apps = [];
        bottom_apps = [];
        for (i = 0, len = apps.length; i < len; i++) {
          app = apps[i];
          if ((typeof app.isBottomApp === "function" ? app.isBottomApp() : void 0) && app.isBottomApp()) {
            bottom_apps.push(app);
          } else {
            regular_apps.push(app);
          }
        }
        submenus = [];
        groups = {};
        apps_per_group = {};
        for (j = 0, len1 = regular_apps.length; j < len1; j++) {
          app = regular_apps[j];
          CUI.util.assert(app.group instanceof Function, "App needs 'group' method.", {
            app: app
          });
          submenu = app.submenu();
          group = submenu + "." + app.group();
          if (!groups[submenu]) {
            groups[submenu] = [];
            submenus.push(submenu);
          }
          if (indexOf.call(groups[submenu], group) < 0) {
            groups[submenu].push(group);
            apps_per_group[group] = [];
          }
          apps_per_group[group].push(app);
        }
        get_items = function(submenu, for_menu) {
          var _groups, cls, fn, items, k, l, len2, len3, ref;
          if (for_menu == null) {
            for_menu = false;
          }
          if (submenu === "root") {
            cls = "ez5-root-menu-button";
          } else {
            cls = "ez5-root-menu-submenu-button";
          }
          items = [];
          if (!groups[submenu]) {
            return items;
          }
          _groups = groups[submenu].slice(0);
          _groups.sort(function(a, b) {
            var group_a, group_b;
            group_a = a.split('.')[1];
            group_b = b.split('.')[1];
            return CUI.util.compareIndex(group_a, group_b);
          });
          for (k = 0, len2 = _groups.length; k < len2; k++) {
            group = _groups[k];
            ref = apps_per_group[group];
            fn = function(app) {
              var button, hasNoIcon, item, ownOnConstruct, ref1;
              item = app.getDisplay();
              if (!for_menu) {
                ownOnConstruct = item.onConstruct;
                item.onConstruct = function(btn) {
                  _this.__app_button_by_unique_id[app.label()] = btn;
                  return typeof ownOnConstruct === "function" ? ownOnConstruct(btn) : void 0;
                };
              }
              if (!item["class"]) {
                item["class"] = "";
              }
              item["class"] += " " + cls;
              item.__app = app;
              item.ui = "root.menu.item:" + (app.label());
              if (item._no_radio === true) {
                return items.push(new LocaButton(item));
              } else {
                button = new LocaButton(item);
                hasNoIcon = (ref1 = CUI.dom.matchSelector(button.DOM, ".cui-no-icon")) != null ? ref1[0] : void 0;
                if (hasNoIcon && app.label()) {
                  hasNoIcon.textContent = app.label().substring(0, 2).toUpperCase();
                }
                return items.push(button);
              }
            };
            for (l = 0, len3 = ref.length; l < len3; l++) {
              app = ref[l];
              CUI.util.assert(app.getDisplay instanceof Function, "App needs 'getDisplay' method.", {
                app: app
              });
              CUI.util.assert(app.label instanceof Function, "App needs 'label' method.", {
                app: app
              });
              fn(app);
            }
          }
          return items;
        };
        root_items = get_items("root");
        submenus.sort(function(a, b) {
          var group_a, group_b;
          if (a === "root") {
            return -1;
          }
          group_a = groups[a][0].split(".")[1];
          group_b = groups[b][0].split(".")[1];
          return CUI.util.compareIndex(group_a, group_b);
        });
        fn = function(submenu) {
          var hasNoIcon, hide_timeout, il, rb, ref, submenuIcon, submenuLocaKey, submenuText, submenuTooltip;
          hide_timeout = null;
          il = new CUI.ItemList({
            "class": "ez5-root-menu-submenu",
            items: get_items(submenu),
            maximize: false
          });
          il.render();
          app = apps_per_group[groups[submenu][0]][0];
          submenuLocaKey = app.getSubmenuKey();
          if (!submenuLocaKey) {
            submenuIcon = app.getSubmenuIcon();
            submenuText = app.getSubmenuText();
            submenuTooltip = app.getSubmenuTooltip();
          }
          rb = new LocaButton({
            loca_key: submenuLocaKey,
            icon: submenuIcon,
            text: submenuText,
            tooltip: {
              text: submenuTooltip
            },
            ui: "root.menu.button:" + submenu,
            "class": "ez5-root-menu-button ez5-root-menu-button--has-submenu",
            right: [
              new CUI.Icon({
                icon: "north",
                "class": "ez-root-menu--close"
              }), new CUI.Icon({
                icon: "south",
                "class": "ez-root-menu--open"
              })
            ],
            menu: {
              placement: "es",
              placements: ["es", "en"],
              pointer: "arrow",
              active_item_idx: null,
              items: function(ev, itemList) {
                var item, items, l, len3, len4, m;
                if (document.body.classList.contains("ez5-root-menu--wide")) {
                  CUI.dom.toggleClass(il.DOM, "ez5-root-menu--submenu-hide");
                  CUI.dom.toggleClass(rb.DOM, "ez5-root-menu--submenu-hide");
                  return;
                }
                items = get_items(submenu, true);
                apps = _this.getActiveApps();
                for (l = 0, len3 = items.length; l < len3; l++) {
                  item = items[l];
                  item.active = false;
                  for (m = 0, len4 = apps.length; m < len4; m++) {
                    app = apps[m];
                    if (app === item.__app) {
                      item.active = true;
                      break;
                    }
                  }
                }
                return items;
              }
            }
          });
          hasNoIcon = (ref = CUI.dom.matchSelector(rb.DOM, ".cui-no-icon")) != null ? ref[0] : void 0;
          if (hasNoIcon && submenuText) {
            hasNoIcon.textContent = submenuText.substring(0, 2).toUpperCase();
          }
          root_items.push(rb);
          rb.__submenu = submenu;
          _this.__submenu_buttons.push(rb);
          return root_items.push({
            content: il.DOM
          });
        };
        for (k = 0, len2 = submenus.length; k < len2; k++) {
          submenu = submenus[k];
          if (submenu === "root") {
            continue;
          }
          fn(submenu);
        }
        icon = new CUI.Icon({
          icon: 'svg-easydb'
        });
        if (((ref = ez5.cssLoader.getActiveCSS()) != null ? ref.theme : void 0) === 'fylr') {
          icon = new CUI.Icon({
            icon: 'svg-fylr-logo'
          });
        }
        fylrHomepageURL = window.fylr_homepage || "";
        fylrLink = CUI.dom.element("A", {
          "class": "ez5-branding ez5-busy-state",
          href: fylrHomepageURL,
          target: "_blank"
        });
        fylrLink.appendChild(icon.DOM);
        pref = ez5.session.getPref("root_menu_open");
        _this.root_menu_button = new LocaButton({
          loca_key: "root.menu.burger",
          "class": "ez5-root-menu-burger-button ez5-root-menu-button",
          active: pref,
          "switch": true,
          onActivate: function() {
            document.body.classList.add("ez5-root-menu--wide");
            ez5.session.savePref("root_menu_open", true);
            return CUI.Events.trigger({
              type: "viewport-resize"
            });
          },
          onDeactivate: function() {
            document.body.classList.remove("ez5-root-menu--wide");
            ez5.session.savePref("root_menu_open", false);
            return CUI.Events.trigger({
              type: "viewport-resize"
            });
          }
        });
        get_itemList_top = function() {
          var ref1, top;
          top = false;
          if (((ref1 = ez5.cssLoader.getActiveCSS()) != null ? ref1.theme : void 0) === 'ng') {
            top = {
              content: _this.root_menu_button
            };
          }
          return top;
        };
        get_bottom_app_items = function() {
          var bottom_items, fn1, l, len3;
          bottom_items = [];
          fn1 = function(app) {
            var button, hasNoIcon, item, ownOnConstruct, ref1;
            item = app.getDisplay();
            ownOnConstruct = item.onConstruct;
            item.onConstruct = function(btn) {
              _this.__app_button_by_unique_id[app.label()] = btn;
              return typeof ownOnConstruct === "function" ? ownOnConstruct(btn) : void 0;
            };
            if (!item["class"]) {
              item["class"] = "";
            }
            item["class"] += " ez5-root-menu-button ez5-root-menu-button--bottom";
            item.__app = app;
            item.ui = "root.menu.item:" + (app.label());
            button = new LocaButton(item);
            hasNoIcon = (ref1 = CUI.dom.matchSelector(button.DOM, ".cui-no-icon")) != null ? ref1[0] : void 0;
            if (hasNoIcon && app.label()) {
              hasNoIcon.textContent = app.label().substring(0, 2).toUpperCase();
            }
            return bottom_items.push(button);
          };
          for (l = 0, len3 = bottom_apps.length; l < len3; l++) {
            app = bottom_apps[l];
            CUI.util.assert(app.getDisplay instanceof Function, "App needs 'getDisplay' method.", {
              app: app
            });
            CUI.util.assert(app.label instanceof Function, "App needs 'label' method.", {
              app: app
            });
            fn1(app);
          }
          return bottom_items;
        };
        get_itemList_bottom = function() {
          var bottom, bottom_app_items, bottom_content, ref1;
          bottom_content = [];
          bottom_app_items = get_bottom_app_items();
          if (bottom_app_items.length > 0) {
            bottom_content = bottom_content.concat(bottom_app_items);
          }
          if (((ref1 = ez5.cssLoader.getActiveCSS()) != null ? ref1.theme : void 0) === 'fylr') {
            bottom_content.push(_this.root_menu_button);
            bottom = {
              content: bottom_content
            };
          }
          bottom_content.push(fylrLink);
          bottom = {
            content: bottom_content
          };
          return bottom;
        };
        itemList = new CUI.ItemList({
          auto_buttonbar: false,
          top: get_itemList_top(),
          bottom: get_itemList_bottom(),
          "class": "ez5-root-menu-item-list",
          items: root_items
        });
        itemList.render();
        CUI.Events.listen({
          type: "click",
          node: itemList,
          call: function() {
            return _this.closeMenu();
          }
        });
        if (!_this.__menuPane) {
          _this.__menuPane = CUI.dom.div("ez5-root-menu");
          CUI.dom.prepend(document.body, _this.__menuPane);
        } else {
          CUI.dom.empty(_this.__menuPane);
        }
        CUI.dom.append(_this.__menuPane, itemList.DOM);
        console.timeLog("Start", "loaded available apps");
        return _this.__menuPane;
      };
    })(this));
  };

  RootMenu.prototype.getDisplay = function() {
    return [this.menuBtn.DOM, this.__title];
  };

  RootMenu.prototype.setTitle = function(locaKey, locaOpts) {
    if (locaOpts == null) {
      locaOpts = {};
    }
    CUI.dom.empty(this.__title);
    if (locaKey) {
      if (ez5.loca.has(locaKey + "|icon")) {
        CUI.dom.append(this.__title, new CUI.Label({
          icon: $$(locaKey + "|icon"),
          text: $$(locaKey, locaOpts)
        }).DOM);
      } else {
        CUI.dom.append(this.__title, new CUI.Label({
          text: $$(locaKey, locaOpts)
        }).DOM);
      }
    }
    return this;
  };

  RootMenu.prototype.getTitle = function() {
    return this.__title;
  };

  RootMenu.prototype.closeMenu = function() {
    return document.body.classList.remove("root-menu");
  };

  RootMenu.prototype.openMenu = function() {
    return document.body.classList.add("root-menu");
  };

  RootMenu.prototype.isMenuOpen = function() {
    if (document.body.classList.contains("root-menu")) {
      return true;
    } else {
      return false;
    }
  };

  RootMenu.prototype.toggleMenu = function() {
    if (this.isMenuOpen()) {
      return this.closeMenu();
    } else {
      return this.openMenu();
    }
  };

  RootMenu.prototype.getActiveApps = function() {
    var app, apps, i, len, ref;
    apps = [];
    if (!this.hasAllowedApps()) {
      return apps;
    }
    ref = this.getAllowedApps();
    for (i = 0, len = ref.length; i < len; i++) {
      app = ref[i];
      if (this.getAppButton(app).isActive()) {
        apps.push(app);
      }
    }
    return apps;
  };

  RootMenu.prototype.__findSubmenuButton = function(submenu) {
    var i, len, ref, sb;
    ref = this.__submenu_buttons;
    for (i = 0, len = ref.length; i < len; i++) {
      sb = ref[i];
      if (sb.__submenu === submenu) {
        return sb;
      }
    }
  };

  RootMenu.prototype.getAppButton = function(app) {
    var appBtn;
    appBtn = this.__app_button_by_unique_id[app.label()];
    if (!appBtn) {
      console.warn("getAppButton", app.label(), "not found", this.__app_button_by_unique_id);
    }
    return appBtn;
  };

  RootMenu.prototype.setActiveApp = function(app) {
    var sb;
    if (!app) {
      return this;
    }
    this.getAppButton(app).activate();
    sb = this.__findSubmenuButton(app.submenu());
    if (sb) {
      sb.activate();
    }
    return this;
  };

  RootMenu.prototype.unsetActiveApp = function(app) {
    var sb;
    if (!app) {
      return this;
    }
    this.getAppButton(app).deactivate();
    sb = this.__findSubmenuButton(app.submenu());
    if (sb) {
      sb.deactivate();
    }
    return this;
  };

  RootMenu.prototype.__appLoader = [];

  RootMenu.prototype.registerAppLoader = function(loader) {
    CUI.util.assert(loader instanceof RootMenuAppLoader, "RootMenu.registerAppLoader", "loader needs to be instance of RootMenuAppLoader.", loader);
    return this.__appLoader.push(loader);
  };

  return RootMenu;

})(AppManager);
// Generated by CoffeeScript 1.12.7
var RootMenuApp,
  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;

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

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

  RootMenuApp.prototype.label = function() {
    return window[this.getObjectClass()].label.call(this);
  };

  RootMenuApp.prototype.submenu = function() {
    return window[this.getObjectClass()].submenu.call(this);
  };

  RootMenuApp.prototype.documentTitle = function() {
    return window[this.getObjectClass()].documentTitle.call(this);
  };

  RootMenuApp.prototype.getMenuButton = function() {
    return window[this.getObjectClass()].getMenuButton.call(this);
  };

  RootMenuApp.getDisplay = function() {
    return this.getMenuButton();
  };

  RootMenuApp.getMenuButton = function() {
    var label, labelReplace, loca_key, text;
    label = this.label();
    if (this.submenu() === "root") {
      loca_key = "root.menu." + label;
      text = void 0;
    } else {
      loca_key = void 0;
      text = $$(label);
    }
    labelReplace = label.replace(/\./g, "-");
    return {
      text: text,
      loca_key: loca_key,
      "class": "ez5-root-menu-button-" + labelReplace,
      ui: loca_key,
      onClick: (function(_this) {
        return function(ev, btn) {
          btn.setActive(false);
          _this.click(ev, btn);
        };
      })(this)
    };
  };

  RootMenuApp.getId = function() {
    return this.label();
  };

  RootMenuApp.isBottomApp = function() {
    return false;
  };

  RootMenuApp.path = function() {};

  RootMenuApp.click = function(ev, btn) {
    return ez5.rootMenu.loadApp(this, true).fail((function(_this) {
      return function() {
        var activeApp;
        activeApp = ez5.rootMenu.getActiveApp();
        if (activeApp) {
          return ez5.rootMenu.getAppButton(activeApp).setActive(true);
        }
      };
    })(this));
  };

  RootMenuApp.getPathname = function() {
    var path;
    path = this.path();
    if (!path) {
      return "";
    }
    return "/" + path.join("/");
  };

  RootMenuApp.group = function() {
    return "main";
  };

  RootMenuApp.submenu = function() {
    return "root";
  };

  RootMenuApp.label = function() {
    return CUI.util.assert(false, (this.getObjectClass()) + ".label", "needs to be overloaded");
  };

  RootMenuApp.documentTitle = function() {
    return $$(this.label());
  };

  RootMenuApp.isStartApp = function() {
    return true;
  };

  RootMenuApp.prototype.pushState = function(path) {
    if (path == null) {
      path = [];
    }
    return this.__setState(path, "pushState");
  };

  RootMenuApp.prototype.replaceState = function(path) {
    if (path == null) {
      path = [];
    }
    return this.__setState(path, "replaceState");
  };

  RootMenuApp.prototype.__setState = function(path, funcName) {
    var full_path, pathname;
    pathname = window[this.__cls].getPathname();
    if (path.length > 0) {
      full_path = window.easydb_base_prefix + pathname + "/" + path.join("/");
    } else {
      full_path = window.easydb_base_prefix + pathname;
    }
    if (document.location.pathname === full_path) {
      console.warn(this.__cls + "." + funcName + ": Path already active: ", full_path);
      return;
    }
    return window.history[funcName]({}, null, full_path);
  };

  RootMenuApp.prototype.setTitle = function(locaKey, locaOpts) {
    this.appManager.setTitle(locaKey, locaOpts);
    return this;
  };

  RootMenuApp.prototype.setSecondaryTitle = function(label) {
    CUI.dom.append(this.appManager.getTitle(), new CUI.Label({
      size: "normal",
      appearance: "secondary",
      text: label
    }));
    return this;
  };

  RootMenuApp.prototype.getAppCssClassName = function() {
    return "ez5-app-" + CUI.util.toDash(this.__cls);
  };

  RootMenuApp.getSubmenuKey = function() {
    return "root.menu.submenu." + (this.submenu());
  };

  RootMenuApp.getSubmenuText = function() {
    return null;
  };

  RootMenuApp.getSubmenuIcon = function() {
    return null;
  };

  RootMenuApp.getSubmenuTooltip = function() {
    return null;
  };

  RootMenuApp.prototype.destroy = function() {};

  RootMenuApp.prototype.load = function(path) {
    this.setTitle(this.label());
    this.appManager.setActiveApp(this);
    this.appManager.closeMenu();
    document.documentElement.classList.add(this.getAppCssClassName());
    RootMenuApp.__super__.load.call(this);
    CUI.Events.trigger({
      node: document.body,
      type: "viewport-resize"
    });
    return CUI.resolvedPromise();
  };

  RootMenuApp.prototype.unload = function() {
    this.appManager.unsetActiveApp(this);
    this.setTitle();
    document.documentElement.classList.remove(this.getAppCssClassName());
    RootMenuApp.__super__.unload.call(this);
    CUI.Events.trigger({
      node: document.body,
      type: "viewport-resize"
    });
    return CUI.resolvedPromise();
  };

  RootMenuApp.prototype.reload = function() {
    return this.setTitle(this.label());
  };

  RootMenuApp.prototype.getObjectClass = function() {
    return CUI.util.getObjectClass(this);
  };

  return RootMenuApp;

})(App);
// Generated by CoffeeScript 1.12.7
var RootMenuAppLoader,
  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;

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

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

  RootMenuAppLoader.prototype.findAppByPathname = function(apps, pathname) {
    return CUI.util.assert(false, this.__cls + ".findAppByPathname", "Not implemented.");
  };

  return RootMenuAppLoader;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var RootMenuAbout,
  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;

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

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

  RootMenuAbout.is_allowed = function() {
    if (ez5.version("6")) {
      return ez5.session.hasSystemRight("root");
    }
    return true;
  };

  RootMenuAbout.group = function() {
    return "zzz_info";
  };

  RootMenuAbout.submenu = function() {
    return "zzz_info";
  };

  RootMenuAbout.label = function() {
    if (ez5.version("6")) {
      return "root.menu.about.fylr.label";
    } else {
      return "root.menu.about.label";
    }
  };

  RootMenuAbout.isStartApp = function() {
    return false;
  };

  RootMenuAbout.click = function() {
    var addCommitUrlEntry, addFullVersionEntry, addInfoTableEntry, addInfoTableList, add_even_more, add_fallback_info, add_more, info_table;
    info_table = new CUI.Table({
      "class": "ez5-about",
      key_value: true
    });
    addCommitUrlEntry = (function(_this) {
      return function(key_text_key, _value, repo) {
        var url;
        if (repo == null) {
          repo = "fylr";
        }
        url = new CUI.ButtonHref({
          appearance: "link",
          text: _value,
          href: "https://github.com/programmfabrik/" + repo + "/commits/" + _value,
          target: "_blank"
        });
        return addInfoTableEntry(key_text_key, url);
      };
    })(this);
    addFullVersionEntry = (function(_this) {
      return function(key_text_key, _value) {
        var regex, replaced, repoIndex, repositories, value;
        repositories = ['fylr', 'easydb-webfrontend'];
        repoIndex = 0;
        regex = /(^|\W)([0-9a-f]{9})(\W|$)/g;
        replaced = _value.replace(regex, function(match, p1, p2, p3) {
          var repo;
          repo = repositories[repoIndex] || 'fylr';
          repoIndex += 1;
          return p1 + "[" + p2 + "](https://github.com/programmfabrik/" + repo + "/commits/" + p2 + ")" + p3;
        });
        value = new CUI.Label({
          text: replaced,
          multiline: true,
          markdown: true
        });
        return addInfoTableEntry(key_text_key, value);
      };
    })(this);
    addInfoTableEntry = (function(_this) {
      return function(key_text_key, _value) {
        var value;
        if (CUI.isString(_value)) {
          value = new CUI.Label({
            text: _value,
            multiline: true
          });
        } else if (CUI.isPlainObject(_value)) {
          value = new CUI.ObjectDumper({
            object: _value,
            headers: false
          });
        } else {
          value = _value;
        }
        return info_table.addRow({
          key: new LocaLabel({
            loca_key: key_text_key
          }),
          value: value
        });
      };
    })(this);
    addInfoTableList = (function(_this) {
      return function(key_text_key, list) {
        var i, item, len, li, ul;
        if (!(list != null ? list.length : void 0)) {
          return;
        }
        ul = CUI.dom.ul("ez5-root-menu-about-plugins-list");
        for (i = 0, len = list.length; i < len; i++) {
          item = list[i];
          li = CUI.dom.li();
          CUI.dom.append(li, item);
          CUI.dom.append(ul, li);
        }
        addInfoTableEntry(key_text_key, ul);
      };
    })(this);
    add_more = (function(_this) {
      return function() {
        var func, i, len, list, name, opt, opts, plugin, plugin_name, plugin_names, ref, show_problem, text;
        plugin_names = (function() {
          var i, len, ref, results;
          ref = ez5.pluginManager.getPluginNames();
          results = [];
          for (i = 0, len = ref.length; i < len; i++) {
            name = ref[i];
            results.push(name);
          }
          return results;
        })();
        if (plugin_names.length > 0) {
          list = [];
          for (i = 0, len = plugin_names.length; i < len; i++) {
            plugin_name = plugin_names[i];
            plugin = ez5.pluginManager.getPlugin(plugin_name);
            list.push(plugin.getInfo());
          }
          addInfoTableList("root.menu.info.plugins", list);
        } else {
          addInfoTableEntry("root.menu.info.plugins", $$("root.menu.info.plugins.none_installed"));
        }
        opts = [];
        ref = {
          debug: function() {
            return ez5.session.isDebug();
          }
        };
        for (opt in ref) {
          func = ref[opt];
          if (func()) {
            opts.push(opt);
          }
        }
        if (opts.length > 0) {
          text = opts.join(", ");
        } else {
          text = "-";
        }
        addInfoTableEntry("root.menu.info.webfrontend_options", text);
        show_problem = function() {
          return CUI.problem({
            text: $$("root.menu.about.failed_to_load_build_info")
          }).done(add_even_more);
        };
        return new CUI.XHR({
          url: window.easydb_base_prefix + '/web/build_info.json'
        }).start().done(function(build_info, status, statusText) {
          var build, k, v;
          if (!CUI.util.isPlainObject(build_info)) {
            show_problem();
            return;
          }
          build = ez5.format_date_and_time(new Date(build_info.date * 1000)) + "@" + build_info.host;
          addInfoTableEntry("root.menu.info.webfrontend_build", build);
          for (k in build_info) {
            v = build_info[k];
            if ((k === "date" || k === "host") || CUI.util.isEmpty(v)) {
              continue;
            }
            if (k === "ez5") {
              addCommitUrlEntry("root.menu.info.webfrontend_build." + k, v = v.split("/")[0], "easydb-webfrontend");
              continue;
            }
            if (k === "cui") {
              addCommitUrlEntry("root.menu.info.webfrontend_build." + k, v = v.split("/")[0], "coffeescript-ui");
              continue;
            }
            addInfoTableEntry("root.menu.info.webfrontend_build." + k, v.replace("/", "/" + (String.fromCharCode("0x0083"))));
          }
          return add_even_more();
        }).fail(show_problem);
      };
    })(this);
    add_fallback_info = (function(_this) {
      return function() {
        var k, ref, v;
        console.error("Unable to read settings from server, using session instance instead.");
        ref = ez5.session.getInstance();
        for (k in ref) {
          v = ref[k];
          addInfoTableEntry("root.menu.info.instance." + k, v);
        }
        add_more();
      };
    })(this);
    addInfoTableEntry("root.menu.info.frontend_version", ez5.FRONTEND_VERSION);
    ez5.api.settings().done((function(_this) {
      return function(settings) {
        var k, v;
        if (!CUI.util.isPlainObject(settings)) {
          add_fallback_info();
          return;
        }
        for (k in settings) {
          v = settings[k];
          if (k === "version_full") {
            addFullVersionEntry("root.menu.info.instance." + k, v);
          } else if (k.endsWith('_time')) {
            addInfoTableEntry("root.menu.info.instance." + k, v.replace(/T/g, ' '));
          } else if (k.endsWith("_commit")) {
            addCommitUrlEntry("root.menu.info.instance." + k, v);
          } else {
            addInfoTableEntry("root.menu.info.instance." + k, v);
          }
        }
        return add_more();
      };
    })(this)).fail(add_fallback_info);
    return add_even_more = (function(_this) {
      return function() {
        var aboutInfoObject, cd, css_hrefs, css_s, i, key, len, ref, value;
        if (ez5.session.isDebug()) {
          css_hrefs = [];
          ref = CUI.dom.matchSelector(document, "link[rel='stylesheet']");
          for (i = 0, len = ref.length; i < len; i++) {
            css_s = ref[i];
            css_hrefs.push(new CUI.ButtonHref({
              appearance: "link",
              text: CUI.dom.getAttribute(css_s, "href"),
              href: CUI.dom.getAttribute(css_s, "href"),
              target: "_blank"
            }));
          }
          addInfoTableList("root.menu.info.css_hrefs", css_hrefs);
        }
        if (window.easydb_server_url) {
          addInfoTableEntry("root.menu.info.server", window.easydb_server_url);
        } else {
          addInfoTableEntry("root.menu.info.server", document.location.origin);
        }
        aboutInfoObject = ez5.session.getClientDefault("about_info");
        for (key in aboutInfoObject) {
          value = aboutInfoObject[key];
          addInfoTableEntry("root.menu.info.dynamic." + key, value);
        }
        cd = new CUI.ConfirmationDialog({
          title: ez5.version("6") ? $$("root.menu.info.fylr.dialog.title") : $$("root.menu.info.dialog.title"),
          "class": "ez5-about-modal",
          padded: false,
          content: info_table,
          buttons: [
            {
              text: $$("base.ok"),
              primary: true,
              onClick: function() {
                return cd.destroy();
              }
            }
          ]
        });
        return cd.show();
      };
    })(this);
  };

  return RootMenuAbout;

})(RootMenuApp);

ez5.session_ready(function() {
  return ez5.rootMenu.registerApp(RootMenuAbout);
});
// Generated by CoffeeScript 1.12.7
var Session,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  Session.prototype.readOpts = function() {
    Session.__super__.readOpts.call(this);
    this.loadPrefs();
    this.__colorLoader = new CUI.CSSLoader();
    this.__updatePrefsQueue = [];
    this.__updatePrefsQueueProcessing = false;
    if (!this._remoteEasydb) {
      EventPoller.listen({
        instance: this,
        filter: {
          type: "BASE_CONFIG_UPDATE"
        },
        call: (function(_this) {
          return function(events) {
            var ref;
            if (events && events.length > 0 && ((ref = events[0].info) != null ? ref.Path.includes("/plugin") : void 0)) {
              return;
            }
            return _this.get(_this.token).done(function() {
              return _this.handleBaseConfigUpdate();
            });
          };
        })(this)
      });
      EventPoller.listen({
        instance: this,
        filter: {
          type: "DATAMODEL_COMMIT"
        },
        call: (function(_this) {
          return function(events) {
            if (_this.__ignore_event_for_schema_update) {
              return;
            }
            if (!_this.__handleSchemaUpdate) {
              _this.handleSchemaUpdate(true);
            }
          };
        })(this)
      });
    }
  };

  Session.prototype.initOpts = function() {
    Session.__super__.initOpts.call(this);
    return this.addOpts({
      remoteEasydb: {
        check: function(v) {
          return window.RemoteEasydb && v instanceof window.RemoteEasydb;
        }
      }
    });
  };

  Session.prototype.getClientDefault = function(key) {
    var d, ref, ref1;
    if (key == null) {
      key = null;
    }
    d = (ref = this.config) != null ? (ref1 = ref.defaults) != null ? ref1.client : void 0 : void 0;
    if (!CUI.util.isPlainObject(d)) {
      return null;
    }
    if (key === null) {
      return d;
    }
    if (d.hasOwnProperty(key)) {
      return d[key];
    }
    return null;
  };

  Session.prototype.isDebug = function() {
    var debug_mode_overwrite;
    debug_mode_overwrite = this.getPref("debug_mode_overwrite");
    if (debug_mode_overwrite) {
      return debug_mode_overwrite === "on";
    }
    return CUI.util.isTrue(this.getClientDefault("debug"));
  };

  Session.prototype.isReadOnly = function() {
    var ref;
    return (ref = this.getXEasydb()) != null ? ref.readonly : void 0;
  };

  Session.prototype.reload = function() {
    return this.get(this.token);
  };

  Session.prototype.deauthenticate = function() {
    return ez5.api.session({
      type: "POST",
      remoteEasydb: this._remoteEasydb,
      api: "/deauthenticate"
    }).done((function(_this) {
      return function(data) {
        _this.setSessionData(data);
        if (!_this._remoteEasydb) {
          return CUI.setSessionStorage("token", void 0);
        }
      };
    })(this));
  };

  Session.prototype.getDuration = function() {
    if (!this.__startTime) {
      return 0;
    }
    return new Date() - this.__startTime;
  };

  Session.prototype.authenticate = function(data) {
    var _data, dfr, opts, stop_error_propagation;
    console.timeLog("Start", "authenticate");
    dfr = new CUI.Deferred();
    stop_error_propagation = false;
    opts = {
      remoteEasydb: this._remoteEasydb,
      type: "POST",
      api: "/authenticate?log_event=true",
      handle_error: (function(_this) {
        return function(xhr) {
          var ref, ref1;
          if (_this.getPref("remember_me") && !ez5.version("6") && !_this._remoteEasydb && ((ref = (ref1 = xhr.responseJSON) != null ? ref1.code : void 0) === 'error.user.session_not_found' || ref === 'error.api.cookie_check_failed' || ref === 'error.user.login_failed')) {
            stop_error_propagation = true;
            CUI.setSessionStorage("token", void 0);
            _this.saveCookiePref("remember_me", false);
            document.location.reload();
            return true;
          }
          if (_this._remoteEasydb) {
            return true;
          }
        };
      })(this)
    };
    if (data.method === "easydb") {
      opts.headers = {};
      opts.headers["content-type"] = "application/x-www-form-urlencoded";
      opts.body = CUI.encodeUrlData({
        login: data.login,
        password: data.password
      });
      _data = CUI.util.copyObject(data, true);
      delete _data.login;
      delete _data.password;
      opts.data = _data;
    } else {
      opts.data = data;
    }
    ez5.api.session(opts).always((function(_this) {
      return function() {
        return console.timeLog("Start", "authenticate done");
      };
    })(this)).done((function(_this) {
      return function(data) {
        _this.__startTime = new Date();
        return _this.setSessionData(data).done(function() {
          return dfr.resolve(data);
        }).fail(dfr.reject);
      };
    })(this)).fail((function(_this) {
      return function(error) {
        if (stop_error_propagation) {
          return;
        }
        return dfr.reject(error);
      };
    })(this));
    return dfr.promise();
  };

  Session.prototype.getRefreshToken = function() {
    return CUI.getSessionStorage("refreshToken", this.refreshToken);
  };

  Session.prototype.refresh = function() {
    var dfr, refresh_token;
    dfr = new CUI.Deferred();
    refresh_token = this.getRefreshToken();
    ez5.server({
      remoteEasydb: this._remoteEasydb,
      type: "POST",
      url: "/oauth2/refresh",
      json_data: {
        access_token: this.token,
        refresh_token: refresh_token
      },
      handle_error: (function(_this) {
        return function() {
          return true;
        };
      })(this)
    }).done((function(_this) {
      return function(data, status, xhr) {
        if (status !== 200) {
          return dfr.reject(data, status, xhr);
        }
        _this.token = data.access_token;
        CUI.setSessionStorage("token", _this.token);
        _this.refreshToken = data.refresh_token;
        CUI.setSessionStorage("refreshToken", _this.refreshToken);
        return dfr.resolve(data, status, xhr);
      };
    })(this)).fail((function(_this) {
      return function() {
        return dfr.reject();
      };
    })(this));
    return dfr.promise();
  };

  Session.prototype.__getTokenParam = function() {
    var base;
    if (this._remoteEasydb) {
      if (typeof (base = this._remoteEasydb).isFylr === "function" ? base.isFylr() : void 0) {
        return "access_token";
      } else {
        return "token";
      }
    } else {
      return ez5.tokenParam;
    }
  };

  Session.prototype.get = function(token, dfr) {
    var endpoint, endpointApi, params, ref;
    if (dfr == null) {
      dfr = new CUI.Deferred();
    }
    params = {};
    if (token) {
      params[this.__getTokenParam()] = token;
    } else {
      params.language = ez5.loca.getLanguage();
    }
    endpoint = "session";
    endpointApi = "";
    if ((!this._remoteEasydb && ez5.version("6")) || ((ref = this._remoteEasydb) != null ? typeof ref.isFylr === "function" ? ref.isFylr() : void 0 : void 0)) {
      endpoint = "user";
      endpointApi = "/session";
    }
    ez5.api[endpoint]({
      api: endpointApi,
      data: params,
      remoteEasydb: this._remoteEasydb,
      handle_error: (function(_this) {
        return function() {
          if (_this._remoteEasydb) {
            return true;
          }
          if (ez5.version("6")) {
            ez5.login.redirectToOAUTH2Login();
            return true;
          }
        };
      })(this),
      error: function() {}
    }).done((function(_this) {
      return function(data, status, xhr) {
        _this.__current_schema = null;
        _this.checkSchemaVersions(xhr);
        return _this.setSessionData(data).done(dfr.resolve).fail(dfr.reject);
      };
    })(this)).fail((function(_this) {
      return function(xhr, status) {
        if (ez5.version("6") && !_this._remoteEasydb) {
          return;
        }
        return dfr.reject(xhr, status);
      };
    })(this));
    return dfr.promise();
  };

  Session.prototype.getSchemaInfo = function() {
    CUI.util.assert(this.__current_schema, "Session.getSchemaInfo", "No current schema found.");
    return this.__current_schema;
  };

  Session.prototype.checkSchemaVersions = function(jqXHR) {
    var current;
    if (this.__handleSchemaUpdate) {
      return false;
    }
    current = ServerRequestApi.getXEasydbHeaders(jqXHR);
    if (!current) {
      return true;
    }
    if (!this.__current_schema) {
      this.__current_schema = current;
      return true;
    }
    if (this.__current_schema.base !== current.base || this.__current_schema.user !== current.user || this.__current_schema.solution !== current.solution) {
      this.handleSchemaUpdate();
      return false;
    }
    return true;
  };

  Session.prototype.stopHandleSchemaUpdateEvent = function() {
    return this.__ignore_event_for_schema_update = true;
  };

  Session.prototype.handleSchemaUpdate = function(allow_cancel) {
    if (allow_cancel == null) {
      allow_cancel = false;
    }
    return this.__handleSchemaUpdate = new CUI.Alert({
      ui: "datamodel.has_schema_update.alert",
      title: $$("admin.schema.update.modal.title"),
      text: $$("admin.schema.update.modal.explain"),
      button_text_ok: $$("admin.schema.update.modal.button"),
      cancel: allow_cancel
    }).open().done((function(_this) {
      return function() {
        return document.location.reload();
      };
    })(this));
  };

  Session.prototype.fylrCacheParams = function(days) {
    var fylrCacheId, ref, ref1;
    if (days == null) {
      days = 30;
    }
    if (!ez5.version("6")) {
      return {};
    }
    fylrCacheId = ((ref = ez5.session.getXEasydb()) != null ? ref.fylrCacheId : void 0) || window.fylrCacheId;
    if (!fylrCacheId) {
      return {};
    }
    return {
      fylr_cache: fylrCacheId,
      user_id: ((ref1 = this.user) != null ? ref1.id : void 0) || 0,
      cache_seconds: days * 86400
    };
  };

  Session.prototype.getXEasydb = function() {
    return this.__x_easydb;
  };

  Session.prototype.setSessionData = function(data1) {
    var checkRemoteInstance, database_locale, dfr, format, i, j, k, l, len, len1, len2, localeDateTimeObject, original_calendar, overrided_locales, ref, ref1, ref2, ref3, ref4, type, v;
    this.data = data1;
    dfr = new CUI.Deferred();
    this.token = this.data[this.__getTokenParam()];
    if (!this._remoteEasydb) {
      CUI.setSessionStorage("token", this.token);
    }
    this.frontend_language = this.data.frontend_language;
    this.frontend_locale = this.data.frontend_locale;
    CUI.util.assert(!CUI.util.isEmptyObject(this.frontend_locale), "Session.set", "Session did not return a frontend_locale. Cannot set session.", {
      data: this.data
    });
    checkRemoteInstance = (function(_this) {
      return function() {
        var base;
        if (!_this._remoteEasydb) {
          return true;
        }
        return typeof (base = _this._remoteEasydb).isFylr === "function" ? base.isFylr() : void 0;
      };
    })(this);
    if (ez5.version("6.7") && checkRemoteInstance()) {
      this.database_locales = this.data.database_locales;
      overrided_locales = [];
      if (this.database_locales) {
        ref = this.database_locales;
        for (i = 0, len = ref.length; i < len; i++) {
          database_locale = ref[i];
          if (!CUI.util.isEmpty(database_locale.calendar)) {
            original_calendar = CUI.util.copyObject(database_locale.calendar, true);
            for (k in original_calendar) {
              v = original_calendar[k];
              database_locale.calendar[k] = CUI.DateTime.convertTimeFormatFromGoToMoment(v);
            }
            localeDateTimeObject = CUI.DateTimeFormats[database_locale.name];
            if (!localeDateTimeObject) {
              localeDateTimeObject = CUI.DateTimeFormats[database_locale.name] = CUI.util.copyObject(CUI.DateTimeFormats["de-DE"], true);
            }
            if (localeDateTimeObject) {
              overrided_locales.push(database_locale.name);
              ref1 = localeDateTimeObject.formats;
              for (j = 0, len1 = ref1.length; j < len1; j++) {
                format = ref1[j];
                type = format.type;
                if (database_locale.calendar[type]) {
                  format.display = format.input = format.display_short = database_locale.calendar[type];
                }
              }
            }
          }
        }
      }
      if (this.frontend_locale && !CUI.util.isEmpty(this.frontend_locale.calendar)) {
        original_calendar = CUI.util.copyObject(this.frontend_locale.calendar, true);
        for (k in original_calendar) {
          v = original_calendar[k];
          this.frontend_locale.calendar[k] = CUI.DateTime.convertTimeFormatFromGoToMoment(v);
        }
      }
      if (ref2 = !this.frontend_language, indexOf.call(overrided_locales, ref2) >= 0) {
        localeDateTimeObject = CUI.DateTimeFormats[this.frontend_language];
        if (localeDateTimeObject) {
          ref3 = localeDateTimeObject.formats;
          for (l = 0, len2 = ref3.length; l < len2; l++) {
            format = ref3[l];
            type = format.type;
            if (this.frontend_locale.calendar[type]) {
              format.display = format.input = format.display_short = this.frontend_locale.calendar[type];
            }
          }
        }
      }
    }
    this.config = this.data.config || {};
    if (this.data.user) {
      this.user = User.newInstance({
        user: this.data.user
      });
    } else {
      this.user = null;
    }
    this.pendingTasks = ((ref4 = this.data.pending_tasks) != null ? ref4.slice() : void 0) || [];
    CUI.util.assert(!this.authenticated || this.user, "Session.set", "user not set in authenticated session", {
      session: this
    });
    if (this.isDebug()) {
      CUI.defaults.debug = true;
      document.body.classList.add("ez5-session-debug");
    }
    this.system_rights = this.data.system_rights || {};
    if (this._remoteEasydb) {
      return CUI.resolvedPromise();
    }
    this.loadPrefs();
    this.setLanguage().fail((function(_this) {
      return function() {
        return _this.setLanguage(true).fail(dfr.reject).done(function() {
          CUI.alert({
            text: $$("l10n.error.fallback"),
            markdown: true
          });
          return dfr.resolve();
        });
      };
    })(this)).done(dfr.resolve).always((function(_this) {
      return function() {
        _this.loadFavicon();
        return _this.setDocumentTitle();
      };
    })(this));
    return dfr.promise();
  };

  Session.prototype.setDocumentTitle = function(extraTitle) {
    var title;
    title = this.getSystemName();
    if (extraTitle) {
      title = title + " - " + extraTitle;
    }
    return document.title = title;
  };

  Session.prototype.getEasydbName = function() {
    var ref, solution;
    solution = this.getInstance().solution ? "-" + (this.getInstance().solution) : "";
    return ((ref = this.getBaseConfig().name) != null ? ref.internal_name : void 0) || "easydb" + solution;
  };

  Session.prototype.getSystemName = function() {
    var displayName, internalName, ref, ref1, ref2, ref3;
    if (ez5.version("6")) {
      displayName = (ref = this.getBaseConfig().name) != null ? ref.title[this.frontend_language] : void 0;
      internalName = (ref1 = this.getBaseConfig().name) != null ? ref1.internal_name : void 0;
    } else {
      displayName = (ref2 = this.getBaseConfig().displayname) != null ? ref2.value[this.frontend_language] : void 0;
      internalName = (ref3 = this.getBaseConfig().name) != null ? ref3.value : void 0;
    }
    if (CUI.util.isString(displayName) && !CUI.util.isEmpty(displayName.trim())) {
      return displayName;
    } else if (!CUI.util.isEmpty(internalName != null ? internalName.trim() : void 0)) {
      return internalName;
    } else if (ez5.version("6")) {
      return "fylr";
    } else {
      return "easydb 5";
    }
  };

  Session.prototype.__getSystemRights = function() {
    return this.system_rights || {};
  };

  Session.prototype.getSystemRight = function(sr) {
    var _sr, part_name, part_value, parts, value;
    if (!sr.match(/^(plugin\.|system\.)/)) {
      sr = "system." + sr;
    }
    parts = sr.match(/^(.*?)(?:|\[([^\]]+)\])(?:|\[([^\]]+)\])$/);
    if (parts[2] && parts[3]) {
      part_name = parts[2];
      part_value = parts[3];
    } else if (!parts[2] && parts[3]) {
      part_name = parts[3];
      part_value = null;
    } else {
      part_name = null;
      part_value = null;
    }
    _sr = this.__getSystemRights()[parts[1]];
    if (!_sr) {
      return null;
    }
    if (CUI.util.isNull(part_name)) {
      return _sr;
    }
    if (!_sr.hasOwnProperty(part_name)) {
      return null;
    }
    value = _sr[part_name];
    if (CUI.util.isNull(part_value)) {
      return value;
    }
    if (value === false) {
      if (CUI.util.isFalse(part_value)) {
        return value;
      } else {
        return null;
      }
    }
    if (value === true) {
      if (CUI.util.isTrue(part_value)) {
        return value;
      } else {
        return null;
      }
    }
    if (CUI.util.isString(value)) {
      if (value === part_value) {
        return value;
      } else {
        return null;
      }
    }
    if (CUI.util.isArray(value)) {
      if (indexOf.call(value, part_value) >= 0) {
        return [part_value];
      } else {
        return null;
      }
    }
    return null;
  };

  Session.prototype.hasSystemRight = function() {
    var i, len, sr;
    for (i = 0, len = arguments.length; i < len; i++) {
      sr = arguments[i];
      if (this.getSystemRight(sr)) {
        return true;
      }
    }
    return false;
  };

  Session.prototype.getData = function() {
    return this.data;
  };

  Session.prototype.getDisplayName = function() {
    if (!this.user) {
      return "(no user)";
    } else {
      return this.user.getDisplayText();
    }
  };

  Session.prototype.getAuthMethod = function() {
    var ref;
    return (ref = this.getData().authenticated) != null ? ref.method : void 0;
  };

  Session.prototype.isAuthenticated = function() {
    return !!this.user;
  };

  Session.prototype.getUser = function() {
    CUI.util.assert(this.user instanceof User, "Session.getUser", "Session not authenticated, unable to get user", {
      session: this
    });
    return this.user;
  };

  Session.prototype.getLanguage = function() {
    return this.frontend_language;
  };

  Session.prototype.loadPrefs = function() {
    var cookiePrefs, cookie_only_prefs, cookies, cookies_ok, db_langs, e, group, i, j, k, l, lang, len, len1, len2, ref, ref1, ref2, ref3, ref4, ref5, ref6, v, webfrontendPreferences;
    this.__prefs = {};
    if (this.user) {
      webfrontendPreferences = this.user.getData().user.frontend_prefs.webfrontend;
      if (!webfrontendPreferences || CUI.util.isEmpty(webfrontendPreferences)) {
        ref = this.getGroups();
        for (i = 0, len = ref.length; i < len; i++) {
          group = ref[i];
          webfrontendPreferences = (ref1 = group.data.group.frontend_prefs) != null ? (ref2 = ref1.webfrontend) != null ? ref2.preferences_new_users : void 0 : void 0;
          if (!CUI.util.isEmpty(webfrontendPreferences)) {
            break;
          }
        }
      }
      for (k in webfrontendPreferences) {
        v = webfrontendPreferences[k];
        this.__prefs[k] = CUI.util.copyObject(v, true);
      }
      ref3 = ["database_languages", "search_languages", "frontend_language"];
      for (j = 0, len1 = ref3.length; j < len1; j++) {
        k = ref3[j];
        if (!this.__prefs[k]) {
          this.__prefs[k] = this.user.getData().user[k];
        }
      }
      db_langs = this.getConfigDatabaseLanguages();
      ref4 = {
        database_languages: "Database",
        search_languages: "Search"
      };
      for (k in ref4) {
        v = ref4[k];
        if (!this.__prefs[k]) {
          continue;
        }
        ref5 = this.__prefs[k];
        for (l = 0, len2 = ref5.length; l < len2; l++) {
          lang = ref5[l];
          if (indexOf.call(db_langs, lang) < 0) {
            console.error(("Session.loadPrefs: " + v + " language \"" + lang + "\" is not enabled in Base Config. Base Config enabled languages are: ") + db_langs.join(", "));
          }
        }
      }
    }
    cookiePrefs = this.getCookieDefaultPrefs();
    try {
      if (window.localStorage.getItem("webfrontend")) {
        cookies = JSON.parse(window.localStorage.getItem("webfrontend"));
      } else {
        cookies = {};
      }
    } catch (error1) {
      e = error1;
      console.error("Session.loadPrefs: ", e);
      cookies = {};
    }
    cookie_only_prefs = this.getCookieOnlyPrefs();
    cookies_ok = [];
    for (k in cookiePrefs) {
      v = cookiePrefs[k];
      cookies_ok.push(k);
      if (!CUI.util.isNull(this.__prefs[k]) && indexOf.call(cookie_only_prefs, k) < 0) {
        continue;
      }
      if (cookies[k] !== void 0) {
        this.__prefs[k] = cookies[k];
      } else {
        this.__prefs[k] = v;
      }
    }
    for (k in cookies) {
      v = cookies[k];
      if (indexOf.call(cookies_ok, k) >= 0) {
        continue;
      }
      this.__prefs[k] = v;
    }
    ref6 = this.getDefaultPrefs();
    for (k in ref6) {
      v = ref6[k];
      if (CUI.util.isNull(this.__prefs[k])) {
        this.__prefs[k] = v;
      }
    }
    return this;
  };

  Session.prototype.getDefaultPrefs = function() {
    var defaults;
    defaults = {
      spellcheck: false,
      show_languages_with_data: true,
      languages_user_selection: false
    };
    if (this.config) {
      defaults.database_languages = [this.getConfigDatabaseLanguages()[0]];
      defaults.search_languages = [this.getConfigDatabaseLanguages()[0]];
    }
    return defaults;
  };

  Session.prototype.clearPrefs = function(ev) {
    var user;
    CUI.util.assert(this.user, "Session.clearPrefs", "No user found.");
    return this.savePrefs(ev, {}, user = this.user).done((function(_this) {
      return function() {
        try {
          return window.localStorage.clear();
        } catch (error1) {}
      };
    })(this));
  };

  Session.prototype.savePrefs = function(ev, prefs, user, mode) {
    var addUpdatePrefsToQueue, deferred, updatePrefs;
    if (prefs == null) {
      prefs = this.__prefs;
    }
    if (mode == null) {
      mode = "settings";
    }
    CUI.util.assert(mode === "settings" || mode === "register", "Session.savePrefs", "mode needs to be settings or register.", {
      mode: mode
    });
    deferred = new CUI.Deferred();
    if (ev != null ? ev.hasModifierKey() : void 0) {
      console.debug("Preferences:", CUI.util.dump(prefs));
      if (!this.user) {
        return deferred.reject();
      }
      this.saveCookiePrefs(prefs);
    }
    if (this.user) {
      addUpdatePrefsToQueue = (function(_this) {
        return function(_user, _prefs, _deferred) {
          _this.__updatePrefsQueue.push({
            _user: _user,
            _prefs: _prefs,
            _deferred: _deferred
          });
          if (_this.__updatePrefsQueueProcessing) {
            return;
          }
          updatePrefs();
        };
      })(this);
      updatePrefs = (function(_this) {
        return function() {
          var _deferred, _prefs, _user, doUpdate, ref;
          if (_this.__updatePrefsQueue.length === 0) {
            _this.__updatePrefsQueueProcessing = false;
            return;
          }
          _this.__updatePrefsQueueProcessing = true;
          doUpdate = function() {
            _user.setDataOfPrefs(_prefs);
            _user.saveLimited(ev, mode).done(function() {
              if (!user) {
                _this.user.loadData(_user.getData());
              }
              _this.__prefs = _prefs;
              updatePrefs();
              return _deferred.resolve();
            }).fail(function() {
              _deferred.reject();
              return updatePrefs();
            });
          };
          ref = _this.__updatePrefsQueue.shift(), _user = ref._user, _prefs = ref._prefs, _deferred = ref._deferred;
          if (!_user) {
            _user = _this.user.copy();
            _user.load().done(function() {
              return doUpdate();
            });
          } else {
            doUpdate();
          }
        };
      })(this);
      addUpdatePrefsToQueue(user, prefs, deferred);
    } else {
      this.__prefs = prefs;
      deferred.resolve();
    }
    return deferred.promise();
  };

  Session.prototype.getPrefs = function() {
    return CUI.util.copyObject(this.__prefs, true);
  };

  Session.prototype.setPref = function(pref, value) {
    this.__prefs[pref] = value;
    return this;
  };

  Session.prototype.saveCookiePrefs = function(cprefs) {
    var cookies, cookies_ok, ex, k, old_cookie, old_cookies, ref, v;
    if (cprefs == null) {
      cprefs = this.__prefs;
    }
    if (window.localStorage.getItem("webfrontend")) {
      old_cookies = JSON.parse(window.localStorage.getItem("webfrontend"));
    } else {
      old_cookie = {};
    }
    cookies_ok = [];
    cookies = {};
    ref = this.getCookieDefaultPrefs();
    for (k in ref) {
      v = ref[k];
      cookies_ok.push(k);
      this.__prefs[k] = cprefs[k];
      if (cprefs[k] !== v) {
        cookies[k] = cprefs[k];
      }
    }
    for (k in old_cookies) {
      v = old_cookies[k];
      if (indexOf.call(cookies_ok, k) >= 0) {
        continue;
      }
      cookies[k] = v;
      this.__prefs[k] = v;
    }
    try {
      window.localStorage.setItem("webfrontend", JSON.stringify(cookies));
    } catch (error1) {
      ex = error1;
      console.error("Unable to save localStorage", ex);
    }
    return this;
  };

  Session.prototype.saveCookiePref = function(pref, value) {
    CUI.util.assert(this.getCookieDefaultPrefs().hasOwnProperty(pref), "Session.saveCookiePref", "Pref \"" + pref + "\" is not a Cookie Pref.");
    CUI.util.assert(value !== void 0, "Session.saveCookiePref", "Value for Pref \"" + pref + "\" cannot be undefined.");
    this.setPref(pref, value);
    this.saveCookiePrefs();
    return this;
  };

  Session.prototype.savePref = function(pref, value, force) {
    var cached_prefs;
    if (force == null) {
      force = false;
    }
    cached_prefs = CUI.util.copyObject(this.getPrefs(), true);
    this.setPref(pref, value);
    if (CUI.util.isEqual(cached_prefs, this.getPrefs()) && !force) {
      return CUI.resolvedPromise();
    }
    return this.savePrefs();
  };

  Session.prototype.getPref = function(pref) {
    return this.__prefs[pref];
  };

  Session.prototype.getCookieOnlyPrefs = function() {
    var arr, cp, i, len, ref;
    arr = ["skip_anonymous", "preferred_language", "show_asset_browser", "detail_sidebar_show_hierarchy", "detail_sidebar_show_map", "remember_me", "event_poll", "css_mode", "css_developer_theme", "debug_mode_overwrite", "debug_locakeys", "easydb_server_url", "secondary_server_url", "easydb_server_url_history", "plugins_load_from_remote", "plugins_remote_url", "browser_unsupported", "recognize_version"];
    ref = this.__customCookieOnlyPrefs;
    for (i = 0, len = ref.length; i < len; i++) {
      cp = ref[i];
      arr.push(cp.name);
    }
    return arr;
  };

  Session.prototype.__customCookieOnlyPrefs = [];

  Session.prototype.addCookieOnlyPref = function(name, _default) {
    if (this.__prefs[name] === void 0) {
      this.__prefs[name] = _default;
    }
    this.__customCookieOnlyPrefs.push({
      name: name,
      "default": _default
    });
    this.loadPrefs();
    return this;
  };

  Session.prototype.getCookieDefaultPrefs = function() {
    var cp, i, len, prefs, ref;
    prefs = {
      skip_anonymous: false,
      css_developer_theme: null,
      remember_me: false,
      event_poll: true,
      preferred_language: null,
      css_mode: null,
      debug_mode_overwrite: null,
      browser_unsupported: null,
      plugins_load_from_remote: true,
      plugins_remote_url: "",
      debug_locakeys: false,
      show_asset_browser: true,
      detail_sidebar_show_hierarchy: false,
      detail_sidebar_show_map: false,
      easydb_server_url_history: [],
      easydb_server_url: null,
      secondary_server_url: null,
      recognize_version: true,
      quick_access_open: true,
      root_menu_open: false
    };
    ref = this.__customCookieOnlyPrefs;
    for (i = 0, len = ref.length; i < len; i++) {
      cp = ref[i];
      prefs[cp.name] = cp["default"];
    }
    return prefs;
  };

  Session.prototype.getConfigDatabaseLanguages = function() {
    var i, idx, lang, langs, len, ref;
    langs = ((ref = this.getBaseConfig().languages) != null ? ref.database : void 0) || [];
    for (idx = i = 0, len = langs.length; i < len; idx = ++i) {
      lang = langs[idx];
      if (lang.value) {
        langs[idx] = lang.value;
      }
    }
    return langs;
  };

  Session.prototype.getConfigFrontendLanguages = function() {
    var ref;
    return ((ref = this.getBaseConfig().languages) != null ? ref.frontend : void 0) || [];
  };

  Session.prototype.loadColor = function(color) {
    var bg_color, e, ref, ref1, ref2, ref3, ref4, ref5;
    if (!color) {
      color = ((ref = ez5.session.getBaseConfig()) != null ? (ref1 = ref.css_colors) != null ? ref1.highlight_color : void 0 : void 0) || 'blue';
    }
    document.documentElement.setAttribute('data-theme-color', color);
    bg_color = ((ref2 = this.getBaseConfig().logo) != null ? (ref3 = ref2.background_color) != null ? ref3.trim() : void 0 : void 0) || null;
    CUI.dom.setStyle(document.documentElement, {
      "--top-header-background": bg_color
    });
    if ((ref4 = ez5.rootMenu) != null) {
      ref4.adjust_title_color();
    }
    if (((ref5 = ez5.cssLoader.getActiveCSS()) != null ? ref5.theme : void 0) === 'fylr') {
      try {
        this.setBrandColorCSSVariables();
      } catch (error1) {
        e = error1;
        console.warn("Error trying to set the brand color CSS variables", e);
      }
    }
  };

  Session.prototype.setBrandColorCSSVariables = function() {
    var background_color, brand_color, brand_color_contrast_black, brand_color_contrast_white, brand_color_hover, brand_color_on_black, brand_color_on_white, chroma, css_body_color, hslPercent, luminance_threshold, ref, ref1, ref2, ref3;
    chroma = window.chroma || {};
    background_color = ((ref = this.getBaseConfig().appearance) != null ? (ref1 = ref.background_color) != null ? ref1.trim() : void 0 : void 0) || null;
    brand_color = ((ref2 = this.getBaseConfig().appearance) != null ? (ref3 = ref2.brand_color) != null ? ref3.trim() : void 0 : void 0) || null;
    if (background_color !== null) {
      document.documentElement.classList.add("pages-background-color-custom");
      CUI.dom.setStyle(document.querySelector(':root'), {
        "--pages-background-color": background_color
      });
    }
    if (brand_color !== null) {
      document.documentElement.classList.add("brand-color-custom");
      brand_color_hover = chroma(brand_color).set("hsl.l", chroma(brand_color).get("hsl.l") - 0.1).hex();
      brand_color_contrast_white = chroma.contrast('white', brand_color);
      brand_color_contrast_black = chroma.contrast('black', brand_color);
      if (brand_color_contrast_white < 4.5) {
        switch (false) {
          case !(brand_color_contrast_white < 2):
            hslPercent = 0.4;
            break;
          case !(brand_color_contrast_white < 3):
            hslPercent = 0.3;
            break;
          case !(brand_color_contrast_white < 4):
            hslPercent = 0.2;
            break;
          case !(brand_color_contrast_white < 4.5):
            hslPercent = 0.1;
        }
        brand_color_on_white = chroma(brand_color).luminance(0.19).hex();
      } else {
        brand_color_on_white = brand_color;
      }
      if (brand_color_contrast_black < 4.5) {
        switch (false) {
          case !(brand_color_contrast_black < 2):
            hslPercent = 0.4;
            break;
          case !(brand_color_contrast_black < 3):
            hslPercent = 0.3;
            break;
          case !(brand_color_contrast_black < 4):
            hslPercent = 0.2;
            break;
          case !(brand_color_contrast_black < 4.5):
            hslPercent = 0.1;
        }
        brand_color_on_black = chroma(brand_color).set("hsl.l", chroma(brand_color).get("hsl.l") + hslPercent).hex();
      } else {
        brand_color_on_black = brand_color;
      }
      luminance_threshold = 0.2;
      if (chroma(brand_color).luminance() > luminance_threshold) {
        css_body_color = CUI.dom.getComputedStyle(document.querySelector(':root')).getPropertyValue('--body-color');
        css_body_color = css_body_color.trim();
        if (!CUI.util.isEmpty(css_body_color)) {
          CUI.dom.setStyle(document.querySelector(':root'), {
            "--brand-foreground-text-color": css_body_color,
            "--brand-foreground-text-color-rgb": chroma(css_body_color).rgb().toString()
          });
        }
        brand_color_hover = chroma(brand_color).set("hsl.l", chroma(brand_color).get("hsl.l") + 0.1).hex();
        document.documentElement.classList.add("brand-color-is-light");
      } else {
        document.documentElement.classList.add("brand-color-is-dark");
      }
      CUI.dom.setStyle(document.querySelector(':root'), {
        "--brand-color": brand_color,
        "--brand-color-rgb": chroma(brand_color).rgb().toString(),
        "--brand-color-hover": brand_color_hover,
        "--brand-color-on-white": brand_color_on_white,
        "--brand-color-on-black": brand_color_on_black,
        "--brand-color-on-black-rgb": chroma(brand_color_on_black).rgb().toString()
      });
    }
  };

  Session.prototype.getCSSMode = function() {
    var css_mode, css_modes;
    css_modes = Start.getCSSModes();
    css_mode = this.getPref("css_mode");
    if (!css_mode || indexOf.call(css_modes, css_mode) < 0) {
      css_mode = css_modes[0];
    }
    return css_mode;
  };

  Session.knownCSSThemes = ["ng", "fylr", "debug", "mockup"];

  Session.prototype.loadTheme = function() {
    var default_theme, theme;
    if (ez5.version("6")) {
      default_theme = "fylr";
    } else {
      default_theme = "ng";
    }
    theme = this.getPref("css_developer_theme");
    if (!theme || indexOf.call(Session.knownCSSThemes, theme) < 0) {
      theme = default_theme;
    }
    console.time("Session.loadTheme", theme, "default", default_theme);
    return ez5.cssLoader.load({
      theme: theme,
      url: Start.getCSSUrl(theme, this.getCSSMode())
    }).done((function(_this) {
      return function() {
        ez5.defaults.focusClass = "cui-selected";
        _this.loadFavicon();
        return console.timeEnd("Session.loadTheme");
      };
    })(this)).fail((function(_this) {
      return function(path) {
        return ez5.cssLoader.load({
          theme: default_theme,
          url: Start.getCSSUrl(default_theme, _this.getCSSMode())
        }).always(function() {
          return CUI.problem({
            text: $$("session.load_theme_error", {
              path: path,
              theme: theme,
              mode: _this.getCSSMode()
            }),
            markdown: true
          });
        });
      };
    })(this));
  };

  Session.prototype.loadFavicon = function() {
    var favicon, link, oldFavicon, ref, ref1, url;
    oldFavicon = CUI.dom.matchSelector(document.documentElement, "LINK[name='favicon']")[0];
    if (oldFavicon) {
      CUI.dom.remove(oldFavicon);
    }
    favicon = this.getConfigPicture("favicon");
    if (!favicon) {
      return;
    }
    url = (ref = favicon.versions) != null ? (ref1 = ref.original) != null ? ref1.url : void 0 : void 0;
    if (!url) {
      return;
    }
    link = CUI.dom.element("LINK", {
      name: "favicon",
      rel: "shortcut icon",
      href: url
    });
    document.head.appendChild(link);
  };

  Session.prototype.getLoginBackdrop = function() {
    var backdrop, cls, dim, img, value;
    value = this.getConfigPicture("background");
    if (!value) {
      return;
    }
    dim = CUI.dom.getDimensions(window);
    img = Asset.getBestImageForViewport(new AssetPlain({
      value: value
    }), dim.width, dim.height);
    if (!img) {
      return;
    }
    if (img.width > img.height) {
      cls = "landscape";
    } else {
      cls = "portrait";
    }
    backdrop = CUI.dom.div("login-backdrop " + cls);
    CUI.dom.setStyle(backdrop, {
      backgroundImage: "url(" + img.url + ")"
    });
    return backdrop;
  };

  Session.prototype.getDefaults = function() {
    var defaults, ref;
    defaults = ((ref = this.config) != null ? ref.defaults : void 0) || {};
    if (!defaults.client) {
      defaults.client = {};
    }
    if (!defaults.server) {
      defaults.server = {};
    }
    return defaults;
  };

  Session.prototype.getEASConfig = function() {
    var ref;
    return ((ref = this.config) != null ? ref.eas : void 0) || {};
  };

  Session.prototype.getBaseConfig = function(type, pluginName) {
    var baseConfig, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7;
    if (type == null) {
      type = "system";
    }
    if (type !== "system" && type !== "plugin") {
      console.warn("Session :: getBaseConfig -> Unknown configuration type: " + type);
      return {};
    }
    if (!ez5.version("6")) {
      if (type === "plugin") {
        type = "system";
      }
      baseConfig = ((ref = this.config) != null ? ref.base : void 0) || {
        system: {},
        defaults: {}
      };
      return baseConfig[type];
    }
    if (type === "system") {
      return ((ref1 = this.config) != null ? (ref2 = ref1.base) != null ? (ref3 = ref2.system) != null ? ref3.config : void 0 : void 0 : void 0) || {};
    }
    if (type === "plugin" && pluginName) {
      return ((ref4 = this.config) != null ? (ref5 = ref4.base) != null ? (ref6 = ref5.plugin) != null ? (ref7 = ref6[pluginName]) != null ? ref7.config : void 0 : void 0 : void 0 : void 0) || {};
    }
    return console.error("getBaseConfig: type plugin needs a pluginName");
  };

  Session.prototype.handleBaseConfigUpdate = function() {
    if (this.__baseConfigUpdateAlert) {
      return;
    }
    ez5.start.updateLogo();
    this.loadColor();
    this.loadFavicon();
    this.__baseConfigUpdateAlert = new CUI.Alert({
      ui: "baseconfig_update.alert",
      title: $$("admin.config.update.alert.title"),
      text: $$("admin.config.update.alert.text"),
      cancel: true,
      button_text_ok: $$("admin.schema.update.modal.button")
    });
    return this.__baseConfigUpdateAlert.open().always((function(_this) {
      return function() {
        return _this.__baseConfigUpdateAlert = null;
      };
    })(this)).done((function(_this) {
      return function() {
        return document.location.reload();
      };
    })(this));
  };

  Session.prototype.getCustomDataTypes = function() {
    return this.getDefaults().server.custom_data_types || {};
  };

  Session.prototype.getInstance = function() {
    var ref;
    return ((ref = this.data) != null ? ref.instance : void 0) || {};
  };

  Session.prototype.getInstanceGlobalName = function() {
    return this.getInstance().name;
  };

  Session.prototype.getConfigPicture = function(name) {
    var img, key, ref;
    switch (name) {
      case "background":
        key = ["login.background_image", "image"];
        break;
      case "logo":
        if (ez5.version("6")) {
          key = ["appearance", "logo"];
        } else {
          key = ["logo", "logo"];
        }
        break;
      case "favicon":
        key = ["favicon", "favicon"];
        break;
      default:
        CUI.util.assert(false, "Session.getConfigPicture", "Unknown picture \"" + name + "}");
        return null;
    }
    img = (ref = this.getBaseConfig()[key[0]]) != null ? ref[key[1]] : void 0;
    if (!img) {

    }
    if ((img != null ? img.status : void 0) === "done") {
      return img;
    }
    return null;
  };

  Session.prototype.getDefaultPicture = function(name) {
    var ref, ref1, ref2, ref3;
    if (ez5.version("6")) {
      return;
    }
    return (ref = this.config) != null ? (ref1 = ref.base) != null ? (ref2 = ref1.defaults) != null ? (ref3 = ref2.pictures) != null ? ref3[name] : void 0 : void 0 : void 0 : void 0;
  };

  Session.prototype.workPendingTasks = function(master_dfr, task_count) {
    var pt;
    if (!master_dfr) {
      master_dfr = new CUI.Deferred();
      task_count = this.pendingTasks.length;
    }
    if (this.pendingTasks.length === 0) {
      return master_dfr.resolve(task_count);
    }
    this.workPendingTask(pt = this.pendingTasks.shift()).fail((function(_this) {
      return function(reason) {
        if (reason === "user_rejected") {
          return CUI.confirm({
            text: $$("session.pending_tasks.cancel_warning"),
            button_text_ok: $$("session.pending_tasks.cancel_warning.button"),
            button_primary: "cancel"
          }).done(function() {
            return master_dfr.reject(reason);
          }).fail(function() {
            _this.pendingTasks.splice(0, 0, pt);
            return _this.workPendingTasks(master_dfr, task_count);
          });
        } else {
          return master_dfr.reject(reason);
        }
      };
    })(this)).done((function(_this) {
      return function() {
        console.debug("next ", _this.pendingTasks.length);
        return _this.workPendingTasks(master_dfr, task_count);
      };
    })(this));
    return master_dfr.promise();
  };

  Session.prototype.workPendingTask = function(pt) {
    var dfr;
    console.debug("working pending task", pt);
    dfr = new CUI.Deferred();
    switch (pt.type) {
      case "message":
        this.pendingTaskMessage(dfr, pt.message);
        break;
      case "system_message":
        this.pendingTaskSystemMessage(dfr, pt.system_message);
        break;
      case "set_password":
        this.pendingTaskSetPassword(dfr);
        break;
      case "logout":
        this.logoutSilent();
        break;
      default:
        console.error("Unknown pending task", pt.type, pt);
        CUI.problem({
          text: $$("session.pending_tasks.unknown_pending_task", {
            pending_task: pt.type
          }),
          button_text_ok: $$("session.pending_tasks.unknown_pending_task.button")
        }).done((function(_this) {
          return function() {
            return _this.logout();
          };
        })(this));
    }
    return dfr.promise();
  };

  Session.prototype.logoutSilent = function(redirect) {
    var ref, up;
    if (redirect == null) {
      redirect = window.easydb_base_prefix + "/";
    }
    if ((ref = ez5.eventPoller) != null) {
      ref.stop();
    }
    if (ez5.version("6") && window.fylr_server) {
      up = new URLSearchParams();
      up.set(ez5.tokenParam, this.token);
      up.set("redirect", redirect);
      CUI.setSessionStorage("token", void 0);
      document.location.assign(window.easydb_base_prefix + "/logout?" + up.toString());
      return;
    }
    return this.deauthenticate().always((function(_this) {
      return function() {
        return document.location.assign(redirect);
      };
    })(this));
  };

  Session.prototype.logout = function() {
    var ref, sso, window_open;
    if (this.getAuthMethod() === "sso") {
      sso = this.getMethod("sso");
      if ((ref = sso.client.logout) != null ? ref.url : void 0) {
        window_open = sso.client.logout.window_open || "";
        if (window_open === "self") {
          this.logoutSilent(sso.client.logout.url);
          return;
        }
        window.open(sso.client.logout.url, "_blank", window_open);
      }
    }
    if (ez5.connector) {
      ez5.connector.logout().done((function(_this) {
        return function() {
          return _this.logoutSilent();
        };
      })(this));
    } else {
      this.logoutSilent();
    }
  };

  Session.prototype.pendingTaskMessage = function(dfr, msg) {
    AdminMessage.showMessageDialog({
      webfrontend_type: msg.webfrontend_type,
      confirm: msg.confirm,
      title: msg.title,
      message: msg.message,
      webfrontend_props: msg.webfrontend_props
    }).done((function(_this) {
      return function() {
        return ez5.api.session({
          type: "POST",
          api: "/messages_confirm",
          json_data: [msg.message_key]
        }).done(function() {
          return dfr.resolve();
        }).fail(function(xhr) {
          return dfr.reject(xhr);
        });
      };
    })(this)).fail((function(_this) {
      return function() {
        return dfr.reject("user_rejected");
      };
    })(this));
    return this;
  };

  Session.prototype.pendingTaskSystemMessage = function(dfr, msg) {
    var key, params, value;
    params = msg.parameters;
    for (key in params) {
      value = params[key];
      if (!CUI.util.isString(value)) {
        continue;
      }
      params[key] = value.replace(/\&/g, "&amp;").replace(/\</g, "&lt;").replace(/\>/g, "&gt;").replace(/\:/g, "&#58;").replace(/\./g, "&#46;");
    }
    return CUI.alert({
      markdown: true,
      text: $$(msg.code, params)
    }).done(function() {
      return dfr.resolve();
    });
  };

  Session.prototype.pendingTaskSetPassword = function(dfr) {
    return this.passwordChangeModal("set_password").done(function() {
      return dfr.resolve();
    }).fail(function() {
      return dfr.reject("user_rejected");
    });
  };

  Session.prototype.getMethod = function(method) {
    var auth_method, found_method, i, len, ref;
    ref = this.data.authentication_methods;
    for (i = 0, len = ref.length; i < len; i++) {
      auth_method = ref[i];
      if (auth_method.method === method) {
        found_method = auth_method;
        break;
      }
    }
    if (!found_method) {
      return null;
    }
    return found_method;
  };

  Session.prototype.loginAgain = function(load_apps, allowCancel) {
    var dfr;
    if (load_apps == null) {
      load_apps = true;
    }
    if (allowCancel == null) {
      allowCancel = true;
    }
    if (ez5.version("6")) {
      ez5.login.redirectToOAUTH2Login("easydb");
      return CUI.rejectedPromise();
    }
    dfr = new CUI.Deferred();
    console.time("Start");
    dfr.always((function(_this) {
      return function() {
        return console.timeEnd("Start");
      };
    })(this));
    ez5.login.showLogin(allowCancel).done((function(_this) {
      return function() {
        console.debug("unloading active app...");
        return ez5.rootMenu.unloadActiveApp().always(function() {
          console.info("going on...");
          return _this.setLanguage().always(function() {
            ez5.eventPoller.stop();
            return _this.workPendingTasks().fail(function(reason) {
              _this.logout();
            }).done(function() {
              if (_this.getPref("event_poll")) {
                ez5.eventPoller.start();
              }
              return ez5.load_defaults().done(function() {
                if (load_apps) {
                  return ez5.start.loadApps().always(dfr.resolve);
                } else {
                  return dfr.resolve();
                }
              });
            }).fail(dfr.reject);
          });
        });
      };
    })(this)).fail(dfr.reject);
    dfr.always((function(_this) {
      return function() {
        return ez5.start.hideSplash();
      };
    })(this));
    return dfr.promise();
  };

  Session.prototype.getReady = function() {
    var auth, dfr, goto_login, login_by_method, ref, ref1, show_errors, sso, timeout, url_parms, visible, work_pending_tasks;
    console.timeLog("Start", "session getReady");
    dfr = new CUI.Deferred();
    dfr.always((function(_this) {
      return function() {
        return console.timeLog("Start", "session getReady done");
      };
    })(this));
    work_pending_tasks = (function(_this) {
      return function() {
        _this.workPendingTasks().done(function() {
          return dfr.resolve();
        }).fail(function() {
          return dfr.reject("goto_login");
        });
        return dfr.promise();
      };
    })(this);
    goto_login = (function(_this) {
      return function() {
        dfr.reject("goto_login");
        return dfr.promise();
      };
    })(this);
    login_by_method = (function(_this) {
      return function(method) {
        _this.authenticate({
          method: method
        }).done(function() {
          return work_pending_tasks();
        }).fail(function(error) {
          return dfr.reject({
            error: "session.authenticate_failure",
            error_args: arguments
          });
        });
        return dfr.promise();
      };
    })(this);
    url_parms = CUI.decodeUrlData(document.location.search.substring(1));
    sso = this.getMethod("sso");
    if (url_parms.use_sso && (sso != null ? (ref = sso.client) != null ? ref.login : void 0 : void 0)) {
      visible = sso.client.login.visible;
      show_errors = sso.client.login.show_errors;
      timeout = sso.client.login.timeout;
      this.SSOAuthAttended(visible, show_errors, timeout, "self");
      return (new CUI.Deferred()).promise();
    }
    if (document.location.pathname.match("^" + window.easydb_base_prefix + "/login(\/|)$")) {
      window.history.pushState({}, null, "/");
      if (url_parms.problem) {
        ez5.start.removeFromUrl("problem");
        CUI.problem({
          text: $$(url_parms.problem)
        }).done((function(_this) {
          return function() {
            return goto_login();
          };
        })(this));
        return dfr.promise();
      } else {
        return goto_login();
      }
    }
    auth = this.getAuthMethodFromURL();
    if (auth) {
      switch (auth.method) {
        case "easydb":
          ez5.start.removeFromUrl("login");
          ez5.start.removeFromUrl("password");
          break;
        case "collection":
          ez5.start.removeFromUrl("collection");
          break;
        case "anonymous":
          ez5.start.removeFromUrl("anonymous");
          break;
        case "task":
          window.history.pushState({}, null, "/");
          break;
        case "login":
          ez5.start.removeFromUrl("login");
          return goto_login();
      }
      if (this.getAuthMethod()) {
        console.warn("User is already authenticated, overloading with new authorization.", auth);
      }
      if (this.getMethod(auth.method)) {
        this.authenticate(auth).done((function(_this) {
          return function() {
            return work_pending_tasks();
          };
        })(this)).fail((function(_this) {
          return function() {
            return goto_login();
          };
        })(this));
      } else {
        return goto_login();
      }
    } else if (this.getAuthMethod()) {
      work_pending_tasks();
      return dfr.promise();
    } else if (this.getPref("remember_me") && this.getMethod("easydb_cookie")) {
      login_by_method("easydb_cookie");
    } else if (sso && ((ref1 = sso.client) != null ? ref1.autostart : void 0)) {
      this.loginByMethodSSO().done((function(_this) {
        return function() {
          return work_pending_tasks();
        };
      })(this)).fail((function(_this) {
        return function(reason) {
          if (reason === "sso_try_anonymous" && _this.getMethod("anonymous") && !_this.getPref("skip_anonymous")) {
            return login_by_method("anonymous");
          } else if (reason === "sso_needs_login") {
            return goto_login();
          } else {
            return dfr.reject({
              error: "session.authenticate_failure",
              error_args: arguments
            });
          }
        };
      })(this));
    } else if (this.getMethod("anonymous") && !this.getPref("skip_anonymous")) {
      login_by_method("anonymous");
    } else {
      goto_login();
    }
    return dfr.promise();
  };

  Session.prototype.getGroups = function() {
    var grp, i, len, ref, results;
    ref = this.data.groups;
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      grp = ref[i];
      results.push(Group.newInstance({
        group: grp
      }));
    }
    return results;
  };

  Session.prototype.getGroupIds = function() {
    var grp;
    return (function() {
      var i, len, ref, results;
      ref = this.data.groups;
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        grp = ref[i];
        results.push(grp.group._id);
      }
      return results;
    }).call(this);
  };

  Session.prototype.dumpGroups = function() {
    var grp, i, len, ref;
    ref = this.getGroups();
    for (i = 0, len = ref.length; i < len; i++) {
      grp = ref[i];
      console.debug(grp.getDisplayText());
    }
  };

  Session.prototype.passwordChangeModal = function(mode) {
    var cancel, changeBtn, checkBtn, data, dfr, form, modal;
    if (mode == null) {
      mode = "change_password";
    }
    CUI.util.assert(mode === "change_password" || mode === "set_password", "Session.passwordChangeModal", "Only change_password and set_password are supported for mode.", {
      mode: mode
    });
    modal = null;
    dfr = new CUI.Deferred();
    data = {
      current_password: "",
      new_password_1: ""
    };
    cancel = function() {
      modal.destroy();
      return dfr.reject();
    };
    changeBtn = new LocaButton({
      loca_key: "auth.button." + mode,
      primary: true,
      disabled: true,
      onClick: (function(_this) {
        return function(ev) {
          var apiCall, sd;
          sd = {
            new_password: data.new_password_1
          };
          if (mode === "change_password") {
            sd.password = data.current_password;
          }
          if (ev.shiftKey() || ev.altKey() || ev.ctrlKey()) {
            console.debug(CUI.util.dump(sd));
            return;
          }
          if (ez5.version("6")) {
            apiCall = ez5.api.user;
          } else {
            apiCall = ez5.api.session;
          }
          return apiCall({
            type: "POST",
            api: "/" + mode,
            json_data: sd
          }).done(function() {
            return CUI.alert({
              text: $$("session.password_changed_success")
            }).done(function() {
              modal.destroy();
              return dfr.resolve();
            });
          });
        };
      })(this)
    });
    checkBtn = function() {
      data.new_password_1 = data.new_password_1.trim();
      changeBtn.disable();
      if (data.new_password_1.length === 0) {
        return false;
      }
      if (mode === "change_password" && data.current_password.trim().length === 0) {
        return false;
      }
      changeBtn.enable();
      return true;
    };
    form = new CUI.Form({
      fields: [
        mode === "change_password" ? {
          type: CUI.Password,
          mark_changed: false,
          form: {
            label: $$("auth.form.current_password")
          },
          name: "current_password",
          toggleButton: true
        } : void 0, {
          type: CUI.Password,
          mark_changed: false,
          form: {
            label: $$("auth.form.new_password_1")
          },
          name: "new_password_1",
          toggleButton: true
        }
      ],
      onDataChanged: checkBtn,
      data: data
    }).start();
    modal = new CUI.Modal({
      "class": "ez5-password-change-modal ez5-auth-" + mode,
      pane: {
        header_left: new CUI.Label({
          text: $$("auth.title." + mode)
        }),
        content: form,
        padded: true,
        footer_right: changeBtn
      },
      cancel: true,
      onCancel: (function(_this) {
        return function() {
          return cancel();
        };
      })(this)
    }).show();
    return dfr.promise();
  };

  Session.prototype.setLanguage = function(fallback) {
    var _lang, ad_prefix, appendix, dfr, frontendLanguage, frontend_languages, i, j, lang, len, len1, ref, ref1;
    if (fallback == null) {
      fallback = false;
    }
    dfr = new CUI.Deferred();
    frontend_languages = (ref = this.getBaseConfig().languages) != null ? ref.frontend : void 0;
    lang = null;
    ref1 = [this.frontend_language, this.getPref("preferred_language"), navigator.language, frontend_languages != null ? frontend_languages[0] : void 0];
    for (i = 0, len = ref1.length; i < len; i++) {
      _lang = ref1[i];
      if (indexOf.call(frontend_languages, _lang) >= 0) {
        lang = _lang;
        break;
      }
      for (j = 0, len1 = frontend_languages.length; j < len1; j++) {
        frontendLanguage = frontend_languages[j];
        if (frontendLanguage.startsWith(_lang + "-")) {
          lang = frontendLanguage;
        }
      }
      if (lang) {
        break;
      }
    }
    if (!lang || fallback) {
      lang = "en-US";
    }
    if (this.isAuthenticated() && (this.frontend_language !== lang || this.getUser().getData().user.frontend_language !== lang || this.__prefs.frontend_language !== lang)) {
      console.warn("Frontend-language is set to a language not available. Changing it to ", lang);
      this.frontend_language = lang;
      this.__prefs.frontend_language = lang;
      this.getUser().getData().user.frontend_language = lang;
    }
    if (ez5.version("6.13")) {
      appendix = this.getFirstDatabaseLanguage().calendar.bc;
      if (!CUI.util.isEmpty(appendix)) {
        appendix = appendix.replace(/\s*%\(\s*date\s*\)s\s*/g, ' ').trim();
        CUI.DateTime.defaults.bc_appendix_output = appendix;
      }
      ad_prefix = this.getFirstDatabaseLanguage().calendar.ad;
      if (!CUI.util.isEmpty(ad_prefix)) {
        CUI.DateTime.defaults.ad_prefix_output = ad_prefix;
      }
    }
    console.info("Session.setLanguage:", lang);
    return ez5.loca.setLanguage(lang);
  };

  Session.prototype.getFirstDatabaseLanguage = function() {
    var first_locale, locales;
    if (!ez5.version("6")) {
      return null;
    }
    locales = ez5.session.getPref("database_languages") || [];
    first_locale = null;
    if (locales.length > 0) {
      first_locale = ez5.session.database_locales.find((function(_this) {
        return function(locale) {
          return locale.name === locales[0];
        };
      })(this));
    }
    return first_locale;
  };

  Session.prototype.SSOAuthAttended = function(visible, show_errors, timeout, window_open) {
    var dfr;
    dfr = new CUI.Deferred();
    return this.__SSOAuth(visible, show_errors, timeout, window_open).done((function(_this) {
      return function(data) {
        return _this.setSessionData(data).done(dfr.resolve).fail(dfr.reject);
      };
    })(this)).fail((function(_this) {
      return function(reason) {
        return dfr.reject(reason);
      };
    })(this));
  };

  Session.prototype.loginByMethodSSO = function() {
    var dfr, show_errors, sso, timeout, visible;
    sso = this.getMethod("sso");
    visible = sso.client.autostart.visible;
    show_errors = sso.client.autostart.show_errors;
    timeout = sso.client.autostart.timeout;
    dfr = new CUI.Deferred();
    this.__SSOAuth(visible, show_errors, timeout).done((function(_this) {
      return function(data) {
        return _this.setSessionData(data).done(dfr.resolve).fail(dfr.reject);
      };
    })(this)).fail((function(_this) {
      return function(reason) {
        if (sso.client.autostart.anonymous_fallback) {
          console.warn("Session: Autostart SSO failed, trying anonymous.", reason);
          return dfr.reject("sso_try_anonymous");
        } else {
          console.warn("Session: Unattended SSO failed, redirecting to Login.", reason);
          return dfr.reject("sso_needs_login");
        }
      };
    })(this));
    return dfr.promise();
  };

  Session.prototype.__SSOAuth = function(visible, show_errors, timeout, window_open) {
    var answer, finish_master_dfr, get_func, href, href_err, iframe, interval, msg_lsn, postee, sso, sso_deferred, sso_master_dfr, sso_modal, url, win;
    if (visible == null) {
      visible = true;
    }
    if (show_errors == null) {
      show_errors = true;
    }
    if (timeout == null) {
      timeout = null;
    }
    if (window_open == null) {
      window_open = null;
    }
    sso = this.getMethod("sso");
    sso_master_dfr = new CUI.Deferred();
    sso_deferred = new CUI.Deferred();
    answer = null;
    url = ez5.getAbsoluteURL(sso.authenticate_base);
    if (url.match(/\?/)) {
      url += "&";
    } else {
      url += "?";
    }
    if (window_open === null) {
      postee = "window.parent";
    } else if (window_open === "self") {
      href = document.location.href;
      href_err = document.location.origin + window.easydb_base_prefix + "/login?problem=session.sso.auth_failed";
      get_func = (function(_this) {
        return function(type) {
          if (type === "success") {
            return "var func = function() { document.location.href='" + href + "'; }; func";
          } else {
            return "var func = function() { document.location.href='" + href_err + "'; }; func";
          }
        };
      })(this);
      postee = null;
    } else {
      postee = "window.opener";
    }
    if (postee) {
      get_func = (function(_this) {
        return function(type) {
          return "var func = function(parm) {\n    var s = {\n	    login: '" + type + "',\n		easydb: true\n	};\n	s.response = parm;\n	" + postee + ".postMessage(s, '*'); };\n\nfunc";
        };
      })(this);
    }
    url += CUI.encodeUrlData({
      success: get_func("success"),
      error: get_func("error"),
      token: this.token
    });
    console.debug("__SSOAuth", "visible:", visible, "show_errors:", show_errors, sso, url);
    interval = null;
    if (window_open === null) {
      iframe = CUI.dom.$element("iframe", "", {
        src: url
      });
    } else if (window_open === "self") {
      document.location.assign(url);
    } else {
      win = window.open(url, "_blank", window_open);
      interval = window.setInterval((function(_this) {
        return function() {
          if (win.closed) {
            return finish_master_dfr();
          }
        };
      })(this), 500);
      window.addEventListener("unload", (function(_this) {
        return function() {
          return win.close();
        };
      })(this));
    }
    msg_lsn = CUI.Events.listen({
      type: "message",
      node: window,
      call: (function(_this) {
        return function(ev, info) {
          var data;
          data = ev.getNativeEvent().data;
          console.debug("Session message received", data);
          if (!data.easydb) {
            return;
          }
          CUI.Events.ignore(msg_lsn);
          if (data.auth_required) {
            sso_deferred.reject({
              code: "session.sso.auth_required"
            });
            return;
          }
          if (sso_deferred.state() === "rejected") {
            return;
          }
          switch (data.login) {
            case "success":
              sso_deferred.resolve(data.response);
              break;
            case "error":
              sso_deferred.reject(data.response);
          }
        };
      })(this)
    });
    finish_master_dfr = (function(_this) {
      return function() {
        if (interval) {
          window.clearInterval(interval);
          interval = null;
        }
        CUI.Events.ignore(msg_lsn);
        switch (sso_deferred.state()) {
          case "rejected":
            sso_master_dfr.reject(answer);
            break;
          case "resolved":
            sso_master_dfr.resolve(answer);
            break;
          default:
            sso_master_dfr.reject();
        }
      };
    })(this);
    sso_deferred.fail((function(_this) {
      return function(reason) {
        var msg;
        answer = reason;
        if (show_errors) {
          msg = $$(reason.code, reason.parameters);
          return new CUI.ConfirmationChoice({
            text: msg,
            title: $$("session.sso.auth_failed.title"),
            choices: [
              {
                text: $$("session.sso.auth_failed.choice.more_info"),
                onClick: function() {
                  if (iframe) {
                    return sso_modal.setVisible(true);
                  } else {
                    return win.focus();
                  }
                }
              }, {
                text: $$("session.sso.auth_failed.choice.ok"),
                onClick: function() {
                  if (iframe) {
                    return sso_modal.destroy();
                  } else {
                    return win.close();
                  }
                }
              }
            ]
          }).open();
        } else if (visible) {

        } else {
          if (iframe) {
            return sso_modal.destroy();
          } else {
            return win.close();
          }
        }
      };
    })(this));
    sso_deferred.done((function(_this) {
      return function(data) {
        answer = data;
        if (iframe) {
          return sso_modal.destroy();
        } else {
          return win.close();
        }
      };
    })(this));
    if (iframe) {
      sso_modal = new CUI.Modal({
        "class": "ez5-session-sso-modal",
        cancel: true,
        visible: visible,
        onHide: (function(_this) {
          return function() {
            return finish_master_dfr();
          };
        })(this),
        pane: {
          header_left: new CUI.Label({
            text: $$("session.sso.modal.title")
          }),
          content: iframe
        }
      });
      if (!visible && (timeout > 0 || timeout === null)) {
        CUI.setTimeout({
          ms: timeout || 5000,
          call: (function(_this) {
            return function() {
              if (sso_deferred.state() === "pending") {
                sso_deferred.reject({
                  code: "session.sso.auth_failed.timeout"
                });
              }
            };
          })(this)
        });
      }
      sso_modal.show();
    }
    return sso_master_dfr.promise();
  };

  Session.cleanServerUrl = function(server) {
    var parsed, s;
    s = server.trim();
    parsed = CUI.parseLocation(server);
    return (parsed != null ? parsed.url : void 0) || "";
  };

  Session.crossServer = function() {
    return window.easydb_server_url !== document.location.origin;
  };

  Session.addToken = function(url) {
    if (ez5.version("6")) {
      if (url.match(/\?/)) {
        url += "&";
      } else {
        url += "?";
      }
      url += "access_token=" + ez5.session.token;
    }
    return ez5.getAbsoluteURL(url);
  };

  Session.addEz5Token = function(url) {
    if (url.match(/\?/)) {
      url += "&";
    } else {
      url += "?";
    }
    url += ez5.tokenParam + "=" + ez5.session.token;
    return url;
  };

  Session.prototype.getAuthMethodFromURL = function() {
    var auth, match, up;
    up = new URLSearchParams(document.location.search);
    if (!CUI.util.isEmpty(up.get("login")) && !CUI.util.isEmpty(up.get("password"))) {
      auth = {
        method: "easydb",
        login: up.get("login"),
        password: up.get("password")
      };
    }
    match = document.location.pathname.match("^" + window.easydb_base_prefix + "/collection/(.*)$");
    if (match) {
      if (up.get("collection")) {
        auth = {
          method: "collection",
          login: match[1],
          collection: match[1],
          password: up.get("collection")
        };
      } else if (up.has("anonymous")) {
        auth = {
          method: "anonymous"
        };
      } else if (up.get("email") && up.get("acl")) {
        auth = {
          method: "email",
          login: up.get("email"),
          password: up.get("acl")
        };
      } else if (up.has("login")) {
        auth = {
          method: "login"
        };
      } else if (!this.getAuthMethod() && !auth) {
        return null;
      }
    } else {
      match = document.location.pathname.match("^" + window.easydb_base_prefix + "/task?(.*)$");
      if (match) {
        auth = {
          method: "task",
          login: up.get("email"),
          password: up.get("code")
        };
      }
    }
    return auth;
  };

  Session.prototype.getReplacementRecord = function() {
    var i, key, len, rec, ref, userData, value;
    rec = {};
    userData = this.getUser().getData();
    ref = ["login", "displayname", "email"];
    for (i = 0, len = ref.length; i < len; i++) {
      key = ref[i];
      value = userData.user[key];
      if (key === "displayname" && CUI.util.isEmpty(value)) {
        value = userData.user["_generated_displayname"];
      }
      rec["user." + key] = value;
    }
    return rec;
  };

  Session.prototype.setCapabilities = function() {
    var dfr;
    dfr = new CUI.Deferred();
    if (!ez5.version("6")) {
      dfr.resolve();
      return dfr.promise();
    }
    ez5.api.settings().done((function(_this) {
      return function(settings) {
        _this.capabilities = settings.capabilities;
        return dfr.resolve();
      };
    })(this));
    return dfr.promise();
  };

  Session.prototype.getCapability = function(name) {
    var ref;
    if (!ez5.version("6")) {
      return null;
    }
    return (ref = this.capabilities) != null ? ref[name] : void 0;
  };

  Session.prototype.getLicense = function(prop) {
    var config;
    if (!ez5.version("6")) {
      return null;
    }
    if (this.getBaseConfig()["license"]["license:info"].is_default) {
      config = this.getBaseConfig()["license"]["license:info"].validation;
    } else {
      config = this.getBaseConfig()["license"]["license"].validation;
    }
    if (prop) {
      return config[prop];
    }
    return config;
  };

  return Session;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var Login,
  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;

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

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

  Login.prototype.__showLoginMessage = function(code) {
    var loc, txt;
    if (window.easydb_server_url) {
      loc = CUI.parseLocation(window.easydb_server_url);
      txt = loc.hostname;
    } else {
      txt = "";
    }
    return this.__loginMessage.setText(txt);
  };

  Login.prototype.__submitForm = function() {
    var eurl, rem_me, submit_url, surl;
    eurl = document.location.origin + window.easydb_base_prefix + "/web/error.html";
    surl = document.location.origin + window.easydb_base_prefix + "/web/success.html";
    if (ez5.session.getPref("remember_me")) {
      rem_me = "&remember_me=1";
    } else {
      rem_me = "";
    }
    submit_url = ez5.api.getFullBase() + "/session/authenticate?" + ez5.tokenParam + "=" + ez5.session.token + "&success=" + surl + "&error=" + eurl + rem_me;
    CUI.dom.setAttribute(this.__form, "action", submit_url);
    return this.__form.submit();
  };

  Login.prototype.showLogin = function(allowCancel) {
    var anonymous_start_page_btn, bd, cannot_access, cannot_access_btn, easydbButtonText, i, icon, img, len, locaButtonOptions, loginFormExtra, loginFormMain, loginPane, ref, ref1, ref2, set_content, sso, ssoActivated, ssoButtonText, ssoStartLinkText, sso_preferred, sso_start_btn, switchIconKey, useLoginButton, welcome_lbl, welcome_text;
    if (allowCancel == null) {
      allowCancel = false;
    }
    this.__initForm();
    this.__loginDeferred = new CUI.Deferred();
    cannot_access = ez5.session.getBaseConfig()["login.forgotten_password_process"];
    if (cannot_access && cannot_access.value && cannot_access.show_in_login_dialog) {
      cannot_access_btn = new LocaButton({
        loca_key: "auth.button.cannot_access",
        "class": "ez5-login-cannot-access",
        appearance: "link",
        onClick: (function(_this) {
          return function() {
            return _this.cannot_access();
          };
        })(this)
      });
    } else {
      cannot_access_btn = null;
    }
    welcome_text = ez5.loca.getBestFrontendValue((ref = ez5.session.getBaseConfig()["login.welcome_text"]) != null ? ref.value : void 0);
    this.__loginMessage = new CUI.Label({
      "class": "ez5-login-message"
    });
    this.__loginButton = new LocaButton({
      loca_key: "auth.button.login",
      primary: true,
      left: true,
      onClick: (function(_this) {
        return function() {
          return _this.__doLogin();
        };
      })(this)
    });
    sso = ez5.session.getMethod("sso");
    sso_preferred = null;
    if (sso && ((ref1 = sso.client) != null ? ref1.login : void 0)) {
      if (sso.client.login.visually_preferred) {
        sso_preferred = true;
      }
      locaButtonOptions = {
        icon: $$("auth.button.login|icon"),
        onClick: (function(_this) {
          return function(ev) {
            var show_errors, timeout, visible, window_open;
            if (ev.ctrlKey()) {
              visible = true;
              show_errors = true;
              timeout = 0;
            } else {
              visible = sso.client.login.visible;
              show_errors = sso.client.login.show_errors;
              timeout = sso.client.login.timeout;
            }
            if (ev.altKey()) {
              if (sso.client.login.window_open !== void 0) {
                window_open = null;
              } else {
                window_open = "";
              }
            } else {
              window_open = sso.client.login.window_open;
            }
            return ez5.session.SSOAuthAttended(visible, show_errors, timeout, window_open).done(function() {
              _this.destroyLoginModal();
              return _this.__loginDeferred.resolve();
            });
          };
        })(this)
      };
      ssoStartLinkText = this.getSSOLoginLinkText();
      if (ssoStartLinkText) {
        locaButtonOptions.text = ssoStartLinkText;
      } else if (sso_preferred) {
        locaButtonOptions.loca_key = 'session.sso.button.preferred.start';
      } else {
        locaButtonOptions.loca_key = 'session.sso.button.start';
      }
      sso_start_btn = new LocaButton(locaButtonOptions);
    }
    if (ez5.session.getMethod("anonymous") && (!allowCancel || ez5.session.getAuthMethod() !== "anonymous")) {
      anonymous_start_page_btn = new LocaButton({
        loca_key: "auth.button.login_as_anonymous",
        appearance: "link",
        onClick: (function(_this) {
          return function() {
            return ez5.session.authenticate({
              method: "anonymous"
            }).done(function() {
              _this.destroyLoginModal();
              return _this.__loginDeferred.resolve();
            }).fail(function() {
              return CUI.problem({
                text: $$("session.authenticate_failure")
              });
            });
          };
        })(this)
      });
    }
    this.__loginAuthError = new CUI.Label({
      "class": "ez5-authentication-error",
      multiline: true
    });
    welcome_lbl = new LocaLabel({
      multiline: true,
      markdown: true,
      "class": "ez5-session-login-welcome-text",
      text: welcome_text
    });
    ref2 = CUI.dom.matchSelector(welcome_lbl, "img");
    for (i = 0, len = ref2.length; i < len; i++) {
      img = ref2[i];
      img.onload = (function(_this) {
        return function() {
          return CUI.Events.trigger({
            type: "content-resize",
            node: img
          });
        };
      })(this);
    }
    loginFormMain = new CUI.Form({
      "class": "ez5-session-login-input-fields",
      data: {},
      fields: [
        {
          type: CUI.DataFieldProxy,
          element: this.__form
        }
      ],
      top: [],
      bottom: this.__loginMessage.DOM
    }).start();
    loginFormExtra = this.getLoginForm();
    easydbButtonText = this.getEasyDBStartLinkText();
    if (!easydbButtonText) {
      easydbButtonText = $$("login.button.use_login.easydb.text");
    }
    ssoButtonText = this.getSSOStartLinkText() || $$("login.button.use_login.sso.text");
    switchIconKey = "login.button.use_login.switch.icon";
    if (ez5.loca.has(switchIconKey)) {
      icon = $$(switchIconKey);
    }
    ssoActivated = true;
    useLoginButton = new CUI.Button({
      text: easydbButtonText,
      icon: icon,
      onClick: function() {
        var buttonText;
        buttonText = ssoActivated ? ssoButtonText : easydbButtonText;
        ssoActivated = !ssoActivated;
        useLoginButton.setText(buttonText);
        return set_content(ssoActivated);
      }
    });
    loginPane = new CUI.SimplePane({
      header_left: (function(_this) {
        return function() {
          return new LocaLabel({
            loca_key: "login.modal.title",
            loca_key_attrs: {
              easydb: ez5.session.getSystemName()
            }
          });
        };
      })(this),
      header_right: (function(_this) {
        return function() {
          var fn, items, j, lang, len1, ref3;
          if (allowCancel) {
            return;
          }
          items = [];
          ref3 = ez5.session.getConfigFrontendLanguages();
          fn = function(lang) {
            return items.push({
              onClick: function() {
                if (lang === ez5.session.getLanguage()) {
                  return;
                }
                _this.__loginModal.disableAllButtons();
                ez5.session.saveCookiePref("preferred_language", lang);
                ez5.api.session({
                  data: {
                    token: ez5.session.token,
                    language: lang
                  }
                }).done(function(sess) {
                  console.debug("got session", sess);
                  if (false && document.location.pathname === "/") {
                    return document.location.assign(window.easydb_base_prefix + "/login");
                  } else {
                    return document.location.reload();
                  }
                });
              },
              active: lang === ez5.session.getLanguage(),
              text: ez5.loca.getLanguageTag(lang) + " " + ez5.loca.getLanguageLabel(lang)
            });
          };
          for (j = 0, len1 = ref3.length; j < len1; j++) {
            lang = ref3[j];
            fn(lang);
          }
          if (items.length < 2) {
            return;
          }
          return new LocaButton({
            text: $$("base.culture." + (ez5.session.getLanguage()) + ".tag"),
            loca_key: "session.language.switch",
            menu: {
              items: items
            }
          });
        };
      })(this),
      footer_left: this.__loginMessage
    });
    set_content = (function(_this) {
      return function(show_sso) {
        var content, hl, hl_opts, info_lbl, info_msg, j, len1, ref3, welcome_info;
        switch (show_sso) {
          case null:
            content = [welcome_lbl, CUI.dom.space(), _this.__loginAuthError, loginFormMain, cannot_access_btn, anonymous_start_page_btn, CUI.dom.space(), loginFormExtra];
            loginPane.replace([sso_start_btn, _this.__loginButton], 'footer_right');
            break;
          case false:
            content = [welcome_lbl, CUI.dom.space(), _this.__loginAuthError, CUI.dom.space(), loginFormMain, cannot_access_btn, anonymous_start_page_btn, CUI.dom.space(), loginFormExtra];
            loginPane.replace([useLoginButton, _this.__loginButton], 'footer_right');
            break;
          case true:
            content = [welcome_lbl, CUI.dom.space(), _this.__loginAuthError];
            loginPane.replace([useLoginButton, sso_start_btn], 'footer_right');
        }
        welcome_info = ez5.session.getBaseConfig()["login.welcome_info"];
        info_msg = ez5.loca.getBestFrontendValue(welcome_info != null ? welcome_info.message : void 0);
        if (info_msg) {
          info_lbl = new CUI.Label({
            "class": "ez5-login-welcome-info",
            markdown: true,
            multiline: true,
            text: info_msg
          });
          ref3 = CUI.dom.matchSelector(info_lbl, "img");
          for (j = 0, len1 = ref3.length; j < len1; j++) {
            img = ref3[j];
            img.onload = function() {
              return CUI.Events.trigger({
                type: "content-resize",
                node: img
              });
            };
          }
        } else {
          info_lbl = null;
        }
        hl_opts = {
          auto_buttonbar: false,
          "class": "ez5-login-layout",
          center: {
            "class": "ez5-login-layout-content",
            content: content
          },
          left: {
            "class": "ez5-login-layout-welcome-info",
            content: info_lbl
          }
        };
        if (!info_lbl) {
          delete hl_opts.left;
        }
        hl = new CUI.HorizontalLayout(hl_opts);
        if (info_lbl) {
          CUI.dom.addClass(hl, "ez5-login-layout--has-welcome-info");
        }
        loginPane.replace(hl);
        CUI.Events.trigger({
          type: "content-resize",
          node: _this.__loginModal
        });
      };
    })(this);
    set_content(sso_preferred);
    if (!allowCancel) {
      bd = {
        policy: "modal",
        content: ez5.session.getLoginBackdrop()
      };
    }
    this.__loginModal = new CUI.Modal({
      "class": "ez5-session-login",
      backdrop: bd,
      cancel: allowCancel,
      cancel_with_click_on_backdrop: false,
      onCancel: (function(_this) {
        return function() {
          if (allowCancel) {
            _this.destroyLoginModal();
            _this.__loginDeferred.reject();
            return;
          }
        };
      })(this),
      pane: loginPane
    });
    this.__loginModal.show();
    this.__showLoginMessage();
    CUI.setTimeout((function(_this) {
      return function() {
        return _this.__login.focus();
      };
    })(this));
    return this.__loginDeferred.promise();
  };

  Login.prototype.destroyLoginModal = function() {
    return this.__loginModal.destroy();
  };

  Login.prototype.getSSOStartLinkText = function() {
    var ref;
    return ez5.loca.getBestFrontendValue((ref = ez5.session.getBaseConfig()["sso"]) != null ? ref.start_link_text : void 0) || void 0;
  };

  Login.prototype.getSSOLoginLinkText = function() {
    var ref;
    return ez5.loca.getBestFrontendValue((ref = ez5.session.getBaseConfig()["sso"]) != null ? ref.login_link_text : void 0) || void 0;
  };

  Login.prototype.getEasyDBStartLinkText = function() {
    var ref;
    return ez5.loca.getBestFrontendValue((ref = ez5.session.getBaseConfig()["sso"]) != null ? ref.easydb_login_button_text : void 0) || void 0;
  };

  Login.prototype.__doLogin = function() {
    if (CUI.util.isEmpty(this.__login.value)) {
      this.__login.focus();
      return;
    }
    if (CUI.util.isEmpty(this.__password.value)) {
      this.__password.focus();
      return;
    }
    this.__loginButton.setIcon("spinner");
    this.__loginButton.disable();
    this.saveLoginLogoutForm();
    this.__preAuthenticate().done((function(_this) {
      return function() {
        CUI.Events.listen({
          type: "message",
          node: window,
          only_once: true,
          call: function(ev) {
            var ref;
            if (((ref = ev.getNativeEvent().data) != null ? ref.login : void 0) === "success") {
              CUI.dom.insertAfter(CUI.dom.find("iframe[name='login_form_target']")[0], _this.__form);
              _this.destroyLoginModal();
              _this.__loginDeferred.resolve();
            }
          }
        });
        _this.__submitForm();
      };
    })(this));
  };

  Login.prototype.__initForm = function() {
    var init;
    if (!this.__form) {
      this.__form = document.getElementById("login_form");
      init = true;
    } else {
      init = false;
    }
    CUI.util.assert(CUI.util.isElement(this.__form), "Session.__initForm", "Fixed Login Form not found in HTML markup, make sure you have loaded login.html");
    this.__login = CUI.dom.matchSelector(this.__form, 'input[type="text"]')[0];
    this.__password = CUI.dom.matchSelector(this.__form, 'input[type="password"]')[0];
    CUI.dom.setAttribute(this.__login, "placeholder", $$("session.login.placeholder"));
    CUI.dom.setAttribute(this.__password, "placeholder", $$("session.password.placeholder"));
    if (!init) {
      return;
    }
    CUI.Events.listen({
      node: this.__password,
      type: "keyup",
      call: (function(_this) {
        return function(ev) {
          _this.__showLoginMessage();
          if (ev.keyCode() === 13) {
            return _this.__doLogin();
          }
        };
      })(this)
    });
    CUI.Events.listen({
      node: this.__login,
      type: "keyup",
      call: (function(_this) {
        return function(ev) {
          _this.__showLoginMessage();
          if (ev.keyCode() === 13) {
            return _this.__password.focus();
          }
        };
      })(this)
    });
  };

  Login.prototype.__preAuthenticate = function() {
    var headers;
    headers = {};
    headers["content-type"] = "application/x-www-form-urlencoded";
    return ez5.api.session({
      type: "POST",
      api: "/authenticate?log_event=false",
      headers: headers,
      body: CUI.encodeUrlData({
        login: this.__login.value,
        password: this.__password.value
      }),
      error: function() {}
    }).done((function(_this) {
      return function(data) {
        return ez5.session.setSessionData(data);
      };
    })(this)).fail((function(_this) {
      return function(xhr) {
        var err;
        _this.__loginButton.setIcon();
        _this.__loginButton.enable();
        err = xhr.responseJSON;
        if ((err != null ? err.realm : void 0) === "user") {
          if (err.code === Login.__LOGIN_BLOCKED_TEMP) {
            _this.__updateSecondsLeft(parseInt(err.parameters.seconds));
          } else {
            _this.__loginAuthError.setText($$(err.code, err.parameters));
          }
          _this.__loginModal.position();
        } else {
          ez5.error_handler(xhr);
        }
      };
    })(this));
  };

  Login.__LOGIN_BLOCKED_TEMP = "error.user.login_blocked_temp";

  Login.prototype.__updateSecondsLeft = function(seconds) {
    this.__loginButton.disable();
    if (!seconds || seconds <= 0) {
      this.__loginButton.enable();
      this.__loginAuthError.setText("");
    } else {
      this.__loginAuthError.setText($$(Login.__LOGIN_BLOCKED_TEMP, {
        seconds: seconds
      }));
      CUI.setTimeout((function(_this) {
        return function() {
          return _this.__updateSecondsLeft(seconds - 1);
        };
      })(this), 1000);
    }
  };

  Login.prototype.cannot_access = function() {
    var doSendAccessCode, fieldInput, forgotButton, forgot_data, modal;
    forgot_data = {};
    doSendAccessCode = (function(_this) {
      return function(ev) {
        if (CUI.util.isEmpty(forgot_data.forgot)) {
          return;
        }
        if (ev.shiftKey() || ev.altKey() || ev.ctrlKey()) {
          console.debug(CUI.util.dump(forgot_data));
          return;
        }
        return ez5.api.session({
          type: "POST",
          api: "/forgot_password",
          json_data: {
            forgot: forgot_data.forgot
          }
        }).done(function() {
          modal.destroy();
          return CUI.alert({
            text: $$("auth.forgotpassword.email.confirm.text")
          });
        }).always(function() {
          forgotButton.enable();
          return forgotButton.stopSpinner();
        });
      };
    })(this);
    forgotButton = new LocaButton({
      loca_key: "auth.forgotpassword.button",
      primary: true,
      disabled: true,
      left: true,
      onClick: (function(_this) {
        return function(ev) {
          forgotButton.disable();
          forgotButton.startSpinner();
          return doSendAccessCode(ev);
        };
      })(this)
    });
    fieldInput = new CUI.Input({
      mark_changed: false,
      name: "forgot",
      form: {
        label: $$("auth.forgotpassword.input.forgot")
      }
    });
    CUI.Events.listen({
      node: fieldInput,
      type: "keyup",
      call: (function(_this) {
        return function(ev) {
          if (ev.keyCode() === 13) {
            doSendAccessCode(ev);
          }
        };
      })(this)
    });
    modal = new CUI.ConfirmationDialog({
      cancel: true,
      "class": "ez5-password-reset",
      title: $$('auth.forgotpassword.title'),
      content: (function(_this) {
        return function() {
          return new CUI.Form({
            fields: [fieldInput],
            onDataChanged: function(data, df, ev) {
              if (CUI.util.isEmpty(df.getValue())) {
                return forgotButton.disable();
              } else {
                forgotButton.enable();
                if (ev.keyCode() === 13) {
                  return doSendAccessCode(ev);
                }
              }
            },
            data: forgot_data,
            top: new CUI.Label({
              text: $$("auth.forgotpassword.text"),
              multiline: true
            })
          }).start();
        };
      })(this),
      buttons: [forgotButton]
    });
    return modal.show();
  };

  Login.prototype.saveLoginLogoutForm = function() {
    if (!this.__cookie_prefs) {
      return;
    }
    ez5.session.saveCookiePrefs(this.__cookie_prefs);
    this.__cookie_prefs = null;
    return this;
  };

  Login.prototype.getLoginForm = function(fields) {
    if (fields == null) {
      fields = [];
    }
    return this.__getLoginLogoutForm(true, fields);
  };

  Login.prototype.getLogoutForm = function(fields) {
    if (fields == null) {
      fields = [];
    }
    return this.__getLoginLogoutForm(false, fields);
  };

  Login.prototype.__getLoginLogoutForm = function(is_login, fields) {
    if (is_login == null) {
      is_login = false;
    }
    this.__cookie_prefs = ez5.session.getPrefs();
    if (ez5.session.getMethod("anonymous")) {
      fields.push({
        type: CUI.Checkbox,
        name: "skip_anonymous",
        mark_changed: false,
        undo_support: false,
        text: $$("auth.button.skip_anonymous")
      });
    }
    if (is_login) {
      fields.push({
        type: CUI.Checkbox,
        name: "remember_me",
        mark_changed: false,
        undo_support: false,
        text: $$("auth.button.remember_me")
      });
    }
    if (fields.length === 0) {
      this.__cookie_prefs = null;
      return;
    }
    return new CUI.Form({
      "class": "ez5-session-login-options",
      data: this.__cookie_prefs,
      fields: fields
    }).start();
  };

  Login.prototype.redirectToOAUTH2Login = function(auth_method) {
    var login, pw, rURL, rURL2, redirect, up;
    redirect = new URL(document.location.href);
    up = new URLSearchParams();
    login = redirect.searchParams.get("login");
    pw = redirect.searchParams.get("password");
    if (auth_method) {
      up.set("auth_method", auth_method);
    }
    if (login) {
      up.set("login", login);
      up.set("password", pw);
      up.set("auth_method", "easydb");
      redirect.searchParams["delete"]("login");
      redirect.searchParams["delete"]("password");
    }
    up.set("redirect", redirect.toString());
    rURL = window.easydb_base_prefix + "/login?" + up.toString();
    rURL2 = ez5.getAbsoluteURL(rURL);
    console.warn("Login.coffee: redirect to url", redirect, "current href", document.location.href, rURL2);
    document.location.assign(rURL2);
  };

  return Login;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var GetTokenDeepLink,
  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;

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

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

  GetTokenDeepLink.prototype.findAppByLocation = function(location, apps) {
    var dfr;
    if (location.pathname !== '/gettoken') {
      return CUI.rejectedPromise();
    }
    console.debug("location:", location, "apps:", apps);
    ez5.login.showLogin(false).done((function(_this) {
      return function() {
        return window.opener.postMessage({
          login: 'success',
          token: ez5.session.token
        }, '*');
      };
    })(this));
    dfr = new CUI.Deferred();
    return dfr.promise();
  };

  return GetTokenDeepLink;

})(RootMenuAppLoader);

ez5.session_ready(function() {
  return ez5.rootMenu.registerAppLoader(new GetTokenDeepLink());
});
// Generated by CoffeeScript 1.12.7
var LanguageTrayApp,
  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;

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

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

  LanguageTrayApp.prototype.getDisplay = function() {
    var btn;
    LanguageTrayApp.__super__.getDisplay.call(this);
    btn = new LocaButton({
      ui: "language.tray.app.button",
      "class": "ez5-language-control-tray-button",
      appearance: "transparent-border",
      loca_key: "language.tray.app.button.tray",
      text: ez5.loca.getLanguageTag(),
      onClick: function(ev, item) {
        return ez5.loca.getLanguageControl().showUserControl();
      }
    });
    CUI.dom.append(this.display, btn);
    return this.display;
  };

  LanguageTrayApp.prototype.getSortValue = function() {
    return 4;
  };

  return LanguageTrayApp;

})(TrayApp);

ez5.session_ready(function() {
  return ez5.tray.registerApp(new LanguageTrayApp());
});
// Generated by CoffeeScript 1.12.7
var LanguageControl,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  LanguageControl.prototype.getKeys = function() {
    var i, keys, lang, len, ref;
    keys = [];
    ref = this.getLanguages();
    for (i = 0, len = ref.length; i < len; i++) {
      lang = ref[i];
      keys.push({
        name: lang,
        tag: ez5.loca.getLanguageTag(lang),
        tooltip: {
          text: ez5.loca.getLanguageLabel(lang)
        }
      });
    }
    this.setKeys(keys);
    return LanguageControl.__super__.getKeys.call(this);
  };

  LanguageControl.prototype.getLanguages = function() {
    var langs, pref;
    langs = ez5.session.getConfigDatabaseLanguages();
    pref = ez5.session.getPref("database_languages");
    langs.sort(function(a, b) {
      var idx_a, idx_b;
      idx_a = pref.indexOf(a);
      idx_b = pref.indexOf(b);
      if (idx_a === -1) {
        idx_a = 1000;
      }
      if (idx_b === -1) {
        idx_b = 1000;
      }
      return CUI.util.compareIndex(idx_a, idx_b);
    });
    return langs;
  };

  LanguageControl.prototype.isEnabled = function(lang) {
    return ez5.session.getPref("database_languages").indexOf(lang) > -1;
  };

  LanguageControl.prototype.isEnabledSearch = function(lang) {
    return ez5.session.getPref("search_languages").indexOf(lang) > -1;
  };

  LanguageControl.prototype.getPreferredKey = function() {
    var i, j, k, key, keys, lang, len, len1, len2, ref, selectedLang;
    keys = this.getKeys();
    if (ez5.version("6")) {
      selectedLang = ez5.session.getLanguage();
      if (selectedLang) {
        for (i = 0, len = keys.length; i < len; i++) {
          key = keys[i];
          if (key.name === selectedLang) {
            return key;
          }
        }
      }
    }
    ref = ez5.session.getConfigFrontendLanguages();
    for (j = 0, len1 = ref.length; j < len1; j++) {
      lang = ref[j];
      for (k = 0, len2 = keys.length; k < len2; k++) {
        key = keys[k];
        if (key.name === lang) {
          return key;
        }
      }
    }
    return keys[0];
  };

  LanguageControl.prototype.showUserControl = function() {
    var data, database_opts, fields, form, frontend_opts, i, j, k, l, lang, languages_user_selection, len, len1, len2, len3, mod, push_opt, ref, ref1, ref2, ref3, search_opts, show_languages_with_data, spellcheck;
    spellcheck = ez5.session.getPref("spellcheck");
    show_languages_with_data = ez5.session.getPref("show_languages_with_data");
    languages_user_selection = ez5.session.getPref("languages_user_selection");
    data = {
      frontend: null,
      database: [],
      search: [],
      spellcheck: spellcheck,
      show_languages_with_data: show_languages_with_data,
      languages_user_selection: languages_user_selection
    };
    frontend_opts = [];
    ref = ez5.session.getConfigFrontendLanguages();
    for (i = 0, len = ref.length; i < len; i++) {
      lang = ref[i];
      frontend_opts.push({
        ui: "language.control.form.frontend.select.option:" + lang,
        value: lang,
        text: ez5.loca.getLanguageLabel(lang)
      });
    }
    data.frontend = ez5.loca.culture;
    database_opts = [];
    search_opts = [];
    push_opt = function(lang, opts) {
      return opts.push({
        ui: "language.control.form.options.option:" + lang,
        value: lang,
        text: ez5.loca.getLanguageLabel(lang)
      });
    };
    ref1 = ez5.session.getPref("database_languages");
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      lang = ref1[j];
      data.database.push(lang);
      push_opt(lang, database_opts);
    }
    ref2 = ez5.session.getPref("search_languages");
    for (k = 0, len2 = ref2.length; k < len2; k++) {
      lang = ref2[k];
      data.search.push(lang);
      push_opt(lang, search_opts);
    }
    ref3 = ez5.session.getConfigDatabaseLanguages();
    for (l = 0, len3 = ref3.length; l < len3; l++) {
      lang = ref3[l];
      if (indexOf.call(data.database, lang) < 0) {
        push_opt(lang, database_opts);
      }
      if (indexOf.call(data.search, lang) < 0) {
        push_opt(lang, search_opts);
      }
    }
    fields = [
      {
        type: CUI.Select,
        form: {
          label: $$("language.control.frontend")
        },
        name: "frontend",
        ui: "language.control.form.frontend.select",
        options: frontend_opts
      }, {
        type: CUI.Options,
        "class": "ez5-language-control-database-languages",
        form: {
          label: $$("language.control.database")
        },
        sortable: true,
        name: "database",
        ui: "language.control.form.database.options",
        min_checked: 1,
        options: database_opts,
        sortable_hint: $$("options.order_hint"),
        onRender: (function(_this) {
          return function() {
            return typeof mod !== "undefined" && mod !== null ? mod.autoSize() : void 0;
          };
        })(this)
      }, !ez5.version("6.5") ? {
        type: CUI.Options,
        "class": "ez5-language-control-search-languages",
        form: {
          label: $$("language.control.search")
        },
        sortable: true,
        name: "search",
        ui: "language.control.form.search.options",
        min_checked: 1,
        options: search_opts,
        sortable_hint: $$("options.order_hint"),
        onRender: (function(_this) {
          return function() {
            return typeof mod !== "undefined" && mod !== null ? mod.autoSize() : void 0;
          };
        })(this)
      } : void 0, {
        type: CUI.Checkbox,
        form: {
          label: $$("language.control.settings")
        },
        text: $$("language.control.spellcheck"),
        ui: "language.control.form.spellcheck.checkbox",
        name: "spellcheck"
      }, {
        type: CUI.Checkbox,
        text: $$("language.control.languages_user_selection"),
        name: "languages_user_selection",
        ui: "language.control.form.languages_user_selection.checkbox"
      }, {
        type: CUI.Checkbox,
        text: $$("language.control.show_languages_with_data"),
        name: "show_languages_with_data",
        ui: "language.control.form.show_languages_with_data.checkbox"
      }
    ];
    form = new CUI.Form({
      data: data,
      fields: fields
    }).start();
    return mod = new CUI.Modal({
      "class": "ez5-language-control",
      cancel: true,
      pane: {
        padded: true,
        footer_right: new CUI.Button({
          ui: "language.control.apply.button",
          text: $$("base.apply"),
          primary: true,
          onClick: (function(_this) {
            return function(ev) {
              mod.disableAllButtons();
              ez5.session.setPref("database_languages", data.database);
              ez5.session.setPref("search_languages", data.search);
              ez5.session.setPref("frontend_language", data.frontend);
              ez5.session.setPref("spellcheck", data.spellcheck);
              ez5.session.setPref("show_languages_with_data", data.show_languages_with_data);
              ez5.session.setPref("languages_user_selection", data.languages_user_selection);
              ez5.session.setPref("preferred_language", data.frontend);
              return ez5.session.savePrefs(ev).done(function() {
                var el, inp, len4, m, ref4;
                mod.destroy();
                if (data.frontend !== ez5.loca.getLanguage()) {
                  console.warn("reload switch language or new spellcheck");
                  return document.location.reload();
                } else {
                  if (spellcheck !== data.spellcheck) {
                    ref4 = CUI.dom.matchSelector(document.documentElement, ".cui-input,cui-multi-input-input");
                    for (m = 0, len4 = ref4.length; m < len4; m++) {
                      el = ref4[m];
                      inp = CUI.dom.data(el, "element");
                      if (CUI.util.getObjectClass(inp) === "Input" || inp instanceof CUI.MultiInputInput) {
                        inp.setSpellcheck(data.spellcheck);
                      }
                    }
                  }
                  return CUI.Events.trigger({
                    type: "multi-input-control-update",
                    info: {
                      user_selectable: data.languages_user_selection
                    }
                  });
                }
              }).fail(function() {
                return mod.enableAllButtons();
              });
            };
          })(this)
        }),
        header_left: new CUI.Label({
          text: $$("language.control.title")
        }),
        content: form
      }
    }).show();
  };

  return LanguageControl;

})(CUI.MultiInputControl);
// Generated by CoffeeScript 1.12.7
var LanguageControlCustom,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  LanguageControlCustom.prototype.initOpts = function() {
    LanguageControlCustom.__super__.initOpts.call(this);
    return this.addOpts({
      getEnabledKeys: {
        check: Function
      },
      hasUserControl: {
        check: Boolean,
        "default": true
      }
    });
  };

  LanguageControlCustom.prototype.hasUserControl = function() {
    return this._hasUserControl;
  };

  LanguageControlCustom.prototype.isEnabled = function(lang) {
    var enabledKeys;
    enabledKeys = this._getEnabledKeys();
    return indexOf.call(enabledKeys, lang) >= 0;
  };

  LanguageControlCustom.prototype.isEnabledSearch = function(lang) {
    return this.isEnabled(lang);
  };

  return LanguageControlCustom;

})(LanguageControl);
// Generated by CoffeeScript 1.12.7
var LanguageControlAdmin,
  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;

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

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

  LanguageControlAdmin.prototype.hasUserControl = function() {
    return true;
  };

  LanguageControlAdmin.prototype.getUserSelectable = function() {
    return ez5.session.getPref("languages_user_selection");
  };

  LanguageControlAdmin.prototype.getLanguages = function() {
    return ez5.session.getConfigFrontendLanguages();
  };

  LanguageControlAdmin.prototype.isEnabled = function(lang) {
    return true;
  };

  return LanguageControlAdmin;

})(LanguageControl);
// Generated by CoffeeScript 1.12.7
var SessionTrayApp,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  SessionTrayApp.prototype.getTrayButtons = function() {
    var buttons, i, item, len, ref, user;
    user = ez5.session.getUser();
    if (user.hasFlatTrayItems()) {
      buttons = [];
      ref = user.getTrayItems(this);
      for (i = 0, len = ref.length; i < len; i++) {
        item = ref[i];
        if (CUI.util.isPlainObject(item)) {
          buttons.push(new CUI.defaults["class"].Button(item));
        } else {
          buttons.push(item);
        }
      }
      return buttons;
    }
    return new LocaButton({
      icon: "user",
      "class": "ez5-session-tray-app-button",
      appearance: "transparent-border",
      ui: "session.tray.app.button",
      loca_key: "session.tray.app.button.tray",
      icon_right: false,
      text: ez5.session.getDisplayName(),
      menu: {
        top: {},
        items: (function(_this) {
          return function(ev, itemList) {
            itemList.replace(ez5.session.getUser().renderCard(), "top");
            return ez5.session.getUser().getTrayItems(_this);
          };
        })(this)
      }
    });
  };

  SessionTrayApp.prototype.cancelPrefsModal = function() {
    if (this.__theme_changed) {
      ez5.session.loadTheme();
    }
    return this.closePrefsModal();
  };

  SessionTrayApp.prototype.closePrefsModal = function() {
    var ref;
    if ((ref = this.modal) != null) {
      ref.destroy();
    }
    this.modal = null;
    return this;
  };

  SessionTrayApp.prototype.userRegisterModal = function() {
    return this.userPrefsModal("register");
  };

  SessionTrayApp.prototype.userSettingsModal = function() {
    return this.userPrefsModal("settings");
  };

  SessionTrayApp.prototype.userPrefsModal = function(mode) {
    var loadPromise, prefs, ref, user;
    this.__currentThemeName = (ref = ez5.cssLoader.getActiveCSS()) != null ? ref.theme : void 0;
    if (mode === "register") {
      user = new ez5.defaults["class"].AnonymousUser();
      loadPromise = CUI.when(user.load(), AdminMessage.load("self_register"));
    } else {
      user = ez5.session.user.copy(false);
      loadPromise = user.load();
    }
    prefs = ez5.session.getPrefs();
    this.__theme_changed = false;
    loadPromise.done((function(_this) {
      return function(_, selfRegisterMessages) {
        var all_required, clearPrefsButton, dataSelfRegisterMessages, f, fields, fn, i, idx, infoblock_txt, initial_data, j, k, len, len1, len2, ref1, ref2, ref3, ref4, ref5, saveButton, selfRegisterMessage, tabs, thank_you_txt, theme, theme_opts, update_btn, user_data;
        if (mode === "register") {
          infoblock_txt = ez5.loca.getBestFrontendValue((ref1 = ez5.session.getBaseConfig().self_register) != null ? ref1.introduction_text : void 0);
          thank_you_txt = ez5.loca.getBestFrontendValue((ref2 = ez5.session.getBaseConfig().self_register) != null ? ref2.thank_you_text : void 0);
          if (CUI.util.isEmpty(thank_you_txt)) {
            thank_you_txt = $$("session.tray.register.confirmation_dialog.text.md");
          }
        } else {
          infoblock_txt = ez5.loca.getBestFrontendValue((ref3 = ez5.session.getBaseConfig().self_register) != null ? ref3.welcome_text : void 0);
          if (CUI.util.isEmpty(infoblock_txt)) {
            infoblock_txt = $$("session.tray.settings.infoblock.md");
          }
          clearPrefsButton = new LocaButton({
            loca_key: "session.tray.clear_prefs.button",
            left: true,
            onClick: function() {
              return CUI.confirm({
                text: $$("session.tray.clear_prefs.confirm")
              }).done(function(confirmation, btn, ev) {
                clearPrefsButton.startSpinner();
                return ez5.session.clearPrefs(ev).always(function() {
                  clearPrefsButton.stopSpinner();
                  return _this.cancelPrefsModal();
                }).done(function() {
                  return document.location.reload();
                });
              });
            }
          });
        }
        saveButton = new LocaButton({
          loca_key: "session.tray." + mode + ".button.save",
          primary: true,
          onClick: function(ev) {
            var email, ref4, ref5;
            _this.modal.disableAllButtons();
            if (_this.__currentThemeName !== ((ref4 = ez5.cssLoader.getActiveCSS()) != null ? ref4.theme : void 0)) {
              _this.__theme_changed = true;
              delete prefs["css_developer_theme"];
              delete prefs["css_mode"];
            }
            email = ((ref5 = user.getData().user._new_primary_email) != null ? ref5.trim() : void 0) || "";
            return ez5.session.savePrefs(ev, prefs, user, mode).fail(function() {
              return _this.modal.enableAllButtons();
            }).done(function() {
              var go_on;
              if (mode === "settings") {
                go_on = function() {
                  if (_this.__theme_changed) {
                    if (CUI.util.xor(_this.__currentThemeName.startsWith("ng"), CUI.__ng__)) {
                      document.location.reload();
                      return;
                    }
                  }
                  return ez5.session.reload().always(function() {
                    _this.updateDisplay();
                    return _this.closePrefsModal();
                  });
                };
                if (email.length > 0) {
                  return CUI.alert({
                    markdown: true,
                    text: $$("session.tray.settings.new_primary_email_saved_confirmation.md", {
                      email: email
                    })
                  }).done(function() {
                    return go_on();
                  });
                } else {
                  return go_on();
                }
              } else {
                return CUI.alert({
                  title: $$("session.tray.register.confirmation_dialog.title"),
                  markdown: true,
                  text: thank_you_txt
                }).done(function() {
                  return _this.closePrefsModal();
                });
              }
            });
          }
        });
        _this.saveButtonMessage = new CUI.Label({
          "class": "ez5-session-tray-app-message",
          text: "",
          multiline: true
        });
        initial_data = null;
        update_btn = function() {
          var checkboxValue, data, e, enable, f, i, is_ok, j, len, len1, not_ok, ref4, ref5, ref6, selfRegisterMessage;
          saveButton.disable();
          enable = true;
          try {
            data = user.getLimitedSaveData(mode);
            if (initial_data === null) {
              initial_data = JSON.stringify(data);
            }
          } catch (error) {
            e = error;
            if (!(e instanceof InvalidSaveDataException)) {
              throw e;
            }
            data = {};
            enable = false;
          }
          not_ok = user.getUserSelfManagementFieldsNotOk(mode, data);
          ref4 = _this.__form.getFields();
          for (i = 0, len = ref4.length; i < len; i++) {
            f = ref4[i];
            if ((typeof f.getInputState === "function" ? f.getInputState() : void 0) === "invalid") {
              is_ok = false;
              enable = false;
            } else {
              is_ok = (ref5 = f.getName(), indexOf.call(not_ok, ref5) < 0);
            }
            if (ref6 = f.getName(), indexOf.call(all_required, ref6) < 0) {
              continue;
            }
            if (is_ok) {
              _this.__form.removeClassFromField(f.getName(), "ez5-form-field--not-ok");
              _this.__form.addClassToField(f.getName(), "ez5-form-field--ok");
            } else {
              _this.__form.addClassToField(f.getName(), "ez5-form-field--not-ok");
              _this.__form.removeClassFromField(f.getName(), "ez5-form-field--ok");
              enable = false;
            }
          }
          if (selfRegisterMessages) {
            for (j = 0, len1 = selfRegisterMessages.length; j < len1; j++) {
              selfRegisterMessage = selfRegisterMessages[j];
              checkboxValue = dataSelfRegisterMessages[selfRegisterMessage.getId()];
              if (!CUI.util.isUndef(checkboxValue) && !checkboxValue) {
                enable = false;
              }
            }
          }
          if (enable && initial_data !== JSON.stringify(data)) {
            saveButton.enable();
          }
        };
        user_data = user.getData();
        theme_opts = [];
        ref4 = Session.knownCSSThemes;
        for (i = 0, len = ref4.length; i < len; i++) {
          theme = ref4[i];
          theme_opts.push({
            text: ez5.loca.str_default("session.tray.app.theme.name." + theme, theme),
            value: theme
          });
        }
        fields = [];
        if (false && user.isAllowedLimited("theme", mode) && user.isAllowedLimited("frontend_prefs", mode)) {
          fields.push({
            type: CUI.Select,
            data: prefs,
            form: {
              label: $$("session.tray.prefs.theme")
            },
            options: theme_opts,
            onDataChanged: function() {
              var wb;
              wb = new CUI.WaitBlock({
                fullscreen: true,
                inactive: true,
                icon: "spinner"
              }).show();
              return ez5.cssLoader.loadTheme(prefs.theme).always((function(_this) {
                return function() {
                  return wb.destroy();
                };
              })(this));
            },
            name: "theme"
          });
        }
        ref5 = user.getUserSelfManagementFields(mode);
        for (idx = j = 0, len1 = ref5.length; j < len1; idx = ++j) {
          f = ref5[idx];
          if (ez5.version("6") && f.name === "mail_schedule") {
            continue;
          }
          fields.push(f);
        }
        _this.__form = new CUI.Form({
          fields: fields,
          "class": 'ez5-form--required-fields',
          render_as_grid: true,
          onDataChanged: function() {
            return update_btn();
          },
          data: user_data.user
        }).start();
        all_required = user.getUserSelfManagementFieldsNotOk(mode);
        if (selfRegisterMessages && selfRegisterMessages.length > 0) {
          selfRegisterMessages.sort(function(adminMessage) {
            return CUI.util.isEmpty(adminMessage.getConfirmationLocalized());
          });
          fields = [];
          fn = function(selfRegisterMessage) {
            return fields.push({
              type: CUI.DataFieldProxy,
              element: function() {
                var button, checkbox, confirmationMessage;
                confirmationMessage = selfRegisterMessage.getConfirmationLocalized();
                if (confirmationMessage) {
                  checkbox = new CUI.Checkbox({
                    text: confirmationMessage,
                    name: "" + (selfRegisterMessage.getId()),
                    data: dataSelfRegisterMessages,
                    disabled: true
                  });
                }
                button = new CUI.ButtonHref({
                  appearance: "link",
                  text: $$("admin.message.webfrontend_type.self_register.link-title", {
                    title: selfRegisterMessage.getTitleLocalized()
                  }),
                  onClick: function() {
                    return selfRegisterMessage.showMessage().done(function() {
                      if (checkbox != null) {
                        checkbox.enable();
                      }
                      return checkbox != null ? checkbox.activate() : void 0;
                    });
                  }
                });
                return new CUI.VerticalList({
                  content: [checkbox, button]
                });
              }
            });
          };
          for (k = 0, len2 = selfRegisterMessages.length; k < len2; k++) {
            selfRegisterMessage = selfRegisterMessages[k];
            fn(selfRegisterMessage);
          }
          dataSelfRegisterMessages = {};
          _this.__formSelfRegisterMessages = new CUI.Form({
            render_as_grid: true,
            fields: fields,
            onDataChanged: function() {
              return update_btn();
            }
          });
          _this.__formSelfRegisterMessages.start();
        }
        update_btn();
        if (ez5.version("6")) {
          tabs = new CUI.Tabs({
            tabs: [
              {
                text: $$("session.tray.settings.tab.general"),
                content: function() {
                  return [_this.__form, _this.__formSelfRegisterMessages];
                }
              }, ez5.session.user.isAllowedLimited("mail_schedule", "settings") ? {
                text: $$("session.tray.settings.tab.email_schedule"),
                content: function() {
                  return ez5.UserPreferencesPlugin.renderEmailScheduleFormForUser(user_data, function(scheduleData) {
                    return update_btn();
                  });
                }
              } : void 0, ez5.session.hasSystemRight("root", "user.write_self") ? {
                text: $$("session.tray.settings.tab.preferences"),
                content: function() {
                  return ez5.UserPreferencesPlugin.renderPreferencesFormForUser(user_data, function(formData) {
                    var key, value;
                    for (key in formData) {
                      value = formData[key];
                      prefs[key] = value;
                    }
                    return update_btn();
                  });
                }
              } : void 0
            ],
            maximize: true
          });
          _this.modal = new CUI.Modal({
            "class": "ez5-session-tray-modal-dialog ez5-session-tray--mode-" + mode,
            cancel: true,
            fill_screen_button: ez5.version("6"),
            onCancel: function() {
              return _this.cancelPrefsModal();
            },
            pane: {
              header_left: new CUI.Label({
                text: $$("session.tray." + mode + ".title")
              }),
              padded: true,
              content: function() {
                return [
                  _this.saveButtonMessage, new CUI.Label({
                    multiline: true,
                    markdown: true,
                    text: infoblock_txt,
                    "class": "cui-label-description"
                  }), tabs
                ];
              },
              footer_right: function() {
                return [clearPrefsButton, saveButton];
              }
            }
          });
        } else {
          _this.modal = new CUI.Modal({
            "class": "ez5-session-tray-modal-dialog ez5-session-tray--mode-" + mode,
            cancel: true,
            onCancel: function() {
              return _this.cancelPrefsModal();
            },
            pane: {
              header_left: new CUI.Label({
                text: $$("session.tray." + mode + ".title")
              }),
              padded: true,
              content: function() {
                return [
                  _this.saveButtonMessage, new CUI.Label({
                    multiline: true,
                    markdown: true,
                    text: infoblock_txt,
                    "class": "cui-label-description"
                  }), _this.__form, _this.__formSelfRegisterMessages
                ];
              },
              footer_right: function() {
                return [clearPrefsButton, saveButton];
              }
            }
          });
        }
        return _this.modal.show();
      };
    })(this));
    return this;
  };

  SessionTrayApp.prototype.getDisplay = function() {
    SessionTrayApp.__super__.getDisplay.call(this);
    return CUI.dom.append(this.display, this.getTrayButtons());
  };

  SessionTrayApp.prototype.updateDisplay = function() {
    CUI.dom.empty(this.display);
    return CUI.dom.append(this.display, this.getTrayButtons());
  };

  SessionTrayApp.prototype.getSortValue = function() {
    return 3;
  };

  return SessionTrayApp;

})(TrayApp);

ez5.session_ready(function() {
  ez5.sessionTray = new SessionTrayApp();
  return ez5.tray.registerApp(ez5.sessionTray);
});
// Generated by CoffeeScript 1.12.7
var DeveloperMenu,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  DeveloperMenu.prototype.readOpts = function() {
    return DeveloperMenu.__super__.readOpts.call(this);
  };

  DeveloperMenu.prototype.start = function() {
    return CUI.Events.listen({
      type: "keydown",
      capture: true,
      node: window,
      call: (function(_this) {
        return function(ev) {
          if (ev.getKeyboard() === "Control+Alt+D" && !_this.__dialog) {
            _this.showDeveloperMenu();
            return ev.stop();
          }
          if (ev.getKeyboard() === "Control+Alt+S") {
            debugger;
          }
        };
      })(this)
    });
  };

  DeveloperMenu.prototype.showDeveloperMenu = function() {
    var activeCSS, check_ok_btn, cookie_defaults, counter, current_data, data, debug_opts, dialog_ok, event_poll_field, form, i, j, k, l, len, len1, len2, len3, mode, mode_opts, ok_btn, on_off, pref_key, pref_keys, prefs_at_default, ref, ref1, reload_for_keys, secondary_server_input, server_input, server_input_cb, server_input_menu, theme, theme_opts;
    activeCSS = ez5.cssLoader.getActiveCSS();
    theme_opts = [
      {
        text: $$("developer.menu.theme.select", {
          theme: (activeCSS != null ? activeCSS.theme : void 0) || "unknown"
        }),
        value: null
      }
    ];
    ref = Session.knownCSSThemes;
    for (i = 0, len = ref.length; i < len; i++) {
      theme = ref[i];
      theme_opts.push({
        text: theme,
        value: theme
      });
    }
    mode_opts = [
      {
        text: "",
        value: null
      }
    ];
    ref1 = Start.getCSSModes();
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      mode = ref1[j];
      mode_opts.push({
        text: mode,
        value: mode
      });
    }
    if (CUI.util.isTrue(ez5.session.getClientDefault("debug"))) {
      on_off = "is_on";
    } else {
      on_off = "is_off";
    }
    debug_opts = [
      {
        text: $$("developer.menu.debug_mode_overwrite.option.from_server." + on_off),
        value: null
      }, {
        text: $$("developer.menu.debug_mode_overwrite.option.on"),
        value: "on"
      }, {
        text: $$("developer.menu.debug_mode_overwrite.option.off"),
        value: "off"
      }
    ];
    pref_keys = ["css_developer_theme", "css_mode", "plugins_load_from_remote", "plugins_remote_url", "debug_mode_overwrite", "easydb_server_url", "secondary_server_url", "easydb_server_url_history", "event_poll", "debug_locakeys"];
    reload_for_keys = ["debug_mode_overwrite", "easydb_server_url", "secondary_server_url", "plugins_load_from_remote", "plugins_remote_url", "debug_locakeys"];
    data = {};
    for (k = 0, len2 = pref_keys.length; k < len2; k++) {
      pref_key = pref_keys[k];
      data[pref_key] = ez5.session.getPref(pref_key);
    }
    if (data.easydb_server_url) {
      data.easydb_server_url_cb = true;
    } else {
      data.easydb_server_url_cb = false;
    }
    if (data.easydb_server_url !== window.easydb_server_url) {
      data.easydb_server_url = window.easydb_server_url;
      data.easydb_server_url_cb = false;
    }
    if (data.secondary_server_url !== window.secondary_server_url) {
      data.secondary_server_url = window.secondary_server_url;
      data.easydb_server_url_cb = false;
    }
    if (CUI.util.isEmpty(data.easydb_server_url)) {
      data.easydb_server_url = "";
    }
    data.__server_url = data.easydb_server_url;
    server_input = null;
    server_input_cb = null;
    server_input_menu = null;
    secondary_server_input = null;
    if (ez5.version("6.3")) {
      if (data.event_poll === true) {
        data.event_poll = "auto";
      }
    }
    current_data = CUI.util.copyObject(data, true);
    check_ok_btn = function() {
      var enable, ref2;
      enable = false;
      if (data.easydb_server_url.trim() === "") {
        server_input_cb.disable();
        data.__server_url = null;
        enable = true;
      } else {
        data.__server_url = Session.cleanServerUrl(data.easydb_server_url);
        enable = server_input.checkInput();
      }
      if (enable && ((ref2 = data.secondary_server_url) != null ? ref2.trim() : void 0) !== "") {
        enable = secondary_server_input.checkInput(data.secondary_server_url);
      }
      if (enable) {
        return ok_btn.enable();
      } else {
        return ok_btn.disable();
      }
    };
    if (ez5.version("6.3")) {
      event_poll_field = {
        type: CUI.Select,
        form: {
          label: $$("developer.menu.event_poll.label")
        },
        name: "event_poll",
        options: [
          {
            text: $$("developer.menu.event_poll.option.auto"),
            value: "auto",
            tooltip: {
              text: $$("developer.menu.event_poll.option.auto|tooltip")
            }
          }, {
            text: $$("developer.menu.event_poll.option.request"),
            value: "poll",
            tooltip: {
              text: $$("developer.menu.event_poll.option.request|tooltip")
            }
          }, {
            text: $$("developer.menu.event_poll.option.disabled"),
            value: false,
            tooltip: {
              text: $$("developer.menu.event_poll.option.disabled|tooltip")
            }
          }
        ]
      };
    } else {
      event_poll_field = {
        text: $$("developer.menu.event_poll.label"),
        type: CUI.Checkbox,
        name: "event_poll"
      };
    }
    form = new CUI.Form({
      data: data,
      undo_and_changed_support: false,
      fields: [
        {
          form: {
            label: $$("developer.menu.css_developer_theme.label")
          },
          type: CUI.Select,
          options: theme_opts,
          name: "css_developer_theme"
        }, {
          form: {
            label: $$("developer.menu.css_mode.label")
          },
          type: CUI.Select,
          options: mode_opts,
          name: "css_mode"
        }, event_poll_field, {
          text: $$("developer.menu.load_plugins_from_remote.label"),
          type: CUI.Checkbox,
          name: "plugins_load_from_remote"
        }, {
          text: $$("developer.menu.debug_loca_keys.label"),
          type: CUI.Checkbox,
          name: "debug_locakeys"
        }, {
          form: {
            label: $$("developer.menu.load_plugins_remote_url.label")
          },
          placeholder: $$("developer.menu.load_plugins_remote_url.placeholder"),
          type: CUI.Input,
          name: "plugins_remote_url"
        }, {
          form: {
            label: $$("developer.menu.debug_mode_overwrite.label")
          },
          type: CUI.Select,
          options: debug_opts,
          name: "debug_mode_overwrite"
        }, {
          type: CUI.Form,
          form: {
            label: $$("developer.menu.easydb_server_url.label")
          },
          fields: [
            {
              type: CUI.Input,
              form: {
                label: $$("developer.menu.primary_easydb_server_url.label")
              },
              name: "easydb_server_url",
              onInit: (function(_this) {
                return function(inp) {
                  var items, l, len3, ref2, url;
                  server_input = inp;
                  items = [];
                  ref2 = data.easydb_server_url_history;
                  for (l = 0, len3 = ref2.length; l < len3; l++) {
                    url = ref2[l];
                    items.push({
                      text: url,
                      value: url
                    });
                  }
                  return server_input_menu = new CUI.Menu({
                    element: inp.DOM,
                    use_element_width_as_min_width: true,
                    itemList: {
                      items: items,
                      onClick: function(ev, btn, item) {
                        server_input.setValue(item.value);
                        server_input_menu.hide();
                        return check_ok_btn();
                      }
                    }
                  });
                };
              })(this),
              onFocus: (function(_this) {
                return function() {
                  if (server_input_menu.hasItems()) {
                    return server_input_menu.show();
                  }
                };
              })(this),
              onBlur: (function(_this) {
                return function() {
                  return server_input_menu.hide();
                };
              })(this),
              checkInput: (function(_this) {
                return function(url) {
                  var e;
                  try {
                    new URL(url);
                    return true;
                  } catch (error) {
                    e = error;
                    return false;
                  }
                };
              })(this),
              placeholder: document.location.hostname,
              onDataChanged: (function(_this) {
                return function() {
                  return CUI.scheduleCallback({
                    ms: 200,
                    call: check_ok_btn
                  });
                };
              })(this)
            }, {
              form: {
                label: $$("developer.menu.secondary_easydb_server_url.label")
              },
              type: CUI.Input,
              name: "secondary_server_url",
              onInit: (function(_this) {
                return function(inp) {
                  return secondary_server_input = inp;
                };
              })(this),
              checkInput: (function(_this) {
                return function(url) {
                  var e;
                  try {
                    new URL(url);
                    return true;
                  } catch (error) {
                    e = error;
                    return false;
                  }
                };
              })(this),
              onDataChanged: (function(_this) {
                return function() {
                  return CUI.scheduleCallback({
                    ms: 200,
                    call: check_ok_btn
                  });
                };
              })(this)
            }, {
              type: CUI.Checkbox,
              onConstruct: (function(_this) {
                return function(cb) {
                  return server_input_cb = cb;
                };
              })(this),
              text: $$("developer.menu.easydb_server_url.cookie_save"),
              name: "easydb_server_url_cb"
            }
          ]
        }
      ]
    });
    dialog_ok = (function(_this) {
      return function() {
        var l, len3, ref2, ref3, reload;
        reload = false;
        for (l = 0, len3 = pref_keys.length; l < len3; l++) {
          pref_key = pref_keys[l];
          if ((pref_key === "easydb_server_url" || pref_key === "secondary_server_url") && !data.easydb_server_url_cb) {
            ez5.session.setPref(pref_key, null);
          } else {
            ez5.session.setPref(pref_key, data[pref_key]);
          }
          if (pref_key === "secondary_server_url" && !current_data[pref_key]) {
            current_data[pref_key] = "";
          }
          if (indexOf.call(reload_for_keys, pref_key) >= 0 && current_data[pref_key] !== data[pref_key]) {
            reload = true;
          }
        }
        if (current_data.easydb_server_url !== data.easydb_server_url && data.easydb_server_url) {
          CUI.util.pushOntoArray(data.easydb_server_url, data.easydb_server_url_history);
        }
        ez5.session.saveCookiePrefs();
        if (current_data.easydb_server_url !== data.easydb_server_url || current_data.easydb_server_url_cb !== data.easydb_server_url_cb) {
          if (!data.easydb_server_url_cb && data.easydb_server_url) {
            CUI.setSessionStorage("server", data.easydb_server_url);
          } else {
            CUI.setSessionStorage("server", void 0);
          }
          CUI.setSessionStorage("token", void 0);
          reload = true;
        }
        if (current_data.secondary_server_url !== data.secondary_server_url || current_data.easydb_server_url_cb !== data.easydb_server_url_cb) {
          if (!data.easydb_server_url_cb && data.secondary_server_url) {
            CUI.setSessionStorage("secondary_server_url", data.secondary_server_url);
          } else {
            CUI.setSessionStorage("secondary_server_url", void 0);
          }
          CUI.setSessionStorage("token", void 0);
          reload = true;
        }
        if (reload) {
          document.location.reload();
          return;
        }
        ez5.session.loadTheme();
        if (data.event_poll) {
          return (ref2 = ez5.eventPoller) != null ? ref2.start() : void 0;
        } else {
          return (ref3 = ez5.eventPoller) != null ? ref3.stop() : void 0;
        }
      };
    })(this);
    counter = 0;
    prefs_at_default = true;
    cookie_defaults = ez5.session.getCookieDefaultPrefs();
    for (l = 0, len3 = pref_keys.length; l < len3; l++) {
      pref_key = pref_keys[l];
      if (data[pref_key] !== cookie_defaults[pref_key]) {
        prefs_at_default = false;
      }
    }
    if (!CUI.util.isEmptyObject(CUI.getLocalStorage())) {
      prefs_at_default = false;
    }
    ok_btn = new LocaButton({
      text: $$("base.ok"),
      primary: true,
      onClick: (function(_this) {
        return function() {
          dialog_ok();
          _this.__dialog.destroy();
          return _this.__dialog = null;
        };
      })(this)
    });
    return this.__dialog = new CUI.ConfirmationDialog({
      title: $$("developer.menu.title"),
      "class": "ez5-developer-menu",
      content: form.start(),
      cancel: true,
      onHide: (function(_this) {
        return function() {
          return _this.__dialog = null;
        };
      })(this),
      buttons: [
        ez5.session.hasSystemRight("system.root") ? {
          loca_key: "developer.menu.send_testmail.button",
          secondary: true,
          onClick: (function(_this) {
            return function(ev) {
              var locaKey, useApi;
              if (ez5.version("6")) {
                useApi = "system";
                locaKey = "developer.menu.send_testmail.prompt.6.md";
              } else {
                useApi = "settings";
                locaKey = "developer.menu.send_testmail.prompt.md";
              }
              return CUI.prompt({
                title: $$("developer.menu.send_testmail.prompt.title"),
                text: $$(locaKey),
                markdown: true
              }).done(function(value) {
                return ez5.api[useApi]({
                  type: "POST",
                  api: "/sendmail/test",
                  json_data: {
                    to: value
                  }
                }).done(function() {
                  return CUI.alert({
                    text: $$("developer.menu.send_testmail.done")
                  });
                }).fail(function() {
                  return CUI.alert({
                    text: $$("developer.menu.send_testmail.failed")
                  });
                });
              });
            };
          })(this)
        } : void 0, {
          loca_key: "developer.menu.throw_error.button",
          secondary: true,
          onClick: (function(_this) {
            return function(ev) {
              if (ev.altKey()) {
                return CUI.util.assert(false, "DeveloperMenu", "This is a test Assert.");
              } else {
                throw new Error("This is a test Error.");
              }
            };
          })(this)
        }, {
          loca_key: "developer.menu.reset_local_storage.button",
          secondary: true,
          disabled: prefs_at_default,
          onClick: (function(_this) {
            return function() {
              window.localStorage.clear();
              document.location.reload();
            };
          })(this)
        }, ok_btn
      ]
    }).show();
  };

  return DeveloperMenu;

})(CUI.Element);

CUI.ready((function(_this) {
  return function() {
    return (new DeveloperMenu()).start();
  };
})(this));
// Generated by CoffeeScript 1.12.7
var DocumentationTrayApp,
  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;

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

  DocumentationTrayApp.defaultUrl = "https://docs.easydb.de";

  function DocumentationTrayApp() {
    DocumentationTrayApp.__super__.constructor.call(this);
    this.trayButton = new LocaButton({
      loca_key: "documentation.tray.app.button",
      onClick: this.__openUrl,
      appearance: "transparent-border"
    });
  }

  DocumentationTrayApp.prototype.getDisplay = function() {
    DocumentationTrayApp.__super__.getDisplay.call(this);
    CUI.dom.append(this.display, this.trayButton);
    return this.display;
  };

  DocumentationTrayApp.prototype.getSortValue = function() {
    return 1;
  };

  DocumentationTrayApp.prototype.__openUrl = function() {
    var ref, url;
    url = (ref = ez5.session.getBaseConfig().documentation) != null ? ref.tray_url : void 0;
    if (CUI.util.isEmpty(url)) {
      url = DocumentationTrayApp.defaultUrl + ("/" + (ez5.loca.culture.split("-")[0]));
    }
    return window.open(url, '_blank');
  };

  return DocumentationTrayApp;

})(TrayApp);

ez5.session_ready(function() {
  var ref;
  if ((ref = ez5.session.getBaseConfig().documentation) != null ? ref.tray_checkbox : void 0) {
    return ez5.tray.registerApp(new DocumentationTrayApp());
  }
});
// Generated by CoffeeScript 1.12.7
var SystemListManager,
  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;

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

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

  SystemListManager.submenu = function() {
    return "settings";
  };

  SystemListManager.prototype.getTreeOpts = function() {
    return {
      no_hierarchy: true
    };
  };

  SystemListManager.prototype.hasFooter = function() {
    return true;
  };

  SystemListManager.prototype.initFilterData = function() {
    return this.__filter = null;
  };

  SystemListManager.prototype.readOpts = function() {
    SystemListManager.__super__.readOpts.call(this);
    return this.initFilterData();
  };

  SystemListManager.prototype.getExtraButton = function() {};

  SystemListManager.prototype.load = function() {
    var opts, ref;
    SystemListManager.__super__.load.call(this);
    this.__lastData = null;
    this.__lastSearchOptions = null;
    this.initFilterData();
    opts = this.getTreeOpts();
    CUI.mergeMap(opts, {
      absolute: true,
      "class": "ez5-system-list-manager-list-view-edit-tree",
      fields: this.getListFields(),
      selectableRows: true,
      force_footer: true,
      rowMove: false,
      footer_left: (function(_this) {
        return function() {
          var buttons;
          if (!_this.hasFooter()) {
            return;
          }
          buttons = [_this.getPlusButton(), _this.getMinusButton(), _this.getExtraButton()];
          return buttons;
        };
      })(this)
    });
    if (((ref = opts.fields) != null ? ref.length : void 0) === 1) {
      opts.no_header = true;
    }
    if (this.loadFilter && !opts.filterManager) {
      opts.filter = (function(_this) {
        return function(filter) {
          return _this.loadFilter(filter);
        };
      })(this);
    }
    this.tree = new ListViewEditTree(opts);
    this.tree.root.canHaveChildren = (function(_this) {
      return function() {
        return _this.rootCanHaveChildren();
      };
    })(this);
    this.__layout = new CUI.HorizontalLayout({
      "class": "ez5-system-list-manager-layout ez5-event-poller ez5-" + CUI.util.toDash(CUI.util.getObjectClass(this)) + "-layout",
      left: {
        "class": "ez5-main-left",
        content: new CUI.SimplePane({
          "class": "cui-pane--window",
          title: this.getLeftTitle(),
          content: this.getTreePaneContent()
        }),
        flexHandle: this.getFlexHandle()
      },
      right: this.getRightPane()
    });
    this.loadInternal();
    this.empty();
    return this.loadTree();
  };

  SystemListManager.prototype.getFlexHandle = function() {
    var flexHandle;
    flexHandle = {
      label: this.getMenuTitle(),
      state_name: "admin-manager-left",
      hidden: false
    };
    return flexHandle;
  };

  SystemListManager.prototype.getRightPane = function() {
    return void 0;
  };

  SystemListManager.prototype.getLeftTitle = function() {
    return "getLeftTitle: overwrite me in " + this.getElementClass();
  };

  SystemListManager.prototype.getCenterTitle = function() {
    return "getCenterTitle: overwrite me " + this.getElementClass();
  };

  SystemListManager.prototype.unload = function() {
    var ref, ref1;
    SystemListManager.__super__.unload.call(this);
    if ((ref = this.tree) != null) {
      ref.destroy();
    }
    if ((ref1 = this.__layout) != null) {
      ref1.destroy();
    }
    return CUI.resolvedPromise();
  };

  SystemListManager.prototype.allow_unload = function(path, ev, info) {
    var promise, ref;
    if (!this.tree) {
      return CUI.resolvedPromise();
    }
    promise = (ref = this.tree.getSelectedNode()) != null ? typeof ref.check_deselect === "function" ? ref.check_deselect(ev) : void 0 : void 0;
    if (promise) {
      return promise;
    }
    return CUI.resolvedPromise();
  };

  SystemListManager.prototype.getTreePaneContent = function() {
    return this.tree.render();
  };

  SystemListManager.prototype.getTree = function() {
    return this.tree;
  };

  SystemListManager.prototype.getHeaderRight = function() {};

  SystemListManager.prototype.loadTree = function() {
    return this.loadList().done((function(_this) {
      return function(nodes, data1) {
        _this.nodes = nodes;
        _this.data = data1;
        _this.loadNodes();
        _this.__data_nodes = _this.tree.root.children.length;
        return _this.setStatus();
      };
    })(this));
  };

  SystemListManager.prototype.loadFilter = function(__filter, opts) {
    this.__filter = __filter;
    if (opts == null) {
      opts = {};
    }
    return this.loadList(this.__filter, opts).done((function(_this) {
      return function(nodes, data1) {
        _this.nodes = nodes;
        _this.data = data1;
        _this.loadNodes();
        _this.__data_nodes = _this.tree.root.children.length;
        return _this.setStatus();
      };
    })(this));
  };

  SystemListManager.prototype.loadInternal = function() {
    return ez5.rootLayout.replace(this.__layout, "center");
  };

  SystemListManager.prototype.getContainer = function() {
    return this.__layout.center();
  };

  SystemListManager.prototype.getLeft = function() {
    return this.__layout.left();
  };

  SystemListManager.prototype.rootCanHaveChildren = function() {
    return true;
  };

  SystemListManager.prototype.__isAlive = function() {
    if (!this.tree || this.tree.isDestroyed()) {
      return false;
    }
    if (!this.__layout || this.__layout.isDestroyed()) {
      return false;
    }
    return true;
  };

  SystemListManager.prototype.loadNodes = function() {
    if (!this.__isAlive()) {
      return;
    }
    this.tree.load_data(this.nodes);
    return this;
  };

  SystemListManager.prototype.setStatus = function() {
    var correction, i, len, navi, ref, ref1, selectedRow, selectedRows;
    if (!this.__isAlive()) {
      return;
    }
    if (this.hasFooter() && this.data) {
      correction = this.tree.root.children.length - this.__data_nodes;
      navi = SystemListManager.renderNavigation({
        loca_key_prefix: this.getNavigationLocaKeyPrefix(),
        count: this.data.count + correction,
        limit: this.data.limit + correction,
        offset: this.data.offset,
        no_record_key: this.getNoRecordLocaKey(),
        callback: (function(_this) {
          return function(offset) {
            return _this.loadFilter(_this.__filter, {
              searchOpts: {
                offset: offset
              }
            });
          };
        })(this)
      });
      this.tree.replace(navi, "footer_right");
    }
    selectedRows = this.tree.getSelectedRows();
    if (selectedRows.length === 0) {
      if ((ref = this.minusButton) != null) {
        ref.disable();
      }
    } else {
      for (i = 0, len = selectedRows.length; i < len; i++) {
        selectedRow = selectedRows[i];
        if (selectedRow && selectedRow.isDeletable()) {
          if ((ref1 = this.minusButton) != null) {
            ref1.enable();
          }
          break;
        }
      }
    }
  };

  SystemListManager.prototype.getMinusButton = function() {
    return this.minusButton = new LocaButton({
      ui: "system.list.manager.minus.button",
      loca_key: "system.list.manager.button.minus",
      icon: "minus",
      group: "plus-minus",
      "class": "btn-mini",
      onClick: (function(_this) {
        return function() {
          var ref, selectedRows;
          selectedRows = _this.tree.getSelectedRows();
          if (selectedRows.length > 1) {
            return _this.deleteRows(selectedRows);
          } else {
            return (ref = selectedRows[0]) != null ? ref["delete"]() : void 0;
          }
        };
      })(this)
    });
  };

  SystemListManager.prototype.getPlusButton = function() {
    return this.plusButton = new LocaButton({
      ui: "system-list-manager-plus-button",
      loca_key: "system.list.manager.button.plus",
      icon: "plus",
      group: "plus-minus",
      onClick: (function(_this) {
        return function() {
          _this.addRow();
          _this.setStatus();
          return _this;
        };
      })(this)
    });
  };

  SystemListManager.prototype.allowCopy = function() {
    return false;
  };

  SystemListManager.prototype.getMenuTitle = function() {
    return new CUI.Label({
      text: $$(this.label())
    });
  };

  SystemListManager.prototype.getTitle = function() {
    return new CUI.Label({
      text: $$("system.list.manager.editor.title")
    });
  };

  SystemListManager.prototype.getMissingName = function() {
    return (CUI.util.getObjectClass(this)) + ".getMissingName needs to be overwritten";
  };

  SystemListManager.prototype.addRow = function() {
    return (CUI.util.getObjectClass(this)) + ".addRow needs to be overwritten";
  };

  SystemListManager.prototype.deleteRows = function() {
    return (CUI.util.getObjectClass(this)) + ".deleteRows needs to be overwritten";
  };

  SystemListManager.prototype.getMissingLabel = function() {
    return new CUI.EmptyLabel({
      centered: true,
      text: $$("admin.systemlistmanager.empty_pane.hint", [this.getMissingName()])
    });
  };

  SystemListManager.prototype.empty = function() {
    CUI.dom.replace(this.getContainer(), this.emptyPane());
    return this;
  };

  SystemListManager.prototype.emptyPane = function() {
    return new CUI.SimplePane({
      "class": "cui-pane--window",
      title: this.getCenterTitle(),
      content: this.getMissingLabel()
    });
  };

  SystemListManager.prototype.getListSearchOptions = function(sopts, filter) {
    if (sopts == null) {
      sopts = {};
    }
  };

  SystemListManager.prototype.loadList = function(filter, opts) {
    var dfr, f, phrase, ref, ref1, sopts, str;
    if (opts == null) {
      opts = {};
    }
    CUI.Element.readOpts(opts, (CUI.util.getObjectClass(this)) + ".loadList", {
      newInstanceFunc: {
        mandatory: true,
        check: Function
      },
      searchOpts: {
        mandatory: true,
        check: "PlainObject"
      }
    });
    sopts = opts.searchOpts;
    if (!CUI.util.isEmpty(filter)) {
      ref = Search.getPhrase(filter), str = ref[0], phrase = ref[1];
      f = {
        type: "match",
        bool: "must",
        mode: "wildcard",
        phrase: phrase,
        string: str + "*"
      };
      if (CUI.util.isArray(sopts.search)) {
        sopts.search.push(f);
      } else {
        sopts.search = [f];
      }
    }
    if ((ref1 = this.__searchRequest) != null) {
      ref1.abort();
    }
    this.__lastSearchOptions = sopts;
    dfr = new CUI.Deferred();
    this.__searchRequest = ez5.api.search({
      data: {
        systemListManager: CUI.util.getObjectClass(this)
      },
      json_data: sopts
    }).always((function(_this) {
      return function() {
        return delete _this.__searchRequest;
      };
    })(this)).done((function(_this) {
      return function(data) {
        var i, len, o, objects, ref2, req;
        req = new Request(sopts);
        objects = [];
        ref2 = data.objects;
        for (i = 0, len = ref2.length; i < len; i++) {
          o = ref2[i];
          objects.push(opts.newInstanceFunc(o, req));
        }
        dfr.resolve(objects, data);
        return _this.__lastData = data;
      };
    })(this)).fail((function(_this) {
      return function() {
        _this.__lastData = null;
        return dfr.reject();
      };
    })(this));
    return dfr.promise();
  };

  SystemListManager.prototype.getLastSearchOptions = function() {
    return this.__lastSearchOptions;
  };

  SystemListManager.prototype.getLastData = function() {
    return this.__lastData;
  };

  SystemListManager.prototype.getNavigationLocaKeyPrefix = function() {
    return "result.navigation.toolbar";
  };

  SystemListManager.prototype.getNoRecordLocaKey = function() {
    return $$("system.list.manager.no_objects");
  };

  SystemListManager.renderNavigation = function(_opts) {
    var navigatorToolbar, opts;
    opts = CUI.Element.readOpts(_opts, "SystemListManager.renderNavi", {
      count: {
        mandatory: true,
        check: "Integer"
      },
      limit: {
        mandatory: true,
        check: "Integer"
      },
      offset: {
        mandatory: true,
        check: "Integer"
      },
      callback: {
        mandatory: true,
        check: Function
      },
      loca_key_prefix: {
        check: String
      },
      no_record_key: {
        check: String
      }
    });
    if (opts.count === 0) {
      return new CUI.Label({
        text: opts.no_record_key
      });
    } else {
      navigatorToolbar = new NavigationToolbar({
        loca_key_prefix: opts.loca_key_prefix,
        onLoadPage: (function(_this) {
          return function(page) {
            return opts.callback(opts.limit * (page++));
          };
        })(this)
      });
      navigatorToolbar.update(opts);
      return navigatorToolbar;
    }
  };

  return SystemListManager;

})(RootMenuApp);
// Generated by CoffeeScript 1.12.7
var SystemListHierarchyManager,
  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;

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

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

  SystemListHierarchyManager.prototype.getTreeOpts = function() {
    return {};
  };

  SystemListHierarchyManager.prototype.getNewNode = function() {
    return CUI.util.assert(false, (CUI.util.getObjectClass(this)) + ".getNewNode", "Method needs implementation.");
  };

  SystemListHierarchyManager.prototype.getPlusButton = function() {
    return this.plusButton = new LocaButton({
      icon: "plus",
      ui: "system.list.hierarchy.manager.plus.button",
      loca_key: "system.list.manager.button.plus",
      group: "plus-minus",
      menu: {
        items: (function(_this) {
          return function() {
            var click, items, nodes, selNode;
            click = function(ev, item) {
              var new_node, ret;
              if (item._value) {
                new_node = item._value.getNewChild();
                ret = item._value.addChild(new_node);
              } else {
                new_node = _this.getNewNode();
                ret = _this.tree.addNode(new_node);
              }
              ret.done(function() {
                return new_node.select().fail(function() {
                  return new_node["delete"]();
                }).done(function() {
                  _this.setStatus();
                  return new_node.scrollIntoView();
                });
              });
              return ret.fail(function() {
                return new_node["delete"]();
              });
            };
            items = [];
            selNode = _this.tree.getSelectedNode();
            if ((selNode != null ? selNode.id : void 0) && selNode.canHaveChildren()) {
              while (selNode.father) {
                items.push({
                  text: $$("system.list.hierarchy.manager.button.new", {
                    parent: selNode.getDisplayText()
                  }),
                  value: selNode,
                  ui: "system.list.hierarchy.manager.item:" + (selNode.getDisplayText()),
                  disabled: !selNode.isCreateChildAllowed(),
                  onClick: click
                });
                if (!selNode.father) {
                  break;
                }
                selNode = selNode.father;
              }
            } else {
              nodes = _this.tree.root.find(function(node) {
                return node.canHaveChildren();
              });
              if (nodes[0]) {
                items.push({
                  text: $$("system.list.hierarchy.manager.button.new", {
                    parent: nodes[0].getDisplayText()
                  }),
                  value: nodes[0],
                  ui: "system.list.hierarchy.manager.item:" + (nodes[0].getDisplayText()),
                  onClick: click
                });
              }
            }
            if (!items.length) {
              items.push({
                ui: "system.list.hierarchy.manager.item:" + (_this.getNewRootText()),
                text: _this.getNewRootText(),
                disabled: !_this.tree.root.canHaveChildren(),
                onClick: click
              });
            }
            return items.reverse();
          };
        })(this)
      }
    });
  };

  SystemListHierarchyManager.prototype.loadList = function(filter, opts) {
    var dfr, phrase, ref, ref1, sopts, str;
    if (opts == null) {
      opts = {};
    }
    CUI.util.assert(CUI.util.isFunction(opts.newInstanceFunc), "SystemListHierarchyManager", "opts.newInstanceFunc needs to be Function.", {
      opts: opts
    });
    sopts = opts.searchOpts || {};
    dfr = new CUI.Deferred();
    if (!sopts.search) {
      ref = Search.getPhrase(filter || ""), str = ref[0], phrase = ref[1];
      if (!CUI.util.isEmpty(filter)) {
        sopts.search = [
          {
            type: "match",
            bool: "should",
            mode: "wildcard",
            phrase: phrase,
            string: str + "*"
          }
        ];
      } else if (opts.parentField && opts.parentId !== void 0) {
        sopts.search = [
          {
            type: "in",
            bool: "must",
            fields: [opts.parentField],
            "in": [opts.parentId]
          }
        ];
      } else {
        sopts.search = [];
      }
    }
    CUI.mergeMap(sopts, {
      format: "short"
    });
    if ((ref1 = this.__searchRequest) != null) {
      ref1.abort();
    }
    this.__searchRequest = ez5.api.search_no_limit({
      json_data: sopts
    }).always((function(_this) {
      return function() {
        return delete _this.__searchRequest;
      };
    })(this)).done((function(_this) {
      return function(data) {
        var doOpen, idx, o, objects, req;
        req = new Request(sopts);
        if (opts.doOpen === false) {
          doOpen = false;
        } else {
          doOpen = true;
        }
        objects = _this.__getObjectsFromData(data, opts);
        if (!CUI.util.isEmpty(filter) || opts.buildTree) {
          objects = ez5.buildObjectTree({
            objects: objects,
            objectKey: opts.objectKey,
            doOpen: doOpen,
            newInstanceFunc: function(o) {
              return opts.newInstanceFunc(o, req);
            }
          });
        } else {
          objects = (function() {
            var i, len, results;
            results = [];
            for (idx = i = 0, len = objects.length; i < len; idx = ++i) {
              o = objects[idx];
              results.push(opts.newInstanceFunc(o, req));
            }
            return results;
          })();
        }
        return dfr.resolve(objects, data);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  SystemListHierarchyManager.prototype.__getObjectsFromData = function(data) {
    return data.objects;
  };

  return SystemListHierarchyManager;

})(SystemListManager);
// Generated by CoffeeScript 1.12.7
var FieldsForm,
  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;

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

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

  FieldsForm.prototype.initOpts = function() {
    FieldsForm.__super__.initOpts.call(this);
    return this.addOpts({
      otm: {
        mandatory: true,
        check: ObjecttypeManager
      },
      data: {
        mandatory: true,
        check: "PlainObject"
      },
      treeNodeClass: {
        mandatory: true,
        check: function(v) {
          return v instanceof Function;
        }
      },
      treeOpts: {
        mandatory: true,
        "default": {},
        check: "PlainObject"
      },
      formWrapper: {
        check: XMLFormWrapper
      },
      exportManagerEasydb: {
        check: ExportManagerEasydb
      },
      acceptField: {
        mandatory: true,
        check: Function,
        "default": function(field) {
          return !(field instanceof MaskSplitter);
        }
      },
      headerNode: {
        check: Function,
        "default": null
      }
    });
  };

  FieldsForm.prototype.readOpts = function() {
    FieldsForm.__super__.readOpts.call(this);
    this.otm = this._otm;
    this.data = this._data;
    this.treeNodeClass = this._treeNodeClass;
    this.treeOpts = this._treeOpts;
    return this;
  };

  FieldsForm.prototype.getTreeOpts = function(opts) {
    var k, ref, treeOpts, v;
    treeOpts = {};
    ref = this.treeOpts;
    for (k in ref) {
      v = ref[k];
      treeOpts[k] = v;
    }
    for (k in opts) {
      v = opts[k];
      if (!treeOpts.hasOwnProperty(k)) {
        treeOpts[k] = v;
      }
    }
    return treeOpts;
  };

  FieldsForm.prototype.renderForm = function() {
    var add_field_to_children, divExportManagerOtFormCommonTitle, divExportManagerOtFormMaskTitle, div_common, div_unique, f, form_fields, i, idx, j, l, len, len1, len2, len3, len4, m, n, o, ot, ot_form, ots, panel, ref, ref1, ref2, ref3, t, tn, top_level_fields, top_level_fields_by_name, tree_options, unique_masks;
    this.__nodes = [];
    form_fields = CUI.dom.div("export-manager-form-fields cui-flex-container");
    top_level_fields = [];
    top_level_fields_by_name = {};
    add_field_to_children = (function(_this) {
      return function(children, opts) {
        var i, len, sf, standardVersionsFields, treeNode;
        if (ez5.version("6")) {
          if (opts.field instanceof StandardField && !opts.isStandard) {
            standardVersionsFields = StandardField.getExportFields(opts.field);
            for (i = 0, len = standardVersionsFields.length; i < len; i++) {
              sf = standardVersionsFields[i];
              add_field_to_children(children, {
                field: sf,
                data: _this.data,
                formWrapper: _this._formWrapper,
                exportManagerEasydb: _this._exportManagerEasydb,
                acceptField: _this._acceptField,
                isStandard: true
              });
            }
            return;
          }
          if (opts.isStandard) {
            delete opts.isStandard;
          }
        }
        if (!_this._acceptField(opts.field, null, 0)) {
          return;
        }
        if (!opts.field.isValidMappingField(0)) {
          return;
        }
        if (opts.field.isTopLevelField()) {
          if (!top_level_fields_by_name[opts.field.name()]) {
            top_level_fields_by_name[opts.field.name()] = true;
            treeNode = new _this.treeNodeClass(opts);
            top_level_fields.push(treeNode);
            treeNode.nodeAdded();
            return _this.__nodes.push(treeNode);
          } else {

          }
        } else {
          treeNode = new _this.treeNodeClass(opts);
          children.push(treeNode);
          treeNode.nodeAdded();
          return _this.__nodes.push(treeNode);
        }
      };
    })(this);
    ots = [];
    ref = this.otm.getObjecttypes();
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      if (ot.getInstance()) {
        continue;
      }
      ots.push(ot);
    }
    ots.sort(function(a, b) {
      return a.nameLocalized().localeCompare(b.nameLocalized());
    });
    for (j = 0, len1 = ots.length; j < len1; j++) {
      ot = ots[j];
      ot_form = CUI.dom.div("export-manager-ot-form fields-form-ot-form form-is-open");
      unique_masks = [];
      ref1 = ot.masks;
      for (l = 0, len2 = ref1.length; l < len2; l++) {
        m = ref1[l];
        if (!m.uniqueFields.length) {
          continue;
        }
        div_unique = CUI.dom.div("export-manager-ot-form-mask");
        tn = [];
        ref2 = m.uniqueFields;
        for (idx = n = 0, len3 = ref2.length; n < len3; idx = ++n) {
          f = ref2[idx];
          if (f.depth() > 0) {
            continue;
          }
          add_field_to_children(tn, {
            field: f,
            data: this.data,
            formWrapper: this._formWrapper,
            exportManagerEasydb: this._exportManagerEasydb,
            acceptField: this._acceptField
          });
        }
        if (tn.length) {
          unique_masks.push(m);
          t = new CUI.ListViewTree(this.getTreeOpts({
            children: tn
          }));
          divExportManagerOtFormMaskTitle = CUI.dom.div("export-manager-ot-form-mask-title");
          divExportManagerOtFormMaskTitle.textContent = m.nameLocalized();
          CUI.dom.append(div_unique, divExportManagerOtFormMaskTitle);
          CUI.dom.append(div_unique, t.render());
          CUI.dom.append(ot_form, div_unique);
          t.root.open();
        }
      }
      if (ot.commonFields.length) {
        div_common = CUI.dom.div("export-manager-ot-form-common");
        if (unique_masks.length > 0) {
          divExportManagerOtFormCommonTitle = CUI.dom.div("export-manager-ot-form-common-title");
          divExportManagerOtFormCommonTitle.textContent = "In allen oder mehreren Masken";
          CUI.dom.append(div_common, divExportManagerOtFormCommonTitle);
        }
        tn = [];
        ref3 = ot.commonFields;
        for (o = 0, len4 = ref3.length; o < len4; o++) {
          f = ref3[o];
          if (f.depth() > 0) {
            continue;
          }
          add_field_to_children(tn, {
            field: f,
            data: this.data,
            formWrapper: this._formWrapper,
            exportManagerEasydb: this._exportManagerEasydb,
            acceptField: this._acceptField
          });
        }
        if (tn.length) {
          tree_options = this.getTreeOpts({
            children: tn
          });
          t = new CUI.ListViewTree(tree_options);
          CUI.dom.append(div_common, t.render());
          CUI.dom.append(ot_form, div_common);
          t.root.open();
        }
      }
      if (ot_form.children.length) {
        panel = new CUI.Panel({
          ui: "fields-form-panel-" + (ot.name()),
          text: ot.nameLocalized(),
          content: ot_form
        });
        CUI.dom.append(form_fields, panel.DOM);
      }
    }
    if (this._headerNode) {
      top_level_fields.splice(0, 0, this._headerNode());
    }
    tree_options = this.getTreeOpts({
      children: top_level_fields,
      fixedRows: 1
    });
    this.__tree = new CUI.ListViewTree(tree_options);
    CUI.dom.prepend(form_fields, this.__tree.render());
    return form_fields;
  };

  FieldsForm.prototype.open = function() {
    CUI.util.assert(this.__tree, "FieldsForm.open", "Cannot open before .renderForm was called.", {
      fieldsForm: this
    });
    return this.__tree.root.open();
  };

  FieldsForm.prototype.isValid = function() {
    return this.__nodes.every((function(_this) {
      return function(node) {
        return node.isValid();
      };
    })(this));
  };

  FieldsForm.prototype.getNodes = function() {
    return this.__nodes;
  };

  return FieldsForm;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var FieldsFormNode,
  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;

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

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

  FieldsFormNode.prototype.readOpts = function() {
    FieldsFormNode.__super__.readOpts.call(this);
    return this.field = this._field;
  };

  FieldsFormNode.prototype.initOpts = function() {
    FieldsFormNode.__super__.initOpts.call(this);
    return this.addOpts({
      data: {
        mandatory: true,
        check: "PlainObject"
      },
      formWrapper: {
        check: XMLFormWrapper
      },
      acceptField: {
        mandatory: true,
        check: Function,
        "default": function(field, fieldsFormNodeFather) {
          return !(field instanceof MaskSplitter);
        }
      },
      field: {
        mandatory: true,
        check: function(v) {
          return v instanceof Field || v instanceof MaskSplitter;
        }
      }
    });
  };

  FieldsFormNode.prototype.getModeForNested = function() {
    return CUI.util.assert(false, "FieldsFormNode.getModeForNested", "Needs to be overwritten.");
  };

  FieldsFormNode.prototype.nodeAdded = function(level) {
    var childField, fieldTreeNode, i, j, k, len, len1, len2, nestedField, ref, ref1, ref2, renderDepth, sf, tn;
    if (level == null) {
      level = 0;
    }
    if (level > 1) {
      return;
    }
    if (this.field instanceof NestedTable && !(this.field instanceof ez5.ParentsNestedTable) && !this.field.FieldSchema.hierarchical_mask_hint) {
      ref = this.field.mask.getFields(this.getModeForNested());
      for (i = 0, len = ref.length; i < len; i++) {
        nestedField = ref[i];
        if (!this._acceptField(nestedField, this, level)) {
          continue;
        }
        if (!nestedField.isValidMappingField(level + 1, this.field)) {
          continue;
        }
        tn = new window[CUI.util.getObjectClass(this)]({
          field: nestedField,
          formWrapper: this._formWrapper,
          acceptField: this._acceptField,
          exportManagerEasydb: this._exportManagerEasydb,
          data: this._data
        });
        this.addChild(tn);
        tn.nodeAdded(level);
      }
    }
    if (!this.field.hasMappingChildFields()) {
      return;
    }
    if (this.field instanceof CustomDataType && this.getModeForNested() === "export" && !ez5.version("6")) {
      return;
    }
    ref1 = this.field.getMappingChildFields(this.getModeForNested(), this);
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      childField = ref1[j];
      if (!this._acceptField(childField, this, level)) {
        continue;
      }
      if (!childField.isValidMappingField(level + 1, this.field)) {
        continue;
      }
      if (childField instanceof StandardField && ez5.version("6")) {
        ref2 = StandardField.getExportFields(childField);
        for (k = 0, len2 = ref2.length; k < len2; k++) {
          sf = ref2[k];
          fieldTreeNode = new window[CUI.util.getObjectClass(this)]({
            field: sf,
            formWrapper: this._formWrapper,
            exportManagerEasydb: this._exportManagerEasydb,
            acceptField: this._acceptField,
            data: this._data
          });
          this.addChild(fieldTreeNode);
          fieldTreeNode.nodeAdded(level);
        }
        continue;
      }
      fieldTreeNode = new window[CUI.util.getObjectClass(this)]({
        field: childField,
        formWrapper: this._formWrapper,
        exportManagerEasydb: this._exportManagerEasydb,
        acceptField: this._acceptField,
        data: this._data
      });
      if (this.field instanceof LinkedObject) {
        renderDepth = this.getLinkedObjectRenderDepth();
        if (level <= renderDepth || (level <= renderDepth + 1 && fieldTreeNode.field.isSystemField())) {
          this.addChild(fieldTreeNode);
          fieldTreeNode.nodeAdded(level + 1);
        }
      } else {
        this.addChild(fieldTreeNode);
        fieldTreeNode.nodeAdded(level);
      }
    }
  };

  FieldsFormNode.prototype.getLinkedObjectRenderDepth = function() {
    return 0;
  };

  FieldsFormNode.prototype.dumpString = function() {
    var cn;
    cn = CUI.util.getObjectClass(this.field);
    if (this.field instanceof LinkedObject) {
      cn += " (" + this.field.linkMask().table.name() + ")";
    }
    return this.field.name() + " [" + cn + "] " + this.fullFieldName();
  };

  FieldsFormNode.prototype.fullFieldName = function(for_path) {
    var fullFieldName;
    if (for_path == null) {
      for_path = false;
    }
    if (this.father instanceof FieldsFormNode) {
      fullFieldName = this.father.fullFieldName(true) + "." + this.__fieldName(for_path);
    } else if (this.field.isTopLevelField()) {
      fullFieldName = this.__fieldName(for_path);
    } else {
      fullFieldName = this.field.getMainMask().table.name() + "." + this.__fieldName(for_path);
    }
    return fullFieldName;
  };

  FieldsFormNode.prototype.__fieldName = function(for_path) {
    var fn, ref;
    if (for_path == null) {
      for_path = false;
    }
    if (for_path) {
      fn = this.field.name();
    } else {
      fn = this.field.getMappingTargetName();
    }
    if (((ref = this.father) != null ? ref.field : void 0) instanceof LinkedObject && !this.field.isTopLevelField()) {
      return this.field.getMainMask().table.name() + "." + fn;
    } else {
      return fn;
    }
  };

  FieldsFormNode.prototype.isValid = function() {
    return true;
  };

  return FieldsFormNode;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var BasicFieldsFormNode,
  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;

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

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

  BasicFieldsFormNode.prototype.setChildren = function(enable_disable) {
    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(enable_disable);
      results.push(c.setChildren(enable_disable));
    }
    return results;
  };

  BasicFieldsFormNode.prototype.setCheckbox = function(enable_disable) {
    var ref;
    if (this.data._disabled) {
      enable_disable = false;
    }
    this.data._enabled = enable_disable;
    if ((ref = this.checkbox) != null) {
      ref.displayValue();
    }
    if (!this.isOpen()) {
      this.setChildren(enable_disable);
    }
    return this;
  };

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

  BasicFieldsFormNode.prototype.removeFromDOM = function(remove_self) {
    if (remove_self == null) {
      remove_self = true;
    }
    BasicFieldsFormNode.__super__.removeFromDOM.call(this, remove_self);
    this.checkbox = null;
    return this;
  };

  BasicFieldsFormNode.prototype.nodeAdded = function(level) {
    BasicFieldsFormNode.__super__.nodeAdded.call(this, level);
    if (!this._data[this.fullFieldName()]) {
      this._data[this.fullFieldName()] = {
        _enabled: this.__getDefaultEnabled()
      };
      if (this.field instanceof NestedTable) {
        this._data[this.fullFieldName()].display_name = this.field.name().replace(/^(_reverse)?_nested:/, "");
      } else {
        this._data[this.fullFieldName()].display_name = this.field.name();
      }
    } else if (!this._data[this.fullFieldName()].hasOwnProperty("_enabled")) {
      this._data[this.fullFieldName()]._enabled = true;
    }
    this._data[this.fullFieldName()]._nameLocalized = this.field.nameLocalized();
    this.data = this._data[this.fullFieldName()];
  };

  BasicFieldsFormNode.prototype.fieldIsDisabled = function() {
    var ref;
    return this.data._disabled || ((ref = this.father) != null ? typeof ref.fieldIsDisabled === "function" ? ref.fieldIsDisabled() : void 0 : void 0) || false;
  };

  BasicFieldsFormNode.prototype.__getNameInput = function() {
    return new CUI.Input(this.__getNameInputOpts());
  };

  BasicFieldsFormNode.prototype.renderContent = function() {
    var checkIndeterminate, nameLocalizedOutput, row;
    this.checkbox = new CUI.Checkbox({
      name: "_enabled",
      group: "basic-group-" + (this.level()),
      undo_and_changed_support: false,
      data: this.data,
      disabled: this.fieldIsDisabled(),
      onDataChanged: (function(_this) {
        return function() {
          if (_this.data._enabled && _this.__isNameInputEditable()) {
            _this.__nameInput.enable();
          } else {
            _this.__nameInput.disable();
          }
          return _this.setCheckbox(_this.data._enabled);
        };
      })(this)
    });
    this.checkbox.start();
    nameLocalizedOutput = new CUI.Output(this.__getNameOutputOpts());
    nameLocalizedOutput.start();
    this.__nameInput = this.__getNameInput();
    this.__nameInput.start();
    row = CUI.dom.table_one_row(this.checkbox, nameLocalizedOutput, this.__nameInput);
    if (this.data._disabled) {
      this.data._enabled = false;
    }
    checkIndeterminate = (function(_this) {
      return function(children) {
        var countEnabled, enabledNodes, totalNodes;
        if (!children) {
          return false;
        }
        totalNodes = 0;
        enabledNodes = 0;
        countEnabled = function(children) {
          var child, i, len, ref;
          ref = children || [];
          for (i = 0, len = ref.length; i < len; i++) {
            child = ref[i];
            if (child.children) {
              countEnabled(child.children);
            }
            totalNodes++;
            if (child.data._enabled) {
              enabledNodes++;
            }
            if (totalNodes > enabledNodes && enabledNodes > 0) {
              return;
            }
          }
        };
        countEnabled(children);
        return totalNodes > enabledNodes && enabledNodes > 0;
      };
    })(this);
    if (checkIndeterminate(this.children)) {
      this.checkbox.setIndeterminate();
    }
    return row;
  };

  BasicFieldsFormNode.prototype.open = function() {
    return BasicFieldsFormNode.__super__.open.call(this).done((function(_this) {
      return function() {
        var ref, ref1;
        if ((ref = _this.checkbox) != null) {
          ref.removeIndeterminate();
        }
        return (ref1 = _this.checkbox) != null ? ref1.reload() : void 0;
      };
    })(this));
  };

  BasicFieldsFormNode.prototype.isValid = function() {
    var isValid;
    if (!this.data["_enabled"]) {
      return true;
    }
    isValid = this.__nameInput.getInputState() === "valid";
    if (!this.children) {
      return isValid;
    }
    return isValid && this.children.every((function(_this) {
      return function(child) {
        return child.isValid();
      };
    })(this));
  };

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

  BasicFieldsFormNode.prototype.__getNameInputOpts = function() {
    var opts;
    opts = {
      undo_and_changed_support: false,
      name: "display_name",
      data: this.data,
      disabled: !this.__isNameInputEditable() || this.fieldIsDisabled() || !this.data._enabled
    };
    return opts;
  };

  BasicFieldsFormNode.prototype.__getNameOutputOpts = function() {
    var opts;
    opts = {
      name: "_nameLocalized",
      data: this.data,
      disabled: this.fieldIsDisabled()
    };
    return opts;
  };

  BasicFieldsFormNode.prototype.__getDefaultEnabled = function() {
    return true;
  };

  BasicFieldsFormNode.prototype.__isNameInputEditable = function() {
    return true;
  };

  return BasicFieldsFormNode;

})(FieldsFormNode);
// Generated by CoffeeScript 1.12.7
var PrintFieldsFormNode,
  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;

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

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

  PrintFieldsFormNode.prototype.__isNameInputEditable = function() {
    return false;
  };

  PrintFieldsFormNode.prototype.getLinkedObjectRenderDepth = function() {
    return 5;
  };

  PrintFieldsFormNode.prototype.fullFieldName = function() {
    return this.getFieldFullName();
  };

  return PrintFieldsFormNode;

})(BasicFieldsFormNode);
// Generated by CoffeeScript 1.12.7
var PoolsFormNode,
  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;

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

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

  PoolsFormNode.prototype.readOpts = function() {
    PoolsFormNode.__super__.readOpts.call(this);
    return this.field = this._field;
  };

  PoolsFormNode.prototype.initOpts = function() {
    PoolsFormNode.__super__.initOpts.call(this);
    return this.addOpts({
      data: {
        mandatory: true,
        check: "PlainObject"
      },
      pool: {
        check: function(v) {
          return v instanceof Pool;
        }
      }
    });
  };

  PoolsFormNode.prototype.getModeForNested = function() {
    return CUI.util.assert(false, "FieldsFormNode.getModeForNested", "Needs to be overwritten.");
  };

  PoolsFormNode.prototype.fieldHasChildNodes = function() {
    return this.field instanceof LinkedObject || this.field instanceof CustomDataType;
  };

  PoolsFormNode.prototype.onCheckboxValueChanged = function() {
    var child, i, len, ref, results, setChildrenCheckbox;
    setChildrenCheckbox = (function(_this) {
      return function(child, value) {
        var i, len, ref, ref1, subchild;
        if (child.children) {
          ref = child.children;
          for (i = 0, len = ref.length; i < len; i++) {
            subchild = ref[i];
            setChildrenCheckbox(subchild, value);
          }
        }
        _this._data["" + (child._pool.getId())] = value;
        return (ref1 = child.checkbox) != null ? ref1.reload() : void 0;
      };
    })(this);
    if (!this.children) {
      return;
    }
    ref = this.children;
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      child = ref[i];
      results.push(setChildrenCheckbox(child, this.checkbox.getValue()));
    }
    return results;
  };

  PoolsFormNode.prototype.renderContent = function() {
    this.checkbox = new CUI.Checkbox({
      name: "" + (this._pool.getId()),
      group: "pools",
      undo_and_changed_support: false,
      data: this._data,
      disabled: false,
      text: this._pool.getDisplayText(),
      onDataChanged: (function(_this) {
        return function() {
          return _this.onCheckboxValueChanged();
        };
      })(this)
    }).start();
    return this.checkbox;
  };

  PoolsFormNode.prototype.isActive = function() {
    return this._data["" + (this._pool.getId())];
  };

  PoolsFormNode.prototype.isValid = function() {
    return true;
  };

  return PoolsFormNode;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var PoolsForm,
  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;

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

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

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

  PoolsForm.prototype.readOpts = function() {
    PoolsForm.__super__.readOpts.call(this);
    this.data = this.loadData();
    this.treeNodeClass = this._treeNodeClass;
    this.treeOpts = this._treeOpts;
    return this;
  };

  PoolsForm.prototype.getSaveData = function() {
    var k, ref, saveData, v;
    saveData = {
      ids: []
    };
    ref = this.data;
    for (k in ref) {
      v = ref[k];
      if (v) {
        saveData.ids.push(k);
      }
    }
    return saveData;
  };

  PoolsForm.prototype.loadData = function() {
    var data, i, len, poolId, ref;
    data = {};
    if (!this._data.ids) {
      return data;
    }
    ref = this._data.ids;
    for (i = 0, len = ref.length; i < len; i++) {
      poolId = ref[i];
      data[poolId] = true;
    }
    return data;
  };

  PoolsForm.prototype.getTreeOpts = function(opts) {
    var k, ref, treeOpts, v;
    treeOpts = {};
    ref = this.treeOpts;
    for (k in ref) {
      v = ref[k];
      treeOpts[k] = v;
    }
    for (k in opts) {
      v = opts[k];
      if (!treeOpts.hasOwnProperty(k)) {
        treeOpts[k] = v;
      }
    }
    return treeOpts;
  };

  PoolsForm.prototype.renderForm = function() {
    var filterInput, filterTree, form_fields, getPoolFormNode, nodeMustBeOpened, root;
    this.pool_rows = [];
    this.__nodes = [];
    form_fields = CUI.dom.div("pools-form-wrapper");
    this.__treeWrapper = CUI.dom.div("pools-tree-wrapper");
    root = ez5.pools.getRootPool();
    this.pool_rows = [root];
    nodeMustBeOpened = (function(_this) {
      return function(force, childrenNodes) {
        var child, i, len;
        if (force == null) {
          force = false;
        }
        if (force) {
          return true;
        }
        if (!childrenNodes) {
          return false;
        }
        for (i = 0, len = childrenNodes.length; i < len; i++) {
          child = childrenNodes[i];
          if (child.isActive()) {
            return true;
          } else if (child.children) {
            if (nodeMustBeOpened(false, child.children)) {
              return true;
            }
          }
        }
        return false;
      };
    })(this);
    getPoolFormNode = (function(_this) {
      return function(pools, filter, root) {
        var children, i, len, node_opts, pool, poolsFormNodes;
        if (filter == null) {
          filter = null;
        }
        if (root == null) {
          root = true;
        }
        poolsFormNodes = [];
        if (!pools) {
          return null;
        }
        for (i = 0, len = pools.length; i < len; i++) {
          pool = pools[i];
          children = getPoolFormNode(pool.children, filter, false);
          if (!root && filter && !pool.getDisplayText().toLowerCase().includes(filter.toLowerCase())) {
            if (children) {
              poolsFormNodes = poolsFormNodes.concat(children);
            }
            continue;
          }
          node_opts = {
            pool: pool,
            data: _this.data,
            open: nodeMustBeOpened(!CUI.util.isEmpty(filter), children)
          };
          if (children) {
            node_opts.children = children;
          }
          poolsFormNodes.push(new PoolsFormNode(node_opts));
        }
        return poolsFormNodes;
      };
    })(this);
    filterTree = (function(_this) {
      return function() {
        var filteredPools;
        filteredPools = getPoolFormNode(_this.pool_rows, _this.__inputFilterData.filter);
        _this.__filteredTree = new CUI.ListViewTree(_this.getTreeOpts({
          root: filteredPools[0],
          maximize_horizontal: true,
          maximize_vertical: false,
          selectableRows: false
        }));
        CUI.dom.replace(_this.__treeWrapper, _this.__filteredTree.render());
        return _this.__filteredTree.root.open();
      };
    })(this);
    this.__inputFilterData = {};
    CUI.dom.prepend(form_fields, this.__treeWrapper);
    filterInput = new CUI.Input({
      placeholder: $$("facet.popover.placeholder"),
      name: "filter",
      "class": "ez5-quicksearch-input",
      maximize_horizontal: true,
      data: this.__inputFilterData,
      onKeyup: (function(_this) {
        return function(df, ev) {
          return filterTree();
        };
      })(this)
    });
    CUI.dom.prepend(form_fields, filterInput.start());
    filterTree();
    return form_fields;
  };

  PoolsForm.prototype.isValid = function() {
    return this.__nodes.every((function(_this) {
      return function(node) {
        return node.isValid();
      };
    })(this));
  };

  PoolsForm.prototype.getNodes = function() {
    return this.__nodes;
  };

  return PoolsForm;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var ListViewEditTree,
  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;

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

  function ListViewEditTree(opts) {
    var field, i, idx, j, len, len1, num_fixed_columns, ref, ref1, ref2, ref3;
    if (opts == null) {
      opts = {};
    }
    this.load_data = bind(this.load_data, this);
    if (CUI.util.isUndef(opts.rowMove)) {
      opts.rowMove = true;
    }
    if (opts.rowMode && CUI.util.isUndef(opts.rowMoveWithinNodesOnly)) {
      opts.rowMoveWithinNodesOnly = true;
    }
    if (opts.fields) {
      if (opts.no_header) {
        opts.fixedRows = 0;
      } else {
        opts.fixedRows = 1;
      }
    } else {
      opts.fixedRows = 0;
    }
    if (opts.extra_header) {
      opts.fixedRows++;
    }
    if (opts.extra_header_below) {
      opts.fixedRows++;
    }
    CUI.util.assert(!opts.search || CUI.util.isFunction(opts.search), "new ListViewEditTree", "opts.search needs to be empty or Function");
    CUI.util.assert(!(opts.filter && opts.filterManager), "new ListViewEditTree", "opts.filter and opts.filterManager are mutually exclusive.", {
      opts: opts
    });
    if (opts.filter) {
      opts.header_center = ListViewEditTree.getFilterManager(opts.filter);
    }
    if (opts.filterManager) {
      opts.header_center = opts.filterManager();
    }
    if (opts.fields) {
      this.fields = opts.fields;
      CUI.util.assert(((ref = this.fields) != null ? ref.length : void 0) > 0, "new " + (CUI.util.getObjectClass(this)), "opts.fields must be an non-empty Array or opts.no_header and opts.cols must be given.", {
        opts: opts
      });
    } else {
      CUI.util.assert(((ref1 = opts.cols) != null ? ref1.length : void 0) > 0, "new " + (CUI.util.getObjectClass(this)), "opts.cols must be an non-empty Array, if opts.fields are not given.", {
        opts: opts
      });
    }
    if (!opts.cols) {
      opts.cols = [];
      num_fixed_columns = 0;
      if (opts.fixedCols) {
        num_fixed_columns = opts.fixedCols;
      }
      ref2 = this.fields;
      for (idx = i = 0, len = ref2.length; i < len; idx = ++i) {
        field = ref2[idx];
        if (idx === num_fixed_columns && opts.maximize !== false) {
          opts.cols.push("maximize");
        } else {
          opts.cols.push("auto");
        }
      }
    } else {
      CUI.util.assert(!this.fields || this.fields.length === opts.cols.length, "new ListViewEditTree", "opts.fields must be of same length as opts.cols", {
        opts: opts
      });
    }
    if (!opts.colClasses && this.fields) {
      opts.colClasses = [];
      ref3 = this.fields;
      for (idx = j = 0, len1 = ref3.length; j < len1; idx = ++j) {
        field = ref3[idx];
        opts.colClasses[idx] = [];
        if (field.th_label) {
          opts.colClasses[idx].push("ez5-col-" + field.th_label.replace(/\./g, "-"));
        }
        if (field.th_rotate_90) {
          opts.colClasses[idx].push("cui-lv-td-rotate-90");
        }
      }
    }
    ListViewEditTree.__super__.constructor.call(this, opts);
  }

  ListViewEditTree.prototype.initOpts = function() {
    ListViewEditTree.__super__.initOpts.call(this);
    this.addOpts({
      filter: {
        check: Function
      },
      filterManager: {
        check: Function
      },
      no_header: {
        check: Boolean
      },
      extra_header: {
        check: (function(_this) {
          return function(v) {
            return CUI.util.isArray(v) || v instanceof CUI.ListViewHeaderRow;
          };
        })(this)
      },
      extra_header_below: {
        check: Boolean
      },
      end_add_row: {
        check: Function
      },
      fields: {
        check: "Array"
      },
      onSort: {
        check: Function
      },
      onRender: {
        check: Function
      }
    });
    return this.removeOpt("getChildren");
  };

  ListViewEditTree.prototype.readOpts = function() {
    ListViewEditTree.__super__.readOpts.call(this);
    return this.__isLoaded = false;
  };

  ListViewEditTree.prototype.isLoaded = function() {
    return this.__isLoaded;
  };

  ListViewEditTree.prototype.render = function() {
    var content;
    content = ListViewEditTree.__super__.render.call(this, false);
    if (typeof this._onRender === "function") {
      this._onRender(this);
    }
    return content;
  };

  ListViewEditTree.prototype.load_data = function(nodes) {
    var child, childTwo, i, j, len, len1, ref, ref1, ref2;
    this.nodes = nodes;
    if ((ref = this.__layout) != null ? ref.isDestroyed() : void 0) {
      return CUI.rejectedPromise();
    }
    if (this.isLoaded()) {
      ref1 = this.root.children;
      for (i = 0, len = ref1.length; i < len; i++) {
        child = ref1[i];
        ref2 = child.find();
        for (j = 0, len1 = ref2.length; j < len1; j++) {
          childTwo = ref2[j];
          childTwo.destroy();
        }
      }
      this.root.removeFromDOM(false);
    } else {
      if (this._extra_header) {
        if (this._extra_header instanceof CUI.ListViewHeaderRow) {
          this.appendRow(this._extra_header);
        } else {
          this.addHeader(this._extra_header);
        }
      }
      if (!this.opts.no_header && this.fields) {
        this.addHeader(this.fields);
      }
      this.__isLoaded = true;
    }
    this.root.children = this.nodes;
    return this.root.open();
  };

  ListViewEditTree.prototype.addHeader = function(fields) {
    var field, header, i, idx, len, loca_key, ref, resizable, text;
    this.__currentSort = "";
    this.__currentSortButton = null;
    header = new CUI.ListViewHeaderRow();
    for (idx = i = 0, len = fields.length; i < len; idx = ++i) {
      field = fields[idx];
      if (field === null) {
        header.addColumn(new CUI.ListViewColumnEmpty());
      } else {
        if (field.th_label) {
          loca_key = field.th_label;
        } else if (field.th_text) {
          text = field.th_text;
        } else if (field.label) {
          loca_key = field.label;
        } else {
          text = field.text;
        }
        if ((ref = field.sortable) != null ? ref.key : void 0) {
          header.addColumn(this.__getSortableHeaderColumn(field.sortable, text, loca_key));
        } else {
          resizable = field.resizable !== false;
          header.addColumn(new CUI.ListViewHeaderColumn({
            spacer: idx === 0,
            colspan: field.th_colspan,
            rotate_90: field.th_rotate_90,
            "class": field["class"],
            resizable: resizable,
            label: {
              loca_key: loca_key,
              text: text
            }
          }));
        }
      }
    }
    return this.appendRow(header);
  };

  ListViewEditTree.prototype.__getSortableHeaderColumn = function(sortable, text, loca_key) {
    var button, key, order;
    key = sortable.key, order = sortable.order;
    text = text || $$(loca_key);
    button = new LocaButton({
      text: text,
      appearance: "link",
      right: true,
      onClick: (function(_this) {
        return function() {
          if (_this.__currentSort.endsWith("DESC")) {
            _this.__currentSort = key + ".ASC";
            order = "ASC";
          } else {
            _this.__currentSort = key + ".DESC";
            order = "DESC";
          }
          _this.__updateSortButtons(button);
          if (typeof _this._onSort === "function") {
            _this._onSort(key, order);
          }
        };
      })(this)
    });
    if (order) {
      this.__currentSort = order;
      this.__updateSortButtons(button);
    }
    return new CUI.ListViewHeaderColumn({
      element: button
    });
  };

  ListViewEditTree.prototype.__updateSortButtons = function(button) {
    var ref;
    if (this.__currentSortButton !== button) {
      if ((ref = this.__currentSortButton) != null) {
        ref.empty("right");
      }
      this.__currentSortButton = button;
    }
    if (this.__currentSort.match(/DESC$/)) {
      button.replace(new CUI.Icon({
        icon: "south"
      }), "right");
    } else {
      button.replace(new CUI.Icon({
        icon: "north"
      }), "right");
    }
    return this;
  };

  ListViewEditTree.getFilterManager = function(filterFunc) {
    var filter_data, run_filter;
    filter_data = {};
    run_filter = (function(_this) {
      return function() {
        var filter, ret;
        filter = filter_data.filter.trim();
        ret = filterFunc(filter);
        if (!CUI.util.isPromise(ret)) {
          return;
        }
        _this.__filterInput.addClass("ez5-quicksearch-input--searching");
        ret.always(function() {
          _this.__filterInput.removeClass("ez5-quicksearch-input--searching");
          _this.__filterInput.enable();
          return _this.__filterInput.focus();
        });
      };
    })(this);
    this.__filterInput = new CUI.Input({
      "class": "ez5-quicksearch-input",
      name: "filter",
      maximize_horizontal: true,
      placeholder: $$("list.view.edit.tree.filter.placeholder"),
      data: filter_data,
      undo_support: false,
      mark_changed: false,
      check_changed: false,
      onDataChanged: (function(_this) {
        return function() {
          return CUI.scheduleCallback({
            ms: 500,
            call: run_filter
          });
        };
      })(this)
    });
    return this.__filterInput.start();
  };

  ListViewEditTree.prototype.getFilterInput = function() {
    return this.__filterInput;
  };

  return ListViewEditTree;

})(CUI.ListViewTree);
// Generated by CoffeeScript 1.12.7
var ListViewEditTreeNode,
  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;

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

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

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

  ListViewEditTreeNode.prototype.readOpts = function() {
    ListViewEditTreeNode.__super__.readOpts.call(this);
    return this.dataFields = [];
  };

  ListViewEditTreeNode.prototype.getEditFields = function() {
    var fields;
    fields = this.opts.fields || this.getTree().fields;
    CUI.util.assert(CUI.util.isArray(fields), (CUI.util.getObjectClass(this)) + ".getEditFields", "Fields need to be an Array", {
      fields: fields,
      opts: this.opts
    });
    return fields;
  };

  ListViewEditTreeNode.prototype.getFieldsByName = function() {
    return CUI.Form.prototype.getFieldsByName.apply(this, arguments);
  };

  ListViewEditTreeNode.prototype.getFieldByIdx = function(idx) {
    return CUI.Form.prototype.getFieldByIdx.apply(this, arguments);
  };

  ListViewEditTreeNode.prototype.getDataFields = function() {
    return CUI.Form.prototype.getDataFields.apply(this, arguments);
  };

  ListViewEditTreeNode.prototype.getOtherField = function(name) {
    var ref, ref1;
    return (ref = this.dataFields) != null ? (ref1 = ref[0]) != null ? ref1.getOtherField(name) : void 0 : void 0;
  };

  ListViewEditTreeNode.prototype.disableDataFields = function() {
    var field, i, len, ref;
    ref = this.dataFields;
    for (i = 0, len = ref.length; i < len; i++) {
      field = ref[i];
      if (field instanceof CUI.Output) {
        continue;
      }
      field.disable();
    }
    return this;
  };

  ListViewEditTreeNode.prototype.getData = function() {
    return this.opts.data;
  };

  ListViewEditTreeNode.prototype.renderContent = function() {
    var c, df, field, i, idx, len, ref, ret;
    this.dataFields = [];
    ref = this.getEditFields();
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      field = ref[idx];
      if (CUI.util.isNull(field)) {
        this.addColumn(new CUI.ListViewColumnEmpty());
        continue;
      }
      if (field instanceof CUI.ListViewColumn) {
        if (idx === 0) {
          ret = field.render();
        } else {
          this.addColumn(field);
        }
        continue;
      }
      if (field instanceof CUI.DataField) {
        CUI.util.assert(false, (CUI.util.getObjectClass(this)) + ".renderContent", "field cannot be instance of DataField");
      }
      if (CUI.util.isFunction(field.type)) {
        CUI.util.assert(!(field.icon instanceof CUI.Icon), "ListViewEditTreeNode.renderContent", "field.icon cannot be instance of Icon", {
          field: field
        });
        CUI.util.assert(!(field.icon_left instanceof CUI.Icon), "ListViewEditTreeNode.renderContent", "field.icon_right cannot be instance of Icon", {
          field: field
        });
        CUI.util.assert(!(field.icon_right instanceof CUI.Icon), "ListViewEditTreeNode.renderContent", "field.icon_left cannot be instance of Icon", {
          field: field
        });
        df = CUI.DataField["new"](field, ["th_label", "th_rotate_90", "colspan"], {
          data: this.getData()
        });
        df.setForm(this);
        if (idx === 0) {
          ret = df.DOM;
        } else {
          this.addColumn(new CUI.ListViewColumn({
            colspan: field.colspan,
            element: df.DOM
          }));
        }
        this.dataFields.push(df);
        continue;
      } else if (CUI.util.isFunction(field.renderContent)) {
        c = field.renderContent(c, this);
      } else {
        CUI.util.assert(false, (CUI.util.getObjectClass(this)) + ".renderContent", "Unable to render field. Needs to be ListViewColumn, null, field.type be set or field.renderContent", {
          field: field
        });
      }
      if (idx === 0) {
        ret = c;
      } else {
        this.addColumn(new CUI.ListViewColumn({
          colspan: field.colspan,
          element: c
        }));
      }
    }
    if (this.opts.renderContent) {
      return this.opts.renderContent(ret, this);
    } else {
      return ret;
    }
  };

  ListViewEditTreeNode.prototype.getFields = function(func) {
    if (func === "render" || func === "displayValue") {
      return [];
    }
    return this.dataFields;
  };

  ListViewEditTreeNode.prototype.addedToListView = function() {
    var df, i, len, ref, ref1, ref2;
    ref = this.dataFields;
    for (i = 0, len = ref.length; i < len; i++) {
      df = ref[i];
      if (df.isRendered()) {
        continue;
      }
      df.start();
    }
    ListViewEditTreeNode.__super__.addedToListView.call(this);
    if ((ref1 = this.getTree()) != null) {
      if ((ref2 = ref1.opts.end_add_row) != null) {
        ref2.call(this, this);
      }
    }
    return this;
  };

  ListViewEditTreeNode.prototype.updateFields = function(opts) {
    var df, i, j, k, l, len, len1, len2, ref, ref1, ref2, ref3, ref4;
    ref = this.dataFields;
    for (i = 0, len = ref.length; i < len; i++) {
      df = ref[i];
      df.show();
      df.enable();
      if (df instanceof CUI.Checkbox && opts.button_group) {
        df.setGroup(df.getName() + "-" + opts.button_group);
      }
    }
    ref1 = opts.hide;
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      k = ref1[j];
      if (CUI.util.isInteger(k)) {
        df = this.getFieldByIdx(k);
      } else {
        df = (ref2 = this.getFieldsByName(k)) != null ? ref2[0] : void 0;
      }
      if (df) {
        df.hide();
      } else {

      }
    }
    ref3 = opts.disable;
    for (l = 0, len2 = ref3.length; l < len2; l++) {
      k = ref3[l];
      if (CUI.util.isInteger(k)) {
        df = this.getFieldByIdx(k);
      } else {
        df = (ref4 = this.getFieldsByName(k)) != null ? ref4[0] : void 0;
      }
      if (df) {
        df.disable();
      } else {

      }
    }
    return this;
  };

  ListViewEditTreeNode.prototype.validate = function() {
    return [];
  };

  return ListViewEditTreeNode;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var TagSimple,
  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;

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

  function TagSimple() {
    this.equals = bind(this.equals, this);
    return TagSimple.__super__.constructor.apply(this, arguments);
  }

  TagSimple.pseudoIdCounter = 0;

  TagSimple.prototype.initOpts = function() {
    TagSimple.__super__.initOpts.call(this);
    return this.addOpts({
      tagFormGroup: {
        check: TagGroupSimple
      }
    });
  };

  TagSimple.prototype.readOpts = function() {
    if (this.opts instanceof TagSimple) {
      CUI.util.assert(false, "Tag cannot be initialized using a Tag");
    }
    this.initData();
    this.pseudoId = -(++TagSimple.pseudoIdCounter);
    return TagSimple.__super__.readOpts.call(this);
  };

  TagSimple.prototype.initData = function() {
    this.data = this.opts.data;
    CUI.util.assert(CUI.util.isPlainObject(this.data.tag), "new Tag", "opts.data.tag needs to be plain object", {
      opts: this.opts
    });
    this.tagFormGroup = this.opts.tagFormGroup;
    if (!this.data._acl) {
      this.data._acl = [];
    }
    if (!this.data.tag.frontend_prefs) {
      this.data.tag.frontend_prefs = {};
    }
    if (!this.data.tag.frontend_prefs.webfrontend) {
      return this.data.tag.frontend_prefs.webfrontend = {};
    }
  };

  TagSimple.prototype.initTooltip = function(el, expiration_data) {
    var desc, text, valid_from, valid_to;
    if (expiration_data == null) {
      expiration_data = null;
    }
    if (!this.getDisplayName() || !this.tagFormGroup) {
      return this;
    }
    text = this.tagFormGroup.getDisplayName() + ": " + this.getDisplayName();
    if (!CUI.util.isEmpty(desc = this.getDescription())) {
      text += "\n\n" + desc;
    }
    if (expiration_data) {
      if (expiration_data.valid_to || expiration_data.valid_from) {
        text += "\n";
        valid_from = CUI.DateTime.format(expiration_data.valid_from, "display");
      }
      if (valid_from) {
        text += "\n Valid from: " + valid_from;
      }
      valid_to = CUI.DateTime.format(expiration_data.valid_to, "display");
      if (valid_to) {
        text += "\n Valid to: " + valid_to;
      }
    }
    if (!CUI.util.isEmpty(text)) {
      new CUI.Tooltip({
        element: el,
        text: text
      });
    }
    return this;
  };

  TagSimple.prototype.available = function() {
    return true;
  };

  TagSimple.prototype.getData = function() {
    return this.data.tag;
  };

  TagSimple.prototype.getDisplayName = function() {
    return ez5.loca.getBestFrontendValue(this.data.tag.displayname);
  };

  TagSimple.prototype.getDisplayType = function() {
    return this.data.tag.displaytype;
  };

  TagSimple.prototype.getReference = function() {
    return this.data.tag.reference;
  };

  TagSimple.prototype.getShortname = function() {
    return this.data.tag.shortname;
  };

  TagSimple.prototype.getId = function() {
    return this.data.tag._id;
  };

  TagSimple.prototype.getLabel = function(showIcon, tooltip, expiration_data) {
    var chroma, colorValue, customColorIdx, customColorName, displayName, icon, labelOpts, lb, ref, ref1, ref2, ref3, ref4;
    if (showIcon == null) {
      showIcon = true;
    }
    if (tooltip == null) {
      tooltip = false;
    }
    if (expiration_data == null) {
      expiration_data = null;
    }
    if (!ez5.session.isDebug()) {
      expiration_data = null;
    }
    displayName = this.getDisplayName();
    if (showIcon) {
      icon = this.getIcon() || (displayName != null ? displayName[0] : void 0);
    }
    labelOpts = {
      "class": "ez5-tag " + this.getColorCls() + " " + this.getIconCls(),
      text: displayName
    };
    if (icon) {
      labelOpts.icon = icon;
    }
    lb = new CUI.Label(labelOpts);
    if (this.hasCustomColor()) {
      customColorName = (ref = this.data) != null ? (ref1 = ref.tag.frontend_prefs.webfrontend) != null ? ref1.color : void 0 : void 0;
      if (customColorName) {
        customColorIdx = (ref2 = customColorName.match(/(\d+)$/)) != null ? ref2[1] : void 0;
      }
      colorValue = (ref3 = ez5.session.getBaseConfig().appearance) != null ? (ref4 = ref3.tag_colors[customColorIdx]) != null ? ref4.tag_color : void 0 : void 0;
      if (colorValue) {
        CUI.dom.setStyle(lb, {
          "--custom-tag-background": colorValue
        });
        chroma = window.chroma;
        if (chroma && chroma.contrast('white', colorValue) < 4.5) {
          CUI.dom.addClass(lb, "has-tag-color-dark");
        }
      }
    }
    if (tooltip) {
      this.initTooltip(lb, expiration_data);
    }
    if (expiration_data) {
      if (expiration_data.valid_to || expiration_data.valid_from) {
        CUI.dom.addClass(lb, "has-expiration-time");
      }
    }
    return lb;
  };

  TagSimple.prototype.getLabelWithExpirationForm = function(opts) {
    var expirationForm, expiration_button, hl, tagLabel;
    if (!ez5.session.isDebug()) {
      return this.getLabel(true, true);
    }
    expirationForm = new CUI.FormPopover({
      data: opts.data,
      button: {
        icon: "fa-clock-o",
        "class": "tag-expiration-time-button"
      },
      popover: {
        pane: {
          padded: true,
          header_left: new CUI.Label({
            text: "Configure expiration"
          })
        }
      },
      fields: [
        {
          type: CUI.DateTime,
          name: "valid_from",
          form: {
            label: "Valid from"
          }
        }, {
          type: CUI.DateTime,
          name: "valid_to",
          form: {
            label: "Valid to"
          }
        }, {
          type: CUI.Select,
          name: "email_notification",
          form: {
            label: "Email notification"
          },
          options: [
            {
              value: "none",
              text: "None"
            }, {
              value: "day_of_expiration",
              text: "Day of expiration"
            }, {
              value: "one_day_before",
              text: "One day before"
            }, {
              value: "one_week_before",
              text: "One week before"
            }
          ]
        }, {
          type: CUI.DataTable,
          no_header: true,
          form: {
            label: "Email recipients"
          },
          name: "recipients",
          fields: [
            {
              type: UserGroupSelector,
              name: "address",
              aclWhoManager: new AclWhoManager({
                allowEmailUser: true,
                allowPoolUser: true,
                allowOwner: ez5.version("6.10"),
                filter_system_groups: true,
                filter_system_users: true
              })
            }
          ]
        }
      ],
      renderDisplayContent: (function(_this) {
        return function(fp) {
          if (opts.data.valid_to || opts.data.valid_from) {
            return CUI.dom.addClass(fp.getButton(), "has-expiration-time");
          } else {
            return CUI.dom.removeClass(fp.getButton(), "has-expiration-time");
          }
        };
      })(this)
    });
    expirationForm.start();
    tagLabel = this.getLabel(true, true);
    expiration_button = expirationForm.getButton();
    hl = new CUI.HorizontalLayout({
      auto_buttonbar: false,
      center: {
        content: tagLabel
      },
      right: {
        content: expiration_button
      }
    });
    return hl;
  };

  TagSimple.prototype.hasCustomColor = function() {
    var ref, ref1, ref2, ref3, ref4;
    if (!ez5.version("6")) {
      return false;
    }
    return (ref = this.data) != null ? (ref1 = ref.tag) != null ? (ref2 = ref1.frontend_prefs) != null ? (ref3 = ref2.webfrontend) != null ? (ref4 = ref3.color) != null ? ref4.includes("custom") : void 0 : void 0 : void 0 : void 0 : void 0;
  };

  TagSimple.prototype.getIcon = function() {
    var ref, ref1;
    return ((ref = this.data) != null ? (ref1 = ref.tag.frontend_prefs.webfrontend) != null ? ref1.icon : void 0 : void 0) || null;
  };

  TagSimple.prototype.getColorCls = function() {
    var color, ref, ref1;
    color = (ref = this.data) != null ? (ref1 = ref.tag.frontend_prefs.webfrontend) != null ? ref1.color : void 0 : void 0;
    if (!color) {
      return '';
    }
    return 'ez5-tag-color-' + color;
  };

  TagSimple.prototype.getIconCls = function(icon) {
    if (icon == null) {
      icon = false;
    }
    icon = this.getIcon();
    if (!icon) {
      return "ez5-tag-no-icon";
    } else {
      return "";
    }
  };

  TagSimple.prototype.getIconElement = function(tooltip) {
    var el, icon;
    if (tooltip == null) {
      tooltip = true;
    }
    icon = this.getIcon();
    if (icon) {
      el = new CUI.Icon({
        icon: icon
      }).DOM;
      CUI.dom.addClass(el, "ez5-tag-icon");
      CUI.dom.addClass(el, this.getColorCls());
      this.initTooltip(el);
      return el;
    } else {
      return null;
    }
  };

  TagSimple.prototype.getDescription = function() {
    return ez5.loca.getBestFrontendValue(this.data.tag.description);
  };

  TagSimple.prototype.equals = function(tagFormTag) {
    return this.getAnyId() === tagFormTag.getAnyId();
  };

  TagSimple.prototype.getAnyId = function() {
    return this.getId() || this.pseudoId;
  };

  TagSimple.prototype.isVisible = function(mode) {
    var _mode, availableModes, displayType, i, len;
    displayType = this.getDisplayType();
    if (!displayType) {
      return false;
    }
    if (displayType === "hidden") {
      return false;
    }
    if (!CUI.util.isString(mode)) {
      return true;
    }
    availableModes = (function() {
      switch (displayType) {
        case "facet":
          return ["facet", "search", "expert", "standard", "detail", "table", "editor", "text"];
        case "search":
          return ["search", "expert", "standard", "detail", "table", "editor", "text"];
        case "detail":
          return ["standard", "detail", "table", "editor", "text"];
        case "editor":
          return ["editor"];
        default:
          return [];
      }
    })();
    for (i = 0, len = availableModes.length; i < len; i++) {
      _mode = availableModes[i];
      if (_mode === mode) {
        return true;
      }
      if (mode.startsWith(_mode) || mode.endsWith(_mode)) {
        return true;
      }
    }
    return false;
  };

  TagSimple.prototype.getTagForFilter = function() {
    var copyTag;
    copyTag = CUI.util.copyObject(this, true);
    delete copyTag.tagFormGroup;
    delete copyTag.opts.tagFormGroup;
    delete copyTag._tagFormGroup;
    return copyTag;
  };

  TagSimple.sortList = function(tags) {
    return tags.sort(function(a, b) {
      var a_d, b_d;
      a_d = a.getData();
      b_d = b.getData();
      if (a_d._group_idx < b_d._group_idx) {
        return -1;
      } else if (a_d._group_idx > b_d._group_idx) {
        return 1;
      } else if (a_d._idx < b_d._idx) {
        return -1;
      } else if (a_d._idx > b_d._idx) {
        return 1;
      } else {
        return 0;
      }
    });
  };

  return TagSimple;

})(ListViewEditTreeNode);
// Generated by CoffeeScript 1.12.7
var SystemTagSimple,
  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;

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

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

  SystemTagSimple.prototype.initOpts = function() {
    SystemTagSimple.__super__.initOpts.call(this);
    return this.removeOpt("tagFormGroup");
  };

  SystemTagSimple.prototype.initData = function() {
    this.data = this.opts.data;
  };

  SystemTagSimple.prototype.getDisplayName = function() {
    var labelLocaKey;
    labelLocaKey = "system.tags.tag." + (this.getInternalName()) + "|label";
    if (ez5.loca.has(labelLocaKey)) {
      return $$(labelLocaKey);
    }
    return this.getInternalName();
  };

  SystemTagSimple.prototype.getIcon = function() {
    var iconLocaKey;
    iconLocaKey = "system.tags.tag." + (this.getInternalName()) + "|icon";
    if (ez5.loca.has(iconLocaKey)) {
      return $$(iconLocaKey);
    }
    return "fa-warning";
  };

  SystemTagSimple.prototype.getColorCls = function() {
    var color, iconLocaKey;
    iconLocaKey = "system.tags.tag." + (this.getInternalName()) + "|color";
    if (ez5.loca.has(iconLocaKey)) {
      color = $$(iconLocaKey);
    } else {
      color = "red";
    }
    return "ez5-tag-color-" + color;
  };

  SystemTagSimple.prototype.initTooltip = function(el) {
    var tooltipText, tooltipTextLocaKey;
    tooltipTextLocaKey = "system.tags.tag." + (this.getInternalName()) + "|tooltip";
    if (ez5.loca.has(tooltipTextLocaKey)) {
      tooltipText = $$(tooltipTextLocaKey);
    } else {
      tooltipText = this.getDisplayName();
    }
    new CUI.Tooltip({
      element: el,
      text: tooltipText
    });
    return this;
  };

  SystemTagSimple.prototype.getInternalName = function() {
    return this.data.system_tag;
  };

  return SystemTagSimple;

})(TagSimple);
// Generated by CoffeeScript 1.12.7
var Tag,
  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;

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

  function Tag() {
    this.getSaveData = bind(this.getSaveData, this);
    return Tag.__super__.constructor.apply(this, arguments);
  }

  Tag.COLORS = ["green", "red", "blue", "orange", "yellow", "magenta", "turquoise", "violet", "white", "black"];

  Tag.getTagColors = function() {
    var default_colors;
    default_colors = CUI.util.copyObject(this.COLORS);
    default_colors = default_colors.concat(this.getCustomColors());
    return default_colors;
  };

  Tag.getCustomColors = function() {
    var colors, custom_color, i, idx, len, ref, ref1;
    colors = [];
    if (!ez5.version("6")) {
      return colors;
    }
    if (((ref = ez5.session.getBaseConfig().appearance.tag_colors) != null ? ref.length : void 0) > 0) {
      ref1 = ez5.session.getBaseConfig().appearance.tag_colors;
      for (idx = i = 0, len = ref1.length; i < len; idx = ++i) {
        custom_color = ref1[idx];
        colors.push("custom-" + idx);
      }
    }
    return colors;
  };

  Tag.prototype.initOpts = function() {
    Tag.__super__.initOpts.call(this);
    return this.addOpts({
      fields: {
        check: Array
      }
    });
  };

  Tag.prototype.initData = function() {
    Tag.__super__.initData.call(this);
    return this.opts.fields = this.getFieldDefs();
  };

  Tag.prototype.getBaseFieldDefs = function() {
    return {
      displayname: {
        type: CUI.MultiInput,
        control: ez5.loca.getLanguageControlAdmin(),
        user_selectable: ez5.session.getPref("languages_user_selection"),
        name: "displayname",
        ui: "tag.field.input:displayname"
      },
      enabled: {
        type: CUI.Checkbox,
        disabled: (function(_this) {
          return function() {
            return _this.tagDisabled;
          };
        })(this),
        name: "enabled",
        ui: "tag.field.checkbox:enabled",
        onDataChanged: (function(_this) {
          return function(data, field) {
            if (!_this.data.tag.enabled) {
              return field.getOtherField("is_default").setValue(false).disable();
            } else {
              return field.getOtherField("is_default").enable();
            }
          };
        })(this)
      },
      is_default: {
        type: CUI.Checkbox,
        name: "is_default",
        ui: "tag.field.checkbox:is_default",
        disabled: (function(_this) {
          return function() {
            return _this.tagDisabled || !_this.data.tag.enabled;
          };
        })(this),
        onDataChanged: (function(_this) {
          return function(data, field) {
            var c, i, len, ref;
            console.debug("opts.data", _this.data, _this.father.data);
            if (_this.data.tag.is_default && _this.father.data.taggroup.type === "choice") {
              ref = _this.father.children;
              for (i = 0, len = ref.length; i < len; i++) {
                c = ref[i];
                if (c === _this || c.tagDisabled) {
                  continue;
                }
                c.getOtherField("is_default").setValue(false);
              }
            }
            return null;
          };
        })(this)
      },
      sticky: {
        type: CUI.Checkbox,
        disabled: (function(_this) {
          return function() {
            return _this.tagDisabled;
          };
        })(this),
        name: "sticky",
        ui: "tag.field.checkbox:sticky"
      }
    };
  };

  Tag.prototype.getFieldDefs = function() {
    var base_fields, color, colorValue, color_opts, coloricon, customColorIdx, custom_icon, custom_icons, i, icon, icon_opts, j, l, len, len1, len2, ref, ref1, ref2, ref3, ref4, ref5, ref6, tag_color, tag_icon, tag_icons;
    base_fields = this.getBaseFieldDefs();
    this.aclManager = new AclManager({
      data: this.data._acl,
      right: true,
      active: true,
      context: this,
      tagfilter: true,
      acl_counter_loca_key: "acl.manager.tag.acl-counter",
      tagForm: this.tagFormGroup.getTagForm()
    });
    icon_opts = [
      {
        text: "",
        value: null
      }
    ];
    color_opts = [
      {
        text: '',
        value: null
      }
    ];
    tag_icons = (ref = ez5.session.getDefaults().client.tag_icons) != null ? ref.trim() : void 0;
    if (!tag_icons) {
      tag_icons = "bolt,check,cloud,warning,legal";
    }
    ref1 = tag_icons.split(",");
    for (i = 0, len = ref1.length; i < len; i++) {
      tag_icon = ref1[i];
      icon = tag_icon.trim();
      icon_opts.push({
        icon: icon,
        value: icon
      });
    }
    if (ez5.version("6") && ((ref2 = ez5.session.getBaseConfig().appearance.tag_icons) != null ? ref2.length : void 0) > 0) {
      custom_icons = ez5.session.getBaseConfig().appearance.tag_icons;
      for (j = 0, len1 = custom_icons.length; j < len1; j++) {
        custom_icon = custom_icons[j];
        icon_opts.push({
          icon: custom_icon["fa-icon"],
          value: custom_icon["fa-icon"]
        });
      }
    }
    ref3 = Tag.getTagColors();
    for (l = 0, len2 = ref3.length; l < len2; l++) {
      tag_color = ref3[l];
      coloricon = new CUI.Icon({
        icon: 'css-swatch ez5-tag-color-' + tag_color
      });
      if (ez5.version("6") && tag_color.includes("custom")) {
        customColorIdx = (ref4 = tag_color.match(/(\d+)$/)) != null ? ref4[1] : void 0;
        colorValue = (ref5 = ez5.session.getBaseConfig().appearance) != null ? (ref6 = ref5.tag_colors[customColorIdx]) != null ? ref6.tag_color : void 0 : void 0;
        if (colorValue) {
          CUI.dom.setStyle(coloricon.DOM, {
            "background-color": colorValue
          });
        }
      }
      color = tag_color.trim();
      color_opts.push({
        icon: coloricon,
        value: color
      });
    }
    return [
      base_fields.displayname, {
        type: CUI.Select,
        name: "type",
        ui: "tag.field.select:type",
        options: function() {
          var k, len3, m, ref7, results;
          ref7 = ["individual", "all_versions"];
          results = [];
          for (m = 0, len3 = ref7.length; m < len3; m++) {
            k = ref7[m];
            results.push({
              text: $$("tag.form.type." + k),
              value: k,
              ui: "tag.field.select.option:type:" + k
            });
          }
          return results;
        }
      }, {
        type: CUI.Select,
        name: "displaytype",
        ui: "tag.field.select:displaytype",
        options: function() {
          var k, len3, m, ref7, results;
          ref7 = ["facet", "search", "detail", "editor", "hidden"];
          results = [];
          for (m = 0, len3 = ref7.length; m < len3; m++) {
            k = ref7[m];
            results.push({
              text: $$("tag.form.displaytype." + k),
              value: k,
              ui: "tag.field.select.option:displaytype:" + k
            });
          }
          return results;
        }
      }, {
        type: CUI.FormPopover,
        popover: {
          pane: {
            padded: true
          }
        },
        fields: [
          {
            type: CUI.MultiInput,
            name: "description",
            control: ez5.loca.getLanguageControlAdmin(),
            user_selectable: ez5.session.getPref("languages_user_selection"),
            textarea: true,
            form: {
              label: $$("admin.tagform.col.description")
            },
            ui: "tag.field.input:description"
          }, {
            type: CUI.Input,
            name: "reference",
            form: {
              label: $$("admin.tagform.col.reference")
            },
            ui: "tag.field.input:reference"
          }, {
            type: CUI.Input,
            name: "shortname",
            form: {
              label: $$("admin.tagform.col.shortname")
            },
            ui: "tag.field.input:shortname"
          }
        ],
        button: {
          icon_active: "file_text_active",
          icon_inactive: "file_text"
        },
        renderDisplayButton: (function(_this) {
          return function(df, data) {
            var attribute, attributes, k, len3, m, ref7, v;
            ref7 = data.description;
            for (k in ref7) {
              v = ref7[k];
              if (!CUI.util.isEmpty(v)) {
                return true;
              }
            }
            attributes = ["shortname", "reference"];
            for (m = 0, len3 = attributes.length; m < len3; m++) {
              attribute = attributes[m];
              if (!CUI.util.isEmpty(data[attribute])) {
                return true;
              }
            }
            return false;
          };
        })(this)
      }, base_fields.enabled, base_fields.is_default, base_fields.sticky, {
        type: CUI.Select,
        "class": "ez5-tag-icon-select",
        name: "icon",
        ui: "tag.field.select:icon",
        data: this.data.tag.frontend_prefs.webfrontend,
        disabled: (function(_this) {
          return function() {
            return _this.tagDisabled;
          };
        })(this),
        options: icon_opts
      }, {
        type: CUI.Select,
        "class": "ez5-tag-icon-select",
        name: "color",
        ui: "tag.field.select:color",
        data: this.data.tag.frontend_prefs.webfrontend,
        disabled: (function(_this) {
          return function() {
            return _this.tagDisabled;
          };
        })(this),
        options: color_opts
      }, this.aclManager.getField()
    ];
  };

  Tag.prototype.renderAsButton = function(editorData) {
    var button, setIcon;
    setIcon = (function(_this) {
      return function() {
        var icon;
        switch (editorData[_this.getAnyId()]) {
          case null:
          case void 0:
            icon = null;
            break;
          case false:
            icon = "minus";
            break;
          case true:
            icon = "plus";
        }
        button.setIcon(icon);
      };
    })(this);
    button = new CUI.Button({
      text: this.getDisplayName(),
      "class": "ez5-tag-editor-button",
      left: true,
      onClick: (function(_this) {
        return function(ev) {
          var nd;
          switch (editorData[_this.getAnyId()]) {
            case null:
            case void 0:
              nd = true;
              break;
            case true:
              nd = false;
              break;
            case false:
              nd = null;
          }
          editorData[_this.getAnyId()] = nd;
          CUI.Events.trigger({
            node: button,
            type: "data-changed"
          });
          return setIcon();
        };
      })(this)
    });
    setIcon();
    return button.DOM;
  };

  Tag.prototype.getSaveData = function() {
    var i, j, k, l, len, len1, len2, len3, m, ref, ref1, ref2, ref3, save_data;
    save_data = {
      tag: {}
    };
    ref = ["displayname", "description", "displaytype", "type", "_id"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      save_data.tag[k] = this.data.tag[k];
    }
    ref1 = ["reference", "shortname"];
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      k = ref1[j];
      save_data.tag[k] = this.data.tag[k] || null;
    }
    ref2 = ["sticky", "is_default", "enabled"];
    for (l = 0, len2 = ref2.length; l < len2; l++) {
      k = ref2[l];
      save_data.tag[k] = !!this.data.tag[k];
    }
    save_data.tag.frontend_prefs = CUI.util.copyObject(this.data.tag.frontend_prefs, true);
    save_data.tag.frontend_prefs.webfrontend = {};
    ref3 = ["icon", 'color'];
    for (m = 0, len3 = ref3.length; m < len3; m++) {
      k = ref3[m];
      save_data.tag.frontend_prefs.webfrontend[k] = this.data.tag.frontend_prefs.webfrontend[k];
    }
    save_data._acl = this.aclManager.getSaveData();
    save_data._pseudo_id = this.pseudoId;
    return save_data;
  };

  Tag.getTagColorsSelectorOp5ionw = function() {
    var color, colorValue, color_opts, coloricon, customColorIdx, i, len, ref, ref1, ref2, ref3, tag_color;
    color_opts = [
      {
        text: '',
        value: null
      }
    ];
    ref = Tag.getTagColors();
    for (i = 0, len = ref.length; i < len; i++) {
      tag_color = ref[i];
      coloricon = new CUI.Icon({
        icon: 'css-swatch ez5-tag-color-' + tag_color
      });
      if (ez5.version("6") && tag_color.includes("custom")) {
        customColorIdx = (ref1 = tag_color.match(/(\d+)$/)) != null ? ref1[1] : void 0;
        colorValue = (ref2 = ez5.session.getBaseConfig().appearance) != null ? (ref3 = ref2.tag_colors[customColorIdx]) != null ? ref3.tag_color : void 0 : void 0;
        if (colorValue) {
          CUI.dom.setStyle(coloricon.DOM, {
            "background-color": colorValue
          });
        }
      }
      color = tag_color.trim();
      color_opts.push({
        icon: coloricon,
        value: color
      });
    }
    return color_opts;
  };

  Tag.getTagIconsSelectorOptions = function() {
    var custom_icon, custom_icons, i, icon, icon_opts, j, len, len1, ref, ref1, ref2, tag_icon, tag_icons;
    icon_opts = [
      {
        text: "",
        value: null
      }
    ];
    tag_icons = (ref = ez5.session.getDefaults().client.tag_icons) != null ? ref.trim() : void 0;
    if (!tag_icons) {
      tag_icons = "bolt,check,cloud,warning,legal";
    }
    ref1 = tag_icons.split(",");
    for (i = 0, len = ref1.length; i < len; i++) {
      tag_icon = ref1[i];
      icon = tag_icon.trim();
      icon_opts.push({
        icon: icon,
        value: icon
      });
    }
    if (ez5.version("6") && ((ref2 = ez5.session.getBaseConfig().appearance.tag_icons) != null ? ref2.length : void 0) > 0) {
      custom_icons = ez5.session.getBaseConfig().appearance.tag_icons;
      for (j = 0, len1 = custom_icons.length; j < len1; j++) {
        custom_icon = custom_icons[j];
        icon_opts.push({
          icon: custom_icon["fa-icon"],
          value: custom_icon["fa-icon"]
        });
      }
    }
    return icon_opts;
  };

  return Tag;

})(TagSimple);
// Generated by CoffeeScript 1.12.7
var TagGroupSimple,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function TagGroupSimple(opts) {
    var i, len, ref, tag_data, tag_idx;
    this.opts = opts != null ? opts : {};
    this.findTagByShortname = bind(this.findTagByShortname, this);
    this.findTagByReference = bind(this.findTagByReference, this);
    this.findTagByDisplayName = bind(this.findTagByDisplayName, this);
    this.findTagByAnyId = bind(this.findTagByAnyId, this);
    this.tagForm = this.opts.tagForm;
    this.children = [];
    this.data = this.opts.data || {
      taggroup: {}
    };
    if (!this.data._tags) {
      this.data._tags = [];
    }
    ref = this.opts.data._tags;
    for (tag_idx = i = 0, len = ref.length; i < len; tag_idx = ++i) {
      tag_data = ref[tag_idx];
      tag_data.tag._idx = tag_idx;
      tag_data.tag._group_idx = this.data.taggroup._idx;
      this.children.push(new this.tagFormTagClass({
        data: tag_data,
        tagFormGroup: this,
        ui: "tag.simple:" + tag_idx
      }));
    }
    if (this.children.length) {
      this.do_open = true;
    }
    TagGroupSimple.__super__.constructor.call(this, this.opts);
  }

  TagGroupSimple.prototype.initOpts = function() {
    TagGroupSimple.__super__.initOpts.call(this);
    return this.addOpts({
      tagForm: {
        check: TagFormSimple
      }
    });
  };

  TagGroupSimple.prototype.tagFormTagClass = TagSimple;

  TagGroupSimple.prototype.getData = function() {
    return this.data.taggroup;
  };

  TagGroupSimple.prototype.getTagForm = function() {
    return this.tagForm;
  };

  TagGroupSimple.prototype.getType = function() {
    return this.data.taggroup.type;
  };

  TagGroupSimple.prototype.getId = function() {
    return this.data.taggroup._id;
  };

  TagGroupSimple.prototype.getTags = function() {
    return this.children;
  };

  TagGroupSimple.prototype.getTagsWithDisplayType = function(types) {
    if (types == null) {
      types = [];
    }
    return this.getTags().filter((function(_this) {
      return function(tag) {
        var ref;
        return ref = tag.getDisplayType(), indexOf.call(types, ref) >= 0;
      };
    })(this));
  };

  TagGroupSimple.prototype.isChoice = function() {
    return this.getType() === "choice";
  };

  TagGroupSimple.prototype.getDisplayName = function() {
    return ez5.loca.getBestFrontendValue(this.opts.data.taggroup.displayname);
  };

  TagGroupSimple.prototype.findTagByAnyId = function(anyId) {
    var i, len, ref, tag;
    ref = this.children;
    for (i = 0, len = ref.length; i < len; i++) {
      tag = ref[i];
      if ("" + tag.getAnyId() === "" + anyId) {
        return tag;
      }
    }
    return null;
  };

  TagGroupSimple.prototype.findTagByDisplayName = function(name) {
    var i, len, ref, ref1, tag;
    ref = this.children;
    for (i = 0, len = ref.length; i < len; i++) {
      tag = ref[i];
      if (((ref1 = tag.getDisplayName()) != null ? ref1.toUpperCase() : void 0) === name.toUpperCase()) {
        return tag;
      }
    }
    return null;
  };

  TagGroupSimple.prototype.findTagByReference = function(reference) {
    var i, len, ref, tag;
    ref = this.children;
    for (i = 0, len = ref.length; i < len; i++) {
      tag = ref[i];
      if (tag.getReference() === reference) {
        return tag;
      }
    }
    return null;
  };

  TagGroupSimple.prototype.findTagByShortname = function(shortname) {
    var i, len, ref, tag;
    ref = this.children;
    for (i = 0, len = ref.length; i < len; i++) {
      tag = ref[i];
      if (tag.getShortname() === shortname) {
        return tag;
      }
    }
    return null;
  };

  return TagGroupSimple;

})(ListViewEditTreeNode);
// Generated by CoffeeScript 1.12.7
var TagGroup,
  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;

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

  function TagGroup(opts) {
    this.opts = opts != null ? opts : {};
    this.opts.fields = this.getFieldDefs();
    TagGroup.__super__.constructor.call(this, this.opts);
  }

  TagGroup.prototype.initOpts = function() {
    TagGroup.__super__.initOpts.call(this);
    return this.addOpts({
      tagForm: {
        check: TagForm
      },
      fields: {
        check: Array
      }
    });
  };

  TagGroup.prototype.tagFormTagClass = Tag;

  TagGroup.prototype.loadData = function(data, context) {};

  TagGroup.prototype.addTag = function() {
    var tag, tag_data;
    tag_data = {
      tag: {
        enabled: true
      }
    };
    this.data._tags.push(tag_data);
    tag = new this.tagFormTagClass({
      data: tag_data,
      tagFormGroup: this
    });
    this.addNode(tag);
    return this;
  };

  TagGroup.prototype.getFieldDefs = function() {
    return [
      {
        type: CUI.MultiInput,
        name: "displayname",
        control: ez5.loca.getLanguageControlAdmin(),
        user_selectable: ez5.session.getPref("languages_user_selection"),
        ui: "tag.group.fields.input:displayname"
      }, {
        type: CUI.Select,
        name: "type",
        ui: "tag.group.fields.select:type",
        options: [
          {
            text: $$("tag.group.type.checkbox"),
            value: "checkbox",
            ui: "tag.group.fields.select.option:checkbox"
          }, {
            text: $$("tag.group.type.choice"),
            value: "choice",
            ui: "tag.group.fields.select.option:choice"
          }
        ],
        onDataChanged: (function(_this) {
          return function() {
            var _tag, defaultCheckbox, first, i, len, ref;
            if (_this.data.taggroup.type === "choice") {
              first = false;
              ref = _this.children;
              for (i = 0, len = ref.length; i < len; i++) {
                _tag = ref[i];
                if (!_tag.data.tag.is_default) {
                  continue;
                }
                if (!first) {
                  first = true;
                  continue;
                }
                defaultCheckbox = _tag.getOtherField("is_default");
                if (defaultCheckbox) {
                  defaultCheckbox.setValue(false);
                } else {
                  _tag.getData().is_default = false;
                }
              }
            }
            return null;
          };
        })(this)
      }, null, {
        type: CUI.FormPopover,
        popover: {
          pane: {
            padded: true
          }
        },
        fields: [
          {
            type: CUI.Input,
            name: "reference",
            form: {
              label: $$("admin.tagform.col.reference")
            },
            ui: "tag.group.fields.input:reference"
          }, {
            type: CUI.Input,
            name: "shortname",
            form: {
              label: $$("admin.tagform.col.shortname")
            },
            ui: "tag.group.fields.input:shortname"
          }
        ],
        button: {
          icon_active: "file_text_active",
          icon_inactive: "file_text"
        },
        renderDisplayButton: (function(_this) {
          return function(df, data) {
            var attribute, attributes, i, len;
            attributes = ["shortname", "reference"];
            for (i = 0, len = attributes.length; i < len; i++) {
              attribute = attributes[i];
              if (!CUI.util.isEmpty(data[attribute])) {
                return true;
              }
            }
            return false;
          };
        })(this)
      }
    ];
  };

  TagGroup.prototype.renderForEditor = function(editorData) {
    var c, child_div, divTagEditorGroup, divTagEditorGroupTitle, i, len, ref;
    divTagEditorGroup = CUI.dom.div("ez5-tag-editor-group");
    divTagEditorGroupTitle = CUI.dom.div("ez5-tag-editor-group-title");
    divTagEditorGroupTitle.textContent = this.getDisplayName();
    CUI.dom.append(divTagEditorGroup, divTagEditorGroupTitle);
    child_div = CUI.dom.div("ez5-tag-editor-group-tags");
    CUI.dom.append(divTagEditorGroup, child_div);
    ref = this.children;
    for (i = 0, len = ref.length; i < len; i++) {
      c = ref[i];
      CUI.dom.append(child_div, c.renderAsButton(editorData));
    }
    return divTagEditorGroup;
  };

  TagGroup.prototype.getSaveData = function() {
    var c, i, j, k, l, len, len1, len2, ref, ref1, ref2, save_data;
    save_data = {
      taggroup: {}
    };
    ref = ["displayname", "type", "_id"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      save_data.taggroup[k] = this.opts.data.taggroup[k];
    }
    ref1 = ["shortname", "reference"];
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      k = ref1[j];
      save_data.taggroup[k] = this.opts.data.taggroup[k] || null;
    }
    save_data._tags = [];
    if (this.children) {
      ref2 = this.children;
      for (l = 0, len2 = ref2.length; l < len2; l++) {
        c = ref2[l];
        save_data._tags.push(c.getSaveData());
      }
    }
    return save_data;
  };

  return TagGroup;

})(TagGroupSimple);
// Generated by CoffeeScript 1.12.7
var TagFormSimple,
  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;

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

  TagFormSimple.prototype.tagFormGroupClass = TagGroupSimple;

  function TagFormSimple(opts) {
    TagFormSimple.__super__.constructor.call(this, opts);
    this.tagGroups = [];
    return this;
  }

  TagFormSimple.prototype.load = function() {
    return ez5.api.tags({
      data: ez5.session.fylrCacheParams()
    }).done((function(_this) {
      return function(data1) {
        var i, len, ref, ref1, ref2, remoteTagGroups, tagGroup;
        _this.data = data1;
        remoteTagGroups = [];
        ref = _this.tagGroups;
        for (i = 0, len = ref.length; i < len; i++) {
          tagGroup = ref[i];
          if (!((ref1 = tagGroup.getData()) != null ? (ref2 = ref1._tags) != null ? ref2.some(function(_tag) {
            return _tag._id.indexOf("@") >= 0;
          }) : void 0 : void 0)) {
            continue;
          }
          remoteTagGroups.push(tagGroup);
        }
        _this.tagGroups = remoteTagGroups;
        _this.addTagGroupsFromData(_this.data);
      };
    })(this));
  };

  TagFormSimple.prototype.findTagByAnyId = function(anyId) {
    var c, found, i, len, ref;
    CUI.util.assert(this.tagGroups, "TagForm.findTagByAnyId", "Not loaded yet", {
      anyId: anyId
    });
    ref = this.tagGroups;
    for (i = 0, len = ref.length; i < len; i++) {
      c = ref[i];
      found = c.findTagByAnyId(anyId);
      if (found) {
        return found;
      }
    }
    return null;
  };

  TagFormSimple.prototype.findTagByDisplayName = function(name) {
    var c, found, i, len, ref;
    CUI.util.assert(this.tagGroups, "TagForm.findTagByDisplayName", "Not loaded yet.");
    ref = this.tagGroups;
    for (i = 0, len = ref.length; i < len; i++) {
      c = ref[i];
      found = c.findTagByDisplayName(name);
      if (found) {
        return found;
      }
    }
    return null;
  };

  TagFormSimple.prototype.findTagByReference = function(reference) {
    var c, found, i, len, ref;
    CUI.util.assert(this.tagGroups, "TagForm.findTagByReference", "Not loaded yet.");
    ref = this.tagGroups;
    for (i = 0, len = ref.length; i < len; i++) {
      c = ref[i];
      found = c.findTagByReference(reference);
      if (found) {
        return found;
      }
    }
    return null;
  };

  TagFormSimple.prototype.findTagByShortname = function(shortname) {
    var c, found, i, len, ref;
    CUI.util.assert(this.tagGroups, "TagForm.findTagByShortname", "Not loaded yet.");
    ref = this.tagGroups;
    for (i = 0, len = ref.length; i < len; i++) {
      c = ref[i];
      found = c.findTagByShortname(shortname);
      if (found) {
        return found;
      }
    }
    return null;
  };

  TagFormSimple.prototype.getAllTags = function() {
    var c, i, len, ref, tags;
    tags = [];
    ref = this.tagGroups;
    for (i = 0, len = ref.length; i < len; i++) {
      c = ref[i];
      tags.push.apply(tags, c.children);
    }
    return tags;
  };

  TagFormSimple.prototype.getTagsByData = function(_tags) {
    var _tag, i, len, tag, tags;
    tags = [];
    if (_tags != null ? _tags.length : void 0) {
      for (i = 0, len = _tags.length; i < len; i++) {
        _tag = _tags[i];
        tag = this.findTagByAnyId(_tag._id);
        if (tag) {
          tags.push(tag);
        } else {
          console.warn("Tag not found:", _tag._id, "Removing it from the list of displayed tags.");
        }
      }
    }
    TagSimple.sortList(tags);
    return tags;
  };

  TagFormSimple.prototype.renderFilterEditorTitle = function() {
    return new LocaLabel({
      loca_key: "tag.form.editor.title"
    }).DOM;
  };

  TagFormSimple.prototype.renderAsSetUnsetEditor = function(data) {
    var checkbox, checkboxes, conditionTypes, fn, group, group_added, i, idx, j, k, len, len1, len2, len3, len4, m, mapped_data, n, o, ref, ref1, ref2, table, tag, tagId, td, tr;
    table = CUI.dom.table("ez5-tag-form-filter-table");
    tr = CUI.dom.tr();
    CUI.dom.append(table, tr);
    CUI.dom.append(tr, CUI.dom.th());
    conditionTypes = ["set", "unset"];
    fn = function(idx) {
      var l;
      l = new LocaLabel({
        loca_key: "tag.form.tagfilter.header." + k
      });
      return CUI.dom.append(tr, CUI.dom.append(CUI.dom.th(), l.DOM));
    };
    for (idx = i = 0, len = conditionTypes.length; i < len; idx = ++i) {
      k = conditionTypes[idx];
      fn(idx);
    }

    /*
    			We need to convert the data from the qpi format to the form format.
    			data from the form should be like:
    			{
    				"tagId1": "set",
    				"tagId2": "unset"
    			}
    			The api format looks like:
    			{
    				tags: [
    					{
    						"_id": "tagId1",
    						"set": true
    					},
    					{
    						"_id": "tagId2",
    						"set": false
    					}
    				]
    			}
     */
    mapped_data = {};
    ref = data.tags || [];
    for (j = 0, len1 = ref.length; j < len1; j++) {
      tag = ref[j];
      if (tag.set) {
        mapped_data[tag._id] = "set";
      } else {
        mapped_data[tag._id] = "unset";
      }
    }
    checkboxes = [];
    ref1 = this.tagGroups;
    for (m = 0, len2 = ref1.length; m < len2; m++) {
      group = ref1[m];
      group_added = false;
      ref2 = group.children;
      for (n = 0, len3 = ref2.length; n < len3; n++) {
        tag = ref2[n];
        if (!tag.available()) {
          continue;
        }
        if (!group_added) {
          td = CUI.dom.append(CUI.dom.td(), new CUI.Label({
            text: group.getDisplayName(),
            multiline: true,
            appearance: "title"
          }).DOM);
          tr = CUI.dom.append(CUI.dom.tr("ez5-tag-form-tag-group-row"), td);
          CUI.dom.append(table, tr);
          group_added = true;
        }
        tagId = tag.getAnyId() + "";
        td = CUI.dom.append(CUI.dom.td("ez5-tag-form-tag-label"), tag.getLabel(true, true));
        tr = CUI.dom.append(CUI.dom.tr("ez5-tag-form-tag-row"), td);
        for (o = 0, len4 = conditionTypes.length; o < len4; o++) {
          k = conditionTypes[o];
          checkbox = new CUI.Checkbox({
            name: tagId,
            undo_support: false,
            radio: tagId,
            radio_allow_null: true,
            value: k,
            data: mapped_data,
            onDataChanged: (function(_this) {
              return function(formData, field, event) {
                var c, changedTag, changedTagId, len5, len6, len7, markDirty, p, q, r, ref3, ref4, v;
                markDirty = false;
                changedTagId = parseInt(field.getName());
                changedTag = _this.findTagByAnyId(changedTagId);
                if (changedTag.tagFormGroup.isChoice() && mapped_data[changedTagId] === "set") {
                  ref3 = changedTag.tagFormGroup.children;
                  for (p = 0, len5 = ref3.length; p < len5; p++) {
                    tag = ref3[p];
                    if (tag.getAnyId() !== changedTagId) {
                      delete mapped_data[tag.getAnyId()];
                      markDirty = true;
                    }
                  }
                } else if (changedTag.tagFormGroup.isChoice() && mapped_data[changedTagId] === "unset") {
                  ref4 = changedTag.tagFormGroup.children;
                  for (q = 0, len6 = ref4.length; q < len6; q++) {
                    tag = ref4[q];
                    if (tag.getAnyId() !== changedTagId && mapped_data[tag.getAnyId()] === "set") {
                      delete mapped_data[tag.getAnyId()];
                      markDirty = true;
                    }
                  }
                }
                if (markDirty) {
                  for (r = 0, len7 = checkboxes.length; r < len7; r++) {
                    c = checkboxes[r];
                    if (c === field) {
                      continue;
                    }
                    c.reload();
                  }
                }

                /*
                    							We need to convert the data from the form to the api format.
                    							data from the form is:
                								{
                									"tagId1": "set",
                									"tagId2": "unset"
                								}
                    							we need to convert it to:
                								{
                									tags: [
                										{
                											"_id": "tagId1",
                											"set": true
                										},
                										{
                											"_id": "tagId2",
                											"set": false
                										}
                									]
                								}
                 */
                data.tags = [];
                for (k in mapped_data) {
                  v = mapped_data[k];
                  if (v === "set") {
                    data.tags.push({
                      "_id": parseInt(k),
                      set: true
                    });
                  } else if (v === "unset") {
                    data.tags.push({
                      "_id": parseInt(k),
                      set: false
                    });
                  }
                }
                if (!data.tags.length) {
                  data = {};
                }
              };
            })(this)
          });
          checkboxes.push(checkbox);
          td = CUI.dom.append(CUI.dom.td("ez5-tag-form-tag-type-" + k), checkbox.DOM);
          CUI.dom.append(tr, td);
        }
        CUI.dom.append(table, tr);
      }
    }
    return table;
  };

  TagFormSimple.prototype.renderAsFilterEditor = function(data, conditionTypes) {
    var fn, group, group_added, i, idx, j, k, len, len1, len2, len3, len4, m, mapped_data, n, o, ref, ref1, table, tag, tagId, td, tr, v;
    table = CUI.dom.table("ez5-tag-form-filter-table");
    tr = CUI.dom.tr();
    CUI.dom.append(table, tr);
    CUI.dom.append(tr, CUI.dom.th());
    fn = function(idx) {
      var l;
      l = new LocaLabel({
        loca_key: "tag.form.tagfilter.header." + k
      });
      return CUI.dom.append(tr, CUI.dom.append(CUI.dom.th(), l.DOM));
    };
    for (idx = i = 0, len = conditionTypes.length; i < len; idx = ++i) {
      k = conditionTypes[idx];
      fn(idx);
    }
    CUI.util.assert(this.tagGroups, "TagForm.renderAsFilterEditor", "tagGroups are not loaded yet, cannot render");
    mapped_data = {};
    for (k in data) {
      v = data[k];
      if (v === false) {
        continue;
      }
      for (j = 0, len1 = v.length; j < len1; j++) {
        tagId = v[j];
        mapped_data[tagId] = k;
      }
    }
    ref = this.tagGroups;
    for (m = 0, len2 = ref.length; m < len2; m++) {
      group = ref[m];
      group_added = false;
      ref1 = group.children;
      for (n = 0, len3 = ref1.length; n < len3; n++) {
        tag = ref1[n];
        if (!tag.available()) {
          continue;
        }
        if (!group_added) {
          td = CUI.dom.append(CUI.dom.td(), new CUI.Label({
            text: group.getDisplayName(),
            multiline: true,
            appearance: "title"
          }).DOM);
          tr = CUI.dom.append(CUI.dom.tr("ez5-tag-form-tag-group-row"), td);
          CUI.dom.append(table, tr);
          group_added = true;
        }
        tagId = tag.getAnyId() + "";
        td = CUI.dom.append(CUI.dom.td("ez5-tag-form-tag-label"), tag.getLabel(true, true));
        tr = CUI.dom.append(CUI.dom.tr("ez5-tag-form-tag-row"), td);
        for (o = 0, len4 = conditionTypes.length; o < len4; o++) {
          k = conditionTypes[o];
          td = CUI.dom.append(CUI.dom.td("ez5-tag-form-tag-type-" + k), new CUI.Checkbox({
            name: tagId,
            undo_support: false,
            radio: tagId,
            radio_allow_null: true,
            value: k,
            data: mapped_data,
            onDataChanged: function() {
              for (k in data) {
                delete data[k];
              }
              for (k in mapped_data) {
                v = mapped_data[k];
                if (v === false) {
                  continue;
                }
                if (!data[v]) {
                  data[v] = [];
                }
                data[v].push(parseInt(k));
              }
            }
          }).DOM);
          CUI.dom.append(tr, td);
        }
        CUI.dom.append(table, tr);
      }
    }
    return table;
  };

  TagFormSimple.prototype.addTagGroupsFromData = function(data) {
    var group_data, group_idx, i, len, tagGroup;
    for (group_idx = i = 0, len = data.length; i < len; group_idx = ++i) {
      group_data = data[group_idx];
      group_data.taggroup._idx = group_idx;
      tagGroup = new this.tagFormGroupClass({
        data: group_data,
        tagForm: this,
        ui: "tag.group.simple:" + group_idx
      });
      this.tagGroups.push(tagGroup);
    }
  };

  return TagFormSimple;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var TagForm,
  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;

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

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

  TagForm.prototype.readOpts = function() {
    TagForm.__super__.readOpts.call(this);
    return this.context = this._context;
  };

  TagForm.prototype.initOpts = function() {
    TagForm.__super__.initOpts.call(this);
    return this.addOpts({
      context: {
        mandatory: true,
        check: function(v) {
          return !!v;
        }
      },
      header: {}
    });
  };

  TagForm.prototype.tagFormGroupClass = TagGroup;

  TagForm.prototype.setInactive = function(set) {
    return this.tree.setInactive(set);
  };

  TagForm.prototype.getPlusItems = function() {
    var items;
    items = [
      {
        loca_key: "tag.form.plus.group",
        ui: "tag.form.add.group.button",
        onClick: (function(_this) {
          return function() {
            return _this.addTagGroup();
          };
        })(this)
      }, {
        loca_key: "tag.form.plus.tag",
        ui: "tag.form.add.tag.button",
        onClick: (function(_this) {
          return function() {
            return _this.tree.getSelectedNode().addTag();
          };
        })(this)
      }
    ];
    if (!(this.tree.getSelectedNode() instanceof TagGroup)) {
      items[1].disabled = true;
    }
    return items;
  };

  TagForm.prototype.addTagGroup = function() {
    var tg, tg_data;
    tg_data = {
      taggroup: {}
    };
    this.data.push(tg_data);
    tg = new TagGroup({
      data: tg_data,
      tagForm: this,
      ui: "tag.group"
    });
    this.tree.addNode(tg).done((function(_this) {
      return function() {
        return tg.select();
      };
    })(this));
    return CUI.Events.trigger({
      type: "data-changed",
      node: this.tree
    });
  };

  TagForm.prototype.load = function() {
    var prom;
    prom = TagForm.__super__.load.call(this);
    return prom.done((function(_this) {
      return function() {
        return prom.done(function() {
          if (_this.tree && !_this.tree.isDestroyed()) {
            return _this.tree.load_data(_this.tagGroups);
          }
        });
      };
    })(this));
  };

  TagForm.prototype.getTree = function(tree_opts) {
    var k, ref, v;
    if (tree_opts == null) {
      tree_opts = {};
    }
    ref = {
      fixedRows: 1,
      "class": 'cui-lv--has-datafields',
      cols: ["maximize", "auto", "auto", "auto", "auto", "auto", "auto", "auto", "auto", "auto"],
      fixedCols: 0,
      rowMove: true,
      onRowMove: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            type: "data-changed",
            node: _this.tree
          });
        };
      })(this),
      selectableRows: true,
      fields: [
        {
          th_label: "admin.tagform.col.name"
        }, {
          th_label: "admin.tagform.col.type"
        }, {
          th_label: "admin.tagform.col.displaytype"
        }, {
          th_label: "admin.tagform.col.additional_info",
          th_rotate_90: true
        }, {
          th_label: "admin.tagform.col.enabled",
          th_rotate_90: true,
          resizable: false
        }, {
          th_label: "admin.tagform.col.is_default",
          th_rotate_90: true,
          resizable: false
        }, {
          th_label: "admin.tagform.col.sticky",
          th_rotate_90: true,
          resizable: false
        }, {
          th_label: "admin.tagform.col.icon"
        }, {
          th_label: "admin.tagform.col.color"
        }, {
          th_label: "admin.tagform.col.acl"
        }
      ],
      header_left: this._header,
      footer_left: [
        {
          icon: "plus",
          loca_key: "tag.form.list.plus",
          ui: "tag.form.add.button",
          group: "plus-minus",
          menu: {
            items: (function(_this) {
              return function() {
                return _this.getPlusItems();
              };
            })(this)
          }
        }, {
          icon: "minus",
          loca_key: "tag.form.list.minus",
          ui: "tag.form.remove.button",
          group: "plus-minus",
          onClick: (function(_this) {
            return function() {
              var ref;
              if ((ref = _this.tree.getSelectedNode()) != null) {
                ref.remove(true);
              }
              return CUI.Events.trigger({
                type: "data-changed",
                node: _this.tree
              });
            };
          })(this)
        }
      ]
    };
    for (k in ref) {
      v = ref[k];
      if (tree_opts.hasOwnProperty(k)) {
        continue;
      }
      tree_opts[k] = v;
    }
    this.tree = new ListViewEditTree(tree_opts);
    this.tree.render();
    if (this.tagGroups) {
      this.tree.load_data(this.tagGroups);
    }
    return this.tree;
  };

  TagForm.prototype.renderForEditor = function(editorData) {
    var div, group, i, len, ref;
    CUI.util.assert(this.tagGroups, "TagForm.renderForEditor", "Not loaded yet", {
      editorData: editorData
    });
    div = CUI.dom.div("ez5-tag-editor");
    ref = this.tagGroups;
    for (i = 0, len = ref.length; i < len; i++) {
      group = ref[i];
      CUI.dom.append(div, group.renderForEditor(editorData));
    }
    return div;
  };

  TagForm.prototype.getSaveData = function() {
    var c, i, len, ref, save_data;
    save_data = [];
    if (this.tagGroups) {
      ref = this.tagGroups;
      for (i = 0, len = ref.length; i < len; i++) {
        c = ref[i];
        save_data.push(c.getSaveData());
      }
    }
    return save_data;
  };

  TagForm.prototype.destroy = function() {
    var ref;
    if ((ref = this.tree) != null) {
      ref.destroy();
    }
    delete this.tree;
    return TagForm.__super__.destroy.call(this);
  };

  return TagForm;

})(TagFormSimple);
// Generated by CoffeeScript 1.12.7
var TagForManager,
  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;

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

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

  TagForManager.prototype.getSaveData = function() {
    var save_data, tag;
    if (this.tagDisabled) {
      return null;
    }
    tag = this.data.tag;
    if (!tag.enabled && !tag.sticky) {
      return null;
    }
    save_data = {
      _id: tag._id,
      enabled: tag.enabled,
      is_default: !!tag.is_default
    };
    if (this.__hasStickyColumn()) {
      save_data.sticky = !!tag.sticky;
    }
    return save_data;
  };

  TagForManager.prototype.__getContext = function() {
    return this.opts.tagFormGroup.tagForm.context;
  };

  TagForManager.prototype.getFieldDefs = function() {
    var base_fields, field, fields, i, len, name, ref;
    base_fields = this.getBaseFieldDefs();
    fields = [];
    ref = ["displayname", "enabled", "is_default", "sticky"];
    for (i = 0, len = ref.length; i < len; i++) {
      name = ref[i];
      field = base_fields[name];
      if (name === "displayname") {
        field.type = CUI.Output;
        delete field.showOnlyPreferredKey;
        delete field.user_selectable;
        delete field.control;
        field.getValue = (function(_this) {
          return function(v) {
            return ez5.loca.getBestFrontendValue(v);
          };
        })(this);
      }
      if (name === "sticky") {
        if (this.__hasStickyColumn()) {
          fields.push(field);
        }
      } else {
        fields.push(field);
      }
    }
    return fields;
  };

  TagForManager.prototype.available = function() {
    return this.data.tag.enabled;
  };

  TagForManager.prototype.__hasStickyColumn = function() {
    var context, ref;
    context = this.__getContext();
    return context instanceof Pool || (ez5.version("6") && ((ref = context.objecttype) != null ? ref.poolLink() : void 0));
  };

  return TagForManager;

})(Tag);
// Generated by CoffeeScript 1.12.7
var TagGroupForManager,
  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;

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

  function TagGroupForManager() {
    this.getSaveData = bind(this.getSaveData, this);
    this.initTagData = bind(this.initTagData, this);
    return TagGroupForManager.__super__.constructor.apply(this, arguments);
  }

  TagGroupForManager.prototype.initTagData = function(context) {
    var c, i, len, ref;
    CUI.util.assert(context, (CUI.util.getObjectClass(this)) + ".initTagData", "context needs to be set");
    ref = this.children;
    for (i = 0, len = ref.length; i < len; i++) {
      c = ref[i];
      if (typeof context.initTagData === "function") {
        context.initTagData(c);
      }
    }
  };

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

  TagGroupForManager.prototype.tagFormTagClass = TagForManager;

  TagGroupForManager.prototype.getSaveData = function(save_data) {
    var c, i, len, ref, sd;
    ref = this.children;
    for (i = 0, len = ref.length; i < len; i++) {
      c = ref[i];
      sd = c.getSaveData();
      if (sd) {
        save_data.push(sd);
      }
    }
    return save_data;
  };

  return TagGroupForManager;

})(TagGroup);
// Generated by CoffeeScript 1.12.7
var TagFormForManager,
  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;

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

  function TagFormForManager() {
    this.getSaveData = bind(this.getSaveData, this);
    this.getTree = bind(this.getTree, this);
    return TagFormForManager.__super__.constructor.apply(this, arguments);
  }

  TagFormForManager.prototype.tagFormGroupClass = TagGroupForManager;

  TagFormForManager.prototype.getTree = function(tree_opts) {
    var f, fields, k, ref, v;
    if (tree_opts == null) {
      tree_opts = {};
    }
    fields = this.getFields();
    ref = {
      fixedRows: 1,
      rowMove: false,
      cols: (function() {
        var i, len, results;
        results = [];
        for (i = 0, len = fields.length; i < len; i++) {
          f = fields[i];
          results.push("auto");
        }
        return results;
      })(),
      fields: fields,
      footer_left: null
    };
    for (k in ref) {
      v = ref[k];
      if (tree_opts.hasOwnProperty(k)) {
        continue;
      }
      tree_opts[k] = v;
    }
    return TagFormForManager.__super__.getTree.call(this, tree_opts);
  };

  TagFormForManager.prototype.load = function() {
    var prom;
    prom = TagFormForManager.__super__.load.call(this);
    return prom.done((function(_this) {
      return function() {
        var i, len, ref, tagGroup;
        ref = _this.tagGroups;
        for (i = 0, len = ref.length; i < len; i++) {
          tagGroup = ref[i];
          tagGroup.initTagData(_this.context);
        }
      };
    })(this));
  };

  TagFormForManager.prototype.getFields = function() {
    var fields, ref;
    fields = [
      {
        th_label: "admin.tagform.col.name"
      }, {
        th_label: "admin.tagform.col.enabled",
        th_rotate_90: true
      }, {
        th_label: "admin.tagform.col.is_default",
        th_rotate_90: true
      }
    ];
    if (this.context instanceof Pool || (ez5.version("6") && ((ref = this.context.objecttype) != null ? ref.poolLink() : void 0))) {
      fields.push({
        th_label: "admin.tagform.col.sticky",
        th_rotate_90: true
      });
    }
    return fields;
  };

  TagFormForManager.prototype.getSaveData = function() {
    var c, i, len, ref, save_data;
    save_data = [];
    if (this.tagGroups) {
      ref = this.tagGroups;
      for (i = 0, len = ref.length; i < len; i++) {
        c = ref[i];
        c.getSaveData(save_data);
      }
    }
    return save_data;
  };

  return TagFormForManager;

})(TagForm);
// Generated by CoffeeScript 1.12.7
var TransitionAction,
  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;

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

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

  TransitionAction.classMap = {};

  TransitionAction.registeredActions = [];

  TransitionAction.registerAction = function(action) {
    CUI.util.assert(action != null ? action.__transitionActionAction : void 0, "TransitionAction.registerAction", "Action needs to be extendes class of TransitionActionAction", {
      action: action
    });
    this.classMap[action.getType()] = action;
    return this.registeredActions.push(action.getType());
  };

  TransitionAction.prototype.initOpts = function() {
    TransitionAction.__super__.initOpts.call(this);
    return this.addOpts({
      data: {
        check: "Array"
      },
      tagForm: {
        check: TagForm
      }
    });
  };

  TransitionAction.prototype.readOpts = function() {
    var action_data, cls, i, len, ref;
    TransitionAction.__super__.readOpts.call(this);
    this.data = this._data;
    this.tagForm = this._tagForm;
    this.actions = [];
    if (this.data.length > 0) {
      ref = this.data;
      for (i = 0, len = ref.length; i < len; i++) {
        action_data = ref[i];
        cls = TransitionAction.classMap[action_data != null ? action_data.type : void 0];
        if (!cls) {
          cls = TransitionAction.classMap["unknown"];
        }
        this.newAction(cls, {
          data: action_data
        });
      }
    }
    return this;
  };

  TransitionAction.prototype.getField = function() {
    var field;
    return field = {
      type: CUI.FormPopover,
      maximize: true,
      button: {
        text: $$("transition.action.button.text")
      },
      popover: {
        pane: {
          padded: false,
          "class": "ez5-transition-action-popover",
          header_left: new CUI.Label({
            text: $$("transition.action.popover.title")
          })
        }
      },
      fields: (function(_this) {
        return function() {
          return [
            {
              type: CUI.DataFieldProxy,
              maximize_horizontal: true,
              call_others: false,
              element: function() {
                return _this.getTree();
              }
            }
          ];
        };
      })(this),
      renderDisplayContent: (function(_this) {
        return function() {
          return ez5.getLabelForCount("transition.action.counter", _this.actions.length);
        };
      })(this)
    };
  };

  TransitionAction.prototype.newAction = function(actionClass, classOpts) {
    var action;
    if (classOpts == null) {
      classOpts = {};
    }
    classOpts.data = classOpts.data || {};
    classOpts.transitionAction = this;
    action = new actionClass(classOpts);
    if (this.tree) {
      this.tree.addNode(action);
      CUI.Events.trigger({
        type: "content-resize",
        node: this.tree
      });
      CUI.Events.trigger({
        type: "data-changed",
        node: this.tree
      });
    } else {
      this.actions.push(action);
    }
    return null;
  };

  TransitionAction.prototype.getTree = function() {
    this.tree = new ListViewEditTree({
      cols: ["auto", "auto"],
      fixedCols: 1,
      "class": 'cui-lv--has-datafields',
      no_hierarchy: true,
      rowMove: true,
      selectable: true,
      fields: [
        {
          th_label: "admin.transition.action.col.action"
        }, {
          th_label: "admin.transition.action.col.info"
        }
      ],
      footer_left: (function(_this) {
        return function() {
          var action, fn, i, items, len, ref;
          items = [];
          ref = TransitionAction.registeredActions;
          fn = function(action) {
            var cls;
            cls = TransitionAction.classMap[action];
            if (!cls.isSupported() || cls === TransitionAction.classMap["unknown"]) {
              return;
            }
            return items.push({
              text: cls.getDisplayName(),
              onClick: function() {
                return _this.newAction(cls);
              }
            });
          };
          for (i = 0, len = ref.length; i < len; i++) {
            action = ref[i];
            fn(action);
          }
          return [
            {
              icon: "plus",
              loca_key: "transition.action.list.plus",
              group: "plus-minus",
              menu: {
                items: items
              }
            }, {
              icon: "minus",
              loca_key: "transition.action.list.minus",
              group: "plus-minus",
              onClick: function() {
                var ref1;
                if ((ref1 = _this.tree.getSelectedNode()) != null) {
                  ref1.remove();
                }
                CUI.Events.trigger({
                  type: "content-resize",
                  node: _this.tree
                });
                return CUI.Events.trigger({
                  type: "data-changed",
                  node: _this.tree
                });
              }
            }
          ];
        };
      })(this)
    });
    this.tree.render();
    this.tree.load_data(this.actions).always((function(_this) {
      return function() {
        return CUI.Events.trigger({
          node: _this.tree,
          type: "content-resize"
        });
      };
    })(this));
    return this.tree;
  };

  TransitionAction.prototype.getSaveData = function() {
    var action, action_data, i, len, ref, save_data;
    save_data = [];
    ref = this.actions;
    for (i = 0, len = ref.length; i < len; i++) {
      action = ref[i];
      action_data = action.getSaveData();
      if (action_data) {
        save_data.push(action_data);
      }
    }
    return save_data;
  };

  return TransitionAction;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var TransitionActionAction,
  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;

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

  function TransitionActionAction(opts) {
    var lv_column;
    this.opts = opts != null ? opts : {};
    TransitionActionAction.__super__.constructor.call(this, this.opts);
    lv_column = this.getListViewColumn();
    CUI.util.assert(lv_column instanceof CUI.ListViewColumn || (CUI.util.isPlainObject(lv_column) && CUI.util.isFunction(lv_column.type)), (CUI.util.getObjectClass(this)) + ".getListViewColumn", "Needs to return instance of listViewColumn or DataField object opts", {
      listViewColumn: lv_column
    });
    this.opts.fields.push(lv_column);
  }

  TransitionActionAction.prototype.initOpts = function() {
    TransitionActionAction.__super__.initOpts.call(this);
    return this.addOpts({
      transitionAction: {
        mandatory: true,
        check: TransitionAction
      },
      fields: {
        check: Array
      }
    });
  };

  TransitionActionAction.prototype.readOpts = function() {
    this.opts.fields = [
      new CUI.ListViewColumn({
        text: window[this.__cls].getDisplayName()
      })
    ];
    TransitionActionAction.__super__.readOpts.call(this);
    return this.transitionAction = this._transitionAction;
  };

  TransitionActionAction.prototype.getListViewColumn = function() {};

  TransitionActionAction.prototype.getData = function() {
    return this.data;
  };

  TransitionActionAction.prototype.getSaveData = function() {};

  TransitionActionAction.isSupported = function() {
    return true;
  };

  TransitionActionAction.__transitionActionAction = true;

  TransitionActionAction.getType = function() {
    return CUI.util.assert(false, this.name + ".getType", "Needs implementation");
  };

  TransitionActionAction.getDisplayName = function() {
    return CUI.util.assert(false, this.name + ".getDisplayName", "Needs implementation");
  };

  return TransitionActionAction;

})(ListViewEditTreeNode);
// Generated by CoffeeScript 1.12.7
var TransitionActionUnknown,
  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;

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

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

  TransitionActionUnknown.prototype.readOpts = function() {
    return TransitionActionUnknown.__super__.readOpts.call(this);
  };

  TransitionActionUnknown.prototype.getListViewColumn = function() {
    return {
      type: CUI.Output,
      text: $$("transition.action.unknown.text")
    };
  };

  TransitionActionUnknown.prototype.getSaveData = function() {
    return CUI.util.copyObject(this._data, true);
  };

  TransitionActionUnknown.getDisplayName = function() {
    return $$("transition.action.unknown.display_name");
  };

  TransitionActionUnknown.getType = function() {
    return "unknown";
  };

  return TransitionActionUnknown;

})(TransitionActionAction);

TransitionAction.registerAction(TransitionActionUnknown);
// Generated by CoffeeScript 1.12.7
var TransitionActionEmail,
  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;

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

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

  TransitionActionEmail.prototype.readOpts = function() {
    var i, len, rec, ref, ref1, ref2, results;
    TransitionActionEmail.__super__.readOpts.call(this);
    if (this.opts.data.info) {
      this.data = this.opts.data.info;
      this.data.__recipients = [];
      if (this.data.recipients) {
        ref = this.data.recipients;
        results = [];
        for (i = 0, len = ref.length; i < len; i++) {
          rec = ref[i];
          if (ez5.version("6") && ((ref1 = rec.user) != null ? ref1.type : void 0) === "" && ((ref2 = rec.user) != null ? ref2._version : void 0) === 0) {
            continue;
          }
          results.push(this.data.__recipients.push({
            address: rec
          }));
        }
        return results;
      }
    } else {
      return this.data = {
        __recipients: []
      };
    }
  };

  TransitionActionEmail.prototype.getListViewColumn = function() {
    return {
      type: CUI.FormPopover,
      "class": 'ez5-transition-action-email-form',
      button: {
        icon: "email",
        text: $$("transition.action.email.button")
      },
      fields: [
        {
          form: {
            label: $$("transition.action.email.form.recipients")
          },
          type: CUI.DataTable,
          no_header: true,
          name: "__recipients",
          fields: [
            {
              type: UserGroupSelector,
              name: "address",
              aclWhoManager: new AclWhoManager({
                allowEmailUser: true,
                allowPoolUser: true,
                allowOwner: ez5.version("6.10"),
                filter_system_groups: true,
                filter_system_users: true
              })
            }
          ]
        }, {
          form: {
            label: $$("transition.action.email.form.subject")
          },
          name: "subject",
          control: ez5.loca.getLanguageControlAdmin(),
          user_selectable: ez5.session.getPref("languages_user_selection"),
          type: CUI.MultiInput
        }, {
          form: {
            label: $$("transition.action.email.form.message")
          },
          name: "message",
          control: ez5.loca.getLanguageControlAdmin(),
          user_selectable: ez5.session.getPref("languages_user_selection"),
          type: CUI.MultiInput,
          textarea: true
        }, {
          form: {
            label: $$("transition.action.email.form.batchable")
          },
          name: "batchable",
          type: CUI.Checkbox
        }
      ]
    };
  };

  TransitionActionEmail.prototype.getSaveData = function() {
    var i, j, k, len, len1, rec, ref, ref1, saveData;
    saveData = {
      type: "email",
      info: {}
    };
    ref = ["subject", "message", "batchable"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      saveData.info[k] = this.data[k];
    }
    saveData.info.recipients = [];
    ref1 = this.data.__recipients;
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      rec = ref1[j];
      saveData.info.recipients.push(rec.address);
    }
    if (saveData.info.recipients.length === 0) {
      throw new InvalidSaveDataException();
    }
    return saveData;
  };

  TransitionActionEmail.getDisplayName = function() {
    return $$("transition.action.email.displayname");
  };

  TransitionActionEmail.getType = function() {
    return "email";
  };

  return TransitionActionEmail;

})(TransitionActionAction);

TransitionAction.registerAction(TransitionActionEmail);
// Generated by CoffeeScript 1.12.7
var TransitionActionSetTags,
  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;

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

  function TransitionActionSetTags(opts) {
    var i, len, ref, tag;
    this.opts = opts != null ? opts : {};
    this.getListViewColumn = bind(this.getListViewColumn, this);
    TransitionActionSetTags.__super__.constructor.call(this, this.opts);
    this.data = {};
    if (this.opts.data.info) {
      ref = this.opts.data.info.tags;
      for (i = 0, len = ref.length; i < len; i++) {
        tag = ref[i];
        this.data[tag._id] = tag.set;
      }
    }
    return;
  }

  TransitionActionSetTags.prototype.getListViewColumn = function() {
    var lv_column;
    lv_column = new CUI.ListViewColumn();
    lv_column.render = (function(_this) {
      return function() {
        var editor_div;
        editor_div = _this.transitionAction.tagForm.renderForEditor(_this.data);
        return editor_div;
      };
    })(this);
    return lv_column;
  };

  TransitionActionSetTags.prototype.getSaveData = function() {
    var list, ref, tag, tagAnyId, value;
    list = [];
    ref = this.data;
    for (tagAnyId in ref) {
      value = ref[tagAnyId];
      if (tagAnyId === "_node") {
        continue;
      }
      tag = this.transitionAction.tagForm.findTagByAnyId(tagAnyId);
      if (!tag || !(value === false || value === true)) {
        continue;
      }
      list.push({
        "_id": tag.getId(),
        set: value
      });
    }
    if (list.length) {
      return {
        type: "set_tags",
        info: {
          tags: list
        }
      };
    } else {
      return null;
    }
  };

  TransitionActionSetTags.getDisplayName = function() {
    return $$("transition.action.set.tags.displayname");
  };

  TransitionActionSetTags.getType = function() {
    return "set_tags";
  };

  return TransitionActionSetTags;

})(TransitionActionAction);

TransitionAction.registerAction(TransitionActionSetTags);
// Generated by CoffeeScript 1.12.7
var TransitionActionWebhook,
  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;

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

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

  TransitionActionWebhook.prototype.readOpts = function() {
    TransitionActionWebhook.__super__.readOpts.call(this);
    this.data = {};
    if (this.opts.data.info) {
      this.data.name = this.opts.data.info.name;
      return this.data.callback = this.opts.data.info.callback || "after_commit_async";
    }
  };

  TransitionActionWebhook.prototype.getListViewColumn = function() {
    var options, ref, webhooks;
    webhooks = (ref = ez5.session.getBaseConfig().transition_webhook) != null ? ref.webhooks : void 0;
    if (webhooks) {
      options = webhooks.map((function(_this) {
        return function(webhook) {
          return {
            text: webhook.name + (" [" + webhook.url + "]"),
            value: webhook.name
          };
        };
      })(this));
    } else {
      options = [];
    }
    return {
      type: CUI.Form,
      fields: [
        {
          form: {
            label: $$("transition.action.webhook.form.name")
          },
          name: "name",
          type: CUI.Select,
          disabled: options.length === 0,
          options: options
        }, {
          form: {
            label: $$("transition.action.webhook.form.callback")
          },
          name: "callback",
          type: CUI.Select,
          disabled: !ez5.version("6"),
          options: [
            {
              text: "after_commit_async",
              value: "after_commit_async"
            }, {
              text: "pre_save",
              value: "pre_save"
            }
          ]
        }
      ]
    };
  };

  TransitionActionWebhook.prototype.getSaveData = function() {
    var sd;
    sd = {
      type: "webhook",
      info: {
        name: this.data.name || "",
        callback: this.data.callback
      }
    };
    return sd;
  };

  TransitionActionWebhook.getDisplayName = function() {
    return $$("transition.action.webhook.displayname");
  };

  TransitionActionWebhook.getType = function() {
    return "webhook";
  };

  return TransitionActionWebhook;

})(TransitionActionAction);

TransitionAction.registerAction(TransitionActionWebhook);
// Generated by CoffeeScript 1.12.7
var TransitionActionChangeOwner,
  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;

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

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

  TransitionActionChangeOwner.prototype.readOpts = function() {
    TransitionActionChangeOwner.__super__.readOpts.call(this);
    if (this.opts.data.info) {
      return this.data = this.opts.data.info;
    } else {
      return this.data = {
        owner: null
      };
    }
  };

  TransitionActionChangeOwner.prototype.getListViewColumn = function() {
    return {
      form: {
        label: $$("transition.action.change_owner.form.owner")
      },
      type: UserGroupSelector,
      name: "owner",
      aclWhoManager: new AclWhoManager({
        allowEmailUser: false,
        allowPoolUser: true,
        filter_system_groups: true
      })
    };
  };

  TransitionActionChangeOwner.prototype.getSaveData = function() {
    var saveData;
    saveData = {
      type: "change_owner",
      info: CUI.util.copyObject(this.data, true)
    };
    return saveData;
  };

  TransitionActionChangeOwner.getDisplayName = function() {
    return $$("transition.action.change_owner.display_name");
  };

  TransitionActionChangeOwner.getType = function() {
    return "change_owner";
  };

  TransitionActionChangeOwner.isSupported = function() {
    return ez5.version("6");
  };

  return TransitionActionChangeOwner;

})(TransitionActionAction);

TransitionAction.registerAction(TransitionActionChangeOwner);
// Generated by CoffeeScript 1.12.7
var TransitionForm, TransitionFormForManager,
  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;

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

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

  TransitionForm.prototype.initOpts = function() {
    TransitionForm.__super__.initOpts.call(this);
    return this.addOpts({
      tagForm: {
        check: TagForm
      },
      footer_right: {},
      objecttypes: {
        "default": true,
        check: Boolean
      }
    });
  };

  TransitionForm.prototype.readOpts = function() {
    TransitionForm.__super__.readOpts.call(this);
    this.tagForm = this._tagForm;
    return this.transitions = [];
  };

  TransitionForm.prototype.setInactive = function(set) {
    if (set) {
      this.__buttonbar.disable();
    } else {
      this.__buttonbar.enable();
    }
    this.tree.setInactive(set);
    return this.onToggleSelect();
  };

  TransitionForm.prototype.hasObjecttypes = function() {
    return this._objecttypes;
  };

  TransitionForm.prototype.onToggleSelect = function() {
    var selectedNode;
    if (this.tree.isInactive()) {
      return;
    }
    selectedNode = this.tree.getSelectedNode();
    if (selectedNode) {
      this.copyButton.enable();
      this.minusButton.enable();
    } else {
      this.copyButton.disable();
      this.minusButton.disable();
    }
  };

  TransitionForm.prototype.renderEditor = function() {
    var cols, extra_header, fields, i, max_col;
    fields = [
      {
        th_label: "admin.transitionform.col.insert",
        th_rotate_90: true,
        resizable: false
      }, {
        th_label: "admin.transitionform.col.update",
        th_rotate_90: true,
        resizable: false
      }, {
        th_label: "admin.transitionform.col.delete",
        th_rotate_90: true,
        resizable: false
      }, {
        th_label: "admin.transitionform.col.type",
        resizable: false
      }, {
        th_label: "admin.transitionform.col.objecttypes",
        resizable: false
      }, {
        th_label: "admin.transitionform.col.acl"
      }, {
        th_label: "admin.transition.action.col.comment"
      }, {
        th_label: "admin.transitionform.col.tagfilter.before"
      }, {
        th_label: "admin.transitionform.col.tagfilter.after"
      }, {
        th_label: "admin.transitionform.col.confirm"
      }, {
        th_label: "admin.transitionform.col.action"
      }, {
        th_label: "admin.transitionform.col.sticky",
        th_rotate_90: true,
        resizable: false
      }
    ];
    if (ez5.version("6.7")) {
      fields.splice(6, 0, {
        th_label: "admin.transitionform.col.who_not",
        th_rotate_90: true,
        resizable: false
      });
    }
    extra_header = [
      {
        th_label: "admin.transitionform.col.operation",
        th_colspan: 3,
        resizable: false
      }, null, null, null, null, {
        th_label: "admin.transitionform.col.tags",
        th_colspan: 2
      }, null, null, null
    ];
    if (ez5.version("6.7")) {
      extra_header.splice(4, 0, null);
    }
    if (!this.hasObjecttypes()) {
      CUI.util.removeFromArray(null, fields, function(v) {
        return v.th_label === "admin.transitionform.col.objecttypes";
      });
      extra_header.splice(2, 1);
      max_col = 5;
    } else {
      max_col = 6;
    }
    if (ez5.version("6.7")) {
      max_col += 1;
    }
    cols = (function() {
      var j, ref, results;
      results = [];
      for (i = j = 0, ref = fields.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
        results.push("auto");
      }
      return results;
    })();
    cols[max_col] = 'maximize';
    this.copyButton = new LocaButton({
      icon: "copy",
      loca_key: "transition.form.list.copy",
      group: "copy",
      onClick: (function(_this) {
        return function() {
          var selectedNode, transition;
          selectedNode = _this.tree.getSelectedNode();
          if (!selectedNode) {
            return;
          }
          transition = selectedNode.copy();
          _this.tree.addNode(transition);
          transition.select();
          return CUI.Events.trigger({
            type: "data-changed",
            node: _this.tree
          });
        };
      })(this)
    });
    this.minusButton = new LocaButton({
      icon: "minus",
      loca_key: "transition.form.list.minus",
      group: "plus-minus",
      onClick: (function(_this) {
        return function() {
          var ref;
          if ((ref = _this.tree.getSelectedNode()) != null) {
            ref.remove();
          }
          return CUI.Events.trigger({
            type: "data-changed",
            node: _this.tree
          });
        };
      })(this)
    });
    this.__buttonbar = new CUI.Buttonbar({
      buttons: [
        {
          icon: "plus",
          loca_key: "transition.form.list.plus",
          group: "plus-minus",
          onClick: (function(_this) {
            return function() {
              var transition;
              transition = new TagTransition({
                transitionForm: _this,
                data: {}
              });
              _this.tree.addNode(transition);
              return CUI.Events.trigger({
                type: "data-changed",
                node: _this.tree
              });
            };
          })(this)
        }, this.minusButton, this.copyButton
      ]
    });
    this.tree = new ListViewEditTree({
      cols: cols,
      rowMove: true,
      "class": 'cui-lv--has-datafields',
      no_hierarchy: true,
      onSelect: (function(_this) {
        return function() {
          return _this.onToggleSelect();
        };
      })(this),
      onDeselect: (function(_this) {
        return function() {
          return _this.onToggleSelect();
        };
      })(this),
      onRowMove: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            type: "data-changed",
            node: _this.tree
          });
        };
      })(this),
      selectableRows: true,
      footer_right: this._footer_right,
      extra_header: extra_header,
      fields: fields,
      footer_left: this.__buttonbar
    });
    this.tree.render();
    if (this.transitions) {
      this.tree.load_data(this.transitions);
    }
    this.onToggleSelect();
    return this.tree;
  };

  TransitionForm.prototype.getTree = function() {
    return this.tree;
  };

  TransitionForm.prototype.loadTransitions = function(transitions) {
    var j, len, transition;
    this.transitions = [];
    for (j = 0, len = transitions.length; j < len; j++) {
      transition = transitions[j];
      this.transitions.push(new TagTransition({
        data: transition,
        transitionForm: this
      }));
    }
    if (this.tree && !this.tree.isDestroyed()) {
      return this.tree.load_data(this.transitions);
    }
  };

  TransitionForm.prototype.load = function() {
    return ez5.api.transitions().done((function(_this) {
      return function(data) {
        return _this.loadTransitions(data);
      };
    })(this));
  };

  TransitionForm.prototype.getSaveData = function() {
    var c, cantSave, e, j, len, ref, save_data;
    save_data = [];
    cantSave = false;
    ref = this.transitions;
    for (j = 0, len = ref.length; j < len; j++) {
      c = ref[j];
      try {
        save_data.push(c.getSaveData());
      } catch (error) {
        e = error;
        if (!(e instanceof InvalidSaveDataException)) {
          throw e;
        }
        cantSave = true;
      }
    }
    if (cantSave) {
      throw new InvalidSaveDataException();
    }
    return save_data;
  };

  TransitionForm.prototype.destroy = function() {
    var ref;
    if ((ref = this.tree) != null) {
      ref.destroy();
    }
    delete this.tree;
    delete this.transitions;
    return TransitionForm.__super__.destroy.call(this);
  };

  return TransitionForm;

})(CUI.Element);

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

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

  return TransitionFormForManager;

})(TransitionForm);
// Generated by CoffeeScript 1.12.7
var TagTransition,
  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;

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

  function TagTransition() {
    this.getSaveData = bind(this.getSaveData, this);
    return TagTransition.__super__.constructor.apply(this, arguments);
  }

  TagTransition.prototype.initOpts = function() {
    TagTransition.__super__.initOpts.call(this);
    return this.addOpts({
      transitionForm: {
        mandatory: true,
        check: TransitionForm
      },
      data: {
        check: "PlainObject"
      }
    });
  };

  TagTransition.prototype.readOpts = function() {
    var i, j, k, l, len, len1, len2, op, ref, ref1, ref2, type_opts, who;
    TagTransition.__super__.readOpts.call(this);
    this.data = this._data;
    this.transitionForm = this._transitionForm;
    this.tagfilterBefore = new TagFilter({
      data: this.data,
      name: "tagfilter:before",
      tagForm: this.transitionForm.tagForm
    });
    this.tagfilterAfter = new TagFilter({
      data: this.data,
      name: "tagfilter:after",
      tagForm: this.transitionForm.tagForm,
      conditionTypes: ["any", "all", "not", "changed"]
    });
    if (!this.data.actions) {
      this.data.actions = [];
    }
    this.action = new TransitionAction({
      data: this.data.actions,
      tagForm: this.transitionForm.tagForm
    });
    this.data.acl = [];
    if (this.data.who) {
      ref = this.data.who;
      for (i = 0, len = ref.length; i < len; i++) {
        who = ref[i];
        this.data.acl.push({
          who: who
        });
      }
    }
    this.aclManager = new AclManager({
      data: this.data.acl,
      tagForm: this.transitionForm.tagForm,
      right: false,
      tagfilter: false,
      onUpdate: (function(_this) {
        return function() {
          return _this.update();
        };
      })(this)
    });
    if (this.data.operations) {
      ref1 = this.data.operations;
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        op = ref1[j];
        this.data[op.toLowerCase()] = true;
      }
    }
    type_opts = [];
    ref2 = ["process", "resolve", "reject", "exit_resolve", "exit_reject"];
    for (l = 0, len2 = ref2.length; l < len2; l++) {
      k = ref2[l];
      type_opts.push({
        value: k,
        text: $$("tag.transition.type." + k)
      });
    }
    this.opts.fields = [
      {
        type: CUI.Checkbox,
        name: "insert"
      }, {
        type: CUI.Checkbox,
        name: "update"
      }, {
        type: CUI.Checkbox,
        name: "delete"
      }, {
        type: CUI.Select,
        name: "type",
        options: type_opts
      }, {
        type: CUI.FormPopover,
        button: {
          loca_key: "tag.transition.objecttype.button"
        },
        renderDisplayContent: function(popover, data) {
          var d, id, len3, m, ref3;
          if (data.objecttype_ids.length === 0) {
            return new CUI.EmptyLabel({
              text: $$("tag.transition.objecttype.no_filter")
            });
          } else {
            d = CUI.dom.div("ez5-tag-transition-objecttypes");
            ref3 = data.objecttype_ids;
            for (m = 0, len3 = ref3.length; m < len3; m++) {
              id = ref3[m];
              CUI.dom.append(d, new CUI.Label({
                "class": "ez5-tag-transition-objecttype-label",
                text: ez5.schema.CURRENT._table_by_id[id]._name_localized
              }).DOM);
            }
            return d;
          }
        },
        fields: [
          AclRight.prototype.getFieldForObjecttypeSelectParameter.call(this, {
            name: "objecttype_ids"
          })
        ]
      }, this.aclManager.getField(), {
        type: CUI.Input,
        textarea: true,
        name: "comment",
        maximize_horizontal: true
      }, this.tagfilterBefore.getField({
        onDataChanged: (function(_this) {
          return function() {
            return _this.update();
          };
        })(this)
      }), this.tagfilterAfter.getField({
        onDataChanged: (function(_this) {
          return function() {
            return _this.update();
          };
        })(this)
      }), {
        type: CUI.FormPopover,
        button: {
          text: $$("admin.transitionform.col.confirm.button-text")
        },
        popover: {
          pane: {
            padded: true,
            header_left: new CUI.Label({
              text: $$("admin.transitionform.col.confirm.popup-text")
            })
          },
          "class": "ez5-tag-transition-confirm-text-popover"
        },
        fields: [
          {
            type: CUI.MultiInput,
            name: "confirm",
            control: ez5.loca.getLanguageControlAdmin(),
            user_selectable: ez5.session.getPref("languages_user_selection"),
            textarea: true
          }
        ],
        renderDisplayContent: (function(_this) {
          return function(data) {
            if (_this.data.confirm) {
              return new CUI.Label({
                text: ez5.loca.getBestFrontendValue(_this.data.confirm)
              });
            }
          };
        })(this)
      }, this.action.getField(), {
        type: CUI.Checkbox,
        name: "sticky"
      }
    ];
    if (ez5.version("6.7")) {
      this.opts.fields.splice(6, 0, {
        type: CUI.Checkbox,
        name: "who_not"
      });
    }
    if (!this.hasObjecttypes()) {
      this.opts.fields.splice(4, 1);
    }
    return this;
  };

  TagTransition.prototype.operations = ["insert", "update", "delete"];

  TagTransition.prototype.hasObjecttypes = function() {
    return this.transitionForm.hasObjecttypes();
  };

  TagTransition.prototype.getSaveData = function(skip_check) {
    var acl, i, j, k, language, len, len1, problem_text, problems, ref, ref1, ref2, ref3, ref4, row, save_data, value;
    if (skip_check == null) {
      skip_check = false;
    }
    save_data = {
      _id: this.data._id
    };
    if (ez5.version("6.7")) {
      save_data.who_not = !!this.data.who_not;
    }
    save_data.comment = this.data.comment || "";
    save_data.confirm = {};
    ref = this.data.confirm;
    for (language in ref) {
      value = ref[language];
      if (!CUI.util.isEmpty(value)) {
        save_data.confirm[language] = value;
      }
    }
    save_data.operations = [];
    ref1 = ["insert", "update", "delete"];
    for (i = 0, len = ref1.length; i < len; i++) {
      k = ref1[i];
      if (this.data[k]) {
        save_data.operations.push(k.toUpperCase());
      }
    }
    save_data.sticky = !!this.data.sticky;
    save_data.type = this.data.type || "process";
    if (this.hasObjecttypes()) {
      if (((ref2 = this.data.objecttype_ids) != null ? ref2.length : void 0) > 0) {
        save_data.objecttype_ids = this.data.objecttype_ids;
      } else {
        save_data.objecttype_ids = [];
      }
    }
    save_data["tagfilter:before"] = this.tagfilterBefore.getSaveData();
    save_data["tagfilter:after"] = this.tagfilterAfter.getSaveData();
    save_data.actions = this.action.getSaveData();
    save_data.who = [];
    ref3 = this.aclManager.getSaveData();
    for (j = 0, len1 = ref3.length; j < len1; j++) {
      acl = ref3[j];
      save_data.who.push(acl.who);
    }
    if (skip_check) {
      return save_data;
    }
    problems = this.validate(save_data);
    if (problems.length > 0) {
      problem_text = (problems.map(function(p) {
        return " - " + p.message;
      })).join("\n");
      this.addClass("cui-row-invalid");
      if (!this.warning_elem) {
        this.warning_elem = new CUI.Label({
          "class": "cui-label-validation cui-label-danger",
          icon: "failed",
          tooltip: {
            text: problem_text
          }
        });
      }
      row = (ref4 = this.getDOMNodes()) != null ? ref4[0] : void 0;
      if (row) {
        CUI.dom.prepend(row, this.warning_elem.DOM);
      }
      throw new InvalidSaveDataException();
    } else {
      this.removeClass("cui-row-invalid");
      if (this.warning_elem != null) {
        CUI.dom.remove(this.warning_elem.DOM);
      }
      this.warning_elem = null;
    }
    return save_data;
  };

  TagTransition.prototype.validate = function(data) {
    var problems;
    problems = TagTransition.__super__.validate.call(this);
    if (!ez5.version("6")) {
      if ((data.objecttype_ids == null) || data.objecttype_ids.length === 0) {
        problems.push({
          field: "objecttype_ids",
          message: $$("admin.transitionform.col.confirm.objecttype.error")
        });
      }
      if (data.operations.length === 0) {
        problems.push({
          field: "operations",
          message: $$("admin.transitionform.col.confirm.operations.error")
        });
      }
    }
    if (data.who.length === 0) {
      problems.push({
        field: "who",
        message: $$("admin.transitionform.col.confirm.who.error")
      });
    }
    return problems;
  };

  TagTransition.prototype.copy = function() {
    var data;
    data = this.getSaveData(true);
    delete data._id;
    return new TagTransition({
      transitionForm: this.transitionForm,
      data: data
    });
  };

  return TagTransition;

})(ListViewEditTreeNode);
// Generated by CoffeeScript 1.12.7
var RightPreset,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function RightPreset(data) {
    if (data == null) {
      data = {};
    }
    RightPreset.__super__.constructor.call(this);
    if (data instanceof RightPreset) {
      this.setData(data.getData());
    } else {
      this.setData(data);
    }
  }

  RightPreset.prototype.setData = function(data1) {
    this.data = data1 != null ? data1 : {};
    CUI.util.assert(this.data._basetype === "right_preset", "new RightPreset", "data._basetype needs to be \"right_preset\"");
    this.__right_preset = this.data.right_preset;
    return this.__signature = null;
  };

  RightPreset.prototype.storeSaveData = function() {
    return this.__signature = JSON.stringify(this.getSaveData());
  };

  RightPreset.prototype.getStoredSaveData = function() {
    return this.__signature;
  };

  RightPreset.prototype.setManager = function(manager) {
    this.manager = manager;
    return CUI.util.assert(this.manager instanceof RightPresetManager, "RightPreset.setManager", "manager needs to be instance of RightPresetManager", {
      manager: this.manager
    });
  };

  RightPreset.prototype.getData = function() {
    return this.data;
  };

  RightPreset.prototype.getManageRecord = function() {
    var i, k, len, rec, ref;
    rec = {
      _id: this.getId(),
      _instance: this
    };
    ref = ["displayname", "description"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      if (this.__right_preset.displayname) {
        rec[k] = CUI.util.copyObject(this.__right_preset[k], true);
      } else {
        rec[k] = {};
      }
    }
    console.debug("manage record", CUI.util.dump(rec));
    return rec;
  };

  RightPreset.prototype.getSaveData = function() {
    var key, presetKeys, saveData;
    saveData = CUI.util.copyObject(this.getData(), true);
    delete saveData.right_preset._undo;
    presetKeys = this.manager.getPresetKeys();
    for (key in saveData.right_preset.preset) {
      if (indexOf.call(presetKeys, key) < 0) {
        delete saveData.right_preset.preset[key];
      } else {
        if (!ez5.version("6") && CUI.util.isEmptyObject(saveData.right_preset.preset[key])) {
          saveData.right_preset.preset[key] = null;
        }
      }
    }
    if (ez5.version("6") && this.manager.getServerContext() === "collection") {
      if (saveData.right_preset.default_expiration_hours != null) {
        saveData.right_preset.preset.default_expiration_hours = parseInt(saveData.right_preset.default_expiration_hours, 10);
      } else {
        saveData.right_preset.preset.default_expiration_hours = null;
      }
      delete saveData.right_preset.default_expiration_hours;
    }
    return saveData;
  };

  RightPreset.prototype.getId = function() {
    return this.__right_preset._id || null;
  };

  RightPreset.prototype.setPosition = function(pos) {
    var signautureObj;
    if (this.getId()) {
      this.__right_preset._version++;
      if (this.__signature) {
        signautureObj = JSON.parse(this.__signature);
        signautureObj.right_preset._position = pos;
        signautureObj.right_preset._version++;
        this.__signature = JSON.stringify(signautureObj);
      }
    }
    return this.__right_preset._position = pos;
  };

  RightPreset.prototype.getPosition = function() {
    if (CUI.util.isNull(this.__right_preset._position)) {
      return null;
    } else {
      return this.__right_preset._position;
    }
  };

  RightPreset.prototype.getPreset = function() {
    return CUI.util.copyObject(this.__right_preset.preset, true);
  };

  RightPreset.prototype.setPreset = function(preset) {
    return this.__right_preset.preset = preset;
  };

  RightPreset.prototype.getDisplayname = function() {
    return ez5.loca.getBestFrontendValue(this.__right_preset.displayname);
  };

  RightPreset.prototype.renderContent = function() {
    if (this.getId()) {
      return new CUI.Label({
        text: this.getDisplayname()
      });
    } else {
      return new CUI.Label({
        content: $empty$("right.preset.new")
      });
    }
  };

  RightPreset.prototype.isEmptyPreset = function() {
    var has_object, k, ref, v;
    has_object = false;
    ref = this.getPreset();
    for (k in ref) {
      v = ref[k];
      if (!CUI.util.isEmptyObject(v)) {
        has_object = true;
        break;
      }
    }
    if (!has_object) {
      return true;
    } else {
      return false;
    }
  };

  RightPreset.prototype.check_deselect = function() {
    if (this.isChanged()) {
      return CUI.confirm({
        text: $$("general.frontend.unsaved_changes.message"),
        button_text_ok: $$("general.frontend.unsaved_changes.confirm"),
        button_primary: "cancel"
      });
    } else {
      return CUI.resolvedPromise();
    }
  };

  RightPreset.prototype.isChanged = function() {
    var a;
    if (this.getStoredSaveData() === null) {
      return false;
    } else if ((a = JSON.stringify(this.getSaveData())) !== this.getStoredSaveData()) {
      return true;
    } else {
      return false;
    }
  };

  RightPreset.prototype.getDescription = function() {
    return ez5.loca.getBestFrontendValue(this.__right_preset.description);
  };

  RightPreset.prototype.getSelectOption = function() {
    var description, opts;
    opts = {
      text: this.getDisplayname(),
      value: this.getId()
    };
    description = this.getDescription();
    if (description) {
      opts.tooltip = {
        text: description
      };
    }
    return opts;
  };

  RightPreset.prototype.applyPreset = function(data) {
    var key, ref, value;
    ref = this.getPreset();
    for (key in ref) {
      value = ref[key];
      data[key] = value;
    }
    return this;
  };

  RightPreset.prototype.deselect = function(ev) {
    return RightPreset.__super__.deselect.call(this, ev).done((function(_this) {
      return function() {
        _this.setData(JSON.parse(_this.getStoredSaveData()));
        if (ev) {
          _this.manager.emptyEditPane();
        }
        return _this.update();
      };
    })(this));
  };

  RightPreset.prototype["delete"] = function(ev) {
    var dfr, remove;
    remove = (function(_this) {
      return function() {
        _this.manager.emptyEditPane();
        _this.remove();
        return dfr.resolve();
      };
    })(this);
    dfr = new CUI.Deferred();
    if (!this.getId()) {
      remove();
    } else {
      ez5.api.right({
        type: "DELETE",
        api: "/" + this.manager.getServerContext() + "/presets/" + this.getId()
      }).done(function() {
        ez5.aclRights.load().done((function(_this) {
          return function() {
            return RightPresetManager.init();
          };
        })(this));
        return remove();
      }).fail(function() {
        return dfr.reject();
      });
    }
    return dfr.promise();
  };

  RightPreset.prototype.save = function(ev) {
    var maxPos, sd;
    sd = this.getSaveData();
    if (!sd.right_preset._version) {
      sd.right_preset._version = 1;
      if (CUI.util.isNull(sd.right_preset._position)) {
        maxPos = this.manager.getMaxPresetPosition();
        if (maxPos === null) {
          sd.right_preset._position = 0;
        } else {
          sd.right_preset._position = maxPos + 1;
        }
      }
    } else {
      sd.right_preset._version++;
    }
    if (ev.hasModifierKey()) {
      console.debug(CUI.util.dump(sd));
      return new CUI.Deferred().reject().promise();
    }
    ez5.splash.show('system.list.manager.item.saving');
    return ez5.api.right({
      type: "POST",
      api: "/" + this.manager.getServerContext() + "/presets",
      json_data: [sd]
    }).done((function(_this) {
      return function(data) {
        ez5.aclRights.load().done(function() {
          return RightPresetManager.init();
        });
        _this.setData(data[0]);
        _this.show();
        return ez5.splash.done('system.list.manager.item.saved');
      };
    })(this)).fail((function(_this) {
      return function() {
        return ez5.splash.hide();
      };
    })(this));
  };

  RightPreset.prototype.show = function() {
    var wb;
    wb = new CUI.WaitBlock({
      element: this.manager.getEditPane(),
      text: $$("right.preset.manager.loading")
    }).show();
    return CUI.setTimeout((function(_this) {
      return function() {
        _this.__show();
        return wb.destroy();
      };
    })(this), 0);
  };

  RightPreset.prototype.__show = function() {
    var data_changed, expirationOptions, generalFields, hours, i, key, label, len, ref, ref1, ref2, save_btn, t, tabs, update_save_btn;
    if (ez5.version("6") && this.manager.getServerContext() === "collection" && (((ref = this.data.right_preset.preset) != null ? ref.default_expiration_hours : void 0) != null)) {
      this.data.right_preset.default_expiration_hours = this.data.right_preset.preset.default_expiration_hours;
    }
    this.aclRightManager = new AclRightManager({
      context: AclRights.getFrontendContextByServerContext(this.manager.getServerContext()),
      data: this.data.right_preset.preset,
      name: "rights"
    });
    this.tagFilter = new TagFilter({
      tagForm: this.manager.getTagForm(),
      data: this.data.right_preset.preset,
      name: "tagfilter"
    });
    save_btn = new CUI.Button({
      disabled: true,
      primary: true,
      text: $$("base.save"),
      onClick: (function(_this) {
        return function(ev) {
          return _this.save(ev).done(function() {
            update_save_btn();
            return _this.update();
          });
        };
      })(this)
    });
    update_save_btn = (function(_this) {
      return function() {
        if (_this.isChanged() && !CUI.util.isEmpty(_this.getDisplayname()) && !CUI.util.isEmptyObject(_this.__right_preset.preset.rights)) {
          return save_btn.enable();
        } else {
          return save_btn.disable();
        }
      };
    })(this);
    data_changed = (function(_this) {
      return function() {
        return update_save_btn();
      };
    })(this);
    generalFields = [
      {
        form: {
          label: $$("right.preset.manager.id")
        },
        type: CUI.Output,
        name: "_id"
      }, {
        form: {
          label: $$("right.preset.manager.displayname")
        },
        name: "displayname",
        type: CUI.MultiInput,
        control: ez5.loca.getLanguageControlAdmin(),
        user_selectable: ez5.session.getPref("languages_user_selection")
      }, {
        form: {
          label: $$("right.preset.manager.description")
        },
        name: "description",
        type: CUI.MultiInput,
        textarea: true,
        control: ez5.loca.getLanguageControlAdmin(),
        user_selectable: ez5.session.getPref("languages_user_selection")
      }
    ];
    if (ez5.version("6") && this.manager.getServerContext() === "collection") {
      expirationOptions = [];
      ref1 = RightPreset.getExpirationLabels();
      for (hours in ref1) {
        label = ref1[hours];
        expirationOptions.push({
          text: label,
          value: parseInt(hours)
        });
      }
      generalFields.push({
        form: {
          label: $$("right.preset.manager.default_expiration")
        },
        name: "default_expiration_hours",
        type: ComboBox,
        inputType: "number",
        disableKeyEvents: true,
        showDisplayValue: true,
        options: expirationOptions,
        placeholder: $$("right.preset.manager.expiration.placeholder"),
        valueConverter: {
          toStoredValue: function(days) {
            return days * 24;
          },
          toDisplayValue: function(hours) {
            return hours / 24;
          }
        },
        customValueLabel: {
          singular: $$("right.preset.manager.expiration.day.singular"),
          plural: $$("right.preset.manager.expiration.day.plural")
        }
      });
    }
    if (ez5.version("6.12")) {
      generalFields.push({
        type: CUI.Output,
        form: {
          label: $$("admin.pool.created_timestamp")
        },
        name: "_created_at",
        data: this.data,
        getValue: (function(_this) {
          return function(v) {
            return ez5.format_date_and_time(v, true);
          };
        })(this),
        placeholder: $$("admin.pool.created_timestamp.new")
      }, {
        type: CUI.Output,
        form: {
          label: $$("admin.pool.last_updated_timestamp")
        },
        name: "_updated_at",
        data: this.data,
        getValue: (function(_this) {
          return function(v) {
            return ez5.format_date_and_time(v, true);
          };
        })(this),
        placeholder: $$("admin.pool.last_updated_timestamp.new")
      });
    }
    tabs = [
      {
        text: $$("right.preset.tab.general"),
        content: (function(_this) {
          return function() {
            return new CUI.Form({
              data: _this.data.right_preset,
              onDataChanged: data_changed,
              fields: generalFields
            }).start();
          };
        })(this)
      }
    ];
    ref2 = this.manager.getPresetKeys();
    for (i = 0, len = ref2.length; i < len; i++) {
      key = ref2[i];
      tabs.push((function() {
        switch (key) {
          case "rights":
            return {
              text: $$("right.preset.tab.rights"),
              content: (function(_this) {
                return function() {
                  var right_form;
                  return right_form = _this.aclRightManager.getForm({
                    onDataChanged: data_changed
                  }).start();
                };
              })(this)
            };
          case "tagfilter":
            return {
              text: $$("right.preset.tab.tagfilter"),
              content: (function(_this) {
                return function() {
                  var tagfilter_field;
                  return tagfilter_field = _this.tagFilter.getDataFieldProxy({
                    onDataChanged: data_changed
                  }).start();
                };
              })(this)
            };
        }
      }).call(this));
    }
    t = new CUI.Tabs({
      "class": "ez5-rights-preset-tabs",
      tabs: tabs,
      padded: true,
      active_idx: this.getActiveTabIdx(),
      onActivate: (function(_this) {
        return function(tabs, tab) {
          var idx;
          if (_this.manager) {
            idx = CUI.dom.getAttribute(tabs.DOM, "active-tab-idx") || 0;
            return _this.manager.__active_tab_idx = parseInt(idx);
          }
        };
      })(this),
      footer_right: [
        {
          text: $$("base.cancel"),
          onClick: (function(_this) {
            return function(ev) {
              return _this.deselect(ev);
            };
          })(this)
        }, save_btn
      ]
    });
    this.manager.getEditPane().replace(t, "center");
    if (this.getStoredSaveData() === null) {
      this.storeSaveData();
    }
    return update_save_btn();
  };

  RightPreset;

  RightPreset.getExpirationLabels = function() {
    return {
      168: $$("right.preset.manager.expiration.week"),
      336: $$("right.preset.manager.expiration.two_weeks"),
      720: $$("right.preset.manager.expiration.month"),
      1440: $$("right.preset.manager.expiration.two_months"),
      2160: $$("right.preset.manager.expiration.three_months"),
      4320: $$("right.preset.manager.expiration.six_months"),
      8760: $$("right.preset.manager.expiration.year")
    };
  };

  RightPreset.getExpirationText = function(hours) {
    var days;
    if (hours === null) {
      return null;
    }
    if (this.getExpirationLabels()[hours]) {
      return this.getExpirationLabels()[hours];
    } else {
      days = hours / 24;
      if (days === 1) {
        return "" + days + " " + $$("right.preset.manager.expiration.day.singular");
      } else {
        return "" + days + " " + $$("right.preset.manager.expiration.day.plural");
      }
    }
  };

  RightPreset.prototype.getActiveTabIdx = function() {
    var ref;
    return ((ref = this.manager) != null ? ref.__active_tab_idx : void 0) || 0;
  };

  RightPreset.createNew = function(preset) {
    var right_preset;
    if (preset == null) {
      preset = {};
    }
    right_preset = {
      _basetype: "right_preset",
      right_preset: {
        displayname: {},
        description: {},
        preset: preset
      }
    };
    return new RightPreset(right_preset);
  };

  return RightPreset;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var RightPresetManager,
  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;

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

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

  RightPresetManager.prototype.initOpts = function() {
    RightPresetManager.__super__.initOpts.call(this);
    return this.addOpts({
      manager: {
        check: RightPresetManagerAdmin
      },
      server_context: {
        mandatory: true,
        check: function(v) {
          if (AclRights.getFrontendContextByServerContext(v)) {
            return true;
          } else {
            return "server_context \"" + v + "\" does not exist.";
          }
        }
      }
    });
  };

  RightPresetManager.prototype.readOpts = function() {
    RightPresetManager.__super__.readOpts.call(this);
    return this.__server_context_displayname = AclRights.getDisplaynameByServerContext(this._server_context);
  };

  RightPresetManager.prototype.getServerContextDisplayname = function() {
    return this.__server_context_displayname;
  };

  RightPresetManager.prototype.getServerContext = function() {
    return this._server_context;
  };

  RightPresetManager.prototype.renderContent = function() {
    return new CUI.Label({
      text: this.getServerContextDisplayname()
    });
  };

  RightPresetManager.prototype.getPresets = function() {
    return RightPresetManager.getByServerContext(this._server_context);
  };

  RightPresetManager.prototype.getField = function(_opts) {
    var _data, opts;
    if (_opts == null) {
      _opts = {};
    }
    _data = null;
    opts = CUI.Element.readOpts(_opts, "RightPresetManager.getField", {
      onDataChanged: {
        check: Function
      },
      allow_custom: {
        "default": false,
        check: Boolean
      },
      onRender: {
        check: Function
      }
    });
    return {
      type: CUI.Select,
      form: {
        label: $$("right.preset.manager.form.label")
      },
      name: "_right_preset",
      onDataInit: (function(_this) {
        return function(df, __data) {
          var preset;
          _data = __data;
          preset = _this.__getPresetById(_data[df.getName()]);
          if (preset) {
            return preset.applyPreset(_data);
          }
        };
      })(this),
      onRender: (function(_this) {
        return function(field) {
          return typeof opts.onRender === "function" ? opts.onRender(field) : void 0;
        };
      })(this),
      tooltip: {
        text: (function(_this) {
          return function() {
            if (_data._right_preset === null) {
              return;
            }
            return _this.__getPresetById(_data._right_preset).getDescription();
          };
        })(this)
      },
      onDataChanged: (function(_this) {
        return function(data, df) {
          var preset;
          preset = _this.__getPresetById(data[df.getName()]);
          if (preset) {
            preset.applyPreset(data);
            if (typeof opts.onDataChanged === "function") {
              opts.onDataChanged(data, df);
            }
          }
        };
      })(this),
      options: (function(_this) {
        return function(df) {
          var i, len, options, preset, presets;
          options = [];
          preset = df.getValue();
          presets = _this.getPresets();
          for (i = 0, len = presets.length; i < len; i++) {
            preset = presets[i];
            options.push(preset.getSelectOption());
          }
          options.push({
            disabled: !opts.allow_custom,
            text: $$("right.preset.manager.preset.custom"),
            value: null
          });
          if (presets.length === 0) {
            options.push({
              disabled: true,
              text: $$("right.preset.manager.preset.no_presets"),
              value: void 0
            });
          }
          return options;
        };
      })(this)
    };
  };

  RightPresetManager.prototype.getPresetData = function(data) {
    var i, key, len, preset, ref;
    preset = {};
    ref = this.getPresetKeys();
    for (i = 0, len = ref.length; i < len; i++) {
      key = ref[i];
      if (data[key]) {
        preset[key] = CUI.util.copyObject(data[key], true);
      } else {
        preset[key] = null;
      }
    }
    return preset;
  };

  RightPresetManager.prototype.getPresetKeys = function() {
    if (ez5.aclRights.hasCapByServerContext("tagfilter", this._server_context) && ez5.tagForm.getAllTags().length > 0) {
      return ["rights", "tagfilter"];
    } else {
      return ["rights"];
    }
  };

  RightPresetManager.prototype.__getPresetById = function(id) {
    if (id === null) {
      return null;
    }
    return CUI.util.findInArray(id, this.getPresets(), function(preset, id) {
      return preset.getId() === id;
    });
  };

  RightPresetManager.prototype.getSaveData = function() {
    return this.data;
  };

  RightPresetManager.prototype.getEditPane = function() {
    return this.editPane;
  };

  RightPresetManager.prototype.emptyEditPane = function() {
    return this.editPane.replace(new CUI.EmptyLabel({
      centered: true,
      multiline: true,
      text: $$("right.preset.manager.empty")
    }), "center");
  };

  RightPresetManager.prototype.hasChanges = function() {
    var i, len, preset, ref;
    if (!this.tree) {
      return false;
    }
    ref = this.tree.root.children;
    for (i = 0, len = ref.length; i < len; i++) {
      preset = ref[i];
      if (preset.isChanged()) {
        return true;
      }
    }
    return false;
  };

  RightPresetManager.prototype.getTagForm = function() {
    return this.tagForm;
  };

  RightPresetManager.prototype.load = function() {
    return CUI.resolvedPromise();
  };

  RightPresetManager.prototype.getMaxPresetPosition = function() {
    var i, idx, len, maxPos, pos, preset, ref;
    maxPos = null;
    ref = this.getPresets();
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      preset = ref[idx];
      pos = preset.getPosition();
      console.debug(maxPos, preset, pos, idx);
      if (pos > maxPos || maxPos === null) {
        maxPos = pos;
      }
    }
    return maxPos;
  };

  RightPresetManager.prototype.show = function() {
    var hl, loadPresets, minus_btn, plus_btn, presets, update_minus_btn;
    plus_btn = new LocaButton({
      icon: "plus",
      loca_key: "right.present.manager.list.button.plus",
      group: "plusminus",
      onClick: (function(_this) {
        return function() {
          var rightPreset;
          rightPreset = RightPreset.createNew(_this.getPresetData({}));
          return _this.tree.addNode(rightPreset).done(function() {
            rightPreset.setManager(_this);
            return rightPreset.select().done(function() {
              return rightPreset.show();
            }).fail(function() {
              return rightPreset.remove();
            }).always(function() {
              return update_minus_btn();
            });
          });
        };
      })(this)
    });
    minus_btn = new LocaButton({
      icon: "minus",
      loca_key: "right.present.manager.list.button.minus",
      disabled: true,
      group: "plusminus",
      onClick: (function(_this) {
        return function(ev) {
          var preset, remove_node;
          preset = _this.tree.getSelectedNode();
          remove_node = function() {
            return preset.deselect().done(function() {
              return preset["delete"]().done(function() {
                return RightPresetManager.init();
              });
            });
          };
          if (preset.getId()) {
            return CUI.confirm({
              text: $$("right.present.manager.list.button.minus.confirm"),
              button_primary: "cancel"
            }).done(remove_node);
          } else {
            return remove_node();
          }
        };
      })(this)
    });
    update_minus_btn = (function(_this) {
      return function() {
        if (_this.tree.getSelectedNode()) {
          return minus_btn.enable();
        } else {
          return minus_btn.disable();
        }
      };
    })(this);
    loadPresets = (function(_this) {
      return function() {
        var i, len, p, preset, ref, rightPreset;
        p = [];
        ref = _this.getPresets();
        for (i = 0, len = ref.length; i < len; i++) {
          preset = ref[i];
          rightPreset = new RightPreset(preset);
          rightPreset.setManager(_this);
          p.push(rightPreset);
        }
        return p;
      };
    })(this);
    presets = loadPresets();
    this.tree = new CUI.ListViewTree({
      "class": "ez5-preset-list-view-tree",
      cols: ["maximize"],
      selectableRows: true,
      onSelect: (function(_this) {
        return function(ev, info) {
          update_minus_btn();
          return info.node.show();
        };
      })(this),
      onDeselect: (function(_this) {
        return function(ev, info) {
          return update_minus_btn();
        };
      })(this),
      rowMove: true,
      no_hierarchy: true,
      children: presets,
      footer_left: [plus_btn, minus_btn]
    });
    CUI.Events.listen({
      node: this.tree,
      type: "row_moved",
      call: (function(_this) {
        return function(ev, info) {
          var i, idx, len, preset, ref, save_data, sd;
          save_data = [];
          ref = _this.tree.getRootChildren();
          for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
            preset = ref[idx];
            preset.setPosition(idx);
            sd = preset.getSaveData();
            save_data.push(sd);
          }
          return ez5.api.right({
            type: "POST",
            api: "/" + _this.getServerContext() + "/presets",
            json_data: save_data
          }).done(function(data) {
            return ez5.aclRights.load().done(function() {
              return RightPresetManager.init();
            });
          });
        };
      })(this)
    });
    this.editPane = new CUI.SimplePane({
      "class": "cui-pane--window",
      title: $$("right.preset.manager.editor.title")
    });
    hl = new CUI.HorizontalLayout({
      absolute: true,
      left: {
        "class": "ez5-right-preset-manager-left",
        content: new CUI.SimplePane({
          "class": "cui-pane--window",
          title: this.manager.getCenterTitle(),
          content: this.tree.render()
        }),
        flexHandle: {
          state_name: 'right-preset-manager'
        }
      },
      center: {
        content: this.editPane
      }
    });
    this.tagForm = new TagForm({
      context: AclRights.getFrontendContextByServerContext(this.getServerContext())
    });
    this.tree.root.open();
    this.tagForm.load().done((function(_this) {
      return function() {
        var cnt;
        _this.emptyEditPane();
        cnt = _this.manager.getContainer();
        return CUI.dom.replace(cnt, hl);
      };
    })(this));
    return this;
  };

  RightPresetManager.__presetsByServerContext = {};

  RightPresetManager.getServerContexts = function() {
    return Object.keys(this.__presetsByServerContext);
  };

  RightPresetManager.getByServerContext = function(server_context) {
    var presets;
    presets = this.__presetsByServerContext[server_context];
    CUI.util.assert(CUI.util.isArray(presets), "RightPresetManager.getByServerContext", "presets not found for server context: \"" + server_context + "\".", {
      allPresets: this.__presetsByServerContext
    });
    return presets;
  };

  RightPresetManager.init = function() {
    var context, i, info, len, preset, ref, ref1;
    RightPresetManager.__presetsByServerContext = {};
    ref = ez5.aclRights.getContexts();
    for (context in ref) {
      info = ref[context];
      if (!info.capabilities.preset) {
        continue;
      }
      this.__presetsByServerContext[context] = [];
      if (!info.presets) {
        continue;
      }
      ref1 = info.presets;
      for (i = 0, len = ref1.length; i < len; i++) {
        preset = ref1[i];
        this.__presetsByServerContext[context].push(new RightPreset(preset));
      }
      this.__presetsByServerContext[context].sort(function(a, b) {
        return a.getPosition() - b.getPosition();
      });
    }
  };

  return RightPresetManager;

})(SystemListManagerItem);
// Generated by CoffeeScript 1.12.7
var AclManager,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function AclManager(opts1) {
    this.opts = opts1 != null ? opts1 : {};
    this.WEGdisableAclWho = bind(this.WEGdisableAclWho, this);
    this.loadFromData = bind(this.loadFromData, this);
    AclManager.__super__.constructor.call(this, this.opts);
    this.aclWhoManager = new AclWhoManager({
      name: "who",
      allowEmailUser: this._allowEmailUser,
      allowPoolUser: this._allowPoolUser,
      allowMatchAny: this._allowMatchAny,
      allowOwner: this._allowOwner,
      filter_system_groups: this._filter_system_groups,
      filter_system_users: this._filter_system_users
    });
    this.loadFromData(this._data);
  }

  AclManager.prototype.initOpts = function() {
    AclManager.__super__.initOpts.call(this);
    return this.addOpts({
      context: {},
      onUpdate: {
        check: Function
      },
      onNewAclItem: {
        check: Function
      },
      allowMatchAny: {
        check: Boolean
      },
      allowOwner: {
        check: Boolean
      },
      allowCollectionUser: {
        check: Boolean
      },
      filter_system_groups: {
        check: Boolean
      },
      filter_system_users: {
        check: Boolean
      },
      allow_empty_rights: {
        "default": false,
        mandatory: true,
        check: Boolean
      },
      allowEmailUser: {
        check: Boolean
      },
      allowPoolUser: {
        check: Boolean
      },
      tagForm: {
        check: TagForm
      },
      data: {
        check: "Array"
      },
      footer_right: {},
      right_filter: {
        check: Function
      },
      date_created: {
        check: Boolean
      },
      preset: {
        check: Boolean
      },
      right: {
        check: Boolean
      },
      tagfilter: {
        check: Boolean
      },
      sticky: {
        check: Boolean
      },
      valid_from: {
        check: Boolean
      },
      valid_to: {
        check: Boolean
      },
      active: {
        check: Boolean
      },
      email_notification: {
        check: Boolean
      },
      email_notification_form: {
        check: Boolean
      },
      share_link: {
        check: Boolean
      },
      invalid_acl: {
        check: Boolean
      },
      expert_menu: {
        check: (function(_this) {
          return function(v) {
            var col, cols, i, len;
            if (!CUI.util.isArray(v) || v.length === 0) {
              return "needs to be Array";
            }
            cols = _this.availableColumns();
            for (i = 0, len = v.length; i < len; i++) {
              col = v[i];
              if (indexOf.call(cols, col) < 0) {
                return ("\"" + col + "\" needs to be one of ") + cols.join(", ");
              }
            }
            return true;
          };
        })(this)
      },
      acl_counter_loca_key: {
        check: String,
        "default": "acl.manager.acl-counter"
      },
      check_who_readable: {
        check: Boolean,
        "default": false
      }
    });
  };

  AclManager.prototype.readOpts = function() {
    var cap, cap_server, i, len, ref, results;
    AclManager.__super__.readOpts.call(this);
    if (this._right || this._tagfilter) {
      CUI.util.assert(this._context, "AclManager", "With opts.right or opts.tagfilter set to true, opts.context is required.", {
        opts: this.opts
      });
    }
    if (this._context) {
      ref = {
        active: "active",
        email_notification: "email",
        preset: "preset",
        sticky: "sticky",
        tagfilter: "tagfilter",
        valid_from: "valid",
        valid_to: "value"
      };
      results = [];
      for (cap_server = i = 0, len = ref.length; i < len; cap_server = ++i) {
        cap = ref[cap_server];
        if (!this.hasColumn(cap)) {
          continue;
        }
        results.push(CUI.util.assert(ez5.aclRights.hasCapByFrontendContext(cap_server, this._context), "context " + (AclRights.getServerContextByFrontendContext(this._context)) + " has no capability \"" + cap_server + "\"."));
      }
      return results;
    }
  };

  AclManager.prototype.hasColumn = function(column) {
    if (!this["_" + column] && (!this._expert_menu || indexOf.call(this._expert_menu, column) < 0)) {
      return false;
    } else {
      return true;
    }
  };

  AclManager.prototype.availableColumns = function() {
    return ["active", "who", "preset", "right", "tagfilter", "sticky", "valid_from", "valid_to", "email_notification_form", "email_notification", "email_language", "email_notification_text", "share_link", "date_created", "expert_menu", "invalid_acl"];
  };

  AclManager.prototype.getColumns = function() {
    var col, cols, i, len, ref;
    cols = [];
    ref = this.availableColumns();
    for (i = 0, len = ref.length; i < len; i++) {
      col = ref[i];
      if (col === "who" || this["_" + col]) {
        cols.push(col);
      }
    }
    return cols;
  };

  AclManager.prototype.getExpertMenuColumns = function() {
    return this._expert_menu;
  };

  AclManager.prototype.getAllColumns = function() {
    var all_cols, col, expert_menu, i, len;
    all_cols = this.getColumns().slice(0);
    expert_menu = this.getExpertMenuColumns();
    if (expert_menu) {
      for (i = 0, len = expert_menu.length; i < len; i++) {
        col = expert_menu[i];
        if (indexOf.call(all_cols, col) < 0) {
          all_cols.push(col);
        }
      }
    }
    return all_cols;
  };

  AclManager.prototype.getContext = function() {
    return this._context;
  };

  AclManager.prototype.getTagForm = function() {
    CUI.util.assert(this._tagForm instanceof TagForm, "AclManager.getTagForm", "tagForm needs to be set", {
      tagForm: this._tagForm
    });
    return this._tagForm;
  };

  AclManager.prototype.getAclWhoManager = function() {
    return this.aclWhoManager;
  };

  AclManager.prototype.loadFromData = function(data) {
    var acl_data, i, len, results;
    this.acl = [];
    if (data != null ? data.length : void 0) {
      results = [];
      for (i = 0, len = data.length; i < len; i++) {
        acl_data = data[i];
        results.push(this.acl.push(new AclItem({
          data: acl_data,
          aclManager: this
        })));
      }
      return results;
    }
  };

  AclManager.prototype.getField = function(opts) {
    if (opts == null) {
      opts = {};
    }
    return {
      onConstruct: (function(_this) {
        return function(__popoverButton) {
          _this.__popoverButton = __popoverButton;
        };
      })(this),
      type: CUI.FormPopover,
      maximize: true,
      "class": "ez5-acl-manager-popover-starter",
      button: {
        loca_key: "acl.manager.button.open_popover"
      },
      popover: {
        pane: {
          header_left: new CUI.Label({
            text: $$("acl.manager.popover.title")
          }),
          padded: false
        },
        placement: "w",
        "class": "acl-manager-popover",
        onHide: (function(_this) {
          return function() {
            if (_this.__dataChanged) {
              if (typeof _this._onUpdate === "function") {
                _this._onUpdate();
              }
              CUI.Events.trigger({
                node: _this.__popoverButton,
                type: "editor-changed"
              });
            }
          };
        })(this)
      },
      fields: [
        {
          type: CUI.DataFieldProxy,
          maximize_horizontal: true,
          call_others: false,
          onDataChanged: function(data, df) {
            return console.debug("data changed in acl manager", df.getForm());
          },
          element: (function(_this) {
            return function() {
              return _this.getTree();
            };
          })(this)
        }
      ],
      renderDisplayContent: (function(_this) {
        return function() {
          if (_this.acl.length === 0 && opts.empty_loca_key) {
            return new CUI.EmptyLabel({
              text: $$(opts.empty_loca_key)
            });
          } else {
            return ez5.getLabelForCount(_this._acl_counter_loca_key, _this.acl.length);
          }
        };
      })(this)
    };
  };

  AclManager.prototype.newAclItem = function(data) {
    var action, actionWho;
    if (data == null) {
      data = {};
    }
    if (!data.hasOwnProperty("active")) {
      data.active = true;
    }
    action = new AclItem({
      data: data,
      aclManager: this
    });
    actionWho = action.getWho();
    if (actionWho instanceof AclWhoCollection) {
      actionWho.showCreateModal();
    }
    return this.tree.addNode(action).done((function(_this) {
      return function() {
        if (typeof _this._onNewAclItem === "function") {
          _this._onNewAclItem(action);
        }
        CUI.Events.trigger({
          type: "data-changed",
          node: _this.tree
        });
        return action.select();
      };
    })(this));
  };

  AclManager.prototype.getTree = function() {
    var add_user_group, btn_opts, canCreateAnonymousLink, col, i, items, len, ref, th_col, tree_opts;
    this.minusButton = new LocaButton({
      "class": "ez5-remove-right-button",
      loca_key: "acl.manager.button.minus",
      icon: "minus",
      disabled: true,
      group: "plusminus",
      onClick: (function(_this) {
        return function() {
          var ref;
          if ((ref = _this.tree.getSelectedNode()) != null) {
            ref.remove();
          }
          return CUI.Events.trigger({
            type: "data-changed",
            node: _this.tree
          });
        };
      })(this)
    });
    btn_opts = {
      "class": "ez5-add-right-button",
      loca_key: "acl.manager.button.plus",
      icon: "plus",
      group: "plusminus"
    };
    items = [];
    canCreateAnonymousLink = (function(_this) {
      return function() {
        return !ez5.version("6.8") || ez5.session.hasSystemRight("root", "frontend_features[collection][share_anonymous]");
      };
    })(this);
    if (this._allowCollectionUser && canCreateAnonymousLink()) {
      items.push({
        text: $$("acl.manager.anoymous_access"),
        onClick: (function(_this) {
          return function() {
            return _this.newAclItem({
              who: {
                _basetype: "user",
                user: {
                  login: ez5.generateUUID(),
                  type: "collection"
                }
              }
            });
          };
        })(this)
      });
    }
    add_user_group = (function(_this) {
      return function() {
        return _this.newAclItem();
      };
    })(this);
    if (ez5.session.hasSystemRight("root", "frontend_features[collection][sharing]")) {
      if (items.length) {
        items.splice(0, 0, {
          text: this.aclWhoManager.getPlaceholderText(),
          onClick: add_user_group
        });
        btn_opts.menu = {
          items: items
        };
      } else {
        btn_opts.onClick = add_user_group;
      }
    } else {
      if (items.length) {
        btn_opts.onClick = items[0].onClick;
      }
    }
    this.plusButton = new LocaButton(btn_opts);
    if (this._context) {
      this.__copySelectedRowButton = new LocaButton({
        loca_key: "acl.manager.button.copy-row",
        disabled: true,
        group: "copy-paste",
        onClick: (function(_this) {
          return function() {
            if (_this.__copySelectedRowButton.isActive()) {
              AclManager.removeCopiedItems();
              _this.__highlightCopiedItems();
              _this.checkButtons();
            } else {
              _this.__copySelectedItem();
            }
          };
        })(this)
      });
      this.__copyButton = new LocaButton({
        loca_key: "acl.manager.button.copy",
        disabled: true,
        group: "copy-paste",
        onClick: (function(_this) {
          return function() {
            if (_this.__copyButton.isActive()) {
              AclManager.removeCopiedItems();
              _this.__highlightCopiedItems();
              _this.checkButtons();
            } else {
              _this.__copyAllAclItems();
            }
          };
        })(this)
      });
      this.__pasteButton = new LocaButton({
        loca_key: "acl.manager.button.paste",
        disabled: true,
        group: "copy-paste",
        onClick: (function(_this) {
          return function() {
            _this.__pasteAllAclItems();
          };
        })(this)
      });
      this.__copiedItemsLabel = new CUI.Label({
        text: ""
      });
    }
    tree_opts = {
      "class": "ez5-acl-manager-tree cui-lv--has-datafields",
      cols: [],
      fields: [],
      rowMove: true,
      no_hierarchy: true,
      onSelect: (function(_this) {
        return function() {
          return _this.checkButtons();
        };
      })(this),
      onDeselect: (function(_this) {
        return function() {
          return _this.checkButtons();
        };
      })(this),
      selectableRows: true,
      onRowMove: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            type: "data-changed",
            node: _this.tree
          });
        };
      })(this),
      footer_left: [this.plusButton, this.minusButton, this.__copySelectedRowButton, this.__copyButton, this.__pasteButton, this.__copiedItemsLabel],
      footer_right: this._footer_right
    };
    ref = this.getColumns();
    for (i = 0, len = ref.length; i < len; i++) {
      col = ref[i];
      th_col = {
        th_label: "admin.aclmanager.col." + col
      };
      if (col === "sticky" || col === "active") {
        th_col.th_rotate_90 = true;
      }
      if (col === "active") {
        tree_opts.cols.push("fixed");
      } else {
        tree_opts.cols.push("auto");
      }
      tree_opts.fields.push(th_col);
    }
    this.tree = new ListViewEditTree(tree_opts);
    this.tree.render();
    CUI.Events.listen({
      node: this.tree,
      type: "data-changed",
      call: (function(_this) {
        return function(ev, info) {
          var ref1;
          _this.checkButtons();
          if (!_this.__popoverButton) {
            if (typeof _this._onUpdate === "function") {
              _this._onUpdate(ev);
            }
          } else {
            _this.__dataChanged = true;
            if ((ref1 = _this.__popoverButton.getPopover()) != null) {
              ref1.position();
            }
          }
        };
      })(this)
    });
    this.tree.load_data(this.acl);
    this.checkButtons();
    CUI.dom.setStyle(this.tree, {
      "--acl-manager-grid-column-count": tree_opts.cols.length
    }, "");
    if (tree_opts.cols.length === 1) {
      CUI.dom.addClass(this.tree, "tree-has-only-one-column");
    }
    CUI.dom.waitForDOMInsert({
      node: this.tree
    }).done((function(_this) {
      return function() {
        if (_this.isDestroyed()) {
          return;
        }
        CUI.Events.trigger({
          type: "content-resize",
          node: _this.tree.DOM,
          bubbles: false
        });
        return _this.__highlightCopiedItems();
      };
    })(this));
    return this.tree;
  };

  AclManager.prototype.checkButtons = function() {
    var canBeEdited, copiedItemsCount, ref, selectedNode;
    selectedNode = this.tree.getSelectedNode();
    canBeEdited = (function(_this) {
      return function() {
        if (selectedNode instanceof AclItem && (selectedNode.canBeEdited != null)) {
          return selectedNode.canBeEdited();
        }
        return true;
      };
    })(this);
    if (canBeEdited()) {
      this.minusButton.enable();
    } else {
      this.minusButton.disable();
    }
    if (this._context) {
      if (canBeEdited()) {
        this.__copySelectedRowButton.enable();
      } else {
        this.__copySelectedRowButton.disable();
      }
      if (((ref = this.tree.nodes) != null ? ref.length : void 0) > 1) {
        this.__copyButton.enable();
      } else {
        this.__copyButton.disable();
      }
      this.__copyButton.deactivate();
      this.__copySelectedRowButton.deactivate();
      copiedItemsCount = this.__getCopiedItems().length;
      if (copiedItemsCount > 0) {
        if (copiedItemsCount === 1) {
          this.__copySelectedRowButton.enable();
          this.__copySelectedRowButton.activate();
        } else {
          this.__copyButton.enable();
          this.__copyButton.activate();
        }
        this.__pasteButton.enable();
        this.__copiedItemsLabel.setText($$("acl.manager.button.copied-items|label", {
          count: copiedItemsCount
        }));
      } else {
        this.__pasteButton.disable();
        this.__copiedItemsLabel.setText("");
      }
    }
  };

  AclManager.prototype.getSaveData = function() {
    var acl_item, acl_item_data, i, len, ref, save_data;
    save_data = [];
    ref = this.acl;
    for (i = 0, len = ref.length; i < len; i++) {
      acl_item = ref[i];
      acl_item_data = acl_item.getSaveData();
      if (!acl_item_data.who) {
        throw new InvalidSaveDataException();
      }
      if (this.hasColumn("right") && !this._allow_empty_rights) {
        if (CUI.util.isEmptyObject(acl_item_data.rights) && !acl_item_data._right_preset) {
          throw new InvalidSaveDataException();
        }
      }
      if (acl_item_data) {
        save_data.push(acl_item_data);
      }
    }
    return save_data;
  };

  AclManager.prototype.__highlightCopiedItems = function() {
    var copiedItems, element, i, idxInArray, item, len, ref, ref1;
    copiedItems = this.__getCopiedItems();
    ref = this.tree.getRootChildren();
    for (i = 0, len = ref.length; i < len; i++) {
      item = ref[i];
      idxInArray = CUI.util.idxInArray(void 0, copiedItems, (function(_this) {
        return function(itemData) {
          return CUI.util.isEqual(itemData, item.getData());
        };
      })(this));
      element = (ref1 = item.getDOMNodes()) != null ? ref1[0] : void 0;
      if (!element) {
        continue;
      }
      if (idxInArray >= 0) {
        CUI.dom.addClass(element, "acl-copied-item");
      } else {
        CUI.dom.removeClass(element, "acl-copied-item");
      }
    }
  };

  AclManager.prototype.__copySelectedItem = function() {
    var items;
    items = [this.tree.getSelectedNode().getData()];
    this.__copyItems(items);
  };

  AclManager.prototype.__copyAllAclItems = function() {
    var data, i, item, items, len, ref;
    items = [];
    ref = this.tree.nodes;
    for (i = 0, len = ref.length; i < len; i++) {
      item = ref[i];
      data = item.getData();
      if (!data) {
        continue;
      }
      items.push(data);
    }
    this.__copyItems(items);
  };

  AclManager.prototype.__copyItems = function(items) {
    CUI.setLocalStorage(AclManager.getCopyPasteStorageKey(), {
      items: items,
      context: this._context.getElementClass()
    });
    this.__highlightCopiedItems();
    this.checkButtons();
  };

  AclManager.prototype.__pasteAllAclItems = function() {
    var data, i, itemData, items, len;
    items = this.__getCopiedItems();
    for (i = 0, len = items.length; i < len; i++) {
      itemData = items[i];
      data = this.__getPasteData(itemData);
      this.newAclItem(data);
    }
    CUI.Events.trigger({
      type: "data-changed",
      node: this.tree
    });
  };

  AclManager.prototype.__getCopiedItems = function() {
    var data;
    if (!this._context) {
      return [];
    }
    data = CUI.getLocalStorage(AclManager.getCopyPasteStorageKey());
    if ((data != null ? data.context : void 0) !== this._context.getElementClass()) {
      return [];
    }
    return data.items;
  };

  AclManager.prototype.__getPasteData = function(data) {
    var idOT, idObjecttype, mask_ids, masks, ref, rightName, standardMaskEnabled, value;
    data = CUI.util.copyObject(data, true);
    delete data._id;
    if (this._context instanceof ObjecttypeWithoutPoolListViewItem) {
      idObjecttype = this._context.getObjecttype().id();
      ref = data.rights;
      for (rightName in ref) {
        value = ref[rightName];
        if (rightName === "mask") {
          standardMaskEnabled = false;
          mask_ids = value.mask_ids;
          for (idOT in mask_ids) {
            masks = mask_ids[idOT];
            idOT = parseInt(idOT);
            if (masks.some((function(_this) {
              return function(mask) {
                return mask === "standard";
              };
            })(this))) {
              standardMaskEnabled = true;
            }
            if (idOT !== idObjecttype) {
              delete mask_ids[idOT];
            }
          }
          if (standardMaskEnabled) {
            if (!mask_ids[idObjecttype]) {
              mask_ids[idObjecttype] = [];
            }
            mask_ids[idObjecttype].push("standard");
          }
          break;
        }
      }
    }
    return data;
  };

  AclManager.getCopyPasteStorageKey = function() {
    return "acl-manager-items";
  };

  AclManager.removeCopiedItems = function() {
    return CUI.setLocalStorage(AclManager.getCopyPasteStorageKey(), null);
  };

  AclManager.prototype.WEGdisableAclWho = function(aclWho) {
    var aclItem, i, len, ref;
    ref = this.acl;
    for (i = 0, len = ref.length; i < len; i++) {
      aclItem = ref[i];
      if (typeof aclItem.getAclWho === "function" ? aclItem.getAclWho().equals(aclWho) : void 0) {
        return true;
      }
    }
    return false;
  };

  return AclManager;

})(CUI.Element);

CUI.ready(function() {
  return AclManager.removeCopiedItems();
});
// Generated by CoffeeScript 1.12.7
var AclItem, SystemAclItem,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  AclItem.prototype.initOpts = function() {
    AclItem.__super__.initOpts.call(this);
    return this.addOpts({
      aclManager: {
        mandatory: true,
        check: AclManager
      },
      data: {
        "default": {},
        check: "PlainObject"
      }
    });
  };

  AclItem.prototype.readOpts = function() {
    AclItem.__super__.readOpts.call(this);
    this.aclManager = this._aclManager;
    this.data = this._data;
    if (!this.data.hasOwnProperty("_right_preset") && (this.data.tagfilter || this.data.rights)) {
      this.data._right_preset = null;
    }
    if (!this.data.tagfilter) {
      this.data.tagfilter = {};
    }
    if (!this.data.rights) {
      this.data.right = {};
    }
    if (this.data.when) {
      if (this.data.when.from) {
        this.data.valid_from = this.data.when.from;
      }
      if (this.data.when.to) {
        this.data.valid_to = this.data.when.to;
      }
    }
    return this.init();
  };

  AclItem.prototype.getData = function() {
    return this.data;
  };

  AclItem.prototype.init = function() {
    var _field, all_cols, col, cols, i, j, len, len1, ref, update_expiration_placeholder, whoManager;
    cols = this.aclManager.getColumns();
    all_cols = this.aclManager.getAllColumns();
    if (indexOf.call(cols, "preset") >= 0) {
      this.__allow_custom = ez5.session.hasSystemRight("root", "allow_custom_in_right_with_preset");
    } else {
      this.__allow_custom = true;
    }
    this.opts.fields = [];
    for (i = 0, len = all_cols.length; i < len; i++) {
      col = all_cols[i];
      switch (col) {
        case "right":
          this.aclRightManager = new AclRightManager({
            context: this.aclManager.getContext(),
            data: this.data,
            name: "rights",
            filter: this.aclManager._right_filter
          });
          break;
        case "tagfilter":
          this.tagFilter = new TagFilter({
            tagForm: this.aclManager.getTagForm(),
            data: this.data,
            name: "tagfilter"
          });
          break;
        case "preset":
          this.presetManager = new RightPresetManager({
            server_context: AclRights.getServerContextByFrontendContext(this.aclManager.getContext())
          });
      }
    }
    ref = this.aclManager.getColumns();
    for (j = 0, len1 = ref.length; j < len1; j++) {
      col = ref[j];
      switch (col) {
        case "who":
          whoManager = this.aclManager.getAclWhoManager().copy();
          this.opts.fields.push({
            type: UserGroupSelector,
            disabled: !this.canBeEdited(),
            maximize_horizontal: true,
            aclWhoManager: whoManager,
            name: whoManager.name(),
            data: this.data,
            onDataChanged: (function(_this) {
              return function(_, field) {
                var ref1, ref2, ref3, ref4, ref5;
                if ((ref1 = field.getForm().getFieldsByName("_share_form")[0]) != null) {
                  ref1.reload();
                }
                if (((ref2 = _this.data.who) != null ? (ref3 = ref2.user) != null ? ref3.type : void 0 : void 0) === "email" || !CUI.util.isEmpty((ref4 = _this.data.who) != null ? (ref5 = ref4.user) != null ? ref5._email : void 0 : void 0)) {
                  if (!_this.data.email_notification && !_this.data._id) {
                    _this.data.email_notification = true;
                    _this.update();
                  }
                }
              };
            })(this)
          });
          break;
        case "preset":
          update_expiration_placeholder = (function(_this) {
            return function(df) {
              var expiration_hours, expire_field, ref1, ref2, ref3, ref4, ref5, ref6;
              if (!ez5.version("6")) {
                return;
              }
              if (!df) {
                return;
              }
              expire_field = (ref1 = df.getForm().getFieldsByName("valid_to")) != null ? ref1[0] : void 0;
              if (expire_field) {
                expiration_hours = (ref2 = _this.presetManager) != null ? (ref3 = ref2.__getPresetById(df.getValue())) != null ? (ref4 = ref3.getData()) != null ? (ref5 = ref4.right_preset) != null ? (ref6 = ref5.preset) != null ? ref6.default_expiration_hours : void 0 : void 0 : void 0 : void 0 : void 0;
                if (!expiration_hours) {
                  return;
                }
                return expire_field._placeholder = RightPreset.getExpirationText(expiration_hours);
              }
            };
          })(this);
          _field = this.presetManager.getField({
            allow_custom: this.__allow_custom && (indexOf.call(cols, "right") >= 0 || indexOf.call(cols, "tagfilter") >= 0),
            onDataChanged: (function(_this) {
              return function(date, df) {
                _this.init();
                _this.update();
                return update_expiration_placeholder(df);
              };
            })(this),
            onRender: (function(_this) {
              return function(df) {
                return update_expiration_placeholder(df);
              };
            })(this)
          });
          this.opts.fields.push(_field);
          break;
        case "date_created":
        case "sticky":
        case "valid_from":
        case "valid_to":
        case "active":
        case "right":
        case "tagfilter":
        case "share_link":
        case "preset":
        case "email_notification":
          this.opts.fields.push(this.getField(col));
          break;
        case "email_notification_form":
          if (this.getWho() instanceof AclWhoCollection) {
            this.opts.fields.push(new CUI.ListViewColumnEmpty());
          } else {
            this.opts.fields.push({
              type: CUI.FormPopover,
              button: {
                icon_active: "envelope_active",
                icon_inactive: "envelope"
              },
              fields: (function(_this) {
                return function() {
                  return [_this.getField("email_notification"), _this.getField("email_language"), _this.getField("email_notification_text")];
                };
              })(this),
              renderDisplayButton: (function(_this) {
                return function(df, data) {
                  if (!_this.getWho()) {
                    df.disable();
                  } else {
                    df.enable();
                  }
                  return data.email_notification;
                };
              })(this)
            });
          }
          break;
        case "expert_menu":
          this.opts.fields.push({
            type: CUI.FormButton,
            icon: "menu",
            onClick: (function(_this) {
              return function() {
                return _this.openExpertEditor();
              };
            })(this)
          });
          break;
        case "invalid_acl":
          this.opts.fields.push(new CUI.ListViewColumn({
            element: new CUI.Icon({
              icon: "fa-exclamation-triangle",
              tooltip: {
                text: $$("admin.aclmanager.col.invalid_acl|tooltip")
              }
            })
          }));
          break;
        default:
          CUI.util.assert(false, "new AclItem", "Unsupported column type \"" + col + "\"");
      }
    }
    return this;
  };

  AclItem.prototype.addedToListView = function() {
    AclItem.__super__.addedToListView.call(this);
    return this.setActiveStateOnRow();
  };

  AclItem.prototype.setActiveStateOnRow = function() {
    if (!this._active) {
      return;
    }
    if (!this.data.active) {
      return this.addClass("inactive");
    } else {
      return this.removeClass("inactive");
    }
  };

  AclItem.prototype.getField = function(col) {
    var field;
    field = ((function(_this) {
      return function() {
        var who;
        switch (col) {
          case "date_created":
            return {
              type: CUI.Output,
              text: ez5.format_date_and_time(_this.data.date_created)
            };
          case "right":
            return _this.aclRightManager.getField({
              onDataChanged: function() {
                var ref;
                return (ref = _this.getOtherField("_right_preset")) != null ? ref.setValue(null) : void 0;
              }
            });
          case "tagfilter":
            return _this.tagFilter.getField({
              onDataChanged: function() {
                var ref;
                return (ref = _this.getOtherField("_right_preset")) != null ? ref.setValue(null) : void 0;
              }
            });
          case "sticky":
            return {
              type: CUI.Checkbox,
              name: "sticky"
            };
          case "valid_from":
            return {
              type: CUI.DateTime,
              display_type: "short",
              name: "valid_from",
              maximize_horizontal: true
            };
          case "valid_to":
            return {
              type: CUI.DateTime,
              display_type: "short",
              name: "valid_to",
              maximize_horizontal: true
            };
          case "active":
            return {
              type: CUI.Checkbox,
              onDataChanged: function() {
                return _this.setActiveStateOnRow();
              },
              name: "active"
            };
          case "email_notification":
            who = _this.getWho();
            if (who instanceof AclWhoCollection) {
              return null;
            }
            return {
              type: CUI.Checkbox,
              name: "email_notification"
            };
          case "email_language":
            who = _this.getWho();
            console.debug("email language", who);
            if (!(who != null ? who.getFrontendLanguage : void 0)) {
              return null;
            } else {
              return {
                type: CUI.Output,
                text: ez5.loca.getLanguageLabel(who.getFrontendLanguage())
              };
            }
            break;
          case "email_notification_text":
            return {
              type: CUI.Input,
              textarea: true,
              placeholder: $$("acl.item.col.email_notification_text_placeholder"),
              name: "email_notification_text",
              maximize_horizontal: true
            };
          case "share_link":
            return _this.getShareLinkField();
          default:
            return CUI.util.assert(false, "AclItem.getField", "Unknown col \"" + col + "\"");
        }
      };
    })(this))();
    if (field && !this.canBeEdited()) {
      field.disabled = true;
    }
    if (field && !(field instanceof CUI.DataField)) {
      CUI.util.assert(CUI.util.isPlainObject(field), "AclItem.getField", "\"" + col + "\": field needs to be PlainObject", {
        field: field
      });
      if (!field.form) {
        field.form = {};
      }
      if (!field.form.label) {
        field.form.label = $$("acl.item.col." + col);
      }
    }
    return field;
  };

  AclItem.prototype.getWho = function() {
    return this.aclManager.getAclWhoManager().getWho(this.data);
  };

  AclItem.prototype.openExpertEditor = function() {
    var apply_btn, cls, rowData, rowSaveData, set_apply_btn;
    rowData = CUI.util.copyObject(this.data, true);
    rowSaveData = JSON.stringify(this.getSaveData());
    apply_btn = new CUI.Button({
      text: $$("base.apply"),
      primary: true,
      disabled: true,
      onClick: (function(_this) {
        return function(ev) {
          if (ev.hasModifierKey()) {
            console.debug(CUI.util.dump(_this.getSaveData()));
            return;
          }
          return _this.__modal.destroy();
        };
      })(this)
    });
    set_apply_btn = (function(_this) {
      return function() {
        if (rowSaveData !== JSON.stringify(_this.getSaveData())) {
          return apply_btn.enable();
        } else {
          return apply_btn.disable();
        }
      };
    })(this);
    if (this.__allow_custom) {
      cls = " ez5-acl-expert-editor-custom-allowed";
    } else {
      cls = "";
    }
    this.__modal = new CUI.Modal({
      "class": "ez5-acl-expert-editor" + cls,
      cancel: true,
      onCancel: (function(_this) {
        return function() {
          console.debug("cancel copy back data", rowData, _this.data);
          return _this.data = rowData;
        };
      })(this),
      onHide: (function(_this) {
        return function() {
          _this.init();
          _this.update();
          if (_this.data !== rowData) {
            console.debug("hiding dialog, updateing...");
            CUI.Events.trigger({
              type: "data-changed",
              node: _this.aclManager.tree
            });
          }
          return delete _this.__modal;
        };
      })(this),
      pane: {
        header_left: new CUI.Label({
          text: $$("acl.item.modal.title")
        }),
        footer_right: apply_btn,
        content: this.getExpertEditorContent()
      }
    });
    CUI.Events.listen({
      type: "data-changed",
      node: this.__modal,
      call: function() {
        return set_apply_btn();
      }
    });
    this.__modal.show();
    return this;
  };

  AclItem.prototype.getExpertEditorContent = function() {
    var col, expert_menu, form1, form1_fields, form2, form2_fields, i, lay, len, preset_form, right_block, tagfilter_block, update_preset, update_rightsmanagement, who, whoManager;
    form1_fields = [];
    form2_fields = [];
    expert_menu = this.aclManager.getExpertMenuColumns();
    for (i = 0, len = expert_menu.length; i < len; i++) {
      col = expert_menu[i];
      switch (col) {
        case "who":
          whoManager = this.aclManager.getAclWhoManager().copy();
          form1_fields.push({
            form: {
              label: $$("acl.item.col.who")
            },
            type: UserGroupSelector,
            maximize_horizontal: true,
            aclWhoManager: whoManager,
            name: whoManager.name(),
            data: this.data,
            onDataChanged: (function(_this) {
              return function() {
                if (_this.data.who) {
                  return _this.__modal.replace(_this.getExpertEditorContent());
                }
              };
            })(this)
          });
          break;
        case "active":
        case "sticky":
        case "valid_from":
        case "valid_to":
          form1_fields.push(this.getField(col));
          break;
        case "share_link":
          who = this.getWho();
          if (who instanceof AclWhoCollection) {
            form1_fields.push(this.getShareLinkField());
          }
          break;
        case "email_notification":
        case "email_language":
        case "email_notification_text":
          if (!(this.getWho() instanceof AclWhoCollection)) {
            form2_fields.push(this.getField(col));
          }
          break;
        case "right":
        case "tagfilter":
        case "preset":
          break;
        default:
          CUI.util.assert(false, "AclItem.openExpertEditor", "\"" + col + "\" unsupported by expert menu", {
            expert_menu: expert_menu
          });
      }
    }
    lay = new CUI.VerticalLayout();
    if (form1_fields.length) {
      form1 = new CUI.Form({
        "class": "ez5-acl-expert-editor-form1",
        data: this.data,
        fields: form1_fields
      }).start();
      lay.append(new CUI.Block({
        "class": "ez5-acl-item-block-general",
        text: $$("acl.item.block.general"),
        appearance: "wide",
        level: 2,
        content: form1
      }), "center");
    }
    if (form2_fields.length) {
      form2 = new CUI.Form({
        "class": "ez5-acl-expert-editor-form2",
        data: this.data,
        fields: form2_fields
      }).start();
      lay.append(new CUI.Block({
        "class": "ez5-acl-item-block-email",
        text: $$("acl.item.block.email"),
        appearance: "wide",
        level: 2,
        content: form2
      }), "center");
    }
    if (this.__allow_custom) {
      if (indexOf.call(expert_menu, "right") >= 0) {
        right_block = new CUI.Block({
          "class": "ez5-acl-item-block-right",
          text: $$("acl.item.block.right"),
          appearance: "wide",
          level: 3
        });
      }
      if (indexOf.call(expert_menu, "tagfilter") >= 0) {
        tagfilter_block = new CUI.Block({
          "class": "ez5-tags-table",
          appearance: "wide",
          text: $$("acl.item.block.tagfilter"),
          level: 2
        });
      }
    }
    update_preset = (function(_this) {
      return function() {
        if (!preset_form) {
          return;
        }
        return preset_form.getFieldsByName("_right_preset")[0].setValue(null);
      };
    })(this);
    update_rightsmanagement = (function(_this) {
      return function() {
        var right_form, tagfilter_field;
        if (!_this.__allow_custom) {
          return;
        }
        if (indexOf.call(expert_menu, "right") >= 0) {
          right_form = _this.aclRightManager.getForm({
            onDataChanged: update_preset
          }).start();
          right_block.setContent(right_form);
        }
        if (indexOf.call(expert_menu, "tagfilter") >= 0) {
          tagfilter_field = _this.tagFilter.getDataFieldProxy({
            onDataChanged: update_preset
          }).start();
          return tagfilter_block.setContent(tagfilter_field);
        }
      };
    })(this);
    if (indexOf.call(expert_menu, "preset") >= 0) {
      preset_form = new CUI.Form({
        "class": "ez5-acl-expert-editor-preset-form",
        data: this.data,
        fields: [
          this.presetManager.getField({
            allow_custom: this.__allow_custom,
            onDataChanged: (function(_this) {
              return function() {
                return update_rightsmanagement();
              };
            })(this)
          })
        ]
      }).start();
    }
    update_rightsmanagement();
    if (right_block || tagfilter_block || preset_form) {
      lay.append(new CUI.Block({
        "class": "ez5-acl-item-block-rightsmanagement",
        appearance: "wide",
        level: 2,
        text: $$("acl.item.block.rightsmanagement"),
        content: [preset_form, right_block, tagfilter_block]
      }), "center");
    }
    return lay;
  };

  AclItem.prototype.canBeEdited = function() {
    var who;
    if (!this.aclManager._check_who_readable) {
      return true;
    }
    if (this.data.who) {
      who = AclWho.newInstance(this.data);
      if (who instanceof AclWhoGroup) {
        if (who.isLimited()) {
          return false;
        }
      }
    }
    return true;
  };

  AclItem.prototype.getSaveData = function() {
    var __who, all_cols, ref, save_data, txt;
    all_cols = this.aclManager.getAllColumns();
    save_data = {};
    if (this.data._id) {
      save_data._id = this.data._id;
    }
    if (this.data.who) {
      save_data.who = (__who = AclWho.newInstance(this.data)).getSaveData();
    } else {
      save_data.who = null;
    }
    if (this.data._right_preset) {
      save_data._right_preset = this.data._right_preset;
    } else {
      if (this.aclRightManager) {
        save_data.rights = this.aclRightManager.getSaveData();
      }
      if (this.tagFilter) {
        save_data.tagfilter = this.tagFilter.getSaveData();
      }
    }
    if (indexOf.call(all_cols, "sticky") >= 0) {
      save_data.sticky = !!this.data.sticky;
    }
    if (indexOf.call(all_cols, "valid_from") >= 0 || indexOf.call(all_cols, "valid_to") >= 0) {
      save_data.when = {};
      if (this.data.valid_from) {
        save_data.when.from = this.data.valid_from;
      }
      if (this.data.valid_to) {
        save_data.when.to = this.data.valid_to;
      }
    }
    if (indexOf.call(all_cols, "active") >= 0) {
      save_data.active = !!this.data.active;
    }
    if (indexOf.call(all_cols, "email_notification") >= 0) {
      if (this.data.email_notification) {
        save_data.send_email_notification = {};
        if (!CUI.util.isEmpty(txt = (ref = this.data.email_notification_text) != null ? ref.trim() : void 0)) {
          save_data.send_email_notification.text = txt;
        }
      }
    }
    return save_data;
  };

  AclItem.prototype.getShareLinkField = function() {
    var form;
    form = {
      type: CUI.Form,
      form: {
        label: $$("acl.item.share_link_field.label")
      },
      name: "_share_form",
      fields: [
        {
          type: CUI.DataFieldProxy,
          element: (function(_this) {
            return function() {
              var url, who;
              who = _this.getWho();
              url = _this.aclManager.getContext().getShareUrl(who);
              return Asset.getShareButtonbar(url, "acl.item.share");
            };
          })(this)
        }
      ]
    };
    return form;
  };

  return AclItem;

})(ListViewEditTreeNode);

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

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

  return SystemAclItem;

})(AclItem);
// Generated by CoffeeScript 1.12.7
var AclWho,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

AclWho = (function() {
  function AclWho() {
    this.getAutocompletionItem = bind(this.getAutocompletionItem, this);
    this.equals = bind(this.equals, this);
  }

  AclWho.prototype.equals = function(aclWhoComp) {
    CUI.util.assert(aclWhoComp instanceof AclWho, "AclWho.equals", "Unable to compare aclWho", {
      aclWho: this,
      aclWhoComp: aclWhoComp
    });
    return aclWhoComp.getIdentifier() === this.getIdentifier();
  };

  AclWho.prototype.getIdentifier = function() {
    return (this.getType()) + "-" + (this.getWho().id);
  };

  AclWho.prototype.getField = function() {
    return {
      type: CUI.Output,
      text: this.getDisplayText()
    };
  };

  AclWho.prototype.getData = function() {
    return this.data;
  };

  AclWho.prototype.getDisplayText = function() {
    return (CUI.util.getObjectClass(this)) + ".getDisplayText misses implementation";
  };

  AclWho.prototype.getDisplayAutocompletion = function() {
    return (CUI.util.getObjectClass(this)) + ".getDisplayAutocompletion misses implementation";
  };

  AclWho.prototype.getAutocompletionItem = function() {
    return new CUI.Label({
      icon: this.getIcon(),
      content: this.getDisplayAutocompletion(),
      tooltip: this.getTooltip()
    });
  };

  AclWho.prototype.getSearchFilter = function(field_name) {};

  AclWho.prototype.getLoginUrl = function() {};

  AclWho.prototype.getTooltip = function() {
    return null;
  };

  AclWho.newInstance = function(data) {
    var __data, aclWho, ref, ref1, ref2, ref3, ref4, ref5;
    if (data == null) {
      data = {};
    }
    if (data.who) {
      __data = data.who;
    } else {
      __data = data;
    }
    if ((!__data.user && !__data.group) && __data._owner) {
      aclWho = new AclWhoOwner();
    } else if (__data.group) {
      aclWho = new AclWhoGroup(__data);
    } else if (__data._pool_contact) {
      aclWho = new AclWhoPool();
    } else if ((ref = (ref1 = __data.user) != null ? ref1.type : void 0) !== "email" && ref !== "collection") {
      aclWho = new AclWhoUser(__data);
    } else if ((ref2 = (ref3 = __data.user) != null ? ref3.type : void 0) === "email") {
      aclWho = new AclWhoEmail(__data);
    } else if ((ref4 = (ref5 = __data.user) != null ? ref5.type : void 0) === "collection") {
      aclWho = new AclWhoCollection(__data);
    } else {
      CUI.util.assert(false, "AclWho.newInstance", "data doesn't contain user, group, collection, nor email in data.who.", {
        data: data
      });
    }
    return aclWho;
  };

  return AclWho;

})();
// Generated by CoffeeScript 1.12.7
var AclWhoUser,
  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;

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

  function AclWhoUser(data) {
    this.data = data != null ? data : {};
    this.getSaveData = bind(this.getSaveData, this);
    CUI.util.assert(CUI.util.isPlainObject(this.data), "new AclWhoUser", "data needs to be PlainObject", {
      data: this.data
    });
    if (CUI.util.isEmptyObject(this.data)) {
      this.data = {
        _basetype: "user",
        user: {}
      };
    }
    this.__user = new User({
      user: this.data
    });
  }

  AclWhoUser.prototype.getType = function() {
    return "user";
  };

  AclWhoUser.prototype.getIcon = function() {
    return "fa-user";
  };

  AclWhoUser.prototype.getFrontendLanguage = function() {
    return this.__user.getFrontendLanguage();
  };

  AclWhoUser.prototype.getDisplayText = function() {
    return this.getGeneratedDisplayName();
  };

  AclWhoUser.prototype.getDisplayAutocompletion = function() {
    return this.__user.getContent(true);
  };

  AclWhoUser.prototype.getId = function() {
    return this.__user.getId();
  };

  AclWhoUser.prototype.getGeneratedDisplayName = function() {
    return this.__user.getDisplayText();
  };

  AclWhoUser.prototype.getUser = function() {
    return this.__user;
  };

  AclWhoUser.prototype.getSaveData = function() {
    return {
      _basetype: "user",
      user: {
        _id: this.__user.getId(),
        _generated_displayname: this.getGeneratedDisplayName(),
        _email: this.__user.getEmail(),
        frontend_language: this.getFrontendLanguage()
      }
    };
  };

  AclWhoUser.prototype.getSearchFilter = function(field_name) {
    var ref;
    return {
      type: "in",
      fields: [field_name + ".user._id"],
      "in": [(ref = this.__user) != null ? ref.getId() : void 0]
    };
  };

  AclWhoUser.prototype.getLoginUrl = function() {
    var ref;
    return (ref = this.__user) != null ? ref.getAuthUrl() : void 0;
  };

  return AclWhoUser;

})(AclWho);
// Generated by CoffeeScript 1.12.7
var AclWhoGroup,
  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;

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

  function AclWhoGroup(data) {
    this.data = data != null ? data : {};
    CUI.util.assert(CUI.util.isPlainObject(this.data), "new AclWhoGroup", "data needs to be PlainObject", {
      data: this.data
    });
    if (!this.data.group.displayname) {
      this.group = ez5.groupManager.getGroupById(this.data.group._id);
    }
    if (!this.group) {
      this.group = Group.newInstance({
        group: this.data
      });
    }
  }

  AclWhoGroup.prototype.getGroup = function() {
    return this.group;
  };

  AclWhoGroup.prototype.isLimited = function() {
    if (this.data.group._id && !ez5.groupManager.getGroupById(this.data.group._id)) {
      return true;
    } else {
      return false;
    }
  };

  AclWhoGroup.prototype.getType = function() {
    return "group";
  };

  AclWhoGroup.prototype.getIcon = function() {
    return "fa-users";
  };

  AclWhoGroup.prototype.getDisplayText = function() {
    return this.group.getDisplayText();
  };

  AclWhoGroup.prototype.getDisplayAutocompletion = function() {
    return this.group.getContent();
  };

  AclWhoGroup.prototype.getTooltip = function() {
    var categories, category, category_value, str;
    categories = this.group.getCategories();
    if (!categories) {
      return null;
    }
    str = ($$("admin.group.categories")) + ":\n";
    for (category in categories) {
      category_value = categories[category];
      if (!CUI.util.isEmpty(category_value)) {
        str += "- " + category_value + "\n";
      }
    }
    return {
      text: str
    };
  };

  AclWhoGroup.prototype.getSaveData = function() {
    if (this.group) {
      return {
        _basetype: "group",
        group: {
          _id: this.group.id
        }
      };
    } else {
      return null;
    }
  };

  AclWhoGroup.prototype.getSearchFilter = function(field_name) {
    if (this.group) {
      return {
        type: "in",
        fields: [field_name + ".group._id"],
        "in": [this.group.id]
      };
    } else {
      return null;
    }
  };

  AclWhoGroup.prototype.getLoginUrl = function() {
    return this.getGroup().getAuthUrl();
  };

  return AclWhoGroup;

})(AclWho);
// Generated by CoffeeScript 1.12.7
var AclWhoEmail,
  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;

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

  function AclWhoEmail(opts1) {
    this.opts = opts1 != null ? opts1 : {};
    AclWhoEmail.__super__.constructor.call(this, this.opts);
    this.init();
  }

  AclWhoEmail.prototype.init = function() {
    return CUI.util.assert(this.__user.getType() === "email", "new AclWhoEmail", "opts.user.type needs to be \"email\".", {
      opts: this.opts,
      __user: this.__user
    });
  };

  AclWhoEmail.prototype.getType = function() {
    return "email";
  };

  AclWhoEmail.prototype.getIcon = function() {
    return "fa-envelope-o";
  };

  AclWhoEmail.prototype.getSaveData = function() {
    var sd;
    sd = AclWhoEmail.__super__.getSaveData.call(this);
    sd.user.login = this.__user.getLogin();
    sd.user.type = this.__user.getType();
    sd._emails = this.__user.getData()._emails;
    return sd;
  };

  AclWhoEmail.prototype.getGeneratedDisplayName = function() {
    return this.getEmail();
  };

  AclWhoEmail.prototype.getEmail = function() {
    var email, ref, ref1;
    email = this.__user.getLogin();
    if (email) {
      return email;
    }
    return (ref = this.__user.getData()._emails) != null ? (ref1 = ref.find(function(_email) {
      return !CUI.util.isEmpty(_email.email);
    })) != null ? ref1.email : void 0 : void 0;
  };

  AclWhoEmail.prototype.showCreateModal = function(opts) {
    var createBtn, dfr, fields, i, lang, lang_opts, len, mod, ref;
    dfr = new CUI.Deferred();
    createBtn = new CUI.Button({
      text: (opts != null ? opts.btn_loca : void 0) || $$("acl.who.email.create.button"),
      primary: true,
      onClick: (function(_this) {
        return function() {
          dfr.resolve();
          return mod.destroy();
        };
      })(this)
    });
    lang_opts = [];
    ref = ez5.session.getConfigFrontendLanguages();
    for (i = 0, len = ref.length; i < len; i++) {
      lang = ref[i];
      lang_opts.push({
        value: lang,
        text: ez5.loca.getLanguageLabel(lang)
      });
    }
    fields = [
      {
        form: {
          label: (opts != null ? opts.form_loca : void 0) || $$("acl.who.email.create.language")
        },
        type: CUI.Select,
        options: lang_opts,
        name: "frontend_language"
      }
    ];
    mod = new CUI.Modal({
      cancel: true,
      onCancel: (function(_this) {
        return function() {
          dfr.reject();
        };
      })(this),
      pane: {
        header_left: new CUI.Label({
          text: (opts != null ? opts.title_loca : void 0) || $$("acl.who.email.create.title")
        }),
        content: (function(_this) {
          return function() {
            return new CUI.Form({
              data: _this.__user.getData().user,
              undo_support: false,
              padded: true,
              fields: fields
            }).start();
          };
        })(this),
        footer_right: createBtn
      }
    }).show();
    return dfr.promise();
  };

  return AclWhoEmail;

})(AclWhoUser);
// Generated by CoffeeScript 1.12.7
var AclWhoPool,
  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;

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

  function AclWhoPool(opts) {
    this.opts = opts != null ? opts : {};
    AclWhoPool.__super__.constructor.call(this, this.opts);
  }

  AclWhoPool.prototype.getType = function() {
    return "pool";
  };

  AclWhoPool.prototype.getIcon = function() {
    return $$("acl.who.pool.icon");
  };

  AclWhoPool.prototype.getSaveData = function() {
    var saveData;
    saveData = {};
    saveData._pool_contact = true;
    return saveData;
  };

  AclWhoPool.prototype.getDisplayText = function() {
    return $$("acl.who.pool.display_name");
  };

  AclWhoPool.prototype.getGeneratedDisplayName = function() {
    return this.getDisplayText();
  };

  AclWhoPool.prototype.getDisplayAutocompletion = function() {
    return this.getDisplayText();
  };

  return AclWhoPool;

})(AclWho);
// Generated by CoffeeScript 1.12.7
var AclWhoCollection,
  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;

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

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

  AclWhoCollection.prototype.init = function() {
    CUI.util.assert(this.__user.getLogin(), "new AclWhoCollection", "opts.user.login needs to be set.", {
      opts: this.opts,
      __user: this.__user
    });
    return CUI.util.assert(this.__user.getType() === "collection", "new AclWhoCollection", "opts.user.type needs to be \"collection\".", {
      opts: this.opts,
      __user: this.__user
    });
  };

  AclWhoCollection.prototype.getType = function() {
    return "collection";
  };

  AclWhoCollection.prototype.getIcon = function() {
    return "fa-folder-o";
  };

  AclWhoCollection.prototype.getSecret = function() {
    return this.__user.getLogin();
  };

  AclWhoCollection.prototype.getLoginUrl = function() {
    return this.__user.getAuthUrl();
  };

  AclWhoCollection.prototype.showCreateModal = function(opts) {
    opts = {
      btn_loca: $$("acl.who.anonymous.create.button"),
      form_loca: $$("acl.who.anonymous.create.language"),
      title_loca: $$("acl.who.anonymous.create.title")
    };
    return AclWhoCollection.__super__.showCreateModal.call(this, opts);
  };

  return AclWhoCollection;

})(AclWhoEmail);
// Generated by CoffeeScript 1.12.7
var AclWhoMatchAny,
  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;

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

  function AclWhoMatchAny() {}

  AclWhoMatchAny.prototype.getDisplayText = function() {
    return $$("acl.who.any");
  };

  AclWhoMatchAny.prototype.getDisplayAutocompletion = function() {
    return CUI.dom.htmlToNodes(this.getDisplayText());
  };

  AclWhoMatchAny.prototype.getType = function() {
    return "any";
  };

  AclWhoMatchAny.prototype.getIcon = function() {
    return "fa-asterisk";
  };

  AclWhoMatchAny.prototype.getSaveData = function() {
    return null;
  };

  return AclWhoMatchAny;

})(AclWho);
// Generated by CoffeeScript 1.12.7
var AclWhoManager,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function AclWhoManager() {
    this.getEmptyRow = bind(this.getEmptyRow, this);
    return AclWhoManager.__super__.constructor.apply(this, arguments);
  }

  AclWhoManager.prototype.initOpts = function() {
    AclWhoManager.__super__.initOpts.call(this);
    return this.addOpts({
      who_filter: {
        "default": ["group", "user"],
        check: Array
      },
      filter_system_groups: {
        check: Boolean
      },
      filter_system_users: {
        check: Boolean
      },
      filter_groups: {
        check: Array
      },
      filter_groups_bool: {
        mandatory: true,
        "default": "must_not",
        check: ["must", "must_not"]
      },
      allowEmailUser: {
        "default": false,
        check: Boolean
      },
      allowPoolUser: {
        "default": false,
        check: Boolean
      },
      allowOwner: {
        "default": false,
        check: Boolean
      },
      allowMatchAny: {
        "default": false,
        check: Boolean
      },
      onUpdate: {
        check: Function
      },
      name: {
        check: String
      },
      store_full_data: {
        check: Boolean
      },
      placeholder: {
        "default": null,
        check: String
      }
    });
  };

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

  AclWhoManager.prototype.copy = function() {
    return new AclWhoManager({
      name: this._name,
      allowEmailUser: this._allowEmailUser,
      allowPoolUser: this._allowPoolUser,
      allowMatchAny: this._allowMatchAny,
      who_filter: this._who_filter,
      allowOwner: this._allowOwner,
      filter_system_groups: this._filter_system_groups,
      filter_system_users: this._filter_system_users,
      placeholder: this._placeholder
    });
  };

  AclWhoManager.prototype.getWho = function(data) {
    if (this._allowMatchAny && data[this.name()] === null) {
      return new AclWhoMatchAny();
    } else if (data[this.name()]) {
      return AclWho.newInstance(data[this.name()]);
    } else {
      return void 0;
    }
  };

  AclWhoManager.prototype.getEmptyRow = function(click_callback) {
    return new AclWhoEmptyRow({
      manager: this,
      click_callback: click_callback
    });
  };

  AclWhoManager.prototype.getPlaceholderText = function() {
    var i, len, ref, str, type;
    if (this._placeholder) {
      if (this._placeholder === "-") {
        return null;
      }
      return this._placeholder;
    }
    str = [];
    ref = ["user", "group"];
    for (i = 0, len = ref.length; i < len; i++) {
      type = ref[i];
      if (indexOf.call(this._who_filter, type) >= 0) {
        str.push($$("acl.who.manager.who_placeholder_" + type));
      }
    }
    if (this._allowEmailUser) {
      str.push($$("acl.who.manager.who_placeholder_email"));
    }
    if (this._allowPoolUser) {
      str.push($$("acl.who.manager.who_placeholder_pool"));
    }
    return str.join("/");
  };

  return AclWhoManager;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var AclWhoEmptyRow,
  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;

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

  function AclWhoEmptyRow(opts) {
    this.opts = opts != null ? opts : {};
    this.renderContent = bind(this.renderContent, this);
    this.setColspan = bind(this.setColspan, this);
    this.opts.data = {};
    AclWhoEmptyRow.__super__.constructor.call(this, this.opts);
  }

  AclWhoEmptyRow.prototype.setColspan = function(colspan) {
    return this.opts.colspan = colspan;
  };

  AclWhoEmptyRow.prototype.renderContent = function() {
    var div;
    div = CUI.dom.div();
    this.inputSearch = this.opts.manager.getInputSearch(this.opts.click_callback);
    CUI.dom.append(div, this.inputSearch.render());
    return div;
  };

  AclWhoEmptyRow.prototype.getSaveData = function() {};

  return AclWhoEmptyRow;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var AclWhoOwner,
  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;

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

  function AclWhoOwner() {
    this.data = {
      _owner: true
    };
  }

  AclWhoOwner.prototype.getType = function() {
    return "user";
  };

  AclWhoOwner.prototype.getIcon = function() {
    return "fa-user-o";
  };

  AclWhoOwner.prototype.getDisplayText = function() {
    return $$("acl.who.owner.display_name");
  };

  AclWhoOwner.prototype.getDisplayAutocompletion = function() {
    return this.getDisplayText();
  };

  AclWhoOwner.prototype.getSaveData = function() {
    return this.data;
  };

  return AclWhoOwner;

})(AclWho);
// Generated by CoffeeScript 1.12.7
var ObjecttypeManager,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function ObjecttypeManager() {
    this.getAllFieldsFromAllMasks = bind(this.getAllFieldsFromAllMasks, this);
    this.getAllFields = bind(this.getAllFields, this);
    this.getEASFields = bind(this.getEASFields, this);
    return ObjecttypeManager.__super__.constructor.apply(this, arguments);
  }

  ObjecttypeManager.prototype.initOpts = function() {
    ObjecttypeManager.__super__.initOpts.call(this);
    return this.addOpts({
      version: {
        check: ["CURRENT", "HEAD"],
        "default": "CURRENT"
      }
    });
  };

  ObjecttypeManager.prototype.readOpts = function() {
    ObjecttypeManager.__super__.readOpts.call(this);
    return this.objecttypes = [];
  };

  ObjecttypeManager.prototype.addObjecttypes = function(filter) {
    var i, len, mask, mask_schema, ref;
    if (filter == null) {
      filter = function() {
        return true;
      };
    }
    ref = ez5.mask[this._version].masks;
    for (i = 0, len = ref.length; i < len; i++) {
      mask_schema = ref[i];
      mask = new Mask(this._version, null, mask_schema);
      if (filter(mask.table, mask)) {
        this.addMask(mask);
      }
    }
    return this;
  };

  ObjecttypeManager.prototype.getObjecttypes = function() {
    return this.objecttypes;
  };

  ObjecttypeManager.prototype.addMask = function(_mask) {
    var mask, ot;
    CUI.util.assert(_mask instanceof Mask, "ObjecttypeManager.addMask", "Mask must be instance of Mask", {
      mask: mask
    });
    if (_mask.name() === "_all_fields") {
      mask = Mask.getMaskByMaskName("_all_fields", _mask.table.id());
    } else {
      mask = new Mask(this._version, _mask.id());
    }
    ot = this.findObjecttypeByName(mask.table.name());
    if (!ot) {
      ot = new Objecttype(mask);
      this.objecttypes.push(ot);
      this.objecttypes.sort(function(a, b) {
        return CUI.util.compareIndex(a.nameLocalized(), b.nameLocalized());
      });
    } else {
      ot.addMask(mask);
    }
    return ot;
  };

  ObjecttypeManager.prototype.findObjecttypeByName = function(name) {
    var i, len, ot, ref;
    ref = this.objecttypes;
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      if (ot.name() === name) {
        return ot;
      }
    }
    return null;
  };

  ObjecttypeManager.prototype.findMaskByName = function(name) {
    var i, j, len, len1, m, ot, ref, ref1;
    ref = this.objecttypes;
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      ref1 = ot.masks;
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        m = ref1[j];
        if (m.name() === name) {
          return m;
        }
      }
    }
    return null;
  };

  ObjecttypeManager.prototype.initCommonFields = function(mode, dive_nested, filter_callback) {
    var fbn, fieldsByName, fn, i, j, k, len, len1, len2, m, ot, ref, ref1, ref2;
    if (dive_nested == null) {
      dive_nested = true;
    }
    if (filter_callback == null) {
      filter_callback = null;
    }
    ref = this.objecttypes;
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      fieldsByName = {};
      ot.commonFields = [];
      ot.fieldsByLocaName = {};
      ot.commonFieldsMasks = [];
      ref1 = ot.masks;
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        m = ref1[j];
        CUI.util.assert(!m.uniqueFields, "ObjecttypeManager.initCommonFields(" + mode + ")", "Cannot init fields more than once on the same mask", {
          manager: this
        });
        m.uniqueFields = [];
        m.invokeOnFields(mode, dive_nested, function(f) {
          var fbn;
          if (filter_callback && !filter_callback(f, ot)) {
            return;
          }
          fbn = fieldsByName[f.fullName()];
          if (!fbn) {
            fbn = {
              masks: [],
              field: f
            };
            fieldsByName[f.fullName()] = fbn;
          }
          return fbn.masks.push(m);
        });
      }
      for (fn in fieldsByName) {
        fbn = fieldsByName[fn];
        ot.fieldsByLocaName[fbn.field.fullNameLocalized()] = fbn.field;
        fbn.field.__in_masks = fbn.masks;
        if (fbn.masks.length > 1 || ot.masks.length === 1) {
          ref2 = fbn.masks;
          for (k = 0, len2 = ref2.length; k < len2; k++) {
            m = ref2[k];
            if (indexOf.call(ot.commonFieldsMasks, m) < 0) {
              ot.commonFieldsMasks.push(m);
            }
          }
          ot.commonFields.push(fbn.field);
        } else {
          fbn.masks[0].uniqueFields.push(fbn.field);
        }
      }
    }
  };

  ObjecttypeManager.prototype.getCommonFieldsByLocaName = function(filter_callback, removeNotCommon) {
    var cf, commonFields, field, fn, i, len, ot, ref, ref1;
    if (filter_callback == null) {
      filter_callback = null;
    }
    if (removeNotCommon == null) {
      removeNotCommon = true;
    }
    commonFields = {};
    ref = this.objecttypes;
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      CUI.util.assert(ot.commonFields, "ObjecttypeManager.getCommonFieldsByLocaName", "Common Fields are not initialized, use .initCommonFields before.");
      ref1 = ot.fieldsByLocaName;
      for (fn in ref1) {
        field = ref1[fn];
        if (filter_callback && !filter_callback(ot, field, commonFields[fn])) {
          continue;
        }
        if (!commonFields[fn]) {
          commonFields[fn] = [];
        }
        commonFields[fn].push(field);
      }
    }
    if (!removeNotCommon) {
      return commonFields;
    }
    for (fn in commonFields) {
      cf = commonFields[fn];
      if (cf.length === 1) {
        delete commonFields[fn];
      }
    }
    return commonFields;
  };

  ObjecttypeManager.prototype.getCommonFieldsMasks = function() {
    var i, j, len, len1, m, masks, ot, ref, ref1;
    masks = [];
    ref = this.objecttypes;
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      CUI.util.assert(ot.commonFields, "ObjecttypeManager.getCommonMaskNames", "Common Fields are not initialized, use .initCommonFields before.");
      ref1 = ot.commonFieldsMasks;
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        m = ref1[j];
        if (indexOf.call(masks, m) < 0) {
          masks.push(m);
        }
      }
    }
    return masks;
  };

  ObjecttypeManager.prototype.addLinkedObjectFields = function(fields) {
    var f, fn, i, len, m, o;
    for (i = 0, len = fields.length; i < len; i++) {
      f = fields[i];
      CUI.util.assert(f instanceof LinkedObject, "ObjecttypeManager.addLinkedObjectFields", "fields need to be instance of LinkedObject", {
        fields: fields
      });
      m = this.findMaskByName(f.linkMask().name());
      if (!m) {
        o = this.addMask(f.linkMask());
      } else {
        o = m.objecttype;
      }
      if (!o._linked_object_fields) {
        o._linked_object_fields = [];
        o._linked_object_fields_by_name = {};
      }
      if (!o._objecttypes) {
        o._objecttypes = {};
      }
      o._objecttypes[f.getMainMask().table.name()] = true;
      fn = f.fullName();
      if (!o._linked_object_fields_by_name[fn]) {
        o._linked_object_fields_by_name[fn] = [];
        o._linked_object_fields.push(fn);
      }
      o._linked_object_fields_by_name[fn].push(f);
    }
    return this;
  };

  ObjecttypeManager.prototype.getEASFields = function(mode, filter, include_linked) {
    var eas_fields, i, len, o, ref;
    if (include_linked == null) {
      include_linked = true;
    }
    eas_fields = [];
    ref = this.objecttypes;
    for (i = 0, len = ref.length; i < len; i++) {
      o = ref[i];
      if (!filter || filter(o)) {
        o.getEASFields(mode, eas_fields, include_linked);
      }
    }
    return eas_fields;
  };

  ObjecttypeManager.prototype.getAllFields = function(mode, filter) {
    var fields, i, len, o, ref;
    fields = [];
    ref = this.objecttypes;
    for (i = 0, len = ref.length; i < len; i++) {
      o = ref[i];
      if (!filter || filter(o)) {
        o.getAllFields(mode, fields);
      }
    }
    return fields;
  };

  ObjecttypeManager.prototype.getAllFieldsFromAllMasks = function(mode, filter) {
    var fields, i, len, o, ref;
    fields = [];
    ref = this.objecttypes;
    for (i = 0, len = ref.length; i < len; i++) {
      o = ref[i];
      if (!filter || filter(o)) {
        o.getAllFieldsFromAllMasks(mode, fields);
      }
    }
    return fields;
  };

  return ObjecttypeManager;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var SearchUtil;

SearchUtil = (function() {
  function SearchUtil() {}

  SearchUtil.QUOTES = '"';

  SearchUtil.SINGLE_QUOTE = "'";

  SearchUtil.ASTERISK = "*";

  SearchUtil.HASH = "#";

  SearchUtil.GRAVE_ACCENT = "`";

  SearchUtil.SPACE_REGEXP = /\s+/;

  SearchUtil.WILDCARD_REGEXP = /[?*]/;

  SearchUtil.SEARCH_MAX_LENGTH = 256;

  SearchUtil.MAX_OBJECTS_COUNT = 1000;

  SearchUtil.isWildcard = function(stringValue) {
    var wildcard;
    wildcard = stringValue.match(SearchUtil.WILDCARD_REGEXP);
    if (wildcard && CUI.util.isEmpty(stringValue.replaceAll('\"', '').replaceAll('*', '').trim())) {
      return null;
    }
    return wildcard;
  };

  SearchUtil.isWrappedWithQuotes = function(stringValue) {
    if (ez5.version("6")) {
      stringValue = SearchUtil.unwrapAsterisk(stringValue);
    }
    return stringValue.startsWith(SearchUtil.QUOTES) && stringValue.endsWith(SearchUtil.QUOTES);
  };

  SearchUtil.isWrappedWithSingleQuotes = function(stringValue) {
    return stringValue.startsWith(SearchUtil.SINGLE_QUOTE) && stringValue.endsWith(SearchUtil.SINGLE_QUOTE);
  };

  SearchUtil.isWrappedWithAsterisk = function(stringValue) {
    return stringValue.startsWith(SearchUtil.ASTERISK) && stringValue.endsWith(SearchUtil.ASTERISK);
  };

  SearchUtil.wrapSingleQuotes = function(token) {
    if (CUI.util.isEmpty(token)) {
      return token;
    }
    if (!token.startsWith(SearchUtil.SINGLE_QUOTE)) {
      token = SearchUtil.SINGLE_QUOTE + token;
    }
    if (!token.endsWith(SearchUtil.SINGLE_QUOTE)) {
      token += SearchUtil.SINGLE_QUOTE;
    }
    return token;
  };

  SearchUtil.wrapWithAsterisk = function(value) {
    value = value.trim();
    if (CUI.util.isEmpty(value)) {
      return value;
    }
    if (!value.startsWith(SearchUtil.ASTERISK)) {
      value = SearchUtil.ASTERISK + value;
    }
    if (!value.endsWith(SearchUtil.ASTERISK)) {
      value += SearchUtil.ASTERISK;
    }
    return value;
  };

  SearchUtil.unwrapAsterisk = function(value) {
    if (CUI.util.isEmpty(value)) {
      return value;
    }
    if (value.startsWith(SearchUtil.ASTERISK)) {
      value = value.substring(1);
    }
    if (value.endsWith(SearchUtil.ASTERISK)) {
      value = value.substring(0, value.length - 1);
    }
    return value;
  };

  SearchUtil.addWildcard = function(value, both_sides) {
    if (both_sides == null) {
      both_sides = false;
    }
    if (CUI.util.isEmpty(value)) {
      return value;
    }
    if (!value.endsWith(SearchUtil.ASTERISK)) {
      value += SearchUtil.ASTERISK;
    }
    if (both_sides && !value.startsWith(SearchUtil.ASTERISK)) {
      value = SearchUtil.ASTERISK + value;
    }
    return value;
  };

  SearchUtil.wrapGraveAccent = function(value) {
    if (CUI.util.isEmpty(value)) {
      return value;
    }
    if (!value.startsWith(SearchUtil.GRAVE_ACCENT)) {
      value = SearchUtil.GRAVE_ACCENT + value;
    }
    if (!value.endsWith(SearchUtil.GRAVE_ACCENT)) {
      value += SearchUtil.GRAVE_ACCENT;
    }
    return value;
  };

  SearchUtil.wrapQuotes = function(string, force) {
    if (force == null) {
      force = false;
    }
    if (CUI.util.isEmpty(string)) {
      return string;
    }
    if (!string.startsWith(SearchUtil.QUOTES) || force) {
      string = SearchUtil.QUOTES + string;
    }
    if (!string.endsWith(SearchUtil.QUOTES) || force) {
      string += SearchUtil.QUOTES;
    }
    return string;
  };

  SearchUtil.removeQuotes = function(value) {
    var endsWithAsterisk, startsWithAsterisk;
    if (ez5.version("6")) {
      if (value.startsWith(SearchUtil.ASTERISK)) {
        startsWithAsterisk = true;
        value = value.substring(1);
      }
      if (value.endsWith(SearchUtil.ASTERISK)) {
        endsWithAsterisk = true;
        value = value.substring(0, value.length - 1);
      }
    }
    if (value.startsWith(SearchUtil.QUOTES)) {
      value = value.substring(1);
    }
    if (value.endsWith(SearchUtil.QUOTES)) {
      value = value.substring(0, value.length - 1);
    }
    if (ez5.version("6")) {
      if (startsWithAsterisk) {
        value = SearchUtil.ASTERISK + value;
      }
      if (endsWithAsterisk) {
        value += SearchUtil.ASTERISK;
      }
    }
    return value;
  };

  SearchUtil.removeSingleQuotes = function(value) {
    if (value.startsWith(SearchUtil.SINGLE_QUOTE)) {
      value = value.substring(1);
    }
    if (value.endsWith(SearchUtil.SINGLE_QUOTE)) {
      value = value.substring(0, value.length - 1);
    }
    return value;
  };

  SearchUtil.isPhrase = function(value) {
    if (ez5.version("6")) {
      value = SearchUtil.unwrapAsterisk(value);
      return !!SearchUtil.SPACE_REGEXP.test(value) && SearchUtil.isWrappedWithQuotes(value);
    } else {
      return SearchUtil.isWrappedWithQuotes(value);
    }
  };

  SearchUtil.cleanWildCard = function(str) {
    var onlyAsterisksAndSpaces;
    onlyAsterisksAndSpaces = /^[* ]+$/;
    if (onlyAsterisksAndSpaces.test(str)) {
      return "";
    } else {
      return str;
    }
  };

  SearchUtil.isOnlyWildcards = function(str) {
    var cleaned;
    if (CUI.util.isEmpty(str)) {
      return false;
    }
    if (!SearchUtil.WILDCARD_REGEXP.test(str)) {
      return false;
    }
    cleaned = str.replaceAll(SearchUtil.ASTERISK, '').replaceAll('?', '').replaceAll(SearchUtil.QUOTES, '').replaceAll(SearchUtil.SINGLE_QUOTE, '').trim();
    return cleaned.length === 0;
  };

  return SearchUtil;

})();
// Generated by CoffeeScript 1.12.7
var Search,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function Search(opts) {
    Search.__super__.constructor.call(this, opts);
    this.__keyboardListeners = [];
  }

  Search.prototype.initOpts = function() {
    Search.__super__.initOpts.call(this);
    this.addOpts({
      request_format: {
        check: ["short", "standard", "long"]
      },
      onAddToRequest: {
        check: Function
      },
      onRequestDone: {
        check: Function
      }
    });
    return this;
  };

  Search.prototype.readOpts = function() {
    var btn_opts;
    Search.__super__.readOpts.call(this);
    this.request_counter = 0;
    btn_opts = this.getSearchButtonOpts();
    if (!btn_opts.onClick) {
      btn_opts.onClick = (function(_this) {
        return function(ev) {
          _this.searchButtonBeforeExecute();
          _this.executeWithLog(null, ev.altKey());
        };
      })(this);
    }
    this.__searchButton = new CUI.defaults["class"].Button(btn_opts);
    this.__executeQueue = [];
    this.searchManagers = [];
    this.__searchBasics = new SearchBasics({
      search: this
    });
    return this.__searchInitialized = new CUI.Deferred();
  };

  Search.prototype.getShareUrl = function() {};

  Search.prototype.searchButtonBeforeExecute = function() {};

  Search.prototype.getRequestFormat = function() {
    return this._request_format;
  };

  Search.prototype.getSearchButtonOpts = function() {
    return {
      "class": "ez-search-main-button ez5-search-button",
      ui: "search.button",
      loca_key: "search.button.search",
      group: "search-button",
      icon: "search"
    };
  };

  Search.prototype.emptyRequest = function() {
    var i, len, ref, sm;
    ref = this.__getSearchManagers();
    for (i = 0, len = ref.length; i < len; i++) {
      sm = ref[i];
      sm.emptyRequest();
    }
    return this;
  };

  Search.prototype.getSearchInitializedPromise = function() {
    return this.__searchInitialized.promise();
  };

  Search.prototype.addSearchManager = function(new_search_manager) {
    CUI.util.assert(new_search_manager instanceof SearchManager, "Search.addSearchManager", "search manager needs to be instanceof SearchManager", {
      searchManager: new_search_manager
    });
    CUI.util.assert(CUI.util.idxInArray(new_search_manager, this.searchManagers) < 0);
    new_search_manager.setSearch(this);
    this.searchManagers.push(new_search_manager);
    return new_search_manager;
  };

  Search.prototype.insertAfterSearchManager = function(previous_search_manager, new_search_manager) {
    var index;
    CUI.util.assert(previous_search_manager instanceof SearchManager, "Search.insertAfterSearchManager", "previous_search_manager needs to be instanceof SearchManager", {
      previous_search_manager: previous_search_manager,
      new_search_manager: new_search_manager
    });
    CUI.util.assert(new_search_manager instanceof SearchManager, "Search.insertAfterSearchManager", "new_search_manager needs to be instanceof SearchManager", {
      previous_search_manager: previous_search_manager,
      new_search_manager: new_search_manager
    });
    CUI.util.assert(CUI.util.idxInArray(new_search_manager, this.searchManagers) < 0);
    new_search_manager.setSearch(this);
    index = CUI.util.idxInArray(previous_search_manager, this.searchManagers);
    CUI.util.assert(index >= 0);
    this.searchManagers.splice(index + 1, 0, new_search_manager);
    return new_search_manager;
  };

  Search.prototype.init = function() {
    this.disableSearchButton();
    return this.__initSearchManagers().done((function(_this) {
      return function() {
        _this.enableSearchButton();
        _this.__searchInitialized.resolve(_this);
        return _this.__doExecuteNext();
      };
    })(this));
  };

  Search.prototype.isTrashModeActive = function() {
    var i, len, ref, sm;
    if (!TrashSearchManager.canSeeDeleted()) {
      return false;
    }
    ref = this.getSearchManagers();
    for (i = 0, len = ref.length; i < len; i++) {
      sm = ref[i];
      if (sm instanceof TrashSearchManager && sm.isActive()) {
        return true;
      }
    }
    return false;
  };

  Search.prototype.__initSearchManagers = function() {
    var funcs, sm;
    funcs = (function() {
      var i, len, ref, results;
      ref = this.__getSearchManagers();
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        sm = ref[i];
        results.push((function(_this) {
          return function(sm) {
            return function() {
              if (_this.isDestroyed()) {
                return new CUI.Deferred().reject().promise();
              }
              return sm.init();
            };
          };
        })(this)(sm));
      }
      return results;
    }).call(this);
    if (this.hasSearchBasics()) {
      funcs.splice(0, 0, (function(_this) {
        return function() {
          return _this.__searchBasics.init();
        };
      })(this));
    }
    return CUI.chainedCall.apply(CUI, funcs);
  };

  Search.prototype.refresh = function() {
    this.destroySearchManagers();
    this.enableSearchButton();
    this.request_counter = 0;
    this.__searchInitialized = new CUI.Deferred();
    return this.init();
  };

  Search.prototype.getStoreData = function() {
    var i, len, ref, sd, sm;
    sd = {};
    ref = this.__getSearchManagers();
    for (i = 0, len = ref.length; i < len; i++) {
      sm = ref[i];
      sm.getStoreData(sd);
    }
    return sd;
  };

  Search.prototype.addCollectionAfterSave = function(received_data) {};

  Search.prototype.getStoreSearchData = function() {
    var ex, sd;
    try {
      sd = {
        version: this.getStoreDataVersion(),
        search: this.getStoreData()
      };
    } catch (error) {
      ex = error;
      if (ex instanceof InvalidSaveDataException) {
        return null;
      }
      throw ex;
    }
    return sd;
  };

  Search.prototype.getStoreDataVersion = function() {
    return {
      schema: ez5.schema.CURRENT.version,
      save_data: Search.storeDataVersion
    };
  };

  Search.prototype.getStoreAsUrlData = function() {
    var ex, i, len, ref, sm, url_data;
    url_data = {};
    try {
      ref = this.__getSearchManagers();
      for (i = 0, len = ref.length; i < len; i++) {
        sm = ref[i];
        sm.getStoreAsUrlData(url_data);
      }
    } catch (error) {
      ex = error;
      if (ex instanceof InvalidSaveDataException) {
        return null;
      }
      throw ex;
    }
    return url_data;
  };

  Search.prototype.addToResultDiv = function(request, result_object, div) {
    var _parms, i, len, managers, renderParms, sm;
    renderParms = null;
    managers = [];
    if (!request.exclusive) {
      managers.push.apply(managers, this.__getSearchManagers());
    }
    if (request.searchManagers) {
      managers.push.apply(managers, request.searchManagers);
    }
    for (i = 0, len = managers.length; i < len; i++) {
      sm = managers[i];
      _parms = sm.addToResultDiv(request, result_object, div);
      if (_parms) {
        CUI.util.assert(renderParms === null, "Search.addToResultDiv", "More than one search manager returned render parms.");
        renderParms = _parms;
      }
    }
    return renderParms;
  };

  Search.prototype.destroySearchManagers = function() {
    var i, len, ref, sm;
    ref = this.__getSearchManagers();
    for (i = 0, len = ref.length; i < len; i++) {
      sm = ref[i];
      sm.destroy();
    }
    this.searchManagers = [];
    return this;
  };

  Search.prototype.removeSearchManager = function(sm) {
    sm.unsetSearch();
    CUI.util.removeFromArray(sm, this.searchManagers);
    return this;
  };

  Search.prototype.objecttypesUpdated = function(initiator) {
    var fn, funcs, i, len, ref, ret, sm;
    funcs = [];
    ref = this.__getSearchManagers();
    fn = (function(_this) {
      return function(sm) {
        return funcs.push(function() {
          return sm.objecttypesUpdated();
        });
      };
    })(this);
    for (i = 0, len = ref.length; i < len; i++) {
      sm = ref[i];
      if (sm === initiator) {
        continue;
      }
      fn(sm);
    }
    ret = CUI.chainedCall.apply(CUI, funcs);
    return ret;
  };

  Search.prototype.canCreateSearchObjecttypes = function() {
    var objecttypes;
    objecttypes = this.getSearchObjecttypes();
    CUI.util.removeFromArray(null, objecttypes, function(o) {
      return !o.isLocal();
    });
    if (objecttypes.length === 0) {
      return CUI.rejectedPromise();
    }
    return DbInfo.canCreate({
      objecttypes: objecttypes
    });
  };

  Search.prototype.getExportObjecttypesAndCount = function(request) {
    var _req, dfr, req;
    _req = request.cleanRequestForSearch();
    req = {
      type: "object",
      best_mask_filter: _req.best_mask_filter,
      search: _req.search,
      objecttypes: _req.objecttypes,
      limit: 0,
      aggregations: {
        _mask: {
          type: "term",
          limit: 100000,
          field: "_mask"
        }
      }
    };
    dfr = new CUI.Deferred();
    ez5.api.search({
      json_data: req
    }).done((function(_this) {
      return function(data) {
        var i, len, otm, ref, term;
        otm = new ObjecttypeManager();
        ref = data.aggregations._mask.terms;
        for (i = 0, len = ref.length; i < len; i++) {
          term = ref[i];
          otm.addMask(Mask.getMaskByMaskName(term.term));
        }
        return dfr.resolve(otm.getObjecttypes(), data.count);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  Search.prototype.getSearchObjecttypes = function(user_selected, filter_by_pool) {
    var i, j, len, len1, o, ot, ref, ref1, sm;
    if (user_selected == null) {
      user_selected = true;
    }
    if (filter_by_pool == null) {
      filter_by_pool = false;
    }
    ot = [];
    ref = this.__getSearchManagers();
    for (i = 0, len = ref.length; i < len; i++) {
      sm = ref[i];
      ref1 = sm.getObjecttypesForSearch(user_selected);
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        o = ref1[j];
        if (!filter_by_pool || o.poolLink()) {
          CUI.util.assert(o instanceof Objecttype, "Search.getSearchObjecttypes", "Objecttype needs to be instanceof Objecttype", {
            objecttype: o
          });
          ot.push(o);
        }
      }
    }
    return ot;
  };

  Search.prototype.getSearchPoolIds = function(include_remote) {
    var i, j, len, len1, pool_id, pool_ids, ref, ref1, sm;
    if (include_remote == null) {
      include_remote = false;
    }
    pool_ids = [];
    ref = this.__getSearchManagers();
    for (i = 0, len = ref.length; i < len; i++) {
      sm = ref[i];
      ref1 = sm.getPoolIdsForSearch(include_remote);
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        pool_id = ref1[j];
        pool_ids.push(pool_id);
      }
    }
    return pool_ids;
  };

  Search.prototype.hasEASFields = function(user_selected) {
    var i, len, ot, ref;
    if (user_selected == null) {
      user_selected = true;
    }
    ref = this.getSearchObjecttypes(user_selected);
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      if (ot.getEASFields().length > 0) {
        return true;
      }
    }
    return false;
  };

  Search.prototype.hasSearchBasics = function() {
    return true;
  };

  Search.prototype.getSearchBasics = function() {
    if (this.hasSearchBasics()) {
      return this.__searchBasics;
    } else {
      return null;
    }
  };

  Search.prototype.getFieldsByFilter = function(filter, mode, user_selected) {
    var fields, i, j, len, len1, m, mask_names, o, ref, ref1, ref2, searchBasics;
    if (user_selected == null) {
      user_selected = false;
    }
    fields = [];
    searchBasics = this.getSearchBasics();
    if (!searchBasics) {
      return fields;
    }
    mask_names = searchBasics.getMaskNames();
    ref = this.getSearchObjecttypes(user_selected);
    for (i = 0, len = ref.length; i < len; i++) {
      o = ref[i];
      ref1 = o.masks;
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        m = ref1[j];
        if (ref2 = m.name(), indexOf.call(mask_names, ref2) < 0) {
          continue;
        }
        m.invokeOnFields(mode, true, function(f) {
          if (typeof filter === "function" ? filter(f) : void 0) {
            fields.push(f);
          }
        });
      }
    }
    fields.sort(function(a, b) {
      return CUI.util.compareIndex(a.nameLocalized(), b.nameLocalized());
    });
    return fields;
  };

  Search.prototype.getLinkedObjectFields = function(mode, user_selected) {
    var filterByLinkedFields, linkedFields;
    if (user_selected == null) {
      user_selected = false;
    }
    filterByLinkedFields = function(f) {
      if (f instanceof TreeColumn) {
        return false;
      }
      if (f instanceof LinkedObject && f.linkMask()) {
        return true;
      }
      return false;
    };
    linkedFields = this.getFieldsByFilter(filterByLinkedFields, mode, user_selected);
    return linkedFields;
  };

  Search.prototype.addToRequest = function(request) {
    var add_and_run, i, j, k, l, len, len1, len2, o, ref, ref1, ref2, ref3, s, sm, v;
    if (!(request != null ? request.exclusive : void 0)) {
      if (!request.hasOwnProperty("objecttypes")) {
        request.objecttypes = (function() {
          var i, len, ref, results;
          ref = this.getSearchObjecttypes();
          results = [];
          for (i = 0, len = ref.length; i < len; i++) {
            o = ref[i];
            results.push(o.name());
          }
          return results;
        }).call(this);
      }
      ref = {
        offset: 0,
        generate_rights: false
      };
      for (k in ref) {
        v = ref[k];
        if (!request.hasOwnProperty(k)) {
          request[k] = v;
        }
      }
    }
    if (!(!request.objecttypes || request.objecttypes.length >= 0)) {
      return this;
    }
    add_and_run = function(sm) {
      var ex;
      try {
        request.__searchManagers.push(sm);
        sm.addToRequest(request);
      } catch (error) {
        ex = error;
        if (ex instanceof UserError) {
          ex.presentError();
        } else {
          throw ex;
        }
      }
    };
    request.__searchManagers = [];
    if (!(request != null ? request.exclusive : void 0)) {
      ref1 = this.__getSearchManagers();
      for (i = 0, len = ref1.length; i < len; i++) {
        sm = ref1[i];
        add_and_run(sm);
      }
    }
    if (request.searchManagers) {
      ref2 = request.searchManagers;
      for (j = 0, len1 = ref2.length; j < len1; j++) {
        sm = ref2[j];
        add_and_run(sm);
      }
    }
    if (request.search) {
      ref3 = request.search;
      for (l = 0, len2 = ref3.length; l < len2; l++) {
        s = ref3[l];
        if (s === false) {
          request.search = false;
          break;
        }
      }
    }
    this.setRequestFormat(request, this._request_format);
    return this;
  };

  Search.prototype.setRequestFormat = function(request, format) {
    if (!format) {
      return this;
    }
    if (!request.format) {
      request.format = format;
      return this;
    }
    if (ResultObject.compareFormats(request.format, format) < 0) {
      request.format = format;
    }
    return this;
  };

  Search.prototype.showResult = function(request, data) {};

  Search.prototype.disableSearchButton = function() {
    var sb;
    sb = this.getSearchButton();
    if (!sb) {
      return;
    }
    if (!this.__sbIcon) {
      this.__sbIcon = sb.getIcon();
      if (this.__sbIcon) {
        sb.setIcon("spinner");
      }
    }
    sb.disable();
    return this;
  };

  Search.prototype.enableSearchButton = function() {
    var sb;
    sb = this.getSearchButton();
    if (!sb) {
      return;
    }
    if (this.__sbIcon) {
      sb.setIcon(this.__sbIcon);
      delete this.__sbIcon;
    }
    sb.enable();
    return this;
  };

  Search.prototype.getDownloadManagerClass = function() {
    return ez5.defaults["class"].DownloadManager;
  };

  Search.prototype.executeAlwaysCallback = function() {
    this.enableSearchButton();
    return this;
  };

  Search.prototype.executeWithLog = function(request, pushState) {
    var ex, sd, share_url;
    if (request == null) {
      request = new Request();
    }
    if (pushState == null) {
      pushState = false;
    }
    if (pushState) {
      share_url = this.getShareUrl();
      if (share_url) {
        window.history.pushState({}, null, share_url);
      }
    }
    try {
      sd = this.getStoreData();
    } catch (error) {
      ex = error;
      if (!(ex instanceof InvalidSaveDataException)) {
        throw ex;
      }
    }
    return this.execute(request).done((function(_this) {
      return function(request, data) {
        var ref, ref1;
        if (!(sd != null ? (ref = sd.SearchInput) != null ? (ref1 = ref.query) != null ? ref1.length : void 0 : void 0 : void 0)) {
          return;
        }
        return EventPoller.saveEvent({
          type: "SEARCH",
          info: {
            version: _this.getStoreDataVersion(),
            request: {
              search: sd,
              offset: request.offset,
              limit: request.limit
            },
            response: {
              count: data.count,
              timings: {
                request_time: data.request_time,
                client: data.clientTook
              }
            }
          }
        });
      };
    })(this));
  };

  Search.prototype.execute = function(request) {
    var master_dfr, promise;
    if (request == null) {
      request = new Request();
    }
    CUI.util.assert(request instanceof Request, this.__cls + ".execute", "Request needs to be instance of Request.", {
      request: request
    });
    if (request.exclusive || request.exclusive_show) {
      CUI.util.assert(request.searchManagers, this.__cls + ".execute", "request.exclusive and request.exclusive_show need request.searchManagers to be set", {
        request: request
      });
    }
    master_dfr = new CUI.Deferred();
    master_dfr.always((function(_this) {
      return function() {
        if (_this.isDestroyed()) {
          return;
        }
        return _this.executeAlwaysCallback();
      };
    })(this));
    if (this.__searchBasics) {
      promise = this.__searchBasics.update();
    } else {
      promise = CUI.resolvedPromise();
    }
    promise.done((function(_this) {
      return function() {
        var chain, i, idx, len, ref, sm;
        if (request.searchManagers) {
          CUI.util.assert(CUI.util.isArray(request.searchManagers), _this.__cls + ".execute", "request.searchManagers needs to be Array.", {
            request: request
          });
          chain = [];
          ref = request.searchManagers;
          for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
            sm = ref[idx];
            CUI.util.assert(sm instanceof SearchManager, _this.__cls + ".execute", "request.searchManagers[" + idx + "] needs to be instance of SearchManager.", {
              request: request
            });
            if (sm.getSearch() === _this) {
              continue;
            }
            chain.push(function() {
              sm.setSearch(_this);
              return sm.init();
            });
          }
          return CUI.chainedCall.apply(CUI, chain).done(function() {
            return _this.__doExecute(request, master_dfr);
          }).fail(master_dfr.reject);
        } else {
          request.execute = true;
          _this.disableSearchButton();
          return _this.__doExecute(request, master_dfr);
        }
      };
    })(this));
    promise.fail(master_dfr.reject);
    return master_dfr.promise();
  };

  Search.prototype.isInitialized = function() {
    return this.__searchInitialized.state() === "resolved";
  };

  Search.prototype.__doExecute = function(request, master_dfr) {
    this.__executeQueue.push({
      request: request,
      master_dfr: master_dfr
    });
    return this.__doExecuteNext();
  };

  Search.prototype.__doExecuteNext = function() {
    var dfr, empty_response, master_dfr, req_data, request, timer, work;
    if (this.__executeQueue.length === 0) {
      return;
    }
    if (this.__executeLock) {
      return;
    }
    if (!this.isInitialized()) {
      return;
    }
    this.__executeLock = true;
    work = this.__executeQueue.splice(0, 1)[0];
    request = work.request;
    master_dfr = work.master_dfr;
    master_dfr.always((function(_this) {
      return function() {
        return master_dfr.always(function() {
          _this.__executeLock = false;
          if (_this.isDestroyed()) {
            return;
          }
          return _this.__doExecuteNext();
        });
      };
    })(this));
    request.__searchManagers = null;
    this.addToRequest(request);
    if (typeof this._onAddToRequest === "function") {
      this._onAddToRequest(request);
    }
    dfr = new CUI.Deferred();
    empty_response = (function(_this) {
      return function() {
        var data;
        data = {
          _dummy_data: true,
          objects: [],
          aggregations: [],
          count: 0,
          limit: request.limit,
          offset: request.offset
        };
        _this.lastData = CUI.util.copyObject(data, true);
        return dfr.resolve(data);
      };
    })(this);
    if (request.search !== false) {
      request.counter = ++this.request_counter;
      timer = (new Date()).getTime();
      CUI.util.assert(!request.hasOwnProperty("limit") || !isNaN(request.limit), "Search.execute", "request.limit is not a number", {
        request: request
      });
      req_data = request.cleanRequestForSearch();
      this.executeSearch(req_data).fail((function(_this) {
        return function(xhr) {
          var ref;
          if (request.execute && (xhr != null ? (ref = xhr.responseJSON) != null ? ref.code : void 0 : void 0) === "error.api.invalid_value") {
            empty_response();
            return;
          }
          console.error("Request #" + request.counter + " failed", xhr);
          return ez5.error_handler(xhr).done(function() {
            _this.lastData = null;
            return dfr.reject(xhr);
          });
        };
      })(this)).done((function(_this) {
        return function(data) {
          if (typeof _this._onRequestDone === "function") {
            _this._onRequestDone(data);
          }
          if (!data) {
            _this.lastData = null;
            dfr.reject();
            return;
          }
          data.clientTook = (new Date()).getTime() - timer;
          _this.lastData = CUI.util.copyObject(data, true);
          if (request.counter !== _this.request_counter) {
            console.info("Request #" + request.counter + ": Ignored response, current request counter is at #" + _this.request_counter + ".");
            return dfr.reject({
              cancelled: true
            });
          } else {
            return dfr.resolve(data);
          }
        };
      })(this));
    } else {
      empty_response();
    }
    dfr.done((function(_this) {
      return function(data) {
        var i, len, promises, ref, ret, sm;
        promises = [];
        ret = _this.showResult(request, data);
        if (CUI.util.isPromise(ret)) {
          promises.push(ret);
        }
        if (request.__searchManagers) {
          ref = request.__searchManagers;
          for (i = 0, len = ref.length; i < len; i++) {
            sm = ref[i];
            if (!request.exclusive_show || indexOf.call(request.searchManagers, sm) >= 0) {
              if (sm.isDestroyed()) {
                continue;
              }
              ret = sm.showResult(request, data);
              if (CUI.util.isPromise(ret)) {
                promises.push(ret);
              }
            }
          }
        }
        master_dfr.always(function() {
          var ref1;
          if (!request.searchManagers && _this.__resultContainer) {
            if ((ref1 = _this.getSearchBasics()) != null) {
              ref1.setEASClassOnResultContainer();
            }
            return CUI.Events.trigger({
              node: _this.__resultContainer,
              type: "search",
              info: {
                search: _this
              }
            });
          }
        });
        return CUI.when(promises).done(function() {
          return master_dfr.resolve(request, data);
        }).fail(function() {
          return master_dfr.reject();
        });
      };
    })(this));
    return dfr.fail((function(_this) {
      return function(xhr) {
        var i, len, ref, sm;
        if (!(xhr != null ? xhr.cancelled : void 0)) {
          ref = request.__searchManagers;
          for (i = 0, len = ref.length; i < len; i++) {
            sm = ref[i];
            sm.failResult(request, xhr);
          }
        }
        return master_dfr.reject(xhr);
      };
    })(this));
  };

  Search.prototype.executeSearch = function(req_data) {
    var dfr;
    dfr = new CUI.Deferred();
    ez5.api.search({
      debug: {
        search: this
      },
      data: {
        debug: this.getRequestDebug()
      },
      json_data: req_data,
      error: (function(_this) {
        return function(xhr) {
          return dfr.reject(xhr);
        };
      })(this),
      success: (function(_this) {
        return function(data) {
          return dfr.resolve(data);
        };
      })(this)
    });
    return dfr.promise();
  };

  Search.prototype.getRequestDebug = function() {
    return this.getElementClass();
  };

  Search.prototype.getCurrentTools = function() {
    var i, len, ref, sm, sm_tools, tools;
    tools = [];
    ref = this.__getSearchManagers();
    for (i = 0, len = ref.length; i < len; i++) {
      sm = ref[i];
      sm_tools = sm.getCurrentTools();
      if ((sm_tools != null ? sm_tools.length : void 0) > 0) {
        tools.push.apply(tools, sm_tools);
      }
    }
    return tools;
  };

  Search.prototype.getLastData = function() {
    return this.lastData || null;
  };

  Search.prototype.getSearchManagers = function(filter) {
    var i, len, ref, sm, sms;
    if (!filter) {
      return this.__getSearchManagers();
    } else {
      sms = [];
      ref = this.__getSearchManagers();
      for (i = 0, len = ref.length; i < len; i++) {
        sm = ref[i];
        if (filter(sm)) {
          sms.push(sm);
        }
      }
      return sms;
    }
  };

  Search.prototype.destroy = function() {
    var i, len, ref, ref1, ref2, sm;
    delete this.data;
    ref = this.__getSearchManagers();
    for (i = 0, len = ref.length; i < len; i++) {
      sm = ref[i];
      sm.destroy();
    }
    delete this.searchManagers;
    if ((ref1 = this.__searchBasics) != null) {
      ref1.destroy();
    }
    this.__searchBasics = null;
    if ((ref2 = this.__searchButton) != null) {
      ref2.destroy();
    }
    delete this.__searchButton;
    this.__cleanKeyboardListeners();
    return Search.__super__.destroy.call(this);
  };

  Search.prototype.registerResultContainer = function(__resultContainer) {
    var ref;
    this.__resultContainer = __resultContainer;
    CUI.dom.addClass(this.__resultContainer, "ez5-search-result-container");
    CUI.dom.data(this.__resultContainer, "search", this);
    if ((ref = this.getSearchBasics()) != null) {
      ref.setEASClassOnResultContainer();
    }
    return this;
  };

  Search.prototype.getResultContainer = function() {
    return this.__resultContainer;
  };

  Search.prototype.getSearchButton = function() {
    return this.__searchButton;
  };

  Search.prototype.hasUserInput = function(request, excludedSearchManager) {
    var i, len, ref, sm;
    if (excludedSearchManager == null) {
      excludedSearchManager = [];
    }
    ref = this.__getSearchManagers();
    for (i = 0, len = ref.length; i < len; i++) {
      sm = ref[i];
      if (indexOf.call(excludedSearchManager, sm) >= 0) {
        continue;
      }
      if (sm.hasUserInput(request)) {
        return true;
      }
    }
    return false;
  };

  Search.prototype.getDefaultSort = function() {};

  Search.prototype.getDefaultSortKey = function() {
    return "main.search.sort.relevance";
  };

  Search.prototype.setEmptyResultTextLocaKey = function(key) {
    var new_label;
    CUI.util.assert(CUI.util.isString(key), "Search.setEmptyResultTextLocaKey", "key must be a string", {
      key: key
    });
    if (!this.__empty_label) {
      return;
    }
    new_label = new LocaLabel({
      loca_key: key,
      "class": "cui-empty-label search-empty-result",
      centered: true,
      multiline: false,
      attr: {
        role: "status"
      }
    });
    CUI.dom.replace(CUI.dom.parent(this.__empty_label.DOM), new_label.DOM);
    this.__empty_label = new_label;
    return this;
  };

  Search.prototype.getEmptyResultDiv = function(request) {
    var cls, k;
    if (this.request_counter === 0) {
      k = "search.welcome";
    } else if (this.hasUserInput(request)) {
      if ((request != null ? request.hasOwnProperty("show_hierarchy") : void 0) && !request.show_hierarchy) {
        k = "search.nothing_found.top_level_only";
      } else {
        k = "search.nothing_found";
      }
      cls = "cui-empty-label";
    } else {
      k = "search.nothing_found_with_empty_search";
      cls = "cui-empty-label";
    }
    this.__empty_label = new LocaLabel({
      loca_key: k,
      "class": cls + " search-empty-result",
      centered: true,
      multiline: true,
      attr: {
        role: "status"
      }
    });
    return this.__empty_label.DOM;
  };

  Search.prototype.__getSearchManagers = function() {
    return this.searchManagers || [];
  };

  Search.keyboardListenerStack = [];

  Search.keyboardListenerControl = null;

  Search.prototype.__cleanKeyboardListeners = function() {
    var i, len, listener, ref;
    ref = this.__keyboardListeners;
    for (i = 0, len = ref.length; i < len; i++) {
      listener = ref[i];
      listener.destroy();
    }
    return this.__keyboardListeners = [];
  };

  Search.prototype.registerKeyboardShortcuts = function(container) {
    var findResult, isResult;
    if (this.__keyboardListeners.length) {
      return;
    }
    container.setAttribute("tabindex", "0");
    container.classList.add("ez5-search-keyboard-container");
    isResult = (function(_this) {
      return function(node) {
        return CUI.dom.hasClass(node, "result-dynamic") || CUI.dom.hasClass(node, "cui-lv-tr-outer");
      };
    })(this);
    findResult = (function(_this) {
      return function(element, select) {
        var next;
        next = select(element);
        if (!next) {
          return;
        }
        if (isResult(next)) {
          return next;
        }
        return findResult(next, select);
      };
    })(this);
    this.__keyboardListeners.push(CUI.Events.listen({
      node: this.getResultContainer(),
      type: ["keydown"],
      call: (function(_this) {
        return function(event) {
          var key, nextKey, previousKey, ref, target;
          key = event.key();
          if (!key.startsWith("Arrow")) {
            return;
          }
          target = event.getNode();
          if (!isResult(target)) {
            target = target.querySelector(".cui-selected");
          }
          if (!isResult(target)) {
            return;
          }
          ref = CUI.dom.hasClass(target, "result-standard") ? ["ArrowLeft", "ArrowRight"] : ["ArrowUp", "ArrowDown"], previousKey = ref[0], nextKey = ref[1];
          switch (key) {
            case previousKey:
              event.preventDefault();
              target = findResult(target, function(element) {
                return element != null ? element.previousElementSibling : void 0;
              });
              break;
            case nextKey:
              event.preventDefault();
              target = findResult(target, function(element) {
                return element != null ? element.nextElementSibling : void 0;
              });
              break;
            default:
              return;
          }
          if (target != null) {
            target.focus();
          }
          if (target != null) {
            target.scrollIntoView();
          }
          if (target != null) {
            target.click();
          }
        };
      })(this)
    }));
    return this.__keyboardListeners.push(CUI.Events.listen({
      node: container,
      type: ["keydown"],
      call: (function(_this) {
        return function(event) {
          var manager, tool;
          if (!event.hasModifierKey()) {
            return;
          }
          manager = _this.getSearchManagers().filter(function(manager) {
            return manager instanceof CollectionSearchManager;
          })[0];
          if (!manager) {
            return;
          }
          switch (event.code()) {
            case "KeyA":
              if (document.activeElement instanceof HTMLInputElement) {
                return;
              }
              event.preventDefault();
              tool = manager.getCurrentTools().find(function(arg) {
                var _name;
                _name = arg._name;
                return _name === "selection.all";
              });
              break;
            case "KeyD":
              event.preventDefault();
              tool = manager._collection.getCurrentTools(false).find(function(arg) {
                var _name;
                _name = arg._name;
                return ["collection.selection.download", "object.download"].includes(_name);
              });
              break;
            case "KeyE":
              event.preventDefault();
              if (event.shiftKey()) {
                tool = manager._collection.getCurrentTools().find(function(arg) {
                  var _name;
                  _name = arg._name;
                  return ["collection.selection.export", "object.export"].includes(_name);
                });
              } else {
                tool = {
                  run: function() {
                    var ref, ref1;
                    return (ref = _this.getSearchInput()) != null ? (ref1 = ref.__expertOpts) != null ? ref1.openPopover() : void 0 : void 0;
                  }
                };
              }
          }
          if (tool != null) {
            tool.run();
          }
        };
      })(this)
    }));
  };

  Search.getPhrase = function(stringValue) {
    var phrase;
    CUI.util.assert(CUI.util.isString(stringValue), "Search.getPhrase", "Parameter must be a String", {
      string: stringValue
    });
    stringValue = stringValue.trim();
    phrase = SearchUtil.isPhrase(stringValue);
    if (SearchUtil.isWrappedWithQuotes(stringValue)) {
      stringValue = SearchUtil.removeQuotes(stringValue);
    } else {
      if (stringValue.startsWith(SearchUtil.SINGLE_QUOTE) || stringValue.startsWith(SearchUtil.GRAVE_ACCENT)) {
        stringValue = stringValue.substring(1);
      }
      if (stringValue.endsWith(SearchUtil.SINGLE_QUOTE) || stringValue.endsWith(SearchUtil.GRAVE_ACCENT)) {
        stringValue = stringValue.substring(0, stringValue.length - 1);
      }
    }
    if (stringValue.length > SearchUtil.SEARCH_MAX_LENGTH) {
      stringValue = stringValue.substring(0, SearchUtil.SEARCH_MAX_LENGTH);
    }
    return [stringValue, phrase];
  };

  Search.findByName = function(name) {
    var i, len, rc, ref, s;
    CUI.util.assert(!CUI.util.isEmpty(name), "Search.findByName", "\"name\" must not be empty.", {
      name: name
    });
    ref = CUI.dom.find(".ez5-search-result-container");
    for (i = 0, len = ref.length; i < len; i++) {
      rc = ref[i];
      s = CUI.dom.data(rc, "search");
      if (CUI.util.getObjectClass(s) === name) {
        return [s, rc];
      }
    }
    return [null, null];
  };

  Search.storeDataVersion = 1;

  return Search;

})(CUI.Element);

CUI.ready((function(_this) {
  return function() {
    return CUI.Events.registerEvent({
      type: "search",
      bubble: true
    });
  };
})(this));
// Generated by CoffeeScript 1.12.7
var SearchManager,
  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;

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

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

  SearchManager.prototype.init = function() {};

  SearchManager.prototype.setSearch = function(_search) {
    this._search = _search;
    CUI.util.assert(this._search instanceof Search, this.__cls + ".setSearch: search needs to be instance of Search", {
      search: this._search
    });
    return this;
  };

  SearchManager.prototype.unsetSearch = function() {
    return this._search = null;
  };

  SearchManager.prototype.getSearch = function() {
    return this._search;
  };

  SearchManager.prototype.destroy = function() {
    return SearchManager.__super__.destroy.call(this);
  };

  SearchManager.prototype.emptyRequest = function() {};

  SearchManager.prototype.getObjecttypesForSearch = function(user_selected) {
    if (user_selected == null) {
      user_selected = true;
    }
    return [];
  };

  SearchManager.prototype.getPoolIdsForSearch = function(include_remote) {
    if (include_remote == null) {
      include_remote = false;
    }
    return [];
  };

  SearchManager.prototype.addToRequest = function(request) {};

  SearchManager.prototype.showResult = function(request, data) {};

  SearchManager.prototype.failResult = function(request, xhr) {};

  SearchManager.prototype.hasUserInput = function() {
    return false;
  };

  SearchManager.prototype.addToResultDiv = function(request, result_object, div) {};

  SearchManager.prototype.objecttypesUpdated = function() {};

  SearchManager.prototype.startSearch = function() {};

  SearchManager.prototype.getStoreData = function(data) {};

  SearchManager.prototype.getStoreAsUrlData = function(url_data) {};

  SearchManager.prototype.initFromUrlData = function(url_data) {};

  SearchManager.prototype.getCurrentTools = function() {};

  return SearchManager;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var SearchStats,
  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;

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

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

  SearchStats.prototype.showResult = function(request, data) {
    var stats;
    stats = this.countData(data);
    console.info("SearchStats.showResult:", data, ez5.format_filesize(JSON.stringify(data).length));
    console.debug("==== ROOT ====");
    return this.printStats(stats.root);
  };

  SearchStats.prototype.printStats = function(stats) {
    var keys, keys_by_size, output_keys;
    output_keys = (function(_this) {
      return function(keys) {
        var i, key, len, output, value;
        output = [];
        for (i = 0, len = keys.length; i < len; i++) {
          key = keys[i];
          value = stats[key];
          output.push(key + ": " + value.count + " (" + ez5.format_filesize(value.bytes) + ")");
        }
        return console.debug(output.join("\n"));
      };
    })(this);
    keys = Object.keys(stats);
    keys.sort();
    keys_by_size = keys.slice(0);
    keys_by_size.sort(function(a, b) {
      return CUI.util.compareIndex(stats[b].bytes, stats[a].bytes);
    });
    console.debug("=== BY KEY ===");
    output_keys(keys);
    console.debug("=== BY SIZE ===");
    return output_keys(keys_by_size);
  };

  SearchStats.prototype.__inc = function(stats, path, data) {
    var path_str;
    path_str = path.join(".");
    if (!stats.hasOwnProperty(path_str)) {
      stats[path_str] = {
        count: 0,
        bytes: 0
      };
    }
    stats[path_str].count += 1;
    return stats[path_str].bytes += JSON.stringify(data).length;
  };

  SearchStats.prototype.countData = function(data, stats, path, level) {
    var count, i, item, len;
    if (stats == null) {
      stats = {
        root: {},
        parts: {}
      };
    }
    if (path == null) {
      path = ["root"];
    }
    if (level == null) {
      level = 0;
    }
    count = (function(_this) {
      return function(_data) {
        var copy_path, cpath, k, v;
        cpath = path.slice(0);
        cpath.shift();
        _this.__inc(stats.root, cpath, _data);
        while (cpath.shift()) {
          _this.__inc(stats.parts, cpath, _data);
        }
        if (CUI.util.isPlainObject(_data)) {
          for (k in _data) {
            v = _data[k];
            copy_path = path.slice(0);
            if (CUI.util.isArray(v)) {
              copy_path.push(k + "[]");
            } else {
              copy_path.push(k);
            }
            _this.countData(v, stats, copy_path, level + 1);
          }
        }
      };
    })(this);
    if (CUI.util.isArray(data)) {
      for (i = 0, len = data.length; i < len; i++) {
        item = data[i];
        count(item);
      }
    } else {
      count(data);
    }
    return stats;
  };

  return SearchStats;

})(SearchManager);
// Generated by CoffeeScript 1.12.7
var SearchFilter,
  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;

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

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

  SearchFilter.prototype.initOpts = function() {
    SearchFilter.__super__.initOpts.call(this);
    return this.addOpts({
      request: {
        mandatory: true,
        check: Request
      }
    });
  };

  SearchFilter.prototype.addToRequest = function(request) {
    request.merge(this._request);
    return console.debug("adding search filter to request", request, this._request);
  };

  return SearchFilter;

})(SearchManager);
// Generated by CoffeeScript 1.12.7
var SearchBasics,
  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;

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

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

  SearchBasics.prototype.initOpts = function() {
    SearchBasics.__super__.initOpts.call(this);
    return this.addOpts({
      search: {
        mandatory: true,
        check: Search
      }
    });
  };

  SearchBasics.prototype.readOpts = function() {
    SearchBasics.__super__.readOpts.call(this);
    return this.__searchBasics = null;
  };

  SearchBasics.prototype.init = function() {
    EventPoller.listen({
      filter: {
        type: ["OBJECT_INDEX", "OBJECT_DELETE", "OBJECT_INSERT"],
        schema: "USER"
      },
      instance: this,
      call: (function(_this) {
        return function(events) {
          var event, i, its_for_us, len;
          _this.__refresh = true;
          its_for_us = false;
          for (i = 0, len = events.length; i < len; i++) {
            event = events[i];
            if (event.session_self) {
              its_for_us = true;
              break;
            }
          }
          if (its_for_us) {
            return _this.__refreshTimeout = CUI.setTimeout({
              ms: 5000,
              call: function() {
                return _this.update();
              }
            });
          }
        };
      })(this)
    });
    this.__refresh = true;
    console.time("SearchBasis");
    return this.update().always((function(_this) {
      return function() {
        return console.timeEnd("SearchBasis");
      };
    })(this));
  };

  SearchBasics.prototype.getBasicRequest = function() {
    var deletedFilter, ot, ots, request, trashManager;
    ots = (function() {
      var i, len, ref, results;
      ref = this._search.getSearchObjecttypes(false);
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        ot = ref[i];
        results.push(ot.name());
      }
      return results;
    }).call(this);
    request = {
      type: "object",
      objecttypes: ots,
      search: [],
      format: "short",
      limit: 0,
      aggregations: {}
    };
    trashManager = this.getActiveTrashManager();
    if (trashManager) {
      request.include_deleted = true;
      if (trashManager.isOnlyDeleted()) {
        deletedFilter = {
          type: "in",
          bool: "must_not",
          fields: ["_latest_version_deleted_at"],
          "in": [null]
        };
        request.search.push(deletedFilter);
      }
    }
    return request;
  };

  SearchBasics.prototype.getActiveTrashManager = function() {
    var i, len, ref, sm;
    ref = this._search.getSearchManagers();
    for (i = 0, len = ref.length; i < len; i++) {
      sm = ref[i];
      if (sm instanceof TrashSearchManager && sm.isActive()) {
        return sm;
      }
    }
    return null;
  };

  SearchBasics.prototype.isTrashModeActive = function() {
    return this.getActiveTrashManager() !== null;
  };

  SearchBasics.prototype.update = function() {
    var aggs, data, dbInfo, dfr, fieldPrefix, i, k, len, ot, ref, ref1, request, type, unique_id_before, v;
    CUI.clearTimeout(this.__refreshTimeout);
    if (!this.__refresh && ez5.version("6") && !!this.__latestTrashFlag !== this.isTrashModeActive()) {
      this.__refresh = true;
    }
    if (!this.__refresh) {
      if (this.__refresh_promise) {
        return this.__refresh_promise;
      } else {
        return CUI.resolvedPromise();
      }
    }
    this.__refresh = false;
    this.__latestTrashFlag = this.isTrashModeActive();
    unique_id_before = (ref = this.__searchBasics) != null ? ref.unique_id : void 0;
    request = this.getBasicRequest();
    if (request.objecttypes.length === 0) {
      data = {
        aggregations: {
          _asset: {
            terms: [],
            count: 0
          },
          _mask: {
            terms: [],
            count: 0
          },
          _objecttype: {
            terms: [],
            count: 0
          },
          _tags: {
            terms: [],
            count: 0
          }
        }
      };
      if (ez5.version("6")) {
        data.aggregations._system_tags = {
          terms: [],
          count: 0
        };
      }
      this.setData(data);
      return CUI.resolvedPromise();
    }
    aggs = {
      _mask: {
        type: "term",
        limit: 100000,
        field: "_mask"
      },
      _objecttype: {
        type: "term",
        limit: 100000,
        field: "_objecttype"
      }
    };
    ref1 = this._search.getSearchObjecttypes(false);
    for (i = 0, len = ref1.length; i < len; i++) {
      ot = ref1[i];
      if (ot.hasTags()) {
        aggs._tags = {
          type: "term",
          field: "_tags._id",
          limit: 100000
        };
        break;
      }
    }
    if (ez5.version("6")) {
      aggs._system_tags = {
        type: "term",
        field: "_system_tags.system_tag",
        limit: 100000
      };
    }
    if (this._search.hasEASFields(false)) {
      type = ez5.version("6") ? "term" : "asset";
      fieldPrefix = ez5.version("6") ? "_linked._asset." : "";
      aggs._asset = {
        type: type,
        field: fieldPrefix + "class_extension",
        limit: 100000
      };
      if (ez5.version("5.45.0")) {
        aggs._asset_class_version_status = {
          type: type,
          field: fieldPrefix + "class_version_status",
          sort: "count",
          limit: 100000
        };
      }
    }
    for (k in aggs) {
      v = aggs[k];
      request.aggregations[k] = v;
    }
    dfr = new CUI.Deferred();
    dfr.always((function(_this) {
      return function() {
        return _this.__refresh_promise = null;
      };
    })(this));
    this.__dbInfo = null;
    dbInfo = new DbInfo();
    dbInfo.load().done((function(_this) {
      return function() {
        return _this.__dbInfo = dbInfo;
      };
    })(this)).always((function(_this) {
      return function() {
        return ez5.api.search({
          data: {
            debug: "SearchBasics.init"
          },
          json_data: request
        }).done(function(data) {
          _this.setData(data);
          if (unique_id_before && unique_id_before !== _this.__searchBasics.unique_id) {
            return _this._search.objecttypesUpdated(_this).done(function() {
              return dfr.resolve(data);
            }).fail(dfr.reject);
          } else {
            return dfr.resolve(data);
          }
        }).fail(dfr.reject);
      };
    })(this));
    this.__refresh_promise = dfr.promise();
    return dfr.promise();
  };

  SearchBasics.prototype.getDbInfo = function() {
    return this.__dbInfo;
  };

  SearchBasics.prototype.destroy = function() {
    CUI.Events.ignore({
      instance: this
    });
    this.__searchBasics = null;
    return SearchBasics.__super__.destroy.call(this);
  };

  SearchBasics.prototype.setEASClassOnResultContainer = function() {
    var has_eas, i, j, len, len1, mask, mn, ot, ots, rc, ref, user_selected;
    rc = this._search.getResultContainer();
    if (!rc || this.__searchBasics === null) {
      return;
    }
    this.__requireInit();
    has_eas = false;
    ots = this._search.getSearchObjecttypes(true);
    ref = this.getMaskNames();
    for (i = 0, len = ref.length; i < len; i++) {
      mn = ref[i];
      mask = ez5.mask.CURRENT._mask_instance_by_name[mn];
      user_selected = false;
      for (j = 0, len1 = ots.length; j < len1; j++) {
        ot = ots[j];
        if (ot.name() === mask.table.name()) {
          user_selected = true;
          break;
        }
      }
      if (user_selected && mask.hasStandardEASFields()) {
        has_eas = true;
        break;
      }
    }
    if (has_eas) {
      CUI.dom.addClass(rc, "ez5-search-has-mask-with-asset-browser");
      CUI.dom.removeClass(rc, "ez5-search-has-no-mask-with-asset-browser");
    } else {
      CUI.dom.addClass(rc, "ez5-search-has-no-mask-with-asset-browser");
      CUI.dom.removeClass(rc, "ez5-search-has-mask-with-asset-browser");
    }
    return this;
  };

  SearchBasics.prototype.setData = function(data) {
    var d, i, info, j, l, len, len1, len2, len3, len4, len5, match, n, o, p, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, sb, status, systemTag, t, tag, term, type, unique_id;
    sb = {
      objecttypes: [],
      masks: [],
      eas_types: {},
      eas_status: {},
      tags: {},
      count: data.count
    };
    d = data.aggregations;
    unique_id = [sb.count];
    ref = d._objecttype.terms;
    for (i = 0, len = ref.length; i < len; i++) {
      t = ref[i];
      sb.objecttypes.push({
        name: t.term,
        count: t.count
      });
      unique_id.push(t.term + t.count);
    }
    ref1 = d._mask.terms;
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      t = ref1[j];
      sb.masks.push({
        name: t.term,
        count: t.count
      });
      unique_id.push(t.term + t.count);
    }
    ref3 = ((ref2 = d._asset) != null ? ref2.terms : void 0) || [];
    for (l = 0, len2 = ref3.length; l < len2; l++) {
      t = ref3[l];
      match = t.term.match(/^(.*?)\.(.*)$/);
      if (!match) {
        console.warn("Received bad term, class.extension expected. Term:", t);
        continue;
      }
      info = [match[1], match[2]];
      if (!sb.eas_types[info[0]]) {
        sb.eas_types[info[0]] = [];
      }
      sb.eas_types[info[0]].push(info[1]);
    }
    ref5 = ((ref4 = d._asset_class_version_status) != null ? ref4.terms : void 0) || [];
    for (n = 0, len3 = ref5.length; n < len3; n++) {
      t = ref5[n];
      term = t.term.split(".");
      type = term[0];
      status = term[2];
      if (!sb.eas_status[status]) {
        sb.eas_status[status] = [];
      }
      if (sb.eas_status[status].indexOf(type) === -1) {
        sb.eas_status[status].push(type);
      }
    }
    ref7 = ((ref6 = d._tags) != null ? ref6.terms : void 0) || [];
    for (o = 0, len4 = ref7.length; o < len4; o++) {
      tag = ref7[o];
      sb.tags[tag.term] = tag.count;
    }
    if (ez5.version("6")) {
      sb.systemTags = {};
      ref9 = ((ref8 = d._system_tags) != null ? ref8.terms : void 0) || [];
      for (p = 0, len5 = ref9.length; p < len5; p++) {
        systemTag = ref9[p];
        sb.systemTags[systemTag.term] = systemTag.count;
      }
    }
    sb.unique_id = unique_id.join(";");
    this.__searchBasics = sb;
    this.setEASClassOnResultContainer();
    return this;
  };

  SearchBasics.prototype.__requireInit = function() {
    return CUI.util.assert(this.__searchBasics, "SearchBasics.__requireInit", "Search Basics not initialized yet.");
  };

  SearchBasics.prototype.getCount = function() {
    this.__requireInit();
    return this.__searchBasics.count;
  };

  SearchBasics.prototype.getMasks = function() {
    this.__requireInit();
    return this.__searchBasics.masks;
  };

  SearchBasics.prototype.getObjecttypes = function() {
    this.__requireInit();
    return this.__searchBasics.objecttypes;
  };

  SearchBasics.prototype.getMaskNames = function() {
    var i, len, m, ref, results;
    ref = this.getMasks();
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      m = ref[i];
      results.push(m.name);
    }
    return results;
  };

  SearchBasics.prototype.getObjecttypeNames = function() {
    var i, len, ot, ref, results;
    ref = this.getObjecttypes();
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      results.push(ot.name);
    }
    return results;
  };

  SearchBasics.prototype.getEASTypes = function() {
    this.__requireInit();
    return this.__searchBasics.eas_types;
  };

  SearchBasics.prototype.easEASStatus = function() {
    this.__requireInit();
    return this.__searchBasics.eas_status;
  };

  SearchBasics.prototype.getCountByTagId = function(idTag) {
    return this.__searchBasics.tags[idTag] || 0;
  };

  SearchBasics.prototype.getSystemTagNames = function() {
    return Object.keys(this.__searchBasics.systemTags);
  };

  return SearchBasics;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var FieldPopoverManager,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  FieldPopoverManager.prototype.initOpts = function() {
    FieldPopoverManager.__super__.initOpts.call(this);
    return this.addOpts({
      mode: {
        mandatory: true,
        check: ["sort", "expert"]
      },
      data: {
        mandatory: true,
        check: "PlainObject"
      },
      search: {
        mandatory: true,
        check: Search
      }
    });
  };

  FieldPopoverManager.prototype.setData = function(data1) {
    this.data = data1;
  };

  FieldPopoverManager.prototype.getObjecttypeNamesWithMasks = function() {
    return this.__ot_names_with_masks;
  };

  FieldPopoverManager.prototype.readOpts = function() {
    FieldPopoverManager.__super__.readOpts.call(this);
    this.mode = this._mode;
    this.setData(this._data);
    return this.init();
  };

  FieldPopoverManager.prototype.init = function() {
    var idx, j, k, len, len1, m, mask_names, ot, ref, ref1, ref2;
    this.otm = new ObjecttypeManager();
    mask_names = this.getMaskNames();
    this.__ot_names_with_masks = [];
    ref = this.getSearchObjecttypes();
    for (idx = j = 0, len = ref.length; j < len; idx = ++j) {
      ot = ref[idx];
      ref1 = ot.masks;
      for (k = 0, len1 = ref1.length; k < len1; k++) {
        m = ref1[k];
        if (ref2 = m.name(), indexOf.call(mask_names, ref2) >= 0) {
          this.otm.addMask(m);
          CUI.util.pushOntoArray(ot.name(), this.__ot_names_with_masks);
        }
      }
    }
    this.otm.initCommonFields(this.mode, false, function(f) {
      return !(f instanceof MaskSplitter);
    });
    return this;
  };

  FieldPopoverManager.prototype.objecttypeIsUserSelected = function(ot_names) {
    var _ot, j, len, ref, ref1;
    ref = this._search.getSearchObjecttypes(true);
    for (j = 0, len = ref.length; j < len; j++) {
      _ot = ref[j];
      if (ref1 = _ot.name(), indexOf.call(ot_names, ref1) >= 0) {
        return true;
      }
    }
    return false;
  };

  FieldPopoverManager.prototype.getMaskNames = function() {
    return this._search.getSearchBasics().getMaskNames();
  };

  FieldPopoverManager.prototype.getCurrentGroup = function() {
    return CUI.util.assert(false, (CUI.util.getObjectClass(this)) + ".getCurrentGroup needs implementation.");
  };

  FieldPopoverManager.prototype.fieldsUpdated = function() {};

  FieldPopoverManager.prototype.__getFilterInput = function() {
    if (!ez5.version("6")) {
      return null;
    }
    if (this.__filterInput) {
      return this.__filterInput;
    }
    if (!this.__filterData) {
      this.__filterData = {
        filter_text: ""
      };
    }
    this.__filterInput = new CUI.Input({
      "class": "ez5-quicksearch-input ez5-field-popover-manager-filter-input",
      name: "filter_text",
      data: this.__filterData,
      placeholder: $$("list.view.edit.tree.filter.placeholder"),
      maximize_horizontal: true,
      onDataChanged: (function(_this) {
        return function() {
          return CUI.scheduleCallback({
            ms: 400,
            call: _this.__applyFieldFilterBound
          });
        };
      })(this)
    });
    return this.__filterInput.start();
  };

  FieldPopoverManager.prototype.getContent = function() {
    var expandNestedDOM, filterTopContent, ref, vl;
    this.__statusLabel = new CUI.Label({
      "class": "ez5-field-popover-manager-status",
      text: $$("field.popover.manager.status.empty." + this.mode),
      multiline: true
    });
    this.all_div = CUI.dom.div("field-popover-manager-main");
    CUI.Events.listen({
      node: this.all_div,
      type: "search-input-change",
      call: (function(_this) {
        return function(ev) {
          return _this.fieldsUpdated();
        };
      })(this)
    });
    if (ez5.version("6")) {
      this.__applyFieldFilterBound = (function(_this) {
        return function() {
          return _this.__applyFieldFilter();
        };
      })(this);
      if (this.mode === "expert") {
        this.__expandNestedData = {
          expand_nested: false
        };
        this.__expandNestedCheckbox = new CUI.Checkbox({
          "class": "ez5-field-popover-manager-expand-nested",
          name: "expand_nested",
          data: this.__expandNestedData,
          text: $$("field.popover.manager.expand.nested"),
          tooltip: {
            text: $$("field.popover.manager.expand.nested|tooltip")
          },
          onDataChanged: (function(_this) {
            return function() {
              return _this.__applyFieldFilter();
            };
          })(this)
        });
      }
      filterTopContent = CUI.dom.div("ez5-field-popover-manager-filter-container");
      if (this.mode !== "expert") {
        filterTopContent.appendChild((ref = this.__getFilterInput()) != null ? ref.DOM : void 0);
      }
      if (this.__expandNestedCheckbox) {
        expandNestedDOM = this.__expandNestedCheckbox.start().DOM;
        CUI.dom.hideElement(expandNestedDOM);
        filterTopContent.appendChild(expandNestedDOM);
      }
    }
    vl = new CUI.VerticalLayout({
      "class": "ez5-field-popover-manager-content-layout",
      top: {
        content: filterTopContent
      },
      center: {
        content: this.all_div
      },
      bottom: {
        content: this.__statusLabel
      }
    });
    return vl;
  };

  FieldPopoverManager.prototype.__applyFieldFilter = function() {
    var expandNested, filterText, filteredFields, hasNestedByChildren, ref, renderFilterText;
    if (!this.__allFields) {
      return;
    }
    filterText = (this.__filterData.filter_text || "").toLowerCase().trim();
    if (!filterText) {
      this.__updateExpandNestedVisibility(false);
      this.__renderFields(this.__allFields).done((function(_this) {
        return function() {
          return _this.__afterFilterApplied();
        };
      })(this));
      return;
    }
    filteredFields = this.__getFilteredFields(this.__allFields, filterText);
    hasNestedByChildren = this.__hasNestedMatchedByChildren(filteredFields, filterText);
    this.__updateExpandNestedVisibility(hasNestedByChildren);
    expandNested = (ref = this.__expandNestedData) != null ? ref.expand_nested : void 0;
    renderFilterText = expandNested ? null : filterText;
    this.__renderFields(filteredFields, true, renderFilterText).done((function(_this) {
      return function() {
        return _this.__afterFilterApplied();
      };
    })(this));
  };

  FieldPopoverManager.prototype.__updateExpandNestedVisibility = function(visible) {
    if (!this.__expandNestedCheckbox) {
      return;
    }
    if (visible) {
      return CUI.dom.showElement(this.__expandNestedCheckbox);
    } else {
      return CUI.dom.hideElement(this.__expandNestedCheckbox);
    }
  };

  FieldPopoverManager.prototype.__hasNestedMatchedByChildren = function(fields, filterText) {
    var childField, childFields, field, j, k, len, len1, ownNameMatches;
    for (j = 0, len = fields.length; j < len; j++) {
      field = fields[j];
      if (field instanceof MaskSplitter) {
        continue;
      }
      if (!(field instanceof NestedTable)) {
        continue;
      }
      ownNameMatches = this.__fieldOwnNameMatches(field, filterText);
      if (ownNameMatches) {
        continue;
      }
      childFields = field.getFields(this.mode) || [];
      for (k = 0, len1 = childFields.length; k < len1; k++) {
        childField = childFields[k];
        if (childField instanceof MaskSplitter) {
          continue;
        }
        if (!this.__fieldMatchesFilter(childField, filterText)) {
          return true;
        }
      }
    }
    return false;
  };

  FieldPopoverManager.prototype.__fieldOwnNameMatches = function(field, filterText) {
    var name, parts;
    if (ez5.session.isDebug() && field.name) {
      name = field.name().toLowerCase();
      if (name.indexOf(":") >= 0) {
        parts = name.split(":");
        name = parts[parts.length - 1];
      }
      if (name.indexOf(filterText) >= 0) {
        return true;
      }
    }
    if (field.nameLocalized && field.nameLocalized().toLowerCase().indexOf(filterText) >= 0) {
      return true;
    }
    return false;
  };

  FieldPopoverManager.prototype.__afterFilterApplied = function() {};

  FieldPopoverManager.prototype.__getFilteredFields = function(fields, filterText) {
    var field, i, matchingFields, panelEnd, panelFields, panelStart, result;
    result = [];
    i = 0;
    while (i < fields.length) {
      field = fields[i];
      if (field instanceof MaskSplitterPanel) {
        panelStart = field;
        panelFields = [];
        i++;
        while (i < fields.length) {
          if (fields[i] instanceof MaskSplitterPanelEnd) {
            panelEnd = fields[i];
            i++;
            break;
          }
          panelFields.push(fields[i]);
          i++;
        }
        matchingFields = this.__filterFieldList(panelFields, filterText);
        if (matchingFields.length > 0) {
          result.push(panelStart);
          result = result.concat(matchingFields);
          result.push(panelEnd || new MaskSplitterPanelEnd());
        }
        continue;
      }
      if (field instanceof MaskSplitter) {
        i++;
        continue;
      }
      if (this.__fieldMatchesFilter(field, filterText)) {
        result.push(field);
      }
      i++;
    }
    return result;
  };

  FieldPopoverManager.prototype.__filterFieldList = function(fields, filterText) {
    var field, j, len, matching;
    matching = [];
    for (j = 0, len = fields.length; j < len; j++) {
      field = fields[j];
      if (field instanceof MaskSplitter) {
        continue;
      }
      if (this.__fieldMatchesFilter(field, filterText)) {
        matching.push(field);
      }
    }
    return matching;
  };

  FieldPopoverManager.prototype.__fieldMatchesFilter = function(field, filterText) {
    var childField, getInpternalPlainName, j, len, ref, ref1;
    getInpternalPlainName = function(field) {
      var fieldName, fieldNameParts;
      if (field.name().indexOf(":") >= 0) {
        fieldNameParts = field.name().split(":");
        fieldName = fieldNameParts[fieldNameParts.length - 1];
      } else {
        fieldName = field.name();
      }
      return fieldName;
    };
    if (ez5.session.isDebug() && field.name && ((ref = getInpternalPlainName(field)) != null ? ref.indexOf(filterText) : void 0) >= 0) {
      return true;
    }
    if (field.nameLocalized && field.nameLocalized().toLowerCase().indexOf(filterText) >= 0) {
      return true;
    }
    if (field instanceof NestedTable) {
      ref1 = field.getFields(this.mode) || [];
      for (j = 0, len = ref1.length; j < len; j++) {
        childField = ref1[j];
        if (childField instanceof MaskSplitter) {
          continue;
        }
        if (this.__fieldMatchesFilter(childField, filterText)) {
          return true;
        }
      }
    }
    return false;
  };

  FieldPopoverManager.prototype.getObjecttypes = function() {
    return this.otm.objecttypes;
  };

  FieldPopoverManager.prototype.getSearchObjecttypes = function() {
    return this._search.getSearchObjecttypes(false);
  };

  FieldPopoverManager.prototype.onPanelChanged = function() {};

  FieldPopoverManager.prototype.updateForm = function() {
    var _fields, add_field, add_fields, cf, commonFieldIds, commonFields, commonPanel, count, eas_fields, expandNested, f, fields, filterText, fn, fn1, group, has_real_group, hide_when_single_linked, idx, isFiltering, j, k, key_appendix, l, len, len1, len10, len2, len3, len4, len5, len6, len7, len8, len9, lot, mask, mask_names, n, o, ot, otName, ot_name, ot_names, ot_shown, other_fields, p, panel, panel_opened, q, r, ref, ref1, ref10, ref11, ref12, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, renderFilterText, s, sortByField, t, title_added, top_level_fields, txt, type, u;
    CUI.dom.empty(this.all_div);
    group = this.getCurrentGroup();
    if (this.getObjecttypes().length === 0 || !group) {
      return CUI.resolvedPromise();
    }
    sortByField = function(a, b) {
      var a_str, b_str;
      if (typeof a.isInPopoverTopLevel === "function" ? a.isInPopoverTopLevel() : void 0) {
        a_str = "_";
      } else {
        a_str = a.nameLocalized().toLocaleLowerCase();
      }
      if (typeof b.isInPopoverTopLevel === "function" ? b.isInPopoverTopLevel() : void 0) {
        b_str = "_";
      } else {
        b_str = b.nameLocalized().toLocaleLowerCase();
      }
      return CUI.util.compareIndex(a_str, b_str);
    };
    fields = [];
    panel_opened = false;
    add_fields = (function(_this) {
      return function(_fields, ot_name, panel_title) {
        var f, j, len, ref;
        if (_fields.length === 0) {
          return;
        }
        if (panel_opened) {
          fields.push(new MaskSplitterPanelEnd());
          panel_opened = false;
        }
        if (panel_title) {
          add_field(new MaskSplitterPanelFixed({
            text: panel_title,
            closed: true
          }), ot_name);
          panel_opened = true;
        }
        ref = _fields.sort(sortByField);
        for (j = 0, len = ref.length; j < len; j++) {
          f = ref[j];
          add_field(f, ot_name);
        }
      };
    })(this);
    add_field = (function(_this) {
      return function(f, ot_name) {
        var d;
        CUI.util.assert(f && ot_name, "FieldPopoverManager.updateForm[add_field]", "field, table and ot_name must be set", {
          field: f,
          ot_name: ot_name
        });
        fields.push(f);
        if (f instanceof MaskSplitter) {
          return;
        }
        f._ot_name = ot_name;
        if (!_this.data[ot_name]) {
          _this.data[ot_name] = {};
        }
        d = _this.data[ot_name][f.fullName()];
        if (!d) {
          d = _this.data[ot_name][f.fullName()] = {};
        }
        if (!d.field) {
          d.field = f;
          d._fields = {};
          d.data = d.data || {};
        }
      };
    })(this);
    mask_names = "";
    if (group === "_COMMONS") {
      key_appendix = ".multiple";
    } else {
      key_appendix = "";
    }
    txt = $$("field.popover.manager.status.label." + this.mode + key_appendix, {
      mask_names: mask_names
    });
    this.__statusLabel.setText(txt);
    if (group === "_COMMONS") {
      commonFields = this.otm.getCommonFieldsByLocaName((function(_this) {
        return function(ot, field, commonFields) {
          if (!_this.objecttypeIsUserSelected([ot.name()])) {
            return false;
          }
          if (!field.isExpertCommon(_this.mode)) {
            return false;
          }
          if (field instanceof TreeColumn) {
            return true;
          }
          if (!(commonFields != null ? commonFields[0] : void 0)) {
            return true;
          }
          if (CUI.util.getObjectClass(field) !== CUI.util.getObjectClass(commonFields[0])) {
            return false;
          }
          if (field instanceof LinkedObject) {
            if (field.linkMask().name() !== commonFields[0].linkMask().name()) {
              return false;
            }
          }
          return true;
        };
      })(this));
      _fields = [];
      for (fn in commonFields) {
        cf = commonFields[fn];
        f = new MultipleFieldsContainer(cf);
        _fields.push(f);
      }
      add_fields(_fields, "_COMMONS");
      if (this.mode === "expert") {
        _fields = [];
        eas_fields = this.otm.getEASFields("expert", (function(_this) {
          return function(ot) {
            return _this.objecttypeIsUserSelected([ot.name()]);
          };
        })(this));
        if (eas_fields.length) {
          f = new MultipleFieldsContainer(eas_fields);
          f.setNameLocalized($$("field.popover.manager.eas.label"));
          _fields.push(f);
        }
        ref = this.link_otm.objecttypes.sort(sortByField);
        for (idx = j = 0, len = ref.length; j < len; idx = ++j) {
          lot = ref[idx];
          ot_names = (function() {
            var results;
            results = [];
            for (ot_name in lot._objecttypes) {
              results.push(ot_name);
            }
            return results;
          })();
          if (!this.objecttypeIsUserSelected(ot_names) || ot_names.length === 1) {
            continue;
          }
          f = new MultipleFieldsContainer();
          for (k = 0, len1 = ot_names.length; k < len1; k++) {
            otName = ot_names[k];
            if (this.objecttypeIsUserSelected([otName])) {
              f.addLinkedObjecttype(lot, otName);
            }
          }
          _fields.push(f);
        }
        add_fields(_fields, "_COMMONS", $$("main.search.expert.linked_objects"));
      }
    } else if (group.startsWith("_")) {
      mask = ez5.mask.CURRENT._mask_instance_by_name[group.substr(1)];
      ref1 = mask.getFields(this.mode);
      for (l = 0, len2 = ref1.length; l < len2; l++) {
        f = ref1[l];
        add_field(f, group);
      }
      if (this.mode === "expert" && ez5.version("6")) {
        hide_when_single_linked = true;
        _fields = [];
        has_real_group = false;
        ref2 = this.link_otm.objecttypes;
        for (idx = n = 0, len3 = ref2.length; n < len3; idx = ++n) {
          lot = ref2[idx];
          f = new MultipleFieldsContainer();
          count = f.addLinkedObjecttype(lot, mask.table.name(), mask.name());
          if (!count) {
            continue;
          }
          if (count > 1) {
            has_real_group = true;
          }
          _fields.push(f);
        }
        if (!hide_when_single_linked || has_real_group) {
          add_fields(_fields, group, $$("main.search.expert.linked_objects"));
        }
      }
    } else {
      ot_shown = null;
      ref3 = this.getObjecttypes();
      for (o = 0, len4 = ref3.length; o < len4; o++) {
        ot = ref3[o];
        if (ot.name() !== group) {
          continue;
        }
        ot_shown = ot;
        _fields = [];
        ref4 = ot.commonFields.sort(sortByField);
        for (p = 0, len5 = ref4.length; p < len5; p++) {
          f = ref4[p];
          if (!f.isExpertCommonOnly(this.mode)) {
            continue;
          }
          _fields.push(f);
        }
        mask_names = (function() {
          var len6, q, ref5, results;
          ref5 = ot.commonFieldsMasks;
          results = [];
          for (q = 0, len6 = ref5.length; q < len6; q++) {
            mask = ref5[q];
            results.push(mask.nameLocalized());
          }
          return results;
        })();
        add_fields(_fields, ot.name());
        ref5 = ot.masks;
        for (q = 0, len6 = ref5.length; q < len6; q++) {
          mask = ref5[q];
          _fields = [];
          ref6 = mask.uniqueFields.sort(sortByField);
          for (r = 0, len7 = ref6.length; r < len7; r++) {
            f = ref6[r];
            if (!f.isExpertCommonOnly(this.mode)) {
              continue;
            }
            _fields.push(f);
          }
          add_fields(_fields, ot.name());
        }
      }
      fields.sort(sortByField);
      if (ot_shown && this.mode === "expert") {
        eas_fields = ot_shown.getEASFields(this.mode);
        title_added = null;
        _fields = [];
        if (eas_fields.length) {
          f = new MultipleFieldsContainer(eas_fields);
          f.setNameLocalized($$("field.popover.manager.eas.label"));
          _fields.push(f);
        }
        ref7 = this.link_otm.objecttypes;
        for (idx = s = 0, len8 = ref7.length; s < len8; idx = ++s) {
          lot = ref7[idx];
          f = new MultipleFieldsContainer();
          if (!f.addLinkedObjecttype(lot, ot_shown.name())) {
            continue;
          }
          _fields.push(f);
        }
        add_fields(_fields, ot_shown.name(), $$("main.search.expert.linked_objects"));
      }
    }
    if (panel_opened) {
      fields.push(new MaskSplitterPanelEnd());
    }
    top_level_fields = [];
    other_fields = [];
    for (t = 0, len9 = fields.length; t < len9; t++) {
      f = fields[t];
      if ((typeof f.isSystemField === "function" ? f.isSystemField() : void 0) || (typeof f.isTopLevelField === "function" ? f.isTopLevelField() : void 0)) {
        top_level_fields.push(f);
      } else {
        other_fields.push(f);
      }
    }
    fields = [];
    if (top_level_fields.length > 0) {
      panel = new MaskSplitterPanelFixed({
        text: $$("admin.mask.form.board"),
        closed: (ref8 = ez5.session.getPref("expert_search_top_level_fields_closed")) != null ? ref8 : false,
        render_fields_closed: true,
        onOpen: (function(_this) {
          return function() {
            _this.onPanelChanged();
            return ez5.session.savePref("expert_search_top_level_fields_closed", false);
          };
        })(this),
        onClose: (function(_this) {
          return function() {
            _this.onPanelChanged();
            return ez5.session.savePref("expert_search_top_level_fields_closed", true);
          };
        })(this)
      });
      fields.push(panel);
      fields = fields.concat(top_level_fields);
      fields.push(new MaskSplitterPanelEnd());
    }
    if (ez5.version("6") && this.mode === "sort" && commonFields) {
      commonPanel = new MaskSplitterPanelFixed({
        text: $$("sort.manager.field.popover.manager.common_fields"),
        closed: (ref9 = ez5.session.getPref("sort_manager_panel_common_fields_closed")) != null ? ref9 : false,
        render_fields_closed: true,
        onOpen: (function(_this) {
          return function() {
            _this.onPanelChanged();
            return ez5.session.savePref("sort_manager_panel_common_fields_closed", false);
          };
        })(this),
        onClose: (function(_this) {
          return function() {
            _this.onPanelChanged();
            return ez5.session.savePref("sort_manager_panel_common_fields_closed", true);
          };
        })(this)
      });
      fields.push(commonPanel);
      fields.push.apply(fields, other_fields);
      fields.push(new MaskSplitterPanelEnd());
      commonFieldIds = Object.values(commonFields).flat().map((function(_this) {
        return function(arg) {
          var ColumnSchema;
          ColumnSchema = arg.ColumnSchema;
          return ColumnSchema != null ? ColumnSchema.column_id : void 0;
        };
      })(this)).filter((function(_this) {
        return function(value) {
          return value !== void 0;
        };
      })(this));
      ref10 = this._search.getSearchObjecttypes();
      fn1 = (function(_this) {
        return function(type) {
          var field, len11, len12, ref11, ref12, ref13, uncommonFields, v, w;
          uncommonFields = [];
          ref11 = type.getAllFields();
          for (v = 0, len11 = ref11.length; v < len11; v++) {
            field = ref11[v];
            if (field.ColumnSchema && (ref12 = field.ColumnSchema.column_id, indexOf.call(commonFieldIds, ref12) < 0) && !field.ColumnSchema._in_nested) {
              uncommonFields.push(field);
            }
          }
          if (uncommonFields.length > 0) {
            panel = new MaskSplitterPanelFixed({
              text: type.nameLocalized(),
              closed: (ref13 = ez5.session.getPref("sort_manager_panel_" + (type.name()) + "_closed")) != null ? ref13 : true,
              render_fields_closed: true,
              onOpen: function() {
                _this.onPanelChanged();
                return ez5.session.savePref("sort_manager_panel_" + (type.name()) + "_closed", false);
              },
              onClose: function() {
                _this.onPanelChanged();
                return ez5.session.savePref("sort_manager_panel_" + (type.name()) + "_closed", true);
              }
            });
            fields.push(panel);
            for (w = 0, len12 = uncommonFields.length; w < len12; w++) {
              field = uncommonFields[w];
              add_field(field, "_COMMONS");
            }
            return fields.push(new MaskSplitterPanelEnd());
          }
        };
      })(this);
      for (u = 0, len10 = ref10.length; u < len10; u++) {
        type = ref10[u];
        fn1(type);
      }
    } else {
      fields = fields.concat(other_fields);
    }
    this.__allFields = fields;
    filterText = (((ref11 = this.__filterData) != null ? ref11.filter_text : void 0) || "").toLowerCase().trim();
    isFiltering = !!filterText;
    if (isFiltering) {
      fields = this.__getFilteredFields(fields, filterText);
    }
    expandNested = (ref12 = this.__expandNestedData) != null ? ref12.expand_nested : void 0;
    renderFilterText = isFiltering && !expandNested ? filterText : null;
    return this.__renderFields(fields, isFiltering, renderFilterText);
  };

  FieldPopoverManager.prototype.__renderFields = function(fields, openPanels, filterText) {
    var dfr, emptyLabel, mainDiv, opts, ref, ref1;
    if (openPanels == null) {
      openPanels = false;
    }
    if (filterText == null) {
      filterText = null;
    }
    CUI.dom.empty(this.all_div);
    if (!fields || fields.length === 0) {
      if ((ref = this.__filterData) != null ? (ref1 = ref.filter_text) != null ? ref1.trim() : void 0 : void 0) {
        emptyLabel = new CUI.EmptyLabel({
          centered: true,
          text: $$("field.popover.manager.filter.nothing_found")
        });
        CUI.dom.append(this.all_div, emptyLabel.DOM);
      }
      return CUI.resolvedPromise();
    }
    this.__mainFieldsRenderer = new FieldsRendererTopLevel();
    this.__mainFieldsRenderer.read(fields);
    opts = this.getRenderOpts();
    if (filterText) {
      opts.fieldFilterText = filterText;
    }
    dfr = new CUI.Deferred();
    opts.onFail = (function(_this) {
      return function() {
        return dfr.reject();
      };
    })(this);
    opts.onDone = (function(_this) {
      return function() {
        if (openPanels) {
          _this.__openAllPanels(_this.__mainFieldsRenderer);
        }
        return dfr.resolve();
      };
    })(this);
    mainDiv = this.__mainFieldsRenderer.render(opts);
    CUI.dom.addClass(mainDiv, "fields-renderer--root");
    CUI.dom.append(this.all_div, mainDiv);
    return dfr.promise();
  };

  FieldPopoverManager.prototype.focusFilterInput = function() {
    var ref;
    return (ref = this.__filterInput) != null ? ref.focus() : void 0;
  };

  FieldPopoverManager.prototype.clearFilter = function() {
    var ref, ref1;
    if (!this.__filterData || !this.__filterData.filter_text) {
      return;
    }
    if ((ref = this.__filterInput) != null) {
      ref.setValue("", {
        no_trigger: true
      });
    }
    if (this.__expandNestedData) {
      this.__expandNestedData.expand_nested = false;
      if ((ref1 = this.__expandNestedCheckbox) != null) {
        ref1.setValue(false, {
          no_trigger: true
        });
      }
    }
    return this.__applyFieldFilter();
  };

  FieldPopoverManager.prototype.__openAllPanels = function(renderer) {
    var field, j, len, ref;
    ref = (typeof renderer.getFields === "function" ? renderer.getFields() : void 0) || [];
    for (j = 0, len = ref.length; j < len; j++) {
      field = ref[j];
      if (field instanceof FieldsRendererPanel) {
        field.restoreState(true);
        this.__openAllPanels(field);
      } else if (field instanceof FieldsRenderer) {
        this.__openAllPanels(field);
      }
    }
  };

  FieldPopoverManager.prototype.getRenderOpts = function() {
    var opts;
    opts = {
      data: this.data,
      mode: this.mode,
      rowMove: false,
      maximize: false,
      search: this._search
    };
    return opts;
  };

  FieldPopoverManager.prototype.getFieldsRenderer = function() {
    return this.__mainFieldsRenderer;
  };

  FieldPopoverManager.getSaveData = function(data) {
    var _data, collectData, fieldData, fieldName, objecttype, saveData, value;
    saveData = {};
    collectData = function(value) {
      var _value, fieldData, j, key, len, val, values;
      if (CUI.util.isArray(value)) {
        values = [];
        for (j = 0, len = value.length; j < len; j++) {
          _value = value[j];
          val = collectData(_value);
          if (CUI.util.isEmpty(val)) {
            continue;
          }
          values.push(val);
        }
        return values;
      }
      if (CUI.util.isPlainObject(value)) {
        if (value._new) {
          return;
        }
        fieldData = {};
        for (key in value) {
          _value = value[key];
          if (key === "_DOM" || CUI.util.isEmpty(_value) || key.endsWith(":mode") || key.endsWith(":type")) {
            continue;
          }
          val = collectData(_value);
          if (CUI.util.isEmpty(val)) {
            continue;
          }
          if (val instanceof CUI.Element) {
            continue;
          }
          fieldData[key] = val;
        }
        return fieldData;
      } else {
        return value;
      }
    };
    for (objecttype in data) {
      _data = data[objecttype];
      saveData[objecttype] = {};
      for (fieldName in _data) {
        value = _data[fieldName];
        fieldData = collectData(value.data);
        if (CUI.util.isEmpty(fieldData)) {
          continue;
        }
        saveData[objecttype][fieldName] = {
          data: fieldData
        };
      }
    }
    if (CUI.util.isEmpty(saveData[objecttype])) {
      return saveData;
    }
    return saveData;
  };

  return FieldPopoverManager;

})(CUI.Element);

CUI.ready((function(_this) {
  return function() {
    return CUI.Events.registerEvent({
      type: "search-input-change",
      bubble: true
    });
  };
})(this));
// Generated by CoffeeScript 1.12.7
var SortManager,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  SortManager.prototype.readOpts = function() {
    SortManager.__super__.readOpts.call(this);
    this.__popover_rendered = null;
    if (this._pref) {
      this.loadSaveData(ez5.session.getPref(this._pref));
    } else {
      this.setData({});
    }
    this.button = new LocaButton({
      "class": "ez5-main-search-sort-button",
      icon: "fa-sort",
      ui: "sort.manager.open.button",
      loca_key: "main.search.sort.button",
      onClick: (function(_this) {
        return function() {
          return _this.openPopover();
        };
      })(this)
    });
    return this;
  };

  SortManager.prototype.initOpts = function() {
    SortManager.__super__.initOpts.call(this);
    this.addOpts({
      pref: {
        check: String
      }
    });
    return this;
  };

  SortManager.prototype.init = function() {
    SortManager.__super__.init.call(this);
    this.fieldPopoverManager = new SortManagerFieldPopoverManager({
      data: this.getData(),
      keys: this.keys,
      sortManager: this
    });
    this.getSearch().getButtonToolbar().append(this.button, "left");
    return this.initPopover().done((function(_this) {
      return function() {
        return _this.setButtonText();
      };
    })(this));
  };

  SortManager.prototype.getData = function() {
    return this.data;
  };

  SortManager.prototype.setData = function(data1) {
    var ref;
    this.data = data1;
    return (ref = this.fieldPopoverManager) != null ? ref.setData(this.data) : void 0;
  };

  SortManager.prototype.closePopover = function() {
    return this.popover.hide();
  };

  SortManager.prototype.openPopover = function() {
    return this.popover.show();
  };

  SortManager.prototype.__getRequest = function() {
    var req;
    req = this.addToRequest(req);
    return {
      fields: req.fields,
      sort: req.sort
    };
  };

  SortManager.prototype.initPopover = function() {
    var dfr;
    this.__popover_rendered = false;
    if (this.popover) {
      this.destroyPopover();
    }
    if (!this.fieldPopoverManager.getCurrentGroup()) {
      this.__popover_rendered = true;
      this.button.disable();
      return CUI.resolvedPromise();
    }
    dfr = new CUI.Deferred();
    dfr.done((function(_this) {
      return function() {
        return _this.__popover_rendered = true;
      };
    })(this));
    this.button.enable();
    this.popover = new CUI.Popover({
      element: this.button,
      backdrop: {
        policy: "click"
      },
      "class": "ez5-sort-manager-popover",
      placement: "s",
      placements: ["sw", "se", "s"],
      onShow: (function(_this) {
        return function() {
          _this.__current_sort_filter = JSON.stringify(_this.__getRequest());
          _this.__current_data = CUI.util.copyObject(_this.data, true);
          _this.__dataSaved = false;
          return _this.fieldPopoverManager.focusFilterInput();
        };
      })(this),
      onHide: (function(_this) {
        return function() {
          _this.fieldPopoverManager.clearFilter();
          _this.popover.disableAllButtons();
          _this.__savePopover().done(function() {
            _this.setButtonText();
            return _this.popover.enableAllButtons();
          });
        };
      })(this),
      pane: {
        header_left: (function(_this) {
          return function() {
            return new CUI.Label({
              text: $$("main.search.sort.title")
            });
          };
        })(this),
        header_right: (function(_this) {
          return function() {
            return new CUI.Label({
              text: _this.fieldPopoverManager.getCurrentGroupLocalized()
            });
          };
        })(this),
        content: (function(_this) {
          return function() {
            var content;
            content = _this.fieldPopoverManager.getContent();
            _this.fieldPopoverManager.updateForm().done(function() {
              _this.updateState();
              return dfr.resolve();
            });
            return content;
          };
        })(this)
      }
    });
    return dfr.promise();
  };

  SortManager.prototype.__savePopover = function() {
    var dfr;
    dfr = new CUI.Deferred();
    if (this.__current_sort_filter !== JSON.stringify(this.__getRequest())) {
      ez5.session.savePref(this._pref, this.getSaveData());
      this.getSearch().execute().always(dfr.resolve);
    } else {
      dfr.resolve();
    }
    return dfr.promise();
  };

  SortManager.prototype.loadSaveData = function(sd) {
    var data, fn, ginfo, group, i, info, key, len, ref;
    if (!sd) {
      this.setData({});
      return;
    }
    data = {};
    for (group in sd) {
      ginfo = sd[group];
      data[group] = {};
      for (fn in ginfo) {
        info = ginfo[fn];
        data[group][fn] = {
          _order: info.order,
          _extra: info.extra
        };
        ref = this.keys;
        for (i = 0, len = ref.length; i < len; i++) {
          key = ref[i];
          data[group][fn][key] = key === info.key;
        }
      }
    }
    this.setData(data);
    return data;
  };

  SortManager.prototype.getSaveData = function() {
    var fn, ginfo, group, i, info, key, len, ref, ref1, sd, store;
    sd = {};
    ref = this.data;
    for (group in ref) {
      ginfo = ref[group];
      for (fn in ginfo) {
        info = ginfo[fn];
        store = false;
        ref1 = this.keys;
        for (i = 0, len = ref1.length; i < len; i++) {
          key = ref1[i];
          if (info[key]) {
            store = true;
            break;
          }
        }
        if (store) {
          if (!sd[group]) {
            sd[group] = {};
          }
          sd[group][fn] = {
            key: key,
            order: info._order,
            extra: info._extra
          };
        }
      }
    }
    return sd;
  };

  SortManager.prototype.objecttypesUpdated = function() {
    var ret;
    console.debug("objecttypes updated SortManager...", "search init:", this.getSearch().isInitialized(), "popover:", this.__popover_rendered);
    this.fieldPopoverManager.init();
    ret = this.initPopover();
    ret.done((function(_this) {
      return function() {
        var active, key, value;
        active = _this.getActiveFields();
        for (key in active) {
          value = active[key];
          if (!CUI.util.isArray(value)) {
            continue;
          }
          if (value.length <= 1 || !value[0].field) {
            continue;
          }
          _this.updateState(value[0].field, key);
        }
        _this.setButtonText();
      };
    })(this));
    return ret;
  };

  SortManager.prototype.destroy = function() {
    this.destroyPopover();
    return SortManager.__super__.destroy.call(this);
  };

  SortManager.prototype.destroyPopover = function() {
    if (this.popover) {
      this.popover.destroy();
      this.popover = null;
    }
    return this;
  };

  SortManager.prototype.setButtonText = function() {
    var active, f, i, key, len, ref, text;
    active = this.getActiveFields();
    text = [];
    ref = this.keys;
    for (i = 0, len = ref.length; i < len; i++) {
      key = ref[i];
      if (active && (f = active[key])) {
        text.push(f[0].field.nameLocalized());
      }
    }
    if (!text.length) {
      text.push($$(this.getSearch().getDefaultSortKey()));
    }
    return this.button.setText($$("main.search.sort.button|text") + ": " + text.join(", "));
  };

  SortManager.prototype.addToRequest = function(request) {
    var active, add_sort_filter, i, key, len, level, ref, req_fields, sort_filter;
    if (request == null) {
      request = {};
    }
    CUI.util.assert(this.__popover_rendered, "SortManager.addToRequest", "Unable to addToRequest while popover is being initialized.");
    active = this.getActiveFields();
    if (this.getSearch().getSearchObjecttypes().length === 0) {
      return request;
    }
    sort_filter = [];
    req_fields = [];
    request.sort_keys = {};
    level = 0;
    add_sort_filter = (function(_this) {
      return function(activeFilters, key) {
        var _name, filter, fn, fn_copy, gf, gm, groupable, has_gf, i, incrementLevel, j, k, key_suffix, len, len1, len2, name, names, sort, use_names, wp;
        filter = activeFilters[key][0];
        filter._key = key;
        groupable = filter.field.isSortGroupable(filter);
        if (groupable) {
          request.sort_keys[key] = filter;
        }
        names = filter.field.getSortFields(filter, _this.keys, activeFilters);
        if (!CUI.util.isArray(names)) {
          names = [names];
        }
        use_names = [];
        for (i = 0, len = names.length; i < len; i++) {
          name = names[i];
          if (CUI.util.isEmpty(name)) {
            continue;
          }
          if (CUI.util.isArray(name)) {
            for (j = 0, len1 = name.length; j < len1; j++) {
              _name = name[j];
              if (CUI.util.isPlainObject(_name)) {
                _name._level = level;
                level++;
              }
              use_names.push(_name);
            }
          } else {
            if (CUI.util.isPlainObject(name)) {
              name._level = level;
              level++;
            }
            use_names.push(name);
          }
        }
        if (use_names.length === 0) {
          return;
        }
        has_gf = false;
        incrementLevel = false;
        for (k = 0, len2 = use_names.length; k < len2; k++) {
          fn = use_names[k];
          if (CUI.util.isPlainObject(fn)) {
            if (fn.field) {
              fn_copy = CUI.util.copyObject(fn);
              delete fn_copy.group_field;
              delete fn_copy.group_mode;
              sort_filter.push(fn_copy);
            }
            key_suffix = fn.group_key_suffix || "";
            gf = fn.group_field;
            gm = fn.group_mode;
            wp = fn.with_path;
          } else {
            incrementLevel = true;
            sort = {
              field: fn,
              order: filter._order,
              _level: level
            };
            sort_filter.push(sort);
            gf = fn;
            key_suffix = "";
            gm = void 0;
            wp = void 0;
          }
          if (groupable && gf) {
            has_gf = true;
            req_fields.push({
              key: key + key_suffix,
              field: gf,
              with_path: wp,
              mode: gm
            });
          }
        }
        if (incrementLevel) {
          level++;
        }
        return CUI.util.assert(!groupable || has_gf, "SortManager.addToRequest", "Group field not found for groupable Field", {
          field: _this,
          filter: use_names
        });
      };
    })(this);
    ref = this.keys;
    for (i = 0, len = ref.length; i < len; i++) {
      key = ref[i];
      if (active[key]) {
        add_sort_filter(active, key);
      }
    }
    if (sort_filter.length === 0) {
      request.sort = this.getSearch().getDefaultSortFilter();
    } else {
      request.sort = sort_filter;
    }
    if (req_fields.length) {
      request.fields = req_fields;
    }
    if (ez5.version("6.12")) {
      request.timezone = CUI.Timezone.getTimezone();
    }
    return request;
  };

  SortManager.prototype.keys = ["_1", "_2", "_3"];

  SortManager.prototype.getActiveFields = function() {
    var active, f, field, fields, fn, group, i, j, key, len, len1, objectTypeNotSelected, objecttypes, ref, ref1, ref2, ref3;
    objecttypes = this.getSearch().getSearchObjecttypes().map((function(_this) {
      return function(ot) {
        return ot.name();
      };
    })(this));
    group = this.fieldPopoverManager.getCurrentGroup();
    active = {};
    ref = this.data[group];
    for (fn in ref) {
      f = ref[fn];
      ref1 = this.keys;
      for (i = 0, len = ref1.length; i < len; i++) {
        key = ref1[i];
        if (!f[key]) {
          continue;
        }
        fields = (ref2 = f.field) != null ? ref2.fields : void 0;
        if (group === "_COMMONS" && fields) {
          objectTypeNotSelected = false;
          for (j = 0, len1 = fields.length; j < len1; j++) {
            field = fields[j];
            if (field && !field.isTopLevelField() && (ref3 = field.table.name(), indexOf.call(objecttypes, ref3) < 0)) {
              objectTypeNotSelected = true;
              break;
            }
          }
          if (objectTypeNotSelected) {
            continue;
          }
        }
        if (!active[key]) {
          active[key] = [];
        }
        active[key].push(f);
        if (!active[fn]) {
          active[fn] = {};
        }
        active[fn][key] = f;
      }
    }
    return active;
  };

  SortManager.prototype.updateState = function(field, key) {
    var __key, _f, _fn, _key, active, fn, group, i, j, k, l, len, len1, len2, len3, ref, ref1, ref2, ref3, ref4, ref5, sels, vis;
    active = this.getActiveFields();
    group = this.fieldPopoverManager.getCurrentGroup();
    if (field && key) {
      fn = field.fullName();
      ref = this.keys;
      for (i = 0, len = ref.length; i < len; i++) {
        __key = ref[i];
        if (active[__key]) {
          ref1 = active[__key];
          for (j = 0, len1 = ref1.length; j < len1; j++) {
            _f = ref1[j];
            if (_f.field.fullName() !== fn) {
              if (_f != null) {
                if ((ref2 = _f._fields[key]) != null) {
                  ref2.setValue(false);
                }
              }
            }
          }
        }
        ref3 = this.keys;
        for (k = 0, len2 = ref3.length; k < len2; k++) {
          _key = ref3[k];
          if (_key === key) {
            continue;
          }
          if (active[fn] && active[fn][_key]) {
            active[fn][_key]._fields[_key].setValue(false);
          }
        }
      }
      active = this.getActiveFields();
    }
    ref4 = this.data[group];
    for (_fn in ref4) {
      _f = ref4[_fn];
      if (!_f._fields) {
        delete this.data[group][_fn];
        continue;
      }
      vis = "hide";
      ref5 = this.keys;
      for (l = 0, len3 = ref5.length; l < len3; l++) {
        _key = ref5[l];
        if (active[_fn]) {
          vis = "show";
        }
      }
      sels = [_f._fields._order, _f._fields._extra];
      if (!sels[0]) {
        continue;
      }
      sels[0][vis]();
      if (sels[1]) {
        sels[1][vis]();
      }
    }
  };

  return SortManager;

})(SearchManager);
// Generated by CoffeeScript 1.12.7
var SortManagerPlain,
  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;

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

  function SortManagerPlain() {
    this.setSearch = bind(this.setSearch, this);
    return SortManagerPlain.__super__.constructor.apply(this, arguments);
  }

  SortManagerPlain.prototype.setSearch = function(_search) {
    this._search = _search;
  };

  SortManagerPlain.prototype.addToRequest = function(request) {
    var sort_filter;
    sort_filter = [];
    sort_filter.push({
      field: "_system_object_id",
      order: "DESC"
    });
    request.sort = sort_filter;
  };

  return SortManagerPlain;

})(SearchManager);
// Generated by CoffeeScript 1.12.7
var SortManagerStandard,
  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;

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

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

  SortManagerStandard.prototype.setSearch = function(_search) {
    this._search = _search;
  };

  SortManagerStandard.prototype.init = function() {};

  SortManagerStandard.prototype.addToRequest = function(request) {
    var sort_filter;
    sort_filter = [];
    sort_filter.push({
      field: "_standard.1.text",
      order: "ASC"
    });
    request.sort = sort_filter;
  };

  return SortManagerStandard;

})(SortManager);
// Generated by CoffeeScript 1.12.7
var SortManagerFieldPopoverManager,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  SortManagerFieldPopoverManager.prototype.initOpts = function() {
    SortManagerFieldPopoverManager.__super__.initOpts.call(this);
    return this.addOpts({
      keys: {
        check: Array
      },
      sortManager: {
        check: SortManager
      }
    });
  };

  SortManagerFieldPopoverManager.prototype.readOpts = function() {
    var ref;
    this.opts.mode = "sort";
    this.opts.search = (ref = this.opts.sortManager) != null ? ref.getSearch() : void 0;
    return SortManagerFieldPopoverManager.__super__.readOpts.call(this);
  };

  SortManagerFieldPopoverManager.prototype.getRenderOpts = function() {
    var cls, fields, i, j, k, key, lbl, len, len1, opts, ref;
    opts = SortManagerFieldPopoverManager.__super__.getRenderOpts.call(this);
    opts.sortManager = this._sortManager;
    opts.sortManagerKeys = this._keys;
    opts.body_header = CUI.dom.element("DIV", {
      "class": "ez5-sort-manager-header"
    });
    fields = ["field"];
    ref = this._keys;
    for (i = 0, len = ref.length; i < len; i++) {
      key = ref[i];
      fields.push("order" + key);
    }
    fields.push("direction", "extra");
    for (j = 0, len1 = fields.length; j < len1; j++) {
      k = fields[j];
      cls = "ez5-sort-manager-header-column-" + k;
      lbl = new CUI.Label({
        "class": cls,
        text: $$("sort.manager.field.popover.manager.header." + k)
      });
      opts.body_header.appendChild(lbl.DOM);
    }
    return opts;
  };

  SortManagerFieldPopoverManager.prototype.__wrapPanelsInSortBody = function() {
    var panels, rendererBody, sortBody;
    rendererBody = CUI.dom.findElement(this.all_div, ".fields-renderer-body");
    if (!rendererBody) {
      return;
    }
    sortBody = CUI.dom.findElement(this.all_div, ".fields-renderer-body > .ez5-sort-manager-body") || CUI.dom.div("ez5-sort-manager-body");
    panels = CUI.dom.findElements(rendererBody, ".ez5-fields-renderer-panel");
    if (panels) {
      CUI.dom.prepend(sortBody, panels.reverse());
    }
    return CUI.dom.append(rendererBody, sortBody);
  };

  SortManagerFieldPopoverManager.prototype.__renderFields = function(fields, openPanels, filterText) {
    var promise;
    if (openPanels == null) {
      openPanels = false;
    }
    if (filterText == null) {
      filterText = null;
    }
    promise = SortManagerFieldPopoverManager.__super__.__renderFields.call(this, fields, openPanels, filterText);
    this.__wrapPanelsInSortBody();
    return promise;
  };

  SortManagerFieldPopoverManager.prototype.__afterFilterApplied = function() {
    return this._sortManager.updateState();
  };

  SortManagerFieldPopoverManager.prototype.onPanelChanged = function() {
    return this._sortManager.updateState();
  };

  SortManagerFieldPopoverManager.prototype.getCurrentGroup = function() {
    var i, len, ot, ot_names, ref, ref1;
    ot_names = [];
    ref = this._search.getSearchObjecttypes();
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      if (ref1 = ot.name(), indexOf.call(this.getObjecttypeNamesWithMasks(), ref1) >= 0) {
        ot_names.push(ot.name());
      }
    }
    if (ot_names.length === 0) {
      return null;
    } else if (ot_names.length === 1) {
      return ot_names[0];
    } else {
      return "_COMMONS";
    }
  };

  SortManagerFieldPopoverManager.prototype.getCurrentGroupLocalized = function() {
    var group;
    group = this.getCurrentGroup();
    switch (group) {
      case "_COMMONS":
        return $$("sort.manager.field.popover.manager.title.common");
      case null:
        return "";
      default:
        return ez5.schema.CURRENT._objecttype_by_name[group]._name_localized;
    }
  };

  return SortManagerFieldPopoverManager;

})(FieldPopoverManager);
// Generated by CoffeeScript 1.12.7
var SearchHierarchyManager,
  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;

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

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

  SearchHierarchyManager.prototype.initOpts = function() {
    SearchHierarchyManager.__super__.initOpts.call(this);
    return this.addOpts({
      container: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isElement(v);
        }
      },
      searchInput: {
        check: SearchInput
      },
      savePrefName: {
        check: String
      }
    });
  };

  SearchHierarchyManager.prototype.readOpts = function() {
    SearchHierarchyManager.__super__.readOpts.call(this);
    this.__layout = new CUI.PaneToolbar({
      "class": "ez5-search-hierarchy-manager",
      left: {}
    });
    this.__expandHierarchyMode = {
      mode: "top_level_without_search"
    };
    this.__loadPref();
    this.__filterTopLevel = true;
    this.button = new CUI.Select({
      "class": "ez5-main-search-expand-hierarchy-button",
      tooltip: {
        text: $$("search.hierarchy.manager.mode|tooltip")
      },
      data: this.__expandHierarchyMode,
      name: "mode",
      options: (function(_this) {
        return function() {
          var i, len, option, options, ref;
          options = [];
          ref = ["top_level_without_search", "top_level", "flat"];
          for (i = 0, len = ref.length; i < len; i++) {
            option = ref[i];
            options.push({
              value: option,
              text: $$("search.hierarchy.manager.mode." + option)
            });
          }
          return options;
        };
      })(this),
      onDataChanged: (function(_this) {
        return function(ev) {
          _this.__savePref();
          return _this.getSearch().execute();
        };
      })(this)
    }).start();
    return this.filter = [];
  };

  SearchHierarchyManager.prototype.init = function() {
    var ref, ref1, ref2;
    SearchHierarchyManager.__super__.init.call(this);
    if (!this.getSearch().isTrashModeActive()) {
      return (ref = this.getSearch()) != null ? (ref1 = ref.getButtonToolbar()) != null ? (ref2 = ref1.getButtonbar("left")) != null ? ref2.append(this.button) : void 0 : void 0 : void 0;
    }
  };

  SearchHierarchyManager.prototype.emptyRequest = function() {
    SearchHierarchyManager.__super__.emptyRequest.call(this);
    this.filter = [];
    return this;
  };

  SearchHierarchyManager.prototype.addFilter = function(result_object) {
    CUI.util.assert(result_object instanceof ResultObject, "SearchHierarchyManager.addFilter", "Parameter needs to be instanceof ResultObject.", {
      parm: result_object
    });
    this.filter.push({
      result_object: result_object
    });
    return this;
  };

  SearchHierarchyManager.prototype.hideExpandButton = function() {
    this.button.hide();
    this.__expandHierarchyMode.mode = "top_level_without_search";
  };

  SearchHierarchyManager.prototype.showExpandButton = function() {
    this.__loadPref();
    this.button.show();
  };

  SearchHierarchyManager.prototype.__checkExpandHierarchyButton = function(request) {
    var i, j, len, len1, ot, ref, ref1, show, sm;
    show = false;
    ref = this.getSearch().getSearchObjecttypes(true);
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      if (ot.isHierarchy() || ot.isPolyhierarchy()) {
        show = true;
        break;
      }
    }
    if (!show) {
      this.hideExpandButton();
      return;
    }
    ref1 = this.getSearch().getSearchManagers();
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      sm = ref1[j];
      if (!sm.allowExpandHierarchy) {
        continue;
      }
      if (!sm.allowExpandHierarchy(request)) {
        show = false;
        this.hideExpandButton();
      } else {
        this.showExpandButton();
      }
    }
    return show;
  };

  SearchHierarchyManager.prototype.__savePref = function() {
    if (this._savePrefName) {
      ez5.session.savePref(this._savePrefName, this.__expandHierarchyMode.mode);
    }
  };

  SearchHierarchyManager.prototype.__loadPref = function() {
    var selectorValue;
    if (this._savePrefName) {
      selectorValue = ez5.session.getPref(this._savePrefName);
      if (selectorValue) {
        this.__expandHierarchyMode.mode = selectorValue;
      }
    }
  };

  SearchHierarchyManager.prototype.__savePref = function() {
    if (this._savePrefName) {
      ez5.session.savePref(this._savePrefName, this.__expandHierarchyMode.mode);
    }
  };

  SearchHierarchyManager.prototype.__loadPref = function() {
    var selectorValue;
    if (this._savePrefName) {
      selectorValue = ez5.session.getPref(this._savePrefName);
      if (selectorValue) {
        this.__expandHierarchyMode.mode = selectorValue;
      }
    }
  };

  SearchHierarchyManager.prototype.addToResultDiv = function(request, result_object, div) {
    var browser, hierarchy_open_button;
    if (request.ignore_hierarchy) {
      return;
    }
    if (result_object.hasChildren()) {
      CUI.dom.addClass(div, "ez5-has-hierarchy-open-button");
      hierarchy_open_button = new LocaButton({
        "class": "ez5-button-hierarchy-open",
        loca_key: "search.hierarchy.manager.button.dive",
        appearance: "transparent-border",
        size: "normal",
        icon: "right",
        onClick: (function(_this) {
          return function(ev) {
            _this.filter.push({
              result_object: result_object,
              offset: request.offset || 0,
              query: _this._searchInput.storeQuery()
            });
            return _this.getSearch().execute();
          };
        })(this)
      }).DOM;
      if (CUI.dom.getAttribute(div, "render-type") === "text") {
        CUI.dom.append(div, hierarchy_open_button);
      } else {
        browser = div.querySelector('.ez5-result-card-asset');
        if (browser) {
          browser.appendChild(hierarchy_open_button);
        } else {
          CUI.dom.append(div, hierarchy_open_button);
        }
      }
    }
  };

  SearchHierarchyManager.prototype.isActive = function() {
    return this.filter.length > 0;
  };

  SearchHierarchyManager.prototype.isTrashModeActive = function() {
    return this.getSearch().isTrashModeActive();
  };

  SearchHierarchyManager.prototype.isFlatHierarchy = function() {
    return this.__expandHierarchyMode.mode === "flat";
  };

  SearchHierarchyManager.prototype.addToRequest = function(request) {
    var fieldName, filter, filterTopLevel, i, isPolyHierarchy, len, ot, ot_name, ots, ref, ref1, ref2, showFilter, values;
    if (request.ignore_hierarchy) {
      return;
    }
    if (!request.force_flat_hierarchy && this.getSearch().isTrashModeActive()) {
      request.force_flat_hierarchy = true;
    }
    ots = [];
    ref = this.getSearch().getSearchObjecttypes();
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      if (!ot.isHierarchy()) {
        continue;
      }
      ots.push(ot);
    }
    if (ots.length === 0) {
      delete request.hierarchy_filter_value;
    }
    if (this.filter.length > 0) {
      filter = this.filter[this.filter.length - 1];
    } else {
      filter = null;
    }
    if (filter) {
      request.hierarchy_filter_value = filter.result_object.id();
      ot_name = filter.result_object.objecttype();
    } else {
      request.hierarchy_filter_value = null;
    }
    if (filter) {
      isPolyHierarchy = filter.result_object.mask.isPolyhierarchy();
      if (request.show_hierarchy) {
        if (isPolyHierarchy) {
          fieldName = ot_name + "._parents." + ot_name + "._id";
        } else {
          fieldName = "_path." + ot_name + "._id";
        }
        request.search.push({
          type: "complex",
          bool: "must",
          search: [
            {
              type: "in",
              bool: "must",
              fields: [fieldName],
              "in": [request.hierarchy_filter_value]
            }, {
              type: "in",
              bool: "must_not",
              fields: [ot_name + "._id"],
              "in": [request.hierarchy_filter_value]
            }
          ]
        });
      } else {
        if (isPolyHierarchy) {
          fieldName = ot_name + "._parents." + ot_name + "._id";
          values = [request.hierarchy_filter_value, 0];
        } else {
          fieldName = ot_name + "._id_parent";
          values = [request.hierarchy_filter_value];
        }
        request.search.push({
          type: "in",
          bool: "must",
          fields: [fieldName],
          "in": values
        });
      }
    } else {
      showFilter = this.__checkExpandHierarchyButton(request);
      filterTopLevel = (ref1 = this.__expandHierarchyMode.mode) === "top_level_without_search" || ref1 === "top_level";
      if (showFilter) {
        request.show_hierarchy = !filterTopLevel;
      } else {
        if (request.show_hierarchy != null) {
          delete request.show_hierarchy;
        }
      }
      if (filterTopLevel && !request.force_flat_hierarchy) {
        if (this.getExpandHierarchyMode() === "top_level_without_search" && ((ref2 = this.getSearch()) != null ? ref2.hasUserInput(request) : void 0)) {
          return this;
        }
        SearchHierarchyManager.addTopLevelFilter(this.getSearch(), request);
      }
    }
    return this;
  };

  SearchHierarchyManager.prototype.getExpandHierarchyMode = function() {
    return this.__expandHierarchyMode.mode;
  };

  SearchHierarchyManager.addTopLevelFilter = function(search, request) {
    var fieldName, i, inOpt, len, ot, ref;
    if (request.for_export) {
      return this;
    }

    /*
    		filter_top = true
    
    		for sm in search.getSearchManagers()
    			if not sm.filterTopLevel
    				continue
    
    			if sm.filterTopLevel(request) != true
    				filter_top = false
    				break
    
    		if not filter_top
    			return @
     */
    ref = search.getSearchObjecttypes(true);
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      if (!ot.isHierarchy() && !ot.isPolyhierarchy()) {
        continue;
      }
      if (!request.search) {
        request.search = [];
      }
      if (!request.show_hierarchy) {
        if (ot.isHierarchy()) {
          fieldName = (ot.name()) + "._id_parent";
        } else if (ot.isPolyhierarchy()) {
          fieldName = (ot.name()) + "._parents." + (ot.name()) + "._id";
        }
        inOpt = ez5.version("6.12") ? [null, "0"] : [null];
        request.search.push({
          type: "in",
          bool: "must",
          fields: [fieldName],
          "in": inOpt
        });
      }
    }
    return this;
  };

  SearchHierarchyManager.prototype.showResult = function(request, data) {
    var div, emptyResult, fn, i, idx, len, pathElement, ref, ref1, ro, updateViewportLayout, update_search;
    if ((data != null ? data.count : void 0) === 0) {
      emptyResult = true;
    }
    updateViewportLayout = (function(_this) {
      return function() {
        return CUI.Events.trigger({
          node: _this._container,
          type: "content-resize"
        });
      };
    })(this);
    if (!request.hierarchy_filter_value) {
      CUI.dom.remove(this.__layout.DOM);
      updateViewportLayout();
      return;
    }
    this.__layout.empty("left");
    this.__layout.empty("center");
    CUI.dom.append(this._container, this.__layout);
    if (this.filter.length === 0) {
      this.__layout.append(new LocaLabel({
        loca_key: "base.top_hierarchy_level"
      }), "center");
      updateViewportLayout();
      return;
    }
    update_search = (function(_this) {
      return function(ev) {
        var filter, offset;
        filter = _this.filter.pop();
        if (filter.query) {
          _this._searchInput.restoreQuery(filter.query);
        }
        offset = filter.offset || 0;
        return _this.getSearch().execute(new Request({
          offset: offset
        })).done(function() {
          var div, i, len, rc, ref, result_object_divs;
          rc = _this.getSearch().getResultContainer();
          result_object_divs = CUI.dom.matchSelector(rc, "[global-object-id=\"" + (filter.result_object.getGlobalObjectId()) + "\"]");
          for (i = 0, len = result_object_divs.length; i < len; i++) {
            div = result_object_divs[i];
            div.scrollIntoView();
          }
          if ((ref = CUI.dom.data(CUI.dom.matchSelector(rc, "[result-dynamic-loading]")[0], "loader")) != null) {
            ref.markLoadMe();
          }
        });
      };
    })(this);
    div = CUI.dom.div("ez5-search-hierarchy-manager-path");
    ref = this.filter;
    fn = (function(_this) {
      return function(idx) {
        return CUI.dom.append(pathElement, new LocaButton({
          loca_key: "search.hierarchy.manager.remove_filter",
          onClick: function(ev) {
            console.debug("remove filter at idx", idx);
            _this.filter = _this.filter.slice(0, idx + 1);
            return update_search(ev);
          }
        }));
      };
    })(this);
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      ro = ref[idx];
      data = ro.result_object.data;
      pathElement = CUI.dom.div("ez5-path-element");
      CUI.dom.append(pathElement, (new ResultObject()).setData(data).renderCardHierarchy({
        path: false
      }));
      fn(idx);
      CUI.dom.append(div, pathElement);
    }
    this.__layout.append(div, "center");
    if (emptyResult) {
      if ((ref1 = this.getSearch()) != null) {
        ref1.setEmptyResultTextLocaKey("ez5.object.no_result_or_not_allowed");
      }
    }
    updateViewportLayout();
    return this;
  };

  return SearchHierarchyManager;

})(SearchManager);
// Generated by CoffeeScript 1.12.7
var SearchListHierarchyManager,
  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;

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

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

  SearchListHierarchyManager.prototype.addToResultDiv = function(request, result_object, div) {
    var resultManager;
    resultManager = this._search.getSearchManagers().find((function(_this) {
      return function(m) {
        return m instanceof ResultManager;
      };
    })(this));
    if (resultManager && resultManager.current_result_manager instanceof ResultStandard || resultManager.current_result_manager instanceof ResultText) {
      SearchListHierarchyManager.__super__.addToResultDiv.call(this, request, result_object, div);
    }
  };

  return SearchListHierarchyManager;

})(SearchHierarchyManager);
// Generated by CoffeeScript 1.12.7
var SearchInput, SearchInputException,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  SearchInput.prototype.initOpts = function() {
    SearchInput.__super__.initOpts.call(this);
    return this.addOpts({
      expert: {
        check: Search
      },
      search: {
        check: Search
      },
      searchTypeSelector: {
        check: SearchTypeSelector
      },
      init_from_data: {
        check: 'PlainObject'
      },
      background_help_loca_key: {
        mandatory: true,
        "default": 'search.input.background.help',
        check: String
      },
      linked_objecttypes: {
        check: 'Array'
      },
      scope: {
        check: 'Array'
      },
      scope_on_return: {
        check: ["token", "fulltext"]
      },
      min_length: {
        check: function(v) {
          return v >= 1;
        }
      },
      fields: {
        check: 'Array'
      },
      fields_suggest: {
        check: Boolean,
        "default": true
      },
      input_opts: {
        check: "PlainObject",
        "default": {}
      }
    });
  };

  SearchInput.prototype.readOpts = function() {
    var inst, j, len, q, ref;
    SearchInput.__super__.readOpts.call(this);
    this.__add_init = [];
    this.query = [];
    this.__buttons = [];
    if (ez5.version("6")) {
      this.__clipboardBuffer = [];
    }
    this.__inputLayout = new CUI.Toolbar({
      "class": "ez5-search-input",
      left: {
        "class": "ez5-search-input-left"
      },
      center: {
        "class": "ez5-search-input-query",
        ui: "search.input.content"
      },
      right: {
        "class": "ez5-search-input-right"
      }
    });
    if (ez5.version("6")) {
      this.__clearAllButton = new CUI.Button({
        text: $$("search.input.button.clear_all|text"),
        icon_right: $$("search.input.button.clear_all|icon"),
        "class": "ez5-expert-search-button ez5-search-input-query-remove-all",
        appearance: "normal",
        onClick: (function(_this) {
          return function() {
            _this.selectAllQueryElements();
            return _this.deleteSelectedQueryElements();
          };
        })(this)
      });
      this.__clearAllButton.hide();
      this.__inputLayout.append(this.__clearAllButton, "right", false);
    }
    if (this._expert) {
      this.__expertBtn = new LocaButton({
        ui: "search.input.expert_button",
        loca_key: "search.input.button.expert",
        "class": "ez5-expert-search-button",
        appearance: "normal",
        onClick: (function(_this) {
          return function(ev) {
            var ref;
            return (ref = _this.__expertOpts) != null ? ref.openPopover() : void 0;
          };
        })(this)
      });
      this.__inputLayout.append(this.__expertBtn, "right", false);
    }
    if (ez5.version("6.17")) {
      this.__settings = {
        search_input_settings: ez5.session.getPref("search_input_settings") || {}
      };
      this.__settingsBtn = new LocaButton({
        ui: "search.input.settings_button",
        loca_key: "search.input.button.settings",
        "class": "ez5-expert-search-button",
        appearance: "normal",
        onClick: (function(_this) {
          return function(ev) {
            return _this.__showSettings();
          };
        })(this)
      });
      this.__inputLayout.append(this.__settingsBtn, "right", false);
    }
    if (this._init_from_data) {
      ref = this._init_from_data.query;
      for (j = 0, len = ref.length; j < len; j++) {
        q = ref[j];
        inst = window[q["class"]].newFromData(q.data);
        this.query.push(inst);
      }
    }
    return this;
  };

  SearchInput.prototype.showResult = function(request, data) {
    var j, len, objecttype, ref, ref1, results;
    SearchInput.__super__.showResult.call(this, request, data);
    if (ez5.version("6")) {
      this.__allow_include_asset_fulltext = false;
      ref1 = ((ref = this.getSearch()) != null ? ref.getSearchObjecttypes() : void 0) || [];
      results = [];
      for (j = 0, len = ref1.length; j < len; j++) {
        objecttype = ref1[j];
        if ((objecttype != null ? objecttype.getEASFields().length : void 0) > 0) {
          this.__allow_include_asset_fulltext = true;
          break;
        } else {
          results.push(void 0);
        }
      }
      return results;
    }
  };

  SearchInput.prototype.__showSettings = function() {
    this.__cachedSettings = CUI.util.copyObject(this.__settings, true);
    if (this.__settingPopover) {
      this.__settingPopover.show();
      return;
    }
    this.__settingPopover = new CUI.Popover({
      element: this.__settingsBtn,
      backdrop: {
        policy: "click"
      },
      cancel_action: "hide",
      placement: "s",
      placements: ["s"],
      onHide: (function(_this) {
        return function() {
          if (CUI.util.isEqual(_this.__cachedSettings, _this.__settings)) {
            return;
          }
          if (!_this.__allow_include_asset_fulltext && _this.__cachedSettings.search_input_settings.include_asset_fulltext) {
            _this.__settings.search_input_settings.include_asset_fulltext = true;
          }
          ez5.session.savePref("search_input_settings", _this.__settings.search_input_settings, true);
          _this.getSearch().execute();
        };
      })(this),
      pane: {
        "class": "ez5-search-input-settings",
        title: $$("search.input.settings.title"),
        content: (function(_this) {
          return function() {
            _this._setting_form = new CUI.Form({
              data: _this.__settings,
              name: "search_input_settings",
              "class": "ez5-search-input-settings-form",
              fields: [
                {
                  type: CUI.Checkbox,
                  disabled: function() {
                    return !_this.__allow_include_asset_fulltext;
                  },
                  text: $$("search.input.settings.include_asset_fulltext"),
                  name: "include_asset_fulltext",
                  tooltip: {
                    text: $$("search.input.settings.include_asset_fulltext|tooltip")
                  }
                }
              ]
            });
            return _this._setting_form.start();
          };
        })(this)
      },
      onShow: (function(_this) {
        return function() {
          var include_fulltext_from_files_field;
          if (!_this._setting_form) {
            return;
          }
          include_fulltext_from_files_field = _this._setting_form.getFieldsByName("include_asset_fulltext")[0];
          if (_this.__allow_include_asset_fulltext) {
            include_fulltext_from_files_field.enable();
            if (_this.__allow_include_asset_fulltext && _this.__settings.search_input_settings.include_asset_fulltext) {
              include_fulltext_from_files_field.setValue(true);
            }
          } else {
            include_fulltext_from_files_field.disable();
            include_fulltext_from_files_field.setValue(false);
          }
          include_fulltext_from_files_field.reload();
        };
      })(this)
    });
    return this.__settingPopover.show();
  };

  SearchInput.prototype.replaceSearchInput = function(queryElement) {
    CUI.util.assert(!queryElement || queryElement instanceof QueryElement, "SearchInput.replaceSearchInput", "Parameter needs to be instance of QueryElement.", {
      parm: queryElement
    });
    this.empty();
    this.addPlaceholder();
    if (queryElement) {
      this.add(queryElement);
      this.addPlaceholder();
    }
    this.focusQueryContainer();
    return this;
  };

  SearchInput.prototype.init = function() {
    var j, len, qi, ref;
    SearchInput.__super__.init.call(this);
    this.__container = this.__inputLayout.center();
    this.__initDragDrop();
    this.empty();
    ref = this.__add_init;
    for (j = 0, len = ref.length; j < len; j++) {
      qi = ref[j];
      this.add(qi);
    }
    if (this._searchTypeSelector) {
      this.__inputLayout.replace(this._searchTypeSelector.getButton(), "left", false);
    }
    if (this._expert) {
      this.__expertOpts = new SearchExpertOptions({
        search: this._expert,
        searchInput: this,
        button: this.__expertBtn
      });
    }
    CUI.Events.listen({
      node: this.__inputLayout,
      type: "click",
      call: (function(_this) {
        return function(ev) {
          ev.stopPropagation();
          _this.__clearAllSelections();
          return _this.focusQueryContainer();
        };
      })(this)
    });
    this.registerEvents();
    this.__initGlobalClickHandler();
    this.__add_init = [];
    return this;
  };

  SearchInput.prototype.__triggerContentResize = function() {
    if (!this.__container) {
      return;
    }
    return CUI.Events.trigger({
      node: this.__container,
      type: "content-resize"
    });
  };

  SearchInput.prototype.getPlaceholder = function() {
    return new QueryElementInput({
      search: this._expert || this._search,
      linked_objecttypes: this._linked_objecttypes,
      scope: this._scope,
      scope_on_return: this._scope_on_return,
      min_length: this._min_length,
      fields_suggest: this._fields_suggest,
      fields: this._fields,
      input_opts: this._input_opts
    });
  };

  SearchInput.prototype.addPlaceholder = function() {
    var qi;
    CUI.util.assert(this._expert || this._search, "SearchInput.addPlaceholder", "opts.expert or opts.search needs to be set", {
      opts: this.opts
    });
    qi = this.getPlaceholder();
    if (!this.__container) {
      this.__add_init.push(qi);
      return null;
    } else {
      return this.add(qi);
    }
  };

  SearchInput.prototype.objecttypesUpdated = function() {
    var j, len, q, ref, ref1;
    if ((ref = this.__expertOpts) != null) {
      ref.objecttypesUpdated();
    }
    this.updateBackgroundHelp();
    ref1 = this.query;
    for (j = 0, len = ref1.length; j < len; j++) {
      q = ref1[j];
      q.objecttypesUpdated();
    }
    return this;
  };

  SearchInput.prototype.getQuery = function() {
    return this.query;
  };

  SearchInput.prototype.getAsString = function() {
    var j, len, parts, q, ref, str;
    parts = [];
    ref = this.query;
    for (j = 0, len = ref.length; j < len; j++) {
      q = ref[j];
      str = q.getAsString();
      if (str) {
        parts.push(str);
      }
    }
    return parts.join("; ");
  };

  SearchInput.prototype.getInputLayout = function() {
    return this.__inputLayout;
  };

  SearchInput.prototype.updateBackgroundHelp = function() {
    var count, ref, search, text;
    if (!this.__backgroundHelp) {
      return;
    }
    if (this._searchTypeSelector) {
      text = this._searchTypeSelector.getCountText("placeholder");
      return this.__backgroundHelp.setText(text);
    } else {
      search = this.getSearch();
      count = (ref = search.getLastData()) != null ? ref.count : void 0;
      if (!CUI.util.isInteger(count)) {
        count = this.getSearch().getSearchBasics().getCount();
      }
      return this.__backgroundHelp.setText($$(this._background_help_loca_key, {
        count: ez5.format_number(count)
      }));
    }
  };

  SearchInput.prototype.getMaskNames = function() {
    if (this._searchTypeSelector) {
      return this._searchTypeSelector.getMaskNames();
    } else {
      return this.getSearch().getSearchBasics().getMaskNames();
    }
  };

  SearchInput.prototype.empty = function() {
    this.query = [];
    CUI.dom.empty(this.__container);
    if (!CUI.util.isEmpty(ez5.loca.get_key('search.input.background.help'))) {
      this.__backgroundHelp = new CUI.Label({
        "class": 'ez5-search-input-background-help',
        text: ''
      });
      this.__inputLayout.append(this.__backgroundHelp, 'center');
      this.updateBackgroundHelp();
    } else {
      this.__backgroundHelp = null;
    }
    return this;
  };

  SearchInput.prototype.addCollectionFixedSearchInsertToday = function(gids) {
    var fixedSearch, ref, ref1, ref2, ref3, ref4;
    if (ez5.version("6") && ((ref = ez5.session.user) != null ? (ref1 = ref.data) != null ? (ref2 = ref1.user) != null ? (ref3 = ref2.frontend_prefs) != null ? (ref4 = ref3.webfrontend) != null ? ref4.avoid_insert_today : void 0 : void 0 : void 0 : void 0 : void 0)) {
      return;
    }
    fixedSearch = new CollectionFixedSearchInsertToday({
      getSearchObjecttypes: (function(_this) {
        return function() {
          return _this.getSearch().getSearchObjecttypes(false);
        };
      })(this),
      listen_for_global_object_ids: gids,
      onIndexEvent: (function(_this) {
        return function() {
          return CUI.scheduleCallback({
            ms: 1000,
            call: function() {
              return _this.getSearch().execute();
            }
          });
        };
      })(this)
    });
    return this.replaceSearchInput(fixedSearch.getQueryElement());
  };

  SearchInput.prototype.emptyRequest = function() {
    this.empty();
    return this.addPlaceholder();
  };

  SearchInput.prototype.storeQuery = function() {
    var j, len, q, query;
    query = this.query.slice();
    for (j = 0, len = query.length; j < len; j++) {
      q = query[j];
      CUI.dom.remove(q.getElement());
    }
    this.empty();
    this.addPlaceholder();
    return query;
  };

  SearchInput.prototype.restoreFromStored = function(searchInput) {
    var j, len, q, query, squery;
    squery = searchInput.getQuery();
    query = [];
    for (j = 0, len = squery.length; j < len; j++) {
      q = squery[j];
      query.push(this.getPlaceholder());
      query.push(q);
    }
    query.push(this.getPlaceholder());
    this.restoreQuery(query);
    return CUI.resolvedPromise();
  };

  SearchInput.inpMap = {
    QueryElementToken: 'token',
    QueryElementFulltext: 'fulltext',
    QueryElementSystemObjectId: 'sid',
    QueryElementUuid: 'uuid',
    QueryElementSuperSearch: 'supersearch'
  };

  SearchInput.prototype.initFromUrlData = function(url_data) {
    var _inp, cls, data, inp, j, k, key, len, q, query, ref, ref1, si, v, value;
    if (url_data.input) {
      si = new SearchInput({
        init_from_data: JSON.parse(url_data.input[0])
      });
      return this.restoreFromStored(si);
    } else {
      query = [];
      this.empty();
      this.addPlaceholder();
      if (url_data.inp) {
        ref = url_data.inp;
        for (j = 0, len = ref.length; j < len; j++) {
          _inp = ref[j];
          if (CUI.util.isEmpty(_inp.trim())) {
            continue;
          }
          inp = _inp.split(':');
          q = null;
          if (inp.length === 1) {
            value = QueryElementBracket.getConstructorValueFromUrlValue(_inp);
            q = new QueryElementBracket({
              char: value
            });
          } else {
            key = inp.splice(0, 1)[0];
            ref1 = SearchInput.inpMap;
            for (k in ref1) {
              v = ref1[k];
              if (v !== key) {
                continue;
              }
              cls = window[k];
              data = cls.getConstructorValueFromUrlValue(inp.join(":"));
              if (cls === QueryElementToken || cls === QueryElementFulltext) {
                data.fields = this._fields;
              }
              q = new cls(data);
              break;
            }
            if (!q && inp.length === 1) {
              data = QueryElementLinkedObjecttype.getConstructorValueFromUrlValue(_inp);
              q = new QueryElementLinkedObjecttype(data);
            }
          }
          if (!q) {
            continue;
          }
          query.push(this.getPlaceholder());
          query.push(q);
        }
      }
      query.push(this.getPlaceholder());
      return this.restoreQuery(query);
    }
  };

  SearchInput.prototype.getStoreAsUrlData = function(url_data) {
    var cls_map, count, idx, inp, j, len, q, ref, sd;
    inp = [];
    count = 0;
    ref = this.query;
    for (idx = j = 0, len = ref.length; j < len; idx = ++j) {
      q = ref[idx];
      if (q instanceof QueryElementInput) {
        continue;
      }
      sd = q.getStoreDataForUrlValue();
      count += 1;
      if (CUI.util.isEmpty(sd)) {
        continue;
      }
      CUI.util.assert(CUI.util.isString(sd), 'SearchInput.getStoreAsUrlData', 'QueryElement needs to return String to store for url.', {
        data: sd,
        queryElement: q
      });
      cls_map = SearchInput.inpMap[CUI.util.getObjectClass(q)];
      if (cls_map) {
        inp.push(cls_map + ':' + sd);
      } else if (q instanceof QueryElementBracket) {
        inp.push(sd);
      } else if (q instanceof QueryElementLinkedObjecttype) {
        inp.push(sd);
      } else {
        console.info("Unable to serialize " + (CUI.util.getObjectClass(q)) + ", falling back to JSON.");
        break;
      }
    }
    if (inp.length === count) {
      url_data.inp = inp;
    } else {
      sd = this.getStoreData().SearchInput;
      if (sd.query.length > 0) {
        url_data.input = JSON.stringify(sd);
      }
    }
    return url_data;
  };

  SearchInput.prototype.restoreQuery = function(query) {
    var j, len, q;
    this.empty();
    for (j = 0, len = query.length; j < len; j++) {
      q = query[j];
      this.add(q);
    }
    return this;
  };

  SearchInput.prototype.registerEvents = function() {
    CUI.Events.listen({
      node: this.__container,
      type: 'keydown',
      call: (function(_this) {
        return function(ev) {
          var _idx, idx, isInTextInput, j, len, qe, ref, ref1, ref2, ref3, target;
          if (ev.keyCode() === 65 && ev.hasModifierKey(false) && _this.query.filter(function(element) {
            return !(element instanceof QueryElementInput);
          }).length) {
            ev.preventDefault();
            ev.stopPropagation();
            _this.selectAllQueryElements();
            return;
          }
          if (ez5.version("6")) {
            if (ev.keyCode() === 67 && ev.hasModifierKey(false)) {
              target = ev.getTarget();
              isInTextInput = target && (CUI.dom.hasClass(target, "ez5-query-element-input") && ((ref = target.textContent) != null ? ref.trim().length : void 0) > 0);
              if (_this.getSelectedQueryElements().length > 0 && !isInTextInput) {
                ev.preventDefault();
                ev.stopPropagation();
                _this.__copySelectedQueryElements();
                return;
              }
            }
            if (ev.keyCode() === 88 && ev.hasModifierKey(false)) {
              if (_this.getSelectedQueryElements().length > 0) {
                ev.preventDefault();
                ev.stopPropagation();
                _this.__cutSelectedQueryElements();
                return;
              }
            }
            if (ev.keyCode() === 86 && ev.hasModifierKey(false)) {
              target = ev.getTarget();
              isInTextInput = target && (CUI.dom.hasClass(target, "ez5-query-element-input") && ((ref1 = target.textContent) != null ? ref1.trim().length : void 0) > 0);
              if (_this.__clipboardBuffer.length > 0 && !isInTextInput) {
                ev.preventDefault();
                ev.stopPropagation();
                _this.__pasteQueryElements();
                return;
              }
            }
          }
          if ((ref2 = ev.keyCode()) === 8 || ref2 === 46) {
            if (_this.getSelectedQueryElements().length > 0 && _this.__shouldAllowElementDeletion(ev)) {
              ev.preventDefault();
              ev.stopPropagation();
              _this.deleteSelectedQueryElements();
              return;
            } else if (_this.getSelectedQueryElements().length === 0) {
              target = ev.getTarget();
              if (CUI.dom.hasClass(target, "ez5-query-element-input")) {
                ref3 = _this.query;
                for (idx = j = 0, len = ref3.length; j < len; idx = ++j) {
                  qe = ref3[idx];
                  if (qe.element === target) {
                    if (qe.isEmpty()) {
                      _this.moveLeft();
                    }
                    _idx = idx;
                    return;
                  }
                }
              }
            }
          }
          if (ev.keyCode() === 37) {
            ev.stopPropagation();
            ev.preventDefault();
            _this.moveLeft();
          }
          if (ev.keyCode() === 39) {
            ev.stopPropagation();
            ev.preventDefault();
            _this.moveRight();
          }
          if (_this.__scheduledSearchExecution) {
            clearTimeout(_this.__scheduledSearchExecution);
          }
        };
      })(this)
    });
    CUI.Events.listen({
      node: this.__container,
      type: 'keyup',
      call: (function(_this) {
        return function(ev) {
          var ref;
          if ((ref = ev.getKeyboardKey()) === "Return" || ref === "Space") {
            _this.__modifyQueryElement();
          }
        };
      })(this)
    });
    CUI.Events.listen({
      node: this.__container,
      type: 'dblclick',
      call: (function(_this) {
        return function() {
          _this.__modifyQueryElement();
          if (_this.__scheduledSearchExecution) {
            return clearTimeout(_this.__scheduledSearchExecution);
          }
        };
      })(this)
    });
    return CUI.Events.listen({
      node: this.__container,
      type: 'click',
      call: (function(_this) {
        return function(ev) {
          if (ev.getTarget() === _this.__container) {
            return _this.__queryElementsToInput();
          }
        };
      })(this)
    });
  };

  SearchInput.prototype.__queryElementsToInput = function() {
    return this.query.forEach(function(queryElement) {
      if (queryElement instanceof QueryElementInput) {
        return queryElement.addInput();
      }
    });
  };

  SearchInput.prototype.__modifyQueryElement = function() {
    var element, index, j, len, queryElementInput, queryElementToken, selectedElements, tokenString;
    selectedElements = this.getSelectedQueryElements();
    queryElementToken = null;
    for (j = 0, len = selectedElements.length; j < len; j++) {
      element = selectedElements[j];
      if (element instanceof QueryElementToken || element instanceof QueryElementFulltext || element instanceof QueryElementExactToken) {
        queryElementToken = element;
        break;
      }
    }
    if (!queryElementToken) {
      return;
    }
    this.__queryElementsToInput();
    index = CUI.util.idxInArray(queryElementToken, this.query);
    queryElementInput = this.query[index - 1];
    if (queryElementInput instanceof QueryElementInput) {
      tokenString = queryElementToken.getDisplayString();
      queryElementInput.setText(tokenString);
      queryElementInput.triggerFocus();
      queryElementInput.triggerAutocomplete(tokenString);
      this.__inlineEditingMode = true;
      this.removeQueryElement(queryElementToken);
      this.__inlineEditingMode = false;
    }
  };

  SearchInput.prototype.focusQueryContainer = function() {
    var ref;
    if ((ref = this.query) != null ? ref.length : void 0) {
      this.query[this.query.length - 1].triggerFocus();
    }
    return this;
  };

  SearchInput.prototype.triggerFocusOnIdx = function(idx) {
    return this.query[idx].triggerFocus();
  };

  SearchInput.prototype.prepareSearch = function() {
    var j, len, q, ref;
    if (this.__destroyed) {
      return;
    }
    ref = this.query;
    for (j = 0, len = ref.length; j < len; j++) {
      q = ref[j];
      if (q instanceof QueryElementInput) {
        q.addInput();
      }
    }
  };

  SearchInput.prototype.removeQueryElementLeft = function(fromInput) {
    var activeElement, allElements, container, element, elementToRemove, i, inputIndex, j, l, len, len1, previousElement, qe, ref;
    if (fromInput == null) {
      fromInput = null;
    }
    activeElement = document.activeElement;
    if (!activeElement || !CUI.dom.hasClass(activeElement, "ez5-query-element-input")) {
      return;
    }
    container = this.__container;
    allElements = container.children;
    inputIndex = -1;
    for (i = j = 0, len = allElements.length; j < len; i = ++j) {
      element = allElements[i];
      if (element === activeElement) {
        inputIndex = i;
        break;
      }
    }
    if (inputIndex <= 0) {
      return;
    }
    previousElement = allElements[inputIndex - 1];
    if (!previousElement || !CUI.dom.hasClass(previousElement, "query-element-span")) {
      return;
    }
    elementToRemove = null;
    ref = this.query;
    for (l = 0, len1 = ref.length; l < len1; l++) {
      qe = ref[l];
      if (qe.getElement() === previousElement) {
        elementToRemove = qe;
        break;
      }
    }
    if (!elementToRemove) {
      return;
    }
    this.removeQueryElement(elementToRemove);
    return setTimeout((function(_this) {
      return function() {
        if (document.activeElement !== activeElement) {
          return activeElement.focus();
        }
      };
    })(this), 0);
  };

  SearchInput.prototype.removeQueryElement = function(queryElement) {
    var destroy, idx;
    idx = CUI.util.idxInArray(queryElement, this.query);
    if (idx === -1) {
      return idx;
    }
    destroy = (function(_this) {
      return function(qe) {
        if (qe) {
          qe.destroy();
          if (qe._rendered_element) {
            return CUI.dom.remove(qe._rendered_element);
          }
        }
      };
    })(this);
    destroy(queryElement);
    if (idx + 1 < this.query.length) {
      destroy(this.query[idx + 1]);
    }
    this.__triggerContentResize();
    this.query.splice(idx, 2);
    this.updateSearchButtonState();
    if (!this.__batchDeletion) {
      this.__restoreFocusAfterDeletion(idx);
    }
    if (!this.getSearch().getSearchButton().isDisabled() && !this.__inlineEditingMode) {
      if (this.__scheduledSearchExecution) {
        clearTimeout(this.__scheduledSearchExecution);
      }
      this.__scheduledSearchExecution = setTimeout((function(_this) {
        return function() {
          var ref;
          if ((ref = _this.getSearch()) != null) {
            ref.execute();
          }
          _this.__scheduledSearchExecution = null;
        };
      })(this), 1000);
    }
    return idx;
  };

  SearchInput.prototype.hasValidQuery = function() {
    return !this.getSearch().getSearchButton().isDisabled();
  };

  SearchInput.prototype.execute = function() {
    var ref;
    if (!this.hasValidQuery()) {
      return;
    }
    return (ref = this.getSearch()) != null ? ref.execute() : void 0;
  };

  SearchInput.prototype.addAfterIdx = function(queryElement, after_idx) {
    this.query.splice(after_idx + 1, 0, queryElement);
    queryElement.setSearchInput(this);
    queryElement._rendered_element = queryElement.render();
    if (queryElement._rendered_element) {
      if (after_idx === -1) {
        this.__inputLayout.append(queryElement._rendered_element, 'center');
      } else {
        CUI.dom.insertAfter(this.query[after_idx]._rendered_element, queryElement._rendered_element);
      }
    }
    this.__triggerContentResize();
    this.updateSearchButtonState();
    return after_idx + 1;
  };

  SearchInput.prototype.updateSearchButtonState = function() {
    var ex, is_empty, ref, ref1, set_class;
    is_empty = null;
    set_class = (function(_this) {
      return function() {
        if (is_empty) {
          return _this.getInputLayout().addClass("ez5-search-input-is-empty");
        } else {
          return _this.getInputLayout().removeClass("ez5-search-input-is-empty");
        }
      };
    })(this);
    if (!this.__container || !this.getSearch()) {
      is_empty = true;
      set_class();
      return;
    }
    try {
      is_empty = this.getSearchFilter().length === 0;
      if (is_empty) {
        if ((ref = this.__clearAllButton) != null) {
          ref.hide();
        }
      } else {
        if ((ref1 = this.__clearAllButton) != null) {
          ref1.show();
        }
      }
      this.getSearch().getSearchButton().enable();
    } catch (error) {
      ex = error;
      if (ex instanceof UserError) {
        is_empty = false;
        console.warn("SearchInput.parseInput:", ex.getError());
        this.getSearch().getSearchButton().disable();
      } else {
        throw ex;
      }
    }
    set_class();
    return this;
  };

  SearchInput.prototype.add = function(queryElement, afterQueryElement) {
    var after_idx, idx, j, len, q, ref;
    if (!this.__container) {
      CUI.util.assert(!afterQueryElement, "SearchInput.add", "2. parameter only supported with container.");
      this.__add_init.push(queryElement);
      return null;
    }
    after_idx = this.query.length - 1;
    ref = this.query;
    for (idx = j = 0, len = ref.length; j < len; idx = ++j) {
      q = ref[idx];
      if (afterQueryElement) {
        if (afterQueryElement === q) {
          after_idx = idx;
          break;
        } else {
          continue;
        }
      }
      if (q.hasFocus()) {
        after_idx = idx;
        break;
      }
    }
    return this.addAfterIdx(queryElement, after_idx);
  };

  SearchInput.prototype.append = function(queryElement) {
    this.add(queryElement);
    return this.addPlaceholder();
  };

  SearchInput.prototype.moveLeft = function(isShiftPressed) {
    var activeElement, container, currentIndex, element, focusableElements, i, j, l, len, len1, qe, restoreselectedElements, targetIndex;
    if (isShiftPressed == null) {
      isShiftPressed = false;
    }
    restoreselectedElements = null;
    activeElement = document.activeElement;
    if (!activeElement) {
      return;
    }
    container = this.__container;
    focusableElements = container.querySelectorAll('.ez5-query-element-input, .query-element-span');
    currentIndex = -1;
    for (i = j = 0, len = focusableElements.length; j < len; i = ++j) {
      element = focusableElements[i];
      if (element === activeElement) {
        currentIndex = i;
        break;
      }
    }
    if (currentIndex > 0) {
      targetIndex = currentIndex - 1;
      if (isShiftPressed) {
        while (targetIndex >= 0 && CUI.dom.hasClass(focusableElements[targetIndex], 'ez5-query-element-input')) {
          targetIndex--;
        }
      }
      if (targetIndex >= 0) {
        if (isShiftPressed) {
          restoreselectedElements = this.getSelectedQueryElements();
        }
        qe = this.query[targetIndex];
        qe.focus();
        this.__selectOrToggleQueryElement(qe, isShiftPressed);
        if (restoreselectedElements) {
          for (l = 0, len1 = restoreselectedElements.length; l < len1; l++) {
            element = restoreselectedElements[l];
            this.__selectQueryElement(element);
          }
        }
      }
    }
    return this;
  };

  SearchInput.prototype.moveRight = function(isShiftPressed) {
    var activeElement, container, currentIndex, element, focusableElements, i, j, l, len, len1, qe, restoreselectedElements, targetIndex;
    if (isShiftPressed == null) {
      isShiftPressed = false;
    }
    restoreselectedElements = null;
    activeElement = document.activeElement;
    if (!activeElement) {
      return;
    }
    container = this.__container;
    focusableElements = container.querySelectorAll('.ez5-query-element-input, .query-element-span');
    currentIndex = -1;
    for (i = j = 0, len = focusableElements.length; j < len; i = ++j) {
      element = focusableElements[i];
      if (element === activeElement) {
        currentIndex = i;
        break;
      }
    }
    if (currentIndex >= 0 && currentIndex < focusableElements.length - 1) {
      targetIndex = currentIndex + 1;
      if (isShiftPressed) {
        while (targetIndex < focusableElements.length && CUI.dom.hasClass(focusableElements[targetIndex], 'ez5-query-element-input')) {
          targetIndex++;
        }
      }
      if (targetIndex < focusableElements.length) {
        if (isShiftPressed) {
          restoreselectedElements = this.getSelectedQueryElements();
        }
        qe = this.query[targetIndex];
        qe.focus();
        this.__selectOrToggleQueryElement(qe, isShiftPressed);
        if (restoreselectedElements) {
          for (l = 0, len1 = restoreselectedElements.length; l < len1; l++) {
            element = restoreselectedElements[l];
            this.__selectQueryElement(element);
          }
        }
      }
    }
    return this;
  };

  SearchInput.prototype.__scheduleSearchExecution = function() {
    if (this.__scheduledSearchExecution) {
      clearTimeout(this.__scheduledSearchExecution);
    }
    return this.__scheduledSearchExecution = setTimeout((function(_this) {
      return function() {
        var ref;
        if ((ref = _this.getSearch()) != null) {
          ref.execute();
        }
        return _this.__scheduledSearchExecution = null;
      };
    })(this), 1000);
  };

  SearchInput.prototype.rebuildQueryStructure = function() {
    var element, j, l, len, len1, len2, len3, m, n, nonInputElements, qe, ref, ref1, selectedElements;
    nonInputElements = [];
    ref = this.query;
    for (j = 0, len = ref.length; j < len; j++) {
      qe = ref[j];
      if (!(qe instanceof QueryElementInput)) {
        nonInputElements.push(qe);
      }
    }
    selectedElements = this.getSelectedQueryElements().slice();
    ref1 = this.query;
    for (l = 0, len1 = ref1.length; l < len1; l++) {
      qe = ref1[l];
      qe.destroy();
      if (qe._rendered_element) {
        CUI.dom.remove(qe._rendered_element);
      }
    }
    this.query = [];
    this.__selectedElements = [];
    this.addPlaceholder();
    for (m = 0, len2 = nonInputElements.length; m < len2; m++) {
      element = nonInputElements[m];
      this.add(element);
      this.addPlaceholder();
    }
    for (n = 0, len3 = selectedElements.length; n < len3; n++) {
      element = selectedElements[n];
      if (indexOf.call(nonInputElements, element) >= 0) {
        this.__selectQueryElement(element);
      }
    }
    if (this.getSelectedQueryElements().length === 0) {
      this.focusQueryContainer();
    }
    this.updateSearchButtonState();
    this.execute();
    return this;
  };

  SearchInput.prototype.__initDragDrop = function() {
    if (!this.__container) {
      return;
    }
    this.__sortable = new CUI.Sortable({
      element: this.__container,
      selector: '.query-element-span',
      allowSort: (function(_this) {
        return function(ev, from_idx, to_idx) {
          return _this.__allowSort(ev, from_idx, to_idx);
        };
      })(this),
      sorted: (function(_this) {
        return function(ev, from_idx, to_idx) {
          return _this.__sorted(ev, from_idx, to_idx);
        };
      })(this)
    });
    return this;
  };

  SearchInput.prototype.__sorted = function(ev, from_idx, to_idx) {
    return this.__rebuildFromCurrentDOMOrder();
  };

  SearchInput.prototype.__rebuildFromCurrentDOMOrder = function() {
    var child, currentDOMOrder, domElement, j, l, len, len1, len2, m, newOrderedElements, qe, ref, ref1;
    currentDOMOrder = [];
    ref = this.__container.children;
    for (j = 0, len = ref.length; j < len; j++) {
      child = ref[j];
      if (CUI.dom.hasClass(child, 'query-element-span')) {
        currentDOMOrder.push(child);
      }
    }
    newOrderedElements = [];
    for (l = 0, len1 = currentDOMOrder.length; l < len1; l++) {
      domElement = currentDOMOrder[l];
      ref1 = this.query;
      for (m = 0, len2 = ref1.length; m < len2; m++) {
        qe = ref1[m];
        if (!(qe instanceof QueryElementInput) && qe._rendered_element === domElement) {
          newOrderedElements.push(qe);
          break;
        }
      }
    }
    if (newOrderedElements.length === 0) {
      return;
    }
    this.__updateQueryArrayOrder(newOrderedElements);
    return this.rebuildQueryStructure();
  };

  SearchInput.prototype.__updateQueryArrayOrder = function(newOrderedNonInputElements) {
    var idx, j, len, nonInputIdx, oldQuery, qe;
    oldQuery = this.query.slice();
    nonInputIdx = 0;
    for (idx = j = 0, len = oldQuery.length; j < len; idx = ++j) {
      qe = oldQuery[idx];
      if (!(qe instanceof QueryElementInput)) {
        if (nonInputIdx < newOrderedNonInputElements.length) {
          oldQuery[idx] = newOrderedNonInputElements[nonInputIdx];
          nonInputIdx++;
        }
      }
    }
    this.query = oldQuery;
    return this;
  };

  SearchInput.prototype.__allowSort = function(ev, from_idx, to_idx) {
    return true;
  };

  SearchInput.prototype.handleQueryElementClick = function(queryElement, ev) {
    return this.__selectOrToggleQueryElement(queryElement, ev.hasModifierKey(true));
  };

  SearchInput.prototype.__selectOrToggleQueryElement = function(queryElement, isToggle) {
    var ref;
    if (isToggle == null) {
      isToggle = false;
    }
    if (isToggle) {
      this.__toggleQueryElementSelection(queryElement);
      return;
    } else {
      this.__clearAllSelections();
      this.__selectQueryElement(queryElement);
    }
    return (ref = queryElement.getElement()) != null ? ref.focus() : void 0;
  };

  SearchInput.prototype.__selectQueryElement = function(queryElement) {
    if (queryElement instanceof QueryElementInput) {
      return;
    }
    if (!this.__selectedElements) {
      this.__selectedElements = [];
    }
    if (indexOf.call(this.__selectedElements, queryElement) < 0) {
      this.__selectedElements.push(queryElement);
      return CUI.dom.addClass(queryElement.getElement(), "ez5-query-element-selected");
    }
  };

  SearchInput.prototype.__toggleQueryElementSelection = function(queryElement) {
    var idx;
    if (!this.__selectedElements) {
      this.__selectedElements = [];
    }
    idx = CUI.util.idxInArray(queryElement, this.__selectedElements);
    if (idx >= 0) {
      this.__selectedElements.splice(idx, 1);
      return CUI.dom.removeClass(queryElement.getElement(), "ez5-query-element-selected");
    } else {
      this.__selectedElements.push(queryElement);
      return CUI.dom.addClass(queryElement.getElement(), "ez5-query-element-selected");
    }
  };

  SearchInput.prototype.__clearAllSelections = function() {
    var element, j, len, ref;
    if (this.__selectedElements) {
      ref = this.__selectedElements;
      for (j = 0, len = ref.length; j < len; j++) {
        element = ref[j];
        CUI.dom.removeClass(element.getElement(), "ez5-query-element-selected");
      }
      return this.__selectedElements = [];
    }
  };

  SearchInput.prototype.getSelectedQueryElements = function() {
    return this.__selectedElements || [];
  };

  SearchInput.prototype.__copySelectedQueryElements = function() {
    var copiedElement, element, elementClass, j, len, results, sortedElements, storeData;
    if (!ez5.version("6") || !this.__selectedElements || this.__selectedElements.length === 0) {
      return;
    }
    sortedElements = this.__selectedElements.slice().sort((function(_this) {
      return function(a, b) {
        var idxA, idxB;
        idxA = CUI.util.idxInArray(a, _this.query);
        idxB = CUI.util.idxInArray(b, _this.query);
        return idxA - idxB;
      };
    })(this));
    this.__clipboardBuffer = [];
    results = [];
    for (j = 0, len = sortedElements.length; j < len; j++) {
      element = sortedElements[j];
      elementClass = window[CUI.util.getObjectClass(element)];
      storeData = element.getStoreData();
      if (elementClass && elementClass.newFromData) {
        copiedElement = elementClass.newFromData(storeData);
      } else {
        if (element instanceof QueryElementToken || element instanceof QueryElementFulltext || element instanceof QueryElementExactToken) {
          copiedElement = new elementClass(CUI.util.mergeMap(storeData, {
            fields: element._fields
          }));
        } else {
          copiedElement = new elementClass(storeData);
        }
      }
      results.push(this.__clipboardBuffer.push(copiedElement));
    }
    return results;
  };

  SearchInput.prototype.__cutSelectedQueryElements = function() {
    if (!ez5.version("6") || !this.__selectedElements || this.__selectedElements.length === 0) {
      return;
    }
    this.__copySelectedQueryElements();
    return this.deleteSelectedQueryElements();
  };

  SearchInput.prototype.__pasteQueryElements = function() {
    var currentIndex, element, elementClass, insertionIndex, j, l, lastElement, len, len1, len2, m, newElement, pastedElements, placeholder, ref, storeData;
    if (!ez5.version("6") || !this.__clipboardBuffer || this.__clipboardBuffer.length === 0) {
      return;
    }
    insertionIndex = this.__findInsertionIndex();
    this.__clearAllSelections();
    pastedElements = [];
    ref = this.__clipboardBuffer;
    for (j = 0, len = ref.length; j < len; j++) {
      element = ref[j];
      elementClass = window[CUI.util.getObjectClass(element)];
      storeData = element.getStoreData();
      if (elementClass && elementClass.newFromData) {
        newElement = elementClass.newFromData(storeData);
      } else {
        if (element instanceof QueryElementToken || element instanceof QueryElementFulltext || element instanceof QueryElementExactToken) {
          newElement = new elementClass(CUI.util.mergeMap(storeData, {
            fields: element._fields
          }));
        } else {
          newElement = new elementClass(storeData);
        }
      }
      pastedElements.push(newElement);
    }
    currentIndex = insertionIndex;
    for (l = 0, len1 = pastedElements.length; l < len1; l++) {
      element = pastedElements[l];
      currentIndex = this.addAfterIdx(element, currentIndex);
      placeholder = this.getPlaceholder();
      currentIndex = this.addAfterIdx(placeholder, currentIndex);
    }
    this.rebuildQueryStructure();
    for (m = 0, len2 = pastedElements.length; m < len2; m++) {
      element = pastedElements[m];
      this.__selectQueryElement(element);
    }
    if (pastedElements.length > 0) {
      lastElement = pastedElements[pastedElements.length - 1];
      lastElement.triggerFocus();
    }
    if (!this.getSearch().getSearchButton().isDisabled()) {
      if (this.__scheduledSearchExecution) {
        clearTimeout(this.__scheduledSearchExecution);
      }
      return this.__scheduledSearchExecution = setTimeout((function(_this) {
        return function() {
          var ref1;
          if ((ref1 = _this.getSearch()) != null) {
            ref1.execute();
          }
          return _this.__scheduledSearchExecution = null;
        };
      })(this), 1000);
    }
  };

  SearchInput.prototype.__findInsertionIndex = function() {
    var activeElement, idx, j, len, qe, ref;
    activeElement = document.activeElement;
    if (!activeElement) {
      return this.query.length - 1;
    }
    ref = this.query;
    for (idx = j = 0, len = ref.length; j < len; idx = ++j) {
      qe = ref[idx];
      if (qe.getElement() === activeElement) {
        if (qe instanceof QueryElementInput) {
          return Math.max(0, idx - 1);
        } else {
          return idx;
        }
      }
    }
    return this.query.length - 1;
  };

  SearchInput.prototype.deleteSelectedQueryElements = function() {
    var element, elementsToDelete, j, lastSelectedElement, lastSelectedIndex, len;
    if (!this.__selectedElements || this.__selectedElements.length === 0) {
      return;
    }
    if (this.__batchDeletion) {
      return;
    }
    lastSelectedElement = this.__selectedElements[this.__selectedElements.length - 1];
    lastSelectedIndex = CUI.util.idxInArray(lastSelectedElement, this.query);
    elementsToDelete = this.__selectedElements.slice();
    elementsToDelete.sort((function(_this) {
      return function(a, b) {
        var idxA, idxB;
        idxA = CUI.util.idxInArray(a, _this.query);
        idxB = CUI.util.idxInArray(b, _this.query);
        return idxB - idxA;
      };
    })(this));
    this.__batchDeletion = true;
    for (j = 0, len = elementsToDelete.length; j < len; j++) {
      element = elementsToDelete[j];
      this.removeQueryElement(element);
    }
    this.__batchDeletion = false;
    this.__selectedElements = [];
    return this.__restoreFocusAfterDeletion(lastSelectedIndex);
  };

  SearchInput.prototype.__restoreFocusAfterDeletion = function(deletedElementIndex) {
    var i, j, ref, targetInput;
    targetInput = null;
    if (deletedElementIndex < this.query.length && this.query[deletedElementIndex] instanceof QueryElementInput) {
      targetInput = this.query[deletedElementIndex];
    }
    if (!targetInput) {
      for (i = j = ref = deletedElementIndex - 1; j >= 0; i = j += -1) {
        if (this.query[i] instanceof QueryElementInput) {
          targetInput = this.query[i];
          break;
        }
      }
    }
    if (targetInput) {
      return targetInput.triggerFocus();
    }
  };

  SearchInput.prototype.selectAllQueryElements = function() {
    var j, len, qe, ref, results;
    this.__clearAllSelections();
    ref = this.query;
    results = [];
    for (j = 0, len = ref.length; j < len; j++) {
      qe = ref[j];
      if (!(qe instanceof QueryElementInput)) {
        results.push(this.__selectQueryElement(qe));
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  SearchInput.prototype.__shouldAllowElementDeletion = function(ev) {
    var j, len, qe, ref, ref1, ref2, target, textContent;
    target = ev.getTarget();
    if (target && target.contentEditable === "true") {
      textContent = ((ref = target.textContent) != null ? ref.trim() : void 0) || "";
      if (textContent.length > 0) {
        return false;
      }
    }
    ref1 = this.query;
    for (j = 0, len = ref1.length; j < len; j++) {
      qe = ref1[j];
      if (qe instanceof QueryElementInput && qe.hasFocus()) {
        textContent = ((ref2 = qe.getElement().textContent) != null ? ref2.trim() : void 0) || "";
        if (textContent.length > 0) {
          return false;
        }
      }
    }
    return true;
  };

  SearchInput.prototype.__initGlobalClickHandler = function() {
    this.__globalClickHandler = (function(_this) {
      return function(ev) {
        if (!_this.__container || CUI.dom.closest(ev.getTarget(), _this.__container)) {
          return;
        }
        return _this.__clearAllSelections();
      };
    })(this);
    return CUI.Events.listen({
      type: "click",
      node: document,
      instance: this,
      call: this.__globalClickHandler
    });
  };

  SearchInput.prototype.isEmpty = function() {
    var ex, ref;
    try {
      return ((ref = this.getSearchFilter()) != null ? ref.length : void 0) === 0;
    } catch (error) {
      ex = error;
      if (ex instanceof UserError) {
        return true;
      }
      throw ex;
    }
  };

  SearchInput.prototype.getSearchFilter = function() {
    var filter, j, len, q, ref, ref1, ref2, search, setFulltextFields;
    if (this.__destroyed) {
      return;
    }
    if (ez5.version("6.17")) {
      setFulltextFields = (ref = this.__settings) != null ? (ref1 = ref.search_input_settings) != null ? ref1.include_asset_fulltext : void 0 : void 0;
      ref2 = this.query;
      for (j = 0, len = ref2.length; j < len; j++) {
        q = ref2[j];
        if (q instanceof QueryElementFulltext) {
          q.setFullTextFields(setFulltextFields);
        }
      }
    }
    filter = SearchInput.parseInput(this.query);
    if (filter.search.length === 0) {
      search = [];
    } else {
      search = [filter];
    }
    return search;
  };

  SearchInput.prototype.getExpertOptions = function() {
    return this.__expertOpts;
  };

  SearchInput.prototype.getStoreData = function(sd) {
    var j, len, q, qsd, ref;
    if (sd == null) {
      sd = {};
    }
    SearchInput.__super__.getStoreData.call(this, sd);
    sd.SearchInput = {
      query: []
    };
    ref = this.query;
    for (j = 0, len = ref.length; j < len; j++) {
      q = ref[j];
      qsd = q.getStoreData();
      if (CUI.util.isNull(qsd)) {
        continue;
      }
      sd.SearchInput.query.push({
        "class": CUI.util.getObjectClass(q),
        data: qsd
      });
    }
    return sd;
  };

  SearchInput.prototype.ignoreSearchManager = function(searchManager) {
    var ign, j, l, len, len1, q, ref, ref1;
    ref = this.query;
    for (j = 0, len = ref.length; j < len; j++) {
      q = ref[j];
      ref1 = q.ignoreSearchManagers();
      for (l = 0, len1 = ref1.length; l < len1; l++) {
        ign = ref1[l];
        if (searchManager instanceof ign) {
          return true;
        }
      }
    }
    return false;
  };

  SearchInput.prototype.addToRequest = function(request) {
    var j, len, q, ref, sf;
    ref = this.query;
    for (j = 0, len = ref.length; j < len; j++) {
      q = ref[j];
      if (q instanceof QueryElementInput) {
        q.setEmpty();
      }
    }
    sf = this.getSearchFilter();
    if (!request.search) {
      request.search = [];
    }
    request.search.push.apply(request.search, sf);
    return this;
  };

  SearchInput.prototype.destroy = function() {
    var element, j, l, len, len1, q, ref, ref1, ref2;
    if ((ref = this.__sortable) != null) {
      ref.destroy();
    }
    if (this.__globalClickHandler) {
      CUI.Events.ignore({
        instance: this
      });
      this.__globalClickHandler = null;
    }
    if (ez5.version("6") && this.__clipboardBuffer) {
      ref1 = this.__clipboardBuffer;
      for (j = 0, len = ref1.length; j < len; j++) {
        element = ref1[j];
        if (typeof element.destroy === "function") {
          element.destroy();
        }
      }
      this.__clipboardBuffer = [];
    }
    this.__container = null;
    if (this.query) {
      ref2 = this.query;
      for (l = 0, len1 = ref2.length; l < len1; l++) {
        q = ref2[l];
        q.destroy();
      }
      delete this.query;
    }
    return SearchInput.__super__.destroy.call(this);
  };

  SearchInput.parseInput = function(query, testmode) {
    var get_bool, get_item_print, idx, parse, top_level_filter;
    if (testmode == null) {
      testmode = false;
    }
    idx = -1;
    top_level_filter = {
      type: "complex",
      __filter: "SearchInput",
      search: []
    };
    get_bool = function(_bind) {
      switch (_bind) {
        case "OR":
          return "should";
        case "AND":
          return "must";
        default:
          return void 0;
      }
    };
    get_item_print = function(item) {
      if (item === "(" || item === ")") {
        return item;
      }
      return $$("query.element.bracket." + item.toLowerCase());
    };
    parse = function(filter, depth, _not) {
      var _f, add_to_filter, bind, bracket, finish_up, item, item_print, set_must;
      if (depth == null) {
        depth = 0;
      }
      if (_not == null) {
        _not = null;
      }
      bind = null;
      set_must = function() {
        var j, len, ref, s;
        ref = filter.search;
        for (j = 0, len = ref.length; j < len; j++) {
          s = ref[j];
          if (s.bool == null) {
            s.bool = "must";
          }
        }
      };
      add_to_filter = function(map) {
        var base, ref;
        if (!map.bool) {
          map.bool = get_bool(bind);
        }
        filter.search.push(map);
        if (((ref = map.bool) === "should" || ref === "must") && filter.search.length >= 2) {
          if ((base = filter.search[filter.search.length - 2]).bool == null) {
            base.bool = map.bool;
          }
        }
        bind = null;
        return map;
      };
      finish_up = (function(_this) {
        return function() {
          if (bind) {
            throw new SearchInputException({
              label: "search.input.error.not_allowed",
              label_attrs: {
                item: get_item_print(bind)
              }
            });
          }
          if (_not) {
            throw new SearchInputException({
              label: "search.input.error.not_allowed",
              label_attrs: {
                item: get_item_print("not")
              }
            });
          }
          return set_must();
        };
      })(this);
      while (true) {
        idx = idx + 1;
        if (idx === query.length) {
          if (depth > 0) {
            if (_not) {
              throw new SearchInputException({
                label: "search.input.error.not_allowed",
                label_attrs: {
                  item: get_item_print("not")
                }
              });
            } else {
              throw new SearchInputException({
                label: "search.input.error.missing_parentheses"
              });
            }
          }
          finish_up();
          return;
        }
        item = query[idx];
        if (item instanceof QueryElementInput && item.isEmpty()) {
          continue;
        }
        if (CUI.util.isString(item) && item.trim().length === 0) {
          continue;
        }
        if (item instanceof QueryElementBracket) {
          item = item.getChar();
          bracket = true;
        } else {
          if (testmode && (item === "(" || item === ")" || item === "AND" || item === "OR" || item === "NOT")) {
            bracket = true;
          } else {
            bracket = false;
          }
        }
        if (bracket) {
          item_print = get_item_print(item);
        } else {
          item_print = null;
        }
        if (testmode) {
          console.debug("parse[" + depth + "] #" + idx + ":", item, "bind: ", bind, "not:", _not, "item_print:", item_print);
        }
        if (bracket) {
          switch (item) {
            case "(":
              _f = add_to_filter({
                type: "complex",
                search: []
              });
              parse(_f, depth + 1);
              if (_not) {
                _not = null;
                finish_up();
                return;
              }
              break;
            case ")":
              if (depth === 0) {
                throw new SearchInputException({
                  label: "search.input.error.not_found",
                  label_attrs: {
                    item: "("
                  }
                });
              }
              if (filter.search.length === 0) {
                throw new SearchInputException({
                  label: "search.input.error.nothing_in_parentheses"
                });
              }
              finish_up();
              return;
            case "AND":
            case "OR":
              if (filter.search.length === 0 || bind || _not) {
                throw new SearchInputException({
                  label: "search.input.error.not_allowed",
                  label_attrs: {
                    item: item_print
                  }
                });
              }
              bind = item;
              break;
            case "NOT":
              if (_not) {
                throw new SearchInputException({
                  label: "search.input.error.not_allowed",
                  label_attrs: {
                    item: item_print
                  }
                });
              }
              _f = {
                __filter: "NOT",
                bool: "must_not",
                type: "complex",
                search: []
              };
              if (bind === "OR") {
                add_to_filter({
                  type: "complex",
                  search: [_f]
                });
              } else {
                add_to_filter(_f);
              }
              parse(_f, depth + 1, true);
          }
        } else {
          if (CUI.util.isString(item)) {
            add_to_filter({
              item: item
            });
          } else {
            _f = item.getSearchFilter();
            if (_f === false) {
              return false;
            }
            if (_f) {
              add_to_filter(_f);
            }
          }
          if (_not) {
            _not = null;
            finish_up();
            return;
          }
        }
      }
    };
    parse(top_level_filter);
    return top_level_filter;
  };

  SearchInput.testParseInput = function() {
    var ex, j, len, ref, str;
    ref = ["A ( B AND C ) NOT D", "A ( B AND C ) OR NOT D1", "A ( B AND C ) NOT ( E OR D )", "A ( B AND C ) OR NOT ( E D AND U )", "A ( B AND C ) NOT AND D", "A ( B AND C ) NOT NOT D", " ", "A0 OR B1", "A0 OR OR B1", "A0 ( ) B1", "A0 ( B8 AND ) B1", "A1 B1 AND C1 OR C2 AND C3", "A ( B AND C OR ( D AND E ) ) D", "NOT A"];
    for (j = 0, len = ref.length; j < len; j++) {
      str = ref[j];
      try {
        console.info("====", str, "====");
        console.debug("OK:", this.parseInput(str.split(/\s+/), true));
      } catch (error) {
        ex = error;
        if (ex instanceof UserError) {
          console.error(ex.getError());
        } else {
          throw ex;
        }
      }
    }
  };

  return SearchInput;

})(SearchManager);

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

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

  return SearchInputException;

})(UserError);
// Generated by CoffeeScript 1.12.7
var SearchExpertOptions,
  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;

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

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

  SearchExpertOptions.prototype.initOpts = function() {
    SearchExpertOptions.__super__.initOpts.call(this);
    return this.addOpts({
      button: {
        mandatory: true,
        check: CUI.Button
      },
      searchInput: {
        mandatory: true,
        check: SearchInput
      },
      onHide: {
        check: Function
      }
    });
  };

  SearchExpertOptions.prototype.readOpts = function() {
    this.opts.mode = "expert";
    this.opts.data = {};
    SearchExpertOptions.__super__.readOpts.call(this);
    this.expertOptionsButton = this._button;
    this.objecttype_select_data = {
      ot_name: null
    };
    this.__plugins = SearchExpertOptions.plugins.newPlugins();
    return this;
  };

  SearchExpertOptions.prototype.hasSearchFilterExpert = function() {
    return this.__searchFilterExpert(true, false);
  };

  SearchExpertOptions.prototype.getSearchFilterExpert = function() {
    return this.__searchFilterExpert(true, true);
  };

  SearchExpertOptions.prototype.addSearchFilterExpert = function() {
    return this.__searchFilterExpert(false, false);
  };

  SearchExpertOptions.prototype.__searchFilterExpert = function(dry_run, get_filters) {
    var _d, _f, data, filters, fn, has_filters, i, info, k, len, ot_name, p, qf, ref, ref1, ref2, set_data, v;
    has_filters = false;
    if (get_filters) {
      filters = [];
    }
    set_data = [];
    ref = this.data;
    for (ot_name in ref) {
      _d = ref[ot_name];
      for (fn in _d) {
        data = _d[fn];
        if (!data.field) {
          continue;
        }
        _f = data.field.getSearchFilter(data.data);
        if (!_f) {
          continue;
        }
        set_data.push(data);
        has_filters = true;
        if (!get_filters && dry_run) {
          return true;
        }
        info = {
          field: data.field,
          data: {}
        };
        ref1 = data.data;
        for (k in ref1) {
          v = ref1[k];
          if (k.endsWith(":field")) {
            continue;
          }
          info.data[k] = CUI.util.copyObject(v, true);
        }
        if (!dry_run) {
          ref2 = this.__plugins;
          for (i = 0, len = ref2.length; i < len; i++) {
            p = ref2[i];
            p.__beforeFieldAdded(info);
          }
        }
        qf = new QueryElementField(info);
        if (get_filters) {
          filters.push(qf.getSearchFilter());
        }
        if (!dry_run) {
          this._searchInput.add(qf);
          this._searchInput.addPlaceholder();
        }
      }
    }
    if (get_filters) {
      return filters;
    } else if (!dry_run) {
      return set_data;
    } else {
      return has_filters;
    }
  };

  SearchExpertOptions.prototype.__getDoneButtonLocaKey = function() {
    return "search.expert.options.button.apply";
  };

  SearchExpertOptions.prototype.openPopover = function() {
    var ref, toolbar;
    if (this.doneButton) {
      this.fieldsUpdated();
    }
    if (!this.popover || this.__objecttypesUpdated) {
      if (this.__objecttypesUpdated = true) {
        this.init();
        this.__objecttypesUpdated = false;
        this.popoverDestroy();
      }
      this.doneButton = new LocaButton({
        ui: "search-expert-options-apply-button",
        loca_key: this.__getDoneButtonLocaKey(),
        primary: true,
        onClick: (function(_this) {
          return function(ev) {
            _this.doneButton.DOM.focus();
            if (ev.hasModifierKey()) {
              console.debug("SearchExpertOptions -----------------");
              console.debug(_this.getFieldsRenderer().dump());
              console.debug("Search Filters:", _this.getSearchFilterExpert());
              console.debug(" -----------------");
              return;
            }
            return _this.closePopover();
          };
        })(this)
      });
      toolbar = new CUI.Toolbar({
        left: {
          content: this.getObjecttypeSelect()
        },
        center: {
          content: (ref = this.__getFilterInput()) != null ? ref.DOM : void 0
        }
      });
      this.popover = new CUI.Popover({
        ui: "search-expert-popover",
        "class": "ez5-search-expert-options-popover",
        element: this.expertOptionsButton,
        cancel: true,
        backdrop: {
          policy: "click"
        },
        fill_screen_button: true,
        fill_screen_button_tooltip: {
          text: $$("base.fill_screen.tooltip")
        },
        cancel_action: "hide",
        placement: "s",
        placements: ["s"],
        onShow: (function(_this) {
          return function() {
            return _this.focusFilterInput();
          };
        })(this),
        onHide: (function(_this) {
          return function() {
            _this.clearFilter();
            return typeof _this._onHide === "function" ? _this._onHide() : void 0;
          };
        })(this),
        pane: {
          "class": "ez5-search-expert-options",
          title: $$("main.search.expert.title"),
          content: (function(_this) {
            return function() {
              var content;
              content = _this.getContent();
              _this.updateForm().done(function() {
                return _this.fieldsUpdated();
              });
              return content;
            };
          })(this),
          footer_left: (function(_this) {
            return function() {
              return {
                loca_key: "search.expert.options.help.button",
                secondary: true,
                onClick: function() {
                  return CUI.alert({
                    "class": 'ez5-search-expert-hotkeys',
                    title: $$("search.expert.options.help.title"),
                    text: $$("search.expert.options.help.text"),
                    markdown: true
                  });
                }
              };
            };
          })(this),
          footer_right: (function(_this) {
            return function() {
              return _this.doneButton;
            };
          })(this)
        }
      });
      this.popover.append(toolbar, "top");
      CUI.Events.listen({
        node: this.popover,
        instance: this,
        type: ["keydown"],
        call: (function(_this) {
          return function(event) {
            if (event.key() === "Enter" && _this.hasSearchFilterExpert()) {
              event.stopPropagation();
              event.preventDefault();
              _this.closePopover();
            }
          };
        })(this)
      });
    }
    return this.popover.show();
  };

  SearchExpertOptions.prototype.popoverTitle = function() {
    return this.title();
  };

  SearchExpertOptions.prototype.init = function() {
    SearchExpertOptions.__super__.init.call(this);
    this.link_otm = new ObjecttypeManager();
    this.link_otm.addLinkedObjectFields(this.getLinkedObjectFields());
    return this;
  };

  SearchExpertOptions.prototype.getLinkedObjectFields = function() {
    return this._search.getLinkedObjectFields(this.mode);
  };

  SearchExpertOptions.prototype.getObjecttypeSelect = function() {
    var disabled, i, j, l, len, len1, len2, mask, masks, opt, ot, ot_count, ot_count_enabled, ot_lbl, ot_name, ot_opts, ots;
    ot_count = this.getSearchObjecttypes().length;
    if (!ot_count) {
      return;
    }
    ot_opts = [];
    if (ot_count > 1) {
      ot_opts.push({
        text: $$("main.search.expert.common"),
        value: "_COMMONS"
      });
    }
    ots = this.getObjecttypes().slice(0);
    ots.sort(function(a, b) {
      return a.nameLocalized().localeCompare(b.nameLocalized());
    });
    masks = this.getMasks();
    if (masks.length === 0) {
      return;
    }
    if (ot_count > 1) {
      ot_opts.push({
        divider: true
      });
    }
    masks.sort(function(a, b) {
      var ot_a, ot_b;
      ot_a = a.getTable().nameLocalized();
      ot_b = b.getTable().nameLocalized();
      if (ot_a !== ot_b) {
        return ot_a.localeCompare(ot_b);
      }
      return a.nameLocalized().localeCompare(b.nameLocalized());
    });
    ot_lbl = null;
    for (i = 0, len = masks.length; i < len; i++) {
      mask = masks[i];
      ot_name = mask.getTable().nameLocalized();
      if (ot_name !== ot_lbl) {
        ot_lbl = ot_name;
        ot_opts.push({
          label: ot_lbl
        });
      }
      disabled = !this.objecttypeIsUserSelected([mask.table.name()]);
      ot_opts.push({
        ui: "search-expert-options-" + mask.name() + "-objecttype-select-option",
        value: "_" + mask.name(),
        _mask: true,
        disabled: disabled,
        text: mask.nameLocalized()
      });
    }
    ot_opts.push({
      divider: true
    });
    ot_opts.push({
      label: $$("search.expert.options.objecttypes.label")
    });
    ot_count_enabled = 0;
    for (j = 0, len1 = ots.length; j < len1; j++) {
      ot = ots[j];
      disabled = !this.objecttypeIsUserSelected([ot.name()]);
      if (!disabled) {
        ot_count_enabled = ot_count_enabled + 1;
      }
      ot_opts.push({
        ui: "search-expert-options-" + ot.name() + "-objecttype-select-option",
        value: ot.name(),
        disabled: disabled,
        text: ot.nameLocalized()
      });
    }
    if (ot_count_enabled <= 1 && ot_count > 1) {
      ot_opts[0].disabled = true;
    }
    for (l = 0, len2 = ot_opts.length; l < len2; l++) {
      opt = ot_opts[l];
      if (opt.value && !opt.disabled && !opt.divider) {
        this.objecttype_select_data.ot_name = opt.value;
        break;
      }
    }
    return new CUI.Select({
      ui: "search-expert-options-objecttype-select",
      name: "ot_name",
      tooltip: {
        text: $$("search.export.options.select.tooltip")
      },
      options: ot_opts,
      onDataChanged: (function(_this) {
        return function(data, field) {
          _this.updateForm();
          return _this.popover.autoSize();
        };
      })(this),
      data: this.objecttype_select_data
    }).start();
  };

  SearchExpertOptions.prototype.getCurrentGroup = function() {
    return this.objecttype_select_data.ot_name;
  };

  SearchExpertOptions.prototype.getMaskNames = function() {
    return this._searchInput.getMaskNames();
  };

  SearchExpertOptions.prototype.getMasks = function() {
    var mask_name;
    return (function() {
      var i, len, ref, results;
      ref = this.getMaskNames();
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        mask_name = ref[i];
        results.push(ez5.mask.CURRENT._mask_instance_by_name[mask_name]);
      }
      return results;
    }).call(this);
  };

  SearchExpertOptions.prototype.closePopover = function() {
    var current_row, data, empty_row, i, k, len, opts, ref, set_data, v;
    set_data = this.addSearchFilterExpert();
    this.popover.hide();
    if (set_data.length > 0) {
      this._searchInput.execute();
      current_row = null;
      for (i = 0, len = set_data.length; i < len; i++) {
        data = set_data[i];
        ref = data.data;
        for (k in ref) {
          v = ref[k];
          if (k === '_DOM') {
            current_row = v;
          }
          delete data.data[k];
        }
        if (!current_row || !current_row.parentElement) {
          continue;
        }
        opts = this.getRenderOpts();
        opts.fieldRenderType = 'expert';
        empty_row = data.field.renderForExpert(data.data, opts);
        CUI.dom.replaceWith(current_row, empty_row.DOM || empty_row);
      }
    }
    return this;
  };

  SearchExpertOptions.prototype.fieldsUpdated = function() {
    if (!this.hasSearchFilterExpert()) {
      return this.doneButton.disable();
    } else {
      return this.doneButton.enable();
    }
  };

  SearchExpertOptions.prototype.objecttypesUpdated = function() {
    return this.__objecttypesUpdated = true;
  };

  SearchExpertOptions.prototype.popoverDestroy = function() {
    var ref;
    if ((ref = this.popover) != null) {
      ref.destroy();
    }
    this.popover = null;
    return CUI.Events.ignore({
      instance: this
    });
  };

  SearchExpertOptions.prototype.destroy = function() {
    var i, len, p, ref;
    SearchExpertOptions.__super__.destroy.call(this);
    this.popoverDestroy();
    ref = this.__plugins || [];
    for (i = 0, len = ref.length; i < len; i++) {
      p = ref[i];
      p.destroy();
    }
  };

  return SearchExpertOptions;

})(FieldPopoverManager);

ez5.session_ready(function() {
  return SearchExpertOptions.plugins = new CUI.PluginRegistry({
    "class": ez5.SearchExpertPlugin
  });
});
// Generated by CoffeeScript 1.12.7
var ObjecttypeSearchExpertOptions,
  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;

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

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

  ObjecttypeSearchExpertOptions.prototype.initOpts = function() {
    ObjecttypeSearchExpertOptions.__super__.initOpts.call(this);
    this.removeOpt("search");
    this.removeOpt("searchInput");
    return this.addOpts({
      button: {
        mandatory: true,
        check: CUI.Button
      },
      masks: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isArray(v) && v.every(function(ot) {
            return ot instanceof Mask;
          });
        }
      }
    });
  };

  ObjecttypeSearchExpertOptions.prototype.readOpts = function() {
    var data;
    data = this.opts.data;
    ObjecttypeSearchExpertOptions.__super__.readOpts.call(this);
    this.setData(data);
    return this;
  };

  ObjecttypeSearchExpertOptions.prototype.getLinkedObjectFields = function() {
    var field, fields, i, j, len, len1, mask, ref, ref1;
    fields = [];
    ref = this._masks;
    for (i = 0, len = ref.length; i < len; i++) {
      mask = ref[i];
      ref1 = mask.getFields("all");
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        field = ref1[j];
        if (!(field instanceof LinkedObject)) {
          continue;
        }
        fields.push(field);
      }
    }
    return fields;
  };

  ObjecttypeSearchExpertOptions.prototype.getRenderOpts = function() {
    var opts;
    opts = ObjecttypeSearchExpertOptions.__super__.getRenderOpts.call(this);
    opts.objecttypeSearchExpert = true;
    return opts;
  };

  ObjecttypeSearchExpertOptions.prototype.getMasks = function() {
    return this._masks;
  };

  ObjecttypeSearchExpertOptions.prototype.getMaskNames = function() {
    return this.getMasks().map(function(mask) {
      return mask.name();
    });
  };

  ObjecttypeSearchExpertOptions.prototype.getSearchObjecttypes = function() {
    var i, len, mask, objecttype, objecttypes, ref;
    objecttypes = {};
    ref = this.getMasks();
    for (i = 0, len = ref.length; i < len; i++) {
      mask = ref[i];
      objecttype = mask.objecttype;
      if (!objecttype) {
        objecttype = new Objecttype(mask);
        mask.objecttype = objecttype;
        continue;
      }
      if (objecttypes[mask.objecttype.name()]) {
        continue;
      }
      objecttypes[mask.objecttype.name()] = objecttype;
    }
    return Object.values(objecttypes);
  };

  ObjecttypeSearchExpertOptions.prototype.objecttypeIsUserSelected = function() {
    return true;
  };

  ObjecttypeSearchExpertOptions.prototype.__searchFilterExpert = function(_, get_filters) {
    return ObjecttypeSearchExpertOptions.__super__.__searchFilterExpert.call(this, true, get_filters);
  };

  ObjecttypeSearchExpertOptions.prototype.fieldsUpdated = function() {
    return this.doneButton.enable();
  };

  ObjecttypeSearchExpertOptions.prototype.__getDoneButtonLocaKey = function() {
    return "admin.objecttype.tab.linked_objects_filters.button.apply";
  };

  return ObjecttypeSearchExpertOptions;

})(SearchExpertOptions);
// 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.SearchExpertPlugin = (function(superClass) {
  extend(SearchExpertPlugin, superClass);

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

  SearchExpertPlugin.prototype.__beforeFieldAdded = function(_opts) {
    var opts;
    opts = CUI.Element.readOpts(_opts, "ez5.SearchExpertPlugin :: beforeFieldAdded", {
      data: {
        mandatory: true,
        check: 'PlainObject'
      },
      field: {
        mandatory: true,
        check: function(v) {
          return v instanceof Field || v instanceof MultipleFieldsContainer;
        }
      }
    });
    return this.beforeFieldAdded(opts);
  };

  SearchExpertPlugin.prototype.beforeFieldAdded = function(opts) {};

  return SearchExpertPlugin;

})(CUI.Plugin);
// Generated by CoffeeScript 1.12.7
var QueryElement,
  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;

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

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

  QueryElement.prototype.initOpts = function() {
    QueryElement.__super__.initOpts.call(this);
    return this.addOpts({
      element: {
        check: function(v) {
          return CUI.util.isElement(v);
        }
      },
      ignoreSearchManagers: {
        check: Array,
        "default": []
      }
    });
  };

  QueryElement.prototype.readOpts = function() {
    QueryElement.__super__.readOpts.call(this);
    if (this._element) {
      return this.setElement(this._element);
    }
  };

  QueryElement.prototype.setElement = function(element) {
    var func, i, k, len, ref, results;
    this.element = element;
    CUI.dom.setAttribute(this.element, "tabindex", "0");
    ref = ["focus", "blur", "click", "dblclick", "input", "paste", "keyup", "keydown", "mousedown", "mouseup"];
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      func = this[k];
      if (!CUI.util.isFunction(func)) {
        continue;
      }
      results.push((function(_this) {
        return function(func) {
          return CUI.Events.listen({
            type: k,
            node: _this.element,
            call: function(ev, info) {
              return func.call(_this, ev, info);
            }
          });
        };
      })(this)(func));
    }
    return results;
  };

  QueryElement.prototype.render = function() {
    return this.element;
  };

  QueryElement.prototype.getElement = function() {
    return this.element;
  };

  QueryElement.prototype.getAsString = function() {
    return null;
  };

  QueryElement.prototype.setSearchInput = function(searchInput) {
    CUI.util.assert(searchInput instanceof SearchInput, (CUI.util.getObjectClass(this)) + ".setSearchInput", "search needs to be instance of SearchInput", {
      searchInput: searchInput
    });
    return this._searchInput = searchInput;
  };

  QueryElement.prototype.getSearchInput = function() {
    return this._searchInput;
  };

  QueryElement.prototype.getCursor = function() {
    if (this.element.selectionStart === this.element.selectionEnd) {
      return this.element.selectionStart;
    } else {
      return null;
    }
  };

  QueryElement.prototype.objecttypesUpdated = function() {};

  QueryElement.prototype.triggerFocus = function() {
    return this.element.focus();
  };

  QueryElement.prototype.triggerBlur = function() {
    return this.element.blur();
  };

  QueryElement.prototype.click = function(ev) {
    var ref;
    if ((ref = this.getSearchInput()) != null) {
      ref.handleQueryElementClick(this, ev);
    }
    return ev.stopPropagation();
  };

  QueryElement.prototype.focus = function(ev) {
    var ref;
    if ((ref = this.element) != null) {
      ref.focus();
    }
    if (this.getSearchInput()) {
      CUI.dom.addClass(this.getSearchInput().getInputLayout(), "ez5-search-input-has-focus");
    }
    this.updateSearchInput();
    return this;
  };

  QueryElement.prototype.blur = function(ev) {
    if (this.getSearchInput()) {
      CUI.dom.removeClass(this.getSearchInput().getInputLayout(), "ez5-search-input-has-focus");
    }
    this.updateSearchInput();
    return this;
  };

  QueryElement.prototype.hasFocus = function() {
    var ref;
    if (this instanceof QueryElementInput) {
      return this.getElement() === document.activeElement;
    } else {
      return ((ref = this.getSearchInput()) != null ? ref.getSelectedQueryElements().includes(this) : void 0) || false;
    }
  };

  QueryElement.prototype.triggerFocus = function() {
    this.focus();
    return this;
  };

  QueryElement.prototype.updateSearchInput = function() {
    var ref;
    return (ref = this.getSearchInput()) != null ? ref.updateSearchButtonState() : void 0;
  };

  QueryElement.prototype.hasFocus = function(ev) {
    return CUI.dom.hasClass(this.element, "focus");
  };

  QueryElement.prototype.getSearchTerm = function() {
    return "";
  };

  QueryElement.prototype.allowAutoExecuteSearch = function() {
    return true;
  };

  QueryElement.prototype.ignoreSearchManagers = function() {
    return this._ignoreSearchManagers;
  };

  QueryElement.prototype.removeFromQueryManager = function() {
    return this.getSearchInput().removeQueryElement(this);
  };

  QueryElement.prototype.destroy = function() {
    return CUI.dom.remove(this.element);
  };

  QueryElement.prototype.getStoreData = function() {};

  QueryElement.prototype.getStoreDataForUrlValue = function() {};

  QueryElement.newFromData = function(data) {
    return new this(data);
  };

  return QueryElement;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var QueryElementSpan,
  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;

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

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

  QueryElementSpan.prototype.readOpts = function() {
    QueryElementSpan.__super__.readOpts.call(this);
    this.__badgeLayout = new CUI.HorizontalLayout({
      "class": "query-element-span " + this.getClass(),
      maximize: false,
      right: {},
      left: {}
    });
    this.__badgeLayout.append(this.getRemoveButton(), "right", false);
    this.setElement(this.__badgeLayout.DOM);
    return this.element.setAttribute("tabindex", "0");
  };

  QueryElementSpan.prototype.getClass = function() {
    return "";
  };

  QueryElementSpan.prototype.getRemoveButton = function() {
    var removeButton;
    removeButton = new LocaButton({
      icon: "remove",
      loca_key: "query.element.remove",
      ui: "query.element.remove.button",
      appearance: "flat",
      tabindex: false,
      size: "mini",
      onClick: (function(_this) {
        return function() {
          return _this.removeFromQueryManager();
        };
      })(this)
    });
    return removeButton;
  };

  QueryElementSpan.prototype.debugPopoverContent = function() {
    var pre;
    pre = CUI.dom.pre();
    pre.innerHTML = CUI.util.toHtml(CUI.util.dump(this.getSearchFilter()));
    return pre;
  };

  QueryElementSpan.prototype.popoverContent = function() {};

  QueryElementSpan.prototype.render = function() {
    return this.renderBadge(this.getBadge());
  };

  QueryElementSpan.prototype.getSearchFilter = function() {
    return CUI.util.getObjectClass(this) + ".getSearchFilter needs to be overwritten";
  };

  QueryElementSpan.prototype.renderBadge = function(__badge) {
    this.__badge = __badge;
    if (CUI.util.isPromise(this.__badge)) {
      this.__badge.done((function(_this) {
        return function(_badge) {
          return _this.renderBadge(_badge);
        };
      })(this));
    } else {
      if (!CUI.util.isEmpty(this.__badge.name) || this.__badge.icon) {
        this.__badgeLayout.replace(new CUI.Label({
          "class": "query-element-span-type-label",
          icon: this.__badge.icon,
          text: ez5.add_ellipsis(this.__badge.name, 10),
          ui: "query.element.label:" + this.__badge.name,
          tooltip: {
            text: this.__badge.tooltip || this.__badge.name
          }
        }), "left");
      } else {
        this.__badgeLayout.empty("left");
      }
      if (!CUI.util.isEmpty(this.__badge.value)) {
        this.__badgeLayout.replace(new CUI.Label({
          "class": "query-element-span-text-label",
          text: ez5.add_ellipsis(this.__badge.value, 30),
          ui: "query.element.value:" + this.__badge.value,
          tooltip: {
            text: this.__badge.tooltip || this.__badge.value || this.__badge.name
          }
        }), "center");
      }
    }
    return this.element;
  };

  QueryElementSpan.prototype.dblclick = function(ev) {
    var ref;
    ev.stopPropagation();
    if (this instanceof QueryElementToken || this instanceof QueryElementFulltext || this instanceof QueryElementExactToken) {
      this.triggerFocus();
      return (ref = this.getSearchInput()) != null ? ref.__modifyQueryElement() : void 0;
    } else {
      if (ez5.session.isDebug()) {
        if (ev.hasModifierKey()) {
          return console.debug(this);
        } else {
          return this.openDebugPopover();
        }
      } else if (ez5.version("6")) {
        return this.openPopover();
      }
    }
  };

  QueryElementSpan.prototype.openPopover = function(content) {
    if (content == null) {
      content = null;
    }
    if (!content) {
      content = this.popoverContent();
    }
    if (CUI.util.isEmpty(content)) {
      return;
    }
    if (CUI.util.isPromise(content)) {
      content.done((function(_this) {
        return function(element) {
          return _this.openPopover(element);
        };
      })(this));
      return;
    }
    CUI.Events.listen({
      node: content,
      type: ["content-resize", "search-input-change"],
      call: (function(_this) {
        return function(ev) {
          return _this.popover.autoSize();
        };
      })(this)
    });
    this.applyPopoverBtn = new LocaButton({
      loca_key: "query.popover.button.apply",
      ui: "query.popover.button.apply",
      primary: true,
      disabled: true,
      onClick: (function(_this) {
        return function(ev) {
          return _this.closePopover(true);
        };
      })(this)
    });
    this.popover = new CUI.Popover({
      "class": "ez5-query-element-popover",
      element: this.element,
      backdrop: {
        policy: "modal"
      },
      cancel: true,
      pane: {
        header_left: new LocaLabel({
          loca_key: "query.popover.title"
        }),
        content: (function(_this) {
          return function() {
            var vl;
            return vl = new CUI.VerticalList({
              "class": "ez5-query-element-popover-content",
              content: [content]
            });
          };
        })(this),
        footer_right: [
          new CUI.Button({
            text: $$("base.abort"),
            onClick: (function(_this) {
              return function(ev) {
                return _this.closePopover();
              };
            })(this)
          }), this.applyPopoverBtn
        ]
      }
    });
    return this.popover.show();
  };

  QueryElementSpan.prototype.openDebugPopover = function() {
    this.popover = new CUI.Popover({
      element: this.element,
      pane: {
        header_center: CUI.util.getObjectClass(this),
        content: (function(_this) {
          return function() {
            var vl;
            return vl = new CUI.VerticalList({
              content: [
                new CUI.Label({
                  text: _this.__badge.name
                }), new CUI.Label({
                  text: _this.__badge.value
                }), _this.debugPopoverContent()
              ]
            });
          };
        })(this)
      }
    });
    return this.popover.show();
  };

  QueryElementSpan.prototype.closePopover = function(changedData) {
    var ref, ref1;
    if (changedData == null) {
      changedData = false;
    }
    if (this.popover) {
      this.popover.destroy();
      this.popover = null;
    }
    if (changedData) {
      this.render();
      return (ref = this.getSearchInput()) != null ? (ref1 = ref.getSearch()) != null ? ref1.execute() : void 0 : void 0;
    }
  };

  QueryElementSpan.prototype.destroy = function() {
    this.closePopover();
    return QueryElementSpan.__super__.destroy.call(this);
  };

  return QueryElementSpan;

})(QueryElement);
// Generated by CoffeeScript 1.12.7
var AutocompleteToken,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function AutocompleteToken() {
    this.__appendToContainer = bind(this.__appendToContainer, this);
    return AutocompleteToken.__super__.constructor.apply(this, arguments);
  }

  AutocompleteToken.prototype.initOpts = function() {
    AutocompleteToken.__super__.initOpts.call(this);
    return this.addOpts({
      autocompletion_popup: {
        mandatory: true,
        check: AutocompletionPopup
      },
      min_length: {
        "default": 1,
        check: function(v) {
          return v >= 1;
        }
      },
      boolean: {
        check: {
          click: {
            mandatory: true,
            check: Function
          }
        }
      },
      gidToken: {
        check: {
          click: {
            mandatory: true,
            check: Function
          },
          getSuggestionLabel: {
            check: Function
          },
          getSuggestionValue: {
            check: Function
          }
        }
      },
      uuidToken: {
        check: {
          click: {
            mandatory: true,
            check: Function
          }
        }
      },
      supersearch: {
        check: {
          click: {
            mandatory: true,
            check: Function
          }
        }
      },
      fulltext: {
        check: {
          click: {
            mandatory: true,
            check: Function
          },
          getSuggestionLabel: {
            check: Function
          },
          getSuggestionValue: {
            check: Function
          }
        }
      },
      token: {
        check: {
          click: {
            mandatory: true,
            check: Function
          },
          getSuggestionLabel: {
            check: Function
          },
          getSuggestionValue: {
            check: Function
          },
          addExactToken: {
            check: Boolean
          }
        }
      },
      tokens: {
        check: {
          field_names: {
            check: function(v) {
              return CUI.util.isArray(v) && v.length > 0;
            }
          },
          field_opts: {
            check: "PlainObject",
            "default": {}
          },
          click: {
            mandatory: true,
            check: Function
          },
          getSuggestionLabel: {
            check: Function
          },
          getSuggestionValue: {
            check: Function
          }
        }
      },
      fields: {
        check: {
          field_names: {
            mandatory: true,
            check: function(v) {
              return CUI.util.isArray(v) && v.length > 0;
            }
          },
          field_opts: {
            check: "PlainObject",
            "default": {}
          },
          click: {
            mandatory: true,
            check: Function
          }
        }
      },
      fields_suggest: {
        check: Boolean,
        "default": true
      },
      linked_objects: {
        check: {
          objecttypes: {
            mandatory: true,
            check: function(v) {
              return CUI.util.isArray(v) && v.length >= 0;
            }
          },
          click: {
            mandatory: true,
            check: Function
          }
        }
      },
      objecttypes: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isFunction(v) || (CUI.util.isArray(v) && v.length > 0);
        }
      },
      pool_ids: {
        check: "Array"
      },
      order: {
        check: function(v) {
          var i, key, len;
          for (i = 0, len = v.length; i < len; i++) {
            key = v[i];
            if (indexOf.call(AutocompleteToken.DEFAULT_ORDER, key) < 0) {
              return false;
            }
          }
          return true;
        },
        "default": AutocompleteToken.DEFAULT_ORDER
      }
    });
  };

  AutocompleteToken.DEFAULT_ORDER = ["fulltext", "token"];

  AutocompleteToken.prototype.readOpts = function() {
    var i, j, key, len, len1, ref, ref1;
    AutocompleteToken.__super__.readOpts.call(this);
    this.__popup = this._autocompletion_popup;
    if (this._supersearch) {
      this.__popup.addContainer("supersearch");
    }
    ref = this._order;
    for (i = 0, len = ref.length; i < len; i++) {
      key = ref[i];
      if (this.getSetOpt(key)) {
        this.__popup.addContainer(key);
      }
    }
    ref1 = ["fields", "tokens", "linked_objects"];
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      key = ref1[j];
      if (this.getSetOpt(key)) {
        this.__popup.addContainer(key);
      }
    }
    this.request_counter = 0;
    return this.__autocompleteCall = (function(_this) {
      return function() {
        return _this.__autocomplete();
      };
    })(this);
  };

  AutocompleteToken.prototype.__emptyContainer = function() {
    this.__popup.emptyContainer();
    return this.__popup.removeItems();
  };

  AutocompleteToken.prototype.__appendToContainer = function(container_name, div, group, func) {
    var item, item_content, item_icon, item_key, item_value;
    item = CUI.dom.element("DIV", {
      "class": "autocomplete-item",
      tabindex: "0"
    });
    item_icon = CUI.dom.element("DIV", {
      "class": "autocomplete-item-icon"
    });
    item_icon.appendChild(new CUI.Icon({
      icon: $$("autocomplete.token.categories.icon." + container_name)
    }).DOM);
    item_content = CUI.dom.element("DIV", {
      "class": "autocomplete-item-content"
    });
    item_value = CUI.dom.element("DIV", {
      "class": "autocomplete-item-value"
    });
    if (div.DOM) {
      item_value.appendChild(div.DOM);
    } else {
      item_value.appendChild(div);
    }
    item_content.appendChild(item_value);
    if (group) {
      item_key = CUI.dom.element("DIV", {
        "class": "autocomplete-item-key"
      });
      item_key.textContent = group;
      item_content.appendChild(item_key);
      CUI.dom.addClass(item, "autocomplete-item--text");
    }
    item.appendChild(item_icon);
    item.appendChild(item_content);
    this.__popup.getContainer(container_name).append(item);
    CUI.Events.listen({
      type: "click",
      node: item,
      call: (function(_this) {
        return function(ev) {
          ev.stopPropagation();
          func();
        };
      })(this)
    });
    return item;
  };

  AutocompleteToken.prototype.autocomplete = function(val) {
    this.__val = val.trim();
    return CUI.scheduleCallback({
      ms: 400,
      call: this.__autocompleteCall
    });
  };

  AutocompleteToken.prototype.__getAnalyzeWildcards = function(value) {
    return /^[^*].*\*/.test(value);
  };

  AutocompleteToken.prototype.__getSuggestQuery = function(value, includeAsterisk) {
    if (includeAsterisk == null) {
      includeAsterisk = false;
    }
    if (value.startsWith(SearchUtil.SINGLE_QUOTE) || value.startsWith(SearchUtil.QUOTES)) {
      value = value.substring(1);
      if (value.endsWith(SearchUtil.SINGLE_QUOTE) || value.endsWith(SearchUtil.QUOTES)) {
        value = value.substring(0, value.length - 1);
      }
      return value;
    }
    if (value.startsWith(SearchUtil.ASTERISK) && !includeAsterisk) {
      value = value.substring(1);
    }
    return value;
  };

  AutocompleteToken.SUGGEST_MODE_NGRAM = "ngram";

  AutocompleteToken.SUGGEST_MODE_EDGENGRAM = "edgengram";

  AutocompleteToken.SUGGEST_MODE_EXACT = "exact";

  AutocompleteToken.SPACE = " ";

  AutocompleteToken.prototype.__getSuggestMode = function(value) {
    var valueSplit;
    if (value.startsWith(SearchUtil.SINGLE_QUOTE)) {
      if (value.endsWith(SearchUtil.SINGLE_QUOTE)) {
        return AutocompleteToken.SUGGEST_MODE_EXACT;
      } else {
        return AutocompleteToken.SUGGEST_MODE_EDGENGRAM;
      }
    }
    if (value.startsWith(SearchUtil.QUOTES) && value.endsWith(SearchUtil.QUOTES)) {
      return AutocompleteToken.SUGGEST_MODE_EXACT;
    }
    valueSplit = value.split(SearchUtil.SPACE_REGEXP);
    value = valueSplit.pop();
    if (value.startsWith(SearchUtil.ASTERISK) || ez5.version("6.17")) {
      return AutocompleteToken.SUGGEST_MODE_NGRAM;
    } else {
      return AutocompleteToken.SUGGEST_MODE_EDGENGRAM;
    }
  };

  AutocompleteToken.prototype.__autocomplete = function() {
    var analyzeWildcards, i, item, j, k, key, len, len1, linked_objecttypes, lot, objecttypes, ot, rc, ref, ref1, ref2, ref3, suggestQuery, suggest_request, v, value;
    rc = ++this.request_counter;
    this.abort();
    analyzeWildcards = this.__getAnalyzeWildcards(this.__val);
    suggestQuery = this.__getSuggestQuery(this.__val, analyzeWildcards);
    if (CUI.util.isTrue(ez5.session.getClientDefault("suggest_disable")) || (!this._linked_objects && !this._tokens) || suggestQuery.length < this._min_length || suggestQuery === SearchUtil.SINGLE_QUOTE || SearchUtil.isOnlyWildcards(this.__val)) {
      this.__processSuggest(this.__val, {
        suggestions: {
          tokens: [],
          fields: [],
          linked_objects: []
        }
      });
      this.__popup.hide();
      return CUI.resolvedPromise();
    }
    if (CUI.util.isFunction(this._objecttypes)) {
      objecttypes = this._objecttypes();
      if ((objecttypes != null ? objecttypes.length : void 0) === 0) {
        this.hide();
        return;
      }
    } else {
      objecttypes = this._objecttypes;
    }
    if (this._supersearch || this._fulltext || this._token) {
      this.__emptyContainer();
      this.__showDefaultSuggestions(this.__val);
      this.__popup.show();
      this.__popup.autoSize();
    }
    suggest_request = {
      objecttypes: (function() {
        var i, len, results;
        results = [];
        for (i = 0, len = objecttypes.length; i < len; i++) {
          ot = objecttypes[i];
          results.push(ot.name());
        }
        return results;
      })(),
      query: suggestQuery,
      tokens_mode: this.__getSuggestMode(this.__val),
      fields_suggest: this._fields_suggest,
      analyze_wildcards: analyzeWildcards
    };
    if (((ref = this._pool_ids) != null ? ref.length : void 0) > 0) {
      suggest_request.pool_ids = this._pool_ids;
    }
    if (this._tokens) {
      suggest_request.tokens = true;
      suggest_request.fields = this._tokens.field_names;
      ref1 = this._tokens.field_opts;
      for (key in ref1) {
        value = ref1[key];
        suggest_request[key] = value;
      }
    } else {
      suggest_request.tokens = false;
    }
    if (this._linked_objects) {
      linked_objecttypes = (function() {
        var i, len, ref2, results;
        ref2 = this._linked_objects.objecttypes;
        results = [];
        for (i = 0, len = ref2.length; i < len; i++) {
          lot = ref2[i];
          results.push(lot.name());
        }
        return results;
      }).call(this);
      suggest_request.linked_objecttypes = linked_objecttypes;
      if (ez5.version("6") && this._tokens) {
        if (suggest_request.objecttypes == null) {
          suggest_request.objecttypes = [];
        }
        for (i = 0, len = linked_objecttypes.length; i < len; i++) {
          item = linked_objecttypes[i];
          if (indexOf.call(suggest_request.objecttypes, item) < 0) {
            suggest_request.objecttypes.push(item);
          }
        }
      }
    }
    if (this._fields) {
      suggest_request.fields = this._fields.field_names;
      ref2 = this._fields.field_opts;
      for (key in ref2) {
        value = ref2[key];
        suggest_request[key] = value;
      }
    }
    ref3 = ["languages"];
    for (j = 0, len1 = ref3.length; j < len1; j++) {
      k = ref3[j];
      if (CUI.util.isFunction(this.opts[k])) {
        v = this.opts[k]();
      } else {
        v = this.opts[k];
      }
      if (!CUI.util.isEmpty(v)) {
        suggest_request[k] = v;
      }
    }
    suggest_request.limit = 10;
    return this.current_search_request = ez5.api.suggest({
      type: "GET",
      data: {
        BODY: JSON.stringify(suggest_request),
        cache_seconds: 60 * 5
      }
    }).done((function(_this) {
      return function(data) {
        if (rc !== _this.request_counter) {
          CUI.util.assert(false, "discard unaborted autocomplete request " + _this.request_counter);
          return;
        }
        if (!data) {
          CUI.util.assert(false, "AutocompleteToken :: Suggest API returned null, this should not happen.");
          return;
        }
        return _this.__processSuggest(_this.__val, data);
      };
    })(this)).fail((function(_this) {
      return function(xhr) {
        if (xhr.statusText === "abort") {
          return;
        }
        _this.__popup.hide();
        return _this.__emptyContainer();
      };
    })(this));
  };

  AutocompleteToken.prototype.__addFulltextContainer = function(stringValue) {
    var base, basicFullText, fn, i, labelLocaKey, len, suggestionValue, suggestionValues;
    if (!ez5.version("6") && SearchUtil.isWildcard(stringValue)) {
      labelLocaKey = "autocomplete.categories.fulltext_wildcard";
    } else {
      if (SearchUtil.isPhrase(stringValue)) {
        labelLocaKey = "autocomplete.categories.fulltext_phrase";
      } else {
        basicFullText = true;
        labelLocaKey = "autocomplete.categories.fulltext";
      }
    }
    suggestionValues = typeof (base = this._fulltext).getSuggestionValue === "function" ? base.getSuggestionValue(stringValue) : void 0;
    if (suggestionValues !== false) {
      if (!CUI.util.isArray(suggestionValues)) {
        suggestionValues = [suggestionValues];
      }
      fn = (function(_this) {
        return function(suggestionValue, stringValue) {
          var base1, label, labelValue;
          if (CUI.util.isPlainObject(suggestionValue)) {
            label = suggestionValue.label;
            suggestionValue = suggestionValue.value;
          }
          if (!label) {
            label = typeof (base1 = _this._fulltext).getSuggestionLabel === "function" ? base1.getSuggestionLabel(suggestionValue) : void 0;
            if (CUI.util.isEmpty(label)) {
              label = $$(labelLocaKey);
            }
          }
          labelValue = new CUI.Label({
            "class": "ez5-autocomplete-token-fulltext",
            text: suggestionValue || stringValue,
            multiline: true
          });
          return _this.__appendToContainer("fulltext", labelValue, label, function() {
            return _this._fulltext.click(suggestionValue);
          });
        };
      })(this);
      for (i = 0, len = suggestionValues.length; i < len; i++) {
        suggestionValue = suggestionValues[i];
        if (!suggestionValue) {
          continue;
        }
        fn(suggestionValue, stringValue);
      }
    }
  };

  AutocompleteToken.prototype.__showDefaultSuggestions = function(value) {
    var bValue, base, base1, booleanLabel, cleaned, displayValue, exactToken, gid, gidLabel, label, labelValue, startsWithSingleQuote, suggestionValue, supersearchLabel, tokenValue, tokens, uuidLabel, uuidMatch;
    if (this._supersearch && !value.startsWith(SearchUtil.SINGLE_QUOTE) && !value.startsWith(SearchUtil.QUOTES)) {
      displayValue = SearchUtil.addWildcard(value, true);
      supersearchLabel = new CUI.Label({
        "class": "ez5-autocomplete-token-supersearch",
        text: displayValue,
        multiline: true
      });
      this.__appendToContainer("supersearch", supersearchLabel, $$("autocomplete.categories.supersearch"), (function(_this) {
        return function() {
          return _this._supersearch.click(value, _this.__lastSuggestData);
        };
      })(this));
    }
    exactToken = false;
    if (this._gidToken) {
      gid = value.match(/^#(\d+)$/);
      if (gid) {
        gidLabel = new CUI.Label({
          "class": "ez5-autocomplete-token-token",
          text: value,
          multiline: true
        });
        this.__appendToContainer("fulltext", gidLabel, $$("autocomplete.categories.gid"), (function(_this) {
          return function() {
            return _this._gidToken.click(value);
          };
        })(this));
      }
    }
    if (this._uuidToken) {
      cleaned = value.replace(/^#\s*/, "#");
      uuidMatch = cleaned.match(/^#([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i);
      if (uuidMatch) {
        uuidLabel = new CUI.Label({
          "class": "ez5-autocomplete-token-token",
          text: uuidMatch[1],
          multiline: true
        });
        this.__appendToContainer("fulltext", uuidLabel, $$("autocomplete.categories.uuid"), (function(_this) {
          return function() {
            return _this._uuidToken.click(cleaned);
          };
        })(this));
      }
    }
    if (this._boolean) {
      switch (value.toUpperCase()) {
        case "AND":
        case "&&":
          bValue = "AND";
          break;
        case "OR":
        case "||":
          bValue = "OR";
          break;
        case "NOT":
        case "!":
          bValue = "NOT";
      }
      if (bValue) {
        label = $$("autocomplete.categories.boolean");
        booleanLabel = new CUI.Label({
          "class": "ez5-autocomplete-token-token",
          text: bValue,
          multiline: true
        });
        this.__appendToContainer("fulltext", booleanLabel, label, (function(_this) {
          return function() {
            return _this._boolean.click(bValue);
          };
        })(this));
      }
    }
    if (this._token && !value.startsWith(SearchUtil.QUOTES)) {
      startsWithSingleQuote = value.startsWith(SearchUtil.SINGLE_QUOTE);
      if (startsWithSingleQuote) {
        tokenValue = SearchUtil.wrapSingleQuotes(value);
      } else {
        tokens = value.split(SearchUtil.SPACE_REGEXP);
        tokenValue = tokens.map((function(_this) {
          return function(token) {
            return SearchUtil.wrapSingleQuotes(token);
          };
        })(this)).join(AutocompleteToken.SPACE);
      }
      suggestionValue = typeof (base = this._token).getSuggestionValue === "function" ? base.getSuggestionValue(value) : void 0;
      if (suggestionValue !== false) {
        label = typeof (base1 = this._token).getSuggestionLabel === "function" ? base1.getSuggestionLabel(tokenValue) : void 0;
        if (CUI.util.isEmpty(label) || (this._token.addExactToken != null)) {
          if (ez5.version("6")) {
            exactToken = true;
          }
          label = $$("autocomplete.categories.token.exact");
          tokenValue = SearchUtil.wrapGraveAccent(value);
        }
        labelValue = new CUI.Label({
          "class": "ez5-autocomplete-token-token",
          text: exactToken ? tokenValue : suggestionValue || tokenValue,
          multiline: true
        });
        this.__appendToContainer("token", labelValue, label, (function(_this) {
          return function() {
            if (startsWithSingleQuote || exactToken) {
              _this._token.click(value, exactToken);
            } else {
              _this._token.click(tokens);
            }
          };
        })(this));
      }
    }
    if (this._fulltext && !value.startsWith(SearchUtil.SINGLE_QUOTE)) {
      if (value.startsWith(SearchUtil.QUOTES)) {
        value = SearchUtil.wrapQuotes(value);
      }
      this.__addFulltextContainer(value);
    }
  };

  AutocompleteToken.prototype.__processSuggest = function(inputValue, data) {
    var eas_url, fn, fn1, fn2, hasAssets, i, idx, j, l, len, len1, len2, linked_object, ref, ref1, ref2, result_object, sorted_tokens, suggest, suggestion, suggestions;
    suggestions = 0;
    this.__lastSuggestData = data;
    this.__emptyContainer();
    this.__showDefaultSuggestions(inputValue);
    if (this._tokens) {
      sorted_tokens = data.suggestions.tokens.slice(0);
      sorted_tokens.sort((function(_this) {
        return function(a, b) {
          return a.tokens[a.tokens.length - 1].localeCompare(b.tokens[b.tokens.length - 1]);
        };
      })(this));
      fn = (function(_this) {
        return function(suggestion) {
          var base, base1, div, label, suggestionValue;
          if (!(suggestionValue = typeof (base = _this._tokens).getSuggestionValue === "function" ? base.getSuggestionValue(suggestion, inputValue) : void 0)) {
            suggestionValue = suggestion.suggest;
          }
          div = CUI.dom.append(CUI.dom.div(), CUI.dom.htmlToNodes(suggestionValue));
          if (!(label = typeof (base1 = _this._tokens).getSuggestionLabel === "function" ? base1.getSuggestionLabel(suggestion) : void 0)) {
            label = $$("autocomplete.categories.tokens");
          }
          return _this.__appendToContainer("tokens", div, label, function(ev) {
            if (inputValue.startsWith(SearchUtil.SINGLE_QUOTE)) {
              suggestion.tokens = [suggestion.tokens.join(AutocompleteToken.SPACE)];
            }
            return _this._tokens.click(suggestion);
          });
        };
      })(this);
      for (idx = i = 0, len = sorted_tokens.length; i < len; idx = ++i) {
        suggestion = sorted_tokens[idx];
        suggestions++;
        fn(suggestion);
      }
    }
    if (this._fields) {
      ref = data.suggestions.fields;
      fn1 = (function(_this) {
        return function(suggest) {
          var div, suggest_text;
          suggest_text = suggest.suggest;
          if (CUI.util.isEmpty(suggest_text) && !CUI.util.isEmpty(suggest.field)) {
            suggest_text = suggest.field;
          }
          div = CUI.dom.append(CUI.dom.div(), CUI.dom.htmlToNodes(suggest_text));
          return _this.__appendToContainer("fields", div, $$("autocomplete.categories.fields"), function() {
            return _this._fields.click(suggest);
          });
        };
      })(this);
      for (idx = j = 0, len1 = ref.length; j < len1; idx = ++j) {
        suggest = ref[idx];
        suggestions++;
        fn1(suggest);
        if (idx === 3) {
          break;
        }
      }
    }
    if (this._linked_objects) {
      eas_url = (ref1 = ez5.session.config.defaults.server.eas) != null ? ref1.url : void 0;
      hasAssets = false;
      ref2 = data.suggestions.linked_objects;
      fn2 = (function(_this) {
        return function(result_object) {
          var card;
          card = result_object.renderCardAutocomplete();
          return _this.__appendToContainer("linked_objects", card, null, function() {
            return _this._linked_objects.click(result_object);
          });
        };
      })(this);
      for (idx = l = 0, len2 = ref2.length; l < len2; idx = ++l) {
        linked_object = ref2[idx];
        suggestions++;
        result_object = (new ResultObject()).setData(linked_object);
        if (result_object.getMask().hasStandardEASFields()) {
          hasAssets = true;
        }
        fn2(result_object);
      }
      if (hasAssets) {
        CUI.dom.removeClass(this.__popup.getContainer("linked_objects"), "ez5-search-has-no-mask-with-asset-browser");
        CUI.dom.addClass(this.__popup.getContainer("linked_objects"), "ez5-search-has-mask-with-asset-browser");
      } else {
        CUI.dom.removeClass(this.__popup.getContainer("linked_objects"), "ez5-search-has-mask-with-asset-browser");
        CUI.dom.addClass(this.__popup.getContainer("linked_objects"), "ez5-search-has-no-mask-with-asset-browser");
      }
    }
    if (this._supersearch || this._fulltext || this._token || this._exactToken || suggestions > 0) {
      this.__popup.show();
      this.__popup.autoSize();
    } else {
      this.__popup.hide();
    }
  };

  AutocompleteToken.prototype.abort = function() {
    if (this.current_search_request) {
      this.current_search_request.abort();
      this.current_search_request = null;
    }
    CUI.scheduleCallbackCancel({
      call: this.__autocompleteCall
    });
    return this;
  };

  AutocompleteToken.prototype.destroy = function() {
    return this.abort();
  };

  AutocompleteToken.prototype.hide = function() {
    this.abort();
    return this.__popup.hide();
  };

  return AutocompleteToken;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var QueryElementField,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  QueryElementField.prototype.initOpts = function() {
    QueryElementField.__super__.initOpts.call(this);
    return this.addOpts({
      data: {
        mandatory: true,
        check: 'PlainObject'
      },
      field: {
        mandatory: true,
        check: function(v) {
          return v instanceof Field || v instanceof MultipleFieldsContainer;
        }
      }
    });
  };

  QueryElementField.prototype.readOpts = function() {
    QueryElementField.__super__.readOpts.call(this);
    this.info = {
      data: this._data,
      field: this._field
    };
    return this;
  };

  QueryElementField.prototype.getSearchFilter = function() {
    if (this.validate()) {
      CUI.dom.removeClass(this.element, "cui-invalid");
      return this.info.field.getSearchFilterWithNested(this.info.data);
    } else {
      CUI.dom.addClass(this.element, "cui-invalid");
      throw new SearchInputException({
        label: "search.input.error.invalid_objecttype",
        label_attrs: {
          field: this.info.field.fullNameLocalized()
        }
      });
    }
    return null;
  };

  QueryElementField.prototype.validate = function() {
    var i, len, obj, objs, ref, ref1;
    objs = [];
    if (!this.getSearchInput()) {
      return true;
    }
    if (this.info.field instanceof LinkedObjecttype) {
      return true;
    }
    if (this.info.field instanceof MultipleFieldsContainer) {
      if (this.info.field.fields[0] instanceof LinkedObject) {
        return true;
      }
      objs = this.info.field.getObjecttypes();
    } else {
      if (this.info.field instanceof NestedTable && (this.info.field.mainMask != null)) {
        objs = [this.info.field.mainMask.table.name()];
      } else {
        objs = [this.info.field.table.name()];
      }
    }
    if (objs.length === 0) {
      return true;
    }
    ref = this.getSearchInput().getSearch().getSearchObjecttypes() || [];
    for (i = 0, len = ref.length; i < len; i++) {
      obj = ref[i];
      if (ref1 = obj.name(), indexOf.call(objs, ref1) >= 0) {
        return true;
      }
    }
    return false;
  };

  QueryElementField.prototype.getBadge = function() {
    var badgeOrBadgePromise, noInheritedBadge;
    noInheritedBadge = this.info.field.getNoInheritedQueryFieldBadge(this.info.data);
    badgeOrBadgePromise = noInheritedBadge || this.info.field.getQueryFieldBadge(this.info.data);
    if (CUI.util.isPromise(badgeOrBadgePromise)) {
      return badgeOrBadgePromise.done((function(_this) {
        return function(badge) {
          return _this.__badge = badge;
        };
      })(this));
    } else {
      return this.__badge = badgeOrBadgePromise;
    }
  };

  QueryElementField.prototype.getAsString = function() {
    if (!this.__badge) {
      return null;
    }
    return this.__badge.name + ": " + this.__badge.value;
  };

  QueryElementField.prototype.getStoreData = function() {
    var _v, i, k, len, ref, sd, v;
    sd = {
      field: this.info.field.getSignature(),
      _ot_name: this.info.field._ot_name,
      data: {}
    };
    ref = this.info.data;
    for (k in ref) {
      v = ref[k];
      if (k === '_undo' || k.startsWith('__') || k === '_DOM') {
        continue;
      }
      if (v === void 0) {
        continue;
      }
      if (CUI.util.isBoolean(v) || CUI.util.isString(v) || CUI.util.isNumber(v)) {
        sd.data[k] = v;
      } else if (CUI.util.isPlainObject(v)) {
        sd.data[k] = this.__getCleanData(v);
      } else if (v === null) {
        sd.data[k] = null;
      } else if (CUI.util.isArray(v)) {
        sd.data[k] = [];
        for (i = 0, len = v.length; i < len; i++) {
          _v = v[i];
          sd.data[k].push(this.__getCleanData(_v));
        }
      } else if (v instanceof CUI.Element) {

      } else {
        CUI.util.assert(false, "QueryElementField.getStoreData", "Unable to serialize value from object.", {
          data: this.info.data,
          value: v
        });
      }
    }
    return sd;
  };

  QueryElementField.prototype.__getCleanData = function(data, level) {
    var _data, i, item, k, len, newArray, rowCleanData, v;
    if (level == null) {
      level = 0;
    }
    if (level === 0) {
      _data = CUI.util.copyObject(data, true);
    } else {
      _data = data;
    }
    for (k in _data) {
      v = _data[k];
      if (v instanceof CUI.Element || k === '_undo' || k === '_DOM' || k.startsWith('__') || k.endsWith(':field')) {
        delete _data[k];
        continue;
      }
      if (CUI.util.isEmpty(v)) {
        delete _data[k];
        delete _data[k + ":type"];
        delete _data[k + ":mode"];
      }
      if (CUI.util.isPlainObject(v)) {
        _data[k] = this.__getCleanData(v, level + 1);
        continue;
      }
      if (CUI.util.isArray(v)) {
        newArray = [];
        for (i = 0, len = v.length; i < len; i++) {
          item = v[i];
          if (CUI.util.isPlainObject(item)) {
            if (item._new) {
              continue;
            }
            rowCleanData = this.__getCleanData(item, level + 1);
            newArray.push(rowCleanData);
          } else {
            newArray.push(item);
          }
        }
        if (newArray.length === 0) {
          delete _data[k];
        } else {
          _data[k] = newArray;
        }
        continue;
      }
    }
    return _data;
  };

  QueryElementField.newFromData = function(data) {
    var info, inst;
    inst = window[data.field["class"]].fromSignature(data.field);
    if (!(inst instanceof window[data.field["class"]])) {
      console.warn("QueryElementField.newFromData: Field could not be instantiated from data.", {
        data: data
      });
      throw "QueryElementField.newFromData: Field could not be instantiated from data.";
    }
    info = {
      field: inst,
      data: data.data
    };
    inst._ot_name = data._ot_name;
    return new QueryElementField(info);
  };

  QueryElementField.prototype.popoverContent = function() {
    var content, expert_data, fieldsRendererPlain, initial_data, opts, ref;
    this.editor_data = CUI.util.copyObjectV2(this.info.data, true);
    expert_data = {};
    expert_data[this.info.field._ot_name] = {};
    expert_data[this.info.field._ot_name][this.info.field.fullName()] = {};
    expert_data[this.info.field._ot_name][this.info.field.fullName()].data = this.editor_data;
    fieldsRendererPlain = new FieldsRendererPlain();
    fieldsRendererPlain.addField(this.info.field);
    initial_data = CUI.util.copyObjectV2(expert_data, true);
    opts = {
      mode: "expert",
      fieldRenderType: "expert",
      data: expert_data,
      search: ((ref = this.getSearchInput()) != null ? ref.getSearch() : void 0) || null,
      query_editor: true
    };
    content = fieldsRendererPlain.render(opts);
    CUI.Events.listen({
      type: ["data-changed", "search-input-change", "editor-changed"],
      node: content,
      call: (function(_this) {
        return function(ev, info) {
          if (info == null) {
            info = {};
          }
          if (CUI.util.isEqual(expert_data, initial_data)) {
            return _this.applyPopoverBtn.disable();
          } else {
            return _this.applyPopoverBtn.enable();
          }
        };
      })(this)
    });
    return content;
  };

  QueryElementField.prototype.closePopover = function(changedData) {
    if (changedData == null) {
      changedData = false;
    }
    if (changedData) {
      this.info.data = this.editor_data;
    }
    return QueryElementField.__super__.closePopover.call(this, changedData);
  };

  return QueryElementField;

})(QueryElementSpan);
// Generated by CoffeeScript 1.12.7
var QueryElementLinkedObjecttype,
  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;

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

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

  QueryElementLinkedObjecttype.prototype.getStoreDataForUrlValue = function() {
    var mask_name;
    mask_name = this.info.field.getSignature().mask.name;
    return encodeURIComponent(mask_name) + ":" + encodeURIComponent(this.info.data[this.info.field.name()][0]);
  };

  QueryElementLinkedObjecttype.getConstructorValueFromUrlValue = function(value) {
    var data, data_value, info, lot, mask_name;
    mask_name = value.split(":")[0];
    data_value = parseInt(value.split(":")[1]);
    lot = LinkedObjecttype.fromSignature({
      "class": "LinkedObjecttype",
      mask: {
        name: mask_name
      }
    });
    data = {};
    data[lot.name()] = [data_value];
    return info = {
      field: lot,
      data: data
    };
  };

  QueryElementLinkedObjecttype.prototype.validate = function() {
    return true;
  };

  QueryElementLinkedObjecttype.prototype.popoverContent = function() {};

  return QueryElementLinkedObjecttype;

})(QueryElementField);
// Generated by CoffeeScript 1.12.7
var QueryElementToken,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  QueryElementToken.prototype.getMode = function() {
    return 'token';
  };

  QueryElementToken.prototype.initOpts = function() {
    QueryElementToken.__super__.initOpts.call(this);
    return this.addOpts({
      string: {
        check: String
      },
      phrase: {
        check: Boolean
      },
      fields: {
        check: Array
      }
    });
  };

  QueryElementToken.prototype.readOpts = function() {
    QueryElementToken.__super__.readOpts.call(this);
    return this.info = {
      string: this._string,
      phrase: this._phrase
    };
  };

  QueryElementToken.prototype.getBadge = function() {
    var badge;
    badge = {
      name: ez5.loca.str_default('query.element.' + this.mode + '.name', ''),
      value: this.getDisplayString()
    };
    return badge;
  };

  QueryElementToken.prototype.getClass = function() {
    return 'query-element-token';
  };

  QueryElementToken.prototype.getSearchFilter = function() {
    var _field, boost, field, filter, i, len, ref, ref1, searchValue;
    searchValue = this.getSearchValue();
    if (this._fields) {
      filter = {
        type: 'complex',
        search: []
      };
      ref = this._fields;
      for (i = 0, len = ref.length; i < len; i++) {
        _field = ref[i];
        if (indexOf.call(_field, '^') >= 0) {
          ref1 = _field.split('^'), field = ref1[0], boost = ref1[1];
        } else {
          field = _field;
          boost = void 0;
        }
        filter.search.push({
          type: 'match',
          bool: 'should',
          boost: parseFloat(boost) || void 0,
          mode: this.getMode(),
          string: searchValue,
          phrase: this.info.phrase,
          fields: [field]
        });
      }
    } else {
      filter = {
        type: 'match',
        mode: this.getMode(),
        string: searchValue,
        phrase: this.info.phrase
      };
      if (ez5.version("6") && filter.mode === "token") {
        filter = this.__addLinkedObjectFilters(filter);
      }
    }
    return filter;
  };

  QueryElementToken.prototype.__addLinkedObjectFilters = function(filter) {
    var addedFields, complexFilter, field, i, inFilter, len, linkedFields, linkedObjecttype, nestedFilter, nestedPath, ref, ref1, search, searchFieldKey, searchValue, subsearch, subsearchFilters;
    search = (ref = this.getSearchInput()) != null ? ref.getSearch() : void 0;
    if (!search) {
      return filter;
    }
    linkedFields = search.getLinkedObjectFields("expert", true);
    if (!linkedFields || linkedFields.length === 0) {
      return filter;
    }
    searchValue = this.getSearchValue();
    subsearchFilters = [];
    addedFields = {};
    for (i = 0, len = linkedFields.length; i < len; i++) {
      field = linkedFields[i];
      searchFieldKey = field.getSearchField(false)[0];
      if (addedFields[searchFieldKey]) {
        continue;
      }
      addedFields[searchFieldKey] = true;
      linkedObjecttype = field.linkMask().table.name();
      subsearch = {
        objecttypes: [linkedObjecttype],
        field: "_global_object_id",
        search: [
          {
            type: "complex",
            search: [
              {
                type: "match",
                mode: "token",
                string: searchValue,
                phrase: this.info.phrase,
                bool: "must"
              }
            ]
          }
        ],
        limit: -1
      };
      inFilter = {
        type: "in",
        fields: field.getSearchField(false),
        bool: "should",
        subsearch: subsearch
      };
      if (field.insideNested() && ((ref1 = field.mask.nestedTableField) != null ? ref1.isNestedIndex() : void 0)) {
        nestedPath = field.path();
        nestedFilter = {
          type: "nested",
          path: nestedPath,
          bool: "should",
          search: [inFilter]
        };
        subsearchFilters.push(nestedFilter);
      } else {
        subsearchFilters.push(inFilter);
      }
    }
    if (subsearchFilters.length === 0) {
      return filter;
    }
    filter.bool = "should";
    complexFilter = {
      type: "complex",
      search: [filter].concat(subsearchFilters)
    };
    return complexFilter;
  };

  QueryElementToken.prototype.getStoreData = function() {
    return this.info;
  };

  QueryElementToken.prototype.getAsString = function() {
    return this.info.string;
  };

  QueryElementToken.prototype.getDisplayString = function() {
    return SearchUtil.wrapSingleQuotes(this.info.string);
  };

  QueryElementToken.prototype.getSearchValue = function() {
    var searchString;
    searchString = Search.getPhrase(this.info.string)[0];
    if (ez5.version("6") && this.getMode() === "token") {
      searchString = searchString.toLowerCase();
    }
    return searchString;
  };

  QueryElementToken.prototype.getStoreDataForUrlValue = function() {
    var searchValue;
    searchValue = Search.getPhrase(this.info.string)[0];
    return searchValue;
  };

  QueryElementToken.getConstructorValueFromUrlValue = function(value) {
    return {
      string: value
    };
  };

  return QueryElementToken;

})(QueryElementSpan);
// Generated by CoffeeScript 1.12.7
var QueryElementExactToken,
  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;

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

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

  QueryElementExactToken.prototype.getMode = function() {
    return 'exactToken';
  };

  QueryElementExactToken.prototype.initOpts = function() {
    QueryElementExactToken.__super__.initOpts.call(this);
    return this.addOpts({
      string: {
        check: String
      },
      phrase: {
        check: Boolean
      },
      fields: {
        check: Array
      }
    });
  };

  QueryElementExactToken.prototype.readOpts = function() {
    QueryElementExactToken.__super__.readOpts.call(this);
    return this.info = {
      string: this._string,
      phrase: this._phrase
    };
  };

  QueryElementExactToken.prototype.getBadge = function() {
    var badge, value;
    value = SearchUtil.wrapGraveAccent(this.info.string);
    badge = {
      name: ez5.loca.str_default('query.element.' + this.mode + '.name', ''),
      value: value
    };
    return badge;
  };

  QueryElementExactToken.prototype.getClass = function() {
    return 'query-element-exact-token';
  };

  QueryElementExactToken.prototype.getSearchFilter = function() {
    var filter, searchValue;
    searchValue = Search.getPhrase(this.info.string)[0];
    if (ez5.version("6")) {
      filter = {
        type: 'text',
        query: "exact",
        string: searchValue
      };
    } else {
      filter = {
        type: 'match',
        mode: 'token',
        string: searchValue,
        phrase: this.info.phrase
      };
    }
    return filter;
  };

  QueryElementExactToken.prototype.getStoreData = function() {
    return this.info;
  };

  QueryElementExactToken.prototype.getDisplayString = function() {
    return SearchUtil.wrapGraveAccent(this.info.string);
  };

  QueryElementExactToken.prototype.getAsString = function() {
    return this.info.string;
  };

  QueryElementExactToken.prototype.getStoreDataForUrlValue = function() {
    var searchValue;
    searchValue = Search.getPhrase(this.info.string)[0];
    return searchValue;
  };

  QueryElementExactToken.getConstructorValueFromUrlValue = function(value) {
    return {
      string: value
    };
  };

  return QueryElementExactToken;

})(QueryElementSpan);
// Generated by CoffeeScript 1.12.7
var QueryElementFulltext,
  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;

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

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

  QueryElementFulltext.prototype.readOpts = function() {
    var ref;
    QueryElementFulltext.__super__.readOpts.call(this);
    this.__wildcard = SearchUtil.isWildcard(this.info.string);
    this.__isWrappedWithQuotes = SearchUtil.isWrappedWithQuotes(this.info.string);
    this.__displayString = this.info.string;
    ref = Search.getPhrase(this.info.string), this.info.string = ref[0], this.info.phrase = ref[1];
    if (ez5.version("6") && !CUI.util.isEmpty(this.info.string.replace("*", ""))) {
      this.info.string = SearchUtil.wrapWithAsterisk(this.info.string);
      this.__wildcard = true;
    }
  };

  QueryElementFulltext.prototype.getBadge = function() {
    var badge;
    badge = {
      name: ez5.loca.str_default('query.element.' + this.mode + '.name', ''),
      value: this.getDisplayString()
    };
    return badge;
  };

  QueryElementFulltext.prototype.getClass = function() {
    if (this.__wildcard) {
      return 'query-element-fulltext query-element-fulltext-wildcard';
    } else {
      return 'query-element-fulltext';
    }
  };

  QueryElementFulltext.prototype.getMode = function() {
    if (ez5.version("6") && !CUI.util.isEmpty(this.info.string.replace("*", ""))) {
      return 'wildcard';
    }
    if (this.__wildcard) {
      return 'wildcard';
    } else {
      return 'fulltext';
    }
  };

  QueryElementFulltext.prototype.getDisplayString = function() {
    var displayString;
    displayString = this.__displayString;
    if (ez5.version("6") && this.__wildcard) {
      return SearchUtil.wrapWithAsterisk(displayString);
    }
    if (!this.__isWrappedWithQuotes && !this.__wildcard) {
      if (displayString.indexOf("*") === -1) {
        displayString += "*";
      }
    }
    return displayString;
  };

  QueryElementFulltext.prototype.getAsString = function() {
    return this.info.string;
  };

  QueryElementFulltext.prototype.getSearchValue = function() {
    return this.info.string;
  };

  QueryElementFulltext.prototype.getStoreData = function() {
    var data;
    data = QueryElementFulltext.__super__.getStoreData.call(this);
    if (this.__displayString && this.__displayString !== this.info.string) {
      data.string = this.__displayString;
    }
    return data;
  };

  QueryElementFulltext.prototype.getSearchFilter = function() {
    var filter, fullTextFields, i, len, objecttype, ref, ref1, ref2;
    filter = QueryElementFulltext.__super__.getSearchFilter.call(this);
    if (ez5.version("6") && ((filter != null ? filter.string : void 0) != null) && this.__wildcard) {
      filter.string = SearchUtil.wrapWithAsterisk(filter.string);
    }
    if (this.__addFullTextFields) {
      fullTextFields = ['_fulltext'];
      ref2 = ((ref = this.getSearchInput()) != null ? (ref1 = ref.getSearch()) != null ? ref1.getSearchObjecttypes() : void 0 : void 0) || [];
      for (i = 0, len = ref2.length; i < len; i++) {
        objecttype = ref2[i];
        if ((objecttype != null ? objecttype.getEASFields().length : void 0) > 0) {
          fullTextFields.push('_linked._asset.metadata_fulltext');
          break;
        }
      }
      if (this._fields) {
        filter.search.push({
          type: 'match',
          bool: 'should',
          mode: this.getMode(),
          string: this.getSearchValue(),
          phrase: this.info.phrase,
          fields: fullTextFields
        });
      } else {
        filter.fields = fullTextFields;
      }
    }
    return filter;
  };

  QueryElementFulltext.prototype.setFullTextFields = function(set) {
    return this.__addFullTextFields = set;
  };

  return QueryElementFulltext;

})(QueryElementToken);
// Generated by CoffeeScript 1.12.7
var QueryElementSuperSearch,
  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;

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

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

  QueryElementSuperSearch.prototype.initOpts = function() {
    QueryElementSuperSearch.__super__.initOpts.call(this);
    return this.addOpts({
      string: {
        check: String
      },
      tokens: {
        check: Array,
        "default": []
      },
      linked_objects: {
        check: Array,
        "default": []
      },
      fields: {
        check: Array
      }
    });
  };

  QueryElementSuperSearch.prototype.readOpts = function() {
    QueryElementSuperSearch.__super__.readOpts.call(this);
    return this.info = {
      string: this._string,
      tokens: this._tokens,
      linked_objects: this._linked_objects
    };
  };

  QueryElementSuperSearch.prototype.getMode = function() {
    return 'supersearch';
  };

  QueryElementSuperSearch.prototype.getBadge = function() {
    var badge;
    badge = {
      name: $$("query.element.supersearch.name"),
      value: this._string
    };
    return badge;
  };

  QueryElementSuperSearch.prototype.getClass = function() {
    return 'query-element-supersearch';
  };

  QueryElementSuperSearch.prototype.getSearchFilter = function() {
    var filter, fulltextFilter, fulltextString, i, j, k, len, len1, len2, linked_object, objecttype, phrase, ref, ref1, ref2, ref3, ref4, ref5, ref6, resultObject, searchParts, token, tokenData, tokenString;
    searchParts = [];
    fulltextString = this._string;
    ref = Search.getPhrase(fulltextString), fulltextString = ref[0], phrase = ref[1];
    if (ez5.version("6") && !CUI.util.isEmpty(fulltextString.replace("*", ""))) {
      fulltextString = SearchUtil.wrapWithAsterisk(fulltextString);
    }
    fulltextFilter = {
      type: 'match',
      bool: 'should',
      mode: 'wildcard',
      string: fulltextString,
      phrase: phrase
    };
    searchParts.push(fulltextFilter);
    if ((ref1 = this._tokens) != null ? ref1.length : void 0) {
      ref2 = this._tokens;
      for (i = 0, len = ref2.length; i < len; i++) {
        tokenData = ref2[i];
        if (!(tokenData != null ? (ref3 = tokenData.tokens) != null ? ref3.length : void 0 : void 0)) {
          continue;
        }
        ref4 = tokenData.tokens;
        for (j = 0, len1 = ref4.length; j < len1; j++) {
          token = ref4[j];
          if (CUI.util.isEmpty(token)) {
            continue;
          }
          tokenString = token.toLowerCase();
          searchParts.push({
            type: 'match',
            bool: 'should',
            mode: 'token',
            string: tokenString
          });
        }
      }
    }
    if ((ref5 = this._linked_objects) != null ? ref5.length : void 0) {
      ref6 = this._linked_objects;
      for (k = 0, len2 = ref6.length; k < len2; k++) {
        linked_object = ref6[k];
        resultObject = (new ResultObject()).setData(linked_object);
        objecttype = new Objecttype(resultObject.getMask());
        searchParts.push({
          type: 'in',
          bool: 'should',
          objecttype: objecttype.name(),
          "in": [resultObject.id()],
          include_path: objecttype.isHierarchy() || objecttype.isPolyhierarchy()
        });
      }
    }
    filter = {
      type: 'complex',
      search: searchParts
    };
    return filter;
  };

  QueryElementSuperSearch.prototype.getDisplayString = function() {
    return this._string;
  };

  QueryElementSuperSearch.prototype.getAsString = function() {
    return this._string;
  };

  QueryElementSuperSearch.prototype.getStoreData = function() {
    var data;
    data = {
      string: this._string,
      tokens: this._tokens,
      linked_objects: this._linked_objects
    };
    return data;
  };

  QueryElementSuperSearch.prototype.getStoreDataForUrlValue = function() {
    return this._string;
  };

  QueryElementSuperSearch.getConstructorValueFromUrlValue = function(value) {
    return {
      string: value
    };
  };

  QueryElementSuperSearch.newFromData = function(data) {
    return new QueryElementSuperSearch(data);
  };

  QueryElementSuperSearch.prototype.allowAutoExecuteSearch = function() {
    return true;
  };

  return QueryElementSuperSearch;

})(QueryElementSpan);
// Generated by CoffeeScript 1.12.7
var QueryElementBracket,
  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;

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

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

  QueryElementBracket.prototype.initOpts = function() {
    QueryElementBracket.__super__.initOpts.call(this);
    return this.addOpts({
      char: {
        mandatory: true,
        check: String
      }
    });
  };

  QueryElementBracket.prototype.readOpts = function() {
    QueryElementBracket.__super__.readOpts.call(this);
    return this.char = this._char;
  };

  QueryElementBracket.prototype.getClass = function() {
    return "query-element-bracket";
  };

  QueryElementBracket.prototype.getStoreData = function() {
    return this.getChar();
  };

  QueryElementBracket.prototype.getAsString = function() {
    return this.getChar();
  };

  QueryElementBracket.prototype.getBadge = function() {
    var c, value;
    c = this.getChar();
    switch (c) {
      case "OR":
      case "NOT":
      case "AND":
        value = $$("query.element.bracket." + c.toLowerCase());
        break;
      default:
        value = c;
    }
    return {
      value: value
    };
  };

  QueryElementBracket.prototype.getChar = function() {
    return this.char;
  };

  QueryElementBracket.prototype.allowAutoExecuteSearch = function() {
    return false;
  };

  QueryElementBracket.prototype.getStoreDataForUrlValue = function() {
    return this.char.toLowerCase();
  };

  QueryElementBracket.getConstructorValueFromUrlValue = function(value) {
    return value.toUpperCase();
  };

  QueryElementBracket.newFromData = function(data) {
    return new this({
      char: data
    });
  };

  return QueryElementBracket;

})(QueryElementSpan);
// Generated by CoffeeScript 1.12.7
var QueryElementInput,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  QueryElementInput.prototype.initOpts = function() {
    QueryElementInput.__super__.initOpts.call(this);
    return this.addOpts({
      search: {
        mandatory: true,
        check: Search
      },
      linked_objecttypes: {
        check: 'Array'
      },
      scope: {
        check: 'Array'
      },
      scope_on_return: {
        check: ["token", "fulltext"]
      },
      min_length: {
        check: function(v) {
          return v >= 1;
        }
      },
      fields: {
        check: Array
      },
      fields_suggest: {
        check: Boolean,
        "default": true
      },
      input_opts: {
        check: "PlainObject",
        "default": {}
      }
    });
  };

  QueryElementInput.prototype.readOpts = function() {
    var config, inputOpts, queryElementInput;
    QueryElementInput.__super__.readOpts.call(this);
    inputOpts = {
      contenteditable: 'true',
      spellcheck: "false"
    };
    CUI.util.mergeMap(this._input_opts, inputOpts);
    queryElementInput = CUI.dom.span('ez5-query-element-input', this._input_opts);
    this.setElement(queryElementInput);
    this.autocomplete = new AutocompletionPopup({
      element: this.element,
      "class": 'autocompletion-query-element-input'
    });
    this.request_counter = 0;
    config = ez5.session.getBaseConfig()['search.suggest.autocompletion'] || {};
    CUI.mergeMap(config, {
      autocomplete: 'one',
      scope: 'linked_objecttypes+tokens'
    });
    this.__scope = config.scope.split("+");
    switch (config.autocomplete) {
      case "one":
        this.__min_length = 1;
        break;
      case "two":
        this.__min_length = 2;
        break;
      case "three":
        this.__min_length = 3;
        break;
      default:
        this.__min_length = 1;
        this.__scope = [];
    }
    if (this._min_length) {
      this.__min_length = this._min_length;
    }
    if (this._scope) {
      this.__scope = this._scope;
    } else {
      if (indexOf.call(this.__scope, 'fulltext') < 0 && indexOf.call(this.__scope, 'token') < 0) {
        this.__scope.splice(0, 0, 'token');
        this.__scope.splice(0, 0, 'fulltext');
      }
    }
  };

  QueryElementInput.prototype.render = function() {
    this.autocomplete.hide();
    return QueryElementInput.__super__.render.call(this);
  };

  QueryElementInput.prototype.objecttypesUpdated = function() {
    return this.init();
  };

  QueryElementInput.prototype.getSearchFilter = function() {
    var filter, i, len, search, token, tokens;
    tokens = this.addInput(true);
    if (!tokens) {
      return void 0;
    }
    search = [];
    for (i = 0, len = tokens.length; i < len; i++) {
      token = tokens[i];
      search.push(token.getSearchFilter());
    }
    filter = [
      {
        type: 'complex',
        bool: 'must',
        search: search
      }
    ];
    return filter;
  };

  QueryElementInput.prototype.addInput = function(return_tokens) {
    var prefix, ql_str, value;
    if (return_tokens == null) {
      return_tokens = false;
    }
    value = this.element.textContent.trim();
    if (value.length === 0) {
      return;
    }
    if (SearchUtil.isOnlyWildcards(value)) {
      return;
    }
    prefix = typeof QueryLanguageQueryElement.getInputPrefix === "function" ? QueryLanguageQueryElement.getInputPrefix() : void 0;
    if (ez5.version("6") && prefix && value.indexOf(prefix) === 0) {
      ql_str = value.substring(prefix.length).trim();
      if (ql_str.length > 0) {
        return this.addQueryLanguage(ql_str, return_tokens);
      } else {
        return;
      }
    }
    if (value.startsWith(SearchUtil.SINGLE_QUOTE)) {
      return this.addToken(value, return_tokens);
    }
    if (value.startsWith(SearchUtil.QUOTES)) {
      value = SearchUtil.wrapQuotes(value);
      return this.addFulltext(value, return_tokens);
    }
    if (value.startsWith(SearchUtil.GRAVE_ACCENT)) {
      return this.addExactToken(value, return_tokens);
    }
    if (SearchUtil.isWildcard(value)) {
      return this.addFulltext(value, return_tokens);
    }
    switch (this._scope_on_return || this.__scope[0]) {
      case 'fulltext':
        return this.addFulltext(value, return_tokens);
      case 'token':
        return this.addToken(value, return_tokens);
    }
  };

  QueryElementInput.prototype.addQueryLanguage = function(val, return_tokens) {
    var el;
    if (return_tokens == null) {
      return_tokens = false;
    }
    if (return_tokens) {
      return;
    }
    el = new QueryLanguageQueryElement({
      string: val
    });
    return this.addElement(el);
  };

  QueryElementInput.prototype.addToken = function(val, return_tokens) {
    var tokens;
    if (return_tokens == null) {
      return_tokens = false;
    }
    tokens = this.__getTokens(val, QueryElementToken);
    if (return_tokens) {
      return tokens;
    }
    return this.__addTokens(tokens);
  };

  QueryElementInput.prototype.addExactToken = function(val, return_tokens) {
    var i, len, tokens, v;
    if (return_tokens == null) {
      return_tokens = false;
    }
    if (CUI.util.isArray(val)) {
      for (i = 0, len = val.length; i < len; i++) {
        v = val[i];
        v = v.replace(/^`/, '').replace(/`$/, '');
      }
    } else {
      val = val.replace(/^`/, '').replace(/`$/, '');
    }
    tokens = this.__getTokens(val, QueryElementExactToken);
    if (return_tokens) {
      return tokens;
    }
    return this.__addTokens(tokens);
  };

  QueryElementInput.prototype.addFulltext = function(val, return_tokens) {
    var tokens;
    if (return_tokens == null) {
      return_tokens = false;
    }
    val = val.replace(/^"\s*/, '"');
    tokens = this.__getTokens(val, QueryElementFulltext);
    if (return_tokens) {
      return tokens;
    }
    return this.__addTokens(tokens);
  };

  QueryElementInput.prototype.__check_gid_token = function(val) {
    return val.match(/^#(\d+)$/);
  };

  QueryElementInput.prototype.__check_uuid_token = function(val) {
    var cleaned;
    cleaned = val.replace(/^#\s*/, "#");
    return cleaned.match(/^#([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i);
  };

  QueryElementInput.prototype.__getTokens = function(value, typeCls) {
    var addTokens, i, len, tokens, val;
    tokens = [];
    addTokens = (function(_this) {
      return function(val) {
        var _val, gid_match, i, len, part, phrase, ref, ref1, results, uuid_match;
        ref = Search.getPhrase(val), _val = ref[0], phrase = ref[1];
        if (_val.length === 0) {
          return;
        }
        if (_val === '#') {
          return;
        }
        if (gid_match = _this.__check_gid_token(_val)) {
          return tokens.push(new QueryElementSystemObjectId({
            system_object_id: gid_match[1]
          }));
        } else if (ez5.version("6") && (uuid_match = _this.__check_uuid_token(_val))) {
          return tokens.push(new QueryElementUuid({
            uuid: uuid_match[1]
          }));
        } else if (typeCls === QueryElementExactToken) {
          return tokens.push(new typeCls({
            string: val,
            fields: _this._fields
          }));
        } else if (phrase || typeCls === QueryElementToken || !SearchUtil.SPACE_REGEXP.test(val)) {
          return tokens.push(new typeCls({
            string: val,
            fields: _this._fields
          }));
        } else {
          ref1 = _val.split(SearchUtil.SPACE_REGEXP);
          results = [];
          for (i = 0, len = ref1.length; i < len; i++) {
            part = ref1[i];
            results.push(tokens.push(new typeCls({
              string: part,
              fields: _this._fields
            })));
          }
          return results;
        }
      };
    })(this);
    if (CUI.util.isArray(value)) {
      for (i = 0, len = value.length; i < len; i++) {
        val = value[i];
        addTokens(val);
      }
    } else {
      addTokens(value);
    }
    return tokens;
  };

  QueryElementInput.prototype.__addTokens = function(tokens) {
    var at_qe, execute_search, i, idx, len, n, token;
    if (!(tokens != null ? tokens.length : void 0)) {
      return;
    }
    at_qe = this;
    n = tokens.length;
    for (idx = i = 0, len = tokens.length; i < len; idx = ++i) {
      token = tokens[idx];
      execute_search = idx === n - 1;
      at_qe = this.addElement(token, at_qe, execute_search);
    }
    return token;
  };

  QueryElementInput.prototype.init = function() {
    var all_ot_search, field, field_names, fn, i, j, k, l, len, len1, len2, len3, link_otm, linked_object, linked_objects, linked_objecttypes, lot, opts, ot_search, ref, ref1, ref2, ref3, schema, table, tn;
    this.init_done = true;
    this.current_search_request = null;
    linked_objecttypes = [];
    ot_search = this._search.getSearchObjecttypes(true);
    if (!this._linked_objecttypes) {
      all_ot_search = this._search.getSearchObjecttypes(false);
      link_otm = new ObjecttypeManager();
      link_otm.addLinkedObjectFields(this._search.getLinkedObjectFields("expert", true));
      ref = link_otm.objecttypes;
      for (i = 0, len = ref.length; i < len; i++) {
        lot = ref[i];
        ref1 = lot._linked_object_fields_by_name;
        for (fn in ref1) {
          linked_objects = ref1[fn];
          for (j = 0, len1 = linked_objects.length; j < len1; j++) {
            linked_object = linked_objects[j];
            table = linked_object.linkMask().table;
            tn = table.name();
            if (CUI.util.idxInArray(tn, all_ot_search, function(ot) {
              return ot.name() === tn;
            }) > -1) {
              continue;
            }
            if (CUI.util.idxInArray(tn, linked_objecttypes, function(ot) {
              return ot.name() === tn;
            }) > -1) {
              continue;
            }
            linked_objecttypes.push(new Objecttype(table));
          }
        }
      }
    } else {
      ref2 = this._linked_objecttypes;
      for (k = 0, len2 = ref2.length; k < len2; k++) {
        lot = ref2[k];
        schema = ez5.schema.CURRENT._table_by_name[lot];
        CUI.util.assert(schema, "QueryElementInput", "Linked Objecttype not found:" + lot, {
          linked_objecttypes: this._linked_objecttypes
        });
        linked_objecttypes.push(new Objecttype(schema));
      }
    }
    opts = {
      autocompletion_popup: this.autocomplete,
      min_length: this.__min_length,
      fields_suggest: this._fields_suggest,
      pool_ids: this._search.getSearchPoolIds(),
      objecttypes: function() {
        return ot_search;
      }
    };
    if (ez5.version("6") && ez5.session.isDebug()) {
      opts.supersearch = {
        click: (function(_this) {
          return function(val, suggestData) {
            var ref3, ref4, tokens;
            tokens = (suggestData != null ? (ref3 = suggestData.suggestions) != null ? ref3.tokens : void 0 : void 0) || [];
            linked_objects = (suggestData != null ? (ref4 = suggestData.suggestions) != null ? ref4.linked_objects : void 0 : void 0) || [];
            return _this.addElement(new QueryElementSuperSearch({
              string: val,
              tokens: tokens,
              linked_objects: linked_objects,
              fields: _this._fields
            }));
          };
        })(this)
      };
    }
    if (indexOf.call(this.__scope, 'fulltext') >= 0) {
      opts.fulltext = {
        click: (function(_this) {
          return function(val) {
            return _this.addFulltext(val);
          };
        })(this),
        getSuggestionValue: function(stringValue) {
          stringValue = SearchUtil.addWildcard(stringValue, true);
          return stringValue;
        }
      };
    }
    if (indexOf.call(this.__scope, 'token') >= 0) {
      opts.token = {
        click: (function(_this) {
          return function(val, exact) {
            if (exact == null) {
              exact = false;
            }
            if (exact) {
              return _this.addExactToken(val);
            } else {
              return _this.addToken(val);
            }
          };
        })(this)
      };
    }
    if (indexOf.call(this.__scope, 'tokens') >= 0) {
      if (this._fields) {
        field_names = [];
        ref3 = this._fields;
        for (l = 0, len3 = ref3.length; l < len3; l++) {
          field = ref3[l];
          field_names.push(field.replace(/\^[0-9]+$/, ""));
        }
      } else {
        field_names = void 0;
      }
      opts.tokens = {
        getSuggestionValue: (function(_this) {
          return function(suggestion, inputValue) {
            var previousTokens, suggestionValue;
            if (!suggestion.suggest) {
              return;
            }
            suggestion.suggest = SearchUtil.wrapSingleQuotes(suggestion.suggest);
            if (inputValue.startsWith(SearchUtil.SINGLE_QUOTE)) {
              return;
            }
            previousTokens = inputValue.split(SearchUtil.SPACE_REGEXP);
            previousTokens.pop();
            suggestionValue = previousTokens.map(function(aValue) {
              aValue = SearchUtil.removeQuotes(aValue);
              return SearchUtil.wrapSingleQuotes(aValue);
            }).join(AutocompleteToken.SPACE) + AutocompleteToken.SPACE + suggestion.suggest;
            return suggestionValue;
          };
        })(this),
        click: (function(_this) {
          return function(suggest) {
            var ate, len4, m, ref4, token;
            if (suggest.phrase) {
              return _this.addElement(new QueryElementToken({
                string: suggest.tokens.join(' '),
                phrase: true
              }));
            } else {
              ate = _this;
              ref4 = suggest.tokens;
              for (m = 0, len4 = ref4.length; m < len4; m++) {
                token = ref4[m];
                if (CUI.util.isEmpty(token)) {
                  continue;
                }
                ate = _this.addElement(new QueryElementToken({
                  string: token,
                  fields: _this._fields
                }), ate);
              }
            }
          };
        })(this),
        field_names: field_names
      };
    }
    if (indexOf.call(this.__scope, 'linked_objecttypes') >= 0) {
      opts.linked_objects = {
        objecttypes: linked_objecttypes,
        click: (function(_this) {
          return function(result_object) {
            var data, f;
            f = new LinkedObjecttype({
              objecttype: new Objecttype(result_object.getMask())
            });
            data = {};
            data[f.name()] = [result_object.id()];
            return _this.addElement(new QueryElementLinkedObjecttype({
              field: f,
              data: data
            }));
          };
        })(this)
      };
    }
    if (this.__scope[0] === "token") {
      opts.order = ["token", "fulltext"];
    }
    opts.gidToken = {
      click: (function(_this) {
        return function(val) {
          return _this.addToken(val);
        };
      })(this)
    };
    if (ez5.version("6")) {
      opts.uuidToken = {
        click: (function(_this) {
          return function(val) {
            return _this.addToken(val);
          };
        })(this)
      };
    }
    opts.boolean = {
      click: (function(_this) {
        return function(val) {
          return _this.addElement(new QueryElementBracket({
            char: val
          }));
        };
      })(this)
    };
    return this.autocomplete_token = new AutocompleteToken(opts);
  };

  QueryElementInput.prototype.isEmpty = function() {
    return this.element.textContent.trim().length === 0;
  };

  QueryElementInput.prototype.setText = function(text) {
    return this.element.textContent = text;
  };

  QueryElementInput.prototype.click = function(ev) {
    ev.stopPropagation();
  };

  QueryElementInput.prototype.focus = function(ev) {
    var ref;
    QueryElementInput.__super__.focus.call(this, ev);
    if (!this.isEmpty() && ((ref = this.autocomplete.getItems()) != null ? ref.length : void 0) > 0) {
      this.autocomplete.show();
    }
    return this;
  };

  QueryElementInput.prototype.triggerFocus = function() {
    var range, sel;
    this.element.focus();
    range = document.createRange();
    range.selectNodeContents(this.element);
    range.collapse(false);
    sel = window.getSelection();
    sel.removeAllRanges();
    try {
      sel.addRange(range);
    } catch (error) {}
    return this;
  };

  QueryElementInput.prototype.selectAllText = function() {
    var range, sel;
    range = document.createRange();
    range.selectNodeContents(this.element);
    sel = window.getSelection();
    sel.removeAllRanges();
    try {
      sel.addRange(range);
    } catch (error) {}
    return this;
  };

  QueryElementInput.prototype.blur = function(ev) {
    QueryElementInput.__super__.blur.call(this, ev);
    CUI.setTimeout((function(_this) {
      return function() {
        if (!_this.autocomplete.getActiveItem()) {
          return _this.autocomplete.hide();
        }
      };
    })(this));
  };

  QueryElementInput.prototype.keydown = function(ev) {
    var ref;
    this.autocomplete.keydown(ev);
    if (ev.isPropagationStopped()) {
      return;
    }
    this.val_on_keydown = this.element.textContent;
    if (ev.keyCode() === 65 && ev.hasModifierKey(false) && this.val_on_keydown.length > 0) {
      ev.preventDefault();
      ev.stopPropagation();
      this.selectAllText();
      return;
    }
    if (((ref = ev.keyCode()) === 37 || ref === 39) && this.val_on_keydown.length > 0) {
      ev.stopPropagation();
    }
    if (ev.keyCode() === 13) {
      ev.preventDefault();
    }
    if (ev.keyCode() === 32) {
      if (this.element.textContent.startsWith(SearchUtil.QUOTES)) {
        return;
      }
      if (this.element.textContent.length === 0 || this.element.textContent.charAt(this.element.textContent.length - 1).trim() === '') {
        ev.preventDefault();
      }
    }
  };

  QueryElementInput.prototype.paste = function() {
    var collect_text, txt;
    txt = [];
    collect_text = (function(_this) {
      return function(parent_el) {
        var i, len, node, ref, results;
        ref = parent_el.childNodes;
        results = [];
        for (i = 0, len = ref.length; i < len; i++) {
          node = ref[i];
          switch (node.nodeType) {
            case 3:
              if (node.textContent.trim().length > 0) {
                results.push(txt.push(node.textContent));
              } else {
                results.push(void 0);
              }
              break;
            case 1:
              results.push(collect_text(node));
              break;
            default:
              results.push(void 0);
          }
        }
        return results;
      };
    })(this);
    return CUI.setTimeout({
      call: (function(_this) {
        return function() {
          var prefix, ref, ref1, val;
          collect_text(_this.element);
          _this.element.textContent = txt.join(" ").replace(/\r/g, "").replace(/\n/g, " ").trim();
          prefix = typeof QueryLanguageQueryElement.getInputPrefix === "function" ? QueryLanguageQueryElement.getInputPrefix() : void 0;
          val = _this.element.textContent;
          if (ez5.version("6") && prefix && val.indexOf(prefix) === 0) {
            if ((ref = _this.autocomplete_token) != null) {
              ref.hide();
            }
            return;
          }
          return (ref1 = _this.autocomplete_token) != null ? ref1.autocomplete(val) : void 0;
        };
      })(this)
    });
  };

  QueryElementInput.prototype.keyup = function(ev) {
    var finish, prefix, ref, ref1, ref2, val;
    this.autocomplete.keyup(ev);
    if (ev.isPropagationStopped()) {
      return;
    }
    finish = (function(_this) {
      return function() {
        _this.updateSearchInput();
      };
    })(this);
    val = this.element.textContent;
    if (val === '(') {
      this.addElement(new QueryElementBracket({
        char: "("
      }));
      return finish();
    }
    if (val === ')') {
      this.addElement(new QueryElementBracket({
        char: ")"
      }));
      return finish();
    }
    if (val === ',') {
      this.addElement(new QueryElementBracket({
        char: "OR"
      }));
      return finish();
    }
    if (val === '+') {
      this.addElement(new QueryElementBracket({
        char: "AND"
      }));
      return finish();
    }
    if (val === '-') {
      this.addElement(new QueryElementBracket({
        char: "NOT"
      }));
      return finish();
    }
    if (ev.keyCode() === 27) {
      if (val.length > 0) {
        this.setEmpty();
      } else {
        this.element.blur();
      }
      return finish();
    }
    if ((val.length > 0 && ez5.version("6")) || (val.length > 0 && !val.startsWith('#'))) {
      if (ev.keyCode() === 13) {
        if (this.addInput()) {
          this._search.getSearchButton().onClickAction(ev);
          return finish();
        } else {
          return;
        }
      } else if (this.val_on_keydown !== val) {
        if (!this.init_done) {
          this.init();
        }
        prefix = typeof QueryLanguageQueryElement.getInputPrefix === "function" ? QueryLanguageQueryElement.getInputPrefix() : void 0;
        if (ez5.version("6") && prefix && val.indexOf(prefix) === 0) {
          if ((ref = this.autocomplete_token) != null) {
            ref.hide();
          }
          return finish();
        }
        if ((ref1 = this.autocomplete_token) != null) {
          ref1.autocomplete(val);
        }
        return finish();
      }
    } else {
      if ((ref2 = this.autocomplete_token) != null) {
        ref2.hide();
      }
      if (ev.keyCode() === 13) {
        this._search.getSearchButton().onClickAction(ev);
      }
      return finish();
    }
  };

  QueryElementInput.prototype.addElement = function(queryElement, atQueryElement, execute) {
    var idx, placeholder, ref, si;
    if (atQueryElement == null) {
      atQueryElement = this;
    }
    if (execute == null) {
      execute = true;
    }
    si = this.getSearchInput();
    atQueryElement.setEmpty();
    idx = si.add(queryElement, atQueryElement);
    this.autocomplete.emptyContainer();
    if ((ref = this.autocomplete_token) != null) {
      ref.hide();
    }
    placeholder = si.getPlaceholder();
    si.addAfterIdx(placeholder, idx);
    placeholder.triggerFocus();
    if (queryElement.allowAutoExecuteSearch() && execute) {
      si.execute();
    }
    return placeholder;
  };

  QueryElementInput.prototype.prepareSearch = function() {
    return this.addInput();
  };

  QueryElementInput.prototype.setEmpty = function() {
    return this.element.textContent = "";
  };

  QueryElementInput.prototype.openPopover = function() {
    var prefix, val;
    if (!this.isEmpty()) {
      prefix = typeof QueryLanguageQueryElement.getInputPrefix === "function" ? QueryLanguageQueryElement.getInputPrefix() : void 0;
      val = this.element.textContent;
      if (ez5.version("6") && prefix && val.indexOf(prefix) === 0) {
        return this.autocomplete.hide();
      } else {
        return this.autocomplete.show();
      }
    }
  };

  QueryElementInput.prototype.closePopover = function() {
    var ref;
    QueryElementInput.__super__.closePopover.call(this);
    return (ref = this.autocomplete_token) != null ? ref.hide() : void 0;
  };

  QueryElementInput.prototype.triggerAutocomplete = function(val) {
    var ref;
    if ((ref = this.autocomplete_token) != null) {
      ref.autocomplete(val);
    }
  };

  QueryElementInput.prototype.destroy = function() {
    var ref;
    if ((ref = this.autocomplete_token) != null) {
      ref.destroy();
    }
    this.autocomplete.destroy();
    return QueryElementInput.__super__.destroy.call(this);
  };

  return QueryElementInput;

})(QueryElement);
// Generated by CoffeeScript 1.12.7
var QueryElementSystemObjectId,
  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;

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

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

  QueryElementSystemObjectId.prototype.initOpts = function() {
    QueryElementSystemObjectId.__super__.initOpts.call(this);
    return this.addOpts({
      system_object_id: {
        check: String
      }
    });
  };

  QueryElementSystemObjectId.prototype.getBadge = function() {
    return {
      name: '#',
      value: this._system_object_id
    };
  };

  QueryElementSystemObjectId.prototype.getClass = function() {
    return "query-element-system-object-id";
  };

  QueryElementSystemObjectId.prototype.getSearchFilter = function() {
    var filter;
    return filter = {
      type: 'in',
      "in": [CUI.util.getInt(this._system_object_id) || -1],
      fields: ['_system_object_id']
    };
  };

  QueryElementSystemObjectId.prototype.getStoreData = function() {
    return this._system_object_id;
  };

  QueryElementSystemObjectId.prototype.getAsString = function() {
    return "#" + this._system_object_id;
  };

  QueryElementSystemObjectId.prototype.getStoreDataForUrlValue = function() {
    return this._system_object_id;
  };

  QueryElementSystemObjectId.getConstructorValueFromUrlValue = function(value) {
    return {
      system_object_id: value
    };
  };

  QueryElementSystemObjectId.newFromData = function(data) {
    return new this({
      system_object_id: data
    });
  };

  return QueryElementSystemObjectId;

})(QueryElementSpan);
// Generated by CoffeeScript 1.12.7
var QueryElementUuid,
  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;

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

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

  QueryElementUuid.prototype.initOpts = function() {
    QueryElementUuid.__super__.initOpts.call(this);
    return this.addOpts({
      uuid: {
        check: String
      }
    });
  };

  QueryElementUuid.prototype.getBadge = function() {
    return {
      name: 'UUID',
      value: this._uuid
    };
  };

  QueryElementUuid.prototype.getClass = function() {
    return "query-element-uuid";
  };

  QueryElementUuid.prototype.getSearchFilter = function() {
    var filter;
    return filter = {
      type: 'in',
      "in": [this._uuid],
      fields: ['_uuid']
    };
  };

  QueryElementUuid.prototype.getStoreData = function() {
    return this._uuid;
  };

  QueryElementUuid.prototype.getAsString = function() {
    return this._uuid;
  };

  QueryElementUuid.prototype.getStoreDataForUrlValue = function() {
    return this._uuid;
  };

  QueryElementUuid.getConstructorValueFromUrlValue = function(value) {
    return {
      uuid: value
    };
  };

  QueryElementUuid.newFromData = function(data) {
    return new this({
      uuid: data
    });
  };

  return QueryElementUuid;

})(QueryElementSpan);
// Generated by CoffeeScript 1.12.7
var QueryElementInputSearch,
  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;

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

  function QueryElementInputSearch() {
    this.executeSearch = bind(this.executeSearch, this);
    this.blur = bind(this.blur, this);
    this.click = bind(this.click, this);
    this.mouseup = bind(this.mouseup, this);
    this.selectAll = bind(this.selectAll, this);
    this.focus = bind(this.focus, this);
    return QueryElementInputSearch.__super__.constructor.apply(this, arguments);
  }

  QueryElementInputSearch.prototype.readOpts = function() {
    var input_opts;
    QueryElementInputSearch.__super__.readOpts.call(this);
    input_opts = {
      type: "text",
      spellcheck: "false",
      placeholder: this._placeholder_text
    };
    CUI.util.mergeMap(this._input_opts, input_opts);
    this.setElement(CUI.dom.$element("input", "ez5-query-element-input-search-input", this._input_opts));
    this.last_searched_val = null;
    this.__contentLayout = new CUI.HorizontalLayout({
      left: {
        content: void 0
      },
      center: {
        content: void 0
      }
    });
    return this;
  };

  QueryElementInputSearch.prototype.initOpts = function() {
    QueryElementInputSearch.__super__.initOpts.call(this);
    return this.addOpts({
      manager: {
        mandatory: true
      },
      onReset: {
        check: Function
      },
      onInputEmptied: {
        check: Function
      },
      button: {
        check: Boolean
      },
      emptyExecute: {
        check: Boolean
      },
      blockedExecute: {
        check: Boolean
      },
      placeholder_text: {
        check: String
      },
      input_opts: {
        check: "PlainObject",
        "default": {}
      }
    });
  };

  QueryElementInputSearch.prototype.__getFunc = function(_func) {
    var func, nfunc;
    nfunc = "QueryElementInputSearch.__getFunc";
    func = this._manager[_func];
    switch (_func) {
      case "autocompletion":
        CUI.util.assert(func instanceof AutocompletionPopup, nfunc, "autocompletion needs to be instance of AutocompletionPopup but is " + func + ".", {
          opts: this.opts
        });
        break;
      case "execute":
        CUI.util.assert(CUI.util.isFunction(func), nfunc, "execute needs to be Function.", {
          opts: this.opts
        });
        break;
      case "inputEmptied":
        CUI.util.assert(CUI.util.isFunction(func) || !func, "inputEmptied needs to be Function or unset.", {
          opts: this.opts
        });
    }
    return func;
  };

  QueryElementInputSearch.prototype.render = function() {
    var btn;
    if (!this._button) {
      return QueryElementInputSearch.__super__.render.call(this);
    }
    btn = new LocaButton({
      "class": "ez5-query-element-input-search-button",
      appearance: "normal",
      loca_key: "query.element.input.search.button.open_search",
      icon: "fa-angle-down",
      onClick: (function(_this) {
        return function() {
          if (_this.__getFunc("autocompletion").isShown()) {
            _this.__getFunc("autocompletion").hide();
          } else {
            _this.executeSearch();
          }
        };
      })(this)
    });
    CUI.Events.listen({
      type: "keydown",
      node: btn,
      call: (function(_this) {
        return function(ev) {
          if (ev.getKeyboard() === "Tab") {
            _this.__getFunc("autocompletion").hide();
          }
        };
      })(this)
    });
    this.__contentLayout.replace(QueryElementInputSearch.__super__.render.call(this), "center");
    return new CUI.HorizontalLayout({
      maximize: false,
      "class": "ez5-query-element-input-search",
      right: {
        content: btn
      },
      center: {
        content: this.__contentLayout
      }
    }).DOM;
  };

  QueryElementInputSearch.prototype.getSearchFilter = function() {
    var filter, val;
    val = this.value();
    if (!val.length) {
      return;
    }
    if (ez5.version("6")) {
      val = val.replaceAll("*", "").trim() + "*";
      if (!SearchUtil.isWildcard(val)) {
        return;
      }
      return filter = {
        type: "match",
        mode: "wildcard",
        phrase: val.substring(0, 1) === "\"",
        string: val
      };
    } else {
      return filter = {
        type: "match",
        phrase: val.substring(0, 1) === "\"",
        string: val
      };
    }
  };

  QueryElementInputSearch.prototype.triggerFocus = function() {
    this.__ignoreShowOnNextFocus = true;
    return QueryElementInputSearch.__super__.triggerFocus.call(this);
  };

  QueryElementInputSearch.prototype.focus = function(ev) {
    QueryElementInputSearch.__super__.focus.call(this, ev);
    if (this.blockInput) {
      if (this._blockedExecute && !this.__ignoreShowOnNextFocus) {
        this.executeSearch();
      }
      CUI.setTimeout((function(_this) {
        return function() {
          return _this.selectAll();
        };
      })(this), 0);
      this.__ignoreShowOnNextFocus = false;
      return;
    }
    if (this.__ignoreShowOnNextFocus) {
      this.__ignoreShowOnNextFocus = false;
      return;
    }
    if (this._emptyExecute) {
      return this.executeSearch();
    }
    if (!this.value().length) {
      return;
    }
    return this.__getFunc("autocompletion").show();
  };

  QueryElementInputSearch.prototype.selectAll = function() {
    return this.element.setSelectionRange(0, this.element.value.length);
  };

  QueryElementInputSearch.prototype.mouseup = function(ev) {
    if (this.blockInput) {
      this.selectAll();
      if (this._blockedExecute) {
        this.executeSearch();
      }
      return ev.preventDefault();
    }
  };

  QueryElementInputSearch.prototype.click = function(ev) {
    ev.stopPropagation();
  };

  QueryElementInputSearch.prototype.blur = function(ev) {
    var base;
    if (!this.blockInput) {
      this.__value(this.__lastValue, this.__lastIcon);
    }
    QueryElementInputSearch.__super__.blur.call(this, ev);
    return typeof (base = this.opts).onBlur === "function" ? base.onBlur(ev) : void 0;
  };

  QueryElementInputSearch.prototype.emptyInput = function(executeSearch) {
    var ref;
    if (executeSearch == null) {
      executeSearch = this._emptyExecute;
    }
    this.value("");
    if ((ref = this.__getFunc("inputEmptied")) != null) {
      ref.call(this._manager);
    }
    if (typeof this._onInputEmptied === "function") {
      this._onInputEmptied(this);
    }
    if (executeSearch) {
      return this.executeSearch();
    }
  };

  QueryElementInputSearch.prototype.keydown = function(ev) {
    var ref;
    this.__getFunc("autocompletion").keydown(ev);
    if (ev.keyCode() === 9) {
      this.__getFunc("autocompletion").hide();
      ev.stopPropagation();
      return;
    }
    if (ev.isPropagationStopped()) {
      return;
    }
    if (this.blockInput) {
      if ((ref = ev.keyCode()) === 37 || ref === 38 || ref === 39 || ref === 40) {
        this.blockInput = false;
        return;
      }
      this.emptyInput();
    }
    return this;
  };

  QueryElementInputSearch.prototype.keyup = function(ev) {
    var ref, ref1, val;
    this.__getFunc("autocompletion").keyup(ev);
    if (ev.isPropagationStopped()) {
      return;
    }
    ev.stopPropagation();
    val = this.element.value;
    if ((ref = ev.keyCode()) === 27) {
      if (this.__getFunc("autocompletion").isShown()) {
        this.__getFunc("autocompletion").hide();
      } else if (this.blockInput) {
        this.element.blur();
        return;
      } else if (this.value().length > 0) {
        this.emptyInput();
      } else {
        this.value(this.__initValue);
        if (typeof this._onReset === "function") {
          this._onReset(ev);
        }
        this.selectAll();
      }
      ev.preventDefault();
    } else if (this.blockInput) {
      return;
    } else if (!val.length && !this._emptyExecute && ((ref1 = !ev.keyCode()) === 40)) {
      this.__getFunc("autocompletion").hide();
    } else if (!this._emptyExecute && val.length === 0) {
      this.__getFunc("autocompletion").hide();
    } else {
      CUI.scheduleCallback({
        ms: 200,
        call: this.executeSearch
      });
    }
    return this;
  };

  QueryElementInputSearch.prototype.executeSearch = function() {
    var auxValue, val;
    val = this.value();
    if (CUI.util.isEmpty(val != null ? val.trim() : void 0)) {
      return;
    }
    if (this.blockInput) {
      auxValue = this.element.value;
      this.element.value = "";
      this.__getFunc("execute").call(this._manager);
      this.element.value = auxValue;
      return;
    }
    if (this.last_searched_val !== val || !this.__getFunc("autocompletion").isShown()) {
      this.last_searched_val = val;
      this.__getFunc("execute").call(this._manager);
    }
  };

  QueryElementInputSearch.prototype.__value = function(val, icon) {
    if (CUI.util.isUndef(val)) {
      return this.element.value;
    }
    if (CUI.util.isUndef(this.__initValue)) {
      this.__initValue = val;
    }
    this.element.value = val;
    if (!CUI.util.isEmpty(val)) {
      this.blockInput = true;
    } else {
      this.blockInput = false;
    }
    this.__lastValue = val;
    this.__lastIcon = icon;
    if (icon) {
      CUI.dom.addClass(this.__contentLayout, "ez5-query-element-input-icon");
      this.__contentLayout.replace(new CUI.Icon({
        "class": icon
      }), "left");
    } else {
      CUI.dom.removeClass(this.__contentLayout, "ez5-query-element-input-icon");
      this.__contentLayout.empty("left");
    }
    return val;
  };

  QueryElementInputSearch.prototype.value = function(val, icon) {
    if (CUI.util.isUndef(val)) {
      return this.element.value;
    }
    this.__value(val, icon);
    this.selectAll();
    return val;
  };

  QueryElementInputSearch.prototype.isBlocked = function() {
    return !!this.blockInput;
  };

  return QueryElementInputSearch;

})(QueryElement);
// Generated by CoffeeScript 1.12.7
var QueryElementGeoBoundingBox,
  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;

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

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

  QueryElementGeoBoundingBox.prototype.initOpts = function() {
    QueryElementGeoBoundingBox.__super__.initOpts.call(this);
    return this.addOpts({
      boundingBox: {
        check: "PlainObject",
        required: true
      }
    });
  };

  QueryElementGeoBoundingBox.prototype.readOpts = function() {
    QueryElementGeoBoundingBox.__super__.readOpts.call(this);
    return this.info = {
      boundingBox: this.opts.boundingBox
    };
  };

  QueryElementGeoBoundingBox.prototype.getBadge = function() {
    var badge;
    badge = {
      name: $$("query.element.geo"),
      value: $$("query.element.geo.value.bounding_box")
    };
    return badge;
  };

  QueryElementGeoBoundingBox.prototype.getSearchFilter = function() {
    var filter;
    filter = {
      type: "geo_bounding_box",
      field: "_standard.geo.1",
      geo_bounding_box: this._boundingBox
    };
    return filter;
  };

  QueryElementGeoBoundingBox.prototype.getStoreData = function() {
    var sd;
    return sd = {
      boundingBox: this._boundingBox
    };
  };

  QueryElementGeoBoundingBox.newFromData = function(data) {
    return new QueryElementGeoBoundingBox({
      boundingBox: data.boundingBox
    });
  };

  return QueryElementGeoBoundingBox;

})(QueryElementSpan);
// Generated by CoffeeScript 1.12.7
var QueryLanguageQueryElement,
  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;

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

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

  QueryLanguageQueryElement.getInputPrefix = function() {
    return $$("base.search.query_language.input_prefix", null, null, "?=");
  };

  QueryLanguageQueryElement.prototype.getMode = function() {
    return 'queryLanguage';
  };

  QueryLanguageQueryElement.prototype.initOpts = function() {
    QueryLanguageQueryElement.__super__.initOpts.call(this);
    return this.addOpts({
      string: {
        check: String
      }
    });
  };

  QueryLanguageQueryElement.prototype.readOpts = function() {
    QueryLanguageQueryElement.__super__.readOpts.call(this);
    this.info = {
      string: this._string
    };
    this.__resolving = false;
    this.__resolved = false;
    this.__resolved_search = null;
    this.__invalid = false;
    this.__error_text = null;
    return this.__request = null;
  };

  QueryLanguageQueryElement.prototype.setSearchInput = function(searchInput) {
    QueryLanguageQueryElement.__super__.setSearchInput.call(this, searchInput);
    if (!this.__resolved && !this.__resolving) {
      return this.__startResolve();
    }
  };

  QueryLanguageQueryElement.prototype.allowAutoExecuteSearch = function() {
    return false;
  };

  QueryLanguageQueryElement.prototype.getClass = function() {
    return 'query-element-query-language';
  };

  QueryLanguageQueryElement.prototype.getBadge = function() {
    var badge;
    badge = {
      name: 'QL',
      value: this.info.string,
      tooltip: (function(_this) {
        return function() {
          if (_this.__error_text) {
            return _this.__error_text;
          }
          return _this.info.string;
        };
      })(this)
    };
    return badge;
  };

  QueryLanguageQueryElement.prototype.getDisplayString = function() {
    var base, prefix;
    prefix = (typeof (base = this.constructor).getInputPrefix === "function" ? base.getInputPrefix() : void 0) || this.constructor.inputPrefix || 'ql:';
    return "" + prefix + this.info.string;
  };

  QueryLanguageQueryElement.prototype.getAsString = function() {
    var base, prefix;
    prefix = (typeof (base = this.constructor).getInputPrefix === "function" ? base.getInputPrefix() : void 0) || this.constructor.inputPrefix || 'ql:';
    return prefix + this.info.string;
  };

  QueryLanguageQueryElement.prototype.getStoreData = function() {
    return {
      string: this.info.string
    };
  };

  QueryLanguageQueryElement.prototype.getStoreDataForUrlValue = function() {
    return this.info.string;
  };

  QueryLanguageQueryElement.getConstructorValueFromUrlValue = function(value) {
    return {
      string: value
    };
  };

  QueryLanguageQueryElement.newFromData = function(data) {
    return new QueryLanguageQueryElement({
      string: data.string
    });
  };

  QueryLanguageQueryElement.prototype.getSearchFilter = function() {
    var filter;
    if (this.__invalid) {
      CUI.dom.addClass(this.element, 'cui-invalid');
      throw new SearchInputException({
        label: 'search.input.error.invalid_query_language'
      });
    }
    if (!this.__resolved) {
      if (!this.getSearchInput()) {
        return void 0;
      }
      throw new UserError({
        label: 'search.input.error.pending'
      });
    }
    CUI.dom.removeClass(this.element, 'cui-invalid');
    filter = {
      type: 'complex',
      search: this.__resolved_search || []
    };
    return filter;
  };

  QueryLanguageQueryElement.prototype.popoverContent = function() {
    var container;
    this.__editor_initial_data = CUI.util.copyObjectV2(this.info, true);
    this.__popover_valid = false;
    this.__popover_validating = false;
    this.__popover_request = null;
    this.__validateBound = (function(_this) {
      return function() {
        return _this.__doValidatePopoverQuery();
      };
    })(this);
    this.__status_label = new CUI.Label({
      "class": "ez5-ql-popover-status",
      multiline: true,
      icon: "spinner",
      text: ""
    });
    this.__editor = new CUI.Form({
      data: this.info,
      fields: [
        {
          type: CUI.Input,
          textarea: true,
          form: {
            label: "Query:"
          },
          name: "string"
        }
      ],
      onDataChanged: (function(_this) {
        return function() {
          return _this.__validatePopoverQuery();
        };
      })(this)
    });
    this.__editor.start();
    this.__validatePopoverQuery();
    container = new CUI.VerticalList({
      content: [this.__editor, this.__status_label]
    });
    CUI.dom.setStyle(container.DOM, {
      width: "400px"
    });
    return container;
  };

  QueryLanguageQueryElement.prototype.__validatePopoverQuery = function() {
    return CUI.scheduleCallback({
      ms: 300,
      call: this.__validateBound
    });
  };

  QueryLanguageQueryElement.prototype.__doValidatePopoverQuery = function() {
    var e, payload, query, ref, ref1;
    query = (this.info.string || '').trim();
    if (CUI.util.isEmpty(query)) {
      this.__popover_valid = false;
      this.__popover_validating = false;
      this.__status_label.setText("");
      this.__status_label.setIcon(null);
      CUI.dom.removeClass(this.__status_label.DOM, "ez5-ql-popover-status-error");
      CUI.dom.removeClass(this.__status_label.DOM, "ez5-ql-popover-status-ok");
      if ((ref = this.applyPopoverBtn) != null) {
        ref.disable();
      }
      return;
    }
    try {
      if ((ref1 = this.__popover_request) != null) {
        ref1.abort();
      }
    } catch (error) {
      e = error;
      0;
    }
    this.__popover_validating = true;
    this.__status_label.setText($$("base.search.query_language.validating"));
    this.__status_label.setIcon("spinner");
    CUI.dom.removeClass(this.__status_label.DOM, "ez5-ql-popover-status-error");
    CUI.dom.removeClass(this.__status_label.DOM, "ez5-ql-popover-status-ok");
    payload = {
      query: query,
      search: false
    };
    return this.__popover_request = ez5.api.search({
      api: "/parse",
      json_data: payload,
      success: (function(_this) {
        return function(data) {
          var ref2;
          _this.__popover_validating = false;
          _this.__popover_valid = true;
          _this.__popover_resolved_search = (data != null ? data.search : void 0) || [];
          _this.__status_label.setText("");
          _this.__status_label.setIcon(null);
          CUI.dom.removeClass(_this.__status_label.DOM, "ez5-ql-popover-status-error");
          CUI.dom.removeClass(_this.__status_label.DOM, "ez5-ql-popover-status-ok");
          return (ref2 = _this.applyPopoverBtn) != null ? ref2.enable() : void 0;
        };
      })(this),
      error: (function(_this) {
        return function(xhr) {
          var err, ref2, ref3, ref4;
          _this.__popover_validating = false;
          _this.__popover_valid = false;
          try {
            err = (xhr != null ? (ref2 = xhr.responseJSON) != null ? ref2.error : void 0 : void 0) || (xhr != null ? (ref3 = xhr.responseJSON) != null ? ref3.message : void 0 : void 0) || (xhr != null ? xhr.statusText : void 0) || 'Invalid query';
          } catch (error) {
            e = error;
            err = 'Invalid query';
          }
          _this.__status_label.setText(err);
          _this.__status_label.setIcon("fa-warning");
          CUI.dom.addClass(_this.__status_label.DOM, "ez5-ql-popover-status-error");
          CUI.dom.removeClass(_this.__status_label.DOM, "ez5-ql-popover-status-ok");
          return (ref4 = _this.applyPopoverBtn) != null ? ref4.disable() : void 0;
        };
      })(this)
    });
  };

  QueryLanguageQueryElement.prototype.closePopover = function(changedData) {
    var e, ref, ref1;
    if (changedData == null) {
      changedData = false;
    }
    try {
      if ((ref = this.__popover_request) != null) {
        ref.abort();
      }
    } catch (error) {
      e = error;
      0;
    }
    if (this.__validateBound) {
      CUI.scheduleCallbackCancel({
        call: this.__validateBound
      });
    }
    if (changedData && this.__popover_valid) {
      this.__resolved = true;
      this.__resolved_search = this.__popover_resolved_search || [];
      this.__invalid = false;
      this.__error_text = null;
      CUI.dom.removeClass(this.element, 'cui-invalid');
      QueryLanguageQueryElement.__super__.closePopover.call(this, false);
      this.render();
      this.updateSearchInput();
      if ((ref1 = this.getSearchInput()) != null) {
        ref1.execute();
      }
      return;
    } else {
      this.info = this.__editor_initial_data;
    }
    delete this.__editor_initial_data;
    delete this.__popover_valid;
    delete this.__popover_validating;
    delete this.__popover_request;
    delete this.__popover_resolved_search;
    delete this.__status_label;
    delete this.__editor;
    delete this.__validateBound;
    QueryLanguageQueryElement.__super__.closePopover.call(this, false);
  };

  QueryLanguageQueryElement.prototype.__startResolve = function() {
    var e, payload, ref, ref1;
    if (this.__resolving || CUI.util.isEmpty((ref = this.info) != null ? ref.string : void 0)) {
      return;
    }
    this.__resolving = true;
    this.__invalid = false;
    this.__error_text = null;
    try {
      if ((ref1 = this.__request) != null) {
        ref1.abort();
      }
    } catch (error) {
      e = error;
      0;
    }
    payload = {
      query: this.info.string,
      search: false
    };
    this.__request = ez5.api.search({
      api: "/parse",
      json_data: payload,
      success: (function(_this) {
        return function(data) {
          var ref2;
          _this.__resolving = false;
          _this.__resolved = true;
          _this.__resolved_search = (data != null ? data.search : void 0) || [];
          CUI.dom.removeClass(_this.element, 'cui-invalid');
          _this.updateSearchInput();
          return (ref2 = _this.getSearchInput()) != null ? ref2.execute() : void 0;
        };
      })(this),
      error: (function(_this) {
        return function(xhr) {
          var err, ref2, ref3;
          _this.__resolving = false;
          _this.__resolved = false;
          _this.__invalid = true;
          try {
            err = (xhr != null ? (ref2 = xhr.responseJSON) != null ? ref2.error : void 0 : void 0) || (xhr != null ? (ref3 = xhr.responseJSON) != null ? ref3.message : void 0 : void 0) || (xhr != null ? xhr.statusText : void 0) || 'Invalid query language';
          } catch (error) {
            e = error;
            err = 'Invalid query language';
          }
          _this.__error_text = err;
          CUI.dom.addClass(_this.element, 'cui-invalid');
          return _this.updateSearchInput();
        };
      })(this)
    });
  };

  QueryLanguageQueryElement.prototype.destroy = function() {
    var e, ref;
    try {
      if ((ref = this.__request) != null) {
        ref.abort();
      }
    } catch (error) {
      e = error;
      0;
    }
    return QueryLanguageQueryElement.__super__.destroy.call(this);
  };

  return QueryLanguageQueryElement;

})(QueryElementSpan);
// Generated by CoffeeScript 1.12.7
var SearchToken,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function SearchToken() {
    this.__setModeWithoutSuggestion = bind(this.__setModeWithoutSuggestion, this);
    this.keyup = bind(this.keyup, this);
    this.keydown = bind(this.keydown, this);
    this.paste = bind(this.paste, this);
    return SearchToken.__super__.constructor.apply(this, arguments);
  }

  SearchToken.prototype.initOpts = function() {
    SearchToken.__super__.initOpts.call(this);
    return this.addOpts({
      column: {
        mandatory: true,
        check: Field
      },
      data: {
        mandatory: true,
        check: "PlainObject"
      },
      fields: {
        check: "Array"
      },
      types: {
        check: "Array",
        "default": ["fulltext", "token", "tokens", "fields"]
      },
      placeholder: {
        check: String
      },
      tokenize: {
        "default": true,
        check: Boolean
      },
      supportsRange: {
        "default": true,
        check: Boolean
      }
    });
  };

  SearchToken.prototype.readOpts = function() {
    var el_opts, f, field_names, field_opts, i, len, objecttypes, opts, ref;
    SearchToken.__super__.readOpts.call(this);
    el_opts = this._column.getElementOpts("expert");
    el_opts.onDataChanged = (function(_this) {
      return function() {
        return CUI.Events.trigger({
          node: _this.__input,
          type: "search-input-change"
        });
      };
    })(this);
    el_opts.data = this._data;
    el_opts.incNumbers = false;
    el_opts.placeholder = this._placeholder;
    el_opts.maximize_horizontal = true;
    this.__input = CUI.DataField["new"](el_opts).start();
    this.setElement(this.__input.getElement());
    this.setModeInData("fulltext");
    this.setTypeInData("fulltext");
    this.autocomplete = new AutocompletionPopup({
      element: this.getElement()
    });
    this.__tokenizer = this._column.getTokenizer();
    field_opts = {};
    if (this._fields) {
      objecttypes = (function() {
        var i, len, ref, results;
        ref = this._fields;
        results = [];
        for (i = 0, len = ref.length; i < len; i++) {
          f = ref[i];
          results.push(new Objecttype(f.getMainMask()));
        }
        return results;
      }).call(this);
      field_names = [];
      ref = this._fields;
      for (i = 0, len = ref.length; i < len; i++) {
        f = ref[i];
        field_names.push.apply(field_names, f.getFieldNamesForSuggest());
        CUI.util.mergeMap(field_opts, f.getFieldOptsForSuggest());
      }
      field_names = arrayUnique(field_names);
    } else {
      objecttypes = [new Objecttype(this._column.getMainMask())];
      field_names = this._column.getFieldNamesForSuggest();
      field_opts = this._column.getFieldOptsForSuggest();
    }
    opts = {
      autocompletion_popup: this.autocomplete,
      objecttypes: objecttypes
    };
    if (indexOf.call(this._types, "fulltext") >= 0) {
      opts.fulltext = {
        click: (function(_this) {
          return function(value) {
            _this.element.value = value;
            return _this.__applyFulltext(value);
          };
        })(this),
        getSuggestionValue: (function(_this) {
          return function(value) {
            var base, label, rangeValue, suggestionValues, tokenValue;
            if (_this.__isRange(_this.element.value) || _this.__isComma(_this.element.value)) {
              rangeValue = _this.__getSuggestDisplayValue(null, false, true);
              label = _this.__isRange(_this.element.value) ? $$("autocomplete.categories.tokens.range") : $$("autocomplete.categories.tokens.comma-fulltext");
              suggestionValues = [
                {
                  value: rangeValue,
                  label: label
                }
              ];
              tokenValue = _this.__getSuggestDisplayValue(null, false, false, true);
              if (rangeValue !== tokenValue) {
                suggestionValues.push({
                  value: tokenValue,
                  label: $$("autocomplete.categories.tokens.comma")
                });
              }
              return suggestionValues;
            } else {
              if (typeof (base = _this._column).allowFullWildcard === "function" ? base.allowFullWildcard() : void 0) {
                value = SearchUtil.wrapWithAsterisk(value);
              } else {
                value = SearchUtil.addWildcard(value);
              }
              return value;
            }
          };
        })(this)
      };
    }
    if (indexOf.call(this._types, "token") >= 0) {
      opts.token = {
        click: (function(_this) {
          return function(value, exactToken) {
            if (exactToken == null) {
              exactToken = false;
            }
            if (CUI.util.isArray(value)) {
              value = value.join(AutocompleteToken.SPACE);
            }
            if (exactToken) {
              return _this.__applyExactToken(value);
            }
            return _this.__applyToken(value);
          };
        })(this),
        getSuggestionValue: (function(_this) {
          return function(value) {
            if (_this.__isRange(_this.element.value) || _this.__isComma(_this.element.value)) {
              return false;
            }
            return SearchUtil.wrapSingleQuotes(value);
          };
        })(this),
        addExactToken: ez5.version("6")
      };
    }
    if (indexOf.call(this._types, "tokens") >= 0) {
      opts.tokens = {
        field_names: field_names,
        field_opts: field_opts,
        click: (function(_this) {
          return function(suggest) {
            return _this.__applyTokens(suggest);
          };
        })(this),
        getSuggestionValue: (function(_this) {
          return function(suggest) {
            return _this.__getSuggestDisplayValue(suggest, true, true);
          };
        })(this),
        getSuggestionLabel: (function(_this) {
          return function(value) {
            if (_this.__isComma(value) && SearchUtil.isWrappedWithSingleQuotes(value)) {
              return $$("autocomplete.categories.tokens.comma");
            }
          };
        })(this)
      };
    }
    if (indexOf.call(this._types, "fields") >= 0) {
      opts.fields = {
        field_names: field_names,
        field_opts: field_opts,
        click: (function(_this) {
          return function(suggest) {
            return _this.__applyFields(suggest);
          };
        })(this)
      };
    }
    return this.autocomplete_token = new AutocompleteToken(opts);
  };

  SearchToken.prototype.paste = function(ev) {
    CUI.setTimeout({
      call: (function(_this) {
        return function() {
          _this.__setModeWithoutSuggestion();
          return _this.autocomplete.keyup(ev);
        };
      })(this)
    });
  };

  SearchToken.prototype.keydown = function(ev) {
    this.autocomplete.keydown(ev);
  };

  SearchToken.prototype.keyup = function(ev) {
    var c, ref, token;
    this.autocomplete.keyup(ev);
    if (ev.isPropagationStopped()) {
      return;
    }
    ev.stopPropagation();
    c = this.getCursor();
    if (c !== null) {
      token = this.getCurrentToken();
    }
    if (c === null || !token.token.length || ((ref = ev.keyCode()) === 27)) {
      this.autocomplete_token.hide();
    } else if (token.token !== this.last_token) {
      this.autocomplete_token.autocomplete(token.token);
    }
    if (token) {
      this.last_token = token.token;
    }
    this.__setModeWithoutSuggestion();
  };

  SearchToken.prototype.getCurrentToken = function() {
    var c, i, len, ref, token, val;
    val = this.element.value;
    if (!this._tokenize) {
      return {
        token: val,
        raw_token: val
      };
    }
    c = this.getCursor();
    if (!this.__tokenizer) {
      return {
        start: 0,
        end: val.length - 1,
        token: val
      };
    }
    ref = this.__tokenizer.getTokens(val);
    for (i = 0, len = ref.length; i < len; i++) {
      token = ref[i];
      if (token.start <= c && c <= token.end) {
        if (token.exact) {
          token.token = SearchUtil.GRAVE_ACCENT + token.token + SearchUtil.GRAVE_ACCENT;
        } else if (token.phrase) {
          token.token = SearchUtil.QUOTES + token.token + SearchUtil.QUOTES;
        }
        return token;
      }
    }
    return {
      token: "",
      raw_token: ""
    };
  };

  SearchToken.prototype.__getSuggestDisplayValue = function(suggest, html, isRange, forceWrapToken) {
    var allTokens, currentToken, elementValue, i, lastToken, len, nextToken, prevToken, suggestValue, token, tokenIdx, tokenToAdd, tokens, tokensLeft, tokensRight;
    if (suggest == null) {
      suggest = null;
    }
    if (html == null) {
      html = false;
    }
    if (isRange == null) {
      isRange = false;
    }
    if (forceWrapToken == null) {
      forceWrapToken = false;
    }
    elementValue = this.element.value;
    currentToken = this.getCurrentToken();
    if (!CUI.util.isNull(suggest)) {
      if (suggest.suggest && suggest.tokens) {
        tokens = CUI.util.copyObject(suggest.tokens, true);
        lastToken = tokens.pop();
        if (tokens.length > 0) {
          suggestValue = tokens.join(AutocompleteToken.SPACE) + AutocompleteToken.SPACE + (html ? suggest.suggest : lastToken);
        } else {
          suggestValue = html ? suggest.suggest : lastToken;
        }
      } else {
        suggestValue = currentToken.token;
      }
      suggestValue = SearchUtil.wrapSingleQuotes(suggestValue);
    } else {
      suggestValue = forceWrapToken ? SearchUtil.wrapSingleQuotes(currentToken.token) : currentToken.raw_token;
    }
    if (!this.__tokenizer || !this._tokenize) {
      return suggestValue;
    }
    tokensLeft = [];
    tokensRight = [];
    allTokens = this.__tokenizer.getTokens(elementValue);
    for (tokenIdx = i = 0, len = allTokens.length; i < len; tokenIdx = ++i) {
      token = allTokens[tokenIdx];
      if (currentToken.start === token.start && currentToken.end === token.end) {
        continue;
      }
      if (token.range) {
        if (isRange) {
          tokenToAdd = Tokenizer.SPACE + Tokenizer.DASH + Tokenizer.SPACE;
        } else {
          tokenToAdd = Tokenizer.COMMA;
        }
      } else if (token.comma) {
        tokenToAdd = Tokenizer.COMMA;
      } else if (token.space) {
        prevToken = allTokens[tokenIdx - 1];
        nextToken = allTokens[tokenIdx + 1];
        if (prevToken && nextToken && !prevToken.range && !prevToken.comma && !prevToken.space && !nextToken.range && !nextToken.comma && !nextToken.space) {
          tokenToAdd = Tokenizer.SPACE;
        } else {
          continue;
        }
      } else {
        tokenToAdd = forceWrapToken ? SearchUtil.wrapSingleQuotes(token.token) : token.raw_token;
      }
      if (currentToken.start >= token.end) {
        tokensLeft.push(tokenToAdd);
      } else {
        tokensRight.push(tokenToAdd);
      }
    }
    return tokensLeft.join("") + suggestValue + tokensRight.join("");
  };

  SearchToken.prototype.__isRange = function(value) {
    return value && this.__tokenizer && this.__tokenizer.getTokens(value).some(function(token) {
      return token.range && token.start !== 0 && token.end !== value.length;
    });
  };

  SearchToken.prototype.__isComma = function(value) {
    return value && this.__tokenizer && this.__tokenizer.getTokens(value).some(function(token) {
      return token.comma && token.start !== 0 && token.end !== value.length;
    });
  };

  SearchToken.prototype.__getFieldsSuggest = function(suggest) {
    var mode, token, token_in, type, val;
    val = this.element.value;
    token = this.getCurrentToken();
    if (suggest.tokens) {
      token_in = suggest.tokens.join(" ");
      if (suggest.phrase) {
        token_in = "\"" + token_in + "\"";
      }
      mode = "token";
      type = "token";
    } else {
      token_in = "\"" + suggest.field + "\"";
      mode = "fulltext";
      type = "field";
    }
    if (this._tokenize) {
      val = val.substr(0, token.start) + token_in + val.substr(token.end + 1);
    } else {
      val = token_in;
    }
    return {
      token: token,
      token_in: token_in,
      mode: mode,
      type: type,
      val: val
    };
  };

  SearchToken.prototype.__applyFields = function(suggest) {
    var c, fieldsSuggest;
    if (!suggest) {
      return;
    }
    fieldsSuggest = this.__getFieldsSuggest(suggest);
    this.element.value = fieldsSuggest.val;
    this.__input.storeValue(fieldsSuggest.val);
    this.setModeInData(fieldsSuggest.mode);
    this.setTypeInData(fieldsSuggest.type);
    c = fieldsSuggest.token.start + fieldsSuggest.token_in.length + 1;
    this.element.setSelectionRange(c, c);
    this.autocomplete_token.hide();
    CUI.Events.trigger({
      node: this.__input,
      type: "search-input-change"
    });
    return this;
  };

  SearchToken.prototype.__applyTokens = function(suggest) {
    var mode, value;
    if (!suggest) {
      return;
    }
    this.__setBadgeInData(suggest);
    value = this.__getSuggestDisplayValue(suggest);
    if (this._supportsRange && (this.__isRange(value) || this.__isComma(value) && !SearchUtil.isWrappedWithSingleQuotes(value))) {
      mode = "range";
    } else {
      mode = "token";
    }
    this.element.value = value;
    this.__input.storeValue(value);
    this.setModeInData(mode);
    this.setTypeInData("token");
    this.autocomplete_token.hide();
    CUI.Events.trigger({
      node: this.__input,
      type: "search-input-change"
    });
    return this;
  };

  SearchToken.prototype.__applyToken = function(value) {
    if (!value) {
      return;
    }
    value = Search.getPhrase(value)[0];
    this.element.value = SearchUtil.wrapSingleQuotes(value);
    this.__input.storeValue(this.element.value);
    this.setModeInData("token");
    this.setTypeInData("token");
    this.autocomplete_token.hide();
    CUI.Events.trigger({
      node: this.__input,
      type: "search-input-change"
    });
    return this;
  };

  SearchToken.prototype.__applyExactToken = function(value) {
    if (!value) {
      return;
    }
    value = Search.getPhrase(value)[0];
    this.element.value = SearchUtil.wrapGraveAccent(value);
    this.__input.storeValue(this.element.value);
    this.setModeInData("exact");
    this.setTypeInData("exact");
    this.autocomplete_token.hide();
    CUI.Events.trigger({
      node: this.__input,
      type: "search-input-change"
    });
    return this;
  };

  SearchToken.prototype.__applyFulltext = function(value) {
    var isWrappedWithAsterisk, isWrappedWithQuotes, mode, phrase, ref, v;
    if (!value) {
      return;
    }
    mode = this.__setModeWithoutSuggestion();
    if (mode === "range") {
      this.element.value = this.__getSuggestDisplayValue(null, false, true);
    } else {
      isWrappedWithAsterisk = SearchUtil.isWrappedWithAsterisk(value);
      isWrappedWithQuotes = SearchUtil.isWrappedWithQuotes(value);
      ref = Search.getPhrase(value), value = ref[0], phrase = ref[1];
      if (isWrappedWithQuotes) {
        if (isWrappedWithAsterisk) {
          v = SearchUtil.unwrapAsterisk(value);
          v = SearchUtil.wrapQuotes(v);
          v = SearchUtil.wrapWithAsterisk(v);
          this.element.value = v;
        } else {
          this.element.value = SearchUtil.wrapQuotes(value);
        }
      } else {
        this.element.value = value;
      }
      this.setTypeInData("fulltext");
    }
    this.__input.storeValue(this.element.value);
    this.autocomplete_token.hide();
    CUI.Events.trigger({
      node: this.__input,
      type: "search-input-change"
    });
    return this;
  };

  SearchToken.prototype.__setModeWithoutSuggestion = function() {
    var value;
    value = this.element.value;
    if (this._supportsRange && (this.__isRange(value) || this.__isComma(value))) {
      this.__setBadgeInData();
      return this.setModeInData("range");
    } else {
      delete this._data[this._column.name() + ":badge"];
      if (value.length > SearchUtil.SEARCH_MAX_LENGTH) {
        value = value.substring(0, SearchUtil.SEARCH_MAX_LENGTH);
        this.__input.storeValue(value);
      }
      if (value.startsWith(SearchUtil.GRAVE_ACCENT)) {
        this.__input.storeValue(SearchUtil.wrapGraveAccent(value));
        this.setModeInData("exact");
        this.setTypeInData("exact");
      } else if (value.startsWith(SearchUtil.SINGLE_QUOTE)) {
        this.__input.storeValue(SearchUtil.wrapSingleQuotes(value));
        this.setModeInData("token");
        this.setTypeInData("token");
      } else {
        if (value.startsWith(SearchUtil.QUOTES)) {
          this.__input.storeValue(SearchUtil.wrapQuotes(value));
        }
        if (SearchUtil.isWildcard(value)) {
          this.setModeInData("wildcard");
        } else {
          this.setModeInData("fulltext");
        }
        this.setTypeInData("fulltext");
      }
    }
  };

  SearchToken.prototype.__setBadgeInData = function(suggest) {
    return this.__setTextBadgeInData(this.__getSuggestDisplayValue(suggest, false, true));
  };

  SearchToken.prototype.__setTextBadgeInData = function(displayText) {
    return this._data[this._column.name() + ":badge"] = displayText;
  };

  SearchToken.prototype.setModeInData = function(mode) {
    return this._data[this._column.name() + ":mode"] = mode;
  };

  SearchToken.prototype.setTypeInData = function(mode) {
    return this._data[this._column.name() + ":type"] = mode;
  };

  SearchToken.prototype.getTypeInData = function() {
    return this._data[this._column.name() + ":type"];
  };

  SearchToken.prototype.getInput = function() {
    return this.__input;
  };

  return SearchToken;

})(QueryElement);
// Generated by CoffeeScript 1.12.7
var Collection,
  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;

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

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

  Collection.prototype.initOpts = function() {
    Collection.__super__.initOpts.call(this);
    return this.addOpts({
      collection: {
        check: "PlainObject"
      },
      readonly: {
        check: Boolean,
        "default": false
      }
    });
  };

  Collection.prototype.readOpts = function() {
    Collection.__super__.readOpts.call(this);
    this.setData(this._collection);
    CUI.util.assert(CUI.util.isArray(this.data._objects) || CUI.util.isNull(this.data._objects), "new " + (CUI.util.getObjectClass(this)), "data._objects needs to be null or an Array", {
      data: this.data
    });
    return this.eventDiv = CUI.dom.div();
  };

  Collection.prototype.on = function(opts) {
    if (opts == null) {
      opts = {};
    }
    CUI.util.assert(CUI.util.isPlainObject(opts), "Collection.on", "opts needs to be plain object.", {
      opts: opts
    });
    opts.node = this.eventDiv;
    return CUI.Events.listen(opts);
  };

  Collection.prototype.off = function(opts) {
    if (opts == null) {
      opts = {};
    }
    CUI.util.assert(CUI.util.isPlainObject(opts), "Collection.off", "opts needs to be plain object.", {
      opts: opts
    });
    return CUI.Events.ignore(opts, this.eventDiv, true);
  };

  Collection.prototype.getCollectionDisplayname = function() {
    return this.getData().collection.displayname;
  };

  Collection.prototype.triggerEvent = function(type, info) {
    var ret;
    if (info == null) {
      info = {};
    }
    info.collection = this;
    info.type = type;
    ret = CUI.Events.trigger({
      type: type,
      node: this.eventDiv,
      info: info
    });
    CUI.util.assert(CUI.util.isPromise(ret) || CUI.util.isUndef(ret), "Collection.triggerEvent", "Event " + type + " must return Promise or undefined.", {
      "return": ret
    });
    if (!ret) {
      return CUI.resolvedPromise();
    } else {
      return ret;
    }
  };

  Collection.prototype.setData = function(data) {
    this.data = data != null ? data : {
      collection: {}
    };
    if (CUI.util.isUndef(this.data._objects)) {
      this.data._objects = [];
    }
    return this;
  };

  Collection.prototype.addedToListView = function(DOMNodes) {
    Collection.__super__.addedToListView.call(this, DOMNodes);
    CUI.dom.setAttribute(DOMNodes[0], "tabindex", "0");
    CUI.dom.setAttribute(DOMNodes[0], "tabindex-prevent-default", true);
    if (this._readonly) {
      return this;
    }
    CUI.Events.listen({
      node: DOMNodes[0],
      type: "toolbox",
      call: (function(_this) {
        return function(ev, info) {
          if (!_this.isSelected()) {
            DOMNodes[0].focus();
          }
          return _this.prepareCurrentTools().done(function() {
            return info.tools.push.apply(info.tools, _this.getCurrentTools());
          });
        };
      })(this)
    });
    return this;
  };

  Collection.prototype.prepareCurrentTools = function() {
    return CUI.resolvedPromise();
  };

  Collection.prototype.select = function(ev) {
    var ref;
    if (ev instanceof CUI.MouseEvent) {
      if ((ref = CUI.dom.find(":focus")[0]) != null) {
        ref.blur();
      }
    }
    return Collection.__super__.select.call(this, ev);
  };

  Collection.prototype.getData = function() {
    return this.data;
  };

  Collection.prototype.canHaveChildren = function() {
    return this.data.collection.children_allowed;
  };

  Collection.prototype.isCreateChildAllowed = function() {
    return false;
  };

  Collection.prototype.isDeletable = function() {
    return false;
  };

  Collection.prototype.canUnlink = function() {
    return true;
  };

  Collection.prototype.isSearchable = function() {
    return false;
  };

  Collection.prototype.enableShare = function() {
    return false;
  };

  Collection.prototype.enableSettings = function() {
    return false;
  };

  Collection.prototype.bigIcon = function() {
    return this.icon();
  };

  Collection.prototype.icon = function() {};

  Collection.prototype.getOwner = function() {
    if (this.data._owner) {
      return User.newInstance({
        user: this.data._owner
      });
    } else {
      return null;
    }
  };

  Collection.prototype.getCurrentTools = function() {
    var i, len, plugin, ref, tools;
    tools = [];
    ref = Collection.__plugins;
    for (i = 0, len = ref.length; i < len; i++) {
      plugin = ref[i];
      tools.push.apply(tools, plugin.getCurrentTools(this));
    }
    return tools;
  };

  Collection.__plugins = [];

  Collection.registerPlugin = function(plugin) {
    CUI.util.assert(plugin instanceof CollectionPlugin, 'Collection.registerPlugin', 'Plugin needs to be instance of CollectionPlugin.');
    return this.__plugins.push(plugin);
  };

  Collection.prototype.getToolGroup = function() {
    return this.getToolNamePrefix();
  };

  Collection.prototype.getToolNamePrefix = function() {
    return "collection";
  };

  Collection.prototype.getButtonbar = function() {
    return Toolbox.getFlyoutButtonbar(this.getCurrentTools());
  };

  Collection.prototype.getButtons = function() {
    return Toolbox.getFlyoutButtons(this.getCurrentTools());
  };

  Collection.prototype.getObjects = function() {
    return CUI.util.assert(false, (CUI.util.getObjectClass(this)) + ".getObjects needs implementation");
  };

  Collection.prototype.getCount = function() {
    return CUI.util.assert(false, (CUI.util.getObjectClass(this)) + ".getCount needs implementation");
  };

  Collection.prototype.getBareCount = function() {
    return this.getCount();
  };

  Collection.prototype.getDescription = function() {};

  Collection.prototype.getInfo = function() {
    var description, lbl, user;
    description = this.getDescription();
    if (CUI.util.isEmpty(description)) {
      lbl = new CUI.EmptyLabel({
        "class": "ez5-collection-description ez5-collection-no-description",
        text: $$("collection.no_description")
      });
    } else {
      lbl = new CUI.MultilineLabel({
        "class": "ez5-collection-description",
        text: description
      });
    }
    user = this.getOwner();
    if (!user || user.getId() === ez5.session.getUser().getId()) {
      if (CUI.util.isEmpty(description)) {
        return null;
      }
      return lbl;
    }
    return [
      lbl, new LocaLabel({
        "class": "ez5-collection-shared-by",
        loca_key: "collection.shared_by_user",
        loca_key_attrs: {
          user: user.getDisplayText()
        }
      })
    ];
  };

  Collection.prototype.render = function() {
    Collection.__super__.render.call(this);
    if (this.__handleDiv) {
      CUI.dom.setAttribute(this.__handleDiv, "ui", "collection.handle");
    }
    return this;
  };

  Collection.prototype.renderContent = function() {
    this.contentLabel = this.createContentLabel();
    new CUI.Tooltip({
      element: this.contentLabel,
      text: (function(_this) {
        return function() {
          return _this.renderNameAsText();
        };
      })(this)
    });
    CUI.Events.listen({
      type: "click",
      node: this.contentLabel,
      call: (function(_this) {
        return function(ev) {
          if (ev.shiftKey()) {
            ev.stopPropagation();
            return console.debug(CUI.util.dump(_this.data));
          }
        };
      })(this)
    });
    CUI.Events.listen({
      type: "multi-input-control-update",
      node: this.contentLabel,
      call: (function(_this) {
        return function() {
          return _this.updateDisplay();
        };
      })(this)
    });
    this.counterLabel = new CUI.Label({
      "class": "collection-counter"
    });
    this.__counterColumn = new CUI.ListViewColumn({
      "class": "collection-counter-td",
      onSetElement: (function(_this) {
        return function() {
          return _this.updateContent();
        };
      })(this)
    });
    this.updateDisplay();
    this.addColumn(this.__counterColumn);
    return this.contentLabel.DOM;
  };

  Collection.prototype.createContentLabel = function() {
    return new CUI.Label({
      icon: true,
      multiline: true,
      content: ""
    });
  };

  Collection.prototype.getContent = function() {
    return [this.counterLabel];
  };

  Collection.prototype.updateContent = function() {
    var content, el, i, item, len, ref, ref1;
    el = (ref = this.__counterColumn) != null ? ref.getElement() : void 0;
    if (!el) {
      return this;
    }
    CUI.dom.empty(el);
    content = this.getContent();
    if (!content || content.length === 0) {
      return this;
    }
    ref1 = this.getContent();
    for (i = 0, len = ref1.length; i < len; i++) {
      item = ref1[i];
      if (item.DOM) {
        CUI.dom.append(el, item.DOM);
      } else {
        CUI.dom.append(el, item);
      }
    }
    return this;
  };

  Collection.prototype.updateDisplay = function() {
    this.updateContent();
    this.updateCounter();
    if (this.contentLabel) {
      this.contentLabel.setContent(CUI.dom.htmlToNodes(this.renderNameAsHtml()));
      this.contentLabel.setIcon(this.icon());
    }
    return this;
  };

  Collection.prototype.updateCounter = function() {
    return CUI.decide(this.getCount()).done((function(_this) {
      return function(__currentCount) {
        _this.__currentCount = __currentCount;
        if (!_this.counterLabel || _this.counterLabel.isDestroyed()) {
          return;
        }
        return _this.counterLabel.setText(ez5.format_number(_this.__currentCount));
      };
    })(this));
  };

  Collection.prototype.removeFromDOM = function(remove_self) {
    if (remove_self == null) {
      remove_self = true;
    }
    Collection.__super__.removeFromDOM.call(this, remove_self);
    this.counterLabel = null;
    return this;
  };

  Collection.prototype.renderNameAsText = function() {
    return CUI.util.assert(false, "Collection.renderNameAsText", "Method needs to be overwritten in " + (CUI.util.getObjectClass(this)));
  };

  Collection.prototype.renderNameAsHtml = function() {
    return CUI.util.toHtml(this.renderNameAsText());
  };

  Collection.prototype.getBadge = function() {
    return {
      icon: this.getBadgeIcon(),
      name: $$("collection.badge.name"),
      value: this.renderNameAsText()
    };
  };

  Collection.prototype.getBadgeIcon = function() {
    return null;
  };

  Collection.prototype.checkObjects = function(collection_objects) {
    var co, i, idx, len;
    CUI.util.assert(CUI.util.isArray(collection_objects), "Collection.insertObjects", "Needs to be an Array", {
      collection_objects: collection_objects
    });
    for (idx = i = 0, len = collection_objects.length; i < len; idx = ++i) {
      co = collection_objects[idx];
      CUI.util.assert(co instanceof CollectionObject, "Collection.insertObjects", "Object[" + idx + "] not an instance of CollectionObject but " + (CUI.util.getObjectClass(co)) + ".", {
        collection_objects: collection_objects
      });
    }
  };

  Collection.prototype.insertObjects = function() {
    return CUI.util.assert(false, (CUI.util.getObjectClass(this)) + ".insertObjects needs implementation");
  };

  Collection.prototype.removeObjects = function() {
    return CUI.util.assert(false, (CUI.util.getObjectClass(this)) + ".removeObjects needs implementation");
  };

  Collection.prototype.getSearchFilter = function() {
    return CUI.util.assert(false, "Collection.renderNameAsText", "Method needs to be overwritten in " + (CUI.util.getObjectClass(this)));
  };

  Collection.prototype.isSelectable = function() {
    return false;
  };

  Collection.prototype.selectOnLoad = function() {
    return this.select();
  };

  Collection.prototype.getHashId = function() {};

  Collection.prototype.reset = function() {};

  Collection.prototype.matchesLocator = function(locator) {
    return this.getHashId() === locator;
  };

  Collection.prototype.addToRequest = function(request) {};

  Collection.prototype.executeSearch = null;

  Collection.prototype.getStoreData = function() {
    throw new InvalidSaveDataException();
  };

  return Collection;

})(CUI.ListViewTreeNode);

CUI.ready((function(_this) {
  return function() {
    CUI.Events.registerEvent({
      type: "insert",
      bubble: false
    });
    CUI.Events.registerEvent({
      type: "remove",
      bubble: false
    });
    CUI.Events.registerEvent({
      type: "select",
      bubble: false
    });
    return CUI.Events.registerEvent({
      type: "update",
      bubble: false
    });
  };
})(this));
// Generated by CoffeeScript 1.12.7
var CollectionPlugin,
  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;

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

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

  CollectionPlugin.prototype.getCurrentTools = function(collection) {
    return [];
  };

  return CollectionPlugin;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var CollectionSearchNode,
  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;

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

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

  CollectionSearchNode.prototype.initOpts = function() {
    CollectionSearchNode.__super__.initOpts.call(this);
    return this.addOpts({
      manager: {
        check: CollectionManager
      },
      search: {
        check: Search
      }
    });
  };

  CollectionSearchNode.prototype.readOpts = function() {
    if (this.opts.manager) {
      this.setManager(this.opts.manager);
    }
    CollectionSearchNode.__super__.readOpts.call(this);
    if (this._search) {
      this.setSearch(this._search);
    }
  };

  CollectionSearchNode.prototype.getCount = function() {
    var dfr, search;
    dfr = new CUI.Deferred();
    search = this.getSearch();
    search.getSearchInitializedPromise().done((function(_this) {
      return function() {
        var c;
        c = search.getSearchTypeSelector().getLastStats().object_count;
        return dfr.resolve(c);
      };
    })(this)).fail((function(_this) {
      return function() {
        return dfr.resolve("Err");
      };
    })(this));
    return dfr.promise();
  };

  CollectionSearchNode.prototype.setManager = function(manager) {
    this.manager = manager;
    CUI.util.assert(this.manager instanceof CollectionManager, (CUI.util.getObjectClass(this)) + ".setManager", "manager needs to be instance of CollectionManager", {
      manager: this.manager,
      opts: this.opts
    });
    return this;
  };

  CollectionSearchNode.prototype.getManager = function() {
    return this.manager;
  };

  CollectionSearchNode.prototype.getHashId = function() {
    return "search";
  };

  CollectionSearchNode.prototype.getCounterItems = function() {
    return [];
  };

  CollectionSearchNode.prototype.getContent = function() {
    var content, i, item, ref;
    content = CollectionSearchNode.__super__.getContent.call(this);
    ref = this.getCounterItems();
    for (i = ref.length - 1; i >= 0; i += -1) {
      item = ref[i];
      content.splice(0, 0, item);
    }
    return content;
  };

  CollectionSearchNode.prototype.renderNameAsText = function() {
    return $$("collection.search.node.name");
  };

  CollectionSearchNode.prototype.showInSearch = function(search, append) {
    var ref;
    if (search == null) {
      search = this.getSearch();
    }
    if (append == null) {
      append = false;
    }
    if ((ref = this.getManager()) != null) {
      ref.showSearch();
    }
    return search.showInSearch(this.getQueryElement(), append);
  };

  CollectionSearchNode.prototype.getQueryElement = function() {
    return this.__queryElement = new QueryElementCollection({
      collection: this
    });
  };

  CollectionSearchNode.prototype.queryElementDestroyed = function() {
    return delete this.__queryElement;
  };

  CollectionSearchNode.prototype.isSelectable = function() {
    return false;
  };

  CollectionSearchNode.prototype.isSearchable = function() {
    var ref, ref1;
    return !!((ref = this.getSearch()) != null ? ref.getSearchInput() : void 0) && ((ref1 = this.getManager()) != null ? ref1.getSearchCollection() : void 0);
  };

  CollectionSearchNode.prototype.isSearchableConnector = function() {
    return false;
  };

  CollectionSearchNode.prototype.setSearch = function(__search) {
    this.__search = __search;
  };

  CollectionSearchNode.prototype.getSearch = function() {
    var ref;
    return this.__search || ((ref = this.getManager()) != null ? ref.getSearch() : void 0);
  };

  CollectionSearchNode.prototype.ignoreSearchManagers = function() {
    return [];
  };

  CollectionSearchNode.prototype.showInSearchWithChildren = function() {
    return ez5.api.search({
      json_data: {
        limit: 10000,
        type: "collection",
        search: [
          {
            type: "in",
            fields: ["_path.collection._id"],
            "in": [this.data.collection._id]
          }
        ]
      }
    });
  };

  return CollectionSearchNode;

})(Collection);
// Generated by CoffeeScript 1.12.7
var CollectionSearchObjecttype,
  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,
  slice = [].slice;

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

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

  CollectionSearchObjecttype.prototype.initOpts = function() {
    CollectionSearchObjecttype.__super__.initOpts.call(this);
    return this.addOpts({
      offset: {
        mandatory: true,
        "default": 0,
        check: function(v) {
          return v >= 0;
        }
      },
      objecttype: {
        mandatory: true,
        check: Objecttype
      },
      filter: {
        check: String
      },
      info: {
        mandatory: true,
        check: "PlainObject"
      }
    });
  };

  CollectionSearchObjecttype.prototype.readOpts = function() {
    CollectionSearchObjecttype.__super__.readOpts.call(this);
    return this.__count = "...";
  };

  CollectionSearchObjecttype.prototype.chunk_size = 50;

  CollectionSearchObjecttype.prototype.readOpts = function() {
    CollectionSearchObjecttype.__super__.readOpts.call(this);
    if (this._filter) {
      this.do_open = true;
    }
    return this;
  };

  CollectionSearchObjecttype.prototype.getParentId = function() {
    return null;
  };

  CollectionSearchObjecttype.prototype.getGroupingChildren = function(count) {
    var children, chunk, depth, filter, fn, i, idx, last_search_data, limit, node, offset, ref, search_data;
    depth = 0;
    children = [];
    while (count > Math.pow(this.chunk_size, depth)) {
      depth = depth + 1;
    }
    chunk = Math.pow(this.chunk_size, depth - 1);
    fn = (function(_this) {
      return function(node) {
        var firstObject, lastObject;
        firstObject = ez5.api.search({
          json_data: search_data
        });
        lastObject = ez5.api.search({
          json_data: last_search_data
        });
        return CUI.whenAll([firstObject, lastObject]).done(function() {
          var args, firstObjectData, firstObjectStandard, label, lastObjectData, lastObjectStandard;
          args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
          firstObjectData = args[0].args[0];
          lastObjectData = args[1].args[0];
          firstObjectStandard = ez5.loca.getBestDatabaseValue(ez5.loca.getFirstStandardText(firstObjectData.objects[0]._standard));
          lastObjectStandard = ez5.loca.getBestDatabaseValue(ez5.loca.getFirstStandardText(lastObjectData.objects[0]._standard));
          label = $$("collection.search.objecttype.from-to-label", {
            from: firstObjectStandard,
            to: lastObjectStandard
          });
          return node.setName(label);
        });
      };
    })(this);
    for (idx = i = 0, ref = Math.ceil(count / chunk); 0 <= ref ? i < ref : i > ref; idx = 0 <= ref ? ++i : --i) {
      offset = idx * chunk + this._offset;
      limit = Math.min(count - idx * chunk, chunk);
      if (this._filter && !this._objecttype.isHierarchy() && !this._objecttype.isPolyhierarchy()) {
        filter = this._filter;
      } else {
        filter = void 0;
      }
      node = new CollectionSearchObjecttypeGroup({
        objecttype: this._objecttype,
        info: this._info,
        offset: offset,
        name: (offset + 1) + " - " + (offset + limit),
        parent_id: this.getParentId(),
        limit: limit
      });
      children.push(node);
      search_data = this.getSearchData();
      search_data.offset = offset;
      search_data.limit = 1;
      last_search_data = this.getSearchData();
      last_search_data.offset = offset + limit - 1;
      last_search_data.limit = 1;
      fn(node);
    }
    return children;
  };

  CollectionSearchObjecttype.prototype.hasChildren = function() {
    return true;
  };

  CollectionSearchObjecttype.prototype.icon = function() {
    return "fa-file-o";
  };

  CollectionSearchObjecttype.prototype.getSearchData = function() {
    var inValues, otName, parentId, search;
    search = [];
    if (this._objecttype.isPolyhierarchy()) {
      otName = this._objecttype.name();
      parentId = this.getParentId();
      inValues = parentId === null ? [null, 0] : [parentId];
      search.push({
        type: "in",
        bool: "must",
        fields: [otName + "._parents." + otName + "._id"],
        "in": inValues
      });
    } else if (this._objecttype.isHierarchy()) {
      search.push({
        type: "in",
        bool: "must",
        fields: [this._objecttype.name() + "._id_parent"],
        "in": [this.getParentId()]
      });
    }
    return {
      objecttypes: [this._objecttype.name()],
      offset: this._offset,
      limit: this.chunk_size,
      search: search,
      generate_rights: false,
      format: "standard",
      sort: [
        {
          field: "_standard.1.text",
          order: "ASC"
        }
      ]
    };
  };

  CollectionSearchObjecttype.prototype.groupChildren = function() {
    if (this._filter) {
      return false;
    } else {
      return true;
    }
  };

  CollectionSearchObjecttype.prototype.doCount = function() {
    return ez5.api.search({
      json_data: {
        objecttypes: [this._objecttype.name()],
        format: "short",
        limit: 0
      }
    }).done((function(_this) {
      return function(data) {
        _this.__count = data.count;
        return _this.updateCounter();
      };
    })(this));
  };

  CollectionSearchObjecttype.prototype.getCount = function() {
    return this.__count;
  };

  CollectionSearchObjecttype.prototype.isSelectable = function() {
    return false;
  };

  CollectionSearchObjecttype.prototype.getChildren = function() {
    var dfr, phrase, ref, search_data, str;
    dfr = new CUI.Deferred();
    search_data = this.getSearchData();
    if (this._filter) {
      ref = Search.getPhrase(this._filter), str = ref[0], phrase = ref[1];
      search_data.search = [
        {
          bool: "should",
          type: "match",
          mode: "fulltext",
          phrase: phrase,
          string: str
        }
      ];
      search_data.highlight = {};
    }
    ez5.api.search({
      json_data: search_data
    }).fail(dfr.reject).done((function(_this) {
      return function(data) {
        var c, children, found_nodes, i, j, len, len1, obj, ref1;
        if (_this._filter) {
          _this.__count = data.count;
          _this.updateCounter();
        }
        if (data.count === 0) {
          dfr.resolve([]);
          return;
        }
        if (data.count > _this.chunk_size && _this.groupChildren()) {
          dfr.resolve(_this.getGroupingChildren(data.count));
          return;
        }
        if (_this._filter && (_this._objecttype.isHierarchy() || _this._objecttype.isPolyhierarchy())) {
          children = ez5.buildObjectTree({
            objects: data.objects,
            objectKey: _this._objecttype.name(),
            doOpen: true,
            newInstanceFunc: function(obj) {
              return new CollectionSearchObjecttypeObject({
                objecttype: _this._objecttype,
                info: _this._info,
                data: obj
              });
            }
          });
          found_nodes = [];
          for (i = 0, len = children.length; i < len; i++) {
            c = children[i];
            found_nodes.push.apply(found_nodes, c.find());
          }
        } else {
          children = [];
          ref1 = data.objects;
          for (j = 0, len1 = ref1.length; j < len1; j++) {
            obj = ref1[j];
            children.push(new CollectionSearchObjecttypeObject({
              objecttype: _this._objecttype,
              info: _this._info,
              data: obj
            }));
          }
          found_nodes = children;
        }
        _this.__foundNodes = found_nodes;
        _this.countLinkedObjects();
        if (_this._filter && data.count > data.limit) {
          children.push(new CollectionSearchObjecttypeLimit({
            count: data.count,
            limit: data.limit
          }));
        }
        return dfr.resolve(children);
      };
    })(this));
    return dfr.promise();
  };

  CollectionSearchObjecttype.prototype.getManager = function() {
    return CollectionSearchNode.prototype.getManager.call(this.getTopLevel());
  };

  CollectionSearchObjecttype.prototype.getTopLevel = function() {
    var i, len, node, ref;
    ref = this.getPath(true);
    for (i = 0, len = ref.length; i < len; i++) {
      node = ref[i];
      if (node instanceof CollectionSearchObjecttype) {
        return node;
      }
    }
    return null;
  };

  CollectionSearchObjecttype.prototype.countLinkedObjects = function() {
    var i, id, ids, len, node, node_by_id, ot, ots, ref, results, search;
    if (!this.__foundNodes) {
      return;
    }
    ots = this.getManager().getSearch().getSearchObjecttypes(false);
    ids = [];
    node_by_id = {};
    ref = this.__foundNodes;
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      node = ref[i];
      id = node.getId();
      node_by_id[id] = node;
      search = {
        data: {
          debug: "countLinkedObjects"
        },
        json_data: {
          objecttypes: (function() {
            var j, len1, results1;
            results1 = [];
            for (j = 0, len1 = ots.length; j < len1; j++) {
              ot = ots[j];
              results1.push(ot.name());
            }
            return results1;
          })(),
          format: "short",
          generate_rights: false,
          limit: 0,
          search: [
            {
              type: "in",
              objecttype: this._objecttype.name(),
              "in": [id],
              include_path: this._objecttype.isHierarchy() || this._objecttype.isPolyhierarchy()
            }
          ]
        }
      };
      results.push((function(_this) {
        return function(id) {
          return ez5.api.search(search).done(function(data) {
            return node_by_id[id].setCount(data.count);
          });
        };
      })(this)(id));
    }
    return results;
  };

  CollectionSearchObjecttype.prototype.renderNameAsText = function() {
    return this._objecttype.nameLocalized() || "";
  };

  CollectionSearchObjecttype.prototype.getFilter = function() {
    return this._filter;
  };

  return CollectionSearchObjecttype;

})(CollectionSearchNode);
// Generated by CoffeeScript 1.12.7
var CollectionSearchObjecttypeGroup,
  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;

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

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

  CollectionSearchObjecttypeGroup.prototype.initOpts = function() {
    CollectionSearchObjecttypeGroup.__super__.initOpts.call(this);
    return this.addOpts({
      name: {
        mandatory: true,
        check: String
      },
      limit: {
        check: function(v) {
          return v >= 0;
        }
      },
      parent_id: {
        "default": null,
        check: function(v) {
          return v > 0;
        }
      }
    });
  };

  CollectionSearchObjecttypeGroup.prototype.readOpts = function() {
    CollectionSearchObjecttypeGroup.__super__.readOpts.call(this);
    return this.setName(this._name);
  };

  CollectionSearchObjecttypeGroup.prototype.renderNameAsText = function() {
    return this.__name;
  };

  CollectionSearchObjecttypeGroup.prototype.isSelectable = function() {
    return false;
  };

  CollectionSearchObjecttypeGroup.prototype.getCount = function() {
    return this._limit;
  };

  CollectionSearchObjecttypeGroup.prototype.getParentId = function() {
    return this._parent_id;
  };

  CollectionSearchObjecttypeGroup.prototype.icon = function() {
    return null;
  };

  CollectionSearchObjecttypeGroup.prototype.groupChildren = function() {
    return false;
  };

  CollectionSearchObjecttypeGroup.prototype.setName = function(__name) {
    this.__name = __name;
    return this.updateDisplay();
  };

  CollectionSearchObjecttypeGroup.prototype.createContentLabel = function() {
    return new CUI.Label({
      icon: true,
      content: "",
      multiline: true
    });
  };

  CollectionSearchObjecttypeGroup.prototype.getChildren = function() {
    if (this._limit > this.chunk_size) {
      return CUI.resolvedPromise(this.getGroupingChildren(this._limit));
    } else {
      return CollectionSearchObjecttypeGroup.__super__.getChildren.call(this);
    }
  };

  return CollectionSearchObjecttypeGroup;

})(CollectionSearchObjecttype);
// Generated by CoffeeScript 1.12.7
var CollectionSearchObjecttypeObject,
  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;

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

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

  CollectionSearchObjecttypeObject.prototype.initOpts = function() {
    CollectionSearchObjecttypeObject.__super__.initOpts.call(this);
    this.addOpts({
      data: {
        mandatory: true,
        check: "PlainObject"
      }
    });
    return this.removeOpt("parent_id");
  };

  CollectionSearchObjecttypeObject.prototype.readOpts = function() {
    CollectionSearchObjecttypeObject.__super__.readOpts.call(this);
    return this.__count = "...";
  };

  CollectionSearchObjecttypeObject.prototype.getParentId = function() {
    return this.getId();
  };

  CollectionSearchObjecttypeObject.prototype.getId = function() {
    return this._data[this._data._objecttype]._id;
  };

  CollectionSearchObjecttypeObject.prototype.getGlobalObjectId = function() {
    return this._data._global_object_id;
  };

  CollectionSearchObjecttypeObject.prototype.icon = function() {
    return "";
  };

  CollectionSearchObjecttypeObject.prototype.setCount = function(__count) {
    this.__count = __count;
    return this.updateCounter();
  };

  CollectionSearchObjecttypeObject.prototype.doCount = function() {};

  CollectionSearchObjecttypeObject.prototype.getCount = function() {
    return this.__count;
  };

  CollectionSearchObjecttypeObject.prototype.select = function() {
    return this.showInSearch();
  };

  CollectionSearchObjecttypeObject.prototype.isSelectable = function() {
    return true;
  };

  CollectionSearchObjecttypeObject.prototype.getQueryElement = function() {
    var data, lt, ro;
    ro = new ResultObject().setData(this._data);
    lt = new LinkedObjecttype({
      objecttype: new Objecttype(ro.getMask())
    });
    data = {};
    data[lt.name()] = [ro.id()];
    return this.__query_element = new QueryElementLinkedObjecttype({
      field: lt,
      data: data
    });
  };

  CollectionSearchObjecttypeObject.prototype.hasChildren = function() {
    return !!this._data._has_children;
  };

  CollectionSearchObjecttypeObject.prototype.getLinkedObjecttype = function() {
    return this.__linkedObjecttype;
  };

  CollectionSearchObjecttypeObject.prototype.getSearchFilter = function() {
    return this.__linkedObjecttype.getSearchFilter(this.__searchData);
  };

  CollectionSearchObjecttypeObject.prototype.renderNameAsText = function() {
    return ez5.loca.getBestDatabaseValue(ez5.loca.getFirstStandardText(this._data._standard));
  };

  CollectionSearchObjecttypeObject.prototype.getCurrentTools = function() {
    var tools;
    tools = [];
    tools.push(new ToolboxTool({
      group: "collection.object",
      name: "collection.object.quick_view",
      run: (function(_this) {
        return function() {
          var collectionObject;
          collectionObject = new CollectionObject({
            _global_object_id: _this.getGlobalObjectId()
          });
          ResultObject.showCollectionObjectInPopover({
            collectionObject: collectionObject,
            element: _this.contentLabel
          });
        };
      })(this)
    }));
    tools.push(new ToolboxTool({
      group: "collection.object",
      name: "collection.object.use_in_search",
      run: (function(_this) {
        return function(ev) {
          _this.select(ev);
        };
      })(this)
    }));
    tools.push(new ToolboxTool({
      group: "collection.object",
      name: "collection.object.show_in_detail",
      run: (function(_this) {
        return function() {
          var collectionSelection, ref;
          collectionSelection = (ref = _this.getManager()) != null ? ref.getCollectionSelection() : void 0;
          return collectionSelection != null ? collectionSelection.loadInSidebar({
            global_object_id: _this.getGlobalObjectId()
          }) : void 0;
        };
      })(this)
    }));
    return tools;
  };

  CollectionSearchObjecttypeObject.prototype.addedToListView = function(DOMNodes) {
    CollectionSearchObjecttypeObject.__super__.addedToListView.call(this, DOMNodes);
    this.makeDroppable(DOMNodes[0]);
    return this;
  };

  CollectionSearchObjecttypeObject.prototype.makeDroppable = function(el) {
    new CUI.Droppable({
      element: el,
      dropHelper: true,
      accept: (function(_this) {
        return function(ev, info) {
          return _this.acceptDrop(ev, info);
        };
      })(this),
      drop: (function(_this) {
        return function(ev, info) {
          return _this.takeDrop(ev, info);
        };
      })(this)
    });
    return this;
  };

  CollectionSearchObjecttypeObject.prototype.acceptDrop = function(ev, info) {
    if (!info.globalDrag.objects) {
      false;
    }
    return true;
  };

  CollectionSearchObjecttypeObject.prototype.takeDrop = function(ev, info) {
    if (!info.globalDrag.objects) {
      return false;
    }
    return this.__showQuickLinkedAllocator(info.globalDrag.objects);
  };

  CollectionSearchObjecttypeObject.prototype.__showQuickLinkedAllocator = function(droppedObjects) {
    var applyLinked, createForm, dbInfo, dbInfoPromise, dbInfoPromises, fieldsPerObjectType, fn, form, formData, getRequestData, j, len, makeRequest, modal, object, objectCollection, objectType, objects, objectsPerTypes, ot, storeFieldForObjectType, table, waitBlock;
    objectsPerTypes = {};
    fieldsPerObjectType = {};
    dbInfoPromises = [];
    modal = null;
    form = null;
    formData = {};
    createForm = (function(_this) {
      return function() {
        var _objectType, fields, formField, formFields, header1, header2, headerRow, selectOptions, verticalLayout;
        formFields = [];
        for (_objectType in fieldsPerObjectType) {
          fields = fieldsPerObjectType[_objectType];
          if (fields.length === 1) {
            formField = {
              type: CUI.Output,
              text: fields[0].field.nameLocalized()
            };
            formData[_objectType] = 0;
          } else {
            selectOptions = fields.map(function(field, index) {
              var option;
              option = {
                text: field.field.nameLocalized(),
                value: index
              };
              return option;
            });
            formField = {
              type: CUI.Select,
              name: _objectType,
              options: selectOptions
            };
          }
          formField.form = {
            label: ez5.schema.CURRENT._objecttype_by_name[_objectType]._name_localized
          };
          formFields.push(formField);
        }
        form = new CUI.Form({
          data: formData,
          padded: true,
          fields: formFields
        });
        form.start();
        header1 = new CUI.Label({
          text: "**" + ($$("base.objecttype.name")) + "**",
          markdown: true
        });
        header2 = new CUI.Label({
          text: "**" + ($$("base.field.name")) + "**",
          markdown: true
        });
        headerRow = CUI.dom.table_one_row(header1, header2);
        verticalLayout = new CUI.VerticalLayout({
          "class": "ez5-keyword-allocator-content",
          top: {
            content: new LocaLabel({
              loca_key: "collections.objecttype.drag_and_drop_tagging.message",
              markdown: true,
              padded: true,
              loca_key_attrs: {
                name: _this.renderNameAsText()
              }
            })
          },
          center: {
            content: headerRow
          },
          bottom: {
            content: form
          }
        });
        modal.setContent(verticalLayout);
      };
    })(this);
    storeFieldForObjectType = (function(_this) {
      return function(_objectType, field, depth, mask, table) {
        var alreadyStored;
        if (!fieldsPerObjectType[_objectType]) {
          fieldsPerObjectType[_objectType] = [];
        }
        alreadyStored = fieldsPerObjectType[_objectType].some(function(f) {
          return f.field.ColumnSchema.column_id === field.ColumnSchema.column_id;
        });
        if (!alreadyStored) {
          fieldsPerObjectType[_objectType].push({
            field: field,
            depth: depth,
            mask: mask,
            table: table
          });
        }
      };
    })(this);
    applyLinked = (function(_this) {
      return function() {
        var _objectType, fieldData, fieldIndex, requests;
        requests = [];
        for (_objectType in formData) {
          fieldIndex = formData[_objectType];
          fieldData = fieldsPerObjectType[_objectType][fieldIndex];
          requests.push(makeRequest(_objectType, fieldData));
        }
        CUI.whenAll(requests).done(function() {
          var eventPollerListener;
          eventPollerListener = CUI.Events.listen({
            type: "event-poller",
            node: _this.contentLabel,
            call: function(ev, info) {
              var ref;
              if (!info.event) {
                return;
              }
              if (info.event.type === "OBJECT_INDEX") {
                if ((ref = _this.father) != null) {
                  ref.countLinkedObjects();
                }
                eventPollerListener.destroy();
              }
            }
          });
          return modal.destroy();
        });
      };
    })(this);
    makeRequest = (function(_this) {
      return function(_objectType, fieldData) {
        var request;
        request = ez5.api.db({
          api: "/" + fieldData.table.name() + "?priority=1&format=short",
          json_data: [getRequestData(_objectType, fieldData)],
          error: function(xhr) {}
        });
        return request;
      };
    })(this);
    getRequestData = (function(_this) {
      return function(_objectType, fieldData) {
        var data, field, fieldName, fieldRequestData, i, j, levelField, nestedTableName, newLayer, ref;
        data = {};
        field = fieldData.field;
        fieldName = field.ColumnSchema.name;
        fieldRequestData = {};
        fieldRequestData[fieldName] = {
          _objecttype: _this._data._objecttype,
          _mask: _this._data._mask,
          _global_object_id: _this._data._global_object_id
        };
        fieldRequestData[fieldName][_this._data._objecttype] = {
          _id: _this._data[_this._data._objecttype]._id
        };
        if (field.insideNested()) {
          levelField = field.mask.nestedTableField;
          nestedTableName = "";
          for (i = j = 1, ref = fieldData.depth; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) {
            nestedTableName = levelField.name();
            newLayer = {};
            newLayer[nestedTableName] = [fieldRequestData];
            fieldRequestData = newLayer;
            levelField = levelField.fatherMask.nestedTableField;
          }
          fieldRequestData[nestedTableName + ":group_mode"] = "append";
        }
        fieldRequestData["_id"] = objectsPerTypes[_objectType];
        data[_objectType] = fieldRequestData;
        data["_mask"] = fieldData.mask.name;
        data["_objecttype"] = _objectType;
        data["_comment"] = $$("collections.objecttype.drag_and_drop_tagging.request_comment");
        return data;
      };
    })(this);
    for (j = 0, len = droppedObjects.length; j < len; j++) {
      objectCollection = droppedObjects[j];
      object = objectCollection.getObject();
      objectType = objectCollection.getObjecttype();
      if (!objectsPerTypes[objectType]) {
        objectsPerTypes[objectType] = [];
      }
      objectsPerTypes[objectType].push(object[objectType]._id);
    }
    fn = (function(_this) {
      return function(dbInfoPromise, objectType, table) {
        return dbInfoPromise.done(function(dbInfoResponse) {
          var k, len1, mask, maskObj, ref, results;
          ref = dbInfoResponse._available_masks || [];
          results = [];
          for (k = 0, len1 = ref.length; k < len1; k++) {
            mask = ref[k];
            maskObj = Mask.getMaskByMaskName(mask.name, table._id);
            maskObj.invokeOnFields("editor", true, (function(field, _, depth) {
              var ref1;
              if (!(field instanceof LinkedObject) || field instanceof TreeColumn) {
                return;
              }
              if (field.FieldSchema.other_table_id !== _this._objecttype.table._id) {
                return;
              }
              if (((ref1 = field.FieldSchema.edit) != null ? ref1.mode : void 0) !== "edit") {
                return;
              }
              return storeFieldForObjectType(objectType, field, depth, mask, table);
            }));
            if (mask.name === "_all_fields") {
              break;
            } else {
              results.push(void 0);
            }
          }
          return results;
        });
      };
    })(this);
    for (objectType in objectsPerTypes) {
      objects = objectsPerTypes[objectType];
      ot = ez5.schema.CURRENT._objecttype_by_name[objectType];
      table = new Table("CURRENT", ot);
      dbInfo = new DbInfo();
      dbInfoPromise = dbInfo.load({
        object_ids: objects,
        table: table
      });
      dbInfoPromises.push(dbInfoPromise);
      fn(dbInfoPromise, objectType, table);
    }
    CUI.whenAll(dbInfoPromises).done((function(_this) {
      return function() {
        waitBlock.hide();
        if (CUI.util.isEmpty(fieldsPerObjectType)) {
          modal.destroy();
          CUI.alert({
            markdown: true,
            text: $$("collections.objecttype.drag_and_drop_tagging.error", {
              name: _this.renderNameAsText()
            })
          });
          return;
        }
        return createForm();
      };
    })(this));
    modal = new CUI.Modal({
      "class": "ez5-keyword-allocator-modal",
      cancel: true,
      pane: {
        header_left: new LocaLabel({
          loca_key: "collections.objecttype.drag_and_drop_tagging.title",
          loca_key_attrs: {
            name: this.renderNameAsText()
          }
        }),
        content: new CUI.dom.div(),
        footer_right: [
          {
            text: $$("base.cancel"),
            onClick: function() {
              return modal.destroy();
            }
          }, {
            type: CUI.Button,
            text: $$("base.apply"),
            primary: true,
            disabled: false,
            left: true,
            onClick: function(ev, btn) {
              applyLinked();
              waitBlock.show();
              btn.startSpinner();
              return btn.disable();
            }
          }
        ]
      }
    });
    waitBlock = new CUI.WaitBlock({
      element: modal.getPane()
    });
    modal.show();
    waitBlock.show();
  };

  return CollectionSearchObjecttypeObject;

})(CollectionSearchObjecttype);
// Generated by CoffeeScript 1.12.7
var CollectionSearchObjecttypeLimit,
  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;

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

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

  CollectionSearchObjecttypeLimit.prototype.initOpts = function() {
    CollectionSearchObjecttypeLimit.__super__.initOpts.call(this);
    return this.addOpts({
      count: {
        check: function(v) {
          return v > 0;
        }
      },
      limit: {
        check: function(v) {
          return v > 0;
        }
      }
    });
  };

  CollectionSearchObjecttypeLimit.prototype.renderContent = function() {
    return new CUI.EmptyLabel({
      multiline: true,
      text: $$("collection.search.objecttype.limit.hint", {
        limit: this._limit,
        count: this._count
      })
    });
  };

  return CollectionSearchObjecttypeLimit;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var CollectionObject;

CollectionObject = (function() {
  function CollectionObject(object) {
    if (!ResultObject.dataFromPurgedObject(object)) {
      CUI.util.assert(CUI.util.isPlainObject(object), "new CollectionObject", "object needs to be PlainObject", {
        object: object
      });
    }
    this.setObject(object);
  }

  CollectionObject.prototype.equals = function(co) {
    CUI.util.assert(co instanceof CollectionObject, "CollectionObject.equals", "Object needs to be of type Collection but is \"" + (CUI.util.getObjectClass(co)) + "\"", {
      collection_object: co
    });
    return this.getGlobalObjectId() === co.getGlobalObjectId();
  };

  CollectionObject.prototype.toString = function() {
    return "{" + (this.getGlobalObjectId()) + "}";
  };

  CollectionObject.prototype.setObject = function(__object) {
    var ref;
    this.__object = __object;
    if (!ResultObject.dataFromPurgedObject(this.__object)) {
      CUI.util.assert(CUI.util.isString((ref = this.__object) != null ? ref._global_object_id : void 0) || this.__object._mapped_metadata_created, "CollectionObject.setObject", "object._global_object_id needs to be String or object._mapped_metadata_created needs to be set.", {
        object: this.__object
      });
    }
    return this;
  };

  CollectionObject.prototype.getObject = function() {
    return this.__object;
  };

  CollectionObject.prototype.getObjecttype = function() {
    return this.__object._objecttype;
  };

  CollectionObject.prototype.isMappedMetadataCreated = function() {
    return this.__object._mapped_metadata_created;
  };

  CollectionObject.prototype.isNotFound = function() {
    return this.__object.__notFound;
  };

  CollectionObject.prototype.getGlobalObjectId = function(assertIfEmpty) {
    if (assertIfEmpty == null) {
      assertIfEmpty = false;
    }
    if (assertIfEmpty) {
      CUI.util.assert(this.__object._global_object_id, "CollectionObject.getGlobalObjectId", "object._global_object_id not set.", {
        object: this.__object
      });
    }
    return this.__object._global_object_id;
  };

  CollectionObject.prototype.getId = function() {
    return this.__object[this.getObjecttype()]._id;
  };

  CollectionObject.prototype.getVersion = function() {
    return this.__object[this.getObjecttype()]._version;
  };

  CollectionObject.prototype.getSelector = function() {
    var gid;
    gid = this.getGlobalObjectId();
    if (!gid) {
      gid = "no-id-set";
    }
    return "[global-object-id=\"" + gid + "\"]";
  };

  CollectionObject.prototype.getStorable = function() {
    return {
      _global_object_id: this.getGlobalObjectId(true)
    };
  };

  CollectionObject.prototype.getSearchFilter = function() {
    return {
      type: "in",
      fields: ["_global_object_id"],
      "in": [this.getGlobalObjectId(true)]
    };
  };

  CollectionObject.reloadObjects = function(collection_objects) {
    var co, co_by_gid, gids, i, len, req_data;
    if (collection_objects.length === 0) {
      return;
    }
    co_by_gid = {};
    for (i = 0, len = collection_objects.length; i < len; i++) {
      co = collection_objects[i];
      co_by_gid[co.getGlobalObjectId(true)] = co;
    }
    gids = Object.keys(co_by_gid);
    req_data = {
      search: [
        {
          type: "in",
          fields: ["_global_object_id"],
          "in": gids
        }
      ],
      format: "standard",
      offset: 0,
      generate_rights: ez5.version("6"),
      limit: gids.length
    };
    return ez5.api.search({
      data: {
        debug: "CollectionObject"
      },
      json_data: req_data
    }).done(function(data) {
      var j, len1, obj, ref;
      ref = data.objects;
      for (j = 0, len1 = ref.length; j < len1; j++) {
        obj = ref[j];
        co_by_gid[obj._global_object_id].setObject(obj);
      }
    });
  };

  return CollectionObject;

})();
// Generated by CoffeeScript 1.12.7
var CollectionWithDetail,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  CollectionWithDetail.prototype.readOpts = function() {
    CollectionWithDetail.__super__.readOpts.call(this);
    return this.searchCollection = null;
  };

  CollectionWithDetail.prototype.unregisterEvents = function() {
    this.off({
      type: ["insert", "remove"]
    });
    if (this.__pollListener) {
      CUI.Events.ignore(this.__pollListener);
    }
    this.__pollListener = null;
    return this;
  };

  CollectionWithDetail.prototype.registerEvents = function() {
    var wait_block, wait_info;
    wait_info = null;
    wait_block = null;
    this.on({
      type: ["insert", "remove"],
      call: (function(_this) {
        return function(ev, info) {
          var co;
          if (ev.getType() === 'insert') {
            if (!wait_info) {
              wait_info = [];
            }
            wait_info.push({
              info: info,
              event: ev,
              gids: (function() {
                var i, len, ref, results;
                ref = info.collection_objects;
                results = [];
                for (i = 0, len = ref.length; i < len; i++) {
                  co = ref[i];
                  results.push(co.getGlobalObjectId());
                }
                return results;
              })()
            });
          }
          if (!wait_block) {
            wait_block = new CUI.WaitBlock({
              element: _this.searchCollection.getResultContainer()
            });
            wait_block.show();
          }
        };
      })(this)
    });
    this.__pollListener = EventPoller.listen({
      filter: (function(_this) {
        return function(event) {
          var found, i, j, len, len1, r_info, ref, remove_wait_info, w_info;
          if (wait_info === null) {
            if (event.type === "OBJECT_INDEX" && event.object_id === _this.getId() && event.basetype === "collection") {
              return true;
            } else {
              return false;
            }
          }
          if (event.type !== 'OBJECT_INDEX' || !event.global_object_id) {
            return false;
          }
          found = false;
          remove_wait_info = [];
          for (i = 0, len = wait_info.length; i < len; i++) {
            w_info = wait_info[i];
            if (ref = event.global_object_id, indexOf.call(w_info.gids, ref) >= 0) {
              CUI.util.removeFromArray(event.global_object_id, w_info.gids);
              if (w_info.gids.length === 0) {
                remove_wait_info.push(w_info);
              }
              event.__info = w_info;
              found = true;
            }
          }
          for (j = 0, len1 = remove_wait_info.length; j < len1; j++) {
            r_info = remove_wait_info[j];
            CUI.util.removeFromArray(r_info, wait_info);
          }
          return found;
        };
      })(this),
      instance: this,
      call: (function(_this) {
        return function(events) {
          var event;
          if (wait_block != null) {
            wait_block.destroy();
          }
          wait_block = null;
          if (wait_info === null) {
            _this.updateAfterInsertOrRemoveEvent(null, null);
            return;
          }
          if (wait_info.length > 0) {
            return;
          }
          wait_info = null;
          event = events[events.length - 1];
          CUI.scheduleCallback({
            ms: 1000,
            call: function() {
              return _this.updateAfterInsertOrRemoveEvent(event.__info.event, event.__info.info);
            }
          });
        };
      })(this)
    });
    return this;
  };

  CollectionWithDetail.prototype.setManager = function(manager) {
    CollectionWithDetail.__super__.setManager.call(this, manager);
    this.detailDiv = this.manager.getCollectionDetailDiv();
    return CUI.util.assert(this.detailDiv, "new " + (CUI.util.getObjectClass(this)), "Manager returned empty collection detail div", {
      opts: this.opts
    });
  };

  CollectionWithDetail.prototype.updateAfterInsertOrRemove = function(before_idx) {
    var offset;
    if (before_idx == null) {
      before_idx = null;
    }
    if (!this.searchCollection) {
      return;
    }
    if (before_idx != null) {
      offset = before_idx;
    } else {
      offset = Math.max(0, this.getCount() - 1);
    }
    return this.searchCollection.execute(new Request({
      update: true,
      offset: offset,
      scroll_into_view_offset: offset
    }));
  };

  CollectionWithDetail.prototype.updateAfterInsertOrRemoveEvent = function(ev, info) {
    var lastData, offset;
    if (!this.searchCollection) {
      return;
    }
    if ((ev != null ? ev.getType() : void 0) === "insert") {
      if (CUI.util.isNull(info.before_idx)) {
        offset = Math.max(0, this.getCount() - 1);
      } else {
        offset = info.before_idx;
      }
    } else {
      lastData = this.searchCollection.getLastData();
      if (!lastData) {
        offset = 0;
      } else {
        offset = lastData.offset;
        if (this.getCount() <= offset) {
          offset = Math.max(0, Math.floor((this.getCount() - 1) / lastData.limit) * lastData.limit);
        }
      }
    }
    return this.searchCollection.execute(new Request({
      update: true,
      offset: offset,
      scroll_into_view_offset: offset
    }));
  };

  CollectionWithDetail.prototype.showFullscreen = function(opts) {
    if (opts == null) {
      opts = {};
    }
    return new DetailFullscreen({
      collection: this,
      offset: opts.offset || 0,
      global_object_id: opts.global_object_id || null
    });
  };

  CollectionWithDetail.prototype.getBadge = function() {
    var name;
    if (this.__subcollectionIds != null) {
      name = $$("collection.badge.name.with_subcollections");
    } else {
      name = $$("collection.badge.name");
    }
    return {
      icon: this.getBadgeIcon(),
      name: name,
      value: this.renderNameAsText()
    };
  };

  CollectionWithDetail.prototype.showInSearchWithSubcollections = function(search, append) {
    if (search == null) {
      search = this.getSearch();
    }
    if (append == null) {
      append = false;
    }
    return this.getAllSubcollectionIds().done((function(_this) {
      return function(subcollectionIds) {
        var collectionCopy;
        collectionCopy = _this.copy();
        collectionCopy.__subcollectionIds = subcollectionIds;
        return collectionCopy.showInSearch(search, append);
      };
    })(this));
  };

  CollectionWithDetail.prototype.getDownloadManagerClass = function() {
    var ref;
    return ((ref = this.getManager()) != null ? ref.getDownloadManagerClass() : void 0) || ez5.defaults["class"].DownloadManager;
  };

  CollectionWithDetail.prototype.allowSubcollectionSearch = function() {
    return false;
  };

  CollectionWithDetail.prototype.isSearchAppendable = function() {
    return this.isSearchable();
  };

  CollectionWithDetail.prototype.showCreateTaskTool = function() {
    return ez5.version("6") && ez5.session.hasSystemRight("root", "task");
  };

  CollectionWithDetail.prototype.getCurrentTools = function() {
    var count, tools;
    tools = CollectionWithDetail.__super__.getCurrentTools.call(this);
    count = this.getBareCount();
    if (ez5.version("6") && this.isSearchable() && this.allowSubcollectionSearch()) {
      tools.push(new ToolboxTool({
        group: this.getToolGroup(),
        sort: "A:5",
        name: this.getToolNamePrefix() + ".search.add.with_subcollections",
        run: (function(_this) {
          return function() {
            return _this.copy().showInSearchWithSubcollections(_this.getSearch(), false);
          };
        })(this)
      }));
    }
    if (this.isSearchable()) {
      tools.push(new ToolboxTool({
        group: this.getToolGroup(),
        sort: "A:4",
        name: this.getToolNamePrefix() + ".search",
        run: (function(_this) {
          return function() {
            return _this.copy().showInSearch();
          };
        })(this)
      }));
    }
    if (this.isSearchAppendable()) {
      tools.push(new ToolboxTool({
        group: this.getToolGroup(),
        sort: "A:6",
        name: this.getToolNamePrefix() + ".search.append",
        run: (function(_this) {
          return function() {
            return _this.copy().showInSearch(_this.getSearch(), true);
          };
        })(this)
      }));
    }
    if (this.isSearchableConnector()) {
      tools.push(new ToolboxTool({
        group: this.getToolGroup(),
        sort: "A:4",
        name: this.getToolNamePrefix() + ".search.connector",
        run: (function(_this) {
          return function() {
            return _this.copy().showInSearchConnector();
          };
        })(this)
      }));
    }
    if (this.showCreateTaskTool()) {
      tools.push(new ToolboxTool({
        group: this.getToolGroup(),
        name: this.getToolNamePrefix() + ".task",
        sort: "D:4",
        run: (function(_this) {
          return function() {
            return new TaskManagerList({
              headless: true
            }).createTaskFromCollection(_this);
          };
        })(this)
      }));
    }
    if (count === 0) {
      return tools;
    }
    if (this.isDownloadable() && ez5.session.hasSystemRight("root", "frontend_features[download]")) {
      tools.push(new ToolboxTool({
        group: this.getToolGroup(),
        name: this.getToolNamePrefix() + ".download",
        sort: "D:2",
        loca_key: "tool." + this.getToolNamePrefix() + ".download",
        loca_key_attrs: {
          count: count
        },
        disabled: count === 0,
        favorite: true,
        run: (function(_this) {
          return function() {
            var cls;
            cls = _this.getDownloadManagerClass();
            return new cls({
              collection: _this
            }).startExport();
          };
        })(this)
      }));
    }
    if (count > 0) {
      if (this.isExportable() && ez5.session.hasSystemRight("root", "frontend_features[export]")) {
        tools.push(new ToolboxTool({
          group: this.getToolGroup(),
          name: this.getToolNamePrefix() + ".export",
          sort: "D:3",
          disabled: count === 0,
          run: (function(_this) {
            return function() {
              return new ExportManager({
                search: new SearchCollectionHeadless({
                  collection: _this
                }),
                sortManager: _this.__getSortManagerForExport()
              }).prepareExport();
            };
          })(this)
        }));
      }
      if (this.isPrintable() && ez5.session.hasSystemRight("root", "frontend_features[print]")) {
        tools.push(new ToolboxTool({
          group: this.getToolGroup(),
          name: this.getToolNamePrefix() + ".print",
          sort: "D:5",
          disabled: count === 0,
          run: (function(_this) {
            return function() {
              var i, len, manager, managers, printManager, request;
              request = {};
              managers = _this.getSearch().getSearchManagers();
              for (i = 0, len = managers.length; i < len; i++) {
                manager = managers[i];
                if (manager instanceof SortManager) {
                  manager.addToRequest(request);
                  break;
                }
              }
              printManager = new PrintManager({
                search: new SearchCollectionHeadless({
                  collection: _this,
                  request: request
                })
              });
              return printManager.getOptionsModal().show();
            };
          })(this)
        }));
      }
      if (this.isFullscreenable()) {
        tools.push(new ToolboxTool({
          group: this.getToolGroup(),
          name: this.getToolNamePrefix() + ".show.fullscreen",
          sort: "A:6",
          run: (function(_this) {
            return function() {
              return _this.showFullscreen();
            };
          })(this)
        }));
      }
    }
    if (this.searchCollection) {
      tools.push.apply(tools, this.searchCollection.getCurrentTools());
    }
    return tools;
  };

  CollectionWithDetail.prototype.addedToListView = function(DOMNodes) {
    CollectionWithDetail.__super__.addedToListView.call(this, DOMNodes);
    this.makeDroppable(DOMNodes[0]);
    return this;
  };

  CollectionWithDetail.prototype.__getSortManagerForExport = function() {
    var ref, ref1, sortManager;
    sortManager = null;
    if (ez5.version("6")) {
      sortManager = (ref = this.getSearch()) != null ? (ref1 = ref.getSearchManagers().filter((function(_this) {
        return function(sm) {
          return sm instanceof SortManager;
        };
      })(this))) != null ? ref1[0] : void 0 : void 0;
    }
    return sortManager;
  };

  CollectionWithDetail.prototype.makeDroppable = function(el) {
    new CUI.Droppable({
      element: el,
      dropHelper: true,
      accept: (function(_this) {
        return function(ev, info) {
          return _this.acceptDrop(ev, info);
        };
      })(this),
      drop: (function(_this) {
        return function(ev, info) {
          return _this.takeDrop(ev, info);
        };
      })(this)
    });
    return this;
  };

  CollectionWithDetail.prototype.makeDetailDroppable = function(el) {
    if (!this.canAppend()) {
      return this;
    }
    new CUI.Droppable({
      element: el,
      selector: ".result-dynamic",
      targetHelper: true,
      dropHelper: true,
      accept: function(ev, info) {
        if (!info.globalDrag.objects) {
          return false;
        }
      },
      drop: (function(_this) {
        return function(ev, info) {
          var before_idx;
          if (!info.dropTargetPos) {
            before_idx = null;
          } else {
            before_idx = parseInt(CUI.dom.getAttribute(info.dropTarget, "offset"));
            if (!(before_idx >= 0)) {
              return false;
            }
            if (info.dropTargetPos === "after") {
              before_idx++;
            }
            if (before_idx === _this.getCount()) {
              before_idx = null;
            }
          }
          return _this.insertObjects(info.globalDrag.objects, before_idx);
        };
      })(this)
    });
    return this;
  };

  CollectionWithDetail.prototype.acceptDrop = function(ev, info) {
    if (!info.globalDrag.objects) {
      return false;
    } else if (this.canAppend()) {
      return true;
    } else {
      return false;
    }
  };

  CollectionWithDetail.prototype.takeDrop = function(ev, info) {
    var confirmationChoice, originSearch, ref, ref1, ref2, ref3, ref4;
    if (info.globalDrag.objects) {
      originSearch = info.globalDrag.originSearch;
      if (((ref = originSearch.collection) != null ? (ref1 = ref.data) != null ? (ref2 = ref1.collection) != null ? ref2.uuid : void 0 : void 0 : void 0) === ((ref3 = this.data.collection) != null ? ref3.uuid : void 0)) {
        return;
      }
      if (CUI.util.getObjectClass(originSearch) === "SearchCollection" && this instanceof CollectionWorkfolder) {
        if (ev.getInfo().originalEvent.hasModifierKey() && ev.getInfo().originalEvent.ctrlKey()) {
          this.insertObjects(info.globalDrag.objects);
          if ((ref4 = originSearch.collection) != null) {
            ref4.removeObjects(info.globalDrag.objects);
          }
          return;
        }
        if (ev.getInfo().originalEvent.hasModifierKey() && ev.getInfo().originalEvent.altKey()) {
          this.insertObjects(info.globalDrag.objects);
          return;
        }
        confirmationChoice = new CUI.ConfirmationChoice({
          text: $$("collection.objects.actions.move.dialog.text"),
          title: $$("collection.objects.actions.move.dialog.title"),
          cancel: true,
          choices: [
            {
              text: $$("base.cancel")
            }, {
              text: $$("collection.objects.action.move"),
              onClick: (function(_this) {
                return function() {
                  var ref5;
                  _this.insertObjects(info.globalDrag.objects);
                  return (ref5 = originSearch.collection) != null ? ref5.removeObjects(info.globalDrag.objects) : void 0;
                };
              })(this)
            }, {
              text: $$("collection.objects.action.copy"),
              primary: true,
              onClick: (function(_this) {
                return function() {
                  return _this.insertObjects(info.globalDrag.objects);
                };
              })(this)
            }
          ]
        });
        return confirmationChoice.open();
      } else {
        return this.insertObjects(info.globalDrag.objects);
      }
    }
  };

  CollectionWithDetail.prototype.insertInProgress = function() {
    return false;
  };

  CollectionWithDetail.prototype.insertObjects = function() {
    return CUI.util.assert(false, CUI.util.getObjectClass(this) + ".insertObjects", "Needs implementation.");
  };

  CollectionWithDetail.prototype.isSelectable = function() {
    return true;
  };

  CollectionWithDetail.prototype.select = function(ev) {
    return CollectionWithDetail.__super__.select.call(this, ev).done((function(_this) {
      return function() {
        return _this.prepareCurrentTools().done(function() {
          return _this.showDetail();
        });
      };
    })(this));
  };

  CollectionWithDetail.prototype.deselect = function(ev) {
    return CollectionWithDetail.__super__.deselect.call(this, ev).done((function(_this) {
      return function() {
        var ref, ref1;
        _this.unregisterEvents();
        if ((ref = _this.searchCollection) != null) {
          ref.destroy();
        }
        _this.searchCollection = null;
        if ((ref1 = _this.manager) != null) {
          ref1.resetCollectionDetailDiv();
        }
        if (_this.detailDiv) {
          return CUI.Droppable.destroy(_this.detailDiv);
        }
      };
    })(this));
  };

  CollectionWithDetail.prototype.canAppend = function() {
    return false;
  };

  CollectionWithDetail.prototype.showDetail = function() {
    var cls;
    if (!this.manager) {
      return;
    }
    CUI.dom.empty(this.detailDiv);
    cls = this.manager.getSearchCollectionClass();
    this.searchCollection = new cls({
      container: this.detailDiv,
      collection: this
    });
    return this.searchCollection.init().done((function(_this) {
      return function() {
        if (!_this.searchCollection) {
          return;
        }
        _this.makeDetailDroppable(_this.searchCollection.getResultContainer());
        return _this.registerEvents();
      };
    })(this));
  };

  CollectionWithDetail.prototype.isFullscreenable = function() {
    return true;
  };

  CollectionWithDetail.prototype.isDownloadable = function() {
    return true;
  };

  CollectionWithDetail.prototype.isExportable = function() {
    return true;
  };

  CollectionWithDetail.prototype.isPrintable = function() {
    return true;
  };

  CollectionWithDetail.prototype.destroy = function() {
    this.unregisterEvents();
    return CollectionWithDetail.__super__.destroy.call(this);
  };

  return CollectionWithDetail;

})(CollectionSearchNode);
// Generated by CoffeeScript 1.12.7
var CollectionStorable,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function CollectionStorable(opts1) {
    this.opts = opts1 != null ? opts1 : {};
    this.equals = bind(this.equals, this);
    CollectionStorable.__super__.constructor.call(this, this.opts);
    this.__loadedFromDb = false;
  }

  CollectionStorable.prototype.equals = function(collection) {
    if (this.data.collection._id && (collection != null ? collection.data.collection._id : void 0)) {
      return this.data.collection._id === collection.data.collection._id;
    } else {
      return false;
    }
  };

  CollectionStorable.prototype.setData = function(data1) {
    this.data = data1;
    CollectionStorable.__super__.setData.call(this, this.data);
    if (!this.data._generated_rights) {
      this.data._generated_rights = {};
    }
    if (!this.data.collection.webfrontend_props) {
      this.data.collection.webfrontend_props = {};
    }
    if (this.data.collection._id) {
      this.hashId = this.data.collection._id + "";
    }
    return this;
  };

  CollectionStorable.prototype.getData = function() {
    return this.data;
  };

  CollectionStorable.prototype.getHashId = function() {
    return this.hashId;
  };

  CollectionStorable.prototype.getChildren = function() {
    var cm, dfr, search, shared_search;
    cm = this.getManager();
    search = [
      {
        type: "in",
        "in": [this.getId()],
        fields: ["collection._id_parent"]
      }
    ];
    if (this.isSharedCollection()) {
      shared_search = cm.getSharedCollectionSearch();
      shared_search[0].search.push(search[0]);
      search = shared_search;
    }
    dfr = new CUI.Deferred();
    ez5.api.search({
      data: {
        debug: "CollectionStorable"
      },
      json_data: {
        type: "collection",
        limit: 100000,
        search: search,
        sort: cm.getCollectionSortFilter()
      }
    }).done((function(_this) {
      return function(data) {
        var col, cols, i, len1, ref;
        cols = [];
        ref = data.objects;
        for (i = 0, len1 = ref.length; i < len1; i++) {
          col = ref[i];
          cols.push(cm.getCollectionWorkfolderClass().newInstance({
            collection: col,
            manager: cm
          }));
        }
        return dfr.resolve(cols);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  CollectionStorable.prototype.hasChildren = function() {
    if (this._build_from_path) {
      return true;
    }
    return !!this.data._has_children;
  };

  CollectionStorable.prototype.getCount = function() {
    if (ez5.version("6") && !CUI.util.isNull(this.data._count_recursive)) {
      if (!this.isOpen()) {
        if (this.isSharedCollection() && (this.__shared_recursive_count != null)) {
          return this.__shared_recursive_count;
        } else {
          return this.data._count_recursive;
        }
      }
    }
    return this.data._count;
  };

  CollectionStorable.prototype.getBareCount = function() {
    return this.data._count;
  };

  CollectionStorable.prototype.isSharedCollection = function() {
    var currentUser;
    if (!this.data._owner) {
      return false;
    }
    currentUser = ez5.session.user;
    if (!currentUser) {
      return false;
    }
    if (this.data._owner.user && this.data._owner.user._id === currentUser.getId()) {
      return false;
    }
    return true;
  };

  CollectionStorable.prototype.setSharedRecursiveCount = function(count) {
    this.__shared_recursive_count = count;
  };

  CollectionStorable.prototype.refreshRecursive = function(first) {
    var ref;
    if (first == null) {
      first = true;
    }
    if (!first) {
      this.refresh(true);
    }
    if (this.isRoot()) {
      return;
    }
    return (ref = this.getFather()) != null ? typeof ref.refreshRecursive === "function" ? ref.refreshRecursive(false) : void 0 : void 0;
  };

  CollectionStorable.prototype.getSaveData = function(data) {
    var empty_pools, mask, ot_name, pool_id, ref, ref1, ref2, ref3, ref4, ref5, save_data, sd;
    if (data == null) {
      data = this.data;
    }
    save_data = {
      collection: {
        _id: data.collection._id,
        _id_parent: data.collection._id_parent,
        _version: data.collection._version,
        children_allowed: data.collection.children_allowed,
        objects_allowed: data.collection.objects_allowed,
        displayname: CUI.util.copyObject(data.collection.displayname, true),
        description: CUI.util.copyObject(data.collection.description, true),
        shortname: data.collection.shortname,
        reference: data.collection.reference,
        type: data.collection.type,
        webfrontend_props: CUI.util.copyObject(data.collection.webfrontend_props, true)
      }
    };
    delete ((ref = save_data.collection.displayname) != null ? ref._undo : void 0);
    if (this.aclManager && data === this.data) {
      save_data._acl = this.aclManager.getSaveData();
    }
    if ((ref1 = data._generated_rights) != null ? ref1.bag_acl : void 0) {
      save_data._private_acl = data._private_acl;
      save_data.collection.pin_code = data.collection.pin_code;
    }
    if (this.editor_data && data === this.data) {
      ot_name = (ref2 = ez5.schema.CURRENT._table_by_id[this.editor_data.choice_table_id]) != null ? ref2.name : void 0;
      if (this.editor_data._create_objects) {
        data.collection.webfrontend_props.select_individual_pools = this.editor_data.select_individual_pools;
        mask = Mask.getMaskByMaskName(this.editor_data.mask_name, this.editor_data.choice_table_id);
        pool_id = ((ref3 = this.editor_data._pool) != null ? ref3.pool._id : void 0) || null;
        if ((mask != null ? mask.table.poolLink() : void 0) && !pool_id) {
          throw new InvalidSaveDataException();
        }
        sd = {
          objecttype: ot_name || null,
          mask_id: (mask != null ? mask.id() : void 0) || null,
          pool_id: pool_id,
          linked_pool_id: this.editor_data.linked_objects_pool_id || this.editor_data.linked_pool_id,
          linked_object_pools: this.getLinkedObjectPools(),
          eas_field: ((ref4 = this.editor_data.bulk_field) != null ? ref4.nameForCollectionSave() : void 0) || null,
          mapping: this.editor_data.mapping || null,
          recognize_series: this.editor_data.recognize_series,
          recognize_version: this.editor_data.recognize_version,
          update_search_field: this.editor_data.update_search_field,
          update_mode: this.editor_data.update_mode,
          update_policy: this.editor_data.update_policy,
          plugin: this.editor_data.plugin,
          plugin_config: this.editor_data.plugin_config
        };
        if (this.editor_data.hierarchy_linked_object_field) {
          sd.hierarchy_linked_object = {
            field: this.editor_data.hierarchy_linked_object_field
          };
        } else if (ez5.version("6")) {
          sd.hierarchy_linked_object = null;
        }
        if (((ref5 = this.editor_data._tags) != null ? ref5.length : void 0) > 0) {
          sd.tags = this.editor_data._tags;
        } else {
          sd.tags = null;
        }
        if (ez5.version("6")) {
          sd.mapping_recipe_configs = this.editor_data.mapping_recipe_configs || null;
        }
        if (this.editor_data._create_objects.plugin) {
          sd.plugin = this.editor_data._create_objects.plugin;
        }
      } else {
        empty_pools = null;
        if (!ez5.version("6")) {
          empty_pools = {};
        }
        sd = {
          objecttype: null,
          mask_id: null,
          pool_id: null,
          linked_pool_id: null,
          eas_field: null,
          tags: null,
          linked_object_pools: empty_pools
        };
      }
      save_data.collection.create_object = sd;
    }
    return save_data;
  };

  CollectionStorable.prototype.getDescription = function() {
    return ez5.loca.getBestFrontendValue(this.data.collection.description);
  };

  CollectionStorable.prototype.getLinkedObjectPools = function() {
    var _linkedObjectPools, field, pool, pool_id, ref, ref1, ref2;
    if (!this.editor_data.linked_object_pools || !this.editor_data.select_individual_pools) {
      if (!ez5.version("6")) {
        return {};
      }
      return null;
    }
    _linkedObjectPools = {};
    ref = this.editor_data.linked_object_pools;
    for (field in ref) {
      pool = ref[field];
      if (!pool) {
        if (ez5.version("6")) {
          pool_id = ((ref1 = this.editor_data._pool) != null ? ref1.pool._id : void 0) || 2;
        } else {
          pool_id = (ref2 = this.editor_data._pool) != null ? ref2.pool._id : void 0;
        }
        _linkedObjectPools[field] = {
          pool: {
            _id: pool_id
          }
        };
      } else {
        _linkedObjectPools[field] = pool;
      }
    }
    return _linkedObjectPools;
  };

  CollectionStorable.prototype.getCounterItems = function() {
    return [];
  };

  CollectionStorable.prototype.__showWaitModal = function(status, attrs) {
    var i, info, k, len1, ref, ref1;
    if (attrs == null) {
      attrs = {};
    }
    info = this.__fileUpload.getInfo();
    ref = ["count", "done", "total", "loaded", "percent"];
    for (i = 0, len1 = ref.length; i < len1; i++) {
      k = ref[i];
      if (k === "total" || k === "loaded") {
        attrs[k] = ez5.format_filesize(info[k]);
      } else if (k === "done") {
        attrs[k] = info[k] + 1;
      } else {
        attrs[k] = info[k];
      }
    }
    attrs.collection = this.renderNameAsText();
    return (ref1 = this.__upload_editor) != null ? ref1.showWaitModal(status, attrs, this.__upload_abort_btn) : void 0;
  };

  CollectionStorable.prototype.__initReport = function() {
    this.__fileObjectArray = [];
    this.__filesUploadLogs = {
      updated: [],
      created: [],
      linked: [],
      skipped: [],
      notFound: [],
      error: [],
      plugin: []
    };
  };

  CollectionStorable.prototype.__showReport = function() {
    var modal, uploadPluginName;
    this.__clearUpload();
    if (ez5.version("6")) {
      this.__reloadCollectionChildren();
    }
    if (Object.values(this.__filesUploadLogs).every((function(_this) {
      return function(logs) {
        return logs.length === 0;
      };
    })(this))) {
      return;
    }
    if (ez5.version("6") && this.hasUploadPluginConfigured()) {
      uploadPluginName = this.getUploadPlugin();
      if (ez5.loca.has(uploadPluginName + ".report.msg")) {
        this.__filesUploadLogs["plugin"].push({
          text: $$(uploadPluginName + ".report.msg")
        });
      }
    }
    modal = new CUI.Modal({
      "class": "ez5-collection-hotfolder-report",
      pane: {
        header_left: new CUI.Label({
          text: $$("collection.storable.hotfolder.report.title")
        }),
        content: (function(_this) {
          return function() {
            var content, i, len1, li, log, logs, ref, title, type, ul;
            content = [
              new CUI.Label({
                text: $$("collection.storable.hotfolder.report.description.md"),
                markdown: true
              })
            ];
            ref = _this.__filesUploadLogs;
            for (type in ref) {
              logs = ref[type];
              if (logs.length === 0) {
                continue;
              }
              ul = CUI.dom.ul();
              for (i = 0, len1 = logs.length; i < len1; i++) {
                log = logs[i];
                li = CUI.dom.li();
                CUI.dom.append(li, new CUI.Label({
                  text: log.text,
                  markdown: true
                }));
                CUI.dom.append(ul, li);
              }
              if (type === "plugin") {
                title = new CUI.Label({
                  text: $$("collection.storable.hotfolder.report.log.title-" + uploadPluginName),
                  markdown: true,
                  multiLine: true
                });
              } else {
                title = new CUI.Label({
                  text: $$("collection.storable.hotfolder.report.log.title-" + type, {
                    count: logs.length
                  }),
                  markdown: true
                });
              }
              content.push(title);
              content.push(ul);
            }
            return new CUI.VerticalList({
              content: content
            });
          };
        })(this),
        footer_right: new CUI.Button({
          text: $$("base.ok"),
          onClick: (function(_this) {
            return function() {
              return modal.destroy();
            };
          })(this)
        })
      }
    });
    modal.show();
  };

  CollectionStorable.prototype.__reloadCollectionChildren = function() {
    var tree;
    if (!this.isAddedToListView()) {
      return;
    }
    if (this.isLoading()) {
      return;
    }
    tree = this.getTree();
    if (!tree) {
      return;
    }
    this.reload().done((function(_this) {
      return function() {
        _this.children = null;
        if (_this.isLeaf() || _this.isLoading()) {
          return;
        }
        return _this.open();
      };
    })(this));
  };

  CollectionStorable.prototype.__isUpdateObjectEnabled = function() {
    var config, ref;
    config = this.data._create_object_compiled;
    if ((ref = config.update_mode) !== "update" && ref !== "upsert") {
      return false;
    }
    if (!config.update_policy || !config.update_search_field) {
      return false;
    }
    return true;
  };

  CollectionStorable.prototype.__searchObjectWithFile = function(file) {
    var config, deferred, filename, matchName, names, objecttype, objecttypeName, ref, searchObject, updateSearchFieldFullName;
    if (!this.__isUpdateObjectEnabled()) {
      this.__fileObjectArray.push({
        file: file
      });
      return;
    }
    config = this.data._create_object_compiled;
    objecttype = ez5.schema.CURRENT._table_by_name[config.objecttype];
    if (!objecttype) {
      this.__filesUploadLogs.error.push({
        text: $$("collection.storable.hotfolder.log.error.objecttype-not-found", {
          objecttype: config.objecttype
        })
      });
      return CUI.rejectedPromise();
    }
    objecttypeName = objecttype._name_localized;
    updateSearchFieldFullName = config.update_search_field;
    deferred = new CUI.Deferred();
    filename = file.getName();
    names = [filename, ez5.bareBasename(filename)];
    if (this.data.collection.create_object.recognize_series) {
      matchName = (ref = ez5.basename(filename).match(EditorModalNew.MATCH_FILENAME_REGEXP)) != null ? ref[1] : void 0;
      if (matchName) {
        names.push(matchName);
      }
    }
    this.__showWaitModal("searching", {
      filename: filename,
      objecttype: objecttypeName
    });
    searchObject = (function(_this) {
      return function(index) {
        if (!names[index]) {
          if (config.update_mode === "upsert") {
            _this.__fileObjectArray.push({
              file: file
            });
            return deferred.resolve();
          } else {
            _this.__filesUploadLogs.notFound.push({
              text: $$("collection.storable.hotfolder.log.not-found", {
                filename: filename,
                objecttype: objecttypeName
              })
            });
            return deferred.reject();
          }
        }
        return ez5.api.search({
          json_data: {
            format: "long",
            limit: 2,
            search: [
              {
                fields: [updateSearchFieldFullName],
                type: "match",
                mode: "fulltext",
                string: names[index]
              }
            ]
          }
        }).done(function(data) {
          var object, ref1;
          if (data.objects.length > 1) {
            _this.__filesUploadLogs.error.push({
              text: $$("collection.storable.hotfolder.log.error.multiple-objects-found", {
                filename: filename,
                objecttype: objecttypeName
              })
            });
            return deferred.reject();
          }
          if (!((ref1 = data.objects) != null ? ref1[0] : void 0)) {
            return searchObject(++index);
          }
          object = data.objects[0];
          _this.__fileObjectArray.push({
            file: file,
            object: object
          });
          return deferred.resolve();
        });
      };
    })(this);
    searchObject(0);
    return deferred.promise();
  };

  CollectionStorable.prototype.__createUploadEditor = function() {
    if (this.__upload_editor) {
      return;
    }
    this.__upload_editor = new EditorHeadlessNew({
      collection: this
    });
    this.__initFromDb = this.loadFromDb();
    this.__upload_abort_btn = new LocaButton({
      loca_key: "collection.storable.abort_upload",
      onClick: (function(_this) {
        return function() {
          return _this.__clearUpload();
        };
      })(this)
    });
  };

  CollectionStorable.prototype.__clearUpload = function() {
    if (!this.__upload_editor) {
      return;
    }
    this.__upload_editor.destroy();
    this.__fileUpload.clear();
    return delete this.__upload_editor;
  };

  CollectionStorable.prototype.__initUploadEditor = function() {
    var co, mask_name;
    co = this.data._create_object_compiled;
    mask_name = ez5.mask.CURRENT._mask_by_id[co.mask_id].name;
    this.__upload_editor.initEditorDataFields();
    this.__upload_editor.editor_data.mask_name = mask_name;
    this.__upload_editor.editor_data.recognize_series = co.recognize_series;
    this.__upload_editor.editor_data.recognise_version = co.recognize_version;
    this.__upload_editor.setTableByName(co.objecttype);
    this.__upload_editor.setPoolFromPoolId(co.pool_id);
    this.__upload_editor.setTags(co.tags);
    this.__upload_editor.setMapping(co.mapping);
    if (co.mapping_recipe_configs) {
      this.__upload_editor.editor_data.mapping_recipe_configs = co.mapping_recipe_configs;
    }
    this.__setLinkedObjectPoolFromPoolId(co.linked_pool_id);
    this.__setLinkedObjectPoolsEditorData(co.linked_object_pools, this.__upload_editor.editor_data);
  };

  CollectionStorable.prototype.__setLinkedObjectPoolFromPoolId = function(linkedPoolId) {
    var pool;
    pool = ez5.pools.findPoolById(linkedPoolId);
    if (!pool) {
      delete this.__upload_editor.editor_data.linked_pool;
      return;
    }
    this.__upload_editor.editor_data.linked_pool = pool.getData();
  };

  CollectionStorable.prototype.__setLinkedObjectPoolsEditorData = function(linked_object_pools, editorData) {
    var fieldName, objecctypeName, pool, poolData;
    if (!editorData) {
      return;
    }
    for (fieldName in linked_object_pools) {
      poolData = linked_object_pools[fieldName];
      objecctypeName = editorData.table.schema.name;
      pool = ez5.pools.findPoolById(poolData.pool._id);
      if (!pool) {
        continue;
      }
      editorData["_pool_" + objecctypeName + "." + fieldName] = pool != null ? pool.getData() : void 0;
    }
  };

  CollectionStorable.prototype.__saveUpload = function() {
    var master_dfr;
    master_dfr = new CUI.Deferred();
    this.__upload_abort_btn.disable();
    this.__showWaitModal('storing');
    this.__initFromDb.done((function(_this) {
      return function() {
        var bulk_field, config, dfr, dupDialog, file, filesAccepted, fn, i, len1, object, objectsByGlobalObjectId, promises, ref, ref1;
        _this.__initUploadEditor();
        config = _this.data._create_object_compiled;
        bulk_field = _this.__upload_editor.setEASFieldByCollectionStoreName(config.eas_field);
        if (!bulk_field) {
          _this.__filesUploadLogs.error.push({
            text: $$('collection.storable.upload_error_eas_field_not_found')
          });
          master_dfr.reject();
          return;
        }
        promises = [];
        dupDialog = new DuplicatesDialog({
          ui: "collection.storable.duplicates.dialog"
        });
        filesAccepted = [];
        objectsByGlobalObjectId = {};
        ref = _this.__fileObjectArray;
        fn = function(dfr, file, object) {
          return dupDialog.addFile(file).done(function() {
            file._value = {
              _id: file.getData()[0]._id,
              original_filename: file.getName()
            };
            if (object != null ? object._global_object_id : void 0) {
              if (objectsByGlobalObjectId[object._global_object_id]) {
                object = objectsByGlobalObjectId[object._global_object_id];
              } else {
                objectsByGlobalObjectId[object._global_object_id] = object;
              }
            }
            filesAccepted.push({
              file: file,
              object: object
            });
            return dfr.resolve();
          }).fail(function() {
            _this.__filesUploadLogs.skipped.push({
              text: $$("collection.storable.hotfolder.log.skipped.duplicated-file", {
                filename: file.getName()
              })
            });
            return dfr.resolve();
          });
        };
        for (i = 0, len1 = ref.length; i < len1; i++) {
          ref1 = ref[i], file = ref1.file, object = ref1.object;
          dfr = new CUI.Deferred();
          promises.push(dfr);
          fn(dfr, file, object);
        }
        return CUI.when(promises).done(function() {
          var filesInsert, filesUpdate, j, len2, ref2;
          if (filesAccepted.length === 0) {
            master_dfr.resolve();
            return;
          }
          filesInsert = [];
          filesUpdate = [];
          for (j = 0, len2 = filesAccepted.length; j < len2; j++) {
            ref2 = filesAccepted[j], file = ref2.file, object = ref2.object;
            if (object) {
              filesUpdate.push({
                file: file,
                object: object
              });
            } else {
              filesInsert.push({
                file: file
              });
            }
          }
          _this.__upload_editor.setCollectionMode("new");
          return _this.__saveObjects(filesInsert).done(function(newResultObjects) {
            if (newResultObjects == null) {
              newResultObjects = [];
            }
            _this.__upload_editor.setCollectionMode("update");
            return _this.__saveObjects(filesUpdate, true).done(function(updatedResultObjects) {
              var collections, l, len3, resultObject, updatedCollectionObjects;
              if (updatedResultObjects == null) {
                updatedResultObjects = [];
              }
              updatedCollectionObjects = [];
              for (l = 0, len3 = updatedResultObjects.length; l < len3; l++) {
                resultObject = updatedResultObjects[l];
                collections = resultObject.getData()._collections;
                if (collections && CUI.util.idxInArray(null, collections, function(collection) {
                  return collection._id === _this.getId();
                }) >= 0) {
                  continue;
                }
                updatedCollectionObjects.push(resultObject.getCollectionObject());
              }
              return _this.__addUpdatedObjectsToCollection(updatedCollectionObjects, filesUpdate).done(function() {
                return _this.__addObjectsToCollection(newResultObjects, filesInsert).done(function() {
                  var len4, m;
                  for (m = 0, len4 = newResultObjects.length; m < len4; m++) {
                    resultObject = newResultObjects[m];
                    _this.__addObjectLinkedToCollectionLog(resultObject, filesInsert);
                  }
                  if (updatedCollectionObjects.length === 0) {
                    _this.data._count += newResultObjects.length;
                  }
                  _this.makeDroppable(_this.getDOMNodes()[0]);
                  _this.updateDisplay(true);
                }).fail(function() {
                  var len4, m;
                  for (m = 0, len4 = newResultObjects.length; m < len4; m++) {
                    resultObject = newResultObjects[m];
                    _this.__addObjectLinkedToCollectionLog(resultObject, filesInsert, true);
                  }
                }).always(master_dfr.resolve);
              });
            });
          });
        });
      };
    })(this)).fail(master_dfr.reject);
    return master_dfr.promise();
  };

  CollectionStorable.prototype.__saveObjects = function(files, isUpdate) {
    var bulk_field, config, deferred, dfr, file, fileWithObject, filesCount, fn, i, index, len1, object, promise, promises, ref, updatePolicy;
    if (isUpdate == null) {
      isUpdate = false;
    }
    if (files.length === 0) {
      return CUI.resolvedPromise([]);
    }
    deferred = new CUI.Deferred();
    config = this.data._create_object_compiled;
    bulk_field = this.__upload_editor.setEASFieldByCollectionStoreName(config.eas_field);
    this.__upload_editor.getObjectList().removeAll();
    filesCount = 0;
    promises = [];
    fn = (function(_this) {
      return function(file, object, index) {
        return promise.done(function(resultObject) {
          if (!isUpdate) {
            files[index].object = resultObject;
          }
          return filesCount++;
        }).fail(function(error) {
          var errorKey, ref;
          if (object && config.update_policy === EditorModalNew.FILE_APPEND_TYPE_REFUSE) {
            return _this.__filesUploadLogs.skipped.push({
              text: $$("collection.storable.hotfolder.log.skipped.object-has-file", {
                system_object_id: object._system_object_id,
                filename: file.getName()
              })
            });
          } else {
            error = (error != null ? (ref = error.responseJSON) != null ? ref.description : void 0 : void 0) || $$("collection.storable.hotfolder.log.error.unknown");
            errorKey = object ? "add-file-with-object-to-editor" : "add-file-to-editor";
            return _this.__filesUploadLogs.error.push({
              text: $$("collection.storable.hotfolder.log.error." + errorKey, {
                error: error,
                system_object_id: object != null ? object.system_object_id : void 0,
                filename: file.getName()
              })
            });
          }
        }).always(dfr.resolve);
      };
    })(this);
    for (index = i = 0, len1 = files.length; i < len1; index = ++i) {
      fileWithObject = files[index];
      file = fileWithObject.file;
      object = fileWithObject.object;
      dfr = new CUI.Deferred();
      promises.push(dfr);
      if (isUpdate) {
        updatePolicy = (ref = this.data._create_object_compiled) != null ? ref.update_policy : void 0;
        promise = this.__upload_editor.addFileWithObjectToEditor(file, object, updatePolicy);
      } else {
        promise = this.__upload_editor.addFileToEditor(file);
      }
      fn(file, object, index);
    }
    CUI.when(promises).done((function(_this) {
      return function() {
        if (filesCount === 0) {
          return deferred.resolve([]);
        }
        return _this.__upload_editor.save().done(function(createdObjects) {
          var action, createdObject, fileNames, fileObject, j, l, len2, len3, ref1, ref2, resultObjects;
          if (isUpdate) {
            for (index = j = 0, len2 = files.length; j < len2; index = ++j) {
              fileObject = files[index];
              file = fileObject.file, object = fileObject.object;
              if (bulk_field.supportsSeries()) {
                action = "append";
              } else {
                action = updatePolicy;
              }
              _this.__filesUploadLogs.updated.push({
                text: $$("collection.storable.hotfolder.log.updated", {
                  system_object_id: object._system_object_id,
                  filename: file.getName(),
                  action: $$("collection.storable.hotfolder.log.updated.update_policy-" + action),
                  standard: ez5.loca.getBestFrontendValue(((ref1 = object._standard[1]) != null ? ref1.text : void 0) || ((ref2 = object._standard[2]) != null ? ref2.text : void 0))
                })
              });
            }
          } else {
            for (l = 0, len3 = createdObjects.length; l < len3; l++) {
              createdObject = createdObjects[l];
              fileNames = files.filter(function(arg) {
                var _, object;
                _ = arg._, object = arg.object;
                return createdObject._system_object_id === object.getSystemObjectId();
              }).map(function(fileObject) {
                return fileObject.file.getName();
              }).join(", ");
              _this.__filesUploadLogs.created.push({
                text: $$("collection.storable.hotfolder.log.created", {
                  system_object_id: createdObject._system_object_id,
                  filename: fileNames
                })
              });
            }
          }
          resultObjects = _this.__upload_editor.object_list.getObjects();
          return deferred.resolve(resultObjects);
        }).fail(function(error) {
          var j, len2, ref1, ref2, ref3, text;
          error = (error != null ? (ref1 = error.responseJSON) != null ? ref1.description : void 0 : void 0) || (error != null ? (ref2 = error.responseJSON) != null ? ref2.error : void 0 : void 0) || $$("collection.storable.hotfolder.log.error.unknown");
          for (j = 0, len2 = files.length; j < len2; j++) {
            ref3 = files[j], file = ref3.file, object = ref3.object;
            if (object && object._system_object_id) {
              text = $$("collection.storable.hotfolder.log.error.object-update", {
                system_object_id: object._system_object_id,
                filename: file.getName(),
                error: error
              });
            } else {
              text = $$("collection.storable.hotfolder.log.error.object-create", {
                filename: file.getName(),
                error: error
              });
            }
            _this.__filesUploadLogs.error.push({
              text: text
            });
          }
          return deferred.resolve([]);
        });
      };
    })(this));
    return deferred.promise();
  };

  CollectionStorable.prototype.__addObjectLinkedToCollectionLog = function(resultObject, filesWithObject, fail) {
    var fileNames, systemObjectId;
    if (fail == null) {
      fail = false;
    }
    if (resultObject instanceof ResultObject) {
      systemObjectId = resultObject.getSystemObjectId();
    } else {
      systemObjectId = resultObject.getObject()._system_object_id;
    }
    fileNames = filesWithObject.filter(function(arg) {
      var _, object, otherSystemObjectId;
      _ = arg._, object = arg.object;
      if (object instanceof ResultObject) {
        otherSystemObjectId = object.getSystemObjectId();
      } else {
        otherSystemObjectId = object != null ? object._system_object_id : void 0;
      }
      return systemObjectId === otherSystemObjectId;
    }).map(function(fileObject) {
      return fileObject.file.getName();
    }).join(", ");
    if (fail) {
      return this.__filesUploadLogs.error.push({
        text: $$("collection.storable.hotfolder.log.error.object-not-linked", {
          system_object_id: systemObjectId,
          filename: fileNames
        })
      });
    } else {
      return this.__filesUploadLogs.linked.push({
        text: $$("collection.storable.hotfolder.log.linked", {
          system_object_id: systemObjectId,
          filename: fileNames
        })
      });
    }
  };

  CollectionStorable.prototype.__addUpdatedObjectsToCollection = function(collectionObjects, filesWithObject) {
    var deferred;
    if (collectionObjects == null) {
      collectionObjects = [];
    }
    if (filesWithObject == null) {
      filesWithObject = [];
    }
    if (collectionObjects.length === 0) {
      return CUI.resolvedPromise();
    }
    this.__showWaitModal('linking_updated_objects');
    deferred = new CUI.Deferred();
    this.insertObjects(collectionObjects).done((function(_this) {
      return function() {
        var collectionObject, i, len1;
        for (i = 0, len1 = collectionObjects.length; i < len1; i++) {
          collectionObject = collectionObjects[i];
          _this.__addObjectLinkedToCollectionLog(collectionObject, filesWithObject);
        }
        return deferred.resolve();
      };
    })(this)).fail((function(_this) {
      return function() {
        var addToCollectionPromises, collectionObject, fn, i, len1;
        addToCollectionPromises = [];
        fn = function(collectionObject) {
          var promise;
          promise = _this.insertObjects([collectionObject]).done(function() {
            return _this.__addObjectLinkedToCollectionLog(collectionObject, filesWithObject);
          }).fail(function() {
            return _this.__addObjectLinkedToCollectionLog(collectionObject, filesWithObject, true);
          });
          return addToCollectionPromises.push(promise);
        };
        for (i = 0, len1 = collectionObjects.length; i < len1; i++) {
          collectionObject = collectionObjects[i];
          fn(collectionObject);
        }
        return CUI.whenAll(addToCollectionPromises).done(deferred.resolve).fail(deferred.resolve);
      };
    })(this));
    return deferred.promise();
  };

  CollectionStorable.prototype.__addObjectsToCollection = function(resultObjects) {
    var cos, i, len1, ro;
    if (resultObjects == null) {
      resultObjects = [];
    }
    if (resultObjects.length === 0) {
      return CUI.resolvedPromise();
    }
    cos = [];
    for (i = 0, len1 = resultObjects.length; i < len1; i++) {
      ro = resultObjects[i];
      cos.push(ro.getCollectionObject());
    }
    return this.triggerEvent("insert", {
      collection_objects: cos
    });
  };

  CollectionStorable.prototype.makeDroppable = function(el) {
    CollectionStorable.__super__.makeDroppable.call(this, el);
    this.initDropzone(el);
    return this;
  };

  CollectionStorable.prototype.makeDetailDroppable = function(el) {
    CollectionStorable.__super__.makeDetailDroppable.call(this, el);
    if (this.canUpload()) {
      this.initDropzone(el);
    }
    return this;
  };

  CollectionStorable.prototype.__initFylrDropFileUpload = function(el) {
    this.__initReport();
    return this.__fileUpload = new CUI.FileUpload({
      url: ez5.eas.getUploadUrl({
        collection: this.getId()
      }),
      onAdd: (function(_this) {
        return function(fileUploadFile) {
          var parms, rawFile;
          rawFile = fileUploadFile.getFile();
          if (rawFile._relativePath) {
            parms = {
              collection: _this.getId(),
              filenames: JSON.stringify([rawFile._relativePath])
            };
            if (rawFile._skipDuplicateCheck) {
              parms.check_for_duplicates = false;
            }
            rawFile.upload_url = ez5.eas.getUploadUrl(parms);
          }
        };
      })(this),
      onBatchStart: (function(_this) {
        return function() {
          return _this.__createUploadEditor();
        };
      })(this),
      onProgress: (function(_this) {
        return function() {
          return _this.__showWaitModal("uploading");
        };
      })(this),
      onFail: (function(_this) {
        return function(file) {
          if (file.getStatus() !== "ABORT") {
            EAS.presentUploadError(file);
          }
          return _this.__clearUpload();
        };
      })(this),
      onDone: (function(_this) {
        return function(file) {
          var data, fileNames, i, len1, linked, ref, ref1, ref2, ref3, ref4, results, systemObjectId, version;
          if (((ref = file.getData()) != null ? (ref1 = ref[0]._duplicates) != null ? ref1.length : void 0 : void 0) > 0) {
            if (_this.__duplicateFiles == null) {
              _this.__duplicateFiles = [];
            }
            _this.__duplicateFiles.push(file);
            return;
          }
          if (file.getStatus() === "DONE") {
            data = (ref2 = file.getData()) != null ? ref2[0] : void 0;
            if ((data != null ? (ref3 = data._linked_objects) != null ? ref3.length : void 0 : void 0) > 0) {
              ref4 = data._linked_objects;
              results = [];
              for (i = 0, len1 = ref4.length; i < len1; i++) {
                linked = ref4[i];
                systemObjectId = linked._system_object_id;
                fileNames = file.getName();
                version = linked._version || 1;
                if (version === 1) {
                  results.push(_this.__filesUploadLogs.created.push({
                    text: $$("collection.storable.hotfolder.log.created", {
                      system_object_id: systemObjectId,
                      filename: fileNames
                    })
                  }));
                } else {
                  results.push(_this.__filesUploadLogs.updated.push({
                    text: $$("collection.storable.hotfolder.log.updated_simple", {
                      system_object_id: systemObjectId,
                      filename: fileNames
                    })
                  }));
                }
              }
              return results;
            }
          }
        };
      })(this),
      onBatchDone: (function(_this) {
        return function() {
          var dupDialog, duplicatePromises, file, fn, i, len1, ref, reimportFiles;
          reimportFiles = [];
          duplicatePromises = [];
          if (_this.__duplicateFiles && _this.__duplicateFiles.length > 0) {
            dupDialog = new DuplicatesDialog({
              ui: "asset.versions.duplicates.dialog"
            });
            ref = _this.__duplicateFiles;
            fn = function(file) {
              var dupDfr;
              dupDfr = dupDialog.addFile(file).done(function(solution) {
                var originalFile;
                originalFile = file.getFile();
                originalFile._skipDuplicateCheck = true;
                originalFile.upload_url = ez5.eas.getUploadUrl({
                  collection: _this.getId(),
                  check_for_duplicates: false
                });
                return reimportFiles.push(originalFile);
              }).fail(function(solution) {
                if (solution === "skip") {
                  _this.__filesUploadLogs.skipped.push({
                    text: $$("collection.storable.hotfolder.log.skipped.duplicated-file", {
                      filename: file.getName()
                    })
                  });
                }
              });
              return duplicatePromises.push(dupDfr);
            };
            for (i = 0, len1 = ref.length; i < len1; i++) {
              file = ref[i];
              fn(file);
            }
            delete _this.__duplicateFiles;
            CUI.whenAll(duplicatePromises).done(function() {
              if (reimportFiles.length > 0) {
                _this.__fileUpload.clear();
                _this.__fileUpload.queueFiles(reimportFiles);
              } else {
                _this.__showReport();
                return _this.__initReport();
              }
            });
            return;
          } else {
            _this.__showReport();
            _this.__initReport();
          }
        };
      })(this)
    });
  };

  CollectionStorable.prototype.__initDropFileUpload = function() {
    return this.__fileUpload = new CUI.FileUpload({
      url: ez5.eas.getUploadUrl(),
      onBatchStart: (function(_this) {
        return function() {
          _this.__createUploadEditor();
          return _this.__initReport();
        };
      })(this),
      onBatchQueued: (function(_this) {
        return function() {
          if (_this.__fileUpload.getFiles().length === 0) {
            return _this.__showReport();
          }
        };
      })(this),
      onAdd: (function(_this) {
        return function(file) {
          return _this.__searchObjectWithFile(file);
        };
      })(this),
      onBatchDone: (function(_this) {
        return function() {
          if (!_this.__upload_editor) {
            return;
          }
          _this.__saveUpload().always(function() {
            return _this.__showReport();
          });
        };
      })(this),
      onProgress: (function(_this) {
        return function() {
          return _this.__showWaitModal("uploading");
        };
      })(this),
      onFail: (function(_this) {
        return function(file) {
          if (file.getStatus() !== "ABORT") {
            EAS.presentUploadError(file);
          }
          return _this.__clearUpload();
        };
      })(this)
    });
  };

  CollectionStorable.prototype.initDropzone = function(el) {
    var ref;
    if (this.hasUploadConfigured()) {
      if (!this.__fileUpload) {
        if (ez5.version("6.10")) {
          this.__initFylrDropFileUpload();
        } else {
          this.__initDropFileUpload();
        }
      }
      this.__fileUpload.initDropZone({
        dropZone: el,
        allow_drop: (function(_this) {
          return function(ev) {
            _this.loadGeneratedRights();
            return _this.canUpload();
          };
        })(this)
      });
    } else {
      if ((ref = this.__fileUpload) != null) {
        ref.resetDropZones();
      }
    }
  };

  CollectionStorable.prototype.hasUploadConfigured = function() {
    var idPool, pool, ref;
    if ((ref = this.data._create_object_compiled) != null ? ref.eas_field : void 0) {
      if (ez5.schema.CURRENT._table_by_name[this.data._create_object_compiled.objecttype].pool_link) {
        idPool = this.data._create_object_compiled.linked_pool_id || this.data._create_object_compiled.pool_id;
        pool = ez5.pools.findPoolById(idPool);
        if (!pool) {
          console.info("CollectionStorable: No upload possible, pool not readable:", this.data._create_object_compiled.pool_id);
          return false;
        } else {
          return true;
        }
      } else {
        return true;
      }
    } else {
      return false;
    }
  };

  CollectionStorable.prototype.canUpload = function() {
    if (!this.hasUploadConfigured()) {
      return false;
    }
    if (this.canCreateInCollection()) {
      return true;
    }
    if (this.canAppend()) {
      return true;
    }
    return false;
  };

  CollectionStorable.prototype.editPromptText = function() {
    return $$("collection.storable.name_prompt_text");
  };

  CollectionStorable.prototype.edit = function() {
    var dfr;
    dfr = new CUI.Deferred();
    this.loadFromDb().done((function(_this) {
      return function() {
        var checkChangedStatus, data, displayNameForm, modal, saveButton;
        if (!_this.data.collection.displayname) {
          _this.data.collection.displayname = {};
        }
        saveButton = new CUI.Button({
          primary: true,
          left: true,
          text: $$("collection.storable.button_prompt_ok"),
          ui: "collection.storable.modal-form.ok.button",
          onClick: function(ev) {
            _this.data.collection.displayname = data.displayname;
            saveButton.startSpinner();
            return _this.save(ev).always(function() {
              return saveButton.stopSpinner();
            }).done(function() {
              modal.destroy();
              return dfr.resolve(_this);
            });
          }
        });
        data = {
          displayname: CUI.util.copyObject(_this.data.collection.displayname)
        };
        displayNameForm = new CUI.Form({
          data: data,
          onDataChanged: function() {
            return checkChangedStatus();
          },
          fields: [
            {
              ui: "collection.storable.modal-form.displayname",
              name: "displayname",
              "class": "ez5-collection-displayname",
              type: CUI.MultiInput,
              control: ez5.loca.getLanguageControl(),
              undo_and_changed_support: true,
              user_selectable: ez5.session.getPref("languages_user_selection")
            }
          ]
        });
        displayNameForm.start();
        checkChangedStatus = function() {
          var hasData, i, language, len1, ref;
          hasData = false;
          ref = ez5.loca.getDatabaseLanguages();
          for (i = 0, len1 = ref.length; i < len1; i++) {
            language = ref[i];
            if (!CUI.util.isEmpty(data.displayname[language])) {
              hasData = true;
              break;
            }
          }
          if (hasData && (displayNameForm.isChanged() || !_this.getId())) {
            return saveButton.enable();
          } else {
            return saveButton.disable();
          }
        };
        checkChangedStatus();
        modal = new CUI.Modal({
          onShow: function() {
            return displayNameForm.getFields()[0].focus();
          },
          pane: {
            padded: true,
            header_left: new CUI.Label({
              text: _this.editPromptText()
            }),
            content: displayNameForm,
            footer_right: [
              {
                text: CUI.Button.defaults.confirm_cancel,
                ui: "collection.storable.modal-form.cancel.button",
                onClick: function() {
                  if (!_this.getId()) {
                    _this.remove(false, false).always(dfr.reject);
                  } else {
                    dfr.reject();
                  }
                  return modal.destroy();
                }
              }, saveButton
            ]
          }
        });
        return modal.show();
      };
    })(this));
    return dfr.promise();
  };

  CollectionStorable.prototype.save = function(ev, save_data) {
    var api, dfr;
    if (save_data == null) {
      save_data = this.getSaveData();
    }
    if (this.getId()) {
      api = "/collection/" + (this.getId());
      save_data.collection._version++;
    } else {
      api = "/collection";
      save_data.collection._version = 1;
    }
    if (ev != null ? ev.hasModifierKey() : void 0) {
      console.debug(CUI.util.getObjectClass(this), CUI.util.dump(save_data));
      dfr = new CUI.Deferred();
      dfr.reject();
      return dfr.promise();
    }
    return ez5.server({
      api: api,
      type: this.getId() ? "POST" : "PUT",
      json_data: save_data
    }).done((function(_this) {
      return function(data) {
        _this.__loadedFromDb = true;
        _this.setData(data);
        if (_this.isAddedToListView()) {
          _this.makeDroppable(_this.getDOMNodes()[0]);
          if (_this.searchCollection) {
            _this.makeDetailDroppable(_this.searchCollection.getResultContainer());
          }
          _this.updateDisplay(true);
        }
        return _this.triggerEvent("update");
      };
    })(this));
  };

  CollectionStorable.prototype.isRenamable = function() {
    return this.isWritable();
  };

  CollectionStorable.prototype.prepareCurrentTools = function() {
    var dfr;
    dfr = new CUI.Deferred();
    CollectionStorable.__super__.prepareCurrentTools.call(this).fail(dfr.reject).done((function(_this) {
      return function() {
        if (!_this.getId()) {
          dfr.resolve();
          return;
        }
        return ez5.api.search({
          json_data: {
            type: "collection",
            limit: 1,
            generate_rights: true,
            search: [
              {
                type: "in",
                fields: ["collection._id"],
                "in": [_this.getId()]
              }
            ]
          }
        }).fail(dfr.reject).done(function(data) {
          if (data.count === 1) {
            _this.data._generated_rights = data.objects[0]._generated_rights;
          } else {
            _this.data._generated_rights = {};
          }
          return dfr.resolve();
        });
      };
    })(this));
    return dfr.promise();
  };

  CollectionStorable.prototype.allowSubcollectionSearch = function() {
    return true;
  };

  CollectionStorable.prototype.getCurrentTools = function() {
    var tools;
    tools = CollectionStorable.__super__.getCurrentTools.call(this);
    if (this.isRenamable()) {
      tools.push(new ToolboxTool({
        group: "collection",
        name: "collection.rename",
        sort: "H:1",
        run: (function(_this) {
          return function() {
            return _this.edit();
          };
        })(this)
      }));
    }
    if (this.isCreateChildAllowed()) {
      tools.push(new ToolboxTool({
        group: "collection",
        name: "collection.new_child",
        sort: "H:1",
        run: (function(_this) {
          return function() {
            var mng;
            mng = _this.getManager();
            return mng.newCollection(mng.getCollectionWorkfolderClass(), _this);
          };
        })(this)
      }));
    }
    if (this.enableShare()) {
      tools.push(new ToolboxTool({
        group: "collection",
        name: "collection.share",
        sort: "F:2",
        favorite: true,
        run: (function(_this) {
          return function() {
            return _this.popoverEditorShare();
          };
        })(this)
      }));
    }
    if (this.enableSettings()) {
      tools.push(new ToolboxTool({
        group: "collection",
        name: "collection.settings",
        sort: "F:3",
        favorite: true,
        run: (function(_this) {
          return function() {
            return _this.popoverEditorSettings();
          };
        })(this)
      }));
    }
    if (this.isDeletable()) {
      tools.push(new ToolboxTool({
        group: "collection",
        name: "collection.delete",
        sort: "H:5",
        run: (function(_this) {
          return function() {
            return _this["delete"]();
          };
        })(this)
      }));
    }
    if (ez5.connector) {
      tools.push.apply(tools, ez5.connector.getCollectionTools(this));
    }
    return tools;
  };

  CollectionStorable.prototype.addedToListView = function(DOMNodes) {
    CollectionStorable.__super__.addedToListView.call(this, DOMNodes);
    if (this._readonly) {
      return this;
    }
    this.makeDraggable(DOMNodes[0]);
    return this;
  };

  CollectionStorable.prototype.makeDraggable = function(el) {
    new CUI.Draggable({
      element: el,
      create: (function(_this) {
        return function() {
          return {
            collectionStorable: _this
          };
        };
      })(this),
      axis: "y"
    });
  };

  CollectionStorable.prototype.loadGeneratedRights = function() {
    if (this.__loadedFromDb || this.__loadingFromDb) {
      return this;
    }
    this.loadFromDb();
    return this;
  };

  CollectionStorable.prototype.acceptDrop = function(ev, info) {
    var col;
    this.loadGeneratedRights();
    col = info.globalDrag.collectionStorable;
    if (!col) {
      return CollectionStorable.__super__.acceptDrop.call(this, ev, info);
    }
    if (indexOf.call(this.getPath(true), col) >= 0) {
      return false;
    }
    if (this === col.getFather()) {
      return false;
    }
    if (this.canHaveChildren()) {
      return true;
    } else {
      return false;
    }
  };

  CollectionStorable.prototype.takeDrop = function(ev, info) {
    var col;
    col = info.globalDrag.collectionStorable;
    if (!col) {
      return CollectionStorable.__super__.takeDrop.call(this, ev, info);
    }
    return col.loadFromDb().done((function(_this) {
      return function() {
        var sd;
        console.debug("col", col.getId(), "new father", _this.getId());
        sd = col.getSaveData();
        sd.collection._id_parent = _this.getId();
        return col.save(ev, sd).done(function() {
          var father;
          father = col.getFather();
          col.remove(false, false);
          return _this.addChild(col);
        });
      };
    })(this));
  };

  CollectionStorable.prototype.removeChild = function(child, keep_children_array) {
    if (keep_children_array == null) {
      keep_children_array = false;
    }
    if (this.children.length === 1 && !this.isRoot() && keep_children_array === false) {
      this.data._has_children = false;
    }
    return CollectionStorable.__super__.removeChild.call(this, child, keep_children_array);
  };

  CollectionStorable.prototype.deselect = function(ev) {
    return CollectionStorable.__super__.deselect.call(this, ev).done((function(_this) {
      return function() {
        return _this.__clearUpload();
      };
    })(this));
  };

  CollectionStorable.prototype.getId = function() {
    return this.data.collection._id;
  };

  CollectionStorable.prototype.getIdParent = function() {
    return this.data.collection._id_parent;
  };

  CollectionStorable.prototype.getVersion = function() {
    return this.data.collection._version;
  };

  CollectionStorable.prototype.getUUID = function() {
    return this.data.collection.uuid;
  };

  CollectionStorable.prototype.matchesLocator = function(locator) {
    return CollectionStorable.__super__.matchesLocator.call(this, locator) || this.getUUID() === locator;
  };

  CollectionStorable.prototype["delete"] = function() {
    var dfr;
    dfr = new CUI.Deferred();
    CUI.confirm({
      text: $$("collection.storable.delete.confirm_text"),
      button_text_ok: $$("collection.storable.delete.confirm_button")
    }).fail(dfr.reject).done((function(_this) {
      return function() {
        if (_this.getId()) {
          return ez5.api.collection({
            api: "/" + _this.getId(),
            type: "DELETE"
          }).done(function() {
            return _this.remove().done(dfr.resolve).fail(dfr.reject);
          }).fail(dfr.reject);
        } else {
          return _this.remove().done(dfr.resolve).fail(dfr.reject);
        }
      };
    })(this));
    return dfr.promise();
  };

  CollectionStorable.prototype.render = function() {
    CollectionStorable.__super__.render.call(this);
    if (this.__markForUpdate) {
      this.__markForUpdate = false;
      this.refresh(true);
    }
    return this;
  };

  CollectionStorable.prototype.renderNameAsHtml = function() {
    var name;
    name = ez5.loca.getBestDatabaseValue(this.data.collection.displayname, true);
    if (CUI.util.isEmpty(name)) {
      name = $$("collection.storable.placeholder");
    }
    return name;
  };

  CollectionStorable.prototype.renderNameAsText = function() {
    return ez5.loca.getBestDatabaseValue(this.data.collection.displayname);
  };

  CollectionStorable.prototype.refresh = function(handleError) {
    this.__loadedFromDb = false;
    return this.loadFromDb(handleError).done((function(_this) {
      return function() {
        return _this.updateDisplay();
      };
    })(this));
  };

  CollectionStorable.prototype.copy = function() {
    var col;
    col = CollectionStorable.__super__.copy.call(this);
    col.setData(this.getData());
    col.__loadedFromDb = this.__loadedFromDb;
    col.__subcollectionIds = this.__subcollectionIds;
    return col;
  };

  CollectionStorable.prototype.loadFromDb = function(handleError) {
    if (handleError == null) {
      handleError = false;
    }
    if (this.__loadedFromDb || !this.getId()) {
      return CUI.resolvedPromise(this.data);
    }
    if (this.__loadingFromDb) {
      return this.__loadingFromDb;
    }
    return this.__loadingFromDb = ez5.api.collection({
      api: "/" + this.getId(),
      handle_error: (function(_this) {
        return function() {
          return handleError;
        };
      })(this)
    }).done((function(_this) {
      return function(data) {
        _this.__loadedFromDb = true;
        return _this.setData(data);
      };
    })(this)).always((function(_this) {
      return function() {
        return delete _this.__loadingFromDb;
      };
    })(this));
  };

  CollectionStorable.prototype.createObjectsTab = function() {
    var dfr;
    dfr = new CUI.Deferred();
    this.loadFromDb().done((function(_this) {
      return function() {
        var co, data_hotfolder_urls, fields, general_form, hotfolder_url, i, idx, lay, len1, modal, new_editor, prefix, ref, ref1, ref2, ref3, ref4, ref5, ref6, set_create_objects_tab_state, set_fields;
        co = _this.data.collection.create_object;
        if (co.objecttype) {
          _this.editor_data = {
            choice_table_id: ((ref = ez5.schema.CURRENT._table_by_name[co.objecttype]) != null ? ref.table_id : void 0) || null,
            mask_name: ((ref1 = ez5.mask.CURRENT._mask_by_id[co.mask_id]) != null ? ref1.name : void 0) || null,
            bulk_field: null,
            mapping: co.mapping,
            mapping_recipe_configs: co.mapping_recipe_configs || void 0,
            _create_objects: true,
            _tags: co.tags || [],
            recognize_series: co.recognize_series,
            recognize_version: co.recognize_version,
            update_search_field: co.update_search_field,
            update_mode: co.update_mode || "insert",
            update_policy: co.update_policy || EditorModalNew.FILE_APPEND_TYPE_CREATE_PREFERRED,
            select_individual_pools: (ref2 = _this.data.collection) != null ? (ref3 = ref2.webfrontend_props) != null ? ref3.select_individual_pools : void 0 : void 0,
            plugin: co.plugin,
            plugin_config: co.plugin_config,
            hierarchy_linked_object_field: ((ref4 = co.hierarchy_linked_object) != null ? ref4.field : void 0) || null
          };
        } else {
          _this.editor_data = {
            _create_objects: false,
            bulk_field: null,
            recognize_series: true,
            recognize_version: false,
            update_mode: "insert",
            update_policy: EditorModalNew.FILE_APPEND_TYPE_CREATE_PREFERRED
          };
        }
        new_editor = new EditorHeadlessNew({
          data: _this.editor_data,
          hide_ignore_duplication_field: true,
          show_update_object_fields: ez5.version("6"),
          filterObjecttypeOption: function(option) {
            var easFields, idTable, objecttype;
            idTable = option.value;
            objecttype = new Objecttype(ez5.schema.CURRENT._table_by_id[idTable]);
            if (!objecttype) {
              return false;
            }
            objecttype.addAllMasks();
            if (objecttype.masks.length === 0) {
              return false;
            }
            easFields = objecttype.getEASFields("all");
            return easFields.length > 0;
          }
        });
        if ((ref5 = ez5.schema.CURRENT._table_by_name[co.objecttype]) != null ? ref5.pool_link : void 0) {
          new_editor.setPoolFromPoolId(co.pool_id);
        } else {
          delete _this.data.collection.create_object.pool_id;
          delete _this.data._create_object_compiled.pool_id;
        }
        if (co.objecttype) {
          new_editor.setTableByName(co.objecttype);
          new_editor.setEASFieldByCollectionStoreName(co.eas_field);
        }
        modal = null;
        lay = new CUI.VerticalLayout({
          maximize: false,
          top: {},
          center: {}
        });
        fields = [
          {
            type: CUI.Checkbox,
            form: {
              label: $$("collection.form.create_objects")
            },
            name: "_create_objects"
          }
        ];
        if (ez5.pluginManager.getPlugin("easydb-hotfolder-plugin") || ez5.version("6")) {
          if (!_this.data._hotfolder_upload_urls) {
            _this.data._hotfolder_upload_urls = [];
          }
          data_hotfolder_urls = {};
          ref6 = _this.data._hotfolder_upload_urls;
          for (idx = i = 0, len1 = ref6.length; i < len1; idx = ++i) {
            hotfolder_url = ref6[idx];
            data_hotfolder_urls["url_" + idx] = hotfolder_url.url;
            if (ez5.version("6")) {
              prefix = "fylr";
            } else {
              prefix = "server.base";
            }
            fields.push({
              type: CUI.Input,
              form: {
                label: $$(prefix + ".hotfolder.urls.type." + hotfolder_url.type),
                hint: $$(prefix + ".hotfolder.urls.type." + hotfolder_url.type + "|hint")
              },
              readonly: true,
              data: data_hotfolder_urls,
              name: "url_" + idx,
              maximize_horizontal: true
            });
          }
        }
        if (fields.length === 1) {
          fields.push({
            type: CUI.Output,
            maximize_horizontal: true,
            placeholder: ez5.version("6") ? $$("collection.form.filesystem-connect.missing_hint") : $$("collection.form.hotfolder_urls.missing_hint")
          });
          set_fields = function(on_off) {};
        } else {
          set_fields = function(on_off) {
            var field, j, len2, ref7, results;
            ref7 = general_form.getFields();
            results = [];
            for (idx = j = 0, len2 = ref7.length; j < len2; idx = ++j) {
              field = ref7[idx];
              if (idx === 0) {
                continue;
              }
              if (on_off) {
                results.push(field.enable());
              } else {
                results.push(field.disable());
              }
            }
            return results;
          };
        }
        general_form = new CUI.Form({
          data: _this.editor_data,
          padded: true,
          fields: fields
        }).start();
        lay.replace(general_form, "top");
        set_create_objects_tab_state = function() {
          var ref7, ref8;
          if (_this.editor_data._create_objects) {
            CUI.dom.removeClass(lay.center(), "cui-disabled");
            if ((ref7 = _this.__tabs) != null ? ref7.getTab("plugins") : void 0) {
              _this.__tabs.getTab("plugins").enable();
            }
            return set_fields(true);
          } else {
            CUI.dom.addClass(lay.center(), "cui-disabled");
            if ((ref8 = _this.__tabs) != null ? ref8.getTab("plugins") : void 0) {
              _this.__tabs.getTab("plugins").disable();
            }
            return set_fields(false);
          }
        };
        set_create_objects_tab_state();
        CUI.Events.listen({
          type: "data-changed",
          node: lay,
          call: function() {
            return set_create_objects_tab_state();
          }
        });
        new_editor.setModalFormContainer(lay.center());
        return new_editor.initDbInfo(false).done(function(opts) {
          var bulk_field, ref7;
          _this.__setLinkedObjectPoolsEditorData(co.linked_object_pools, _this.editor_data);
          if (_this.editor_data._create_objects && (bulk_field = _this.editor_data.bulk_field)) {
            if (bulk_field instanceof EASColumnLinkedObject && (bulk_field != null ? bulk_field.mask.table.poolLink() : void 0)) {
              _this.editor_data["_pool_" + (bulk_field.getLinkedObject().fullName())] = (ref7 = ez5.pools.findPoolById(co.linked_pool_id)) != null ? ref7.getData() : void 0;
            }
          }
          if (opts.length === 0) {
            return dfr.resolve();
          } else {
            return new_editor.updateModalForm().done(function() {
              return dfr.resolve(lay);
            }).fail(function() {
              var errorMsg;
              errorMsg = new CUI.Label({
                text: $$("collection.form.create_objects.no_rights_text"),
                markdown: true,
                multiline: true
              });
              lay.replace(errorMsg, "top");
              return dfr.resolve(lay);
            });
          }
        }).fail(dfr.reject);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  CollectionStorable.prototype.getShareUrl = function(who) {
    var loc, login_url, url;
    loc = document.location;
    login_url = who != null ? who.getLoginUrl() : void 0;
    if (login_url) {
      url = loc.origin + ("/collection/" + (this.getUUID()) + "?") + login_url;
    } else {
      url = loc.origin + ("/collection/" + (this.getUUID()));
    }
    if (window.easydb_server_url && window.easydb_server_url !== loc.origin) {
      if (url.match(/\?/)) {
        url = url + "&server=" + window.easydb_server_url;
      } else {
        url = url + "?server=" + window.easydb_server_url;
      }
    }
    return url;
  };

  CollectionStorable.prototype.isCreateChildAllowed = function() {
    var ref;
    if (!this.getManager().newCollection) {
      return false;
    } else if (((ref = this.data._generated_rights) != null ? ref.bag_create : void 0) && this.data.collection.children_allowed) {
      return true;
    } else {
      return false;
    }
  };

  CollectionStorable.prototype.canCreateInCollection = function() {
    var ref;
    if (ez5.session.isReadOnly()) {
      return false;
    }
    if (this.getId() && ((ref = this.data._generated_rights) != null ? ref.create_in_collection : void 0)) {
      return true;
    } else {
      return false;
    }
  };

  CollectionStorable.prototype.isWritable = function() {
    var ref;
    if (!this.getId() || ((ref = this.data._generated_rights) != null ? ref.bag_write : void 0)) {
      return true;
    } else {
      return false;
    }
  };

  CollectionStorable.prototype.isDeletable = function() {
    var ref;
    if (!this.getId() || ((ref = this.data._generated_rights) != null ? ref.bag_delete : void 0)) {
      return true;
    } else {
      return false;
    }
  };

  CollectionStorable.prototype.canUnlink = function() {
    var ref;
    if (!this.getId() || ((ref = this.data._generated_rights) != null ? ref.unlink : void 0)) {
      return true;
    } else {
      return false;
    }
  };

  CollectionStorable.prototype.enableShare = function() {
    var ref;
    if (!this.getId() || ((ref = this.data._generated_rights) != null ? ref.bag_acl : void 0)) {
      if (ez5.session.hasSystemRight("root", "frontend_features[collection][sharing]", "frontend_features[collection][share_anonymous]")) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  };

  CollectionStorable.prototype.enableSettings = function() {
    if (this.isWritable()) {
      return true;
    } else {
      return false;
    }
  };

  CollectionStorable.prototype.popoverEditorSettings = function() {
    return this.popoverEditorShare("general");
  };

  CollectionStorable.prototype.getGeneralFormFields = function(data) {
    return [
      {
        type: CUI.MultiInput,
        data: data.collection,
        form: {
          label: $$("collection.form.displayname")
        },
        name: "displayname",
        ui: "collection.storable.form.general.displayname.input",
        control: ez5.loca.getLanguageControl()
      }, {
        type: CUI.MultiInput,
        data: data.collection,
        form: {
          label: $$("collection.form.description")
        },
        textarea: true,
        name: "description",
        ui: "collection.storable.form.general.description.input",
        control: ez5.loca.getLanguageControl()
      }, {
        type: CUI.Select,
        data: data.collection.webfrontend_props,
        form: {
          label: $$("collection.form.default_view")
        },
        options: [
          {
            text: $$("main.search.view.result-standard"),
            value: 0
          }, {
            text: $$("main.search.view.result-detail"),
            value: 1
          }
        ],
        name: "default_view"
      }, {
        type: CUI.Input,
        data: data.collection,
        form: {
          label: $$("collection.form.shortname")
        },
        name: "shortname",
        ui: "collection.storable.form.general.shortname.input"
      }, {
        type: CUI.Input,
        data: data.collection,
        form: {
          label: $$("collection.form.reference")
        },
        name: "reference",
        ui: "collection.storable.form.general.reference.input"
      }
    ];
  };

  CollectionStorable.prototype.popoverEditorShare = function(start_tab) {
    var activateButton, generalForm, horizontalList, keys, modal, modal_fail, rollbackData, rollback_data, saveButton, setRollbackData, tagForm, wb;
    if (start_tab == null) {
      start_tab = "share";
    }
    generalForm = null;
    keys = ["_acl", "collection"];
    rollbackData = {};
    setRollbackData = (function(_this) {
      return function() {
        var i, k, len1, results;
        results = [];
        for (i = 0, len1 = keys.length; i < len1; i++) {
          k = keys[i];
          results.push(rollbackData[k] = CUI.util.copyObject(_this.data[k], true));
        }
        return results;
      };
    })(this);
    activateButton = new CUI.Button({
      text: $$("base.activate"),
      disabled: true,
      onClick: (function(_this) {
        return function(ev) {
          _this.data.collection = generalForm.getData().collection;
          return _this.save(ev).done(function(response_data) {
            if (_this.enableShare()) {
              _this.aclManager.loadFromData(response_data._acl);
              _this.__tabs.getTab("share").setContent(_this.aclManager.getTree());
            }
            generalForm.getData().collection._version++;
            setRollbackData();
            saveButton.disable();
            return activateButton.disable();
          });
        };
      })(this)
    });
    saveButton = new CUI.Button({
      text: $$("base.save"),
      primary: true,
      disabled: true,
      ui: "collection.storable.editor.save.button",
      onClick: (function(_this) {
        return function(ev) {
          _this.data.collection = generalForm.getData().collection;
          return _this.save(ev).done(function() {
            return modal.destroy();
          });
        };
      })(this)
    });
    horizontalList = new CUI.HorizontalList({
      content: [activateButton, saveButton]
    });
    modal_fail = (function(_this) {
      return function() {
        wb.destroy();
        return modal.destroy();
      };
    })(this);
    setRollbackData();
    rollback_data = (function(_this) {
      return function() {
        var i, k, len1;
        for (i = 0, len1 = keys.length; i < len1; i++) {
          k = keys[i];
          _this.data[k] = rollbackData[k];
        }
      };
    })(this);
    modal = new CUI.Modal({
      "class": "ez5-collection-storable-acl",
      cancel: true,
      fill_space: "auto",
      ui: "collection.storable.editor.modal",
      onHide: (function(_this) {
        return function() {
          _this.aclManager = null;
          return _this.editor_data = null;
        };
      })(this),
      onCancel: function() {
        if (saveButton.isDisabled()) {
          return modal.destroy();
        } else {
          return CUI.confirm({
            text: $$("collection.storable.confirm_cancel")
          }).done(rollback_data);
        }
      },
      pane: {
        header_left: new CUI.Label({
          text: $$("collection.form.title|text", {
            name: this.renderNameAsText()
          }),
          icon: $$("collection.form.title|icon")
        }),
        footer_right: horizontalList
      }
    }).show();
    wb = new CUI.WaitBlock({
      element: modal.getPane().center(),
      ui: "collection.storable.editor.wait.block"
    });
    wb.show();
    tagForm = new TagForm({
      context: this
    });
    CUI.when(tagForm.load(), this.loadFromDb()).fail(function() {
      return modal_fail();
    }).done((function(_this) {
      return function() {
        var check_btn_state, fields, owner_displayname, saveDataJson;
        if (modal.isDestroyed()) {
          return;
        }
        saveDataJson = null;
        check_btn_state = function() {
          var e, sd;
          try {
            sd = _this.getSaveData();
            if (JSON.stringify(sd) !== saveDataJson) {
              saveButton.enable();
              activateButton.enable();
            } else {
              saveButton.disable();
              activateButton.disable();
            }
          } catch (error1) {
            e = error1;
            saveButton.disable();
            activateButton.disable();
            if (!(e instanceof InvalidSaveDataException)) {
              throw e;
            }
          }
        };
        if (_this.data._owner) {
          if (_this.data._owner.user) {
            owner_displayname = _this.data._owner.user._generated_displayname;
          }
          if (_this.data._owner.group) {
            owner_displayname = _this.data._owner.group._generated_displayname;
          }
        }
        fields = [
          {
            form: {
              label: $$("collection.form.owner")
            },
            type: CUI.Output,
            text: owner_displayname,
            ui: "collection.storable.editor.owner.output",
            placeholder: $$("collection.storable.form.general.no_owner")
          }
        ];
        fields.push.apply(fields, _this.getGeneralFormFields(_this.data));
        fields.push(function() {
          var field;
          field = {
            type: CUI.DataFieldProxy,
            element: Asset.getShareButtonbar(_this.getShareUrl(), "acl.item.share"),
            form: {
              label: $$("collection.form.direct_url")
            }
          };
          return field;
        });
        generalForm = new CUI.Form({
          data: _this.data,
          onDataChanged: function() {
            return check_btn_state();
          },
          fields: fields
        }).start();
        _this.aclManager = new AclManager({
          data: _this.data._acl,
          context: _this,
          allowCollectionUser: true,
          allowEmailUser: true,
          filter_system_groups: !ez5.session.hasSystemRight("root", "frontend_features[collection][sharing_include_system_groups]"),
          footer_right: function() {
            var pin_code, pin_label, private_acl_cb;
            pin_label = new CUI.Label({
              text: $$("collection.storable.pin_code")
            });
            pin_code = new CUI.Input({
              data: _this.data.collection,
              regexp: "[a-z0-9A-Z]{3,}",
              name: "pin_code"
            });
            private_acl_cb = new CUI.Checkbox({
              data: _this.data,
              name: "_private_acl",
              onDataChanged: function() {
                return check_btn_state();
              },
              text: $$("collection.storable.private_acl")
            });
            return [pin_label, pin_code.start(), private_acl_cb.start()];
          },
          tagForm: tagForm,
          preset: _this.allowACLPreset(),
          invalid_acl: !!_this.hasInvalidACL(),
          email_notification: true,
          valid_to: true,
          onNewAclItem: function(item) {
            return _this.onShareAclItemCreated(item);
          },
          onUpdate: function() {
            check_btn_state();
          },
          share_link: true,
          expert_menu: _this.getACLExpertOptions(),
          right_filter: function(right) {
            return _this.ACLRightFilter(right);
          }
        });
        return _this.createObjectsTab().fail(function() {
          return modal_fail();
        }).done(function(create_objects_tab) {
          var collection_plugins_tab_content, e, tabs;
          if (modal.isDestroyed()) {
            return;
          }
          try {
            saveDataJson = JSON.stringify(_this.getSaveData());
          } catch (error1) {
            e = error1;
            saveDataJson = "_INVALID";
          }
          tabs = [];
          if (_this.enableSettings()) {
            tabs.push({
              name: "general",
              text: $$("collection.storable.tab.general"),
              content: generalForm
            });
          }
          if (_this.enableShare()) {
            tabs.push({
              name: "share",
              icon: _this.hasInvalidACL() ? "fa-exclamation-triangle" : null,
              padded: false,
              text: $$("collection.storable.tab.share"),
              content: _this.aclManager.getTree()
            });
          }
          if (create_objects_tab) {
            tabs.push({
              padded: false,
              name: "create_objects",
              text: ez5.version("6") ? $$("collection.storable.tab.fylr.create_objects") : $$("collection.storable.tab.create_objects"),
              content: create_objects_tab
            });
            collection_plugins_tab_content = _this.__loadUploadPluginsForm();
            if (ez5.version("6.10")) {
              tabs.push({
                name: "plugins",
                text: $$("collection.storable.upload_plugins.tab.label"),
                content: collection_plugins_tab_content,
                disabled: !_this.editor_data._create_objects
              });
              CUI.Events.listen({
                type: ["data-changed"],
                node: collection_plugins_tab_content,
                call: function() {
                  return check_btn_state();
                }
              });
            }
            CUI.Events.listen({
              type: ["data-changed", "pool-field-changed"],
              node: create_objects_tab,
              call: function() {
                return check_btn_state();
              }
            });
          }
          wb.destroy();
          _this.__tabs = new CUI.Tabs({
            "class": "ez5-collection-storable-tabs",
            padded: true,
            tabs: tabs
          });
          return modal.replace(_this.__tabs.activate(start_tab));
        });
      };
    })(this));
    return this;
  };

  CollectionStorable.prototype.allowACLPreset = function() {
    return true;
  };

  CollectionStorable.prototype.onShareAclItemCreated = function(item) {};

  CollectionStorable.prototype.ACLRightFilter = function(right) {
    return true;
  };

  CollectionStorable.prototype.getACLExpertOptions = function() {
    return ["active", "who", "right", "preset", "valid_from", "valid_to", "sticky", "share_link", "email_notification", "email_language", "email_notification_text"];
  };

  CollectionStorable.prototype.hasInvalidACL = function() {
    return this.data._invalid_acl;
  };

  CollectionStorable.prototype.canAppend = function() {
    var ref;
    if (ez5.session.isReadOnly()) {
      return false;
    }
    if (!this.getId() || ((ref = this.data._generated_rights) != null ? ref.link : void 0)) {
      return true;
    } else {
      return false;
    }
  };

  CollectionStorable.prototype.isSearchableConnector = function() {
    var ref;
    if (((ref = ez5.connector) != null ? ref.getActiveEasydbs().length : void 0) > 0 && this.data._has_remote_objects) {
      return true;
    } else {
      return false;
    }
  };

  CollectionStorable.prototype.showInSearchConnector = function(search) {
    if (search == null) {
      search = this.getSearch();
    }
    ez5.splash.show("collection.storable.connector.loading");
    this.__cached_objects = null;
    return this.loadObjects().always((function(_this) {
      return function() {
        return ez5.splash.hide();
      };
    })(this)).done((function(_this) {
      return function(__cached_objects) {
        _this.__cached_objects = __cached_objects;
        return CollectionWithDetail.prototype.showInSearch.call(_this, search);
      };
    })(this));
  };

  CollectionStorable.prototype.showInSearch = function(search, append) {
    if (search == null) {
      search = this.getSearch();
    }
    if (append == null) {
      append = false;
    }
    this.__cached_objects = null;
    return CollectionStorable.__super__.showInSearch.call(this, search, append);
  };

  CollectionStorable.prototype.getAllSubcollectionIds = function() {
    var allIds, dfr, search;
    dfr = new CUI.Deferred();
    allIds = [this.getId()];
    search = [
      {
        type: "in",
        fields: ["_path.collection._id"],
        "in": [this.getId()]
      }
    ];
    ez5.api.search({
      json_data: {
        limit: 10000,
        type: "collection",
        search: search,
        generate_rights: true
      }
    }).done((function(_this) {
      return function(data) {
        var collection, i, len1, ref, ref1, ref2;
        ref = data.objects;
        for (i = 0, len1 = ref.length; i < len1; i++) {
          collection = ref[i];
          if (!((ref1 = collection._generated_rights) != null ? ref1.bag_read : void 0)) {
            continue;
          }
          if (collection._has_pin && !collection._pin_ok) {
            continue;
          }
          if (ref2 = collection.collection._id, indexOf.call(allIds, ref2) >= 0) {
            continue;
          }
          allIds.push(collection.collection._id);
        }
        return dfr.resolve(allIds);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  CollectionStorable.prototype.getSearchFilter = function() {
    var collectionIds, filter, obj;
    if (!this.getId()) {
      return false;
    }
    if (this.__cached_objects) {
      filter = {
        type: "in",
        fields: ["_global_object_id"],
        "in": (function() {
          var i, len1, ref, results;
          ref = this.__cached_objects;
          results = [];
          for (i = 0, len1 = ref.length; i < len1; i++) {
            obj = ref[i];
            results.push(obj._global_object_id);
          }
          return results;
        }).call(this)
      };
    } else {
      collectionIds = this.__subcollectionIds ? this.__subcollectionIds : [this.getId()];
      filter = {
        type: "in",
        fields: ["_collections._id"],
        "in": collectionIds
      };
    }
    return filter;
  };

  CollectionStorable.prototype.insertInProgress = function() {
    return this.__insert_in_progress;
  };

  CollectionStorable.prototype.insertObjects = function(collection_objects, before_idx, update_event) {
    var co, dfr, promise;
    if (before_idx == null) {
      before_idx = null;
    }
    if (update_event == null) {
      update_event = true;
    }
    this.__insert_in_progress = true;
    dfr = new CUI.Deferred();
    dfr.always((function(_this) {
      return function() {
        return _this.__insert_in_progress = false;
      };
    })(this));
    this.checkObjects(collection_objects);
    if (before_idx !== null) {
      promise = ez5.server({
        type: "POST",
        api: "/collection/splice/" + (this.getId()),
        json_data: {
          index: before_idx,
          count: 0,
          objects: (function() {
            var i, len1, results;
            results = [];
            for (i = 0, len1 = collection_objects.length; i < len1; i++) {
              co = collection_objects[i];
              results.push(co.getStorable());
            }
            return results;
          })()
        }
      });
    } else {
      promise = ez5.server({
        type: "POST",
        api: "/collection/push/" + (this.getId()),
        json_data: {
          objects: (function() {
            var i, len1, results;
            results = [];
            for (i = 0, len1 = collection_objects.length; i < len1; i++) {
              co = collection_objects[i];
              results.push(co.getStorable());
            }
            return results;
          })()
        }
      });
    }
    promise.done((function(_this) {
      return function(res) {
        if (!update_event) {
          return;
        }
        _this.data._count = res.count;
        _this.updateAfterInsertOrRemove(before_idx);
        if (ez5.version("6")) {
          _this.refreshRecursive();
        }
        _this.updateDisplay(true);
        dfr.resolve(_this);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  CollectionStorable.prototype.removeObjects = function(collection_objects) {
    var co, dfr, promise;
    dfr = new CUI.Deferred();
    this.checkObjects(collection_objects);
    promise = ez5.server({
      type: "POST",
      api: "/collection/remove/" + (this.getId()),
      json_data: (function() {
        var i, len1, results;
        results = [];
        for (i = 0, len1 = collection_objects.length; i < len1; i++) {
          co = collection_objects[i];
          results.push(co.getStorable());
        }
        return results;
      })()
    });
    promise.done((function(_this) {
      return function(res) {
        _this.data._count = res.count;
        return _this.triggerEvent("remove", {
          collection_objects: collection_objects
        }).done(function() {
          if (ez5.version("6")) {
            _this.refreshRecursive();
          }
          _this.updateDisplay(true);
          return dfr.resolve();
        }).fail(dfr.reject);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  CollectionStorable.prototype.addToRequest = function(request) {
    if (!request.search) {
      request.search = [];
    }
    return request.search.push({
      bool: "must",
      type: "in",
      fields: ["_collections._id"],
      "in": [this.getId()]
    });
  };

  CollectionStorable.prototype.executeSearch = function(req_data) {
    var opts;
    if (req_data == null) {
      req_data = {};
    }
    opts = {
      api: "/objects/" + (this.getId())
    };
    if (req_data) {
      opts.data = {
        limit: req_data.limit || 0,
        offset: req_data.offset || 0
      };
    }
    opts.handle_error = (function(_this) {
      return function(xhr) {
        var error;
        try {
          if (!CUI.util.isEmpty(xhr.response.error) && CUI.util.isString(xhr.response.error)) {
            if (xhr.response.code === "RightRequired" && xhr.response.error.includes("bag_read")) {
              return xhr.responseJSON.error = $$("collection.storable.error_date_expired");
            }
          }
        } catch (error1) {
          error = error1;
          return console.error(error);
        }
      };
    })(this);
    return ez5.api.collection(opts);
  };

  CollectionStorable.prototype.loadObjects = function(limit) {
    var arr, chunk_size, dfr, objects;
    if (limit == null) {
      limit = this.getCount();
    }
    dfr = new CUI.Deferred();
    chunk_size = 100;
    arr = [];
    arr[limit - 1] = true;
    objects = [];
    CUI.chunkWork.call(this, {
      items: arr,
      chunk_size: chunk_size,
      call: (function(_this) {
        return function(items, offset, len) {
          return ez5.api.collection({
            api: "/objects/" + _this.getId(),
            data: {
              offset: offset,
              limit: chunk_size
            }
          }).done(function(data) {
            var i, len1, obj, ref;
            ref = data.objects;
            for (i = 0, len1 = ref.length; i < len1; i++) {
              obj = ref[i];
              objects.push(obj);
            }
          });
        };
      })(this)
    }).fail(dfr.reject).done((function(_this) {
      return function() {
        return dfr.resolve(objects);
      };
    })(this));
    return dfr.promise();
  };

  CollectionStorable.prototype.destroy = function() {
    var ref;
    if ((ref = this.__loadingFromDb) != null) {
      ref.abort();
    }
    delete this.__loadingFromDb;
    return CollectionStorable.__super__.destroy.call(this);
  };

  CollectionStorable.prototype.getUploadPlugin = function() {
    var ref;
    return (ref = this.data.collection.create_object) != null ? ref.plugin : void 0;
  };

  CollectionStorable.prototype.hasUploadPluginConfigured = function() {
    return !CUI.util.isEmpty(this.getUploadPlugin());
  };

  CollectionStorable.prototype.__loadUploadPluginsForm = function() {
    var collectionUploadPlugin, collectionUploadPluginName, configFields, def, fields, form, groupFields, i, j, l, l10nFn, len1, len2, len3, options, paramName, paramObj, parameterArray, parameters, plugin, pluginConfigGroup, pluginConfigGroups, pluginName, plugins, ref, ref1, ref2;
    l10nFn = function(type, parentDef) {
      var attrs;
      attrs = ["collection_upload"];
      if (type) {
        attrs.push(type);
      }
      if (parentDef) {
        attrs.push(parentDef._parameter_name);
      }
      return attrs.join(".");
    };
    plugins = {};
    ref = ez5.pluginManager.getPluginNames();
    for (i = 0, len1 = ref.length; i < len1; i++) {
      pluginName = ref[i];
      plugin = ez5.pluginManager.getPlugin(pluginName);
      if ((ref1 = plugin.opts) != null ? ref1.hasOwnProperty("collection_upload") : void 0) {
        ref2 = plugin.opts.collection_upload;
        for (collectionUploadPluginName in ref2) {
          collectionUploadPlugin = ref2[collectionUploadPluginName];
          plugins[pluginName + ":" + collectionUploadPluginName] = collectionUploadPlugin;
        }
      }
    }
    if (CUI.util.isEmpty(plugins)) {
      return new CUI.Label({
        text: $$("collection.storable.upload_plugins.no_plugins")
      });
    }
    options = [
      {
        text: "None",
        value: ""
      }
    ];
    for (pluginName in plugins) {
      plugin = plugins[pluginName];
      options.push({
        text: pluginName,
        value: pluginName
      });
    }
    configFields = [];
    if (this.editor_data.plugin !== "") {
      pluginConfigGroups = plugins[this.editor_data.plugin];
      if (pluginConfigGroups) {
        for (j = 0, len2 = pluginConfigGroups.length; j < len2; j++) {
          pluginConfigGroup = pluginConfigGroups[j];
          groupFields = [];
          parameters = pluginConfigGroup.parameters;
          if (parameters) {
            parameterArray = [];
            for (paramName in parameters) {
              def = parameters[paramName];
              parameterArray.push({
                name: paramName,
                def: def,
                position: def.position || 0
              });
            }
            parameterArray.sort((function(_this) {
              return function(a, b) {
                var posA, posB;
                posA = a.position || 0;
                posB = b.position || 0;
                return posA - posB;
              };
            })(this));
            for (l = 0, len3 = parameterArray.length; l < len3; l++) {
              paramObj = parameterArray[l];
              groupFields.push(BaseConfig.getFieldDefinitionFromParameter(paramObj.name, paramObj.def, null, l10nFn));
            }
            if (groupFields.length > 0) {
              configFields.push({
                type: CUI.Form,
                name: pluginConfigGroup.name,
                fields: groupFields,
                form: {
                  label: pluginConfigGroup.name
                }
              });
            }
          }
        }
      }
    }
    fields = [
      {
        type: CUI.Select,
        form: {
          label: "Upload Plugin"
        },
        options: options,
        name: "plugin",
        onDataChanged: (function(_this) {
          return function() {
            var newForm;
            _this.editor_data.plugin_config = {};
            newForm = _this.__loadUploadPluginsForm();
            return _this.__tabs.getTab("plugins").setContent(newForm);
          };
        })(this)
      }
    ];
    if (configFields.length > 0) {
      fields.push({
        type: CUI.Form,
        name: "plugin_config",
        fields: configFields
      });
    }
    form = new CUI.Form({
      data: this.editor_data,
      fields: fields
    });
    return form.start();
  };

  return CollectionStorable;

})(CollectionWithDetail);
// Generated by CoffeeScript 1.12.7
var CollectionStoredSearch,
  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;

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

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

  CollectionStoredSearch.prototype.icon = function() {
    return "fa-search";
  };

  CollectionStoredSearch.prototype.setData = function(data) {
    this.data = data;
    CollectionStoredSearch.__super__.setData.call(this, this.data);
    this.data.collection.children_allowed = false;
    this.data.collection.type = "search";
    this.data.collection.objects_allowed = false;
    return this;
  };

  CollectionStoredSearch.prototype.enableSettings = function() {
    return false;
  };

  CollectionStoredSearch.prototype.getCounterItems = function() {
    return CollectionSearchNode.prototype.getCounterItems.call(this);
  };

  CollectionStoredSearch.prototype.__initShowInSearch = function() {
    var e, err, k, props, ref, sm, v;
    if (this.__initShow) {
      return this;
    }
    props = this.data.collection.webfrontend_props;
    if (!props.search) {
      props.search = {
        search: {},
        version: {}
      };
    }
    this.__search_props = props.search;
    this.__searchManagers = [];
    ref = this.__search_props.search;
    for (k in ref) {
      v = ref[k];
      if (!CUI.util.isFunction(window[k])) {
        continue;
      }
      try {
        sm = new window[k]({
          init_from_data: v
        });
        sm.setSearch(this.getSearch());
        this.__searchManagers.push(sm);
      } catch (error) {
        e = error;
        console.error("Problems loading stored search", e, v);
        err = true;
      }
    }
    if (err) {
      CUI.problem({
        text: $$("collection.stored.search.error.loading", {
          name: this.renderNameAsText()
        }),
        markdown: true
      });
    }
    this.__initShow = true;
    return this;
  };

  CollectionStoredSearch.prototype.destroy = function() {
    var i, len, ref, sm;
    if (this.__searchManagers) {
      ref = this.__searchManagers;
      for (i = 0, len = ref.length; i < len; i++) {
        sm = ref[i];
        sm.destroy();
      }
      this.__searchManagers = null;
    }
    return CollectionStoredSearch.__super__.destroy.call(this);
  };

  CollectionStoredSearch.prototype.updateCounter = function() {
    return this.counterLabel.setContent();
  };

  CollectionStoredSearch.prototype.ignoreSearchManagers = function() {
    return [];
  };

  CollectionStoredSearch.prototype.makeDraggable = function(el) {};

  CollectionStoredSearch.prototype.getBadge = function() {
    return {
      icon: this.getBadgeIcon(),
      name: $$("collection.stored.search.badge.name"),
      value: this.renderNameAsText()
    };
  };

  CollectionStoredSearch.prototype.select = function() {
    return this.showInSearch();
  };

  CollectionStoredSearch.prototype.isSelectable = function() {
    return true;
  };

  CollectionStoredSearch.prototype.showInSearch = function(search) {
    var i, len, promises, ref, ref1, ref2, sm;
    if (search == null) {
      search = this.getSearch();
    }
    this.__initShowInSearch();
    if ((ref = search.getFacetManager()) != null) {
      ref.resetFacets();
    }
    promises = [];
    ref1 = this.__searchManagers;
    for (i = 0, len = ref1.length; i < len; i++) {
      sm = ref1[i];
      if (sm instanceof SearchTypeSelector) {
        if (search.getSearchTypeSelector()) {
          promises.push(search.getSearchTypeSelector().restoreFromStored(sm));
          continue;
        }
      }
      if (sm instanceof FacetManager) {
        promises.push(search.getFacetManager().restoreFromStored(sm));
        continue;
      }
      if (sm instanceof SearchInput) {
        promises.push(search.getSearchInput().restoreFromStored(sm));
        continue;
      }
      console.warn("CollectionStoredSearch.showInSearch: Skipping unknown saved search manager:", sm);
    }
    if ((ref2 = this.getManager()) != null) {
      ref2.showSearch();
    }
    return CUI.when(promises).done((function(_this) {
      return function() {
        return search.execute();
      };
    })(this));
  };

  CollectionStoredSearch.prototype.createObjectsTab = function() {
    return CUI.resolvedPromise(null);
  };

  CollectionStoredSearch.prototype.addToRequest = function(request) {
    if (!request.search) {
      request.search = [];
    }
    request.search.push(this.getSearchFilter());
    console.debug("CollectionStoredSearch.addToRequest", request);
    return request;
  };

  CollectionStoredSearch.prototype.executeSearch = null;

  CollectionStoredSearch.prototype.editPromptText = function() {
    return $$("collection.stored.search.name_prompt_text");
  };

  CollectionStoredSearch.prototype.getSearchFilter = function() {
    var i, len, ref, req, search, sm;
    req = new Request();
    ref = this.__searchManagers;
    for (i = 0, len = ref.length; i < len; i++) {
      sm = ref[i];
      sm.addToRequest(req);
    }
    search = req.search;
    if (!search.length) {
      return false;
    }
    return {
      bool: "must",
      type: "complex",
      search: search
    };
  };

  CollectionStoredSearch.prototype.allowACLPreset = function() {
    return false;
  };

  CollectionStoredSearch.prototype.ACLRightFilter = function(right) {
    if (!ez5.version("6")) {
      return true;
    }
    return right.name === "bag_read";
  };

  CollectionStoredSearch.prototype.getACLExpertOptions = function() {
    return ["active", "who", "valid_from", "right", "valid_to", "sticky", "share_link", "email_notification", "email_language", "email_notification_text"];
  };

  CollectionStoredSearch.prototype.onShareAclItemCreated = function(item) {
    var ref;
    return item != null ? (ref = item.data) != null ? ref.rights = {
      bag_read: {}
    } : void 0 : void 0;
  };

  CollectionStoredSearch.prototype.allowSubcollectionSearch = function() {
    return false;
  };

  CollectionStoredSearch.prototype.isSearchAppendable = function() {
    return false;
  };

  return CollectionStoredSearch;

})(CollectionStorable);
// Generated by CoffeeScript 1.12.7
var CollectionFixedSearch,
  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;

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

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

  CollectionFixedSearch.prototype.initOpts = function() {
    CollectionFixedSearch.__super__.initOpts.call(this);
    return this.addOpts({
      hashId: {
        check: String
      },
      getSearchObjecttypes: {
        mandatory: true,
        check: Function
      }
    });
  };

  CollectionFixedSearch.prototype.getFilter = function() {
    return this.opts.filter;
  };

  CollectionFixedSearch.prototype.edit = false;

  CollectionFixedSearch.prototype.canUnlink = function() {
    return false;
  };

  CollectionFixedSearch.prototype.getObjecttypeNames = function() {
    var i, len, ot, ref, results;
    ref = this._getSearchObjecttypes();
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      results.push(ot.name());
    }
    return results;
  };

  CollectionFixedSearch.prototype.includeDeleted = function() {
    return false;
  };

  CollectionFixedSearch.prototype.getCount = function() {
    var dfr, filter, hasLocalObjecttype, i, instance, instances, len, ot, ots, search_data;
    dfr = new CUI.Deferred();
    ots = this.getObjecttypeNames();
    if (ots.length === 0) {
      return dfr.resolve(0).promise();
    }
    instances = [];
    for (i = 0, len = ots.length; i < len; i++) {
      ot = ots[i];
      instance = ot.match(/@(.+)/);
      if (instance) {
        instances.push(instance[1]);
      } else {
        hasLocalObjecttype = true;
      }
    }
    if (hasLocalObjecttype) {
      instances.push("local");
    }
    filter = this.getSearchFilter();
    search_data = {
      format: "short",
      limit: 0,
      generate_rights: false,
      search: [filter]
    };
    if (this.includeDeleted()) {
      search_data.include_deleted = true;
    }
    ez5.api.search({
      data: {
        debug: "CollectionFixedSearch",
        instances: instances
      },
      json_data: search_data
    }).done((function(_this) {
      return function(data) {
        var c;
        c = _this.getCountFromData(data, filter);
        return dfr.resolve(c);
      };
    })(this)).fail(function(xhr) {
      return dfr.resolve("Err");
    });
    return dfr.promise();
  };

  CollectionFixedSearch.prototype.getCountFromData = function(data, filter) {
    return data.count;
  };

  CollectionFixedSearch.prototype.renderNameAsText = function() {
    return $$("collection.fixed_search." + this.getHashId());
  };

  CollectionFixedSearch.prototype.getDescription = function() {
    return $$("collection.fixed_search." + this.getHashId() + ".description");
  };

  CollectionFixedSearch.prototype.getHashId = function() {
    return this._hashId;
  };

  CollectionFixedSearch.prototype.getSearchFilter = function() {
    var filter;
    filter = {
      type: "complex",
      search: [this.getFilter()]
    };
    filter.search.push({
      type: "in",
      fields: ["_objecttype"],
      "in": this.getObjecttypeNames()
    });
    return filter;
  };

  CollectionFixedSearch.prototype.addToRequest = function(request) {
    if (!request.search) {
      request.search = [];
    }
    request.search.push(this.getSearchFilter());
    return request;
  };

  CollectionFixedSearch.prototype.showInSearch = function(search) {
    var ref;
    if (search == null) {
      search = this.getSearch();
    }
    if ((ref = search.getFacetManager()) != null) {
      ref.resetFacets();
    }
    return CollectionFixedSearch.__super__.showInSearch.call(this, search);
  };

  CollectionFixedSearch.prototype.select = function() {
    return this.showInSearch();
  };

  CollectionFixedSearch.prototype.ignoreSearchManagers = function() {
    return [];
  };

  CollectionFixedSearch.prototype.isSelectable = function() {
    return true;
  };

  CollectionFixedSearch.prototype.isMovable = function() {
    return false;
  };

  return CollectionFixedSearch;

})(CollectionSearchNode);
// Generated by CoffeeScript 1.12.7
var CollectionFixedSearchAnyToday,
  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;

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

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

  CollectionFixedSearchAnyToday.prototype.getHashId = function() {
    return "any_today";
  };

  CollectionFixedSearchAnyToday.prototype.getBadge = function() {
    return {
      icon: this.getBadgeIcon(),
      name: $$("collection.fixed.search.badge.name"),
      value: this.renderNameAsText()
    };
  };

  CollectionFixedSearchAnyToday.prototype.getCountFromData = function(data, filter) {
    if (filter.search[0].search[1]) {
      return data.count + filter.search[0].search[1]["in"].length;
    } else {
      return data.count;
    }
  };

  CollectionFixedSearchAnyToday.prototype.getFilter = function(operation) {
    var cc, search, today;
    if (operation == null) {
      operation = void 0;
    }
    cc = new ChangelogColumnForCollection();
    today = (new Date()).toISOString().split('T')[0];
    search = [
      cc.getSearchFilter({
        who: ez5.session.getUser().getData(),
        from: today,
        to: today + "T23:59:59.999Z",
        operation: operation
      })
    ];
    return {
      type: "complex",
      search: search
    };
  };

  CollectionFixedSearchAnyToday.prototype.getStoreData = function() {};

  return CollectionFixedSearchAnyToday;

})(CollectionFixedSearch);
// Generated by CoffeeScript 1.12.7
var CollectionFixedSearchUpdateToday,
  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;

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

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

  CollectionFixedSearchUpdateToday.prototype.getHashId = function() {
    return "update_today";
  };

  CollectionFixedSearchUpdateToday.prototype.getFilter = function() {
    return CollectionFixedSearchUpdateToday.__super__.getFilter.call(this, "UPDATE");
  };

  return CollectionFixedSearchUpdateToday;

})(CollectionFixedSearchAnyToday);
// Generated by CoffeeScript 1.12.7
var CollectionFixedSearchInsertToday,
  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;

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

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

  CollectionFixedSearchInsertToday.prototype.initOpts = function() {
    CollectionFixedSearchInsertToday.__super__.initOpts.call(this);
    return this.addOpts({
      listen_for_global_object_ids: {
        check: function(v) {
          return (v != null ? v.length : void 0) > 0;
        }
      },
      onIndexEvent: {
        check: Function
      }
    });
  };

  CollectionFixedSearchInsertToday.prototype.readOpts = function() {
    var call_update_counter, listener, secs;
    CollectionFixedSearchInsertToday.__super__.readOpts.call(this);
    if (!this._listen_for_global_object_ids) {
      return;
    }
    secs = parseInt(ez5.session.getClientDefault("collection_refresh_rate_seconds") || 30);
    call_update_counter = (function(_this) {
      return function() {
        var ref;
        _this.updateCounter();
        if ((ref = _this.__queryElement) != null) {
          ref.render();
        }
        return typeof _this._onIndexEvent === "function" ? _this._onIndexEvent() : void 0;
      };
    })(this);
    this.__gids = this._listen_for_global_object_ids.slice(0);
    listener = EventPoller.listen({
      filter: {
        type: "OBJECT_INDEX"
      },
      instance: this,
      call: (function(_this) {
        return function(events) {
          var event, i, len;
          for (i = 0, len = events.length; i < len; i++) {
            event = events[i];
            CUI.util.removeFromArray(event.global_object_id, _this.__gids);
          }
          if (_this.__gids.length === 0) {
            listener.destroy();
            listener = null;
          }
          if (secs > 0 && _this.__gids.length > 0) {
            return CUI.scheduleCallback({
              ms: secs * 1000,
              call: call_update_counter
            });
          } else {
            return call_update_counter();
          }
        };
      })(this)
    });
    return this;
  };

  CollectionFixedSearchInsertToday.prototype.getBadgeIcon = function() {
    var ref;
    if (((ref = this.__gids) != null ? ref.length : void 0) > 0) {
      return "spinner";
    } else {
      return null;
    }
  };

  CollectionFixedSearchInsertToday.prototype.destroy = function() {
    CUI.Events.ignore({
      instance: this
    });
    return CollectionFixedSearchInsertToday.__super__.destroy.call(this);
  };

  CollectionFixedSearchInsertToday.prototype.queryElementDestroyed = function() {
    CUI.Events.ignore({
      instance: this
    });
    return CollectionFixedSearchInsertToday.__super__.queryElementDestroyed.call(this);
  };

  CollectionFixedSearchInsertToday.prototype.getHashId = function() {
    return "insert_today";
  };

  CollectionFixedSearchInsertToday.prototype.getFilter = function() {
    return CollectionFixedSearchInsertToday.__super__.getFilter.call(this, "INSERT");
  };

  return CollectionFixedSearchInsertToday;

})(CollectionFixedSearchAnyToday);
// Generated by CoffeeScript 1.12.7
var CollectionWorkfolder,
  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;

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

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

  CollectionWorkfolder.prototype.icon = function() {
    var folder, ref;
    if (((ref = this.data._acl) != null ? ref.length : void 0) || this.data._has_acl) {
      if (this.data._invalid_acl) {
        folder = "fa-exclamation-triangle";
      } else {
        folder = "folder_shared";
      }
    } else {
      folder = "folder";
    }
    if (this.hasUploadConfigured()) {
      folder = folder + "_upload";
    }
    return folder;
  };

  CollectionWorkfolder.prototype.getCounterItems = function() {
    var btn, items, loca_key;
    items = CollectionWorkfolder.__super__.getCounterItems.call(this);
    if (this.data.collection.type === "presentation") {
      btn = new LocaButton({
        loca_key: "collection.workfolder.button.start_presentation",
        appearance: "flat",
        icon: "svg-presentation-play",
        onClick: (function(_this) {
          return function() {
            return new Presentation({
              collection: _this
            }).play();
          };
        })(this)
      });
      items.push(btn);
    }
    if (this.hasPin()) {
      if (this.pinOk()) {
        if (this.data.collection.pin_code) {
          loca_key = "collection.workfolder.button.unlock.reveal_pin";
        } else {
          loca_key = "collection.workfolder.button.unlock";
        }
      } else {
        loca_key = "collection.workfolder.button.lock";
      }
      items.push(new LocaButton({
        appearance: "flat",
        loca_key: loca_key,
        loca_key_attrs: {
          pin_code: this.data.collection.pin_code
        },
        onClick: (function(_this) {
          return function(ev) {
            if (_this.data.collection.pin_code) {
              return;
            }
            return _this.__askPin(ev);
          };
        })(this)
      }));
    }
    return items;
  };

  CollectionWorkfolder.prototype.__getSortManagerForExport = function() {
    return null;
  };

  CollectionWorkfolder.prototype.hasPin = function() {
    return !!this.data._has_pin;
  };

  CollectionWorkfolder.prototype.pinOk = function() {
    return !!this.data._pin_ok;
  };

  CollectionWorkfolder.prototype.placeholder = function() {
    return "collection.workfolder.new";
  };

  CollectionWorkfolder.prototype.setData = function(data1) {
    this.data = data1;
    CollectionWorkfolder.__super__.setData.call(this, this.data);
    this.data.collection.children_allowed = true;
    if (!this.data.collection.type) {
      this.data.collection.type = "workfolder";
    }
    return this.data.collection.objects_allowed = true;
  };

  CollectionWorkfolder.prototype.getCurrentTools = function() {
    var count, father, ref, ref1, tools, userRoot;
    tools = CollectionWorkfolder.__super__.getCurrentTools.call(this);
    count = this.getBareCount();
    if (count > 0 && this.isPresentable() && ez5.session.hasSystemRight("root", "frontend_features[collection_presentation]")) {
      tools.push(new ToolboxTool({
        group: "collection",
        name: "collection.presentation",
        sort: "A:6",
        run: (function(_this) {
          return function() {
            return new Presentation({
              collection: _this
            }).showEditor().done(function() {
              return _this.reload();
            });
          };
        })(this)
      }));
    }
    if (this.isPresentable() && this.isCreateChildAllowed() && this.getFather() instanceof CollectionStorable) {
      tools.push(new ToolboxTool({
        group: "collection",
        name: "collection.copy",
        sort: "H:4",
        run: (function(_this) {
          return function() {
            return _this.__createNewCopy();
          };
        })(this)
      }));
    }
    if (this.hasUploadConfigured()) {
      tools.push(new ToolboxTool({
        group: this.getToolGroup(),
        name: "collection.upload",
        sort: "D:1",
        favorite: true,
        run: (function(_this) {
          return function(ev, btn) {
            return _this.__fileUpload.openDialog({
              directory: ev.altKey() || ev.shiftKey(),
              multiple: true
            });
          };
        })(this)
      }));
    }
    father = this.getFather();
    if (father && !((ref = father.data) != null ? (ref1 = ref.collection) != null ? ref1.is_system_collection : void 0 : void 0) && this.isWritable() && !this.isSharedCollection()) {
      userRoot = father;
      while (userRoot && !(userRoot instanceof CollectionSystemUser)) {
        userRoot = typeof userRoot.getFather === "function" ? userRoot.getFather() : void 0;
      }
      if (userRoot) {
        tools.push(new ToolboxTool({
          group: "collection",
          name: "collection.move_to_top_level",
          sort: "H:2",
          run: (function(_this) {
            return function(ev) {
              return _this.__moveToTopLevel(ev, userRoot);
            };
          })(this)
        }));
      }
    }
    return tools;
  };

  CollectionWorkfolder.prototype.__moveToTopLevel = function(ev, targetParent) {
    return this.loadFromDb().done((function(_this) {
      return function() {
        var sd;
        sd = _this.getSaveData();
        sd.collection._id_parent = targetParent.getId();
        return _this.save(ev, sd).done(function() {
          _this.remove(false, false);
          return targetParent.addChild(_this);
        });
      };
    })(this));
  };

  CollectionWorkfolder.prototype.close = function() {
    var dfr, manager;
    dfr = CollectionWorkfolder.__super__.close.call(this);
    manager = this.getManager();
    if (manager != null ? typeof manager.hasFilter === "function" ? manager.hasFilter() : void 0 : void 0) {
      dfr.done((function(_this) {
        return function() {
          return delete _this.children;
        };
      })(this));
    }
    return dfr;
  };

  CollectionWorkfolder.prototype.isPresentable = function() {
    return true;
  };

  CollectionWorkfolder.prototype.__askPin = function(ev) {
    var ask_pin, dfr, pin;
    dfr = new CUI.Deferred();
    pin = ez5.session.user.getPinCode(this.getId());
    ask_pin = (function(_this) {
      return function() {
        return new CUI.prompt({
          markdown: true,
          text: $$("collection.workfolder.prompt.pin_code.md", {
            collection: _this.renderNameAsText()
          }),
          "default": pin
        }).fail(dfr.reject).done(function(pin2) {
          console.debug("entered pin:", pin2);
          ez5.session.user.setPinCode(_this.getId(), pin2);
          return ez5.session.user.saveLimited(ev, "settings").done(function(data) {
            console.debug("saved user", data);
            return _this.refresh(true).fail(function(xhr) {
              var ref;
              if ((xhr != null ? (ref = xhr.responseJSON) != null ? ref.code : void 0 : void 0) === "RightRequired") {
                return new CUI.problem({
                  text: $$("collection.storable.error_date_expired")
                }).done(dfr.reject);
              } else {
                return new CUI.problem({
                  text: $$("collection.workfolder.prompt.wrong_pin")
                }).done(ask_pin);
              }
            }).done(function() {
              if (!_this.hasPin() || _this.pinOk()) {
                return dfr.resolve();
              } else {
                pin = pin2;
                return new CUI.problem({
                  text: $$("collection.workfolder.prompt.wrong_pin")
                }).done(ask_pin);
              }
            });
          }).fail(dfr.reject);
        });
      };
    })(this);
    ask_pin();
    return dfr.promise();
  };

  CollectionWorkfolder.prototype.select = function(ev) {
    var deferred;
    if (this.hasPin() && !this.pinOk()) {
      return this.__askPin(ev).done((function(_this) {
        return function() {
          return _this.select(ev);
        };
      })(this));
    }
    if (this.isLeaf()) {
      return CollectionWorkfolder.__super__.select.call(this);
    }
    deferred = new CUI.Deferred();
    CollectionWorkfolder.__super__.select.call(this, ev).done((function(_this) {
      return function() {
        return _this.open().done(deferred.resolve).fail(deferred.reject);
      };
    })(this)).fail(deferred.reject);
    return deferred.promise();
  };

  CollectionWorkfolder.prototype.removeObjects = function(collection_objects) {
    var dfr;
    dfr = new CUI.Deferred();
    (new Presentation({
      collection: this
    })).checkRemoveObjects(collection_objects).done((function(_this) {
      return function() {
        return CollectionWorkfolder.__super__.removeObjects.call(_this, collection_objects).done(dfr.resolve).fail(dfr.reject);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  CollectionWorkfolder.newInstance = function(opts) {
    if (opts.collection.collection.is_system_collection) {
      if (opts.collection.collection._id_parent) {
        return new CollectionSystemUser(opts);
      } else {
        return new CollectionSystemRoot(opts);
      }
    } else {
      return new this(opts);
    }
  };

  CollectionWorkfolder.prototype.addedToListView = function(DOMNodes) {
    CollectionWorkfolder.__super__.addedToListView.call(this, DOMNodes);
    CUI.dom.setAttribute(DOMNodes[0], "ui", "collection.workfolder");
    return this;
  };

  CollectionWorkfolder.prototype.__createNewCopy = function() {
    var collectionManager, copiedData, copyNumber, nameExists, originalDisplayname, setCopyName;
    collectionManager = this.getManager();
    originalDisplayname = this.getData().collection.displayname;
    copiedData = CUI.util.copyObject(this.getData().collection, true);
    delete copiedData._id;
    delete copiedData.uuid;
    nameExists = (function(_this) {
      return function(displayname) {
        var collectionWorkfolder, existingDisplayName, i, j, language, len, len1, ref, ref1;
        ref = _this.getFather().children;
        for (i = 0, len = ref.length; i < len; i++) {
          collectionWorkfolder = ref[i];
          existingDisplayName = collectionWorkfolder.getData().collection.displayname;
          ref1 = ez5.loca.getDatabaseLanguages();
          for (j = 0, len1 = ref1.length; j < len1; j++) {
            language = ref1[j];
            if (displayname[language]) {
              if (existingDisplayName[language] === displayname[language]) {
                return true;
              }
            }
          }
        }
        return false;
      };
    })(this);
    copyNumber = 0;
    setCopyName = (function(_this) {
      return function() {
        var copyName, i, language, len, ref;
        copyNumber++;
        ref = ez5.loca.getDatabaseLanguages();
        for (i = 0, len = ref.length; i < len; i++) {
          language = ref[i];
          if (copiedData.displayname[language]) {
            copyName = $$("collection.workfolder.copy.name", {
              number: copyNumber,
              name: originalDisplayname[language]
            });
            copiedData.displayname[language] = copyName;
          }
        }
        if (nameExists(copiedData.displayname) && copyNumber < 1000) {
          return setCopyName();
        }
      };
    })(this);
    setCopyName();
    collectionManager.newCollection(collectionManager.getCollectionWorkfolderClass(), this.getFather(), copiedData).done((function(_this) {
      return function(newCollection) {
        var batchOffset, collectionObjectsArray, searchObjects;
        batchOffset = 1000;
        collectionObjectsArray = [];
        searchObjects = function(limit, offset) {
          return _this.executeSearch({
            limit: limit,
            offset: offset
          }).done(function(data) {
            var i, len, object, ref;
            ref = data.objects;
            for (i = 0, len = ref.length; i < len; i++) {
              object = ref[i];
              collectionObjectsArray.push(new CollectionObject({
                _global_object_id: object._global_object_id
              }));
            }
            offset = offset + batchOffset;
            if (offset < data.count) {
              return searchObjects(limit, offset);
            } else {
              if (collectionObjectsArray.length > 0) {
                return newCollection.insertObjects(collectionObjectsArray);
              }
            }
          }).fail(function() {
            return console.error("There was an error when fetching collection objects.");
          });
        };
        return searchObjects(batchOffset, 0);
      };
    })(this));
  };

  CollectionWorkfolder.prototype.getStoreData = function() {
    if (ez5.version("6")) {
      return {
        className: this.constructor.name,
        subcollectionIds: this.__subcollectionIds,
        data: {
          collection: structuredClone(this._collection)
        }
      };
    }
    return CollectionWorkfolder.__super__.getStoreData.call(this);
  };

  return CollectionWorkfolder;

})(CollectionStorable);
// Generated by CoffeeScript 1.12.7
var CollectionSystem,
  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;

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

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

  CollectionSystem.prototype.icon = function() {
    return "fa-hdd-o";
  };

  CollectionSystem.prototype.getCount = function() {
    return "";
  };

  CollectionSystem.prototype.canAppend = function() {
    return false;
  };

  CollectionSystem.prototype.isPresentable = function() {
    return false;
  };

  CollectionSystem.prototype.isSelectable = function() {
    return false;
  };

  CollectionSystem.prototype.isRenamable = function() {
    return false;
  };

  CollectionSystem.prototype.isDownloadable = function() {
    return false;
  };

  CollectionSystem.prototype.isExportable = function() {
    return false;
  };

  CollectionSystem.prototype.isSearchable = function() {
    return false;
  };

  CollectionSystem.prototype.getEmptyLabelLocaKey = function() {
    return CUI.util.toDash(CUI.util.getObjectClass(this)).replace(/-/g, '.') + ".empty_label";
  };

  CollectionSystem.prototype.getGeneralFormFields = function(data) {
    return [
      {
        type: CUI.MultiOutput,
        data: data.collection,
        form: {
          label: $$("collection.form.displayname")
        },
        name: "displayname",
        control: ez5.loca.getLanguageControlAdmin(),
        user_selectable: ez5.session.getPref("languages_user_selection")
      }, {
        type: CUI.MultiOutput,
        data: data.collection,
        form: {
          label: $$("collection.form.description")
        },
        name: "description",
        control: ez5.loca.getLanguageControlAdmin(),
        user_selectable: ez5.session.getPref("languages_user_selection")
      }, {
        type: CUI.Output,
        data: data.collection,
        form: {
          label: $$("collection.form.reference")
        },
        name: "reference"
      }
    ];
  };

  CollectionSystem.prototype.getCounterItems = function() {
    return [];
  };

  CollectionSystem.prototype.showDetail = function() {
    var pane;
    pane = this._manager.resetCollectionDetailDiv(this);
    pane.append(this.getButtonbar(), "footer_right");
    return CUI.resolvedPromise();
  };

  CollectionSystem.prototype.setDisplayname = function(key) {
    return this.data.collection.displayname = ez5.loca.get_complete_key(key);
  };

  CollectionSystem.prototype.getSaveData = function() {
    var sd;
    sd = CollectionSystem.__super__.getSaveData.call(this);
    delete sd.collection.displayname;
    delete sd.collection.description;
    delete sd.collection.children_allowed;
    delete sd.collection.objects_allowed;
    delete sd.collection.type;
    delete sd.collection._id_parent;
    return sd;
  };

  CollectionSystem.prototype.isDeletable = function() {
    return false;
  };

  CollectionSystem.prototype.makeDraggable = function(el) {};

  return CollectionSystem;

})(CollectionWorkfolder);
// Generated by CoffeeScript 1.12.7
var CollectionSystemUser,
  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;

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

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

  CollectionSystemUser.prototype.icon = function() {
    return "fa-user";
  };

  CollectionSystemUser.prototype.enableShare = function() {
    return false;
  };

  CollectionSystemUser.prototype.isSelectable = function() {
    return false;
  };

  CollectionSystemUser.prototype.renderNameAsHtml = function() {
    return CUI.util.toHtml(this.renderNameAsText());
  };

  CollectionSystemUser.prototype.renderNameAsText = function() {
    var cm, ref, ref1;
    if (((ref = this.data._owner) != null ? (ref1 = ref.user) != null ? ref1._id : void 0 : void 0) === ez5.session.getUser().getId()) {
      cm = this.getManager();
      return $$(cm.getDisplayNameKeyForOwnCollections());
    } else {
      return CollectionSystemUser.__super__.renderNameAsText.call(this);
    }
  };

  CollectionSystemUser.prototype.isLeaf = function() {
    return false;
  };

  CollectionSystemUser.prototype.getSearchFilter = function() {
    var i, ids, len, node, ref;
    ids = [];
    ref = this.find();
    for (i = 0, len = ref.length; i < len; i++) {
      node = ref[i];
      if (node.data.collection._id) {
        ids.push(node.data.collection._id);
      }
    }
    if (!ids.length) {
      return false;
    }
    return {
      bool: "must",
      type: "in",
      fields: ["_collections"],
      "in": ids
    };
  };

  return CollectionSystemUser;

})(CollectionSystem);
// Generated by CoffeeScript 1.12.7
var CollectionSystemRoot,
  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;

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

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

  CollectionSystemRoot.prototype.canHaveChildren = function() {
    return false;
  };

  CollectionSystemRoot.prototype.isCreateChildAllowed = function() {
    return false;
  };

  CollectionSystemRoot.prototype.getChildren = null;

  CollectionSystemRoot.prototype.isSelectable = function() {
    return false;
  };

  return CollectionSystemRoot;

})(CollectionSystem);
// Generated by CoffeeScript 1.12.7
var CollectionStructure,
  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;

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

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

  CollectionStructure.prototype.initOpts = function() {
    CollectionStructure.__super__.initOpts.call(this);
    return this.addOpts({
      icon: {
        "default": "fa-cloud",
        mandatory: true,
        check: function(v) {
          return CUI.util.isString(v) || v instanceof CUI.Icon || v === null;
        }
      },
      displayname: {
        "default": "Structure",
        check: function(v) {
          return CUI.util.isString(v) || CUI.util.isContent(v);
        }
      },
      displaytext: {
        check: String
      },
      navigation: {
        check: function(v) {
          return v instanceof NavigationToolbar || v === null;
        }
      }
    });
  };

  CollectionStructure.prototype.readOpts = function() {
    CollectionStructure.__super__.readOpts.call(this);
    this.__icon = this._icon;
    this.__displayname = this._displayname;
    this.__displaytext = this._displaytext || this.__displayname;
    return this;
  };

  CollectionStructure.prototype.icon = function() {
    return this.__icon;
  };

  CollectionStructure.prototype.updateCounter = function() {};

  CollectionStructure.prototype.getChildren = function() {
    return typeof this._getChildren === "function" ? this._getChildren() : void 0;
  };

  CollectionStructure.prototype.isMovable = function() {
    return false;
  };

  CollectionStructure.prototype.isSelectable = function() {
    return false;
  };

  CollectionStructure.prototype.renderNameAsText = function() {
    return this.__displaytext;
  };

  CollectionStructure.prototype.updateDisplay = function() {
    var ref;
    if (CUI.util.isString(this.__displayname)) {
      return CollectionStructure.__super__.updateDisplay.call(this);
    }
    if ((ref = this.contentLabel) != null) {
      ref.setContent(this.__displayname);
    }
    return this;
  };

  return CollectionStructure;

})(CollectionSearchNode);
// Generated by CoffeeScript 1.12.7
var QueryElementCollection,
  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;

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

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

  QueryElementCollection.prototype.initOpts = function() {
    QueryElementCollection.__super__.initOpts.call(this);
    return this.addOpts({
      collection: {
        mandatory: true,
        check: Collection
      }
    });
  };

  QueryElementCollection.prototype.readOpts = function() {
    QueryElementCollection.__super__.readOpts.call(this);
    return this.collection = this._collection;
  };

  QueryElementCollection.prototype.getBadge = function() {
    return this.collection.getBadge();
  };

  QueryElementCollection.prototype.getSearchFilter = function() {
    return this.collection.getSearchFilter();
  };

  QueryElementCollection.prototype.ignoreSearchManagers = function() {
    return this.collection.ignoreSearchManagers();
  };

  QueryElementCollection.prototype.getCollection = function() {
    return this.collection;
  };

  QueryElementCollection.prototype.getStoreData = function() {
    return this.collection.getStoreData();
  };

  QueryElementCollection.prototype.destroy = function() {
    this._collection.queryElementDestroyed();
    return QueryElementCollection.__super__.destroy.call(this);
  };

  QueryElementCollection.newFromData = function(arg) {
    var className, collection, data, subcollectionIds;
    className = arg.className, subcollectionIds = arg.subcollectionIds, data = arg.data;
    collection = new window[className](data);
    collection.__subcollectionIds = subcollectionIds;
    return new QueryElementCollection({
      collection: collection
    });
  };

  return QueryElementCollection;

})(QueryElementSpan);
// Generated by CoffeeScript 1.12.7
var AddToCollectionHelper,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

AddToCollectionHelper = (function() {
  function AddToCollectionHelper() {}

  AddToCollectionHelper.MAX_RECENT_COLLECTIONS = 5;

  AddToCollectionHelper.__getStorageKey = function() {
    return window.easydb_server_url + ".recent_collections." + (ez5.session.getUser().getId());
  };

  AddToCollectionHelper.getRecentCollections = function() {
    var e, stored;
    try {
      stored = CUI.getLocalStorage(this.__getStorageKey());
      if (stored) {
        return JSON.parse(stored);
      }
    } catch (error) {
      e = error;
      console.error("AddToCollectionHelper.getRecentCollections: Error reading localStorage", e);
    }
    return [];
  };

  AddToCollectionHelper.addToRecentCollections = function(collection) {
    var collectionData, e, recent, ref, ref1;
    if (!(collection != null ? typeof collection.getId === "function" ? collection.getId() : void 0 : void 0)) {
      return;
    }
    collectionData = {
      id: collection.getId(),
      displayname: (typeof collection.getCollectionDisplayname === "function" ? collection.getCollectionDisplayname() : void 0) || (typeof collection.getData === "function" ? (ref = collection.getData()) != null ? (ref1 = ref.collection) != null ? ref1.displayname : void 0 : void 0 : void 0) || {}
    };
    recent = this.getRecentCollections();
    recent = recent.filter(function(c) {
      return c.id !== collectionData.id;
    });
    recent.unshift(collectionData);
    recent = recent.slice(0, this.MAX_RECENT_COLLECTIONS);
    try {
      CUI.setLocalStorage(this.__getStorageKey(), JSON.stringify(recent));
    } catch (error) {
      e = error;
      console.error("AddToCollectionHelper.addToRecentCollections: Error saving to localStorage", e);
    }
  };

  AddToCollectionHelper.__validateRecentCollections = function() {
    var dfr, recent, recentIds;
    dfr = new CUI.Deferred();
    recent = this.getRecentCollections();
    if (recent.length === 0) {
      dfr.resolve([]);
      return dfr.promise();
    }
    recentIds = recent.map(function(c) {
      return c.id;
    });
    ez5.api.search({
      json_data: {
        type: "collection",
        limit: this.MAX_RECENT_COLLECTIONS,
        generate_rights: true,
        search: [
          {
            type: "in",
            bool: "must",
            fields: ["collection._id"],
            "in": recentIds
          }
        ]
      }
    }).done((function(_this) {
      return function(data) {
        var collectionsById, currentUserId, i, isOwn, j, len, len1, obj, recentCol, ref, ref1, ref2, ref3, ref4, ref5, serverCol, validCollections;
        currentUserId = ez5.session.getUser().getId();
        validCollections = [];
        collectionsById = {};
        ref = data.objects || [];
        for (i = 0, len = ref.length; i < len; i++) {
          obj = ref[i];
          collectionsById[obj.collection._id] = obj;
        }
        for (j = 0, len1 = recent.length; j < len1; j++) {
          recentCol = recent[j];
          serverCol = collectionsById[recentCol.id];
          if (serverCol) {
            isOwn = ((ref1 = serverCol._owner) != null ? (ref2 = ref1.user) != null ? ref2._id : void 0 : void 0) === currentUserId;
            validCollections.push({
              id: recentCol.id,
              displayname: serverCol.collection.displayname,
              shared: !isOwn || serverCol._has_acl,
              hotfolder: !CUI.util.isEmpty((ref3 = serverCol.collection) != null ? (ref4 = ref3.create_object) != null ? ref4.objecttype : void 0 : void 0),
              hasLinkRight: (ref5 = serverCol._generated_rights) != null ? ref5.link : void 0
            });
          }
        }
        return dfr.resolve(validCollections);
      };
    })(this)).fail((function(_this) {
      return function() {
        return dfr.resolve([]);
      };
    })(this));
    return dfr.promise();
  };

  AddToCollectionHelper.getAddToCollectionMenuItems = function(opts) {
    var collection, existingItems, fn, i, item, len, loadingItem, manager, menu_items, onAddToCollection, onRecentCollectionsValidated, recent;
    collection = opts.collection, manager = opts.manager, onAddToCollection = opts.onAddToCollection, onRecentCollectionsValidated = opts.onRecentCollectionsValidated;
    if (!ez5.session.hasSystemRight("root", "search", "search_collection_only")) {
      return [];
    }
    menu_items = [];
    recent = this.getRecentCollections();
    if (recent.length > 0) {
      menu_items.push({
        label: $$("tool.add_to_collection.recent_collections")
      });
      loadingItem = {
        text: $$("tool.add_to_collection.loading_recent"),
        icon: new CUI.Icon({
          icon: "spinner",
          "class": "fa-spin"
        }),
        disabled: true
      };
      menu_items.push(loadingItem);
      menu_items.push({
        divider: true
      });
      this.__validateRecentCollections().done((function(_this) {
        return function(validRecent) {
          return typeof onRecentCollectionsValidated === "function" ? onRecentCollectionsValidated(validRecent) : void 0;
        };
      })(this));
    }
    menu_items.push({
      label: $$("tool.add_to_collection.browse_collections")
    });
    menu_items.push({
      text: $$("tool.add_to_collection.select_collection"),
      icon: "fa-search",
      onClick: (function(_this) {
        return function() {
          return _this.showCollectionPicker(collection, manager, onAddToCollection);
        };
      })(this)
    });
    if (manager != null ? manager.getMenuItems : void 0) {
      existingItems = manager.getMenuItems();
      if ((existingItems != null ? existingItems.length : void 0) > 0) {
        menu_items.push({
          divider: true
        });
        fn = (function(_this) {
          return function(item) {
            return menu_items.push({
              text: item.text,
              disabled: item.disabled,
              onClick: function(ev, btn) {
                return item.onClick(ev, btn).done(function(new_collection) {
                  return typeof onAddToCollection === "function" ? onAddToCollection(new_collection) : void 0;
                });
              }
            });
          };
        })(this);
        for (i = 0, len = existingItems.length; i < len; i++) {
          item = existingItems[i];
          if (item.label) {
            menu_items.push(item);
            continue;
          }
          fn(item);
        }
      }
    }
    return menu_items;
  };

  AddToCollectionHelper.getCollectionIcon = function(colData) {
    var hotfolder, icon, ref, ref1, ref2, shared;
    if (colData.shared != null) {
      shared = colData.shared;
      hotfolder = colData.hotfolder;
    } else {
      shared = ((ref = colData._acl) != null ? ref.length : void 0) || colData._has_acl;
      hotfolder = !CUI.util.isEmpty((ref1 = colData.collection) != null ? (ref2 = ref1.create_object) != null ? ref2.objecttype : void 0 : void 0);
    }
    icon = "folder";
    if (shared) {
      icon += "_shared";
    }
    if (hotfolder) {
      icon += "_upload";
    }
    return icon;
  };

  AddToCollectionHelper.__buildRecentCollectionItems = function(validRecent, collection, onAddToCollection) {
    var fn, i, items, len, recentCol;
    items = [];
    fn = (function(_this) {
      return function(recentCol) {
        var displayText;
        displayText = ez5.loca.getBestDatabaseValue(recentCol.displayname) || $$("tool.add_to_collection.unknown_collection");
        return items.push({
          text: displayText,
          icon: _this.getCollectionIcon(recentCol),
          onClick: function() {
            return _this.__addToCollectionById(recentCol.id, collection, onAddToCollection);
          }
        });
      };
    })(this);
    for (i = 0, len = validRecent.length; i < len; i++) {
      recentCol = validRecent[i];
      fn(recentCol);
    }
    return items;
  };

  AddToCollectionHelper.updateMenuItemsWithValidatedRecent = function(currentItems, validRecent, collection, onAddToCollection) {
    var i, item, j, len, len1, newItems, recentItem, recentItems, skipUntilDivider;
    newItems = [];
    skipUntilDivider = false;
    for (i = 0, len = currentItems.length; i < len; i++) {
      item = currentItems[i];
      if (item.label === $$("tool.add_to_collection.recent_collections")) {
        skipUntilDivider = true;
        if (validRecent.length > 0) {
          newItems.push(item);
          recentItems = this.__buildRecentCollectionItems(validRecent, collection, onAddToCollection);
          for (j = 0, len1 = recentItems.length; j < len1; j++) {
            recentItem = recentItems[j];
            newItems.push(recentItem);
          }
          newItems.push({
            divider: true
          });
        }
        continue;
      }
      if (skipUntilDivider) {
        if (item.divider) {
          skipUntilDivider = false;
        }
        continue;
      }
      newItems.push(item);
    }
    return newItems;
  };

  AddToCollectionHelper.__addToCollectionById = function(collectionId, sourceCollection, onAddToCollection) {
    ez5.api.search({
      json_data: {
        type: "collection",
        limit: 1,
        generate_rights: true,
        search: [
          {
            type: "in",
            bool: "must",
            fields: ["collection._id"],
            "in": [collectionId]
          }
        ]
      }
    }).done((function(_this) {
      return function(data) {
        var addWithRestrictions, colData, ref, targetCollection;
        if (((ref = data.objects) != null ? ref.length : void 0) > 0) {
          colData = data.objects[0];
          targetCollection = CollectionWorkfolder.newInstance({
            collection: colData,
            readonly: true
          });
          addWithRestrictions = function() {
            var allObjects, linkRight, ref1, ref2, result;
            linkRight = (ref1 = targetCollection.getData()) != null ? (ref2 = ref1._generated_rights) != null ? ref2.link : void 0 : void 0;
            if (!linkRight) {
              CUI.problem({
                text: $$("tool.add_to_collection.no_permission")
              });
              return;
            }
            allObjects = (sourceCollection != null ? typeof sourceCollection.getObjects === "function" ? sourceCollection.getObjects() : void 0 : void 0) || [];
            if (allObjects.length === 0) {
              CUI.problem({
                text: $$("tool.add_to_collection.no_objects_to_add")
              });
              return;
            }
            result = _this.__checkLinkRestrictions(linkRight, allObjects);
            if (result.allowed.length === 0) {
              CUI.problem({
                text: $$("tool.add_to_collection.no_objects_allowed")
              });
              return;
            }
            if (result.allowed.length < allObjects.length) {
              CUI.problem({
                text: $$("tool.add_to_collection.partial_objects_added", {
                  allowed: result.allowed.length,
                  total: allObjects.length
                }),
                type: "info"
              });
            }
            _this.addToRecentCollections(targetCollection);
            return typeof onAddToCollection === "function" ? onAddToCollection(targetCollection, result.allowed) : void 0;
          };
          if ((typeof targetCollection.hasPin === "function" ? targetCollection.hasPin() : void 0) && !(typeof targetCollection.pinOk === "function" ? targetCollection.pinOk() : void 0)) {
            _this.__askPinForCollection(targetCollection).done(function() {
              return addWithRestrictions();
            });
            return;
          }
          return addWithRestrictions();
        } else {
          return CUI.problem({
            text: $$("tool.add_to_collection.collection_not_found")
          });
        }
      };
    })(this)).fail((function(_this) {
      return function() {
        return CUI.problem({
          text: $$("tool.add_to_collection.error_loading_collection")
        });
      };
    })(this));
  };

  AddToCollectionHelper.showCollectionPicker = function(sourceCollection, manager, onAddToCollection, opts) {
    var buildTree, contentPane, currentFilter, disabledIds, filterData, filterInput, handleDeselect, handleSelect, infoLabel, linkableObjects, loadCollections, loadSharedCollectionsPage, markDisabledNodes, modal, ownTree, paginateSharedCollections, panelsContainer, ref, selectButton, selectedCollection, selectedCollections, sharedCollectionsCount, sharedCollectionsOffset, sharedNavigationToolbar, sharedPanel, sharedTree, updateSelectButton, updateSelectionState;
    if (opts == null) {
      opts = {};
    }
    modal = null;
    selectedCollection = null;
    selectedCollections = {};
    currentFilter = "";
    panelsContainer = CUI.dom.div();
    linkableObjects = [];
    disabledIds = ((ref = opts.disabledIds) != null ? ref.slice(0) : void 0) || [];
    ownTree = null;
    sharedTree = null;
    sharedCollectionsOffset = 0;
    sharedCollectionsCount = 0;
    paginateSharedCollections = false;
    sharedPanel = null;
    sharedNavigationToolbar = null;
    infoLabel = new CUI.Label({
      "class": "cui-label-danger",
      icon: "fa-exclamation-triangle",
      text: ""
    });
    CUI.dom.hideElement(infoLabel.DOM);
    updateSelectButton = (function(_this) {
      return function() {
        var count;
        count = Object.keys(selectedCollections).length;
        if (count > 0) {
          selectButton.enable();
        } else {
          selectButton.disable();
        }
        return CUI.dom.hideElement(infoLabel.DOM);
      };
    })(this);
    markDisabledNodes = (function(_this) {
      return function(nodes) {
        var children, colId, i, len, node, ref1, ref2, ref3, results;
        if (!nodes || disabledIds.length === 0) {
          return;
        }
        results = [];
        for (i = 0, len = nodes.length; i < len; i++) {
          node = nodes[i];
          if (node instanceof CollectionStorable) {
            colId = (ref1 = node.getData()) != null ? (ref2 = ref1.collection) != null ? ref2._id : void 0 : void 0;
            if (colId && indexOf.call(disabledIds, colId) >= 0) {
              node.isSelectable = function() {
                return false;
              };
            }
          }
          children = node.children || ((ref3 = node.opts) != null ? ref3.children : void 0);
          if (children) {
            results.push(markDisabledNodes(children));
          } else {
            results.push(void 0);
          }
        }
        return results;
      };
    })(this);
    selectButton = new CUI.Button({
      text: $$("tool.add_to_collection.picker_select"),
      primary: true,
      disabled: true,
      onClick: (function(_this) {
        return function() {
          var colId, node;
          if (opts.multiSelect) {
            for (colId in selectedCollections) {
              node = selectedCollections[colId];
              if (opts.browseOnly) {
                if (typeof onAddToCollection === "function") {
                  onAddToCollection(node);
                }
              } else {
                _this.addToRecentCollections(node);
                if (typeof onAddToCollection === "function") {
                  onAddToCollection(node);
                }
              }
            }
            modal.destroy();
            return;
          }
          if (opts.browseOnly) {
            if (selectedCollection) {
              if (typeof onAddToCollection === "function") {
                onAddToCollection(selectedCollection);
              }
              modal.destroy();
            }
            return;
          }
          if (selectedCollection && linkableObjects.length > 0) {
            _this.addToRecentCollections(selectedCollection);
            if (typeof onAddToCollection === "function") {
              onAddToCollection(selectedCollection, linkableObjects);
            }
            return modal.destroy();
          }
        };
      })(this)
    });
    buildTree = (function(_this) {
      return function(collections, onSelect, onDeselect) {
        var rootNode, tree, treeContent, treeOpts;
        if (opts.multiSelect) {
          markDisabledNodes(collections);
        }
        rootNode = new CUI.ListViewTreeNode({
          children: collections
        });
        treeOpts = {
          cols: ["maximize", "auto"],
          maximize_horizontal: true,
          no_header: true,
          rowMove: false,
          root: rootNode,
          colClasses: ["ez5-collection-manager-column-main", "ez5-collection-manager-column-utils ez5-list-view-column-count"],
          selectableRows: opts.multiSelect ? "multiple" : true,
          onSelect: onSelect
        };
        if (onDeselect) {
          treeOpts.onDeselect = onDeselect;
        }
        tree = new ListViewEditTree(treeOpts);
        treeContent = tree.render();
        tree.load_data(collections);
        return {
          tree: tree,
          content: treeContent
        };
      };
    })(this);
    updateSelectionState = (function(_this) {
      return function() {
        var allObjects, linkRight, ref1, ref2, result;
        if (!selectedCollection) {
          linkableObjects = [];
          selectButton.disable();
          CUI.dom.hideElement(infoLabel.DOM);
          return;
        }
        if (opts.browseOnly) {
          selectButton.enable();
          return;
        }
        linkRight = (ref1 = selectedCollection.getData()) != null ? (ref2 = ref1._generated_rights) != null ? ref2.link : void 0 : void 0;
        if (!linkRight) {
          linkableObjects = [];
          selectButton.disable();
          infoLabel.setText($$("tool.add_to_collection.no_permission"));
          CUI.dom.showElement(infoLabel.DOM);
          return;
        }
        allObjects = (sourceCollection != null ? typeof sourceCollection.getObjects === "function" ? sourceCollection.getObjects() : void 0 : void 0) || [];
        if (allObjects.length === 0) {
          linkableObjects = [];
          selectButton.disable();
          CUI.dom.hideElement(infoLabel.DOM);
          return;
        }
        result = _this.__checkLinkRestrictions(linkRight, allObjects);
        linkableObjects = result.allowed;
        if (linkableObjects.length === 0) {
          selectButton.disable();
          infoLabel.setText($$("tool.add_to_collection.no_objects_allowed"));
          return CUI.dom.showElement(infoLabel.DOM);
        } else if (linkableObjects.length < allObjects.length) {
          selectButton.enable();
          infoLabel.setText($$("tool.add_to_collection.partial_objects_allowed", {
            allowed: linkableObjects.length,
            total: allObjects.length
          }));
          return CUI.dom.showElement(infoLabel.DOM);
        } else {
          selectButton.enable();
          return CUI.dom.hideElement(infoLabel.DOM);
        }
      };
    })(this);
    handleSelect = (function(_this) {
      return function(ev, info, sourceTree) {
        var colId, node, ref1, ref2, ref3, ref4, ref5, ref6;
        node = info.node;
        if (opts.multiSelect) {
          if (node instanceof CollectionStorable) {
            colId = (ref1 = node.getData()) != null ? (ref2 = ref1.collection) != null ? ref2._id : void 0 : void 0;
            if (colId) {
              selectedCollections[colId] = node;
              updateSelectButton();
            }
          }
          return;
        }
        if (sourceTree === "own" && sharedTree) {
          if ((ref3 = sharedTree.getSelectedNode()) != null) {
            ref3.deselect();
          }
        } else if (sourceTree === "shared" && ownTree) {
          if ((ref4 = ownTree.getSelectedNode()) != null) {
            ref4.deselect();
          }
        }
        if (node instanceof CollectionStorable) {
          colId = (ref5 = node.getData()) != null ? (ref6 = ref5.collection) != null ? ref6._id : void 0 : void 0;
          if (colId && indexOf.call(disabledIds, colId) >= 0) {
            selectedCollection = null;
            selectButton.disable();
            infoLabel.setText($$("tool.add_to_collection.already_selected"));
            CUI.dom.showElement(infoLabel.DOM);
            return;
          }
          selectedCollection = node;
          if (!opts.browseOnly && (typeof selectedCollection.hasPin === "function" ? selectedCollection.hasPin() : void 0) && !(typeof selectedCollection.pinOk === "function" ? selectedCollection.pinOk() : void 0)) {
            selectButton.disable();
            CUI.dom.hideElement(infoLabel.DOM);
            _this.__askPinForCollection(selectedCollection, ev).done(function() {
              return updateSelectionState();
            }).fail(function() {
              selectButton.disable();
              return CUI.dom.hideElement(infoLabel.DOM);
            });
            return;
          }
          return updateSelectionState();
        } else {
          selectedCollection = null;
          linkableObjects = [];
          selectButton.disable();
          return CUI.dom.hideElement(infoLabel.DOM);
        }
      };
    })(this);
    handleDeselect = (function(_this) {
      return function(ev, info) {
        var colId, node, ref1, ref2;
        if (!opts.multiSelect) {
          return;
        }
        node = info.node;
        if (node instanceof CollectionStorable) {
          colId = (ref1 = node.getData()) != null ? (ref2 = ref1.collection) != null ? ref2._id : void 0 : void 0;
          if (colId) {
            delete selectedCollections[colId];
            return updateSelectButton();
          }
        }
      };
    })(this);
    loadSharedCollectionsPage = (function(_this) {
      return function(page) {
        if (page == null) {
          page = 0;
        }
        sharedCollectionsOffset = page * CollectionManager.SHARED_COLLECTIONS_PAGE_SIZE;
        if (sharedNavigationToolbar != null) {
          sharedNavigationToolbar.disable();
        }
        return _this.__loadSharedCollections(manager, currentFilter, sharedCollectionsOffset).done(function(result) {
          var shared_collections;
          sharedCollectionsCount = result.count;
          shared_collections = result.collections;
          if (sharedNavigationToolbar != null) {
            sharedNavigationToolbar.update({
              count: sharedCollectionsCount,
              offset: sharedCollectionsOffset,
              limit: CollectionManager.SHARED_COLLECTIONS_PAGE_SIZE
            });
          }
          if (sharedNavigationToolbar != null) {
            sharedNavigationToolbar.enable();
          }
          if (sharedNavigationToolbar != null) {
            sharedNavigationToolbar.__update();
          }
          if (sharedTree) {
            if (opts.multiSelect) {
              markDisabledNodes(shared_collections);
            }
            return sharedTree.load_data(shared_collections);
          }
        });
      };
    })(this);
    loadCollections = (function(_this) {
      return function(filter) {
        var loadingLabel;
        if (filter == null) {
          filter = "";
        }
        selectedCollection = null;
        selectedCollections = {};
        selectButton.disable();
        sharedCollectionsOffset = 0;
        CUI.dom.empty(panelsContainer);
        loadingLabel = new CUI.Label({
          icon: "spinner",
          text: $$("tool.add_to_collection.loading_collections")
        });
        CUI.dom.append(panelsContainer, loadingLabel.DOM);
        return _this.__loadOwnCollections(manager, filter).done(function(own_collections) {
          return _this.__checkSharedCollectionsCount(filter).done(function(count) {
            var ownPanel, ownTreeResult, panelContent, rootNode, sharedTreeContainer, sharedTreeOpts;
            sharedCollectionsCount = count;
            paginateSharedCollections = count > CollectionManager.SHARED_COLLECTIONS_PAGE_SIZE;
            CUI.dom.empty(panelsContainer);
            if (own_collections.length === 0 && sharedCollectionsCount === 0) {
              CUI.dom.append(panelsContainer, new CUI.EmptyLabel({
                text: $$("tool.add_to_collection.no_collections_available")
              }).DOM);
              return;
            }
            ownPanel = null;
            if (own_collections.length > 0) {
              ownTreeResult = buildTree(own_collections, (function(ev, info) {
                return handleSelect(ev, info, "own");
              }), (function(ev, info) {
                return handleDeselect(ev, info);
              }));
              ownTree = ownTreeResult.tree;
              ownPanel = new CUI.Panel({
                closed: false,
                radio: "own-collections",
                text: $$("collection.manager.own_collections"),
                content: ownTreeResult.content
              });
              CUI.dom.append(panelsContainer, ownPanel.DOM);
            }
            if (sharedCollectionsCount > 0) {
              if (paginateSharedCollections) {
                sharedNavigationToolbar = new NavigationToolbar({
                  append_count_label: true,
                  render_on_left: false,
                  onLoadPage: function(page) {
                    return loadSharedCollectionsPage(page);
                  }
                });
              }
              sharedTreeContainer = CUI.dom.div();
              rootNode = new CUI.ListViewTreeNode({
                children: []
              });
              sharedTreeOpts = {
                cols: ["maximize", "auto"],
                maximize_horizontal: true,
                no_header: true,
                rowMove: false,
                root: rootNode,
                colClasses: ["ez5-collection-manager-column-main", "ez5-collection-manager-column-utils ez5-list-view-column-count"],
                selectableRows: opts.multiSelect ? "multiple" : true,
                onSelect: function(ev, info) {
                  return handleSelect(ev, info, "shared");
                }
              };
              if (opts.multiSelect) {
                sharedTreeOpts.onDeselect = function(ev, info) {
                  return handleDeselect(ev, info);
                };
              }
              sharedTree = new ListViewEditTree(sharedTreeOpts);
              CUI.dom.append(sharedTreeContainer, sharedTree.render());
              panelContent = CUI.dom.div();
              if (sharedNavigationToolbar) {
                CUI.dom.append(panelContent, sharedNavigationToolbar.DOM);
              }
              CUI.dom.append(panelContent, sharedTreeContainer);
              sharedPanel = new CUI.Panel({
                closed: false,
                radio: "shared-collections",
                text: $$("collection.manager.shared_collections"),
                content: panelContent
              });
              CUI.dom.append(panelsContainer, sharedPanel.DOM);
              loadSharedCollectionsPage(0);
            }
            return CUI.scheduleCallback({
              ms: 100,
              call: function() {
                if (ownPanel != null) {
                  CUI.Events.trigger({
                    type: "content-resize",
                    node: ownPanel
                  });
                }
                if (sharedPanel != null) {
                  CUI.Events.trigger({
                    type: "content-resize",
                    node: sharedPanel
                  });
                }
                return modal.autoSize();
              }
            });
          });
        });
      };
    })(this);
    filterData = {
      filter: ""
    };
    filterInput = new CUI.Input({
      "class": "ez5-quicksearch-input",
      name: "filter",
      maximize_horizontal: true,
      placeholder: $$("list.view.edit.tree.filter.placeholder"),
      data: filterData,
      undo_support: false,
      mark_changed: false,
      check_changed: false,
      onDataChanged: (function(_this) {
        return function() {
          return CUI.scheduleCallback({
            ms: 500,
            call: function() {
              if (filterData.filter !== currentFilter) {
                currentFilter = filterData.filter;
                return loadCollections(currentFilter);
              }
            }
          });
        };
      })(this)
    });
    filterInput.start();
    contentPane = new CUI.VerticalLayout({
      "class": "ez5-add-to-collection-picker-panels ez5-collection-manager-pane-panels",
      top: {
        content: [
          filterInput.DOM, new CUI.Label({
            "text": $$("collection.manager.block.collection")
          })
        ]
      },
      center: {
        content: panelsContainer
      }
    });
    modal = new CUI.Modal({
      "class": "ez5-add-to-collection-picker-modal",
      cancel: true,
      fill_space: "auto",
      pane: {
        header_left: new CUI.Label({
          text: $$("tool.add_to_collection.picker_title")
        }),
        content: contentPane,
        footer_left: infoLabel,
        footer_right: [
          new CUI.Button({
            text: $$("base.cancel"),
            onClick: (function(_this) {
              return function() {
                return modal.destroy();
              };
            })(this)
          }), selectButton
        ]
      }
    });
    modal.show();
    loadCollections();
  };

  AddToCollectionHelper.__getFilterSearch = function(filter) {
    var inputSearch, phrase, ref, str;
    if (CUI.util.isEmpty(filter)) {
      return null;
    }
    ref = Search.getPhrase(filter), str = ref[0], phrase = ref[1];
    if (ez5.version("6")) {
      inputSearch = {
        bool: "should",
        type: "match",
        mode: "wildcard",
        string: str + SearchUtil.ASTERISK
      };
    } else {
      inputSearch = {
        bool: "should",
        type: "match",
        mode: "fulltext",
        phrase: phrase,
        string: str
      };
    }
    return {
      type: "complex",
      bool: "must",
      search: [
        inputSearch, {
          type: "complex",
          bool: "should",
          search: [
            {
              type: "in",
              bool: "must",
              fields: ["_level"],
              "in": [2]
            }, {
              type: "in",
              bool: "must",
              fields: ["_owner.user._id"],
              "in": [ez5.session.getUser().getId()]
            }
          ]
        }
      ]
    };
  };

  AddToCollectionHelper.__loadOwnCollections = function(manager, filter) {
    var dfr, filterSearch, search;
    if (filter == null) {
      filter = "";
    }
    dfr = new CUI.Deferred();
    search = [
      {
        type: "in",
        bool: "must",
        fields: ["_owner.user._id"],
        "in": [ez5.session.getUser().getId()]
      }, {
        type: "in",
        bool: "must_not",
        fields: ["collection.type"],
        "in": ["search"]
      }
    ];
    filterSearch = this.__getFilterSearch(filter);
    if (filterSearch) {
      search.push(filterSearch);
    }
    ez5.api.search_no_limit({
      json_data: {
        type: "collection",
        limit: 100000,
        generate_rights: true,
        search: search,
        sort: [
          {
            field: "_level"
          }, {
            field: "collection.displayname"
          }
        ]
      }
    }).done((function(_this) {
      return function(data) {
        var _own, i, len, linkableCollections, obj, own_collections, ref, ref1;
        _own = [];
        ref = data.objects;
        for (i = 0, len = ref.length; i < len; i++) {
          obj = ref[i];
          if (obj.collection.type !== "search" && obj._owner.user._id === ez5.session.getUser().getId()) {
            _own.push(obj);
          }
        }
        linkableCollections = _own.filter(function(col) {
          var ref1;
          return (ref1 = col._generated_rights) != null ? ref1.link : void 0;
        });
        own_collections = ez5.buildObjectTree({
          objects: linkableCollections,
          objectKey: "collection",
          filter: false,
          newInstanceFunc: function(collection) {
            return CollectionWorkfolder.newInstance({
              collection: collection,
              manager: manager,
              readonly: true
            });
          }
        });
        if (own_collections.length > 0) {
          own_collections = own_collections[0].children || [];
          own_collections = ((ref1 = own_collections[0]) != null ? ref1.children : void 0) || [];
        }
        return dfr.resolve(own_collections);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  AddToCollectionHelper.__getSharedCollectionsSearch = function(filter) {
    var filterSearch, search;
    if (filter == null) {
      filter = "";
    }
    search = [
      {
        type: "complex",
        bool: "must",
        search: [
          {
            type: "in",
            bool: "should",
            fields: ["_owner.group._id"],
            "in": ez5.session.getGroupIds()
          }, {
            type: "in",
            bool: "should",
            fields: ["_has_acl"],
            "in": [true]
          }
        ]
      }, {
        type: "in",
        bool: "must_not",
        fields: ["_owner.user._id"],
        "in": [ez5.session.getUser().getId()]
      }, {
        type: "in",
        bool: "must_not",
        fields: ["collection.type"],
        "in": ["search"]
      }
    ];
    filterSearch = this.__getFilterSearch(filter);
    if (filterSearch) {
      search.push(filterSearch);
    }
    return search;
  };

  AddToCollectionHelper.__checkSharedCollectionsCount = function(filter) {
    var dfr;
    if (filter == null) {
      filter = "";
    }
    dfr = new CUI.Deferred();
    ez5.api.search({
      json_data: {
        type: "collection",
        limit: 0,
        search: this.__getSharedCollectionsSearch(filter)
      }
    }).done((function(_this) {
      return function(data) {
        return dfr.resolve(data.count);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  AddToCollectionHelper.__loadSharedCollections = function(manager, filter, offset) {
    var dfr;
    if (filter == null) {
      filter = "";
    }
    if (offset == null) {
      offset = 0;
    }
    dfr = new CUI.Deferred();
    ez5.api.search({
      json_data: {
        type: "collection",
        limit: CollectionManager.SHARED_COLLECTIONS_PAGE_SIZE,
        offset: offset,
        generate_rights: true,
        search: this.__getSharedCollectionsSearch(filter),
        sort: [
          {
            field: "_level"
          }, {
            field: "collection.displayname"
          }
        ]
      }
    }).done((function(_this) {
      return function(data) {
        var shared_collections;
        shared_collections = ez5.buildObjectTree({
          objects: data.objects,
          objectKey: "collection",
          filter: true,
          newInstanceFunc: function(collection) {
            return CollectionWorkfolder.newInstance({
              collection: collection,
              manager: manager,
              readonly: true
            });
          }
        });
        return dfr.resolve({
          count: data.count,
          collections: shared_collections
        });
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  AddToCollectionHelper.__askPinForCollection = function(collection, ev) {
    var askPin, collectionId, collectionName, dfr, pin, ref, ref1;
    dfr = new CUI.Deferred();
    collectionId = collection.getId();
    pin = ez5.session.user.getPinCode(collectionId);
    collectionName = (typeof collection.renderNameAsText === "function" ? collection.renderNameAsText() : void 0) || ez5.loca.getBestDatabaseValue(typeof collection.getData === "function" ? (ref = collection.getData()) != null ? (ref1 = ref.collection) != null ? ref1.displayname : void 0 : void 0 : void 0) || "";
    askPin = (function(_this) {
      return function() {
        return new CUI.prompt({
          markdown: true,
          text: $$("collection.workfolder.prompt.pin_code.md", {
            collection: collectionName
          }),
          "default": pin
        }).fail(dfr.reject).done(function(enteredPin) {
          ez5.session.user.setPinCode(collectionId, enteredPin);
          return ez5.session.user.saveLimited(ev, "settings").done(function(data) {
            return collection.refresh(true).fail(function(xhr) {
              var ref2;
              if ((xhr != null ? (ref2 = xhr.responseJSON) != null ? ref2.code : void 0 : void 0) === "RightRequired") {
                return new CUI.problem({
                  text: $$("collection.storable.error_date_expired")
                }).done(dfr.reject);
              } else {
                return new CUI.problem({
                  text: $$("collection.workfolder.prompt.wrong_pin")
                }).done(askPin);
              }
            }).done(function() {
              if (!(typeof collection.hasPin === "function" ? collection.hasPin() : void 0) || (typeof collection.pinOk === "function" ? collection.pinOk() : void 0)) {
                return dfr.resolve();
              } else {
                pin = enteredPin;
                return new CUI.problem({
                  text: $$("collection.workfolder.prompt.wrong_pin")
                }).done(askPin);
              }
            });
          }).fail(dfr.reject);
        });
      };
    })(this);
    askPin();
    return dfr.promise();
  };

  AddToCollectionHelper.__checkLinkRestrictions = function(linkRight, collectionObjects) {
    var allowed, co, denied, hasObjecttypeRestriction, hasPoolRestriction, i, j, len, len1, obj, objecttypeAllowed, objecttypeIds, objecttypeInfo, objecttypeName, pathPool, poolAllowed, poolId, poolIds, poolPath, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, tableId;
    allowed = [];
    denied = [];
    if (linkRight === true) {
      return {
        allowed: collectionObjects,
        denied: []
      };
    }
    objecttypeIds = (linkRight != null ? linkRight.objecttype_ids : void 0) || [];
    poolIds = (linkRight != null ? linkRight.pool_ids : void 0) || [];
    hasObjecttypeRestriction = objecttypeIds.length > 0;
    hasPoolRestriction = poolIds.length > 0;
    if (!hasObjecttypeRestriction && !hasPoolRestriction) {
      return {
        allowed: collectionObjects,
        denied: []
      };
    }
    for (i = 0, len = collectionObjects.length; i < len; i++) {
      co = collectionObjects[i];
      obj = (typeof co.getObject === "function" ? co.getObject() : void 0) || co;
      objecttypeName = obj._objecttype;
      objecttypeInfo = (ref = ez5.schema.CURRENT._objecttype_by_name) != null ? ref[objecttypeName] : void 0;
      tableId = objecttypeInfo != null ? objecttypeInfo.table_id : void 0;
      poolId = (ref1 = obj[objecttypeName]) != null ? (ref2 = ref1._pool) != null ? (ref3 = ref2.pool) != null ? ref3._id : void 0 : void 0 : void 0;
      objecttypeAllowed = true;
      if (hasObjecttypeRestriction) {
        objecttypeAllowed = tableId && indexOf.call(objecttypeIds, tableId) >= 0;
      }
      poolAllowed = true;
      if (hasPoolRestriction) {
        poolPath = ((ref4 = obj[objecttypeName]) != null ? (ref5 = ref4._pool) != null ? ref5._path : void 0 : void 0) || [];
        poolAllowed = false;
        for (j = 0, len1 = poolPath.length; j < len1; j++) {
          pathPool = poolPath[j];
          if (ref6 = (ref7 = pathPool.pool) != null ? ref7._id : void 0, indexOf.call(poolIds, ref6) >= 0) {
            poolAllowed = true;
            break;
          }
        }
        if (!poolAllowed && poolId && indexOf.call(poolIds, poolId) >= 0) {
          poolAllowed = true;
        }
      }
      if (objecttypeAllowed && poolAllowed) {
        allowed.push(co);
      } else {
        denied.push(co);
      }
    }
    return {
      allowed: allowed,
      denied: denied
    };
  };

  return AddToCollectionHelper;

})();
// Generated by CoffeeScript 1.12.7
var CollectionSelection,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  CollectionSelection.prototype.selectedClass = "cui-selected";

  CollectionSelection.lastMode = "detail";

  function CollectionSelection(opts1) {
    this.opts = opts1 != null ? opts1 : {};
    this.getNextPreviousGlobalObjectIds = bind(this.getNextPreviousGlobalObjectIds, this);
    CollectionSelection.__super__.constructor.call(this, this.opts);
    this.setSingleMode(false);
    this.__singleClickTimeout = null;
    this.__doubleClickProcessed = false;
    this.on({
      type: ["remove", "insert", "select"],
      call: (function(_this) {
        return function(ev, info) {
          var base, co, div, divs, functionToInvoke, i, j, len, len1, ref, ref1, ref2;
          if (!_this.selectableContainer) {
            if (((ref = info.collection_objects) != null ? ref.length : void 0) === 1) {
              _this.__loadSidebar(info.collection_objects[0]);
            }
            return;
          }
          if (!info.collection_objects) {
            info.collection_objects = _this.getObjects();
          }
          if (!info.skip_update) {
            if (typeof (base = _this.__select_opts).onUpdate === "function") {
              base.onUpdate(_this);
            }
          }
          ref1 = info.collection_objects;
          for (i = 0, len = ref1.length; i < len; i++) {
            co = ref1[i];
            divs = CUI.dom.matchSelector(_this.selectableContainer, co.getSelector());
            if (ev.getType() === "remove") {
              functionToInvoke = CUI.dom.removeClass;
            } else {
              functionToInvoke = CUI.dom.addClass;
            }
            for (j = 0, len1 = divs.length; j < len1; j++) {
              div = divs[j];
              functionToInvoke(div, _this.selectedClass);
              if (!_this._preventBlurOnSelect) {
                CUI.dom.blur(div);
              }
            }
            if (((ref2 = _this._sidebar) != null ? ref2.isShown() : void 0) && _this._sidebar.isEmpty()) {
              co = _this.getLatestObject();
              _this.__loadSidebar(co);
            }
          }
        };
      })(this)
    });
  }

  CollectionSelection.prototype.__getAssetBrowserFromElement = function(element) {
    return CUI.dom.data(CUI.dom.findElement(element, ".cui-asset-browser"), "element");
  };

  CollectionSelection.prototype.initOpts = function() {
    CollectionSelection.__super__.initOpts.call(this);
    return this.addOpts({
      parent_collection: {
        check: CollectionWithDetail
      },
      sidebar: {
        check: Sidebar
      },
      isObjectInsertable: {
        check: Function
      },
      preventBlurOnSelect: {
        check: Boolean,
        "default": false
      }
    });
  };

  CollectionSelection.prototype.getParentCollection = function() {
    return this._parent_collection;
  };

  CollectionSelection.prototype.copy = function() {
    var cs;
    cs = new window[this.getElementClass()](this.opts);
    cs.setSingleMode(this.isSingleMode());
    cs.insertObjects(this.getObjects());
    return cs;
  };

  CollectionSelection.prototype.destroy = function() {
    this.unsetSelectableContainer();
    this.off();
    return CollectionSelection.__super__.destroy.call(this);
  };

  CollectionSelection.prototype.getDescription = function() {
    return $$("collection.selection.description");
  };

  CollectionSelection.prototype.setData = function(data1) {
    this.data = data1;
    CollectionSelection.__super__.setData.call(this, this.data);
    this.data.collection.objects_allowed = true;
    return this;
  };

  CollectionSelection.prototype.showFullscreen = function(opts) {
    var assetBrowser, asset_browser_idx, count, div, globalObjectId;
    if (opts == null) {
      opts = {};
    }
    CollectionSelection.lastMode = "detail";
    count = this.getCount();
    if (count === 0) {
      return;
    }
    if (count === 1) {
      globalObjectId = opts.global_object_id || this.getObjects()[0].getGlobalObjectId();
      div = CUI.dom.matchSelector(this.selectableContainer, "[global-object-id=\"" + globalObjectId + "\"]")[0];
      assetBrowser = this.__getAssetBrowserFromElement(div);
      asset_browser_idx = assetBrowser != null ? assetBrowser.getCurrentIdx() : void 0;
      return new DetailFullscreen({
        search: this.getSearch(),
        offset: this.getOffsetInSearch(),
        global_object_id: globalObjectId,
        asset_browser_idx: asset_browser_idx,
        collection: this
      });
    } else {
      return CollectionSelection.__super__.showFullscreen.call(this, opts);
    }
  };

  CollectionSelection.prototype.hasSidebar = function() {
    return !!this._sidebar;
  };

  CollectionSelection.prototype.loadInSidebar = function(opts) {
    if (opts == null) {
      opts = {};
    }
    opts.search = this.getSearch();
    opts.next_previous_global_object_ids = this.getNextPreviousGlobalObjectIds();
    this._sidebar.showSidebar();
    this._sidebar.loadDetail(opts);
    return this;
  };

  CollectionSelection.prototype.getButtons = function(tools) {
    if (!tools) {
      tools = this.getCurrentTools(false);
    }
    return Toolbox.getFlyoutButtons(tools);
  };

  CollectionSelection.prototype.isTrashModeActive = function() {
    var i, len, ref, search, sm;
    search = this.getSearch();
    if (!search) {
      return false;
    }
    ref = search.getSearchManagers();
    for (i = 0, len = ref.length; i < len; i++) {
      sm = ref[i];
      if (sm instanceof TrashSearchManager && sm.isActive()) {
        return true;
      }
    }
    return false;
  };

  CollectionSelection.prototype.showCreateTaskTool = function() {
    if (this.isTrashModeActive() || this.getCount() === 0) {
      return false;
    }
    return CollectionSelection.__super__.showCreateTaskTool.call(this);
  };

  CollectionSelection.prototype.getCurrentTools = function(immediately_load_tools) {
    var addToCollectionTool, add_to_col_tools, can_write, check_copy, copy_tool, copy_tools, count, createNewChildTool, dbInfo, delete_tool, domEl, editor_bulk_tool, editor_bulk_tools, element, load_editor, load_in_sidebar, load_sidebar_new_child, manageTagsTools, manager, mask, menuItems, min, obj, objecttype, onAddToCollection, parentInfo, purge_tool, ref, ref1, ref2, ref3, ref4, ref5, remove_from_collection_tool, tools, topCollection, undelete_tool, write_tool;
    if (immediately_load_tools == null) {
      immediately_load_tools = true;
    }
    if (this.isTrashModeActive()) {
      return this.getTrashModeTools(immediately_load_tools);
    }
    tools = CollectionSelection.__super__.getCurrentTools.call(this);
    count = this.getCount();
    if (count === 0) {
      return tools;
    }
    obj = this.__currentSelectedObject || this.getObjects()[0];
    if (count === 1 && this.selectableContainer) {
      element = CUI.dom.matchSelector(this.selectableContainer, obj.getSelector())[0];
      if (element) {
        tools.push(new ToolboxTool({
          group: this.getToolGroup(),
          name: this.getToolNamePrefix() + ".show.popover",
          sort: "B:1",
          run: (function(_this) {
            return function() {
              return ResultObject.showCollectionObjectInPopover({
                collectionObject: obj,
                element: element
              });
            };
          })(this)
        }));
        remove_from_collection_tool = new ToolboxTool({
          group: this.getToolGroup(),
          name: this.getToolNamePrefix() + ".remove_from_collection",
          sort: "F:2",
          disabled: true,
          loading: true,
          tools: []
        });
      }
    }
    if (count <= 1 && this._sidebar) {
      tools.push(new ToolboxTool({
        group: this.getToolGroup(),
        disabled: count === 0,
        favorite: false,
        name: "object.show.sidebar",
        sort: "B:2",
        loca_key: "tool.object.show.sidebar",
        run: (function(_this) {
          return function() {
            return _this.loadInSidebar({
              global_object_id: obj.getGlobalObjectId()
            });
          };
        })(this)
      }));
      if (ez5.version("6")) {
        tools.push(new ToolboxTool({
          group: this.getToolGroup(),
          disabled: count === 0,
          favorite: false,
          name: "object.show.new_tab",
          sort: "B:3",
          loca_key: "tool.object.show.new_tab",
          run: (function(_this) {
            return function() {
              return window.open(window.easydb_base_prefix + "/#/detail/" + (obj.getGlobalObjectId()), "_blank");
            };
          })(this)
        }));
      }
    }
    if ((ref = this._parent_collection) != null ? ref.canUnlink() : void 0) {
      tools.push(new ToolboxTool({
        disabled: count === 0,
        group: this.getToolGroup(),
        name: this.getToolNamePrefix() + ".remove-from-collection",
        sort: "F:2",
        loca_key_attrs: {
          count: count
        },
        run: (function(_this) {
          return function() {
            var objects;
            objects = _this.getObjects().slice(0);
            _this.removeObjects();
            return _this._parent_collection.removeObjects(objects);
          };
        })(this)
      }));
    } else if (remove_from_collection_tool) {
      tools.push(remove_from_collection_tool);
    }
    if (manager = this.getManager()) {
      if (!ez5.version("6")) {
        if (manager.getAddToCollectionMenuItems) {
          add_to_col_tools = this.getManager().getAddToCollectionMenuItems({
            collection: this
          });
          if (add_to_col_tools.length > 0) {
            tools.push(new ToolboxTool({
              group: this.getToolGroup(),
              disabled: count === 0,
              name: this.getToolNamePrefix() + ".add_to_collection",
              sort: "F:1",
              tools: add_to_col_tools
            }));
          }
        }
      } else {
        onAddToCollection = (function(_this) {
          return function(targetCollection, filteredObjects) {
            var objectsToAdd;
            if (targetCollection) {
              objectsToAdd = filteredObjects || _this.getObjects();
              return targetCollection.insertObjects(objectsToAdd, null, false);
            }
          };
        })(this);
        addToCollectionTool = null;
        menuItems = AddToCollectionHelper.getAddToCollectionMenuItems({
          collection: this,
          manager: manager,
          onAddToCollection: onAddToCollection,
          onRecentCollectionsValidated: (function(_this) {
            return function(validRecent) {
              var newItems;
              newItems = AddToCollectionHelper.updateMenuItemsWithValidatedRecent(addToCollectionTool._tools, validRecent, _this, onAddToCollection);
              return addToCollectionTool._tools = newItems;
            };
          })(this)
        });
        if (menuItems.length > 0) {
          addToCollectionTool = new ToolboxTool({
            group: this.getToolGroup(),
            disabled: count === 0,
            name: this.getToolNamePrefix() + ".collection_picker",
            sort: "F:1",
            tools: menuItems
          });
          tools.push(addToCollectionTool);
        }
      }
      if (ez5.version("6") && count >= 2 && (topCollection = typeof manager.getTopCreateCollection === "function" ? manager.getTopCreateCollection() : void 0)) {
        tools.push(new ToolboxTool({
          group: this.getToolGroup(),
          name: this.getToolNamePrefix() + ".create_collection_detail",
          loca_key_attrs: {
            count: count
          },
          sort: "F:2",
          run: (function(_this) {
            return function() {
              var cls, data, dateTime, i, key, len, newCollection, ref1;
              ez5.splash.show("collection.manager.compare_collections_splash");
              cls = manager.getCollectionWorkfolderClass();
              newCollection = new cls({
                manager: manager
              });
              data = {
                displayname: {},
                webfrontend_props: {
                  default_view: 1
                }
              };
              dateTime = ez5.format_date_and_time(new Date(), true);
              ref1 = ez5.session.getConfigDatabaseLanguages();
              for (i = 0, len = ref1.length; i < len; i++) {
                key = ref1[i];
                data.displayname[key] = $$("collection.manager.compare_collections.name", {
                  date: dateTime
                });
              }
              newCollection.setData({
                collection: data
              });
              manager.addCollection(newCollection, topCollection).done(function(collectionCreated) {
                return collectionCreated.save().done(function() {
                  return collectionCreated.insertObjects(_this.getObjects()).done(function() {
                    return collectionCreated.select().done(function() {
                      return ez5.splash.hide();
                    });
                  });
                }).fail(function() {
                  collectionCreated.remove(false, false);
                  return ez5.splash.hide();
                });
              }).fail(function() {
                return ez5.splash.hide();
              });
            };
          })(this)
        }));
      }
    }
    if (!this.showEditTools()) {
      return tools;
    }
    if (count >= 1 && ((ref1 = obj.getObjecttype()) != null ? ref1.indexOf('@') : void 0) === -1) {
      load_in_sidebar = (function(_this) {
        return function(copy) {
          if (copy == null) {
            copy = false;
          }
          _this._sidebar.showSidebar();
          _this._sidebar.loadEditor({
            global_object_id: obj.getGlobalObjectId(),
            copy: copy,
            search: _this.getSearch(),
            next_previous_global_object_ids: _this.getNextPreviousGlobalObjectIds()
          });
        };
      })(this);
      load_sidebar_new_child = (function(_this) {
        return function() {
          var data, domEl, editor;
          data = obj.getObject();
          if (_this._sidebar) {
            _this._sidebar.showSidebar();
            _this._sidebar.loadEditor({
              parent_id: data[data._objecttype]._id,
              table_id: ez5.schema.CURRENT._table_by_name[data._objecttype].table_id,
              search: _this.getSearch(),
              next_previous_global_object_ids: _this.getNextPreviousGlobalObjectIds()
            });
          } else {
            domEl = CUI.dom.matchSelector(_this.selectableContainer, obj.getSelector())[0];
            editor = new EditorPopover({
              parent_id: data[data._objecttype]._id,
              mode: 'new',
              popover_element: domEl,
              table_id: ez5.schema.CURRENT._table_by_name[data._objecttype].table_id,
              search: _this.getSearch(),
              next_previous_global_object_ids: _this.getNextPreviousGlobalObjectIds(),
              onCancel: function() {
                return editor.destroy();
              },
              onSave: function() {
                return editor.destroy();
              },
              onSaveReadOnly: function() {
                return editor.destroy();
              },
              onDelete: function() {
                return editor.destroy();
              }
            });
            editor.open();
          }
        };
      })(this);
      load_editor = (function(_this) {
        return function(copy, popover_element) {
          var editor, func;
          if (copy == null) {
            copy = false;
          }
          CollectionSelection.lastMode = "editor";
          if (ez5.session.isReadOnly()) {
            CUI.alert({
              text: $$("base.error.user.read_only_mode")
            });
            return;
          }
          if (popover_element) {
            func = EditorPopover;
          } else {
            func = EditorModalSingle;
          }
          editor = new func({
            global_object_id: obj.getGlobalObjectId(),
            mode: copy ? "copy" : "single",
            popover_element: popover_element,
            next_previous_global_object_ids: _this.getNextPreviousGlobalObjectIds(),
            onCancel: function() {
              return editor.destroy();
            },
            onSave: function(received_data) {
              if (copy) {
                _this.getSearch().addCollectionAfterSave([received_data.object.data]);
              }
              return editor.destroy();
            },
            onSaveReadOnly: function() {
              return editor.destroy();
            },
            onDelete: function() {
              return editor.destroy();
            },
            onCopy: function() {
              editor.destroy();
              return load_editor(true);
            }
          });
          editor.open();
        };
      })(this);
      if (this.selectableContainer) {
        domEl = CUI.dom.matchSelector(this.selectableContainer, obj.getSelector())[0];
      }
      can_write = (ref2 = obj.getObject()._generated_rights) != null ? ref2.write : void 0;
      write_tool = new ToolboxTool({
        group: this.getToolGroup(),
        disabled: !can_write,
        loading: !can_write,
        name: "object.edit",
        onFlyoutMenuShow: (function(_this) {
          return function(ev, tools) {
            return _this.__loadTools(ev, tools);
          };
        })(this),
        sort: "E:1",
        loca_key: "tool.object.single-edit",
        tools: [
          this._sidebar && count >= 1 ? new ToolboxTool({
            group: "object",
            name: "object.edit.sidebar",
            run: (function(_this) {
              return function() {
                return load_in_sidebar();
              };
            })(this)
          }) : domEl ? new ToolboxTool({
            group: "object",
            name: "object.edit.popover",
            run: (function(_this) {
              return function() {
                return load_editor(false, domEl);
              };
            })(this)
          }) : void 0, new ToolboxTool({
            group: "object",
            name: "object.edit.fullscreen",
            run: (function(_this) {
              return function() {
                return load_editor();
              };
            })(this)
          })
        ]
      });
      tools.push(write_tool);
      dbInfo = (ref3 = this.getSearch()) != null ? (ref4 = ref3.getSearchBasics()) != null ? ref4.getDbInfo() : void 0 : void 0;
      if (count === 1 && (!dbInfo || Object.keys(dbInfo.getAvailableObjecttypes()).length > 0)) {
        copy_tools = [];
        if (this._sidebar) {
          copy_tools.push(new ToolboxTool({
            group: "object",
            name: "object.copy.sidebar",
            run: (function(_this) {
              return function() {
                return load_in_sidebar(true);
              };
            })(this)
          }));
        } else if (domEl) {
          copy_tools.push(new ToolboxTool({
            group: "object",
            name: "object.copy.popover",
            run: (function(_this) {
              return function() {
                return load_editor(true, domEl);
              };
            })(this)
          }));
        }
        copy_tools.push(new ToolboxTool({
          name: "object.copy.fullscreen",
          run: (function(_this) {
            return function() {
              return load_editor(true);
            };
          })(this)
        }));
        copy_tools.push(new ToolboxTool({
          group: "object",
          name: "object.copy.adhoc_template",
          run: (function(_this) {
            return function() {
              var ro;
              ro = new ResultObject();
              ro.setData(obj.getObject());
              return ro.loadFromDbWithFormat("full").done(function() {
                return ro.copyAsTemplate();
              });
            };
          })(this)
        }));
        copy_tool = new ToolboxTool({
          group: "object",
          disabled: true,
          loading: true,
          sort: "E:2",
          name: "object.copy",
          tools: copy_tools
        });
        tools.push(copy_tool);
        objecttype = ez5.schema.CURRENT._objecttype_by_name[obj.getObjecttype()];
        if (objecttype.is_hierarchical) {
          mask = objecttype._preferred_mask;
          parentInfo = mask != null ? (ref5 = mask.system_fields) != null ? ref5.parent : void 0 : void 0;
          if (parentInfo && !TreeColumn.isReadOnly(parentInfo)) {
            createNewChildTool = new ToolboxTool({
              group: this.getToolGroup(),
              name: this.getToolNamePrefix() + ".create_new_child",
              disabled: true,
              loading: true,
              sort: "E:3",
              run: (function(_this) {
                return function() {
                  return load_sidebar_new_child();
                };
              })(this)
            });
            tools.push(createNewChildTool);
          }
        }
        check_copy = (function(_this) {
          return function() {
            var ot_schema;
            ot_schema = ez5.schema.CURRENT._objecttype_by_name[obj.getObjecttype()];
            return DbInfo.canCreate({
              objecttypes: [new Objecttype(ot_schema)]
            }).always(function() {
              copy_tool.setLoading(false);
              return createNewChildTool != null ? createNewChildTool.setLoading(false) : void 0;
            }).done(function(data) {
              copy_tool.enable();
              return createNewChildTool != null ? createNewChildTool.enable() : void 0;
            });
          };
        })(this);
        if (!obj.getObjecttype()) {
          CollectionObject.reloadObjects([obj]).done((function(_this) {
            return function() {
              return check_copy();
            };
          })(this));
        } else {
          check_copy();
        }
      }
      manageTagsTools = new ToolboxTool({
        group: this.getToolGroup(),
        disabled: true,
        loading: true,
        sort: "E:3",
        name: (this.getToolNamePrefix()) + ".add_tags",
        loca_key_attrs: {
          count: count
        },
        run: (function(_this) {
          return function(ev) {
            return _this.__openTagsManagement();
          };
        })(this)
      });
      tools.push(manageTagsTools);
    }
    min = ez5.version("6") ? 1 : 2;
    if (count >= min && ez5.session.hasSystemRight("root", "frontend_features[editor_bulk]")) {
      editor_bulk_tools = [];
      editor_bulk_tool = new ToolboxTool({
        group: this.getToolGroup(),
        disabled: true,
        loading: true,
        name: "selection.bulk-edit",
        sort: "E:1",
        onFlyoutMenuShow: (function(_this) {
          return function(ev, tools) {
            return _this.__loadTools(ev, tools);
          };
        })(this),
        loca_key: "tool.selection.bulk-edit",
        tools: editor_bulk_tools
      });
      tools.push(editor_bulk_tool);
    }
    delete_tool = new ToolboxTool({
      group: this.getToolGroup(),
      disabled: true,
      loading: true,
      name: this.getToolNamePrefix() + ".delete_objects_from_server",
      sort: "E:4",
      loca_key_attrs: {
        count: count
      },
      run: (function(_this) {
        return function(ev) {
          return _this.deleteObjectsFromServer(ev);
        };
      })(this)
    });
    tools.push(delete_tool);
    if (TrashSearchManager.canUndelete()) {
      if (obj.getObject()._latest_version_deleted_at != null) {
        undelete_tool = new ToolboxTool({
          group: this.getToolGroup(),
          name: this.getToolNamePrefix() + ".undelete_objects_from_server",
          sort: "E:5",
          loca_key_attrs: {
            count: count
          },
          run: (function(_this) {
            return function(ev) {
              return _this.undeleteObjectsFromServer(ev);
            };
          })(this)
        });
        tools.push(undelete_tool);
      }
    }
    if (TrashSearchManager.canPurge()) {
      if (obj.getObject()._latest_version_deleted_at != null) {
        purge_tool = new ToolboxTool({
          group: this.getToolGroup(),
          name: this.getToolNamePrefix() + ".purge_objects_from_server",
          sort: "E:6",
          loca_key_attrs: {
            count: count
          },
          run: (function(_this) {
            return function(ev) {
              return _this.purgeObjectsFromServer(ev);
            };
          })(this)
        });
        tools.push(purge_tool);
      }
    }
    if (immediately_load_tools) {
      this.__loadTools(null, tools);
    }
    return tools;
  };

  CollectionSelection.prototype.getNextPreviousGlobalObjectIds = function() {
    var nextPreviousGlobalObjectIds, o, objects, ref, ref1;
    objects = this.getObjects();
    if (objects.length <= 1) {
      o = (ref = this.getSearch()) != null ? (ref1 = ref.getLastData()) != null ? ref1.objects.filter(function(o) {
        return o != null;
      }) : void 0 : void 0;
      nextPreviousGlobalObjectIds = o != null ? o.map((function(_this) {
        return function(object) {
          return object != null ? object._global_object_id : void 0;
        };
      })(this)) : void 0;
    } else {
      nextPreviousGlobalObjectIds = objects.map((function(_this) {
        return function(object) {
          return object.getGlobalObjectId();
        };
      })(this));
    }
    return nextPreviousGlobalObjectIds;
  };

  CollectionSelection.prototype.showEditTools = function() {
    return true;
  };

  CollectionSelection.prototype.allowSubcollectionSearch = function() {
    return false;
  };

  CollectionSelection.prototype.__loadTools = function(ev, tools) {
    var addTagsTool, delete_tool, editor_bulk_tool, editor_bulk_tools, i, len, objects, promise, ref, remove_from_collection_tool, tool, write_tool;
    if (!this.showEditTools()) {
      return CUI.resolvedPromise();
    }
    objects = this.getObjects();
    if (objects.some(function(object) {
      return object.isNotFound();
    })) {
      CUI.util.removeFromArray(null, tools, (function(_this) {
        return function(tool) {
          if (tool.getName() === ((_this.getToolNamePrefix()) + ".remove-from-collection")) {
            return false;
          }
          return true;
        };
      })(this));
      return CUI.resolvedPromise();
    }
    ref = tools || [];
    for (i = 0, len = ref.length; i < len; i++) {
      tool = ref[i];
      if (tool.getName() === "selection.bulk-edit") {
        editor_bulk_tool = tool;
        editor_bulk_tools = tool.getTools();
        continue;
      }
      if (tool.getName() === "object.edit") {
        write_tool = tool;
        continue;
      }
      if (tool.getName() === ((this.getToolNamePrefix()) + ".delete_objects_from_server")) {
        delete_tool = tool;
        continue;
      }
      if (tool.getName() === ((this.getToolNamePrefix()) + ".remove_from_collection")) {
        remove_from_collection_tool = tool;
        continue;
      }
      if (tool.getName() === ((this.getToolNamePrefix()) + ".add_tags")) {
        addTagsTool = tool;
        continue;
      }
    }
    promise = this.__loadGeneratedRights().done((function(_this) {
      return function() {
        var can_delete, co, collection, count, enableDeleteTool, existTags, fn, idx, j, l, len1, len2, len3, len4, list, m, min, obj, object, objectsWithTagEnabled, objecttype, ot, ots, p, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, removeTools, t, tagGroup;
        count = _this.getCount();
        ref1 = [write_tool, delete_tool, editor_bulk_tool, addTagsTool];
        for (j = 0, len1 = ref1.length; j < len1; j++) {
          t = ref1[j];
          if (t != null) {
            t.setLoading(false);
          }
        }
        enableDeleteTool = function() {
          if (count === 1 || ez5.session.hasSystemRight("root", "frontend_features[editor_bulk_delete]")) {
            return delete_tool != null ? delete_tool.enable() : void 0;
          }
        };
        if (count >= 1) {
          obj = _this.getObjects()[0];
          if ((ref2 = obj.getObject()._generated_rights) != null ? ref2.write : void 0) {
            if (write_tool != null) {
              write_tool.enable();
            }
          }
          if ((ref3 = obj.getObject()._generated_rights) != null ? ref3["delete"] : void 0) {
            if (!ez5.version("6") || (obj.getObject()._latest_version_deleted_at == null)) {
              enableDeleteTool();
            }
          }
        }
        ots = {};
        can_delete = true;
        objectsWithTagEnabled = 0;
        objects = _this.getObjects();
        for (idx = l = 0, len2 = objects.length; l < len2; idx = ++l) {
          co = objects[idx];
          ot = co.getObjecttype();
          if (!((ref4 = co.getObject()._generated_rights) != null ? ref4["delete"] : void 0)) {
            can_delete = false;
          }
          if (ez5.version("6") && (co.getObject()._latest_version_deleted_at != null)) {
            can_delete = false;
          }
          if (!((ref5 = co.getObject()._generated_rights) != null ? ref5.write : void 0)) {
            continue;
          }
          if (!ots[ot]) {
            ots[ot] = [];
          }
          ots[ot].push(co);
          if (can_delete) {
            enableDeleteTool();
          }
          if (ez5.schema.CURRENT._objecttype_by_name[ot].has_tags) {
            objectsWithTagEnabled++;
          }
        }
        existTags = false;
        ref6 = ez5.tagForm.tagGroups;
        for (m = 0, len3 = ref6.length; m < len3; m++) {
          tagGroup = ref6[m];
          if (tagGroup.children.length > 0) {
            existTags = true;
            break;
          }
        }
        if (objectsWithTagEnabled >= 1 && existTags) {
          addTagsTool.enable();
        }
        if (count === 1 && remove_from_collection_tool) {
          object = objects[0].getObject();
          removeTools = remove_from_collection_tool.getTools();
          if (((ref7 = object.__removeCollectionsTools) != null ? ref7.length : void 0) > 1) {
            ref8 = object.__removeCollectionsTools;
            for (p = 0, len4 = ref8.length; p < len4; p++) {
              tool = ref8[p];
              removeTools.push(tool);
            }
            remove_from_collection_tool.enable();
            remove_from_collection_tool.setLoading(false);
          } else if (((ref9 = object._collections) != null ? ref9.length : void 0) > 0) {
            ez5.api.search_no_limit({
              json_data: {
                type: "collection",
                generate_rights: true,
                limit: 1000000,
                search: [
                  {
                    type: "in",
                    bool: "must",
                    fields: ["collection._id"],
                    "in": (function() {
                      var len5, q, ref10, results;
                      ref10 = object._collections;
                      results = [];
                      for (q = 0, len5 = ref10.length; q < len5; q++) {
                        collection = ref10[q];
                        results.push(collection._id);
                      }
                      return results;
                    })()
                  }
                ]
              }
            }).done(function(data) {
              var collectionObject, collections, fn, len5, q;
              object.__removeCollectionsTools = removeTools;
              removeTools.push({
                label: $$("collection.selection.remove_from_collection.title")
              });
              collections = data.objects.map(function(col) {
                return new CollectionStorable({
                  collection: col
                });
              }).filter(function(col) {
                return col.canUnlink();
              }).sort(function(col1, col2) {
                return col1.renderNameAsText().localeCompare(col2.renderNameAsText());
              });
              fn = function(collectionObject) {
                return removeTools.push(new ToolboxTool({
                  group: _this.getToolGroup(),
                  text: collectionObject.renderNameAsText(),
                  name: "" + (collectionObject.getId()),
                  disabled: !collectionObject.canUnlink(),
                  run: function() {
                    return collectionObject.removeObjects(objects).done(function() {
                      CUI.util.removeFromArray(null, removeTools, function(tool) {
                        return (typeof tool.getName === "function" ? tool.getName() : void 0) === ("" + (collectionObject.getId()));
                      });
                      return CUI.util.removeFromArray(null, object._collections, function(col) {
                        return col._id === collectionObject.getId();
                      });
                    });
                  }
                }));
              };
              for (q = 0, len5 = collections.length; q < len5; q++) {
                collectionObject = collections[q];
                fn(collectionObject);
              }
              if (collections.length === 0) {
                remove_from_collection_tool.setHidden(true);
              } else {

              }
              return remove_from_collection_tool.enable();
            }).always(function() {
              return remove_from_collection_tool.setLoading(false);
            });
          } else {
            remove_from_collection_tool.setHidden(true);
            remove_from_collection_tool.setLoading(false);
          }
        }
        if (!editor_bulk_tool) {
          return;
        }
        editor_bulk_tools.length = 0;
        fn = function(objecttype, list) {
          var _ot_schema;
          _ot_schema = ez5.schema.CURRENT._objecttype_by_name[objecttype];
          count = ez5.format_number(list.length);
          return editor_bulk_tools.push(new ToolboxTool({
            group: _this.getToolGroup(),
            name: "selection.bulk-edit",
            loca_key: "tool.selection.bulk-edit.objecttype",
            loca_key_attrs: {
              count: count,
              objecttype: _ot_schema._name_localized
            },
            run: function() {
              var editor, len5, ol, q, ref10;
              ol = new ObjectList();
              editor = new EditorModalBulk({
                object_list: ol,
                mode: "bulk",
                table_id: _ot_schema.table_id,
                onCancel: function() {
                  editor.destroy();
                  return editor = null;
                },
                onSave: function() {
                  editor.destroy();
                  return editor = null;
                },
                onDelete: function() {
                  editor.destroy();
                  return editor = null;
                }
              });
              editor.addNewTemplateObject();
              ref10 = ots[objecttype];
              for (q = 0, len5 = ref10.length; q < len5; q++) {
                co = ref10[q];
                editor.addNewResultObject(CUI.util.copyObject(co.getObject(), true));
              }
              return editor.open();
            }
          }));
        };
        for (objecttype in ots) {
          list = ots[objecttype];
          min = ez5.version("6") ? 1 : 2;
          if (list.length < min) {
            continue;
          }
          fn(objecttype, list);
        }
        if (editor_bulk_tools.length > 0) {
          editor_bulk_tool.enable();
        }
      };
    })(this));
    return promise;
  };

  CollectionSelection.prototype.getTrashModeTools = function(immediately_load_tools) {
    var count, obj, purge_tool, tools, undelete_tool;
    if (immediately_load_tools == null) {
      immediately_load_tools = true;
    }
    tools = [];
    count = this.getCount();
    if (count === 0) {
      return tools;
    }
    if (count === 1) {
      obj = this.getObjects()[0];
      if (this._sidebar) {
        tools.push(new ToolboxTool({
          group: this.getToolGroup(),
          name: "object.show.sidebar",
          sort: "A:2",
          loca_key: "tool.object.show.sidebar",
          run: (function(_this) {
            return function() {
              return _this.loadInSidebar({
                global_object_id: obj.getGlobalObjectId()
              });
            };
          })(this)
        }));
      }
    }
    if (TrashSearchManager.canUndelete()) {
      undelete_tool = new ToolboxTool({
        group: this.getToolGroup(),
        name: this.getToolNamePrefix() + ".undelete_objects_from_server",
        sort: "T:1",
        loca_key_attrs: {
          count: count
        },
        run: (function(_this) {
          return function(ev) {
            return _this.undeleteObjectsFromServer(ev);
          };
        })(this)
      });
      tools.push(undelete_tool);
    }
    if (TrashSearchManager.canPurge()) {
      purge_tool = new ToolboxTool({
        group: this.getToolGroup(),
        name: this.getToolNamePrefix() + ".purge_objects_from_server",
        sort: "T:2",
        loca_key_attrs: {
          count: count
        },
        run: (function(_this) {
          return function(ev) {
            return _this.purgeObjectsFromServer(ev);
          };
        })(this)
      });
      tools.push(purge_tool);
    }
    if (immediately_load_tools) {
      this.__loadGeneratedRights().done((function(_this) {
        return function() {
          var i, len, results, tool;
          results = [];
          for (i = 0, len = tools.length; i < len; i++) {
            tool = tools[i];
            if (tool.getName().includes("undelete") || tool.getName().includes("purge")) {
              tool.setLoading(false);
              results.push(tool.enable());
            } else {
              results.push(void 0);
            }
          }
          return results;
        };
      })(this));
    }
    return tools;
  };

  CollectionSelection.prototype.getToolNamePrefix = function() {
    if (this.getCount() === 1) {
      return "object";
    } else {
      return "collection.selection";
    }
  };

  CollectionSelection.prototype.getSelectableContainer = function() {
    CUI.util.assert(this.selectableContainer, "CollectionSelection.getSelectableContainer", "no container set");
    return this.selectableContainer;
  };

  CollectionSelection.prototype.isSearchable = function() {
    return CollectionSelection.__super__.isSearchable.call(this) && this.getCount() > 1;
  };

  CollectionSelection.prototype.getSearchFilter = function() {
    var co;
    if (this.getCount() === 0) {
      return {
        bool: "must",
        type: "in",
        fields: ["_global_object_id"],
        "in": [null]
      };
    } else {
      return {
        bool: "must",
        type: "in",
        fields: ["_global_object_id"],
        "in": (function() {
          var i, len, ref, results;
          ref = this.data._objects;
          results = [];
          for (i = 0, len = ref.length; i < len; i++) {
            co = ref[i];
            results.push(co.getGlobalObjectId());
          }
          return results;
        }).call(this)
      };
    }
  };

  CollectionSelection.prototype.getReadOnly = function(co) {
    if (co.getObject()._generated_rights) {
      return !co.getObject()._generated_rights.write;
    } else {
      return null;
    }
  };

  CollectionSelection.prototype.__loadSidebar = function(co, opts) {
    if (!this._sidebar || !co) {
      return;
    }
    if (co.isNotFound()) {
      return;
    }
    return this._sidebar.loadCollectionObject({
      global_object_id: co.getGlobalObjectId(),
      read_only: this.getReadOnly(co),
      search: this.getSearch(),
      offset: co.getObject().__offset,
      asset_browser_idx: opts != null ? opts.asset_browser_idx : void 0,
      next_previous_global_object_ids: this.getNextPreviousGlobalObjectIds()
    });
  };

  CollectionSelection.prototype.getOffsetInSearch = function() {
    var offset, ref;
    offset = ((ref = this.getLatestObject()) != null ? ref.getObject().__offset : void 0) || 0;
    return offset;
  };

  CollectionSelection.prototype.getLatestObject = function() {
    return this.data._objects[this.data._objects.length - 1];
  };

  CollectionSelection.prototype.__selectObjectQueue = [];

  CollectionSelection.prototype.__selectNextObject = function() {
    var load_sidebar, selObj;
    selObj = this.__selectObjectQueue[0];
    if (!selObj.hasOwnProperty("load_sidebar")) {
      load_sidebar = true;
    } else {
      load_sidebar = selObj.load_sidebar;
    }
    return this.__selectObject(selObj.obj, selObj.append_mode, selObj.skip_update, load_sidebar).done((function(_this) {
      return function() {
        return selObj.dfr.resolve(selObj.obj);
      };
    })(this)).fail(selObj.dfr.reject).always((function(_this) {
      return function() {
        _this.__selectObjectQueue.splice(0, 1);
        if (_this.__selectObjectQueue.length > 0) {
          _this.__selectNextObject();
        }
      };
    })(this));
  };

  CollectionSelection.prototype.selectObjectByGlobalId = function(globalObjectId, load_sidebar) {
    if (load_sidebar == null) {
      load_sidebar = true;
    }
    return this.__selectObjectByAttribute("global-object-id", globalObjectId, load_sidebar);
  };

  CollectionSelection.prototype.selectAndScrollByGlobalId = function(globalObjectId, load_sidebar) {
    if (load_sidebar == null) {
      load_sidebar = true;
    }
    return this.selectObjectByGlobalId(globalObjectId, load_sidebar).done((function(_this) {
      return function() {
        var objectElement, ref, ref1;
        objectElement = (ref = CUI.dom) != null ? (ref1 = ref.matchSelector(_this.selectableContainer, "[global-object-id=\"" + globalObjectId + "\"]")) != null ? ref1[0] : void 0 : void 0;
        return objectElement.scrollIntoView();
      };
    })(this));
  };

  CollectionSelection.prototype.selectObjectByUUID = function(uuid, load_sidebar) {
    if (load_sidebar == null) {
      load_sidebar = true;
    }
    return this.__selectObjectByAttribute("uuid", uuid, load_sidebar);
  };

  CollectionSelection.prototype.__selectObjectByAttribute = function(attribute, id, load_sidebar) {
    var divs, object;
    if (load_sidebar == null) {
      load_sidebar = true;
    }
    if (!this.selectableContainer) {
      return CUI.rejectedPromise();
    }
    divs = CUI.dom.matchSelector(this.selectableContainer, "[" + attribute + "=\"" + id + "\"]");
    object = CUI.dom.data(divs != null ? divs[0] : void 0, "object");
    if (!object) {
      return CUI.rejectedPromise();
    }
    return this.selectObject(object, false, true, load_sidebar);
  };

  CollectionSelection.prototype.openModalEditor = function(object, copy) {
    var editor;
    if (copy == null) {
      copy = false;
    }
    CollectionSelection.lastMode = "editor";
    editor = new EditorModalSingle({
      global_object_id: object._global_object_id,
      mode: copy ? "copy" : "single",
      next_previous_global_object_ids: this.getNextPreviousGlobalObjectIds(),
      onCancel: (function(_this) {
        return function() {
          return editor.destroy();
        };
      })(this),
      onSave: (function(_this) {
        return function() {
          return editor.destroy();
        };
      })(this),
      onSaveReadOnly: (function(_this) {
        return function() {
          return editor.destroy();
        };
      })(this),
      onDelete: (function(_this) {
        return function() {
          return editor.destroy();
        };
      })(this),
      onCopy: (function(_this) {
        return function() {
          editor.destroy();
          return _this.openModalEditor(object, true);
        };
      })(this),
      collection_selection: this
    });
    return editor.open();
  };

  CollectionSelection.prototype.selectObject = function(obj, append_mode, skip_update, load_sidebar) {
    var dfr;
    if (append_mode == null) {
      append_mode = false;
    }
    if (skip_update == null) {
      skip_update = false;
    }
    if (load_sidebar == null) {
      load_sidebar = true;
    }
    dfr = new CUI.Deferred();
    this.__selectObjectQueue.push({
      obj: obj,
      append_mode: append_mode,
      skip_update: skip_update,
      load_sidebar: load_sidebar,
      dfr: dfr
    });
    if (this.__selectObjectQueue.length === 1) {
      this.__selectNextObject();
    }
    return dfr.promise();
  };

  CollectionSelection.prototype.__selectObject = function(obj, append_mode, skip_update, load_sidebar) {
    var assetBrowser, co, dfr, divs, is_selected, ref, remove_obj;
    if (append_mode == null) {
      append_mode = false;
    }
    if (skip_update == null) {
      skip_update = false;
    }
    if (load_sidebar == null) {
      load_sidebar = true;
    }
    if (this.__select_opts.isSelectable && !this.__select_opts.isSelectable(obj)) {
      return CUI.rejectedPromise();
    }
    if (!obj) {
      return CUI.rejectedPromise();
    }
    co = new CollectionObject(obj);
    is_selected = this.objectIdx(co) > -1;
    if (!append_mode || !is_selected) {
      divs = CUI.dom.matchSelector(this.selectableContainer, co.getSelector());
      if (divs.length === 1) {
        assetBrowser = this.__getAssetBrowserFromElement(divs[0]);
      }
      if (!append_mode && load_sidebar) {
        if (is_selected) {
          if (!ez5.version("6")) {
            if (this._sidebar && (!ez5.session.getPref("use_fullscreen") || this.isTrashModeActive())) {
              this._sidebar.showSidebar();
              if (this._sidebar.getLoadedGlobalObjectId() !== co.getGlobalObjectId()) {
                this.__loadSidebar(co);
              }
            }
          } else {
            if (((ref = this._sidebar) != null ? ref.isShown() : void 0) && this._sidebar.isEmpty()) {
              this.__loadSidebar(co);
            }
          }
          if (this.__select_opts.deselect && this.__select_opts.select_with_modifier === false) {
            return this.removeObjects([co]);
          } else {
            return CUI.resolvedPromise();
          }
        } else {
          this.__loadSidebar(co);
        }
      }
      dfr = new CUI.Deferred();
      if (append_mode) {
        remove_obj = [];
      } else {
        remove_obj = void 0;
      }
      this.removeObjects(remove_obj, {
        skip_update: true
      }).done((function(_this) {
        return function() {
          var div, i, len;
          divs = CUI.dom.matchSelector(_this.selectableContainer, co.getSelector());
          for (i = 0, len = divs.length; i < len; i++) {
            div = divs[i];
            CUI.dom.addClass(div, _this.selectedClass);
          }
          return _this.insertObjects([co], null, {
            skip_update: skip_update
          }).done(function() {
            return dfr.resolve();
          }).fail(function() {
            CUI.dom.removeClass(div, _this.selectedClass);
            return dfr.reject();
          });
        };
      })(this)).fail(dfr.reject);
      return dfr.promise();
    }
    if (is_selected && this.__select_opts.deselect) {
      return this.removeObjects([co]);
    }
    return CUI.resolvedPromise();
  };

  CollectionSelection.prototype.unsetSelectableContainer = function() {
    if (this.selectableContainer) {
      CUI.dom.removeClass(this.selectableContainer, "ez5-collection-selection-selectable-container");
      CUI.Lasso.destroy(this.selectableContainer);
      CUI.Draggable.destroy(this.selectableContainer);
      delete this.selectableContainer;
    }
    if (this.__select_opts) {
      CUI.Events.ignore({
        instance: this.__select_opts
      });
      return delete this.__select_opts;
    }
  };

  CollectionSelection.prototype.__registerFullScreenEvents = function() {
    return CUI.Events.listen({
      type: "fullscreen-object-changed",
      node: window,
      call: (function(_this) {
        return function(ev, info) {
          return _this.selectAndScrollByGlobalId(info.global_object_id);
        };
      })(this)
    });
  };

  CollectionSelection.prototype.setSelectableContainer = function(_opts) {
    var __handleClickEvent, currently_selecting, new_object_gids, objectSelector, removed_objects;
    if (_opts == null) {
      _opts = {};
    }
    this.unsetSelectableContainer();
    this.__select_opts = CUI.Element.readOpts(_opts, "CollectionSelection.setSelectableContainer", CollectionSelection.selectableOptsCheck(true));
    this.selectableContainer = this.__select_opts.container;
    objectSelector = this.__select_opts.object_selector;
    new_object_gids = [];
    if (ez5.version("6")) {
      CUI.Events.listen({
        type: "result-dynamic-loading-object-index",
        node: this.selectableContainer,
        instance: this.__select_opts,
        call: (function(_this) {
          return function(ev, info) {
            var co, i, j, len, len1, object, ref, ref1, ref2, results, update_cos;
            if (CUI.util.isEmpty(info.objects)) {
              if (!CUI.util.isEmpty(info.objects_ids)) {
                update_cos = [];
                ref = _this.getObjects();
                for (i = 0, len = ref.length; i < len; i++) {
                  co = ref[i];
                  if (ref1 = co.getGlobalObjectId(), indexOf.call(info.objects_ids, ref1) >= 0) {
                    update_cos.push(co);
                  }
                }
                if (update_cos.length === 0) {
                  return;
                }
                CollectionObject.reloadObjects(update_cos);
              }
            } else {
              ref2 = _this.getObjects();
              results = [];
              for (j = 0, len1 = ref2.length; j < len1; j++) {
                co = ref2[j];
                object = info.objects.find(function(obj) {
                  return obj._global_object_id === co.getGlobalObjectId();
                });
                if (object) {
                  results.push(co.setObject(object));
                } else {
                  results.push(void 0);
                }
              }
              return results;
            }
          };
        })(this)
      });
    }
    CUI.Events.listen({
      type: "event-poller",
      node: this.selectableContainer,
      instance: this.__select_opts,
      call: (function(_this) {
        return function(ev, info) {
          var co, i, len, ref, ref1, ref2, ref3, ref4, ref5, ref6, type, update_cos;
          if (info.batch_done) {
            update_cos = [];
            ref = _this.getObjects();
            for (i = 0, len = ref.length; i < len; i++) {
              co = ref[i];
              if (ref1 = co.getGlobalObjectId(), indexOf.call(new_object_gids, ref1) >= 0) {
                update_cos.push(co);
              }
            }
            if (update_cos.length === 0) {
              return;
            }
            CollectionObject.reloadObjects(update_cos);
            return;
          }
          if (((ref2 = info.event) != null ? ref2.schema : void 0) === "BASE") {
            return;
          }
          if (((ref3 = (type = (ref4 = info.event) != null ? ref4.type : void 0)) === "OBJECT_INDEX") && !ez5.version("6")) {
            new_object_gids.push(info.event.global_object_id);
          }
          if ((ref5 = (type = (ref6 = info.event) != null ? ref6.type : void 0)) === "OBJECT_DELETE") {
            return _this.removeObjects([
              new CollectionObject({
                _global_object_id: info.event.global_object_id
              })
            ], {
              skip_update: true
            });
          }
        };
      })(this)
    });
    currently_selecting = 0;
    if (this.__select_opts.draggable) {
      new CUI.Draggable({
        element: this.selectableContainer,
        selector: objectSelector,
        helper: (function(_this) {
          return function(info) {
            var collection_object, data, is_selected, loca_key;
            data = CUI.dom.data(info.$source, "object");
            info.originSearch = _this.getSearch();
            collection_object = new CollectionObject(data);
            is_selected = _this.objectIdx(collection_object) > -1;
            if (is_selected) {
              info.objects = _this.getObjectsSorted();
            } else {
              info.objects = [collection_object];
            }
            if (info.objects.length === 1) {
              loca_key = "collection.selection.draggable.helper.one";
            } else {
              loca_key = "collection.selection.draggable.helper";
            }
            return new LocaLabel({
              "class": "ez5-drag-objects-helper",
              loca_key: loca_key,
              loca_key_attrs: {
                count: info.objects.length
              }
            }).DOM;
          };
        })(this),
        create: (function(_this) {
          return function(ev, target) {
            var collection_object, data;
            if (currently_selecting) {
              return false;
            }
            data = CUI.dom.data(target, "object");
            if (!data) {
              return false;
            }
            if (_this.__select_opts.lasso || _this.__select_opts.select) {
              if (_this.getCount() === 0) {
                return false;
              }
              collection_object = new CollectionObject(data);
              if (_this.objectIdx(collection_object) === -1) {
                return false;
              }
            }
            return _this.__select_opts.onDraggableCreate(ev);
          };
        })(this)
      });
    }
    if (this.__select_opts.lasso) {
      removed_objects = null;
      new CUI.Lasso({
        element: this.selectableContainer,
        filter: objectSelector,
        lasso_filter: ".ez5-lassoable",
        create: (function(_this) {
          return function(ev) {
            if (ev.hasModifierKey() && CUI.dom.closest(ev.getTarget(), objectSelector)) {
              return false;
            }
          };
        })(this),
        dragstart: (function(_this) {
          return function(ev) {
            if (!ev.hasModifierKey() && !ev.cui_layer_closed) {
              removed_objects = _this.getObjects().slice(0);
              _this.removeObjects(null, {
                skip_update: true
              });
            } else {
              removed_objects = null;
            }
            return true;
          };
        })(this),
        dragstop: (function(_this) {
          return function(ev) {
            if (removed_objects) {
              return _this.insertObjects(removed_objects, null, {
                skip_update: true
              });
            }
          };
        })(this),
        selected: (function(_this) {
          return function(ev, info) {
            var co, dfr, el, i, insert_cos, len, ref, remove_cos;
            currently_selecting++;
            insert_cos = [];
            remove_cos = [];
            ref = info.elements;
            for (i = 0, len = ref.length; i < len; i++) {
              el = ref[i];
              co = new CollectionObject(CUI.dom.data(el, "object"));
              if (CUI.dom.hasClass(el, _this.selectedClass)) {
                insert_cos.push(co);
              } else {
                remove_cos.push(co);
              }
            }
            dfr = new CUI.Deferred();
            dfr.always(function() {
              return currently_selecting--;
            });
            _this.removeObjects(remove_cos, {
              skip_update: insert_cos.length > 0
            }).done(function() {
              return _this.insertObjects(insert_cos).done(dfr.resolve).fail(dfr.reject);
            }).fail(dfr.reject);
            return dfr.promise();
          };
        })(this)
      });
    }
    if (this.__select_opts.select) {
      CUI.dom.addClass(this.selectableContainer, "ez5-collection-selection-selectable-container");
      this.__registerFullScreenEvents();
      CUI.Events.listen({
        type: "focus-sidebar-selection",
        node: window,
        call: (function(_this) {
          return function(ev, info) {
            return _this.selectAndScrollByGlobalId(info.global_object_id, false);
          };
        })(this)
      });
      CUI.Events.listen({
        node: this.selectableContainer,
        type: ["mousedown"],
        call: (function(_this) {
          return function(ev, info) {
            if (!ev.cui_layer_closed) {
              return;
            }
            CUI.Events.listen({
              node: document.documentElement,
              type: ["click"],
              capture: true,
              only_once: true,
              call: function(ev) {
                if (CUI.dom.closest(ev.getTarget(), _this.selectableContainer)) {
                  ev.stopPropagation();
                }
              }
            });
          };
        })(this)
      });
      CUI.Events.listen({
        node: this.selectableContainer,
        type: ["dblclick", "click", "keydown"],
        instance: this.__select_opts,
        call: (function(_this) {
          return function(ev, info) {
            var ref;
            if (_this.__select_opts.dblclick === false && ev.getType() === "dblclick") {
              return;
            }
            if (ev.getType() === "keydown" && ((ref = ev.getKeyboardKey()) !== "Return" && ref !== "Space")) {
              return;
            }
            ev.stopPropagation();
            if (ev.shiftKey()) {
              document.getSelection().removeAllRanges();
            }
            if (ev.getType() === "dblclick") {
              if (_this.__singleClickTimeout) {
                CUI.clearTimeout(_this.__singleClickTimeout);
                _this.__singleClickTimeout = null;
              }
              _this.__doubleClickProcessed = true;
              CUI.setTimeout({
                ms: 300,
                call: function() {
                  return _this.__doubleClickProcessed = false;
                }
              });
              return __handleClickEvent(ev, true);
            } else if (ev.getType() === "click") {
              if (_this.__doubleClickProcessed) {
                return;
              }
              return _this.__singleClickTimeout = CUI.setTimeout({
                ms: 200,
                call: function() {
                  _this.__singleClickTimeout = null;
                  if (!_this.__doubleClickProcessed) {
                    return __handleClickEvent(ev, false);
                  }
                }
              });
            } else {
              return __handleClickEvent(ev, false);
            }
          };
        })(this)
      });
      __handleClickEvent = (function(_this) {
        return function(ev, isDoubleClick) {
          var append, co, domEl, obj, select_shift;
          if (!_this.__select_opts) {
            return;
          }
          domEl = CUI.dom.closest(ev.getTarget(), _this.__select_opts.object_selector);
          if (!domEl) {
            if (!ev.hasModifierKey() && _this.__select_opts.deselect) {
              _this.__lastDomEl = null;
              _this.removeObjects();
            }
          } else {
            obj = CUI.dom.data(domEl, "object");
            if (!obj) {
              return;
            }
            co = new CollectionObject(obj);
            append = ev.hasModifierKey();
            select_shift = function() {
              var dfr, done, i, j, k, l, len, len1, len2, pco, protect, protect_cos, ref, ref1, remove_cos, sel_cos, sibl, sibl_co, sibl_obj;
              if (!(!isDoubleClick && ev.getType() === "click" && !_this.isSingleMode() && _this.__select_opts.select_with_modifier)) {
                return CUI.resolvedPromise();
              }
              if (_this.__selectObjectQueue.length > 0) {
                return CUI.resolvedPromise();
              }
              if (!ev.shiftKey()) {
                _this.__lastDomEl = domEl;
                return CUI.resolvedPromise();
              }
              if (_this.objectIdx(co) > -1) {
                return CUI.resolvedPromise();
              }
              if (!_this.__lastDomEl) {
                _this.__lastDomEl = CUI.dom.firstElementChild(domEl.parentNode, _this.__select_opts.object_selector);
              }
              if (!CUI.dom.isInDOM(_this.__lastDomEl)) {
                _this.__lastDomEl = null;
              }
              done = false;
              ref = ["previous", "next"];
              for (i = 0, len = ref.length; i < len; i++) {
                k = ref[i];
                sel_cos = [];
                protect_cos = [];
                sibl = _this.__lastDomEl;
                while (true) {
                  if (!sibl) {
                    break;
                  }
                  if (sibl === domEl) {
                    done = true;
                    break;
                  }
                  sibl_obj = CUI.dom.data(sibl, "object");
                  if (sibl_obj) {
                    sibl_co = new CollectionObject(sibl_obj);
                    if (_this.objectIdx(sibl_co) === -1) {
                      sel_cos.push(sibl_co);
                    } else {
                      protect_cos.push(sibl_co);
                    }
                  }
                  sibl = sibl[k + "ElementSibling"];
                }
                if (done) {
                  break;
                }
              }
              if (!done) {
                return CUI.resolvedPromise();
              }
              dfr = new CUI.Deferred();
              if (!append) {
                append = true;
                remove_cos = [];
                ref1 = _this.getObjects();
                for (j = 0, len1 = ref1.length; j < len1; j++) {
                  co = ref1[j];
                  protect = false;
                  for (l = 0, len2 = protect_cos.length; l < len2; l++) {
                    pco = protect_cos[l];
                    if (pco.equals(co)) {
                      protect = true;
                      break;
                    }
                  }
                  if (!protect) {
                    remove_cos.push(co);
                  }
                }
                _this.removeObjects(remove_cos).fail(dfr.reject).done(function() {
                  return _this.insertObjects(sel_cos).done(dfr.resolve).fail(dfr.reject);
                });
              } else {
                _this.insertObjects(sel_cos).done(dfr.resolve).fail(dfr.reject);
              }
              return dfr.promise();
            };
            if (_this._sidebar) {
              if (isDoubleClick) {
                if (CollectionSelection.lastMode === "detail" && !ev.hasModifierKey()) {
                  if (ez5.session.getPref("use_fullscreen") && !_this.isTrashModeActive()) {
                    _this.selectObject(obj, false);
                    _this._sidebar.hideSidebarWithWarning().done(function() {
                      return _this.showFullscreen();
                    });
                    return;
                  } else {
                    _this._sidebar.showSidebar();
                  }
                } else {
                  if ((ev.hasModifierKey() || ez5.session.getPref("use_fullscreen")) && !_this.isTrashModeActive()) {
                    append = false;
                    _this._sidebar.hideSidebarWithWarning().done(function() {
                      var spinner;
                      spinner = CUI.spinner({
                        text: $$("editor.modal.single.loading|text")
                      });
                      spinner.open();
                      return _this.openModalEditor(obj).always(function() {
                        return spinner.destroy();
                      });
                    });
                    return;
                  } else {
                    _this._sidebar.showSidebar();
                  }
                }
              }
              _this._sidebar.allow_unload().done(function() {
                return select_shift().done(function() {
                  return _this.selectObject(obj, append);
                });
              });
            } else {
              select_shift().done(function() {
                return _this.selectObject(obj, append);
              });
            }
          }
        };
      })(this);
    }
    if (this.__select_opts.toolbox) {
      CUI.Events.listen({
        node: this.selectableContainer,
        type: "toolbox",
        instance: this.__select_opts,
        call: (function(_this) {
          return function(ev, info) {
            var colObj, domEl, is_selected, obj, promise;
            info.tools.splice(0);
            domEl = CUI.dom.closest(ev.getTarget(), _this.__select_opts.object_selector);
            if (!domEl) {
              return;
            }
            if (!(CUI.dom.closest(ev.getTarget(), ".ez5-lassoable") || CUI.dom.closest(ev.getTarget(), ".cui-selected"))) {
              return;
            }
            if (currently_selecting) {
              return CUI.rejectedPromise();
            }
            obj = CUI.dom.data(domEl, "object");
            colObj = new CollectionObject(obj);
            _this.__currentSelectedObject = colObj;
            is_selected = _this.objectIdx(colObj) > -1;
            if (!is_selected) {
              promise = _this.selectObject(obj, ev.hasModifierKey(), true);
            } else {
              promise = CUI.resolvedPromise();
            }
            promise.done(function() {
              var base;
              info.tools.push.apply(info.tools, _this.getCurrentTools());
              return typeof (base = _this.__select_opts).onToolbox === "function" ? base.onToolbox(ev, info.tools) : void 0;
            });
            ev.stopPropagation();
            return promise;
          };
        })(this)
      });
    }
    return this;
  };

  CollectionSelection.prototype.renderNameAsText = function() {
    return $$("collection.search.current_selection");
  };

  CollectionSelection.prototype.icon = function() {
    return "fa-crosshairs";
  };

  CollectionSelection.prototype.getHashId = function() {
    return "sel";
  };

  CollectionSelection.prototype.isMovable = function() {
    return false;
  };

  CollectionSelection.prototype.canAppend = function() {
    return true;
  };

  CollectionSelection.prototype.getCount = function() {
    return this.data._objects.length;
  };

  CollectionSelection.prototype.getObjects = function() {
    return this.data._objects;
  };

  CollectionSelection.prototype.getObjectsSorted = function() {
    var sorted;
    sorted = this.data._objects.slice(0);
    sorted.sort(function(a, b) {
      return CUI.util.compareIndex(a.getObject().__offset, b.getObject().__offset);
    });
    return sorted;
  };

  CollectionSelection.prototype.isSingleMode = function() {
    return this.single;
  };

  CollectionSelection.prototype.setSingleMode = function(single) {
    this.single = single;
    CUI.util.assert(CUI.util.isBoolean(this.single), "CollectionSelection.setSingleMode", "parameter needs to be Boolean", {
      single: this.single
    });
  };

  CollectionSelection.prototype.deleteObjectsFromServer = function(ev) {
    var dfr, req, search;
    search = new SearchCollectionHeadless({
      collection: this
    });
    req = new Request();
    req.aggregations = {
      _mask: {
        type: "term",
        limit: 100000,
        field: "_mask"
      }
    };
    req.format = "short";
    req.limit = 1000000;
    req.generate_rights = true;
    dfr = new CUI.Deferred();
    dfr.done((function(_this) {
      return function() {
        return _this.removeObjects();
      };
    })(this));
    dfr.always((function(_this) {
      return function() {
        return ez5.splash.hide();
      };
    })(this));
    ez5.splash.show("main.list.objecttypes.tool.prepare-delete");
    search.execute(req).done(function(req, data) {
      var allow_empty, ask, editor, i, j, len, len1, obj, ol, ref, ref1, term;
      ez5.splash.show("main.list.objecttypes.tool.delete");
      console.debug("search", req, search, data);
      ask = false;
      allow_empty = true;
      ref = data.aggregations._mask.terms;
      for (i = 0, len = ref.length; i < len; i++) {
        term = ref[i];
        switch (ez5.mask.CURRENT._mask_instance_by_name[term.term].requireComment()) {
          case "never":
            break;
          case "default-enabled":
          case "default-disabled":
            ask = true;
            break;
          case "always":
            ask = true;
            allow_empty = false;
        }
      }
      ol = new ObjectList();
      ref1 = data.objects;
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        obj = ref1[j];
        if (obj._generated_rights["delete"]) {
          ol.push(new ResultObject().setData(obj));
        }
      }
      if (ol.getCount() === 0) {
        return CUI.problem({
          text: $$("collection.selection.no_right_to_delete_objects")
        }).done(dfr.reject);
      } else {
        editor = new EditorHeadlessDelete({
          object_list: ol,
          require_comment: true
        });
        return editor.deleteObjects(ask, allow_empty).done(function() {
          return dfr.resolve(this);
        }).fail(dfr.reject);
      }
    }).fail((function(_this) {
      return function() {
        return ez5.splash.hide();
      };
    })(this));
    return dfr.promise();
  };

  CollectionSelection.prototype.undeleteObjectsFromServer = function(ev) {
    var co, dfr, editor, i, len, ol, ref;
    if (!ez5.version("6")) {
      return CUI.rejectedPromise();
    }
    ol = new ObjectList();
    ref = this.getObjects();
    for (i = 0, len = ref.length; i < len; i++) {
      co = ref[i];
      ol.push(new ResultObject().setData(co.getObject()));
    }
    dfr = new CUI.Deferred();
    dfr.done((function(_this) {
      return function() {
        return _this.removeObjects();
      };
    })(this));
    dfr.always((function(_this) {
      return function() {
        return ez5.splash.hide();
      };
    })(this));
    ez5.splash.show("main.list.objecttypes.tool.prepare-delete");
    editor = new EditorHeadlessDelete({
      object_list: ol,
      require_comment: false
    });
    editor.undeleteObjects().done(function() {
      return dfr.resolve(this);
    }).fail(dfr.reject);
    return dfr.promise();
  };

  CollectionSelection.prototype.purgeObjectsFromServer = function(ev) {
    var co, dfr, editor, i, len, ol, ref;
    if (!ez5.version("6")) {
      return CUI.rejectedPromise();
    }
    ol = new ObjectList();
    ref = this.getObjects();
    for (i = 0, len = ref.length; i < len; i++) {
      co = ref[i];
      ol.push(new ResultObject().setData(co.getObject()));
    }
    dfr = new CUI.Deferred();
    dfr.done((function(_this) {
      return function() {
        return _this.removeObjects();
      };
    })(this));
    dfr.always((function(_this) {
      return function() {
        return ez5.splash.hide();
      };
    })(this));
    ez5.splash.show("main.list.objecttypes.tool.prepare-purge");
    editor = new EditorHeadlessDelete({
      object_list: ol,
      require_comment: false
    });
    editor.purgeObjects().done(function() {
      return dfr.resolve(this);
    }).fail(dfr.reject);
    return dfr.promise();
  };

  CollectionSelection.prototype.insertObjects = function(__collection_objects, before_idx, event_info) {
    var _collection_objects_filtered, allowedObjectsCount, before_obj, co, collectionObject, collection_objects, dfr, i, j, l, len, len1, len2, objectsCount, promise, ref, ref1;
    if (before_idx == null) {
      before_idx = null;
    }
    if (event_info == null) {
      event_info = {};
    }
    objectsCount = ((ref = this.data._objects) != null ? ref.length : void 0) || 0;
    allowedObjectsCount = SearchUtil.MAX_OBJECTS_COUNT - objectsCount;
    if (allowedObjectsCount === 0) {
      return CUI.rejectedPromise();
    }
    this.checkObjects(__collection_objects);
    if (__collection_objects === this.data._objects) {
      __collection_objects = collection_objects.slice(0);
    }
    _collection_objects_filtered = [];
    for (i = 0, len = __collection_objects.length; i < len; i++) {
      co = __collection_objects[i];
      if (!_collection_objects_filtered.some(function(filteredObject) {
        return filteredObject !== co && filteredObject.getGlobalObjectId() === co.getGlobalObjectId();
      })) {
        _collection_objects_filtered.push(co);
      }
    }
    __collection_objects = _collection_objects_filtered;
    if (this._isObjectInsertable) {
      collection_objects = [];
      for (j = 0, len1 = __collection_objects.length; j < len1; j++) {
        co = __collection_objects[j];
        if (this._isObjectInsertable(co)) {
          collection_objects.push(co);
        }
      }
    } else {
      collection_objects = __collection_objects;
    }
    if (collection_objects.length === 0) {
      if (__collection_objects.length === 0) {
        return CUI.resolvedPromise(this);
      } else {
        return new CUI.Deferred().reject();
      }
    }
    before_obj = null;
    if (collection_objects.length > allowedObjectsCount) {
      ref1 = this.data._objects;
      for (l = 0, len2 = ref1.length; l < len2; l++) {
        collectionObject = ref1[l];
        CUI.util.removeFromArray(null, collection_objects, function(_collectionObject) {
          return collectionObject.getGlobalObjectId() === _collectionObject.getGlobalObjectId();
        });
      }
      collection_objects = collection_objects.slice(0, allowedObjectsCount);
      if (collection_objects.length === 0) {
        return CUI.rejectedPromise();
      }
    }
    if (this.isSingleMode()) {
      CUI.util.assert(collection_objects.length === 1, "Collection.insertObjects", "In single mode, only one object can be inserted into Collection", {
        collection_objects: collection_objects,
        before_idx: before_idx
      });
      CUI.util.assert(before_idx === null, "Collection.insertObjects", "In single mode, before_idx is not supported.", {
        collection_objects: collection_objects,
        before_idx: before_idx
      });
      promise = this.removeObjects();
    } else {
      if (before_idx !== null) {
        before_obj = this.getObjects()[before_idx];
        CUI.util.assert(before_obj, "Collection.insertObjects", "Collection object after index " + before_idx + " not found.", {
          collection_objects: collection_objects,
          before_idx: before_idx
        });
        console.debug("BEFORE IDX", before_idx, before_obj, collection_objects);
      }
      promise = this.removeObjects(collection_objects);
    }
    dfr = new CUI.Deferred();
    promise.done((function(_this) {
      return function() {
        var __before_idx, args;
        if (before_obj === null) {
          _this.data._objects.push.apply(_this.data._objects, collection_objects);
        } else {
          __before_idx = _this.objectIdx(before_obj);
          args = collection_objects.slice(0);
          args.splice(0, 0, 0);
          args.splice(0, 0, __before_idx);
          _this.data._objects.splice.apply(_this.data._objects, args);
        }
        event_info.collection_objects = collection_objects;
        event_info.before_idx = __before_idx;
        return promise = _this.triggerEvent("insert", event_info).fail(dfr.reject).done(function() {
          _this.updateDisplay();
          return dfr.resolve(_this);
        });
      };
    })(this));
    return dfr.promise();
  };

  CollectionSelection.prototype.__loadGeneratedRights = function() {
    var co, gid_map, gids, i, len, obj, ref, ref1;
    gid_map = {};
    gids = [];
    ref = this.getObjects();
    for (i = 0, len = ref.length; i < len; i++) {
      co = ref[i];
      obj = co.getObject();
      if (!obj._global_object_id) {
        continue;
      }
      if (!obj._generated_rights || !obj._objecttype) {
        gids.push(obj._global_object_id);
        gid_map[obj._global_object_id] = obj;
      }
    }
    if (gids.length === 0) {
      return CUI.resolvedPromise();
    }
    try {
      if ((ref1 = this.__loadingGenRights) != null) {
        ref1.abort();
      }
    } catch (error) {}
    this.__loadingGenRights = ez5.api.search({
      data: {
        debug: "CollectionSelection.__loadGeneratedRights"
      },
      json_data: {
        format: "short",
        limit: 1000,
        generate_rights: true,
        search: [
          {
            type: "in",
            fields: ["_global_object_id"],
            "in": gids
          }
        ]
      }
    }).done((function(_this) {
      return function(data) {
        var j, k, len1, obj_loaded, ref2, v;
        ref2 = data.objects;
        for (j = 0, len1 = ref2.length; j < len1; j++) {
          obj_loaded = ref2[j];
          obj = gid_map[obj_loaded._global_object_id];
          if (!obj._objecttype) {
            for (k in obj_loaded) {
              v = obj_loaded[k];
              obj[k] = v;
            }
          } else {
            obj._generated_rights = obj_loaded._generated_rights;
          }
        }
      };
    })(this));
    this.__loadingGenRights.always((function(_this) {
      return function() {
        return delete _this.__loadingGenRights;
      };
    })(this));
    return this.__loadingGenRights;
  };

  CollectionSelection.prototype.removeObjects = function(collection_objects, event_info) {
    var co, cos, i, idx, len, promise;
    if (collection_objects == null) {
      collection_objects = this.data._objects;
    }
    if (event_info == null) {
      event_info = {};
    }
    if (collection_objects.length === 0) {
      return CUI.resolvedPromise(this);
    }
    if (collection_objects === this.data._objects) {
      collection_objects = collection_objects.slice(0);
    }
    cos = [];
    for (i = 0, len = collection_objects.length; i < len; i++) {
      co = collection_objects[i];
      idx = this.objectIdx(co);
      if (idx === -1) {
        continue;
      }
      this.data._objects.splice(idx, 1);
      cos.push(co);
    }
    if (cos.length) {
      event_info.collection_objects = cos;
      promise = this.triggerEvent("remove", event_info);
    } else {
      promise = CUI.resolvedPromise(this);
    }
    return promise.done((function(_this) {
      return function() {
        return _this.updateDisplay();
      };
    })(this));
  };

  CollectionSelection.prototype.objectIdx = function(collection_object, strict) {
    var i, idx, len, obj, ref;
    if (strict == null) {
      strict = true;
    }
    CUI.util.assert(collection_object instanceof CollectionObject, "Collection.objectIdx", "collection_object needs to an instance of CollectionObject", {
      collection_object: collection_object
    });
    ref = this.getObjects();
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      obj = ref[idx];
      if (strict) {
        if (obj != null ? obj.equals(collection_object) : void 0) {
          return idx;
        }
      } else {
        if ((obj != null ? obj.getGlobalObjectId() : void 0) === collection_object.getGlobalObjectId()) {
          return idx;
        }
      }
    }
    return -1;
  };

  CollectionSelection.prototype.addToRequest = function(request) {
    var co, cos, gids, i, len, mask_filter, obj;
    if (!request.search) {
      request.search = [];
    }
    cos = this.getObjects();
    if (cos.length === 0) {
      return;
    }
    if (request.search.length === 0 && cos.length === 1) {
      obj = cos[0].getObject();
      if (obj._mask && !obj._best_mask) {
        request.best_mask_filter = false;
        mask_filter = {};
        mask_filter[obj._objecttype] = obj._mask;
        request.search.push(MaskFieldSelector.getSearchFilter(mask_filter));
      }
    }
    gids = [];
    for (i = 0, len = cos.length; i < len; i++) {
      co = cos[i];
      gids.push(co.getGlobalObjectId());
    }
    request.search.push({
      type: "in",
      fields: ["_global_object_id"],
      "in": gids
    });
  };

  CollectionSelection.prototype.executeSearch = function(req_data) {
    var co, data, dfr, i, obj, objs, offset, ref, ref1;
    CUI.util.assert(!req_data.aggregations, (CUI.util.getObjectClass(this)) + ".executeSearch", "request.aggregations not supported.", {
      request: req_data
    });
    CUI.util.assert(!req_data.format || req_data.format === "standard", (CUI.util.getObjectClass(this)) + ".executeSearch", "request.format not supported.", {
      request: req_data
    });
    dfr = new CUI.Deferred();
    objs = this.getObjects();
    data = {
      limit: req_data.limit,
      count: objs.length,
      objects: [],
      offset: req_data.offset
    };
    for (offset = i = ref = req_data.offset, ref1 = req_data.offset + req_data.limit; ref <= ref1 ? i < ref1 : i > ref1; offset = ref <= ref1 ? ++i : --i) {
      if (!(co = objs[offset])) {
        break;
      }
      obj = {
        _global_object_id: co.getGlobalObjectId()
      };
      data.objects.push(obj);
    }
    dfr.resolve(data);
    return dfr.promise();
  };

  CollectionSelection.prototype.getBadge = function() {
    return {
      icon: this.getBadgeIcon(),
      name: $$("collection.selection.badge.name"),
      value: $$("collection.selection.badge.value", {
        count: this.getCount()
      })
    };
  };

  CollectionSelection.prototype.areAllObjectsSelectedInContainer = function() {
    var countInContainer, selected;
    if (!this.selectableContainer) {
      return false;
    }
    selected = CUI.dom.matchSelector(this.selectableContainer, "." + this.selectedClass).length;
    countInContainer = CUI.dom.matchSelector(this.selectableContainer, "[global-object-id]").length;
    return selected === countInContainer;
  };

  CollectionSelection.prototype.__openTagsManagement = function() {
    var addTagsButton, apiDataPerObjectType, checkIndeterminate, countOfObjectsWithEditableTags, createTagForm, data, dbInfo, dbInfoPromise, dbInfoPromises, fields, fn, form, getCustomTagGroups, getRequestItems, getTagsToModify, i, initialTagsToModify, len, makeRequest, maxObjectsCountByTag, modal, obj, objCollection, objectType, objectsCountByTag, objectsIds, ot, ref, saveTags, table, tagsToModify, validObjectsIds, validTagsPerObject, waitBlock;
    form = null;
    data = {};
    fields = [];
    objectsCountByTag = {};
    maxObjectsCountByTag = {};
    validObjectsIds = {};
    apiDataPerObjectType = {};
    countOfObjectsWithEditableTags = 0;
    validTagsPerObject = {};
    initialTagsToModify = {};
    tagsToModify = {};
    checkIndeterminate = function(tagId) {
      var n;
      n = objectsCountByTag[tagId] || 0;
      return n > 0 && n < maxObjectsCountByTag[tagId];
    };
    getCustomTagGroups = function() {};
    createTagForm = (function(_this) {
      return function() {
        var fieldOptions, i, infoWrapper, j, len, len1, options, ref, ref1, tag, tagGroup, tagGroupPropertyName, verticalLayout, warningLabel;
        ref = ez5.tagForm.tagGroups;
        for (i = 0, len = ref.length; i < len; i++) {
          tagGroup = ref[i];
          options = [];
          tagGroupPropertyName = "tagGroup_" + (tagGroup.getId()) + "_" + (tagGroup.getType());
          data[tagGroupPropertyName] = [];
          fieldOptions = new CUI.Options({
            name: tagGroupPropertyName,
            horizontal: false,
            radio: tagGroup.isChoice(),
            min_checked: 0,
            title: tagGroup.getDisplayName(),
            options: options
          });
          ref1 = tagGroup.children;
          for (j = 0, len1 = ref1.length; j < len1; j++) {
            tag = ref1[j];
            if (!tag.isVisible("editor") || !maxObjectsCountByTag[tag.getId()]) {
              continue;
            }
            options.push({
              content: tag.getLabel(true, true),
              value: tag.getId(),
              indeterminate: checkIndeterminate(tag.getId())
            });
            if (objectsCountByTag[tag.getId()] && objectsCountByTag[tag.getId()] === maxObjectsCountByTag[tag.getId()]) {
              data[tagGroupPropertyName].push(tag.getId());
            }
          }
          if (options.length > 0) {
            fields.push(fieldOptions);
          }
        }
        form = new CUI.Form({
          data: data,
          "class": "ez5-modify-tags-form",
          padded: true,
          onDataChanged: function() {
            var actualData;
            actualData = getTagsToModify();
            if (CUI.util.isEqual(actualData, initialTagsToModify)) {
              return addTagsButton.disable();
            } else {
              return addTagsButton.enable();
            }
          },
          fields: fields
        });
        form.start();
        initialTagsToModify = getTagsToModify();
        warningLabel = new LocaLabel({
          "class": "ez5-editor-required-message",
          loca_key: "tool.object.add_tags.warning"
        });
        infoWrapper = CUI.dom.div("ez5-required-message");
        CUI.dom.append(infoWrapper, [warningLabel]);
        verticalLayout = new CUI.VerticalLayout({
          center: {
            content: form
          },
          bottom: {
            content: infoWrapper
          }
        });
        if (_this.getObjects().length > countOfObjectsWithEditableTags) {
          modal.setContent(verticalLayout);
        } else {
          modal.setContent(form);
        }
      };
    })(this);
    ref = this.getObjects();
    for (i = 0, len = ref.length; i < len; i++) {
      objCollection = ref[i];
      obj = objCollection.getObject();
      objectType = objCollection.getObjecttype();
      if (!ez5.schema.CURRENT._objecttype_by_name[objectType].has_tags && !obj._tags) {
        continue;
      }
      validObjectsIds[objectType] = validObjectsIds[objectType] || [];
      validObjectsIds[objectType].push(obj[objectType]._id);
    }
    dbInfoPromises = [];
    fn = (function(_this) {
      return function(dbInfoPromise, objectType, table) {
        return dbInfoPromise.done(function(dbInfoResponse) {
          var j, len1, mask, maskObj, objTypeCanBeEdited, ref1, ref2, ref3, tagsField;
          objTypeCanBeEdited = false;
          validTagsPerObject[objectType] = dbInfoResponse._available_tags;
          if (((ref1 = dbInfoResponse._available_tags) != null ? ref1.length : void 0) > 0) {
            ref2 = dbInfoResponse._available_masks || [];
            for (j = 0, len1 = ref2.length; j < len1; j++) {
              mask = ref2[j];
              if (mask.name === "_all_fields") {
                objTypeCanBeEdited = true;
                maskObj = Mask.getMaskByMaskName(mask.name, table._id);
                break;
              }
              maskObj = Mask.getMaskByMaskName(mask.name);
              tagsField = maskObj.getTagsField("editor-header");
              if (tagsField && !tagsField.isReadOnly()) {
                objTypeCanBeEdited = true;
                break;
              }
            }
          }
          if (!objTypeCanBeEdited || ((ref3 = dbInfoResponse._available_tags) != null ? ref3.length : void 0) < 1) {
            return delete validObjectsIds[objectType];
          } else {
            return apiDataPerObjectType[objectType] = {
              mask: maskObj.name(),
              table: table.name()
            };
          }
        });
      };
    })(this);
    for (objectType in validObjectsIds) {
      objectsIds = validObjectsIds[objectType];
      ot = ez5.schema.CURRENT._objecttype_by_name[objectType];
      table = new Table("CURRENT", ot);
      dbInfo = new DbInfo();
      dbInfoPromise = dbInfo.load({
        object_ids: objectsIds,
        table: table
      });
      dbInfoPromises.push(dbInfoPromise);
      fn(dbInfoPromise, objectType, table);
    }
    CUI.whenAll(dbInfoPromises).done((function(_this) {
      return function() {
        var j, l, len1, len2, len3, m, objectIds, ref1, ref2, ref3, tag;
        for (objectType in validObjectsIds) {
          objectIds = validObjectsIds[objectType];
          ref1 = validTagsPerObject[objectType];
          for (j = 0, len1 = ref1.length; j < len1; j++) {
            tag = ref1[j];
            maxObjectsCountByTag[tag._id] = maxObjectsCountByTag[tag._id] || 0;
            maxObjectsCountByTag[tag._id] += objectIds.length;
          }
          countOfObjectsWithEditableTags += objectIds.length;
        }
        ref2 = _this.getObjects();
        for (l = 0, len2 = ref2.length; l < len2; l++) {
          objCollection = ref2[l];
          obj = objCollection.getObject();
          objectType = objCollection.getObjecttype();
          if (validObjectsIds[objectType] && obj._tags) {
            ref3 = obj._tags;
            for (m = 0, len3 = ref3.length; m < len3; m++) {
              tag = ref3[m];
              objectsCountByTag[tag._id] = objectsCountByTag[tag._id] || 0;
              objectsCountByTag[tag._id]++;
            }
          }
        }
        if (countOfObjectsWithEditableTags < 1) {
          modal.destroy();
          CUI.alert({
            title: $$("tool.object.add_tags.no_rigths|text"),
            text: $$("tool.object.add_tags.no_rigths_text|text")
          });
          return;
        }
        createTagForm();
        return waitBlock.hide();
      };
    })(this));
    getRequestItems = (function(_this) {
      return function(tags, tagsMode, objectType) {
        var j, len1, requestItems, tag;
        requestItems = [];
        data = {};
        data[objectType] = {
          _id: validObjectsIds[objectType]
        };
        data._mask = apiDataPerObjectType[objectType].mask;
        data._objecttype = objectType;
        data._tags = [];
        for (j = 0, len1 = tags.length; j < len1; j++) {
          tag = tags[j];
          if (validTagsPerObject[objectType].some(function(validTag) {
            return validTag._id === tag;
          })) {
            data._tags.push({
              _id: tag
            });
          }
        }
        data["_tags:group_mode"] = tagsMode;
        data._comment = $$("tool.object.add_tags.comment");
        requestItems.push(data);
        return requestItems;
      };
    })(this);
    getTagsToModify = (function(_this) {
      return function() {
        var field, j, l, len1, len2, option, ref1, ref2, tagGroup, tagGroupArray, tagInData, tags;
        tags = {
          addTags: [],
          removeTags: [],
          indeterminateTags: []
        };
        ref1 = form.getFields();
        for (j = 0, len1 = ref1.length; j < len1; j++) {
          field = ref1[j];
          ref2 = field.getOptions();
          for (l = 0, len2 = ref2.length; l < len2; l++) {
            option = ref2[l];
            if (option.indeterminate) {
              tags.indeterminateTags.push(option.value);
            } else {
              tagInData = false;
              for (tagGroup in data) {
                tagGroupArray = data[tagGroup];
                if (tagGroupArray.includes(option.value)) {
                  tagInData = true;
                  break;
                }
              }
              if (tagInData) {
                tags.addTags.push(option.value);
              } else {
                tags.removeTags.push(option.value);
              }
            }
          }
        }
        return tags;
      };
    })(this);
    makeRequest = (function(_this) {
      return function(objectType, tagsMode, tagsIds) {
        var request, requestItems;
        requestItems = getRequestItems(tagsIds, tagsMode, objectType);
        request = ez5.api.db({
          api: "/" + apiDataPerObjectType[objectType].table + "?priority=1&format=short&base_fields_only=1&skip_bidirectional_update=true",
          json_data: requestItems
        });
        return request;
      };
    })(this);
    saveTags = (function(_this) {
      return function() {
        var actualTagsToModify, addRequests, closeModal, j, l, len1, len2, makeAddRequest, makeRemoveRequest, mode, ref1, ref2, removeRequests, tag;
        closeModal = function() {
          return modal.destroy();
        };
        makeRemoveRequest = function() {
          var results;
          results = [];
          for (objectType in validObjectsIds) {
            objectsIds = validObjectsIds[objectType];
            results.push(removeRequests.push(makeRequest(objectType, "tag_remove", tagsToModify.removeTags)));
          }
          return results;
        };
        makeAddRequest = function() {
          for (objectType in validObjectsIds) {
            objectsIds = validObjectsIds[objectType];
            addRequests.push(makeRequest(objectType, "tag_add", tagsToModify.addTags));
          }
          return CUI.whenAllReject(addRequests).done(function() {
            return closeModal();
          }).fail(function(rejectedPromise) {
            var msg, ref1, rejectedByTransition, request;
            rejectedByTransition = false;
            if (rejectedPromise != null ? rejectedPromise.args : void 0) {
              request = rejectedPromise.args.find(function(arg) {
                return arg instanceof XMLHttpRequest;
              });
              if ((request.responseJSON != null) && request.responseJSON.code === "TransitionReject") {
                rejectedByTransition = true;
                if (!CUI.util.isEmpty(((ref1 = request.responseJSON.parameters) != null ? ref1.messages : void 0) != null)) {
                  closeModal();
                  _this.__openTagsManagement();
                  return;
                }
              }
            }
            msg = rejectedByTransition ? $$("tool.object.add_tags.fail.transition") : $$("tool.object.add_tags.fail");
            closeModal();
            return CUI.alert({
              text: msg
            }).done(function() {
              return _this.__openTagsManagement();
            });
          });
        };
        actualTagsToModify = getTagsToModify();
        tagsToModify = {
          addTags: [],
          removeTags: []
        };
        ref1 = ['addTags', 'removeTags'];
        for (j = 0, len1 = ref1.length; j < len1; j++) {
          mode = ref1[j];
          ref2 = actualTagsToModify[mode];
          for (l = 0, len2 = ref2.length; l < len2; l++) {
            tag = ref2[l];
            if (!initialTagsToModify[mode].includes(tag)) {
              tagsToModify[mode].push(tag);
            }
          }
        }
        removeRequests = [];
        addRequests = [];
        if (tagsToModify.removeTags.length > 0) {
          makeRemoveRequest();
        }
        CUI.whenAllReject(removeRequests).done(function() {
          if (tagsToModify.addTags.length > 0) {
            return makeAddRequest();
          } else {
            return closeModal();
          }
        }).fail(function() {
          closeModal();
          return CUI.alert({
            text: $$("tool.object.add_tags.fail")
          });
        });
      };
    })(this);
    addTagsButton = new CUI.Button({
      text: $$("base.save"),
      primary: true,
      disabled: true,
      left: true,
      onClick: function(df) {
        waitBlock.show();
        addTagsButton.startSpinner();
        addTagsButton.disable();
        saveTags();
      }
    });
    modal = new CUI.Modal({
      cancel: true,
      "class": "ez5-modify-tags-modal",
      pane: {
        header_left: new LocaLabel({
          loca_key: "tool.object.add_tags.title"
        }),
        content: new CUI.dom.div(),
        footer_right: [
          {
            text: $$("base.cancel"),
            onClick: function() {
              return modal.destroy();
            }
          }, addTagsButton
        ]
      }
    });
    waitBlock = new CUI.WaitBlock({
      element: modal.getPane()
    });
    modal.show();
    waitBlock.show();
  };

  CollectionSelection.selectableOptsCheck = function(for_collection_selection) {
    var check;
    if (for_collection_selection == null) {
      for_collection_selection = false;
    }
    check = {
      onUpdate: {
        check: Function
      },
      onDraggableCreate: {
        check: Function,
        mandatory: true,
        "default": (function(_this) {
          return function(ev) {
            return !ev.hasModifierKey();
          };
        })(this)
      },
      draggable: {
        "default": true,
        check: Boolean
      },
      lasso: {
        "default": true,
        check: Boolean
      },
      toolbox: {
        "default": true,
        mandatory: true,
        check: Boolean
      },
      select: {
        "default": true,
        check: Boolean
      },
      select_with_modifier: {
        "default": true,
        check: Boolean
      },
      dblclick: {
        "default": true,
        check: Boolean
      },
      deselect: {
        "default": true,
        check: Boolean
      },
      fullscreen: {
        "default": true,
        check: Boolean
      },
      isSelectable: {
        check: Function
      },
      onToolbox: {
        check: Function
      },
      onInit: {
        check: Function
      }
    };
    if (for_collection_selection) {
      check.container = {
        check: function(v) {
          return CUI.util.isElement(v);
        }
      };
      check.object_selector = {
        mandatory: true,
        check: String
      };
    } else {
      check.collection = {
        mandatory: true,
        check: Collection
      };
    }
    return check;
  };

  return CollectionSelection;

})(CollectionWithDetail);
// Generated by CoffeeScript 1.12.7
var CollectionMemory,
  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;

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

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

  CollectionMemory.prototype.updateDisplay = function() {};

  CollectionMemory.prototype.getBadgeText = function() {
    var c, dfr, obj;
    dfr = new CUI.Deferred();
    c = this.getCount();
    if (c === 0) {
      dfr.resolve("");
    } else {
      obj = this.getObjects()[0].getObject();
      ResultObject.loadFromData(obj, "standard", false, true).done(function(ro) {
        if (c === 1) {
          return dfr.resolve(ro.renderText());
        } else {
          return dfr.resolve(c + " " + ro.objecttypeLocalized());
        }
      }).fail((function(_this) {
        return function(userError) {
          return dfr.resolve('#' + obj._global_object_id.split('@')[0]);
        };
      })(this));
    }
    return dfr.promise();
  };

  CollectionMemory.prototype.initOpts = function() {
    CollectionMemory.__super__.initOpts.call(this);
    return this.addOpts({
      hasEASFields: {
        check: Boolean,
        mandatory: true,
        "default": true
      }
    });
  };

  CollectionMemory.prototype.removeObjects = function(collection_objects, event_info) {
    if (collection_objects == null) {
      collection_objects = this.data._objects;
    }
    if (event_info == null) {
      event_info = {};
    }
    this._subsearch = null;
    return CollectionMemory.__super__.removeObjects.call(this, collection_objects, event_info);
  };

  CollectionMemory.prototype.hasEASFields = function() {
    return this._hasEASFields;
  };

  CollectionMemory.prototype.isDownloadable = function() {
    return this.hasEASFields();
  };

  CollectionMemory.prototype.isFullscreenable = function() {
    return this.hasEASFields();
  };

  CollectionMemory.prototype.addSubsearchData = function(subsearch) {
    return this._subsearch = CUI.util.copyObjectV2(subsearch, true);
  };

  CollectionMemory.prototype.getSubsearchData = function() {
    return this._subsearch;
  };

  CollectionMemory.prototype.hasSubsearchData = function() {
    return !CUI.util.isEmpty(this._subsearch);
  };

  CollectionMemory.prototype.copy = function() {
    var c;
    c = CollectionMemory.__super__.copy.call(this);
    c.addSubsearchData(this.getSubsearchData());
    return c;
  };

  return CollectionMemory;

})(CollectionSelection);
// Generated by CoffeeScript 1.12.7
var CollectionTemporary,
  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;

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

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

  CollectionTemporary.prototype.showEditTools = function() {
    return false;
  };

  return CollectionTemporary;

})(CollectionMemory);
// Generated by CoffeeScript 1.12.7
var Field,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function Field(mask1, FieldSchema) {
    var ref;
    this.mask = mask1;
    this.FieldSchema = FieldSchema;
    CUI.util.assert(CUI.util.getObjectClass(this) !== "Field", "Field.constructor", "Field cannot be instantiated directly. You need to use a derived class to instantiate.", {
      mask: this.mask,
      FieldSchema: this.FieldSchema
    });
    CUI.util.assert(this.mask instanceof Mask, "new " + (CUI.util.getObjectClass(this)), "mask must be instance of Mask", {
      mask: this.mask,
      FieldSchema: this.FieldSchema
    });
    this.version = this.mask.version;
    this.table = this.mask.table;
    this.__cls = "ez5-" + CUI.util.toDash(CUI.util.getObjectClass(this));
    if (this.FieldSchema && ((ref = this.FieldSchema.kind) !== "splitter")) {
      this.ColumnSchema = this.table.schema._column_by_id[this.FieldSchema.column_id];
      CUI.util.assert(this.ColumnSchema, "new " + (CUI.util.getObjectClass(this)), "Column schema not found", {
        mask: this.mask,
        field_schema: this.FieldSchema
      });
      this.__dbg_full_name = this.fullName();
    }
  }

  Field.prototype.init = function() {};

  Field.prototype.depth = function() {
    return this.mask.depth;
  };

  Field.prototype.name = function() {
    if (!this.ColumnSchema) {
      throw (CUI.util.getObjectClass(this)) + ".name(): no ColumnSchema set.";
    }
    return this.ColumnSchema.name;
  };

  Field.prototype.getReplacementRecord = function(data, key_prepend, use_array, record) {
    var _data, add_data, k, key, v;
    if (key_prepend == null) {
      key_prepend = "";
    }
    if (use_array == null) {
      use_array = false;
    }
    _data = this.getDataForReplacementRecord(data);
    if (CUI.util.isEmpty(_data)) {
      return;
    }
    key = key_prepend + this.name();
    add_data = (function(_this) {
      return function(_key, _value) {
        if (CUI.util.isEmpty(_value)) {
          return;
        }
        if (use_array) {
          if (!record[_key]) {
            record[_key] = [];
          }
          CUI.util.assert(CUI.util.isArray(record[_key]), "Field.getReplacementRecord", "Record is no Array", {
            key: key_prepend,
            data: data,
            field: _this
          });
          return record[_key].push(_value + "");
        } else {
          return record[_key] = _value + "";
        }
      };
    })(this);
    if (CUI.util.isPlainObject(_data)) {
      for (k in _data) {
        v = _data[k];
        if (k === "_undo") {
          continue;
        }
        add_data(key + "." + k, v);
      }
    } else {
      add_data(key, _data);
    }
    return record;
  };

  Field.prototype.getDataForReplacementRecord = function(data) {
    return data != null ? data[this.name()] : void 0;
  };

  Field.prototype.getMappingSourceFullNameLocalized = function(useTableName) {
    if (useTableName == null) {
      useTableName = false;
    }
    return this.fullNameLocalized(useTableName, useTableName);
  };

  Field.prototype.getMappingTargetName = function() {
    return this.name();
  };

  Field.prototype.getFatherField = function() {
    if (this.mask.nestedTableField) {
      return this.mask.nestedTableField;
    } else {
      return null;
    }
  };

  Field.prototype.getFieldPath = function(path) {
    var ff;
    if (path == null) {
      path = [];
    }
    ff = this.getFatherField();
    if (ff) {
      ff.getFieldPath(path);
    }
    path.splice(0, 0, this);
    return path;
  };

  Field.prototype.insideNested = function() {
    if (!this.mask) {
      return false;
    } else if (!this.mask.nestedTableField) {
      return false;
    } else if (this === this.mask.nestedTableField) {
      return false;
    } else {
      return true;
    }
  };

  Field.prototype.getMainMask = function() {
    if (this.mask.nestedTableField) {
      return this.mask.nestedTableField.mainMask;
    } else {
      return this.mask;
    }
  };

  Field.prototype.getMask = function() {
    return this.mask;
  };

  Field.prototype.hasOption = function(data, option) {
    if (CUI.util.isNull(this.getOption(data, option))) {
      return false;
    } else {
      return true;
    }
  };

  Field.prototype.getOptions = function(data) {
    return data != null ? data[(this.name()) + ":options"] : void 0;
  };

  Field.prototype.getOption = function(data, option) {
    var ref;
    return data != null ? (ref = data[(this.name()) + ":options"]) != null ? ref[option] : void 0 : void 0;
  };

  Field.prototype.setOption = function(data, option, value) {
    if (!data[(this.name()) + ":options"]) {
      data[(this.name()) + ":options"] = {};
    }
    return data[(this.name()) + ":options"][option] = value;
  };

  Field.prototype.renderStandard = function(standard, data) {};

  Field.prototype.getNoInheritedQueryFieldBadge = function(data) {
    var valueBadge, valueText;
    if (!this.isInherited() || !data[this.name() + ":notInherited"]) {
      return null;
    }
    valueBadge = this.getQueryFieldBadge(data);
    valueText = '';
    if (valueBadge.value) {
      valueText = (valueBadge != null ? valueBadge.value : void 0) + " | ";
    }
    return {
      name: this.name(),
      value: valueText + $$("text.column.badge.non_inherited")
    };
  };

  Field.prototype.getQueryFieldBadge = function(data) {
    var cls;
    cls = CUI.util.getObjectClass(this);
    return {
      name: cls + ".getQueryFieldBadge",
      value: "unimplemented"
    };
  };

  Field.prototype.checkValue = function(data, top_level_data, opts) {
    return true;
  };

  Field.prototype.isRequired = function(data, top_level_data, opts) {
    if (this.ColumnSchema && (this.ColumnSchema.length_min > 0 || this.ColumnSchema.check === "not_empty" || (this.ColumnSchema.check === "range" && this.ColumnSchema.check_range_not_empty))) {
      if (this.ColumnSchema.check === "not_empty" && top_level_data && opts && !this.isVisible(opts.render_mode, {
        top_level_data: top_level_data
      }) && !this.isVisible(opts.render_mode_header, {
        top_level_data: top_level_data
      })) {
        return false;
      } else {
        return true;
      }
    } else {
      return false;
    }
  };

  Field.prototype.getClass = function() {
    return this.__cls;
  };

  Field.prototype.getElementClass = function() {
    return this.__cls;
  };

  Field.prototype.getLabel = function(data, top_level_data, opts) {
    var arr, iconStyleClass, infoModes, inheritedIcon, inheritedTooltipText, label, labelContent, lbl, lblText, noInfoModes, ref, ref1, ref2, requiredClass;
    if (opts == null) {
      opts = {};
    }
    if (CUI.util.isFunction(opts.getLabel)) {
      label = opts.getLabel(this, top_level_data, opts);
      if (label instanceof CUI.Label) {
        return label;
      }
    }
    if (opts.fieldRenderType === 'editor' && this.isRequired()) {
      requiredClass = "ez5-field-label--required";
    } else {
      requiredClass = "";
    }
    if (opts.overwriteLabel) {
      lblText = opts.overwriteLabel;
    } else if (opts.mode === "sort") {
      lblText = this.fullNameLocalized();
    } else {
      lblText = this.nameLocalized();
    }
    if (this.isInherited()) {
      iconStyleClass = "";
      if (opts.mode === "detail" && this.isInheritanceVisibleInDetail() && data[this.name() + ":inherited"]) {
        inheritedTooltipText = $$("admin.mask.form.inheritance.message");
      } else if (opts.mode === "editor") {
        inheritedTooltipText = $$("admin.mask.form.inheritance.editor_message");
        if (!data[this.name() + ":parent"]) {
          iconStyleClass = " no-inherited-data-icon";
        }
      }
      if (inheritedTooltipText) {
        inheritedIcon = new CUI.Icon({
          "class": $$("admin.mask.form.inheritance.icon") + iconStyleClass,
          tooltip: {
            on_hover: true,
            text: inheritedTooltipText,
            show_ms: 10
          }
        });
      }
    }
    if ((ref = opts.mode) === "editor" || ref === "expert") {
      labelContent = CUI.dom.element("label");
      labelContent.setAttribute('for', this.fullName());
      CUI.dom.append(labelContent, lblText);
      lbl = new CUI.Label({
        "class": "ez5-field-label " + requiredClass,
        content: labelContent,
        multiline: true,
        icon: inheritedIcon
      });
    } else {
      lbl = new CUI.Label({
        "class": "ez5-field-label " + requiredClass,
        text: lblText,
        multiline: true,
        icon: inheritedIcon
      });
    }
    if (opts.mode) {
      CUI.dom.setAttribute(lbl, "ui", "field.label:" + opts.mode + ":" + (this.fullName()));
    }
    arr = [lbl];
    noInfoModes = ["detail-head", "table", "sort"];
    infoModes = ["detail", "text"];
    if (ez5.version("6.22")) {
      infoModes.push("expert");
    } else {
      noInfoModes.push("expert");
    }
    if ((ref1 = opts.mode, indexOf.call(noInfoModes, ref1) >= 0) || ((ref2 = opts.mode, indexOf.call(infoModes, ref2) < 0) && this.isReadOnly(data, top_level_data, opts))) {
      return arr;
    }
    arr.push.apply(arr, this.getInfoLabels(data, top_level_data, opts));
    return arr;
  };

  Field.prototype.getInfoLabels = function(data, top_level_data, opts) {
    var hint_key, info, info_lbl, ref, ref1, user_hint;
    if (this.FieldSchema) {
      if ((ref = opts.mode) === "detail" || ref === "text") {
        hint_key = this.FieldSchema._user_output_hint_loca_key();
      } else if (opts.mode === "expert") {
        hint_key = this.FieldSchema._user_search_hint_loca_key();
      } else {
        hint_key = this.FieldSchema._user_hint_loca_key();
      }
      if (ez5.loca.has_user_key_localized("CURRENT", hint_key)) {
        user_hint = ez5.loca.get_user_key_localized("CURRENT", hint_key);
      }
    }
    if (user_hint) {
      info = [user_hint];
    } else {
      info = this.getCheckInfo(opts.mode);
      CUI.util.assert(CUI.util.isArray(info), "Field.getLabel[getCheckInfo]", "Info needs to be Array.", {
        field: this.field,
        info: info
      });
    }
    if (info.length > 0) {
      info_lbl = new CUI.Button({
        "class": "ez5-field-label-info",
        icon: ((ref1 = ez5.cssLoader.getActiveCSS()) != null ? ref1.theme : void 0) === "ng" ? "info_circle_ng" : "info_circle",
        appearance: "flat",
        onClick: (function(_this) {
          return function() {
            var pop;
            pop = new ez5.HintPopover({
              element: info_lbl,
              content: new CUI.Label({
                text: info.join("\n").trim(),
                multiline: true,
                markdown: true
              })
            });
            return pop.show();
          };
        })(this)
      });
      return [info_lbl];
    } else {
      return [];
    }
  };

  Field.prototype.needsDirectRender = function() {
    return this.isRequired();
  };

  Field.prototype.getTokenizer = function() {};

  Field.prototype.getDataForFieldData = function(data, top_level_data) {
    if (this.isTopLevelField()) {
      return top_level_data;
    } else {
      return data;
    }
  };

  Field.prototype.__formatBareValue = function(v) {
    return v;
  };

  Field.prototype.getCheckInfo = function(mode) {
    var cs, lower, lower_openness, upper, upper_openness, warn;
    if (mode === "detail" || mode === "text") {
      return [];
    }
    warn = [];
    cs = this.ColumnSchema || {};
    switch (cs.check) {
      case "regexp":
        warn.push($$("field.warn.regexp", {
          regexp: cs.check_regexp
        }));
        break;
      case "range":
        if (cs.hasOwnProperty("check_range_lower")) {
          lower = this.__formatBareValue(cs.check_range_lower);
          lower_openness = $$("field.warn.range.openness.inclusive");
        } else if (cs.hasOwnProperty("check_range_lower_open")) {
          lower = this.__formatBareValue(cs.check_range_lower_open);
          lower_openness = $$("field.warn.range.openness.exclusive");
        } else {
          lower = $$("field.warn.range.empty");
          lower_openness = "";
        }
        if (cs.hasOwnProperty("check_range_upper")) {
          upper = this.__formatBareValue(cs.check_range_upper);
          upper_openness = $$("field.warn.range.openness.inclusive");
        } else if (cs.hasOwnProperty("check_range_upper_open")) {
          upper = this.__formatBareValue(cs.check_range_upper_open);
          upper_openness = $$("field.warn.range.openness.exclusive");
        } else {
          upper = $$("field.warn.range.empty");
          upper_openness = "";
        }
        warn.push($$("field.warn.range", {
          lower: lower,
          lower_openness: lower_openness,
          upper: upper,
          upper_openness: upper_openness
        }));
        break;
      case "email":
        warn.push($$("field.warn.email"));
    }
    if (cs.length_min > 1) {
      warn.push($$("field.warn.length_min", {
        min: cs.length_min + ""
      }));
    }
    if (cs.length_max > 0) {
      warn.push($$("field.warn.length_max", {
        max: cs.length_max + ""
      }));
    }
    return warn;
  };

  Field.prototype.hasBulkCheckbox = function(opts) {
    return true;
  };

  Field.prototype.getBulkCheckbox = function(content, data, top_level_data, opts) {
    var cb;
    if (this.insideNested()) {
      return;
    }
    if (!(opts.mode === 'editor-bulk' || opts.mode === 'editor-header-bulk')) {
      return;
    }
    if (!this.hasOption(data, "bulk")) {
      this.setOption(data, "bulk", false);
    }
    return cb = new CUI.Checkbox({
      name: "bulk",
      "class": 'ez5-field-control-button',
      disabled: !this.hasBulkCheckbox(opts),
      data: data[(this.name()) + ":options"],
      onDataChanged: function(ev) {
        return CUI.Events.trigger({
          type: "editor-changed",
          node: content
        });
      }
    }).start();
  };

  Field.prototype.getBulkOptionsForm = function(options, data, key) {
    var f_options, form, j, len, min_checked, opt, options_data;
    if (key == null) {
      key = null;
    }
    if (!(options != null ? options.length : void 0)) {
      return;
    }
    CUI.util.assert(CUI.util.isPlainObject(data), (CUI.util.getObjectClass(this)) + ".getBulkOptionsForm", "data needs to be a PlainObject but is " + (CUI.util.getObjectClass(data)), {
      options: options,
      data: data,
      key: key
    });
    CUI.util.assert(!data._mask, (CUI.util.getObjectClass(this)) + ".getBulkOptionsForm", "data cannot be top-level-data for bulk options", {
      options: options,
      data: data,
      key: key
    });
    if (!data[(this.name()) + ":options"]) {
      data[(this.name()) + ":options"] = {};
    }
    if (key) {
      options_data = data[(this.name()) + ":options"];
      if (!options_data[key]) {
        options_data[key] = options[0];
      }
    } else {
      key = (this.name()) + ":options";
      options_data = data;
    }
    f_options = [];
    for (j = 0, len = options.length; j < len; j++) {
      opt = options[j];
      if (CUI.util.isPlainObject(opt)) {
        f_options.push(opt);
      } else {
        f_options.push({
          text: $$("main.editor.option." + opt, {
            fieldname: this.nameLocalized()
          }),
          value: opt
        });
      }
    }
    if (options.min_checked !== void 0) {
      min_checked = options.min_checked;
    } else {
      min_checked = 1;
    }
    form = new CUI.Options({
      data: options_data,
      radio: true,
      horizontal: false,
      min_checked: min_checked,
      name: key,
      onDataChanged: (function(_this) {
        return function(data) {
          return _this.onBulkOptionsChanged(data, form);
        };
      })(this),
      options: f_options
    });
    return form.start().DOM;
  };

  Field.prototype.onBulkOptionsChanged = function(data, form) {
    return CUI.Events.trigger({
      type: "editor-changed",
      node: form
    });
  };

  Field.prototype.getBulkSaveData = function(data, save_data, opts, key) {
    var bulk_key;
    if (opts.bulk && this.hasOption(data, "bulk")) {
      if (!data[(this.name()) + ":options"][key]) {
        throw new InvalidSaveDataException();
      }
      bulk_key = (this.name()) + ":group_mode";
      save_data[bulk_key] = data[(this.name()) + ":options"][key].substr("bulk_".length);
      return bulk_key;
    }
  };

  Field.prototype.hasUserData = function(data, top_level_data, opts) {
    return !this.isEmpty(data, top_level_data, opts);
  };

  Field.prototype.isPluginSupported = function(plugin) {
    return false;
  };

  Field.prototype.getDataAsString = function() {
    return console.error((CUI.util.getObjectClass(this)) + ".getDataAsString method not implemented.");
  };

  Field.prototype.renderSearchInput = function(data) {
    return CUI.dom.textEmpty((CUI.util.getObjectClass(this)) + ".renderSearchInput unimplemented");
  };

  Field.prototype.renderForEditor = function(data, top_level_data, opts) {
    opts.fieldRenderType = 'editor';
    return this.renderRow(this.renderEditorInput, data, top_level_data, opts);
  };

  Field.prototype.renderForExpert = function(data, opts) {
    var func, row;
    opts.fieldRenderType = 'expert';
    func = (function(_this) {
      return function(data, top_level_data, opts) {
        return _this.renderSearchInput(data, opts);
      };
    })(this);
    row = this.renderRow(func, data, null, opts);
    data._DOM = row.DOM || row;
    return row;
  };

  Field.prototype.renderForDetail = function(data, top_level_data, opts) {
    if (!this.hasRenderForDetail() && !opts.fieldRenderType) {
      return;
    }
    opts.fieldRenderType = opts.fieldRenderType || 'detail';
    return this.renderRow(this.renderDetailOutput, data, top_level_data, opts);
  };

  Field.prototype.renderForTable = function(data, top_level_data, opts) {
    if (!this.hasRenderForTable()) {
      return;
    }
    opts.fieldRenderType = 'table';
    opts.render_value_only = true;
    return this.renderTableOutput(data, top_level_data, opts);
  };

  Field.prototype.renderForSort = function(data, opts) {
    var func;
    if (!this.hasRenderForSort()) {
      return;
    }
    opts.fieldRenderType = 'sort';
    func = (function(_this) {
      return function(data, top_level_data, opts) {
        return _this.renderSortInput(data, opts);
      };
    })(this);
    return this.renderRow(func, data, null, opts);
  };

  Field.prototype.renderSortInput = function(_data, opts) {
    var ascOptionText, data, descOptionText, extraOpts, fieldType, fields, fn1, j, key, len, ref, ref1, sel, sel2, sel_opts;
    data = _data[this.fullName()];
    fields = [];
    ref = opts.sortManagerKeys;
    fn1 = (function(_this) {
      return function(key) {
        var cb;
        cb = new CUI.Checkbox({
          radio: _this.fullName(),
          radio_allow_null: true,
          name: key,
          onDataChanged: function() {
            return opts.sortManager.updateState(_this, key);
          },
          data: data
        }).start();
        data._fields[key] = cb;
        return fields.push(cb);
      };
    })(this);
    for (j = 0, len = ref.length; j < len; j++) {
      key = ref[j];
      fn1(key);
    }
    ascOptionText = $$("sort.manager.field.popover.manager.option.asc");
    descOptionText = $$("sort.manager.field.popover.manager.option.desc");
    fieldType = data != null ? (ref1 = data.field) != null ? ref1.constructor.name : void 0 : void 0;
    if (fieldType) {
      if (ez5.loca.has("sort.manager.field.popover.manager.option." + fieldType + ".asc")) {
        ascOptionText = $$("sort.manager.field.popover.manager.option." + fieldType + ".asc");
      }
      if (ez5.loca.has("sort.manager.field.popover.manager.option." + fieldType + ".desc")) {
        descOptionText = $$("sort.manager.field.popover.manager.option." + fieldType + ".desc");
      }
    }
    sel_opts = [
      {
        text: ascOptionText,
        value: "ASC"
      }, {
        text: descOptionText,
        value: "DESC"
      }
    ];
    sel = new CUI.Select({
      options: sel_opts,
      name: "_order",
      hidden: true,
      data: data
    });
    sel.start();
    data._fields._order = sel;
    fields.push(sel);
    extraOpts = this.sortExtraOpts(data);
    if (extraOpts) {
      sel2 = new CUI.Select({
        options: extraOpts,
        name: "_extra",
        hidden: true,
        data: data
      }).start();
      fields.push(sel2);
    }
    data._fields._extra = sel2;
    return new CUI.Buttonbar({
      buttons: fields
    });
  };

  Field.prototype.renderFieldAsGroup = function(data, top_level_data, opts) {
    return false;
  };

  Field.prototype.allowsList = function(data, top_level_data, opts) {
    return this.allowsCondensed(data, top_level_data, opts);
  };

  Field.prototype.allowsCondensed = function(data, top_level_data, opts) {
    return !this.renderFieldAsGroup(data, top_level_data, opts);
  };

  Field.prototype.renderFieldLabel = function(data, top_level_data, opts) {
    return opts.render_value_only !== true;
  };

  Field.prototype.renderHalfWidth = function() {
    return false;
  };

  Field.prototype.getBulkOptions = function() {};

  Field.prototype.renderRow = function(func, data, top_level_data, opts) {
    var attr, block, blockWidth, bulk_options, cb, cls, content, contents, div, div_left, div_right, div_row, extraButton, hasValueCheckbox, j, l, label, len, len1, noInheritedCheckbox, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, render_as_group, render_as_row, render_label, supportsHasValueSearch, unsetCheckbox;
    if (opts == null) {
      opts = {};
    }
    cls = ['ez5-field'];
    if (((ref = opts.mode) === "detail" || ref === "detail-header") && (top_level_data != null ? (ref1 = top_level_data.versionDiff) != null ? ref1[this.name()] : void 0 : void 0)) {
      cls.push("ez5-block-field-history-" + (top_level_data != null ? (ref2 = top_level_data.versionDiff) != null ? ref2[this.name()] : void 0 : void 0));
    }
    if (((ref3 = this.FieldSchema) != null ? (ref4 = ref3.custom_settings) != null ? ref4.hide_label : void 0 : void 0) && this.insideNested() && !opts.forceShowLabel) {
      cls.push("ez5-field--hide-label");
    }
    content = func.call(this, data, top_level_data, opts);
    if (CUI.util.isEmpty(content)) {
      return null;
    }
    if (content instanceof CUI.DataField && !content.isRendered()) {
      content.start();
    }
    bulk_options = this.getBulkOptions(data, opts);
    if (opts.mode) {
      CUI.dom.setAttribute(content, "ui", "field.content:" + opts.mode + ":" + (this.fullName()));
    }
    contents = [(content != null ? content.DOM : void 0) || content || CUI.dom.element("DIV"), this.getBulkOptionsForm(bulk_options, data, "mode")];
    label = this.getLabel(data, top_level_data, opts);
    supportsHasValueSearch = (function(_this) {
      return function() {
        if ((!(_this instanceof CustomDataType)) || (_this instanceof CustomDataType && _this.getHasValueFilter(data) !== null)) {
          return true;
        }
        return false;
      };
    })(this);
    if (opts.fieldRenderType === "editor" && opts.include_unset_btn) {
      label.push(this.getSearchUnsetElement(data, opts));
      if (supportsHasValueSearch()) {
        label.push(this.getSearchHasValueElement(data, opts));
      }
    }
    if (opts.fieldRenderType === 'expert') {
      cls.push('ez5-field--expert');
      if (opts.nested_level === void 0 || opts.nested_level === 0 && this instanceof NestedTable) {
        ref5 = this.getExpertLabelButtons(data, opts);
        for (j = 0, len = ref5.length; j < len; j++) {
          extraButton = ref5[j];
          label.splice(0, 0, extraButton);
        }
        if (this.isInherited()) {
          noInheritedCheckbox = this.getInheritanceUnsetElement(data, opts);
          label.splice(0, 0, noInheritedCheckbox);
        }
        unsetCheckbox = this.getSearchUnsetElement(data, opts);
        label.splice(0, 0, unsetCheckbox);
        if (supportsHasValueSearch()) {
          hasValueCheckbox = this.getSearchHasValueElement(data, opts);
          label.splice(0, 0, hasValueCheckbox);
        }
        cls.push('ez5-field--has-control-button ez5-field--has-unset-button');
      } else if (this.insideNested()) {
        if (supportsHasValueSearch()) {
          label.push(this.getSearchHasValueElement(data, opts));
        }
        label.push(this.getSearchUnsetElement(data, opts));
        ref6 = this.getExpertLabelButtons(data, opts);
        for (l = 0, len1 = ref6.length; l < len1; l++) {
          extraButton = ref6[l];
          label.push(extraButton);
        }
        cls.push('ez5-field--has-control-button ez5-field--has-unset-button');
      }
    } else {
      cb = this.getBulkCheckbox(content, data, top_level_data, opts);
      if (cb) {
        cb.registerLabel(label[0].DOM);
        label.splice(0, 0, cb);
        cls.push('ez5-field--has-control-button');
      }
    }
    render_label = this.renderFieldLabel(data, top_level_data, opts);
    render_as_group = this.renderFieldAsGroup(data, top_level_data, opts);
    if (this.renderHalfWidth() && opts.fieldRenderType !== 'expert') {
      cls.push('ez5-field--half-width');
    }
    attr = {};
    attr["ez5-field-name"] = this.fullName();
    attr["ez5-field-id"] = this.id() || "";
    attr["ui"] = "field.block:" + opts.mode + ":" + (this.fullName());
    if (!(opts != null ? opts.removeBlockWidth : void 0)) {
      blockWidth = (ref7 = this.FieldSchema) != null ? (ref8 = ref7.custom_settings) != null ? ref8.blockWidth : void 0 : void 0;
      if (blockWidth) {
        attr["data-block-width"] = blockWidth;
      }
    }
    if (opts.fieldRenderType === 'sort') {
      render_as_row = true;
    } else {
      render_as_row = false;
    }
    cls.push(this.getClass());
    switch (opts.fieldRenderType) {
      case 'editor':
      case 'expert':
        cls.push('ez5-field--input-mode');
        break;
      default:
        cls.push('ez5-field--output-mode');
    }
    CUI.dom.addClass(contents[0], 'ez5-field-value');
    if (render_as_row) {
      cls.push('ez5-field-row');
      div_row = CUI.dom.div(cls.join(' '), attr);
      div_left = CUI.dom.div("ez5-field-key");
      CUI.dom.append(div_left, label);
      div_right = CUI.dom.div("ez5-field-value");
      CUI.dom.append(div_right, contents);
      CUI.dom.append(div_row, [div_left, div_right]);
      return div_row;
    }
    if (render_label) {
      block = new CUI.Template({
        name: 'field-block',
        "class": cls.join(' '),
        attr: attr,
        map: {
          title: true,
          header: true,
          header_right: true,
          content: true
        }
      });
      block.append(contents, 'content');
      if (render_as_group) {
        CUI.dom.addClass(block.map.content, 'ez5-field-group');
      }
      block.append(label, 'title');
      return block;
    }
    if (render_as_group) {
      cls.push('ez5-field-group');
    }
    div = CUI.dom.div(cls.join(' '), attr);
    CUI.dom.append(div, contents);
    return div;
  };

  Field.prototype.renderEditorInput = function(data, top_level_data, opts) {
    return CUI.dom.textEmpty((CUI.util.getObjectClass(this)) + ".renderEditorInput unimplemented");
  };

  Field.prototype.renderDetailOutput = function(data, top_level_data, opts) {
    return CUI.dom.textEmpty((CUI.util.getObjectClass(this)) + ".renderDetailOutput unimplemented");
  };

  Field.prototype.renderTableOutput = function(data, top_level_data, opts) {
    return this.renderDetailOutput(data, top_level_data, opts);
  };

  Field.prototype.getSortFields = function(filter, keys) {
    return CUI.util.assert(false, (CUI.util.getObjectClass(this)) + ".getSortFields unimplemented");
  };

  Field.prototype.getSaveData = function(data, save_data, opts) {};

  Field.prototype.preferTemplateOverMapping = function(opts) {
    var ref, ref1;
    if ((ref = opts.editor) != null ? (ref1 = ref.editor_data) != null ? ref1.prefer_template_over_mapping : void 0 : void 0) {
      return true;
    } else {
      return false;
    }
  };

  Field.prototype.path = function() {
    if (this.mask.nestedTableField) {
      return this.mask.nestedTableField.fullName();
    } else {
      return this.mask.table.name();
    }
  };

  Field.prototype.fullName = function(include_top_level_objecttype) {
    var parts;
    if (include_top_level_objecttype == null) {
      include_top_level_objecttype = true;
    }
    if (include_top_level_objecttype) {
      return this.path() + "." + this.name();
    } else {
      parts = (this.path() + "." + this.name()).split('.');
      parts.splice(0, 1);
      return parts.join('.');
    }
  };

  Field.prototype.getFieldNamesForSuggest = function() {
    return [this.fullName()];
  };

  Field.prototype.getFieldOptsForSuggest = function() {
    return {};
  };

  Field.prototype.getCSVDestinationFields = function(csvImporter) {
    return [];
  };

  Field.prototype.getCSVRecordKeyPath = function() {
    var path;
    if (this.mask.nestedTableField) {
      path = this.mask.nestedTableField.getCSVRecordKeyPath() + ".";
    } else if (this.isTopLevelField()) {
      path = "";
    } else {
      path = this.mask.table.name() + ".";
    }
    return path + this.name();
  };

  Field.prototype.getCSVName = function() {
    var path;
    if (this.mask.nestedTableField) {
      path = this.mask.nestedTableField.getCSVName() + ".";
    } else {
      path = "";
    }
    return path + this.name();
  };

  Field.prototype.getCSVLabel = function() {
    return this.fullNameLocalized();
  };

  Field.prototype.nameForCommonField = function() {
    return this.nameLocalized();
  };

  Field.prototype.nameLocalized = function() {
    if (!this.ColumnSchema) {
      throw (CUI.util.getObjectClass(this)) + ".nameLocalized(): no ColumnSchema set";
    }
    return this.ColumnSchema._name_localized;
  };

  Field.prototype.fullNameLocalized = function(include_top_level_mask, use_table_name, return_path, mask) {
    var path;
    if (include_top_level_mask == null) {
      include_top_level_mask = false;
    }
    if (use_table_name == null) {
      use_table_name = false;
    }
    if (return_path == null) {
      return_path = false;
    }
    if (mask == null) {
      mask = this.mask;
    }
    if (this.insideNested()) {
      path = mask.nestedTableField.fullNameLocalized(include_top_level_mask, use_table_name, true);
      path.push(this.nameLocalized());
    } else if (include_top_level_mask) {
      if (use_table_name) {
        path = [mask.table.nameLocalized(), this.nameLocalized()];
      } else {
        path = [mask.nameLocalized(), this.nameLocalized()];
      }
    } else {
      path = [this.nameLocalized()];
    }
    if (return_path) {
      return path;
    } else {
      return path.join(" / ");
    }
  };

  Field.prototype.getOutputStandard = function() {
    var ref;
    if (((ref = this.FieldSchema) != null ? ref.output.standard.order : void 0) > 0) {
      return this.FieldSchema.output.standard;
    } else {
      return null;
    }
  };

  Field.prototype.getOutputStandardEAS = function() {
    var ref;
    if (((ref = this.FieldSchema) != null ? ref.output.standard_eas.order : void 0) > 0) {
      return this.FieldSchema.output.standard_eas;
    } else {
      return null;
    }
  };

  Field.prototype.supportsFacet = function() {
    return false;
  };

  Field.prototype.getFacet = function() {};

  Field.prototype.isVisibleToSaveData = function(mode, header_mode, opts) {
    opts.skip_columnfilter = true;
    return this.isVisible(mode, opts) || this.isVisible(header_mode, opts);
  };

  Field.prototype.isVisible = function(mode, opts) {
    var allowed, isStandardAllowed, isVisible, ref, ref1, skipColumnFilter;
    if (opts == null) {
      opts = {};
    }
    if (CUI.util.isFunction(opts.isVisible)) {
      isVisible = opts.isVisible(this, mode, opts);
      if (CUI.util.isBoolean(isVisible)) {
        return isVisible;
      }
    }
    CUI.util.assert(mode === "editor-header" || mode === "editor-footer" || mode === "editor-header-bulk" || mode === "editor-header-template" || mode === "editor-bulk" || mode === "editor-template" || mode === "editor" || mode === "csv-import" || mode === "expert" || mode === "index" || mode === "detail" || mode === "detail-header" || mode === "detail-footer" || mode === "result-card-info-detail" || mode === "sort" || mode === "facet" || mode === "text" || mode === "table" || mode === "text-inline" || mode === "fulltext" || mode === "standard" || mode === "export", "Field.isVisible", "mode " + mode + " unknown", {
      mode: mode
    });
    CUI.util.assert(this.FieldSchema, (CUI.util.getObjectClass(this)) + ".isVisible", "Unknown FieldSchema for mode " + mode + ".");
    if (mode === "index") {
      if (this.FieldSchema.search.facet || this.FieldSchema.search.fulltext || this.FieldSchema.search.expert) {
        allowed = true;
      } else {
        return false;
      }
    } else if (mode.startsWith("editor")) {
      if (mode === "editor-footer") {
        return false;
      }
      if (this.FieldSchema.edit.mode !== "off" && (((ref = this.FieldSchema.custom_settings) != null ? ref.editor_frontend_mode : void 0) !== "hide" || opts.get_save_data)) {
        if (this.isReadOnly() && opts.new_mode) {
          return false;
        }
        allowed = true;
      } else {
        return false;
      }
    } else {
      if (((ref1 = this.FieldSchema.output.standard_eas) != null ? ref1.order : void 0) > 0 || this.FieldSchema.output.standard.order > 0) {
        isStandardAllowed = true;
      } else {
        isStandardAllowed = false;
      }
      switch (mode) {
        case "detail-footer":
          allowed = false;
          break;
        case "csv-import":
          allowed = this.FieldSchema.edit.mode === "edit";
          break;
        case "detail":
        case "detail-header":
        case "export":
        case "result-card-info-detail":
          allowed = this.FieldSchema.output.detail;
          break;
        case "standard":
          allowed = isStandardAllowed;
          break;
        case "facet":
          allowed = this.FieldSchema.search.facet;
          break;
        case "expert":
          allowed = this.FieldSchema.search.expert;
          break;
        case "fulltext":
          allowed = this.FieldSchema.search.fulltext;
          break;
        case "text":
          allowed = this.FieldSchema.output.text;
          break;
        case "table":
          allowed = this.FieldSchema.output.table;
          break;
        case "sort":
          allowed = this.isVisibleSort();
          break;
        default:
          CUI.util.assert(false, "Field.isVisible", "Unkown mode " + mode);
      }
    }
    if (!allowed) {
      return false;
    }
    if (mode === "table" && !this.hasRenderForTable()) {
      return false;
    }
    if ((mode === "text" || mode === "detail") && !this.hasRenderForDetail()) {
      return false;
    }
    skipColumnFilter = opts.skip_columnfilter;
    if (ez5.session.hasSystemRight("ignore_columnfilters")) {
      skipColumnFilter = true;
    }
    if (!skipColumnFilter && this.ColumnSchema && !this.getMainMask().isAllFieldsMask()) {
      if (this.isFilteredByRights(opts, mode)) {
        return false;
      }
    }
    return true;
  };

  Field.prototype.isFilteredByRights = function(opts, mode) {
    var acl_item, cf, cfs, check, j, l, len, len1, match, objecttype, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, row_matches, tags, top_level_data;
    if (opts == null) {
      opts = {};
    }
    if (mode == null) {
      mode = "";
    }
    if (!this.isRightsEnabled()) {
      return false;
    }
    top_level_data = opts.top_level_data;
    if ((!top_level_data || top_level_data.__version === "TEMP") && mode !== "expert") {
      return false;
    }
    objecttype = (top_level_data != null ? top_level_data._objecttype : void 0) || this.table.name();
    if (!ez5.schema.CURRENT._objecttype_by_name[objecttype]) {
      return false;
    }
    cfs = ez5.objecttypes.getColumnFilters(objecttype);
    if (cfs.length > 0) {
      if (ez5.schema.CURRENT._objecttype_by_name[objecttype].has_tags && !mode !== "facet") {
        tags = (top_level_data != null ? top_level_data._tags : void 0) || [];
        if (tags.length === 0 && (top_level_data != null ? top_level_data._template : void 0)) {
          tags = top_level_data._template._tags || [];
        }
      } else {
        tags = null;
      }
      row_matches = true;
      for (j = 0, len = cfs.length; j < len; j++) {
        cf = cfs[j];
        if (ref = this.getKeyInRights(), indexOf.call(cf.columns, ref) < 0) {
          continue;
        }
        row_matches = false;
        if (((ref1 = cf.acl) != null ? ref1.length : void 0) > 0) {
          match = false;
          ref2 = cf.acl;
          for (l = 0, len1 = ref2.length; l < len1; l++) {
            acl_item = ref2[l];
            if (acl_item.who._basetype === 'user' && acl_item.who.user._id === ez5.session.user.getId()) {
              match = true;
              break;
            }
            if (acl_item.who._basetype === 'group' && (ref3 = acl_item.who.group._id, indexOf.call(ez5.session.getGroupIds(), ref3) >= 0)) {
              match = true;
              break;
            }
            if (acl_item.who._owner) {
              if (opts.new_mode) {
                match = true;
              } else if ((top_level_data != null ? (ref4 = top_level_data._owner) != null ? (ref5 = ref4.user) != null ? ref5._id : void 0 : void 0 : void 0) === ez5.session.user.getId()) {
                match = true;
              } else if (ref6 = top_level_data != null ? (ref7 = top_level_data._owner) != null ? (ref8 = ref7.group) != null ? ref8._id : void 0 : void 0 : void 0, indexOf.call(ez5.session.getGroupIds(), ref6) >= 0) {
                match = true;
              }
              break;
            }
          }
        } else {
          match = true;
        }
        if (match && tags) {
          check = TagFilter.matchesTags(cf.tagfilter, tags);
          if (!check) {
            match = false;
          }
        }
        if (match) {
          row_matches = true;
          break;
        }
      }
      if (row_matches === false) {
        return true;
      }
    }
    return false;
  };

  Field.prototype.isSourceForMapping = function(required_type) {
    return true;
  };

  Field.prototype.isReadOnly = function(data, top_level_data, opts) {
    var ref, ref1, ref2;
    if (opts == null) {
      opts = {};
    }
    if (((ref = this.FieldSchema) != null ? ref.edit.mode : void 0) === "show" || (((ref1 = this.FieldSchema) != null ? (ref2 = ref1.custom_settings) != null ? ref2.editor_frontend_mode : void 0 : void 0) === "readonly" && !opts.get_save_data)) {
      return true;
    }
    if (opts.read_only && !opts.get_save_data) {
      return true;
    }
    return false;
  };

  Field.prototype.isUnique = function() {
    var column, j, l, len, len1, ref, ref1, uniqueKey;
    if (this.table.schema.unique_keys && this.ColumnSchema) {
      ref = this.table.schema.unique_keys;
      for (j = 0, len = ref.length; j < len; j++) {
        uniqueKey = ref[j];
        ref1 = uniqueKey.columns;
        for (l = 0, len1 = ref1.length; l < len1; l++) {
          column = ref1[l];
          if (column.column_id === this.ColumnSchema.column_id) {
            return true;
          }
        }
      }
    }
    return false;
  };

  Field.prototype.isVisibleSort = function() {
    var ref, ref1;
    if ((ref = this.FieldSchema) != null ? (ref1 = ref.custom_settings) != null ? ref1.hide_sort : void 0 : void 0) {
      return false;
    }
    return (this.FieldSchema.edit.mode !== "off" || this.FieldSchema.output.detail) && (this.FieldSchema.search.expert || this.FieldSchema.search.fulltext);
  };

  Field.prototype.mergeData = function(top_level_data, top_level_data_new, replace, is_restore) {
    var data, data_new, fdata, fdata_new;
    if (replace == null) {
      replace = false;
    }
    if (is_restore == null) {
      is_restore = false;
    }
    data = top_level_data[top_level_data._objecttype];
    data_new = top_level_data_new[top_level_data_new._objecttype];
    if (this.hasUserData(data, top_level_data) && !replace) {
      return this;
    }
    fdata = this.getDataForFieldData(data, top_level_data);
    fdata_new = this.getDataForFieldData(data_new, top_level_data_new);
    fdata[this.name()] = fdata_new[this.name()];
    return this;
  };

  Field.prototype.id = function() {
    var ref;
    return (ref = this.ColumnSchema) != null ? ref.column_id : void 0;
  };

  Field.prototype.idAttribute = function(data) {
    if (this.insideNested() && !CUI.util.isUndef(data != null ? data._row_number : void 0)) {
      return (this.fullName()) + "_row-" + data._row_number;
    } else {
      return this.fullName();
    }
  };

  Field.prototype.isRightsEnabled = function() {
    return !!this.getKeyInRights();
  };

  Field.prototype.getKeyInRights = function() {
    return this.id();
  };

  Field.prototype.identifier = function() {
    return this.fullName();
  };

  Field.prototype.getSearchUnsetElement = function(data, opts) {
    var field, radioElement;
    if (opts == null) {
      opts = {};
    }
    if (opts.readonly) {
      return;
    }
    CUI.util.assert(!data.data, "Field.getSearchUnsetElement", "data needs to be set correctly", {
      data: data
    });
    field = new CUI.Checkbox({
      name: (this.name()) + ":unset",
      radio: (this.name()) + ":unset",
      ui: "field.search.unset.checkbox:" + (this.name()),
      "class": 'ez5-field-control-button ez5-field-control-button--unset',
      data: data,
      icon_active: "fa-ban",
      radio_allow_null: true,
      icon_inactive: "fa-ban",
      tooltip: {
        text: $$("main.search.expert.unset_tooltip")
      },
      onDataChanged: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            type: "search-input-change",
            node: field
          });
        };
      })(this)
    }).start();
    radioElement = field.DOM.querySelector('[role="radio"]');
    if (radioElement != null) {
      radioElement.removeAttribute('role');
    }
    return field;
  };

  Field.prototype.getSearchHasValueElement = function(data, opts) {
    var field, radioElement;
    if (opts == null) {
      opts = {};
    }
    if (opts.readonly || !this.getSearchUnsetElement(data, opts)) {
      return;
    }
    CUI.util.assert(!data.data, "Field.getSearchSetElement", "data needs to be set correctly", {
      data: data
    });
    field = new CUI.Checkbox({
      name: (this.name()) + ":has_value",
      radio: (this.name()) + ":unset",
      ui: "field.search.set.checkbox:" + (this.name()),
      "class": 'ez5-field-control-button ez5-field-control-button--unset',
      data: data,
      icon_active: "fa-check",
      icon_inactive: "fa-check",
      radio_allow_null: true,
      tooltip: {
        text: $$("main.search.expert.has_value_tooltip")
      },
      onDataChanged: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            type: "search-input-change",
            node: field
          });
        };
      })(this)
    }).start();
    radioElement = field.DOM.querySelector('[role="radio"]');
    if (radioElement != null) {
      radioElement.removeAttribute('role');
    }
    return field;
  };

  Field.prototype.getInheritanceUnsetElement = function(data) {
    var field, radioElement;
    CUI.util.assert(!data.data, "Field.getInheritanceUnsetElement", "data needs to be set correctly", {
      data: data
    });
    field = new CUI.Checkbox({
      name: (this.name()) + ":notInherited",
      ui: "field.inheritance.unset.checkbox:" + (this.name()),
      "class": 'ez5-field-control-button ez5-field-control-button--unset',
      radio: (this.name()) + ":unset",
      data: data,
      radio_allow_null: true,
      icon_active: $$("admin.mask.form.inheritance.icon"),
      icon_inactive: $$("admin.mask.form.inheritance.icon"),
      tooltip: {
        text: "Search records not inherited"
      },
      onDataChanged: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            type: "search-input-change",
            node: field
          });
        };
      })(this)
    }).start();
    radioElement = field.DOM.querySelector('[role="radio"]');
    if (radioElement != null) {
      radioElement.removeAttribute('role');
    }
    return field;
  };

  Field.prototype.getExpertLabelButtons = function(data, opts) {
    if (opts == null) {
      opts = {};
    }
    return [];
  };

  Field.prototype.getSearchFilter = function(data, key) {
    if (key == null) {
      key = this.name();
    }
    return this.getUnsetSearchFilter(data, key);
  };

  Field.prototype.getSortFunction = function() {};

  Field.prototype.getSortFunctions = function(opts) {
    var func, j, len, nestedSortField, ref, sortFunctions;
    if (opts == null) {
      opts = {};
    }
    sortFunctions = [];
    ref = opts.nested_sort_fields;
    for (j = 0, len = ref.length; j < len; j++) {
      nestedSortField = ref[j];
      if (nestedSortField.sort_field !== this.name()) {
        continue;
      }
      func = this.getSortFunction();
      if (!func) {
        continue;
      }
      sortFunctions.push({
        nested_sort_field: nestedSortField,
        func: func
      });
    }
    return sortFunctions;
  };

  Field.prototype.getSortGroup = function() {};

  Field.prototype.getSearchFilterWithNested = function(data, key) {
    var i, j, path, ref, sf;
    sf = this.getSearchFilter(data, key);
    if (!sf) {
      return;
    }
    path = this.getFieldPath();
    if (path.length === 1) {
      return sf;
    }
    for (i = j = 1, ref = path.length; 1 <= ref ? j < ref : j > ref; i = 1 <= ref ? ++j : --j) {
      if (!path[i].isNestedIndex()) {
        continue;
      }
      sf = {
        type: "nested",
        path: path[i].fullName(),
        search: [sf]
      };
    }
    return sf;
  };

  Field.prototype.getSearchField = function() {
    return console.error((CUI.util.getObjectClass(this)) + ".getSearchField method not implemented.");
  };

  Field.prototype.getUnsetSearchFilter = function(data, key) {
    var combinedFilter, field, fieldFilter, filter, fn, j, l, len, len1, sub_filter;
    if (key == null) {
      key = this.name();
    }
    if (data[key + ":unset"]) {
      field = this.getSearchField();
      if (CUI.util.isArray(field) && field.length > 0) {
        filter = {
          type: "complex",
          search: []
        };
        for (j = 0, len = field.length; j < len; j++) {
          fn = field[j];
          filter.search.push({
            type: "in",
            fields: [fn],
            "in": [null]
          });
        }
      } else {
        filter = {
          type: "in",
          fields: [field],
          "in": [null]
        };
      }
      filter._unnest = true;
      filter._unset_filter = true;
    } else if (data[key + ":has_value"]) {
      field = this.getSearchField();
      if (CUI.util.isArray(field) && field.length > 0) {
        sub_filter = {
          type: "complex",
          search: []
        };
        for (l = 0, len1 = field.length; l < len1; l++) {
          fn = field[l];
          sub_filter.search.push({
            type: "in",
            fields: [fn],
            "in": [null]
          });
        }
        sub_filter.bool = "must_not";
        filter = {
          type: "complex",
          bool: "should",
          search: [sub_filter]
        };
      } else {
        filter = {
          type: "complex",
          bool: "should",
          search: [
            {
              type: "in",
              fields: [field],
              "in": [null],
              bool: "must_not"
            }
          ]
        };
      }
      filter._unnest = true;
      filter._has_value_filter = true;
      filter = {
        type: "complex",
        search: [filter]
      };
    }
    if (!this.__noCheckInheritance) {
      if (data[key + ":notInherited"]) {
        this.__noCheckInheritance = true;
        filter = {
          type: "in",
          fields: [this.getNotInheritedSearchField()],
          "in": [false]
        };
        filter._unnest = true;
        fieldFilter = this.getSearchFilter(data, key);
        if (fieldFilter) {
          fieldFilter.bool = "must";
          filter.bool = "must";
          combinedFilter = {
            type: "complex",
            search: [fieldFilter, filter]
          };
          return combinedFilter;
        }
      }
    } else {
      this.__noCheckInheritance = false;
    }
    return filter;
  };

  Field.prototype.getNotInheritedSearchField = function() {
    return (this.getSearchField()) + ":inherited";
  };

  Field.prototype.isEmpty = function(data, top_level_data, opts) {
    return true;
  };

  Field.prototype.isDataEqualsValue = function(data, value) {
    return console.error((CUI.util.getObjectClass(this)) + ".isDataEqualsValue method not implemented.");
  };

  Field.prototype.formatValue = function(value) {
    return value;
  };

  Field.prototype.mergeReplaceData = function(data, top_level_data, opts) {};

  Field.prototype.getExportOptions = function(fields) {
    if (fields == null) {
      fields = [];
    }
    return fields;
  };

  Field.prototype.isExpertCommon = function(mode) {
    return false;
  };

  Field.prototype.isExpertCommonOnly = function(mode) {
    return true;
  };

  Field.prototype.sortExtraOpts = function() {};

  Field.prototype.isSortUnique = function() {
    return false;
  };

  Field.prototype.sortRenderContent = function(path, renderDynamic) {
    return path[0];
  };

  Field.prototype.formatSortGroupable = function(item, filter, idx, resdata) {
    return item;
  };

  Field.prototype.isSortGroupable = function() {
    return false;
  };

  Field.prototype.allowAppendMultipleRows = function() {
    return false;
  };

  Field.prototype.getXMLFormWrapperFields = function() {
    return [];
  };

  Field.prototype.castData = function(sourceClass, sourceData) {};

  Field.prototype.getXMLFormWrapperType = function() {
    return "text";
  };

  Field.prototype.getXMLFormWrapperSaveData = function(wrapperField) {
    return {
      type: this.getXMLFormWrapperType()
    };
  };

  Field.prototype.isInPopoverTopLevel = function() {
    return this.isTopLevelField();
  };

  Field.prototype.isTopLevelField = function() {
    return false;
  };

  Field.prototype.isSystemField = function() {
    return false;
  };

  Field.prototype.getStoreDataForUrlValue = function(data) {};

  Field.prototype.getSignature = function() {
    var sig;
    sig = {
      "class": CUI.util.getObjectClass(this),
      mask: {
        name: this.getMainMask().name()
      },
      field: {
        name: this.fullName()
      }
    };
    return sig;
  };

  Field.prototype.hasRenderForSort = function() {
    return true;
  };

  Field.prototype.hasRenderForDetail = function() {
    return true;
  };

  Field.prototype.hasRenderForTable = function() {
    return true;
  };

  Field.prototype.emptyEditorInputValue = function(value, top_level_data) {};

  Field.prototype.inheritanceOptions = function() {
    var ref;
    return (ref = this.FieldSchema) != null ? ref.inheritance : void 0;
  };

  Field.prototype.getCustomPlaceholder = function() {
    var ph, ref, ref1;
    ph = (ref = this.FieldSchema) != null ? (ref1 = ref.custom_settings) != null ? ref1.edit_user_placeholder_l10n : void 0 : void 0;
    if (CUI.util.isEmpty(ph)) {
      return null;
    }
    return ez5.loca.getBestFrontendValue(ph);
  };

  Field.prototype.isInherited = function() {
    var ref;
    if (!ez5.version("6")) {
      return false;
    }
    return (ref = this.inheritanceOptions()) != null ? ref.inherit : void 0;
  };

  Field.prototype.isInheritanceVisibleInDetail = function() {
    var ref;
    return (ref = this.inheritanceOptions()) != null ? ref.show_in_detail : void 0;
  };

  Field.prototype.hasMappingChildFields = function() {
    return false;
  };

  Field.prototype.getMappingChildFields = function() {
    return [];
  };

  Field.prototype.isValidMappingField = function(level, parentNode) {
    if (level == null) {
      level = 0;
    }
    return true;
  };

  Field.prototype.onServerValidationProblem = function(data, message, params) {
    var save_data;
    save_data = {};
    this.getSaveData(data, save_data, {});
    data[this.name() + ":validation_data"] = save_data;
  };

  Field.prototype.checkServerValidationProblemHandled = function(data, top_level_data, message, opts) {
    var save_data;
    save_data = {};
    this.getSaveData(data, save_data, {});
    return !CUI.util.isEqual(data[this.name() + ":validation_data"], save_data);
  };

  Field.fromSignature = function(signature) {
    var found, mask, mask_schema;
    CUI.util.assert(window[signature["class"]] === this, "Field.newFromSignature", "Function mismatch", {
      signature: signature
    });
    mask_schema = ez5.mask.CURRENT._mask_by_name[signature.mask.name];
    mask = new Mask("CURRENT", null, mask_schema);
    found = null;
    mask.invokeOnFields("all", true, (function(_this) {
      return function(f) {
        if (!(f instanceof Field) || found) {
          return;
        }
        if (f.fullName() === signature.field.name) {
          found = f;
        }
      };
    })(this));
    return found;
  };

  Field.focusFirstTextField = function(node, preventScroll) {
    var el, j, k, l, len, len1, order, ref, ref1, sel;
    if (preventScroll == null) {
      preventScroll = false;
    }
    CUI.util.assert(node instanceof HTMLElement, "FieldsRenderer.focusFirstField", "node needs to be instance of HTMLElement", {
      node: node
    });
    ref = [1, 2, 3, null];
    for (j = 0, len = ref.length; j < len; j++) {
      order = ref[j];
      ref1 = ["input:not(.ez5-query-element-input-search-input)", "textarea"];
      for (l = 0, len1 = ref1.length; l < len1; l++) {
        k = ref1[l];
        if (order !== null) {
          sel = (".ez5-standard-order[standard-order=\"" + order + "\"] ") + k;
        } else {
          sel = k;
        }
        el = CUI.dom.findElement(node, sel);
        if (el) {
          el.focus({
            preventScroll: preventScroll
          });
          return el;
        }
      }
    }
    return null;
  };

  Field.focusAndScrollToLabelOfFirstField = function(node, preventScroll) {
    var el, parentBlockNode;
    if (preventScroll == null) {
      preventScroll = false;
    }
    CUI.util.assert(node instanceof HTMLElement, "FieldsRenderer.focusAndScrollToField", "node needs to be instance of HTMLElement", {
      node: node
    });
    el = this.focusFirstTextField(node, preventScroll);
    if (el && !preventScroll) {
      parentBlockNode = CUI.dom.closest(el, ".ez5-field-block");
      if (parentBlockNode) {
        CUI.dom.scrollIntoView(parentBlockNode);
        parentBlockNode.scrollIntoView();
        return parentBlockNode;
      }
      el.scrollIntoView();
      return el;
    }
    return null;
  };

  Field.focusNextField = function(node) {
    var el;
    CUI.util.assert(node instanceof HTMLElement, "FieldsRenderer.focusNextField", "node needs to be instance of HTMLElement", {
      node: node
    });
    el = CUI.dom.findNextVisibleElement(node, "[tabindex]");
    if (el) {
      el.focus();
      return el;
    }
    return null;
  };

  return Field;

})(CUI.Dummy);

CUI.ready(function() {
  return CUI.Events.registerEvent({
    type: ["field-get-check-info", "field-check-field", "field-is-required"]
  });
});
// Generated by CoffeeScript 1.12.7
var CheckDataProblem,
  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;

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

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

  CheckDataProblem.prototype.initOpts = function() {
    CheckDataProblem.__super__.initOpts.call(this);
    return this.addOpts({
      field: {
        check: Field
      },
      text: {
        check: String
      },
      renderedField: {
        check: RenderedField
      },
      rowIndex: {
        check: "Integer",
        mandatory: false
      }
    });
  };

  CheckDataProblem.prototype.setProblemClass = function(cls) {
    var panelBody, panelHeader, rows, tab_body;
    if (!this._renderedField) {
      return;
    }
    if (CUI.util.isNumber(this._rowIndex)) {
      if (this._rowIndex === -1) {
        this._renderedField.addClass("ez5-check-failed-row");
      } else {
        rows = CUI.dom.matchSelector(this._renderedField.getElement(), "& > .ez5-field-block-content > .ez5-nested > .cui-data-form-row");
        if ((rows != null ? rows.length : void 0) && rows.length > this._rowIndex) {
          CUI.dom.addClass(rows[this._rowIndex], "ez5-check-failed-row");
        }
      }
    }
    this._renderedField.addClass(cls);
    if (!this._renderedField.getElement()) {
      return;
    }
    tab_body = CUI.dom.closest(this._renderedField.getElement(), ".cui-tab-body");
    if (tab_body) {
      CUI.dom.data(tab_body, "element").getButton().addClass("has-failed-content");
    }
    panelBody = CUI.dom.closest(this._renderedField.getElement(), ".cui-panel-body");
    if (panelBody) {
      panelHeader = CUI.dom.findPreviousSiblings(panelBody, ".cui-panel-header")[0];
      if (panelHeader) {
        CUI.dom.addClass(panelHeader, "has-failed-content");
      }
    }
  };

  CheckDataProblem.prototype.getProblemText = function() {
    var ref;
    if (CUI.util.isEmpty(this._text)) {
      return $$("check.data.problem.general", {
        field: (ref = this._field.fullNameLocalized()) != null ? ref.trim() : void 0
      });
    }
    return this._text;
  };

  CheckDataProblem.prototype.setRenderedField = function(renderedField) {
    this._renderedField = renderedField;
  };

  return CheckDataProblem;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var DataColumn,
  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;

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

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

  DataColumn.prototype.isEmpty = function(data, top_level_data) {
    return CUI.util.isEmpty(data[this.name()]);
  };

  DataColumn.prototype.renderData = function(data) {
    return [data[this.name()], data[(this.name()) + ":highlight"]];
  };

  DataColumn.prototype.isVisible = function(mode, opts) {
    var visible;
    visible = DataColumn.__super__.isVisible.call(this, mode, opts);
    if (!visible) {
      return false;
    }
    switch (mode) {
      case "detail-header":
      case "editor-header":
      case "editor-header-template":
      case "editor-header-bulk":
        return false;
      default:
        return true;
    }
  };

  DataColumn.prototype.renderStandard = function(standard, data) {
    var highlight, os, ref, value;
    os = this.getOutputStandard();
    if (!os) {
      return;
    }
    ref = this.renderData(data), value = ref[0], highlight = ref[1];
    standard.push({
      field: this,
      highlight: highlight,
      value: value,
      render_info: os
    });
    return this;
  };

  DataColumn.prototype.getCSVDestinationFields = function(csvImporter) {
    var dest_field;
    dest_field = {
      format: "string",
      field: this,
      csvImporter: csvImporter
    };
    return [new ObjecttypeCSVImporterDestinationField(dest_field)];
  };

  DataColumn.prototype.getDataAsString = function(data) {
    if (CUI.util.isEmpty(data[this.name()])) {
      return "";
    } else {
      return JSON.stringify(data[this.name()]);
    }
  };

  DataColumn.prototype.checkValue = function(data, top_level_data, opts) {
    var ref, v;
    v = data[this.name()];
    if (CUI.util.isEmpty(v)) {
      if (data[this.name() + ":append"]) {
        v = data[this.name() + ":append"];
      } else {
        v = (ref = data._template) != null ? ref[this.name()] : void 0;
      }
    }
    return this.checkBareValue(v, data, top_level_data, opts);
  };

  DataColumn.prototype.checkBareValue = function(v, data, top_level_data, opts) {
    var cs, err, re;
    cs = this.ColumnSchema || {};
    err = (function(_this) {
      return function(key) {
        var params;
        params = {
          field: _this.fullNameLocalized()
        };
        if (cs.check === "range") {
          params[key] = _this.__formatBareValue(cs[key]);
        } else if (key === "regexp") {
          params["regexp"] = cs.check_regexp;
        } else {
          params[key] = cs[key];
        }
        return $$("data.column.check." + key, params);
      };
    })(this);
    if (CUI.util.isEmpty(v) || CUI.util.isString(v) && v.trim() === "") {
      if (this.isRequired(data, top_level_data, opts)) {
        return err("required");
      } else {
        return true;
      }
    }
    if (cs.check === "not_empty") {
      if (v === false) {
        return err("not_empty");
      }
      if ((v + "").trim().length === 0) {
        return err("not_empty");
      }
    }
    if (cs.length_min > 0) {
      if (v.length < cs.length_min) {
        return err("length_min");
      }
    }
    if (cs.length_max > 0) {
      if (v.length > cs.length_max) {
        return err("length_max");
      }
    }
    switch (cs.check) {
      case "regexp":
        re = new RegExp(cs.check_regexp, cs.check_regexp_flags);
        if (re.exec(v)) {
          return true;
        } else {
          return err("regexp");
        }
        break;
      case "range":
        if (cs.hasOwnProperty("check_range_lower")) {
          if (v < cs.check_range_lower) {
            return err("check_range_lower");
          }
        } else if (cs.hasOwnProperty("check_range_lower_open")) {
          if (v <= cs.check_range_lower_open) {
            return err("check_range_lower_open");
          }
        }
        if (cs.hasOwnProperty("check_range_upper")) {
          if (v > cs.check_range_upper) {
            return err("check_range_upper");
          }
        } else if (cs.hasOwnProperty("check_range_upper_open")) {
          if (v >= cs.check_range_upper_open) {
            return err("check_range_upper_open");
          }
        }
        return true;
      case "email":
        if (CUI.EmailInput.regexp.exec(v)) {
          return true;
        } else {
          return err("email");
        }
    }
    return true;
  };

  DataColumn.prototype.getElementOpts = function(mode) {
    var opts;
    opts = {
      name: this.name(),
      type: CUI.Input
    };
    return opts;
  };

  DataColumn.prototype.getSearchFilterTokenized = function(val) {
    var f, filter, i, len, t, tokens;
    tokens = (this.getTokenizer()).tokenize(val);
    if (tokens.length === 0) {
      return;
    }
    if (tokens.length > 1) {
      filter = {
        type: "complex",
        search: []
      };
      for (i = 0, len = tokens.length; i < len; i++) {
        t = tokens[i];
        f = t.getFilter(this);
        if (!f) {
          continue;
        }
        f.bool = "should";
        filter.search.push(f);
      }
      if (filter.length === 0) {

      } else {
        return filter;
      }
    } else {
      return tokens[0].getFilter(this);
    }
  };

  DataColumn.prototype.getSortFunction = function() {
    return (function(_this) {
      return function(a, b) {
        return CUI.util.compareIndex(a[_this.name()], b[_this.name()]);
      };
    })(this);
  };

  DataColumn.prototype.getSearchField = function() {
    return this.fullName();
  };

  DataColumn.prototype.getSortFields = function() {
    return this.fullName();
  };

  return DataColumn;

})(Field);
// Generated by CoffeeScript 1.12.7
var AclField,
  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;

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

  function AclField(mask, FieldSchema) {
    this.mask = mask;
    this.FieldSchema = FieldSchema;
    AclField.__super__.constructor.call(this, this.mask, this.FieldSchema);
  }

  AclField.prototype.name = function() {
    return "_acl";
  };

  AclField.prototype.getDataForFieldData = function(data, top_level_data) {
    return top_level_data;
  };

  AclField.prototype.nameLocalized = function() {
    return $$("acl.field.name");
  };

  AclField.prototype.isSourceForMapping = function(required_type) {
    return false;
  };

  AclField.prototype.isExpertCommon = function(mode) {
    return true;
  };

  AclField.prototype.isExpertCommonOnly = function(mode) {
    return false;
  };

  AclField.prototype.renderHalfWidth = function() {
    return true;
  };

  AclField.prototype.isEmpty = function(data, top_level_data, opts) {
    var ref;
    if (((ref = top_level_data[this.name()]) != null ? ref.length : void 0) > 0) {
      return false;
    } else {
      return true;
    }
  };

  AclField.prototype.isVisible = function(mode, opts) {
    var isVisible;
    if (opts == null) {
      opts = {};
    }
    if (CUI.util.isFunction(opts.isVisible)) {
      isVisible = opts.isVisible(this, mode, opts);
      if (CUI.util.isBoolean(isVisible)) {
        return isVisible;
      }
    }
    if (mode === "editor-header" || mode === "editor-header-template" || mode === "editor-header-bulk") {
      if (this.mask.schema.system_fields.acl.edit.mode === "off") {
        return false;
      } else {
        return true;
      }
    } else if (mode === "detail-footer" && this.mask.schema.system_fields.acl.output.mode !== "off") {
      return true;
    } else {
      return false;
    }
  };

  AclField.prototype.isReadOnly = function(data, top_level_data) {
    var ref;
    if (this.mask.schema.system_fields.acl.edit.mode === "show") {
      return true;
    } else if (!(top_level_data != null ? (ref = top_level_data._generated_rights) != null ? ref.acl : void 0 : void 0)) {
      return true;
    } else {
      return false;
    }
  };

  AclField.prototype.renderEditorInput = function(data, top_level_data, opts) {
    var bulk, df, div, empty_loca_key, expert_menu, footer_right, o, options, ref, ref1, sticky;
    if (!top_level_data[this.name()]) {
      top_level_data[this.name()] = [];
    }
    bulk = (ref = opts.mode) === "editor-bulk" || ref === "editor-header-bulk";
    sticky = this.mask.isHierarchy();
    expert_menu = ["preset", "right"];
    if (sticky) {
      expert_menu.push("sticky");
    }
    if (this.mask.isHierarchy()) {
      footer_right = new CUI.Checkbox({
        data: top_level_data,
        name: "_private_acl",
        text: $$("acl.field.private_acl")
      }).start();
    }
    this.aclManager = new AclManager({
      data: CUI.util.copyObject(top_level_data[this.name()], true),
      preset: true,
      sticky: sticky,
      context: this,
      onUpdate: (function(_this) {
        return function() {
          var acl_data, e;
          try {
            acl_data = _this.aclManager.getSaveData();
            top_level_data[_this.name()] = acl_data;
          } catch (error) {
            e = error;
            if (e instanceof InvalidSaveDataException) {
              return;
            } else {
              throw e;
            }
          }
        };
      })(this),
      expert_menu: expert_menu,
      footer_right: footer_right
    });
    if (((ref1 = opts.editor) != null ? ref1.editor_data.mode : void 0) === "new" && top_level_data._template) {
      empty_loca_key = "acl.field.set_by_template";
    }
    opts = this.aclManager.getField({
      empty_loca_key: empty_loca_key
    });
    opts.id = this.idAttribute(data);
    df = CUI.DataField["new"](opts).start();
    CUI.Events.listen({
      type: "data-changed",
      node: df,
      call: function(ev, info) {
        return CUI.Events.trigger({
          type: "editor-changed",
          node: df
        });
      }
    });
    if (!bulk) {
      return df.DOM;
    }
    div = CUI.dom.div("ez5-acl-field-group-mode");
    CUI.dom.append(div, df.DOM);
    options = (function() {
      var i, len, ref2, results;
      ref2 = ["add", "replace", "remove_all"];
      results = [];
      for (i = 0, len = ref2.length; i < len; i++) {
        o = ref2[i];
        results.push("bulk_acl_" + o);
      }
      return results;
    })();
    CUI.dom.append(div, this.getBulkOptionsForm(options, data, "mode"));
    return div;
  };

  AclField.prototype.getDataAsString = function(data, top_level_data) {
    var str;
    str = JSON.stringify({
      _acl: top_level_data._acl,
      _private_acl: top_level_data._private_acl
    });
    return str;
  };

  AclField.prototype.getSaveData = function(data, save_data, opts) {
    var acl, i, item, len, ref;
    if (data == null) {
      data = null;
    }
    if (opts == null) {
      opts = {};
    }
    if (opts.demo_data) {
      save_data._top_level._acl = [];
      return;
    }
    acl = data._top_level[this.name()] || [];
    if (acl.length === 0 && data._top_level._template) {
      acl = data._top_level._template[this.name()] || [];
    }
    if (opts.copy) {
      save_data._top_level._acl = [];
      ref = CUI.util.copyObject(acl, true);
      for (i = 0, len = ref.length; i < len; i++) {
        item = ref[i];
        delete item._id;
        delete item.date_created;
        save_data._top_level._acl.push(item);
      }
    } else {
      save_data._top_level._acl = acl;
    }
    if (this.mask.isHierarchy()) {
      save_data._top_level._private_acl = !!data._top_level._private_acl;
    }
    return this.getBulkSaveData(data, save_data._top_level, opts, "mode");
  };

  AclField.prototype.checkValue = function(data, top_level_data, opts) {
    var ref;
    if (this.getOption(data, "bulk")) {
      if (this.getOption(data, "mode") !== "bulk_acl_remove_all") {
        if (!((ref = top_level_data[this.name()]) != null ? ref.length : void 0)) {
          return false;
        }
      }
    }
    return AclField.__super__.checkValue.call(this, data, top_level_data, opts);
  };

  AclField.prototype.renderDetailOutput = function(data, top_level_data, opts) {
    var count, ref;
    count = (ref = top_level_data[this.name()]) != null ? ref.length : void 0;
    if (count > 0) {
      return new CUI.Label({
        text: $$("acl.field.display.rights", {
          count: count
        })
      });
    } else {
      return new CUI.EmptyLabel({
        text: $$("acl.field.display.empty-rights")
      });
    }
  };

  AclField.prototype.isTopLevelField = function() {
    return true;
  };

  AclField.prototype.fullName = function() {
    return this.name();
  };

  return AclField;

})(Field);
// Generated by CoffeeScript 1.12.7
var BooleanColumn,
  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;

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

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

  BooleanColumn.prototype.getSearchFilter = function(data, key) {
    var filter, value;
    if (key == null) {
      key = this.name();
    }
    filter = BooleanColumn.__super__.getSearchFilter.call(this, data, key);
    if (filter) {
      return filter;
    }
    value = data[key];
    if (CUI.util.isEmpty(value)) {
      return;
    }
    if (value === "false") {
      filter = {
        type: "in",
        fields: [this.getSearchField()],
        "in": [false]
      };
    } else {
      filter = {
        type: "in",
        fields: [this.getSearchField()],
        "in": [true]
      };
    }
    return filter;
  };

  BooleanColumn.prototype.getSortFunction = function() {
    return (function(_this) {
      return function(a, b) {
        if (a[_this.name()] === b[_this.name()]) {
          return 0;
        } else if (a[_this.name()]) {
          return 1;
        } else {
          return -1;
        }
      };
    })(this);
  };

  BooleanColumn.prototype.getOutputStandard = function() {
    return null;
  };

  BooleanColumn.prototype.getCSVDestinationFields = function(csvImporter) {
    var opts;
    opts = {
      csvImporter: csvImporter,
      field: this
    };
    return [new BooleanColumnCSVImporterDestinationField(opts)];
  };

  BooleanColumn.prototype.getQueryFieldBadge = function(data) {
    var badge, key, value;
    if (CUI.util.isNull(data[this.name()])) {
      badge = {
        name: this.nameLocalized(),
        value: $$("eas.column.search.without")
      };
      return badge;
    }
    if (data[this.name()] === "true") {
      key = "boolean.column.search.true";
    } else {
      key = "boolean.column.search.false";
    }
    value = $$(key);
    return {
      name: this.nameLocalized(),
      value: value + (" (" + (this.nameLocalized()) + ")"),
      popoverContent: CUI.util.dump(this.getSearchFilter(data))
    };
  };

  BooleanColumn.prototype.renderSearchInput = function(data) {
    var select;
    return select = new CUI.Select({
      name: this.name(),
      data: data,
      id: this.idAttribute(data),
      ui: "boolean.column.search:" + (this.name()),
      onDataChanged: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            node: select,
            type: "search-input-change"
          });
        };
      })(this),
      options: [
        {
          text: "",
          value: null
        }, {
          text: $$("boolean.column.search.true"),
          value: "true"
        }, {
          text: $$("boolean.column.search.false"),
          value: "false"
        }
      ]
    }).start().DOM;
  };

  BooleanColumn.prototype.getSaveData = function(data, save_data, opts) {
    var ref;
    if (opts == null) {
      opts = {};
    }
    if (data[this.name()] || (((ref = data._template) != null ? ref[this.name()] : void 0) && !data[this.name() + ":changed"]) || opts.demo_data) {
      save_data[this.name()] = true;
    } else {
      save_data[this.name()] = false;
    }
    return save_data;
  };

  BooleanColumn.prototype.hasUserData = function(data) {
    return !!data[this.name()];
  };

  BooleanColumn.prototype.isRequired = function() {
    return false;
  };

  BooleanColumn.prototype.checkValue = function(data, top_level_data, opts) {
    return true;
  };

  BooleanColumn.prototype.renderEditorInput = function(data) {
    var cb, ref, ref1;
    if (!CUI.util.isUndef((ref = data._template) != null ? ref[this.name()] : void 0)) {
      if (!data[this.name() + ":changed"]) {
        if ((ref1 = data._template) != null ? ref1[this.name()] : void 0) {
          data[this.name()] = true;
        } else {
          data[this.name()] = false;
        }
      }
    }
    return cb = new CUI.Checkbox({
      name: this.name(),
      data: data,
      text_active: $$("boolean.column.editor.true"),
      text_inactive: $$("boolean.column.editor.true"),
      id: this.idAttribute(data),
      onDataChanged: (function(_this) {
        return function() {
          data[_this.name() + ":changed"] = true;
          return CUI.Events.trigger({
            type: "editor-changed",
            node: cb
          });
        };
      })(this)
    }).start().DOM;
  };

  BooleanColumn.prototype.isEmpty = function(data) {
    var booleanShowFalseSetting, ref;
    booleanShowFalseSetting = (ref = this.FieldSchema.custom_settings) != null ? ref.boolean_show_false : void 0;
    return booleanShowFalseSetting === false && !data[this.name()];
  };

  BooleanColumn.prototype.renderDetailOutput = function(data) {
    var hideLabel, isCondensedOutput, key, ref, ref1, text;
    key = "boolean.column.detail." + !!data[this.name()];
    hideLabel = (ref = this.FieldSchema.custom_settings) != null ? ref.hide_label : void 0;
    if (this.insideNested()) {
      isCondensedOutput = (ref1 = this.getFatherField().FieldSchema.custom_settings) != null ? ref1.condensed_output : void 0;
    }
    if (isCondensedOutput) {
      text = this.nameLocalized();
      if (hideLabel) {
        if (!value) {
          return null;
        }
      } else {
        text += ": " + ($$(key));
      }
    } else {
      text = $$(key);
      if (hideLabel) {
        text = (this.nameLocalized()) + ": " + text;
      }
    }
    return new CUI.Label({
      text: text
    });
  };

  BooleanColumn.prototype.isExpertCommon = function(mode) {
    return true;
  };

  BooleanColumn.prototype.getFacet = function(opts) {
    opts.field = this;
    return new ez5.BooleanFacet(opts);
  };

  BooleanColumn.prototype.supportsFacet = function() {
    return true;
  };

  BooleanColumn.prototype.updateEditorInputValue = function(value, top_level_data) {
    var data;
    data = top_level_data[top_level_data._objecttype];
    if (CUI.util.isEmpty(data._id) && value !== data[this.name()]) {
      this.updateValue(data, value);
      return;
    }
  };

  BooleanColumn.prototype.updateValue = function(data, value) {
    var element, fieldData;
    data[this.name()] = value;
    fieldData = data[this.name() + ":rendered"];
    element = fieldData != null ? fieldData.getElement() : void 0;
    if (!element) {
      return;
    }
    CUI.Events.trigger({
      node: element,
      type: "editor-changed"
    });
    return this;
  };

  return BooleanColumn;

})(DataColumn);
// Generated by CoffeeScript 1.12.7
var ChangelogColumn, ChangelogColumnForCollection, ChangelogColumnSearchComment,
  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,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

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

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

  ChangelogColumn.prototype.isVisible = function(mode, opts) {
    var isVisible;
    if (opts == null) {
      opts = {};
    }
    if (CUI.util.isFunction(opts.isVisible)) {
      isVisible = opts.isVisible(this, mode, opts);
      if (CUI.util.isBoolean(isVisible)) {
        return isVisible;
      }
    }
    if (mode === "expert" || mode === "sort") {
      if (ez5.session.hasSystemRight("root", "frontend_features[changelog]")) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  };

  ChangelogColumn.prototype.name = function() {
    return "_changelog";
  };

  ChangelogColumn.prototype.getMappingSourceFullNameLocalized = function() {
    return this.fullNameLocalized();
  };

  ChangelogColumn.prototype.isSourceForMapping = function(required_type) {
    return false;
  };

  ChangelogColumn.prototype.getReplacementRecord = function() {};

  ChangelogColumn.prototype.nameLocalized = function() {
    return $$("changelog.column.name");
  };

  ChangelogColumn.prototype.isExpertCommon = function() {
    return true;
  };

  ChangelogColumn.prototype.getQueryFieldBadge = function(data) {
    return {
      name: this.nameLocalized(),
      value: this.getSearchInfo(data).join(" & ")
    };
  };

  ChangelogColumn.prototype.sortExtraOpts = function(data) {
    var i, j, len, len1, mode, modes, opts, width, widths;
    if (!ez5.version("6")) {
      return [
        {
          text: $$("changelog.column.created"),
          value: "created"
        }, {
          text: $$("changelog.column.updated"),
          value: "updated"
        }
      ];
    }
    opts = [];
    modes = ["created", "updated"];
    widths = ["day", "week", "month", "year"];
    for (i = 0, len = modes.length; i < len; i++) {
      mode = modes[i];
      for (j = 0, len1 = widths.length; j < len1; j++) {
        width = widths[j];
        if (width === "none") {
          opts.push({
            text: $$("changelog.column." + mode),
            value: mode
          });
        } else {
          opts.push({
            text: $$("changelog.column." + mode + "." + width),
            value: mode + ":" + width
          });
        }
      }
    }
    return opts;
  };

  ChangelogColumn.prototype.isSortUnique = function() {
    return true;
  };

  ChangelogColumn.prototype.isSortGroupable = function() {
    return true;
  };

  ChangelogColumn.prototype.getSortFields = function(filter, keys, activeFilters) {
    var f, field_name, fields, i, len, mode, nFilters, parts, ref, ref1, sort_field, width;
    mode = null;
    width = null;
    if ((ref = filter._extra) != null ? ref.includes(":") : void 0) {
      parts = filter._extra.split(":");
      mode = parts[0];
      width = parts[1];
    } else {
      mode = filter._extra;
    }
    if (mode === "created") {
      field_name = "_changelog.date_created";
    } else {
      field_name = "_changelog.date_last_updated";
    }
    sort_field = {
      field: field_name,
      order: filter._order
    };
    if (ez5.version("6.12") && width && width !== "none") {
      sort_field.width = width;
      sort_field.group_field = field_name;
      fields = [sort_field];
      nFilters = 0;
      ref1 = ["_1", "_2", "_3"];
      for (i = 0, len = ref1.length; i < len; i++) {
        f = ref1[i];
        if (activeFilters[f]) {
          nFilters++;
        }
      }
      if (nFilters === 1) {
        fields.push({
          field: field_name,
          order: filter._order
        });
      }
      if (!activeFilters) {
        return fields[0];
      }
      if ((filter._key === "_1" && CUI.util.isEmpty(activeFilters["_2"]) && CUI.util.isEmpty(activeFilters["_3"])) || (filter._key === "_2" && CUI.util.isEmpty(activeFilters["_3"])) || (filter._key === "_3")) {
        fields.push({
          field: "_system_object_id",
          order: filter._order
        });
        return fields;
      } else {
        return fields[0];
      }
    } else {
      sort_field.group_field = field_name;
      fields = [sort_field];
      if (!activeFilters) {
        return fields[0];
      }
      if ((filter._key === "_1" && CUI.util.isEmpty(activeFilters["_2"]) && CUI.util.isEmpty(activeFilters["_3"])) || (filter._key === "_2" && CUI.util.isEmpty(activeFilters["_3"])) || (filter._key === "_3")) {
        fields.push({
          field: "_system_object_id",
          order: filter._order
        });
        return fields;
      } else {
        return fields[0];
      }
    }
  };

  ChangelogColumn.prototype.formatSortGroupable = function(item, filter) {
    var locale, locales, parts, ref, width;
    if (!ez5.version("6.12")) {
      return ez5.format_date(item);
    }
    if ((ref = filter._extra) != null ? ref.includes(":") : void 0) {
      parts = filter._extra.split(":");
      width = parts[1];
      if (width && width !== "none") {
        locale = CUI.DateTime.getLocale();
        locales = ez5.session.getPref("database_languages") || [];
        if (CUI.util.isEmpty(locales)) {
          locales = ez5.session.getConfigDatabaseLanguages();
        }
        locale = locales[0] || locale;
        return CUI.DateTime.formatGroupLabel(item, width, locale);
      }
    }
    return ez5.format_date(item);
  };

  ChangelogColumn.prototype.getSearchInfo = function(data) {
    var info;
    info = [];
    if (!this.getSearchFilter(data)) {
      return info;
    }
    if (data.who) {
      info.push(AclWho.newInstance(data.who).getDisplayText());
    }
    if (data.operation) {
      info.push($$("changelog.column.popover.form.operation." + data.operation.toLowerCase()));
    }
    if (data.from) {
      info.push($$("changelog.column.popover.from"));
    }
    if (data.to) {
      info.push($$("changelog.column.popover.to"));
    }
    if (!CUI.util.isEmpty(data.comment)) {
      info.push($$("changelog.column.popover.comment"));
    }
    if (info.length === 0) {
      return;
    }
    return info;
  };

  ChangelogColumn.prototype.getSearchFilter = function(data, key, for_collection) {
    var base, comment, filter, from, phrase, ref, search, to, user_id;
    if (key == null) {
      key = this.name();
    }
    if (for_collection == null) {
      for_collection = false;
    }
    if (!(data.who || data.from || data.to || !CUI.util.isEmpty(data.comment))) {
      return;
    }
    search = [];
    if (data.who) {
      user_id = (typeof (base = AclWho.newInstance(data.who)).getId === "function" ? base.getId() : void 0) || null;
    } else {
      user_id = null;
    }
    if (!CUI.util.isEmpty(data.from)) {
      from = ez5.version("6") ? new Date(data.from).toISOString() : data.from;
    } else {
      from = void 0;
    }
    if (!CUI.util.isEmpty(data.to)) {
      to = ez5.version("6") ? new Date(data.to).toISOString() : data.to;
    } else {
      to = void 0;
    }
    if (!CUI.util.isEmpty(data.comment)) {
      ref = Search.getPhrase(data.comment), comment = ref[0], phrase = ref[1];
    } else {
      comment = void 0;
    }
    if (!from && !to) {
      to = "2200-11-07T08:39:00-05:00";
    }
    search.push({
      type: "changelog_range",
      user: user_id,
      operation: data.operation,
      from: from,
      to: to,
      comment: comment
    });
    filter = {
      type: "complex",
      bool: "must",
      search: search
    };
    if (for_collection) {
      return filter;
    } else {
      return {
        type: "complex",
        search: [
          {
            type: "in",
            bool: "must",
            fields: ["_objecttype"],
            "in": [this.path()]
          }, filter
        ]
      };
    }
  };

  ChangelogColumn.prototype.getSaveData = function() {};

  ChangelogColumn.prototype.renderSearchInput = function(data) {
    var inp;
    inp = new CUI.FormPopover({
      data: data,
      undo_and_changed_support: false,
      button: {
        loca_key: "changelog.column.search.button"
      },
      trigger_data_changed_while_open: true,
      popover: {
        onHide: (function(_this) {
          return function() {
            return CUI.Events.trigger({
              node: inp,
              type: "search-input-change"
            });
          };
        })(this)
      },
      fields: (function(_this) {
        return function() {
          return _this.getPopoverFields(data);
        };
      })(this),
      renderDisplayContent: (function(_this) {
        return function() {
          return ez5.renderFormPopoverInfo(_this.getSearchInfo(data));
        };
      })(this)
    });
    inp.start();
    return inp;
  };

  ChangelogColumn.prototype.getPopoverFields = function(data) {
    var changelogSearchColumn, searchComment;
    changelogSearchColumn = new ChangelogColumnSearchComment(this.mask, this.FieldSchema);
    searchComment = (new SearchToken({
      column: changelogSearchColumn,
      data: data
    })).getInput();
    return [
      {
        type: UserGroupSelector,
        form: {
          label: $$("changelog.column.popover.form.who")
        },
        undo_and_changed_support: false,
        aclWhoManager: new AclWhoManager({
          who_filter: ["user"]
        }),
        name: "who",
        data: data
      }, {
        form: {
          label: $$("changelog.column.popover.form.operation")
        },
        type: CUI.Select,
        undo_and_changed_support: false,
        name: "operation",
        options: [
          {
            text: $$("changelog.column.popover.form.operation.any"),
            value: null
          }, {
            text: $$("changelog.column.popover.form.operation.insert"),
            value: "INSERT"
          }, {
            text: $$("changelog.column.popover.form.operation.update"),
            value: "UPDATE"
          }
        ]
      }, {
        type: CUI.DateTime,
        undo_and_changed_support: false,
        placeholder: $$("changelog.column.popover.form.from|placeholder"),
        form: {
          label: $$("changelog.column.popover.form.from")
        },
        name: "from"
      }, {
        type: CUI.DateTime,
        undo_and_changed_support: false,
        placeholder: $$("changelog.column.popover.form.to|placeholder"),
        form: {
          label: $$("changelog.column.popover.form.to")
        },
        name: "to"
      }, {
        type: CUI.DataFieldProxy,
        form: {
          label: $$("changelog.column.popover.form.comment")
        },
        undo_and_changed_support: false,
        name: "comment",
        element: searchComment
      }
    ];
  };

  ChangelogColumn.prototype.getSearchUnsetElement = function(data) {};

  ChangelogColumn.prototype.isTopLevelField = function() {
    return true;
  };

  ChangelogColumn.prototype.fullName = function() {
    return this.name();
  };

  return ChangelogColumn;

})(Field);

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

  function ChangelogColumnForCollection(opts1) {
    this.opts = opts1 != null ? opts1 : {};
  }

  ChangelogColumnForCollection.prototype.getSearchFilter = function(data) {
    return ChangelogColumnForCollection.__super__.getSearchFilter.call(this, data, this.name(), true);
  };

  return ChangelogColumnForCollection;

})(ChangelogColumn);

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

  function ChangelogColumnSearchComment() {
    this.getElementOpts = bind(this.getElementOpts, this);
    return ChangelogColumnSearchComment.__super__.constructor.apply(this, arguments);
  }

  ChangelogColumnSearchComment.prototype.fullName = function() {
    return "_changelog.comment";
  };

  ChangelogColumnSearchComment.prototype.name = function() {
    return "comment";
  };

  ChangelogColumnSearchComment.prototype.getElementOpts = function() {
    return {
      type: CUI.Input,
      name: "comment"
    };
  };

  return ChangelogColumnSearchComment;

})(ChangelogColumn);
// Generated by CoffeeScript 1.12.7
var CollectionsField,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  CollectionsField.prototype.isVisible = function(mode, opts) {
    var isVisible, ref, ref1;
    if (opts == null) {
      opts = {};
    }
    if (CUI.util.isFunction(opts.isVisible)) {
      isVisible = opts.isVisible(this, mode, opts);
      if (CUI.util.isBoolean(isVisible)) {
        return isVisible;
      }
    }
    if (opts.new_mode) {
      return false;
    } else if (mode === "detail-footer" && ((ref = this.mask.schema.system_fields.collections) != null ? ref.output.mode : void 0) !== "off") {
      return true;
    } else if (mode === "editor-footer" && ((ref1 = this.mask.schema.system_fields.collections) != null ? ref1.edit.mode : void 0) !== "off") {
      return true;
    } else if (mode === "expert" && ez5.version("6")) {
      return true;
    } else {
      return false;
    }
  };

  CollectionsField.prototype.isExpertCommon = function() {
    return true;
  };

  CollectionsField.prototype.getReplacementRecord = function() {};

  CollectionsField.prototype.getDataForFieldData = function(data, top_level_data) {
    return top_level_data;
  };

  CollectionsField.prototype.isEmpty = function(data, top_level_data) {
    var ref;
    if (((ref = top_level_data._collections) != null ? ref.length : void 0) > 0) {
      return false;
    } else {
      return true;
    }
  };

  CollectionsField.prototype.nameLocalized = function() {
    return $$("collections_field.label");
  };

  CollectionsField.prototype.fillReplacementRecord = function() {};

  CollectionsField.prototype.getDataAsString = function() {
    return true;
  };

  CollectionsField.prototype.name = function() {
    return "_collections";
  };

  CollectionsField.prototype.isTopLevelField = function() {
    return true;
  };

  CollectionsField.prototype.fullName = function() {
    return this.name();
  };

  CollectionsField.prototype.getOutputStandard = function() {};

  CollectionsField.prototype.renderEditorInput = function(data, top_level_data, opts) {
    return this.renderDetailOutput(data, top_level_data, opts);
  };

  CollectionsField.prototype.renderSearchInput = function(data, top_level_data) {
    var autocompletion, browseBtn, container, executeSearch, input, inputLayout, inputWrapper, key, renderTags, tagsDiv, triggerChange;
    key = this.name();
    if (!data[key]) {
      data[key] = [];
    }
    container = CUI.dom.div("ez5-collections-field-search");
    tagsDiv = CUI.dom.div("ez5-collections-field-search-tags ez5-tags");
    input = CUI.dom.element("INPUT", {
      "class": "ez5-collections-field-search-input",
      placeholder: $$("collections_field.search.placeholder")
    });
    inputWrapper = CUI.dom.div("ez5-collections-field-search-input-wrapper");
    CUI.dom.append(inputWrapper, input);
    browseBtn = new CUI.Button({
      "class": "ez5-collections-field-search-browse-button",
      icon: "ellipsis_v",
      onClick: (function(_this) {
        return function() {
          return _this.__showCollectionPicker(data, key, renderTags, triggerChange);
        };
      })(this)
    });
    inputLayout = new CUI.HorizontalLayout({
      maximize_horizontal: true,
      "class": "ez5-collections-field-search-combobox",
      center: {
        content: inputWrapper
      },
      right: {
        content: browseBtn
      }
    });
    CUI.dom.append(container, inputLayout.DOM);
    CUI.dom.append(container, tagsDiv);
    autocompletion = new AutocompletionPopup({
      element: inputWrapper
    });
    autocompletion.addContainer("collections");
    triggerChange = (function(_this) {
      return function() {
        return CUI.Events.trigger({
          type: "search-input-change",
          node: container
        });
      };
    })(this);
    renderTags = (function(_this) {
      return function() {
        var colId, fn, i, len, ref, tagLabelsById;
        CUI.dom.empty(tagsDiv);
        tagLabelsById = {};
        ref = data[key];
        fn = function(colId) {
          var removeBtn, tagLabel;
          tagLabel = new CUI.Label({
            "class": "ez5-tag ez5-collections-field-search-tag",
            icon: "folder",
            text: colId.toString()
          });
          tagLabelsById[colId] = tagLabel;
          removeBtn = new CUI.Button({
            icon: "remove",
            appearance: "flat",
            size: "mini",
            tabindex: false,
            "class": "ez5-collections-field-search-tag-remove",
            onClick: function() {
              CUI.util.removeFromArray(colId, data[key]);
              renderTags();
              return triggerChange();
            }
          });
          CUI.dom.append(tagLabel.DOM, removeBtn.DOM);
          return CUI.dom.append(tagsDiv, tagLabel.DOM);
        };
        for (i = 0, len = ref.length; i < len; i++) {
          colId = ref[i];
          fn(colId);
        }
        if (data[key].length > 0) {
          ez5.api.search({
            json_data: {
              type: "collection",
              limit: data[key].length,
              search: [
                {
                  type: "in",
                  bool: "must",
                  fields: ["collection._id"],
                  "in": data[key]
                }
              ]
            }
          }).done(function(result) {
            var j, label, len1, obj, ref1, results;
            ref1 = result.objects;
            results = [];
            for (j = 0, len1 = ref1.length; j < len1; j++) {
              obj = ref1[j];
              label = tagLabelsById[obj.collection._id];
              if (label) {
                label.setText(ez5.loca.getBestDatabaseValue(obj.collection.displayname));
                results.push(label.setIcon(AddToCollectionHelper.getCollectionIcon(obj)));
              } else {
                results.push(void 0);
              }
            }
            return results;
          });
        }
      };
    })(this);
    executeSearch = (function(_this) {
      return function() {
        var phrase, ref, s, searchData, str;
        str = input.value.trim();
        if (str.length === 0) {
          autocompletion.hide();
          return;
        }
        searchData = [
          {
            type: "match",
            bool: "must",
            mode: ez5.version("6") ? "wildcard" : "fulltext",
            fields: ["collection.displayname"],
            string: ez5.version("6") ? str + SearchUtil.ASTERISK : str
          }, {
            type: "complex",
            bool: "must",
            search: [
              {
                type: "in",
                bool: "should",
                fields: ["_owner.user._id"],
                "in": [ez5.session.getUser().getId()]
              }, {
                type: "in",
                bool: "should",
                fields: ["_owner.group._id"],
                "in": ez5.session.getGroupIds()
              }, {
                type: "in",
                bool: "should",
                fields: ["_has_acl"],
                "in": [true]
              }
            ]
          }, {
            type: "in",
            bool: "must_not",
            fields: ["collection.type"],
            "in": ["search"]
          }
        ];
        if (!ez5.version("6")) {
          ref = Search.getPhrase(str), s = ref[0], phrase = ref[1];
          searchData[0].phrase = phrase;
          searchData[0].string = s;
        }
        ez5.api.search({
          json_data: {
            type: "collection",
            limit: 10,
            search: searchData
          }
        }).done(function(result) {
          var collections, fn, i, item, len, obj;
          autocompletion.emptyContainer();
          collections = result.objects.filter(function(obj) {
            return !obj.collection.is_system_collection;
          });
          if (collections.length === 0) {
            item = CUI.dom.div("ez5-collections-field-search-no-results ez5-item-not-selectable");
            item.textContent = $$("collections_field.search.no_results");
            autocompletion.appendItem("collections", item);
          } else {
            fn = function(obj) {
              var colId, isAlreadySelected, itemClass, name, popupItem;
              colId = obj.collection._id;
              name = ez5.loca.getBestDatabaseValue(obj.collection.displayname);
              isAlreadySelected = indexOf.call(data[key], colId) >= 0;
              itemClass = "autocomplete-item";
              if (isAlreadySelected) {
                itemClass += " ez5-item-not-selectable";
              }
              item = CUI.dom.div(itemClass);
              item.textContent = name || colId.toString();
              popupItem = autocompletion.appendItem("collections", item);
              if (!isAlreadySelected) {
                return CUI.Events.listen({
                  type: "click",
                  node: popupItem,
                  call: function() {
                    if (indexOf.call(data[key], colId) < 0) {
                      data[key].push(colId);
                      renderTags();
                      triggerChange();
                    }
                    input.value = "";
                    return autocompletion.hide();
                  }
                });
              }
            };
            for (i = 0, len = collections.length; i < len; i++) {
              obj = collections[i];
              fn(obj);
            }
          }
          autocompletion.show();
          return autocompletion.autoSize();
        });
      };
    })(this);
    CUI.Events.listen({
      type: "keydown",
      node: input,
      call: (function(_this) {
        return function(ev) {
          return autocompletion.keydown(ev);
        };
      })(this)
    });
    CUI.Events.listen({
      type: "keyup",
      node: input,
      call: (function(_this) {
        return function(ev) {
          autocompletion.keyup(ev);
          if (ev.isPropagationStopped()) {
            return;
          }
          ev.stopPropagation();
          if (ev.getKeyboardKey() === "Esc") {
            if (autocompletion.isShown()) {
              autocompletion.hide();
            }
            return;
          }
          CUI.scheduleCallback({
            ms: 300,
            call: executeSearch
          });
        };
      })(this)
    });
    renderTags();
    return container;
  };

  CollectionsField.prototype.__showCollectionPicker = function(data, key, renderTags, triggerChange) {
    return AddToCollectionHelper.showCollectionPicker(null, null, (function(_this) {
      return function(selectedCollection) {
        var colData, colId;
        colData = selectedCollection.getData();
        colId = colData.collection._id;
        if (indexOf.call(data[key], colId) < 0) {
          data[key].push(colId);
          renderTags();
          return triggerChange();
        }
      };
    })(this), {
      browseOnly: true,
      multiSelect: true,
      disabledIds: data[key].slice(0)
    });
  };

  CollectionsField.prototype.getSearchFilter = function(data, key) {
    var filter;
    if (key == null) {
      key = this.name();
    }
    filter = this.getUnsetSearchFilter(data, key);
    if (filter) {
      return filter;
    }
    if (CUI.util.isEmpty(data[key])) {
      return;
    }
    return {
      type: "in",
      bool: "must",
      fields: ["_collections._id"],
      "in": data[key]
    };
  };

  CollectionsField.prototype.getSearchField = function() {
    return ["_collections._id"];
  };

  CollectionsField.prototype.getQueryFieldBadge = function(data) {
    var dfr, ids, key;
    key = this.name();
    if (data[key + ":unset"]) {
      return {
        name: this.nameLocalized(),
        value: $$("collections_field.search.badge.without")
      };
    }
    if (data[key + ":has_value"]) {
      return {
        name: this.nameLocalized(),
        value: $$("collections_field.search.badge.has_value")
      };
    }
    ids = data[key];
    if (CUI.util.isEmpty(ids)) {
      return {
        name: this.nameLocalized(),
        value: ""
      };
    }
    dfr = new CUI.Deferred();
    ez5.api.search({
      json_data: {
        type: "collection",
        limit: ids.length,
        search: [
          {
            type: "in",
            bool: "must",
            fields: ["collection._id"],
            "in": ids
          }
        ]
      }
    }).done((function(_this) {
      return function(result) {
        var i, len, name, names, obj, ref;
        names = [];
        ref = result.objects;
        for (i = 0, len = ref.length; i < len; i++) {
          obj = ref[i];
          name = ez5.loca.getBestDatabaseValue(obj.collection.displayname);
          if (name) {
            names.push(name);
          }
        }
        return dfr.resolve({
          name: _this.nameLocalized(),
          value: names.join(", ")
        });
      };
    })(this)).fail((function(_this) {
      return function() {
        return dfr.resolve({
          name: _this.nameLocalized(),
          value: ids.join(", ")
        });
      };
    })(this));
    return dfr.promise();
  };

  CollectionsField.prototype.renderDetailOutput = function(data, top_level_data, opts) {
    var col, div, ref, ref1, search, set_empty;
    div = CUI.dom.div("ez5-collections-field-collections");
    set_empty = function(key) {
      return CUI.dom.append(div, new CUI.EmptyLabel({
        text: $$(key)
      }).DOM);
    };
    if (this.isEmpty(data, top_level_data)) {
      switch (opts.mode) {
        case "detail-footer":
        case "editor-footer":
          return;
      }
      set_empty("collections_field.no_collections");
    } else {
      if (((ref = opts.detail) != null ? ref.getSearch : void 0) && !opts.for_print) {
        search = opts.detail.getMainSearch();
      }
      if ((ref1 = opts.editor) != null ? ref1.getSearch : void 0) {
        search = opts.editor.getSearch();
      }
      ez5.api.search({
        json_data: {
          type: "collection",
          limit: 10,
          search: [
            {
              type: "in",
              bool: "must",
              fields: ["collection._id"],
              "in": (function() {
                var i, len, ref2, results;
                ref2 = top_level_data._collections;
                results = [];
                for (i = 0, len = ref2.length; i < len; i++) {
                  col = ref2[i];
                  results.push(col._id);
                }
                return results;
              })()
            }
          ]
        }
      }).done(function(data) {
        var col, fn, i, len, ref2, wf;
        if (data.objects.length === 0) {
          set_empty("collections_field.no_collections_visible");
          return;
        }
        ref2 = data.objects;
        fn = function(wf) {
          if (search) {
            return CUI.dom.append(div, (new LocaButton({
              ui: "collections.show_in_search.button",
              "class": "ez5-collections-field-button",
              appearance: "link",
              loca_key: "collections.fields.show_collection",
              text: wf.renderNameAsText(),
              onClick: (function(_this) {
                return function() {
                  return wf.showInSearch(search);
                };
              })(this)
            })).DOM);
          } else {
            return CUI.dom.append(div, (new CUI.Label({
              "class": "ez5-collections-field-label",
              text: wf.renderNameAsText()
            })).DOM);
          }
        };
        for (i = 0, len = ref2.length; i < len; i++) {
          col = ref2[i];
          wf = new CollectionWorkfolder({
            collection: col
          });
          fn(wf);
        }
      });
    }
    return div;
  };

  CollectionsField.prototype.getMappingSourceFullNameLocalized = function() {
    return this.fullNameLocalized();
  };

  CollectionsField.prototype.isSourceForMapping = function(required_type) {
    return false;
  };

  return CollectionsField;

})(DataColumn);
// Generated by CoffeeScript 1.12.7
var DateColumn,
  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;

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

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

  DateColumn.prototype.getSearchFilter = function(data, key, addRanges) {
    var filter, from, predefinedMode, predefinedType, to;
    if (key == null) {
      key = this.name();
    }
    if (addRanges == null) {
      addRanges = true;
    }
    filter = DateColumn.__super__.getSearchFilter.call(this, data, key);
    if (filter) {
      return filter;
    }
    predefinedMode = data[key + ":predefined_mode"];
    predefinedType = data[key + ":predefined_type"];
    if (predefinedMode && !CUI.util.isEmpty(predefinedType)) {
      return this.__getPredefinedSearchFilter(data, key, predefinedType, addRanges);
    } else if (!predefinedMode) {
      this.__clearPredefinedData(data, key);
    }
    from = data[key + ":from"];
    to = data[key + ":to"];
    if (CUI.util.isEmpty(from) && CUI.util.isEmpty(to)) {
      return;
    }
    filter = {
      type: "range",
      field: this.getSearchField(key)
    };
    if (!CUI.util.isEmpty(from)) {
      filter.from = from;
    }
    if (!CUI.util.isEmpty(to)) {
      filter.to = to;
    }
    if (!addRanges) {
      return filter;
    }
    return this.__addRangesToFilter(filter);
  };

  DateColumn.prototype.__addRangesToFilter = function(filter) {
    var filters, i, k, len, nFilter, ref, ref1;
    if (ez5.version("6") && (filter != null ? (ref = filter.field) != null ? ref.includes(".range") : void 0 : void 0)) {
      filters = [];
      filter.bool = "should";
      filters.push(filter);
      ref1 = ["_year", "_month"];
      for (i = 0, len = ref1.length; i < len; i++) {
        k = ref1[i];
        nFilter = CUI.util.copyObjectV2(filter, true);
        nFilter.field = nFilter.field + k;
        filters.push(nFilter);
      }
      return {
        type: "complex",
        search: filters
      };
    } else {
      return filter;
    }
  };

  DateColumn.prototype.__getPredefinedSearchFilter = function(data, key, predefinedType, addRanges) {
    var customAmount, customDirection, customUnit, filter, unitSuffix;
    filter = {
      type: "range",
      field: this.getSearchField(key)
    };
    switch (predefinedType) {
      case "today":
        filter.from = "$today";
        filter.to = "$today";
        break;
      case "yesterday":
        filter.from = "$today-1d";
        filter.to = "$today-1d";
        break;
      case "in_7_days":
        filter.from = "$today";
        filter.to = "$today+7d";
        break;
      case "last_7_days":
        filter.from = "$today-7d";
        filter.to = "$today";
        break;
      case "in_one_month":
        filter.from = "$today";
        filter.to = "$today+1M";
        break;
      case "last_month":
        filter.from = "$today-1M";
        filter.to = "$today";
        break;
      case "custom":
        customAmount = data[key + ":predefined_custom_amount"];
        customDirection = data[key + ":predefined_custom_direction"];
        customUnit = data[key + ":predefined_custom_unit"];
        if (CUI.util.isEmpty(customAmount) || customAmount < 1) {
          return null;
        }
        if (CUI.util.isEmpty(customDirection)) {
          return null;
        }
        if (CUI.util.isEmpty(customUnit)) {
          return null;
        }
        unitSuffix = (function() {
          switch (customUnit) {
            case "days":
              return "d";
            case "weeks":
              return "w";
            case "months":
              return "M";
            case "years":
              return "y";
            default:
              return "d";
          }
        })();
        if (customDirection === "backward") {
          filter.from = "$today-" + customAmount + unitSuffix;
          filter.to = "$today";
        } else {
          filter.from = "$today";
          filter.to = "$today+" + customAmount + unitSuffix;
        }
        break;
      default:
        return null;
    }
    if (!addRanges) {
      return filter;
    }
    return this.__addRangesToFilter(filter);
  };

  DateColumn.prototype.supportsFacet = function() {
    return true;
  };

  DateColumn.prototype.__formatBareValue = function(v) {
    return this.renderDateValue(v);
  };

  DateColumn.prototype.getDataLocale = function() {
    var dbLocale, i, len, locale, locales;
    locale = CUI.DateTime.getLocale();
    locales = ez5.session.getPref("database_languages") || [];
    if (CUI.util.isEmpty(locales)) {
      locales = ez5.session.getConfigDatabaseLanguages();
    }
    if (!ez5.version("6")) {
      for (i = 0, len = locales.length; i < len; i++) {
        dbLocale = locales[i];
        if (CUI.DateTimeFormats[dbLocale]) {
          return dbLocale;
        }
      }
      return locale;
    }
    return locale = locales[0] || locale;
  };

  DateColumn.prototype.getFacet = function(opts) {
    opts.field = this;
    return new DateFacet(opts);
  };

  DateColumn.prototype.isSortGroupable = function(filter) {
    if (!ez5.version("6.12")) {
      return DateColumn.__super__.isSortGroupable.call(this, filter);
    }
    if (filter._extra === "none") {
      return false;
    }
    return true;
  };

  DateColumn.prototype.sortExtraOpts = function(data) {
    var i, len, opts, ref, v;
    if (!ez5.version("6.12")) {
      return DateColumn.__super__.sortExtraOpts.call(this, data);
    }
    opts = [];
    ref = ["width_none", "width_year", "width_month", "width_week", "width_day"];
    for (i = 0, len = ref.length; i < len; i++) {
      v = ref[i];
      opts.push({
        text: $$("date.column.sort." + v),
        value: v.split("_")[1]
      });
    }
    return opts;
  };

  DateColumn.prototype.getSortFields = function(filter, keys, activeFilters) {
    var f, field_name, fields, i, len, nFilters, ref, sort_field;
    if (!ez5.version("6.12")) {
      return DateColumn.__super__.getSortFields.call(this, filter);
    }
    field_name = DateColumn.__super__.getSortFields.call(this, filter);
    sort_field = {
      field: field_name,
      order: filter._order
    };
    if (filter._extra !== "none") {
      sort_field["width"] = filter._extra;
      sort_field["group_field"] = field_name;
      fields = [sort_field];
      nFilters = 0;
      ref = ["_1", "_2", "_3"];
      for (i = 0, len = ref.length; i < len; i++) {
        f = ref[i];
        if (activeFilters[f]) {
          nFilters++;
        }
      }
      if (nFilters === 1) {
        fields.push({
          field: field_name,
          order: filter._order
        });
      }
      return fields;
    }
    return sort_field;
  };

  DateColumn.prototype.__getPredefinedSelectOptions = function() {
    return [
      {
        text: $$("date.column.predefined.select_range", null, null, "Select a range..."),
        value: null
      }, {
        text: $$("date.column.predefined.today", null, null, "Today"),
        value: "today"
      }, {
        text: $$("date.column.predefined.in_7_days", null, null, "In 7 days"),
        value: "in_7_days"
      }, {
        text: $$("date.column.predefined.in_one_month", null, null, "In one month"),
        value: "in_one_month"
      }, {
        text: $$("date.column.predefined.custom", null, null, "Custom"),
        value: "custom"
      }
    ];
  };

  DateColumn.prototype.__getPredefinedCustomUnitOptions = function() {
    return [
      {
        text: $$("date.column.predefined.custom_unit.select", null, null, "Select unit..."),
        value: null
      }, {
        text: $$("date.column.predefined.custom_unit.days", null, null, "Days"),
        value: "days"
      }, {
        text: $$("date.column.predefined.custom_unit.weeks", null, null, "Weeks"),
        value: "weeks"
      }, {
        text: $$("date.column.predefined.custom_unit.months", null, null, "Months"),
        value: "months"
      }, {
        text: $$("date.column.predefined.custom_unit.years", null, null, "Years"),
        value: "years"
      }
    ];
  };

  DateColumn.prototype.__getPredefinedCustomDirectionOptions = function() {
    return [
      {
        text: $$("date.column.predefined.custom_direction.select", null, null, "Select direction..."),
        value: null
      }, {
        text: $$("date.column.predefined.custom_direction.forward", null, null, "Forward (future)"),
        value: "forward"
      }, {
        text: $$("date.column.predefined.custom_direction.backward", null, null, "Backward (past)"),
        value: "backward"
      }
    ];
  };

  DateColumn.prototype.__getPredefinedOptionsForm = function(data) {
    var fieldName;
    fieldName = this.name();
    return new CUI.DataFieldProxy({
      element: (function(_this) {
        return function(df) {
          var customAmountInput, customDirectionSelect, customOptionsLayout, customUnitSelect, layout, predefinedSelect;
          predefinedSelect = new CUI.Select({
            name: fieldName + ":predefined_type",
            options: _this.__getPredefinedSelectOptions(),
            data: data,
            onDataChanged: function(data, select) {
              if (data[fieldName + ":predefined_type"] === "custom") {
                customOptionsLayout.show();
              } else {
                customOptionsLayout.hide();
                data[fieldName + ":predefined_custom_amount"] = null;
                data[fieldName + ":predefined_custom_direction"] = null;
                data[fieldName + ":predefined_custom_unit"] = null;
              }
              return CUI.Events.trigger({
                node: select,
                type: "search-input-change"
              });
            }
          });
          customDirectionSelect = new CUI.Select({
            name: fieldName + ":predefined_custom_direction",
            options: _this.__getPredefinedCustomDirectionOptions(),
            data: data,
            onDataChanged: function(data, select) {
              return CUI.Events.trigger({
                node: select,
                type: "search-input-change"
              });
            }
          });
          customAmountInput = new CUI.NumberInput({
            name: fieldName + ":predefined_custom_amount",
            placeholder: $$("date.column.predefined.custom_amount.placeholder", null, null, "Amount..."),
            min: 1,
            data: data,
            onDataChanged: function(data, input) {
              return CUI.Events.trigger({
                node: input,
                type: "search-input-change"
              });
            }
          });
          customUnitSelect = new CUI.Select({
            name: fieldName + ":predefined_custom_unit",
            options: _this.__getPredefinedCustomUnitOptions(),
            data: data,
            onDataChanged: function(data, select) {
              return CUI.Events.trigger({
                node: select,
                type: "search-input-change"
              });
            }
          });
          customOptionsLayout = new CUI.HorizontalList({
            "class": "ez5-date-custom-options",
            content: [customAmountInput, customUnitSelect, customDirectionSelect]
          });
          layout = new CUI.VerticalList({
            content: [predefinedSelect, customOptionsLayout]
          });
          if (data[fieldName + ":predefined_type"] !== "custom") {
            customOptionsLayout.hide();
          }
          return layout;
        };
      })(this)
    });
  };

  DateColumn.prototype.__clearPredefinedData = function(data, fieldName) {
    data[fieldName + ":predefined_type"] = null;
    data[fieldName + ":predefined_custom_amount"] = null;
    data[fieldName + ":predefined_custom_direction"] = null;
    data[fieldName + ":predefined_custom_unit"] = null;
  };

  DateColumn.prototype.formatSortGroupable = function(item, filter) {
    if (!ez5.version("6.12")) {
      return DateColumn.__super__.formatSortGroupable.call(this, item, filter);
    }
    return CUI.DateTime.formatGroupLabel(item, filter._extra, this.getDataLocale());
  };

  DateColumn.prototype.getSortFunction = function() {
    return (function(_this) {
      return function(a, b) {
        var ref, ref1;
        return CUI.util.compareIndex(((ref = a[_this.name()]) != null ? ref.value : void 0) || '9999', ((ref1 = b[_this.name()]) != null ? ref1.value : void 0) || '9999');
      };
    })(this);
  };

  DateColumn.prototype.getSaveData = function(data, save_data, opts) {
    var ref, v;
    if (opts.copy && this.isUnique()) {
      if (this.isReadOnly(data, save_data, opts) || !this.isVisible(opts.mode || "editor")) {
        return;
      }
    }
    if (opts.demo_data) {
      v = CUI.DateTime.format(CUI.util.moment(), "store", this.getDateTimeInputTypes()[0]);
    } else {
      if (!((ref = data[this.name()]) != null ? ref.value : void 0)) {
        v = this.getFallbackValue(data, opts, "store");
      } else {
        v = data[this.name()].value;
      }
    }
    if (CUI.util.isEmpty(v)) {
      return save_data[this.name()] = null;
    } else {
      return save_data[this.name()] = {
        value: v
      };
    }
  };

  DateColumn.prototype.getQueryFieldBadge = function(data) {
    var value;
    value = this.__getQueryFieldBadgeValue(data);
    if (CUI.util.isUndef(value)) {
      value = data[(this.name()) + ":unset"] ? $$("field.search.badge.without") : $$("field.search.badge.has_value");
    }
    return {
      name: this.nameLocalized(),
      value: value
    };
  };

  DateColumn.prototype.__getQueryFieldBadgeValue = function(data, opts) {
    var arr, fieldOptions, fn, i, k, len, predefinedMode, predefinedType, value;
    if (opts == null) {
      opts = {};
    }
    fieldOptions = opts.fieldOptions || ["from", "to"];
    if (data[(this.name()) + ":unset"] || data[(this.name()) + ":has_value"]) {
      return void 0;
    }
    predefinedMode = data[(this.name()) + ":predefined_mode"];
    predefinedType = data[(this.name()) + ":predefined_type"];
    if (predefinedMode && !CUI.util.isEmpty(predefinedType)) {
      return this.__getPredefinedBadgeValue(data, predefinedType);
    }
    arr = [];
    for (i = 0, len = fieldOptions.length; i < len; i++) {
      k = fieldOptions[i];
      fn = this.name() + ":" + k;
      arr.push(data[fn] || "");
    }
    if (arr.every(function(value) {
      return CUI.util.isEmpty(value);
    })) {
      value = "";
    } else {
      value = arr.join(" - ").trim();
    }
    return value;
  };

  DateColumn.prototype.__getPredefinedBadgeValue = function(data, predefinedType) {
    switch (predefinedType) {
      case "today":
        return $$("date.column.predefined.badge.today", null, null, "Today");
      case "yesterday":
        return $$("date.column.predefined.badge.yesterday", null, null, "Yesterday");
      case "in_7_days":
        return $$("date.column.predefined.badge.in_7_days", null, null, "Today to 7 days");
      case "last_7_days":
        return $$("date.column.predefined.badge.last_7_days", null, null, "Last 7 days to today");
      case "in_one_month":
        return $$("date.column.predefined.badge.in_one_month", null, null, "Today to 1 month");
      case "last_month":
        return $$("date.column.predefined.badge.last_month", null, null, "Last month to today");
      case "custom":
        return this.__getCustomBadgeValue(data);
      default:
        return predefinedType;
    }
  };

  DateColumn.prototype.__getCustomBadgeValue = function(data) {
    var amount, direction, unit, unitText;
    amount = data[(this.name()) + ":predefined_custom_amount"];
    direction = data[(this.name()) + ":predefined_custom_direction"];
    unit = data[(this.name()) + ":predefined_custom_unit"];
    if (CUI.util.isEmpty(amount) || amount < 1) {
      return $$("date.column.predefined.badge.custom_invalid", null, null, "Custom range");
    }
    if (CUI.util.isEmpty(direction)) {
      direction = "forward";
    }
    if (CUI.util.isEmpty(unit)) {
      unit = "days";
    }
    unitText = (function() {
      switch (unit) {
        case "days":
          if (amount === 1) {
            return $$("date.column.predefined.badge.unit.day", null, null, "day");
          } else {
            return $$("date.column.predefined.badge.unit.days", null, null, "days");
          }
          break;
        case "weeks":
          if (amount === 1) {
            return $$("date.column.predefined.badge.unit.week", null, null, "week");
          } else {
            return $$("date.column.predefined.badge.unit.weeks", null, null, "weeks");
          }
          break;
        case "months":
          if (amount === 1) {
            return $$("date.column.predefined.badge.unit.month", null, null, "month");
          } else {
            return $$("date.column.predefined.badge.unit.months", null, null, "months");
          }
          break;
        case "years":
          if (amount === 1) {
            return $$("date.column.predefined.badge.unit.year", null, null, "year");
          } else {
            return $$("date.column.predefined.badge.unit.years", null, null, "years");
          }
          break;
        default:
          return unit;
      }
    })();
    if (direction === "backward") {
      return $$("date.column.predefined.badge.custom_backward", {
        amount: amount,
        unit: unitText
      }, null, amount + " " + unitText + " ago to today");
    } else {
      return $$("date.column.predefined.badge.custom_forward", {
        amount: amount,
        unit: unitText
      }, null, "Today to " + amount + " " + unitText);
    }
  };

  DateColumn.prototype.renderSearchInput = function(data, opts) {
    var fieldName, form, normalForm, predefinedForm, showPredefined, switchButton, switchFields;
    if (opts.bulk_expert) {
      return this.renderEditorInput(data, {}, opts);
    }
    if (!ez5.version("6")) {
      return new CUI.Form({
        "class": "ez5-date-range-form",
        undo_and_changed_support: false,
        fields: this.__getSearchFields(data)
      }).start();
    }
    fieldName = this.name();
    normalForm = new CUI.Form({
      undo_and_changed_support: false,
      "class": "ez5-date-range-form",
      fields: this.__getSearchFields(data)
    });
    if (!ez5.version("6")) {
      return normalForm;
    }
    predefinedForm = this.__getPredefinedOptionsForm(data);
    if (data[fieldName + ":predefined_type"] != null) {
      showPredefined = true;
    } else {
      showPredefined = false;
    }
    data[fieldName + ":predefined_mode"] = showPredefined;
    switchFields = (function(_this) {
      return function() {
        data[fieldName + ":predefined_mode"] = showPredefined;
        if (showPredefined) {
          normalForm.hide(true);
          predefinedForm.show(true);
          predefinedForm.reload();
          switchButton.setText($$("date.column.search.show-less-options", null, null, "Manual Range Definition"));
        } else {
          predefinedForm.hide(true);
          normalForm.show(true);
          normalForm.reload();
          switchButton.setText($$("date.column.search.show-more-options", null, null, "Predefined Ranges"));
          _this.__clearPredefinedData(data, fieldName);
        }
      };
    })(this);
    switchButton = new CUI.Button({
      text: $$("date.column.search.show-more-options", null, null, "Predefined Ranges"),
      appearance: "link",
      size: "mini",
      onClick: (function(_this) {
        return function() {
          showPredefined = !showPredefined;
          switchFields();
          if (showPredefined) {
            data[fieldName + ":from"] = null;
            data[fieldName + ":to"] = null;
          } else {
            data[fieldName + ":predefined_type"] = null;
            data[fieldName + ":predefined_custom_amount"] = null;
            data[fieldName + ":predefined_custom_direction"] = null;
            data[fieldName + ":predefined_custom_unit"] = null;
          }
          CUI.Events.trigger({
            node: form,
            type: "search-input-change"
          });
          CUI.Events.trigger({
            type: "viewport-resize"
          });
        };
      })(this)
    });
    form = new CUI.Form({
      undo_and_changed_support: false,
      fields: [
        normalForm, predefinedForm, {
          type: CUI.DataFieldProxy,
          element: switchButton
        }
      ],
      data: data,
      onRender: (function(_this) {
        return function() {
          return switchFields();
        };
      })(this),
      onDataChanged: function(_, field) {
        return CUI.Events.trigger({
          node: field,
          type: "search-input-change"
        });
      }
    }).start();
    return form;
  };

  DateColumn.prototype.isEmpty = function(data, _, opts) {
    var predefinedMode, ref;
    if (opts == null) {
      opts = {};
    }
    if (opts.mode === "expert") {
      predefinedMode = data[this.name() + ":predefined_mode"];
      if (predefinedMode) {
        if (!CUI.util.isEmpty(data[this.name() + ":predefined_type"])) {
          return false;
        }
        if (CUI.util.isEmpty(data[this.name() + ":predefined_custom_amount"]) || CUI.util.isEmpty(data[this.name() + ":predefined_custom_direction"]) || CUI.util.isEmpty(data[this.name() + ":predefined_custom_unit"])) {
          return true;
        }
      }
      return CUI.util.isEmpty(data[this.name() + ":from"]) && CUI.util.isEmpty(data[this.name() + ":to"]);
    } else {
      return CUI.util.isEmpty((ref = data[this.name()]) != null ? ref.value : void 0);
    }
  };

  DateColumn.prototype.hasUserData = function(data, _, opts) {
    if (opts == null) {
      opts = {};
    }
    return !this.isEmpty(data, _, opts);
  };

  DateColumn.prototype.renderStandard = function(standard, data) {
    var os;
    if (data[this.name()] && (os = this.getOutputStandard())) {
      return standard.push({
        field: this,
        value: this.renderDateValue(data[this.name()].value),
        render_info: os
      });
    }
  };

  DateColumn.prototype.showCalendar = function() {
    var ref;
    if ((ref = this.ColumnSchema.custom_settings) != null ? ref.only_years : void 0) {
      return false;
    }
    return true;
  };

  DateColumn.prototype.getDateTimeInputTypes = function() {
    var ref;
    if ((ref = this.ColumnSchema.custom_settings) != null ? ref.only_years : void 0) {
      return ["year"];
    }
    return ["date", "year_month", "year"];
  };

  DateColumn.prototype.getFallbackValue = function(data, opts, output_format) {
    var mv, ref, ref1, ref2, tv, v;
    tv = (ref = data._template) != null ? (ref1 = ref[this.name()]) != null ? ref1.value : void 0 : void 0;
    mv = (ref2 = data[this.name() + ":mapped_metadata"]) != null ? ref2.value : void 0;
    if (this.preferTemplateOverMapping(opts)) {
      if (tv) {
        v = tv;
      } else {
        v = mv;
      }
    } else {
      if (mv) {
        v = mv;
      } else {
        v = tv;
      }
    }
    if (v === "invalid") {
      return invalid;
    }
    return CUI.DateTime.formatWithInputTypes(v, this.getDateTimeInputTypes(), output_format);
  };

  DateColumn.prototype.renderEditorInput = function(data, top_level_data, opts) {
    var dt, placeholder, ref;
    if (!data[this.name()]) {
      data[this.name()] = {
        value: null
      };
    }
    placeholder = this.getFallbackValue(data, opts, "input") || this.__getPlaceholder();
    return dt = new CUI.DateTime({
      name: "value",
      input_types: this.getDateTimeInputTypes(),
      store_invalid: true,
      locale: this.getDataLocale(),
      calendar_locale: ez5.session.getLanguage(),
      placeholder: placeholder,
      display_type: "short",
      show_calendar: this.showCalendar(),
      id: this.idAttribute(data),
      avoid_bc_conversion: ((ref = this.FieldSchema.custom_settings) != null ? ref.avoid_bc_conversion : void 0) || false,
      onDataChanged: (function(_this) {
        return function(data, df) {
          return CUI.Events.trigger({
            node: dt,
            type: "editor-changed"
          });
        };
      })(this),
      data: data[this.name()]
    }).start().DOM;
  };

  DateColumn.prototype.__getPlaceholder = function() {
    return this.getCustomPlaceholder() || this.getFormattedPlaceholder();
  };

  DateColumn.prototype.getFormattedPlaceholder = function(placeholder_locaKey, format, date_str) {
    var ref;
    if (placeholder_locaKey == null) {
      placeholder_locaKey = "date.column.formatted.placeholder";
    }
    if (format == null) {
      format = "date";
    }
    if (date_str == null) {
      date_str = "2021-01-01T13:13:00";
    }
    if ((ref = this.ColumnSchema.custom_settings) != null ? ref.only_years : void 0) {
      format = "year";
    }
    return $$(placeholder_locaKey, {
      date: CUI.DateTime.format(date_str, "input", format, false, this.getDataLocale())
    });
  };

  DateColumn.prototype.checkValue = function(data, top_level_data, opts) {
    var ref, v;
    v = (ref = data[this.name()]) != null ? ref.value : void 0;
    if (CUI.util.isEmpty(v)) {
      v = this.getFallbackValue(data, opts, "store");
    }
    if (v === 'invalid') {
      return this.getInvalidText();
    }
    return this.checkBareValue(v, data, top_level_data, opts);
  };

  DateColumn.prototype.getInvalidKey = function() {
    var ref;
    if ((ref = this.ColumnSchema.custom_settings) != null ? ref.only_years : void 0) {
      return "date.column.check.invalid.only_years";
    }
    return "date.column.check.invalid";
  };

  DateColumn.prototype.getInvalidText = function() {
    return $$(this.getInvalidKey(), {
      field: this.fullNameLocalized()
    });
  };

  DateColumn.prototype.getElementOpts = function() {
    return {
      type: CUI.DateTime,
      input_types: this.getDateTimeInputTypes(),
      display_type: "short"
    };
  };

  DateColumn.prototype.renderDetailOutput = function(data, top_level_data) {
    var ref;
    return new CUI.Label({
      text: this.renderDateValue((ref = data[this.name()]) != null ? ref.value : void 0)
    }).DOM;
  };

  DateColumn.prototype.renderDateValue = function(value) {
    var opts, ref;
    opts = {
      input_types: this.getDateTimeInputTypes(),
      locale: this.getDataLocale(),
      add_AD: true,
      avoid_bc_conversion: ((ref = this.FieldSchema.custom_settings) != null ? ref.avoid_bc_conversion : void 0) || false
    };
    return CUI.DateTime.display(value, opts);
  };

  DateColumn.prototype.isExpertCommon = function(mode) {
    return true;
  };

  DateColumn.prototype.getCSVDestinationFields = function(csvImporter) {
    var opts;
    opts = {
      csvImporter: csvImporter,
      field: this
    };
    return [new DateColumnCSVImporterDestinationField(opts)];
  };

  DateColumn.prototype.__getRenderedElement = function(data) {
    var fieldData;
    fieldData = data[this.name() + ":rendered"];
    return fieldData != null ? fieldData.getElement() : void 0;
  };

  DateColumn.prototype.__getRenderedDateTime = function(data) {
    var domInput, element;
    element = this.__getRenderedElement(data);
    if (!element) {
      return;
    }
    domInput = CUI.dom.matchSelector(element, ".cui-date-time")[0];
    return CUI.dom.data(domInput, "element");
  };

  DateColumn.prototype.emptyEditorInputValue = function(value, top_level_data) {
    var currentValue, data;
    data = top_level_data[top_level_data._objecttype];
    if (this.isEmpty(data)) {
      return;
    }
    currentValue = data[this.name()];
    if (currentValue.value === value) {
      this.updateValue(data, "");
    }
  };

  DateColumn.prototype.updateEditorInputValue = function(value, top_level_data) {
    var currentValue, data, renderedField;
    value = CUI.DateTime.format(value, "store", this.getDateTimeInputTypes()[0]);
    data = top_level_data[top_level_data._objecttype];
    renderedField = this.__getRenderedDateTime(data);
    if (this.isEmpty(data) && !CUI.util.isEmpty(renderedField)) {
      this.updateValue(data, value);
      return;
    }
    if (this.isEmpty(data) && CUI.util.isEmpty(renderedField)) {
      data[this.name()] = {
        value: value
      };
      return;
    }
    currentValue = data[this.name()];
    if (currentValue.value === value) {
      this.updateValue(data, value);
      return;
    }
    CUI.confirm({
      markdown: true,
      text: $$("text.column.update.value.confirm", {
        name: this.nameLocalized(),
        current_value: currentValue.value,
        new_value: value
      })
    }).done((function(_this) {
      return function() {
        return _this.updateValue(data, value);
      };
    })(this));
  };

  DateColumn.prototype.updateValue = function(data, value) {
    var dateTime;
    dateTime = this.__getRenderedDateTime(data);
    if (!dateTime) {
      return;
    }
    try {
      dateTime.setValue(value, {
        no_trigger: false
      });
    } catch (error) {}
  };

  DateColumn.prototype.getSearchField = function(key, type) {
    var field;
    if (key == null) {
      key = this.name();
    }
    if (type == null) {
      type = "range";
    }
    field = DateColumn.__super__.getSearchField.call(this);
    if (!ez5.version("6")) {
      return field;
    }
    return field + "." + type;
  };

  DateColumn.prototype.__getSearchFields = function(data, opts) {
    var _opts, defaultPlaceholder, fieldOptions, fields, fn1, i, key, len, toDate;
    if (opts == null) {
      opts = {};
    }
    fieldOptions = opts.fieldOptions || ["from", "to"];
    _opts = this.getElementOpts("expert");
    fields = [];
    toDate = null;
    defaultPlaceholder = "";
    fn1 = (function(_this) {
      return function(key) {
        var field, fn;
        opts = CUI.util.copyObject(_opts);
        fn = (_this.name()) + ":" + key;
        opts.placeholder = $$("date.column.placeholder." + key);
        opts.name = fn;
        if (CUI.util.isUndef(data[fn])) {
          data[fn] = null;
        }
        opts.data = data;
        opts.onDataChanged = function(data, dataField) {
          var from;
          CUI.Events.trigger({
            node: dataField,
            type: "search-input-change"
          });
          if ((key !== "from" && key !== "from:from") || !toDate) {
            return;
          }
          if (data[toDate.getName()]) {
            return;
          }
          if (!defaultPlaceholder) {
            defaultPlaceholder = CUI.dom.getAttribute(toDate.getElement(), "placeholder");
          }
          dataField.focus();
          from = data[fn];
          if (!from || from === "invalid") {
            toDate.setPlaceholder(defaultPlaceholder);
          } else {
            toDate.setPlaceholder(from);
          }
        };
        opts.onBlur = function() {
          var from;
          if ((key !== "from" && key !== "from:from") || !toDate) {
            return;
          }
          if (data[toDate.getName()]) {
            return;
          }
          from = data[fn];
          if (!from || from === "invalid") {
            data[toDate.getName()] = null;
          } else {
            data[toDate.getName()] = from;
          }
          toDate.reload();
        };
        opts.id = _this.idAttribute(data) + ("." + key);
        opts.locale = _this.getDataLocale();
        field = CUI.DataField["new"](opts);
        if (key === "to" || key === "from:to") {
          toDate = field;
        }
        return fields.push(field);
      };
    })(this);
    for (i = 0, len = fieldOptions.length; i < len; i++) {
      key = fieldOptions[i];
      fn1(key);
    }
    return fields;
  };

  return DateColumn;

})(DataColumn);
// Generated by CoffeeScript 1.12.7
var DateRangeColumn,
  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;

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

  function DateRangeColumn() {
    this.__showInternalDatesInTextualRepresentation = bind(this.__showInternalDatesInTextualRepresentation, this);
    this.__isTextualRepresentation = bind(this.__isTextualRepresentation, this);
    return DateRangeColumn.__super__.constructor.apply(this, arguments);
  }

  DateRangeColumn.prototype.isEmpty = function(data, _, opts) {
    var fromCustomValid, predefinedMode, ref, ref1, toCustomValid;
    if (opts == null) {
      opts = {};
    }
    if (opts.mode === "expert") {
      predefinedMode = data[this.name() + ":predefined_mode"];
      if (predefinedMode) {
        if (!CUI.util.isEmpty(data[this.name() + ":predefined_from_type"]) || !CUI.util.isEmpty(data[this.name() + ":predefined_to_type"])) {
          return false;
        }
        fromCustomValid = !(CUI.util.isEmpty(data[this.name() + ":predefined_from_custom_amount"]) || CUI.util.isEmpty(data[this.name() + ":predefined_from_custom_direction"]) || CUI.util.isEmpty(data[this.name() + ":predefined_from_custom_unit"]));
        toCustomValid = !(CUI.util.isEmpty(data[this.name() + ":predefined_to_custom_amount"]) || CUI.util.isEmpty(data[this.name() + ":predefined_to_custom_direction"]) || CUI.util.isEmpty(data[this.name() + ":predefined_to_custom_unit"]));
        if (fromCustomValid || toCustomValid) {
          return false;
        }
      }
      return DateRangeColumn.__super__.isEmpty.call(this, data, _, opts);
    }
    return CUI.util.isEmpty((ref = data[this.name()]) != null ? ref.from : void 0) && CUI.util.isEmpty((ref1 = data[this.name()]) != null ? ref1.to : void 0);
  };

  DateRangeColumn.prototype.getCSVDestinationFields = function(csvImporter) {
    var opts;
    opts = {
      csvImporter: csvImporter,
      field: this
    };
    return [new DateRangeColumnCSVImporterDestinationField(opts)];
  };

  DateRangeColumn.prototype.getSaveData = function(data, save_data, opts) {
    var dataValue, from, i, j, k, len, len1, locale, ref, ref1, ref2, textualRepresentationTexts, to, value;
    if (opts.demo_data) {
      dataValue = {
        from: CUI.DateTime.format(CUI.util.moment().startOf("year"), "store", "date"),
        to: CUI.DateTime.format(CUI.util.moment().endOf("year"), "store", "date")
      };
    } else if (!this.hasUserData(data)) {
      dataValue = this.getFallbackValue(data);
    } else {
      dataValue = data[this.name()];
      if (!ez5.version("6")) {
        ref = ["_from", "_to", "_middle"];
        for (i = 0, len = ref.length; i < len; i++) {
          k = ref[i];
          delete dataValue[k];
        }
      }
    }
    if (CUI.util.isEmpty(dataValue.from) && CUI.util.isEmpty(dataValue.to)) {
      save_data[this.name()] = null;
    } else {
      save_data[this.name()] = {
        from: dataValue.from || null,
        to: dataValue.to || null
      };
    }
    if (!save_data[this.name()] || !this.__isTextualRepresentation()) {
      return;
    }
    from = save_data[this.name()].from;
    to = save_data[this.name()].to;
    if (dataValue.text) {
      save_data[this.name()].text = dataValue.text;
    }
    if (!CUI.util.isEmpty(dataValue.string_date)) {
      textualRepresentationTexts = {};
      ref1 = ez5.loca.getDatabaseLanguages();
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        locale = ref1[j];
        if (locale === CUI.DateTime.getLocale() && !CUI.util.isEmpty(dataValue.string_date)) {
          textualRepresentationTexts[locale] = dataValue.string_date;
        } else {
          value = ((ref2 = dataValue.text) != null ? ref2[locale] : void 0) || this.__dateRangeToString(from, to, locale);
          if (value) {
            textualRepresentationTexts[locale] = value;
          }
        }
      }
      save_data[this.name()].text = textualRepresentationTexts;
    }
  };

  DateRangeColumn.prototype.isSortGroupable = function(filter) {
    return false;
  };

  DateRangeColumn.prototype.getSortFunction = function() {
    var get_value;
    get_value = (function(_this) {
      return function(v) {
        var ref, ref1;
        return ((ref = v[_this.name()]) != null ? ref.from : void 0) || ((ref1 = v[_this.name()]) != null ? ref1.to : void 0) || '9999';
      };
    })(this);
    return (function(_this) {
      return function(a, b) {
        return CUI.util.compareIndex(get_value(a), get_value(b));
      };
    })(this);
  };

  DateRangeColumn.prototype.getFallbackValue = function(data, opts, output_format) {
    var i, k, len, ref, ref1, ref2, v;
    if (output_format && ((ref = data._template) != null ? ref[this.name()] : void 0)) {
      v = CUI.util.copyObject(data._template[this.name()]);
      ref1 = ["from", "to"];
      for (i = 0, len = ref1.length; i < len; i++) {
        k = ref1[i];
        if (v[k]) {
          v[k] = CUI.DateTime.formatWithInputTypes(v[k], this.getDateTimeInputTypes(), output_format, this.getDataLocale());
        }
      }
      return v;
    }
    return ((ref2 = data._template) != null ? ref2[this.name()] : void 0) || {};
  };

  DateRangeColumn.prototype.checkValue = function(data, top_level_data, opts) {
    var cv_from, cv_to, errors, v;
    if (!this.hasUserData(data)) {
      v = this.getFallbackValue(data);
    } else {
      v = data[this.name()];
    }
    if (v.from === "invalid" || v.to === "invalid") {
      return this.getInvalidText();
    }
    errors = [];
    cv_from = this.checkBareValue(v.from, data, top_level_data, opts);
    if (cv_from !== true) {
      cv_from = cv_from.replace(this.fullNameLocalized(), this.fullNameLocalized() + ": " + $$('date.range.column.sort.from'));
      errors.push(cv_from);
    }
    cv_to = this.checkBareValue(v.to, data, top_level_data, opts);
    if (cv_to !== true) {
      cv_to = cv_to.replace(this.fullNameLocalized(), this.fullNameLocalized() + ": " + $$('date.range.column.sort.to'));
      errors.push(cv_to);
    }
    if (errors.length > 0) {
      return errors;
    } else {
      return this.checkRange(v.from, v.to);
    }
  };

  DateRangeColumn.prototype.getInvalidKey = function() {
    var ref;
    if ((ref = this.ColumnSchema.custom_settings) != null ? ref.only_years : void 0) {
      return "date.range.column.check.invalid.only_years";
    }
    return "date.range.column.check.invalid";
  };

  DateRangeColumn.prototype.checkRange = function(from, to) {
    var error, fromMom, toMom;
    error = $$("date.range.column.check.order.error", {
      field: this.nameLocalized()
    });
    fromMom = CUI.DateTime.toMoment(from);
    toMom = CUI.DateTime.toMoment(to);
    if ((fromMom != null ? fromMom.bc : void 0) && !(toMom != null ? toMom.bc : void 0)) {
      return true;
    }
    if ((toMom != null ? toMom.bc : void 0) && !(fromMom != null ? fromMom.bc : void 0)) {
      return error;
    }
    if ((fromMom != null ? fromMom.bc : void 0) && (toMom != null ? toMom.bc : void 0)) {
      if (parseInt(toMom.bc) > parseInt(fromMom.bc)) {
        return error;
      } else {
        return true;
      }
    }
    if (fromMom && toMom && toMom.isBefore(fromMom)) {
      return error;
    }
    return true;
  };

  DateRangeColumn.prototype.getQueryFieldBadge = function(data) {
    var badge, badgeValue, badgeValueFrom, badgeValueTo, predefinedFromType, predefinedMode, predefinedToType;
    predefinedMode = data[(this.name()) + ":predefined_mode"];
    if (predefinedMode) {
      predefinedFromType = data[(this.name()) + ":predefined_from_type"];
      predefinedToType = data[(this.name()) + ":predefined_to_type"];
      if (!CUI.util.isEmpty(predefinedFromType) || !CUI.util.isEmpty(predefinedToType)) {
        badgeValue = this.__getPredefinedBadgeValue(data, predefinedFromType, predefinedToType);
        badge = {
          name: this.nameLocalized(),
          value: badgeValue
        };
        return badge;
      }
    }
    if (this.__isTextualRepresentation()) {
      badgeValue = this.__dateRangeToString(data[(this.name()) + ":from"], data[(this.name()) + ":to"]);
    } else {
      badgeValue = this.__getQueryFieldBadgeValue(data, {
        fieldOptions: ["from", "to"]
      });
    }
    if (!badgeValue) {
      badgeValueFrom = this.__getQueryFieldBadgeValue(data, {
        fieldOptions: ["from:from", "from:to"]
      });
      badgeValueTo = this.__getQueryFieldBadgeValue(data, {
        fieldOptions: ["to:from", "to:to"]
      });
      if (CUI.util.isUndef(badgeValueFrom) && CUI.util.isUndef(badgeValueTo)) {
        badgeValue = $$("field.search.badge.without");
      } else if (badgeValueFrom && badgeValueTo) {
        badgeValue = badgeValueFrom + " / " + badgeValueTo;
      } else if (badgeValueTo) {
        badgeValue = badgeValueTo;
      } else if (badgeValueFrom) {
        badgeValue = badgeValueFrom;
      } else {
        badgeValue = "";
      }
    }
    badge = {
      name: this.nameLocalized(),
      value: badgeValue
    };
    return badge;
  };

  DateRangeColumn.prototype.__getPredefinedBadgeValue = function(data, predefinedFromType, predefinedToType) {
    var fromBadge, toBadge;
    fromBadge = this.__getSinglePredefinedBadgeValue(data, predefinedFromType, "from");
    toBadge = this.__getSinglePredefinedBadgeValue(data, predefinedToType, "to");
    if (fromBadge && toBadge) {
      return "From " + fromBadge + " to " + toBadge;
    } else if (fromBadge) {
      return "From " + fromBadge;
    } else if (toBadge) {
      return "To " + toBadge;
    } else {
      return "";
    }
  };

  DateRangeColumn.prototype.__getSinglePredefinedBadgeValue = function(data, predefinedType, fieldType) {
    switch (predefinedType) {
      case "today":
        return $$("date.column.predefined.badge.today", null, null, "Today");
      case "yesterday":
        return $$("date.column.predefined.badge.yesterday", null, null, "Yesterday");
      case "in_7_days":
        if (fieldType === "from") {
          return $$("date.column.predefined.badge.today", null, null, "Today");
        } else {
          return "7 days from now";
        }
        break;
      case "last_7_days":
        if (fieldType === "from") {
          return "7 days ago";
        } else {
          return $$("date.column.predefined.badge.today", null, null, "Today");
        }
        break;
      case "in_one_month":
        if (fieldType === "from") {
          return $$("date.column.predefined.badge.today", null, null, "Today");
        } else {
          return "1 month from now";
        }
        break;
      case "last_month":
        if (fieldType === "from") {
          return "1 month ago";
        } else {
          return $$("date.column.predefined.badge.today", null, null, "Today");
        }
        break;
      case "custom":
        return this.__getCustomBadgeValueForRange(data, fieldType);
      default:
        return predefinedType;
    }
  };

  DateRangeColumn.prototype.__getCustomBadgeValueForRange = function(data, fieldType) {
    var amount, direction, unit, unitText;
    amount = data[(this.name()) + ":predefined_" + fieldType + "_custom_amount"];
    direction = data[(this.name()) + ":predefined_" + fieldType + "_custom_direction"];
    unit = data[(this.name()) + ":predefined_" + fieldType + "_custom_unit"];
    if (CUI.util.isEmpty(amount) || amount < 1) {
      return $$("date.column.predefined.badge.custom_invalid", null, null, "Custom");
    }
    if (CUI.util.isEmpty(direction)) {
      direction = "forward";
    }
    if (CUI.util.isEmpty(unit)) {
      unit = "days";
    }
    unitText = (function() {
      switch (unit) {
        case "days":
          if (amount === 1) {
            return $$("date.column.predefined.badge.unit.day", null, null, "day");
          } else {
            return $$("date.column.predefined.badge.unit.days", null, null, "days");
          }
          break;
        case "weeks":
          if (amount === 1) {
            return $$("date.column.predefined.badge.unit.week", null, null, "week");
          } else {
            return $$("date.column.predefined.badge.unit.weeks", null, null, "weeks");
          }
          break;
        case "months":
          if (amount === 1) {
            return $$("date.column.predefined.badge.unit.month", null, null, "month");
          } else {
            return $$("date.column.predefined.badge.unit.months", null, null, "months");
          }
          break;
        case "years":
          if (amount === 1) {
            return $$("date.column.predefined.badge.unit.year", null, null, "year");
          } else {
            return $$("date.column.predefined.badge.unit.years", null, null, "years");
          }
          break;
        default:
          return unit;
      }
    })();
    if (direction === "backward") {
      return amount + " " + unitText + " ago";
    } else {
      return amount + " " + unitText + " from now";
    }
  };

  DateRangeColumn.prototype.renderSearchInput = function(data) {
    var buttonContainer, fieldName, form, fromFields, fromForm, fromToFields, fromToForm, isTextualRepresentation, predefinedButton, predefinedForm, showMoreOptions, showPredefined, switchButton, switchFields, switchPredefinedFields, toFields, toForm;
    if (!ez5.version("6")) {
      return this.__renderLegacySearchInput(data);
    }
    fieldName = this.name();
    fromFields = this.__getSearchFields(data, {
      fieldOptions: ["from:from", "from:to"]
    });
    fromForm = new CUI.Form({
      "class": "ez5-date-range-form",
      fields: fromFields
    });
    toFields = this.__getSearchFields(data, {
      fieldOptions: ["to:from", "to:to"]
    });
    toForm = new CUI.Form({
      "class": "ez5-date-range-form",
      fields: toFields
    });
    isTextualRepresentation = this.__isTextualRepresentation();
    if (isTextualRepresentation) {
      fromToForm = this.__getTextualRepresentationFields(data, fieldName + ":from", fieldName + ":to", false);
    } else {
      fromToFields = this.__getSearchFields(data, {
        fieldOptions: ["from", "to"]
      });
      fromToForm = new CUI.Form({
        "class": "ez5-date-range-form",
        fields: fromToFields
      });
    }
    predefinedForm = this.__getPredefinedOptionsForm(data);
    if ((data[fieldName + ":from:to"] != null) || (data[fieldName + ":from:from"] != null) || (data[fieldName + ":to:from"] != null) || (data[fieldName + ":to:to"] != null)) {
      showMoreOptions = true;
    } else {
      showMoreOptions = false;
    }
    if ((data[fieldName + ":predefined_from_type"] != null) || (data[fieldName + ":predefined_to_type"] != null)) {
      showPredefined = true;
    } else {
      showPredefined = false;
    }
    data[fieldName + ":predefined_mode"] = showPredefined;
    switchButton = new CUI.Button({
      text: $$("date.range.column.search.show-more-options"),
      appearance: "link",
      size: "mini",
      onClick: (function(_this) {
        return function() {
          var from, to;
          showMoreOptions = !showMoreOptions;
          switchFields();
          if (showMoreOptions) {
            data[fieldName + ":from:from"] = data[fieldName + ":from"];
            data[fieldName + ":from:to"] = data[fieldName + ":to"];
            data[fieldName + ":from"] = null;
            data[fieldName + ":to"] = null;
            toForm.reload();
            fromForm.reload();
          } else {
            data[fieldName + ":from"] = data[fieldName + ":from:from"];
            data[fieldName + ":to"] = data[fieldName + ":from:to"];
            data[fieldName + ":from:from"] = null;
            data[fieldName + ":from:to"] = null;
            if (isTextualRepresentation) {
              from = data[fieldName + ":from"];
              to = data[fieldName + ":to"];
              if (from !== "" || to !== "") {
                data.string_date = _this.__dateRangeToString(from, to);
              } else {
                data.string_date = "";
              }
            }
            fromToForm.reload();
          }
          CUI.Events.trigger({
            node: form,
            type: "search-input-change"
          });
          CUI.Events.trigger({
            type: "viewport-resize"
          });
        };
      })(this)
    });
    predefinedButton = new CUI.Button({
      text: $$("date.column.search.show-more-options", null, null, "Relative Dates"),
      appearance: "link",
      size: "mini",
      onClick: (function(_this) {
        return function() {
          showPredefined = !showPredefined;
          switchPredefinedFields();
          if (showPredefined) {
            data[fieldName + ":from"] = null;
            data[fieldName + ":to"] = null;
            data[fieldName + ":from:from"] = null;
            data[fieldName + ":from:to"] = null;
            data[fieldName + ":to:from"] = null;
            data[fieldName + ":to:to"] = null;
          } else {
            _this.__clearPredefinedData(data, fieldName);
          }
          CUI.Events.trigger({
            node: form,
            type: "search-input-change"
          });
          CUI.Events.trigger({
            type: "viewport-resize"
          });
        };
      })(this)
    });
    switchFields = (function(_this) {
      return function() {
        if (showMoreOptions) {
          toForm.show(true);
          fromForm.show(true);
          CUI.dom.showElement(toForm);
          CUI.dom.showElement(fromForm);
          fromToForm.hide(true);
          CUI.dom.hideElement(fromToForm);
          switchButton.setText($$("date.range.column.search.show-less-options"));
        } else {
          toForm.hide(true);
          fromForm.hide(true);
          CUI.dom.hideElement(toForm);
          CUI.dom.hideElement(fromForm);
          fromToForm.show(true);
          CUI.dom.showElement(fromToForm);
          switchButton.setText($$("date.range.column.search.show-more-options"));
        }
      };
    })(this);
    switchPredefinedFields = (function(_this) {
      return function() {
        data[fieldName + ":predefined_mode"] = showPredefined;
        if (showPredefined) {
          fromToForm.hide(true);
          fromForm.hide(true);
          toForm.hide(true);
          switchButton.hide(true);
          predefinedForm.show(true);
          predefinedForm.reload();
          predefinedButton.setText($$("date.column.search.show-less-options", null, null, "Manual Range Definition"));
        } else {
          predefinedForm.hide(true);
          switchButton.show(true);
          switchFields();
          predefinedButton.setText($$("date.range.column.search.predefined-ranges", null, null, "Relative Dates"));
          _this.__clearPredefinedData(data, fieldName);
        }
      };
    })(this);
    buttonContainer = new CUI.HorizontalList({
      content: [switchButton, predefinedButton]
    });
    form = new CUI.Form({
      undo_and_changed_support: false,
      fields: [
        fromToForm, fromForm, toForm, predefinedForm, {
          type: CUI.DataFieldProxy,
          element: buttonContainer
        }
      ],
      data: data,
      onRender: (function(_this) {
        return function() {
          switchFields();
          return switchPredefinedFields();
        };
      })(this),
      onDataChanged: function(_, field) {
        return CUI.Events.trigger({
          node: field,
          type: "search-input-change"
        });
      }
    }).start();
    return form;
  };

  DateRangeColumn.prototype.__renderLegacySearchInput = function(data) {
    var fieldName, form, fromFields, fromForm, fromToFields, fromToForm, isTextualRepresentation, showMoreOptions, switchButton, switchFields, toFields, toForm;
    fieldName = this.name();
    fromFields = this.__getSearchFields(data, {
      fieldOptions: ["from:from", "from:to"]
    });
    fromForm = new CUI.Form({
      "class": "ez5-date-range-form",
      fields: fromFields
    });
    toFields = this.__getSearchFields(data, {
      fieldOptions: ["to:from", "to:to"]
    });
    toForm = new CUI.Form({
      "class": "ez5-date-range-form",
      fields: toFields
    });
    isTextualRepresentation = this.__isTextualRepresentation();
    if (isTextualRepresentation) {
      fromToForm = this.__getTextualRepresentationFields(data, fieldName + ":from", fieldName + ":to", false);
    } else {
      fromToFields = this.__getSearchFields(data, {
        fieldOptions: ["from", "to"]
      });
      fromToForm = new CUI.Form({
        "class": "ez5-date-range-form",
        fields: fromToFields
      });
    }
    if ((data[fieldName + ":from:to"] != null) || (data[fieldName + ":from:from"] != null) || (data[fieldName + ":to:from"] != null) || (data[fieldName + ":to:to"] != null)) {
      showMoreOptions = true;
    } else {
      showMoreOptions = false;
    }
    switchButton = new CUI.Button({
      text: $$("date.range.column.search.show-more-options"),
      appearance: "link",
      size: "mini",
      onClick: (function(_this) {
        return function() {
          var from, to;
          showMoreOptions = !showMoreOptions;
          switchFields();
          if (showMoreOptions) {
            data[fieldName + ":from:from"] = data[fieldName + ":from"];
            data[fieldName + ":from:to"] = data[fieldName + ":to"];
            data[fieldName + ":from"] = null;
            data[fieldName + ":to"] = null;
            toForm.reload();
            fromForm.reload();
          } else {
            data[fieldName + ":from"] = data[fieldName + ":from:from"];
            data[fieldName + ":to"] = data[fieldName + ":from:to"];
            data[fieldName + ":from:from"] = null;
            data[fieldName + ":from:to"] = null;
            if (isTextualRepresentation) {
              from = data[fieldName + ":from"];
              to = data[fieldName + ":to"];
              if (from !== "" || to !== "") {
                data.string_date = _this.__dateRangeToString(from, to);
              } else {
                data.string_date = "";
              }
            }
            fromToForm.reload();
          }
          CUI.Events.trigger({
            node: form,
            type: "search-input-change"
          });
          CUI.Events.trigger({
            type: "viewport-resize"
          });
        };
      })(this)
    });
    switchFields = (function(_this) {
      return function() {
        if (showMoreOptions) {
          toForm.show(true);
          fromForm.show(true);
          CUI.dom.showElement(toForm);
          CUI.dom.showElement(fromForm);
          fromToForm.hide(true);
          CUI.dom.hideElement(fromToForm);
          switchButton.setText($$("date.range.column.search.show-less-options"));
        } else {
          toForm.hide(true);
          fromForm.hide(true);
          CUI.dom.hideElement(toForm);
          CUI.dom.hideElement(fromForm);
          fromToForm.show(true);
          CUI.dom.showElement(fromToForm);
          switchButton.setText($$("date.range.column.search.show-more-options"));
        }
      };
    })(this);
    form = new CUI.Form({
      undo_and_changed_support: false,
      fields: [
        fromToForm, fromForm, toForm, {
          type: CUI.DataFieldProxy,
          element: switchButton
        }
      ],
      data: data,
      onRender: (function(_this) {
        return function() {
          return switchFields();
        };
      })(this),
      onDataChanged: function(_, field) {
        return CUI.Events.trigger({
          node: field,
          type: "search-input-change"
        });
      }
    }).start();
    return form;
  };

  DateRangeColumn.prototype.__getPredefinedOptionsForm = function(data) {
    var fieldName;
    fieldName = this.name();
    return new CUI.DataFieldProxy({
      element: (function(_this) {
        return function(df) {
          var customFromAmountInput, customFromDirectionSelect, customFromOptionsLayout, customFromUnitSelect, customToAmountInput, customToDirectionSelect, customToOptionsLayout, customToUnitSelect, fromSelectOptions, layout, predefinedFromSelect, predefinedToSelect, toSelectOptions;
          fromSelectOptions = _this.__getPredefinedSelectOptions();
          fromSelectOptions[0] = {
            text: $$("date.column.predefined.select_range", null, null, "Select FROM range..."),
            value: null
          };
          toSelectOptions = _this.__getPredefinedSelectOptions();
          toSelectOptions[0] = {
            text: $$("date.column.predefined.select_range", null, null, "Select TO range..."),
            value: null
          };
          predefinedFromSelect = new CUI.Select({
            "class": "ez5-date-range-select-from",
            name: fieldName + ":predefined_from_type",
            options: fromSelectOptions,
            data: data,
            onDataChanged: function(data, select) {
              if (data[fieldName + ":predefined_from_type"] === "custom") {
                customFromOptionsLayout.show();
              } else {
                customFromOptionsLayout.hide();
              }
              return CUI.Events.trigger({
                node: select,
                type: "search-input-change"
              });
            }
          });
          predefinedToSelect = new CUI.Select({
            "class": "ez5-date-range-select-to",
            name: fieldName + ":predefined_to_type",
            options: toSelectOptions,
            data: data,
            onDataChanged: function(data, select) {
              if (data[fieldName + ":predefined_to_type"] === "custom") {
                customToOptionsLayout.show();
              } else {
                customToOptionsLayout.hide();
              }
              return CUI.Events.trigger({
                node: select,
                type: "search-input-change"
              });
            }
          });
          customFromAmountInput = new CUI.NumberInput({
            name: fieldName + ":predefined_from_custom_amount",
            placeholder: $$("date.column.predefined.custom_amount.placeholder", null, null, "Amount..."),
            min: 1,
            data: data,
            onDataChanged: function(data, input) {
              return CUI.Events.trigger({
                node: input,
                type: "search-input-change"
              });
            }
          });
          customFromUnitSelect = new CUI.Select({
            name: fieldName + ":predefined_from_custom_unit",
            options: _this.__getPredefinedCustomUnitOptions(),
            data: data,
            onDataChanged: function(data, select) {
              return CUI.Events.trigger({
                node: select,
                type: "search-input-change"
              });
            }
          });
          customFromDirectionSelect = new CUI.Select({
            name: fieldName + ":predefined_from_custom_direction",
            options: _this.__getPredefinedCustomDirectionOptions(),
            data: data,
            onDataChanged: function(data, select) {
              return CUI.Events.trigger({
                node: select,
                type: "search-input-change"
              });
            }
          });
          customToAmountInput = new CUI.NumberInput({
            name: fieldName + ":predefined_to_custom_amount",
            placeholder: $$("date.column.predefined.custom_amount.placeholder", null, null, "Amount..."),
            min: 1,
            data: data,
            onDataChanged: function(data, input) {
              return CUI.Events.trigger({
                node: input,
                type: "search-input-change"
              });
            }
          });
          customToUnitSelect = new CUI.Select({
            name: fieldName + ":predefined_to_custom_unit",
            options: _this.__getPredefinedCustomUnitOptions(),
            data: data,
            onDataChanged: function(data, select) {
              return CUI.Events.trigger({
                node: select,
                type: "search-input-change"
              });
            }
          });
          customToDirectionSelect = new CUI.Select({
            name: fieldName + ":predefined_to_custom_direction",
            options: _this.__getPredefinedCustomDirectionOptions(),
            data: data,
            onDataChanged: function(data, select) {
              return CUI.Events.trigger({
                node: select,
                type: "search-input-change"
              });
            }
          });
          customFromOptionsLayout = new CUI.HorizontalList({
            "class": "ez5-date-custom-options ez5-date-custom-options-from",
            content: [customFromAmountInput, customFromUnitSelect, customFromDirectionSelect]
          });
          customToOptionsLayout = new CUI.HorizontalList({
            "class": "ez5-date-custom-options ez5-date-custom-options-to",
            content: [customToAmountInput, customToUnitSelect, customToDirectionSelect]
          });
          layout = new CUI.dom.div("ez5-date-range-custom");
          CUI.dom.append(layout, [
            new CUI.Label({
              text: $$("date.column.search.label.from", null, null, "Start"),
              "class": "ez5-date-range-custom-label-from"
            }), predefinedFromSelect, customFromOptionsLayout, new CUI.dom.div("ez5-date-range-divider"), new CUI.Label({
              text: $$("date.column.search.label.to", null, null, "End"),
              "class": "ez5-date-range-custom-label-to"
            }), predefinedToSelect, customToOptionsLayout
          ]);
          if (data[fieldName + ":predefined_from_type"] !== "custom") {
            customFromOptionsLayout.hide();
          }
          if (data[fieldName + ":predefined_to_type"] !== "custom") {
            customToOptionsLayout.hide();
          }
          return layout;
        };
      })(this)
    });
  };

  DateRangeColumn.prototype.getFacet = function(opts) {
    opts.field = this;
    return new DateRangeFacet(opts);
  };

  DateRangeColumn.prototype.getPlaceholderText = function(targetInput, data) {
    var custom_placeholder, placeholder, ref, ref1;
    placeholder = this.getFallbackValue(data, {}, "display_short");
    if (CUI.util.isEmpty(placeholder[targetInput])) {
      custom_placeholder = (ref = this.FieldSchema) != null ? (ref1 = ref.custom_settings) != null ? ref1["edit_user_placeholder_l10n_" + targetInput] : void 0 : void 0;
      if (custom_placeholder) {
        return ez5.loca.getBestFrontendValue(custom_placeholder);
      }
      return this.getFormattedPlaceholder("date.range.column.field." + targetInput + ".formatted.placeholder", "date");
    }
    return placeholder[targetInput];
  };

  DateRangeColumn.prototype.renderEditorInput = function(data, _, opts) {
    var _data, fields, form, placeholder, ref, ref1, ref2, ref3, textualRepresentationText, toDate;
    if (CUI.util.isEmptyObject(data[this.name()])) {
      data[this.name()] = {
        from: null,
        to: null
      };
    }
    toDate = null;
    fields = [
      {
        type: CUI.DateTime,
        name: "from",
        locale: this.getDataLocale(),
        store_invalid: true,
        avoid_bc_conversion: ((ref = this.FieldSchema.custom_settings) != null ? ref.avoid_bc_conversion : void 0) || false,
        input_types: this.getDateTimeInputTypes(),
        display_type: "short",
        show_calendar: this.showCalendar(),
        placeholder: this.getPlaceholderText("from", data),
        id: this.idAttribute(data) + ".from",
        onDataChanged: (function(_this) {
          return function(_, field) {
            var from, toPlaceholder;
            if (data[_this.name()].to) {
              return;
            }
            field.focus();
            from = data[_this.name()].from;
            if (!from || from === "invalid") {
              toPlaceholder = _this.getPlaceholderText("to", data);
              return toDate.setPlaceholder(toPlaceholder);
            } else {
              return toDate.setPlaceholder(from);
            }
          };
        })(this),
        onBlur: (function(_this) {
          return function() {
            var from;
            if (data[_this.name()].to) {
              return;
            }
            from = data[_this.name()].from;
            if (!from || from === "invalid") {
              data[_this.name()].to = null;
            } else {
              data[_this.name()].to = from;
            }
            toDate.reload();
            CUI.Events.trigger({
              node: form,
              type: "editor-changed"
            });
          };
        })(this)
      }, toDate = new CUI.DateTime({
        name: "to",
        id: this.idAttribute(data) + ".to",
        avoid_bc_conversion: ((ref1 = this.FieldSchema.custom_settings) != null ? ref1.avoid_bc_conversion : void 0) || false,
        placeholder: this.getPlaceholderText("to", data),
        locale: this.getDataLocale(),
        show_calendar: this.showCalendar(),
        store_invalid: true,
        input_types: this.getDateTimeInputTypes(),
        display_type: "short"
      })
    ];
    _data = data[this.name()];
    if (this.__isTextualRepresentation()) {
      textualRepresentationText = ez5.loca.getBestFrontendValue(data[this.name()].text);
      if (opts.mode === "editor-template" && !textualRepresentationText && ((ref2 = data[this.name()]) != null ? ref2.string_date : void 0)) {
        textualRepresentationText = data[this.name()].string_date;
      }
      data[this.name()].string_date = textualRepresentationText || "";
      fields[0].hidden = true;
      toDate.hide(true);
      placeholder = (ref3 = this.getFallbackValue(data)) != null ? ref3.string_date : void 0;
      fields = fields.concat(this.__getTextualRepresentationFields(_data, "from", "to", true, placeholder));
    }
    return form = new CUI.Form({
      data: _data,
      "class": "ez5-date-range-form",
      fields: fields,
      onDataChanged: (function(_this) {
        return function() {
          CUI.Events.trigger({
            node: form,
            type: "editor-changed"
          });
        };
      })(this)
    }).start().DOM;
  };

  DateRangeColumn.prototype.renderDetailOutput = function(data, top_level_data, opts) {
    var _data, date_text, from, label, labelText, ref, secondaryLabel, separator, textualRepresentationText, to, verticalList;
    _data = data[this.name()];
    if (!_data) {
      return "";
    }
    from = _data.from;
    to = _data.to;
    if (this.__isTextualRepresentation() && (textualRepresentationText = ez5.loca.getBestFrontendValue(data[this.name()].text))) {
      label = new CUI.Label({
        text: textualRepresentationText
      });
      if (!this.__showInternalDatesInTextualRepresentation()) {
        return label;
      }
      labelText = this.__getInternalDatesTextForTextualRepresentation(from, to);
      if (label.getText() === labelText) {
        return label;
      }
      if (opts.fieldRenderType === "table") {
        if (CUI.util.isEmpty(labelText)) {
          return label;
        }
        return new CUI.Label({
          text: textualRepresentationText + " ( " + labelText + " )"
        });
      }
      secondaryLabel = new CUI.Label({
        size: "mini",
        appearance: "secondary",
        text: labelText
      });
      verticalList = new CUI.VerticalList({
        content: [label, secondaryLabel]
      });
      return verticalList;
    }
    from = this.renderDateValue(from) || "";
    to = this.renderDateValue(to) || "";
    if (from === to) {
      date_text = from;
    } else {
      if ((ref = this.FieldSchema.custom_settings) != null ? ref.avoid_bc_conversion : void 0) {
        separator = " " + ($$("admin.datamodel.range_to.placeholder").toLowerCase()) + " ";
      } else {
        separator = " - ";
      }
      date_text = ("" + from + separator + to).trim();
    }
    return new CUI.Label({
      text: date_text
    });
  };

  DateRangeColumn.prototype.sortExtraOpts = function() {
    return [
      {
        text: $$('date.range.column.sort.from'),
        value: "from"
      }, {
        text: $$('date.range.column.sort.to'),
        value: "to"
      }
    ];
  };

  DateRangeColumn.prototype.getSortFields = function(filter) {
    var sortField;
    sortField = {
      field: this.fullName() + "." + filter._extra,
      order: filter._order
    };
    return sortField;
  };

  DateRangeColumn.prototype.getCheckInfo = function(mode) {
    var info;
    if (mode === "detail" || mode === "text") {
      return [];
    }
    if (!this.__isTextualRepresentation()) {
      return DateRangeColumn.__super__.getCheckInfo.call(this);
    }
    info = [$$("date.range.column.textual-representation-hint.md")];
    return info;
  };

  DateRangeColumn.prototype.__isTextualRepresentation = function() {
    var ref;
    return !!((ref = this.FieldSchema.custom_settings) != null ? ref.enable_textual_representation : void 0);
  };

  DateRangeColumn.prototype.__showInternalDatesInTextualRepresentation = function() {
    var ref;
    return !!((ref = this.FieldSchema.custom_settings) != null ? ref.textual_representation_show_internal_dates : void 0);
  };

  DateRangeColumn.prototype.__getTextualRepresentationFields = function(data, fromName, toName, addSwitchButton, placeholder) {
    var fields, form, fromField, outputDiv, setStringDate, stringDateField, toField, toRangeRepresentationText, toTextualRepresentationText, updateOutput;
    if (addSwitchButton == null) {
      addSwitchButton = true;
    }
    if (placeholder == null) {
      placeholder = $$("date.range.column.field.placeholder");
    }
    form = null;
    stringDateField = null;
    fromField = null;
    toField = null;
    setStringDate = (function(_this) {
      return function() {
        if (data.string_date !== "") {
          return;
        }
        return data.string_date = _this.__dateRangeToString(data[fromName], data[toName]) || "";
      };
    })(this);
    setStringDate();
    outputDiv = CUI.dom.div();
    updateOutput = (function(_this) {
      return function() {
        var from, internalDatesText, label, to;
        CUI.dom.empty(outputDiv);
        if (!CUI.dom.isVisible(stringDateField)) {
          return;
        }
        from = data[fromName];
        to = data[toName];
        internalDatesText = _this.__getInternalDatesTextForTextualRepresentation(from, to);
        if (!internalDatesText) {
          return;
        }
        label = new CUI.Label({
          size: "mini",
          appearance: "secondary",
          text: internalDatesText
        });
        CUI.dom.replace(outputDiv, label);
      };
    })(this);
    toTextualRepresentationText = $$("date.range.column.textual-representation-button");
    toRangeRepresentationText = $$("date.range.column.range-representation-button");
    fields = [
      {
        type: CUI.Input,
        name: "string_date",
        placeholder: placeholder,
        hidden: false,
        onDataInit: function(dataField) {
          form = dataField.getForm();
          CUI.Events.listen({
            node: form,
            type: "data-changed",
            call: (function(_this) {
              return function() {
                updateOutput();
              };
            })(this)
          });
          stringDateField = form.getFieldsByName("string_date")[0];
          fromField = form.getFieldsByName(fromName)[0];
          toField = form.getFieldsByName(toName)[0];
          return updateOutput();
        },
        onDataChanged: (function(_this) {
          return function() {
            var value;
            value = CUI.DateTime.stringToDateRange(data.string_date);
            data[fromName] = value != null ? value.from : void 0;
            data[toName] = value != null ? value.to : void 0;
          };
        })(this),
        onBlur: (function(_this) {
          return function() {
            var value;
            if (CUI.util.isEmpty(data.string_date)) {
              delete data[fromName];
              delete data[toName];
            } else {
              value = CUI.DateTime.stringToDateRange(data.string_date);
              if (!value.error) {
                data[fromName] = value != null ? value.from : void 0;
                data[toName] = value != null ? value.to : void 0;
              }
            }
            if (fromField && CUI.dom.isVisible(fromField)) {
              fromField.reload();
              toField.reload();
            }
            updateOutput();
            CUI.Events.trigger({
              node: form,
              type: "editor-changed"
            });
          };
        })(this),
        checkInput: (function(_this) {
          return function(value) {
            value = CUI.DateTime.stringToDateRange(value);
            return !value.error;
          };
        })(this)
      }
    ];
    if (addSwitchButton) {
      fields.push({
        type: CUI.DataFieldProxy,
        name: "output_string_date",
        id: this.idAttribute(data),
        element: function() {
          var button;
          button = new CUI.Button({
            text: toRangeRepresentationText,
            appearance: "link",
            size: "mini",
            onClick: function() {
              if (!CUI.dom.isVisible(stringDateField)) {
                setStringDate();
                stringDateField.show(true).reload();
                if (fromField != null) {
                  fromField.hide(true);
                }
                if (toField != null) {
                  toField.hide(true);
                }
                button.setText(toRangeRepresentationText);
              } else {
                stringDateField.hide(true);
                if (fromField != null) {
                  fromField.show(true).reload();
                }
                if (toField != null) {
                  toField.show(true).reload();
                }
                button.setText(toTextualRepresentationText);
              }
              updateOutput();
            }
          });
          return new CUI.HorizontalList({
            content: [outputDiv, CUI.dom.space('flexible'), button]
          });
        }
      });
      return fields;
    }
    return CUI.DataField["new"](fields[0]);
  };

  DateRangeColumn.prototype.__getInternalDatesTextForTextualRepresentation = function(from, to) {
    var avoid_bc, formatfn, labelText, ref;
    if (!this.__showInternalDatesInTextualRepresentation()) {
      return;
    }
    avoid_bc = ((ref = this.FieldSchema.custom_settings) != null ? ref.avoid_bc_conversion : void 0) || false;
    formatfn = avoid_bc ? CUI.DateTime.formatWithoutBC : CUI.DateTime.format;
    if (!to && from) {
      labelText = $$("date.range.column.text-representation.open_to", {
        date: formatfn(from, "display_short")
      });
    } else if (!from && to) {
      labelText = $$("date.range.column.text-representation.open_from", {
        date: formatfn(to, "display_short")
      });
    } else if (from === to) {
      labelText = formatfn(from, "display_short");
    } else {
      labelText = $$("date.range.column.output.text", {
        from: formatfn(from, "display_short"),
        to: formatfn(to, "display_short")
      });
    }
    return labelText;
  };

  DateRangeColumn.prototype.updateValue = function(data, value) {
    var dateFrom, dateFromDOM, dateTo, dateToDOM, element, ref, stringDate, textDOM, textInput;
    element = this.__getRenderedElement(data);
    if (!element) {
      return;
    }
    ref = CUI.dom.matchSelector(element, ".cui-date-time"), dateFromDOM = ref[0], dateToDOM = ref[1];
    dateFrom = CUI.dom.data(dateFromDOM, "element");
    dateTo = CUI.dom.data(dateToDOM, "element");
    try {
      if (value.from) {
        dateFrom.setValue(value.from, {
          no_trigger: false
        });
      }
      if (value.to) {
        dateTo.setValue(value.to, {
          no_trigger: false
        });
      }
    } catch (error1) {}
    if (!this.__isTextualRepresentation()) {
      return;
    }
    textDOM = CUI.dom.matchSelector(element, ".cui-data-field-input")[2];
    textInput = CUI.dom.data(textDOM, "element");
    if (!(textInput instanceof CUI.Input)) {
      return;
    }
    stringDate = this.__dateRangeToString(value.from, value.to);
    if (!stringDate) {
      return;
    }
    textInput.setValue(stringDate, {
      no_trigger: false
    });
    dateFrom.reload();
    dateTo.reload();
  };

  DateRangeColumn.prototype.__dateRangeToString = function(from, to, locale) {
    var avoid_bc, ref;
    avoid_bc = ((ref = this.FieldSchema.custom_settings) != null ? ref.avoid_bc_conversion : void 0) || false;
    return CUI.DateTime.dateRangeToString(from, to, locale, avoid_bc);
  };

  DateRangeColumn.prototype.getSearchFilter = function(data, key) {
    var filter, filterFrom, filterFromTo, filterTo, predefinedFromType, predefinedMode, predefinedToType;
    if (key == null) {
      key = this.name();
    }
    predefinedMode = data[key + ":predefined_mode"];
    if (predefinedMode) {
      predefinedFromType = data[key + ":predefined_from_type"];
      predefinedToType = data[key + ":predefined_to_type"];
      if (!CUI.util.isEmpty(predefinedFromType) || !CUI.util.isEmpty(predefinedToType)) {
        return this.__getPredefinedSearchFilter(data, key, predefinedFromType, predefinedToType);
      }
    } else if (!predefinedMode) {
      this.__clearPredefinedData(data, key);
    }
    filterFromTo = DateRangeColumn.__super__.getSearchFilter.call(this, data, key);
    if (filterFromTo) {
      return this.__addRangesToFilter(filterFromTo);
    }
    filterFrom = DateRangeColumn.__super__.getSearchFilter.call(this, data, key + ":from", false);
    filterTo = DateRangeColumn.__super__.getSearchFilter.call(this, data, key + ":to", false);
    if (!filterFrom && !filterTo) {
      return;
    }
    if (!filterFrom) {
      return filterTo;
    }
    if (!filterTo) {
      return filterFrom;
    }
    filter = {
      type: "complex",
      search: [filterFrom, filterTo]
    };
    return filter;
  };

  DateRangeColumn.prototype.__getPredefinedSearchFilter = function(data, key, predefinedFromType, predefinedToType) {
    var filter, fromValue, toValue;
    filter = {
      type: "range",
      field: this.getSearchField(key)
    };
    if (!CUI.util.isEmpty(predefinedFromType)) {
      fromValue = this.__getPredefinedValue(data, key, predefinedFromType, "from");
      if (fromValue) {
        filter.from = fromValue;
      }
    }
    if (!CUI.util.isEmpty(predefinedToType)) {
      toValue = this.__getPredefinedValue(data, key, predefinedToType, "to");
      if (toValue) {
        filter.to = toValue;
      }
    }
    if (!filter.from && !filter.to) {
      return null;
    }
    return this.__addRangesToFilter(filter);
  };

  DateRangeColumn.prototype.__getPredefinedValue = function(data, key, predefinedType, fieldType) {
    var customAmount, customDirection, customUnit, unitSuffix;
    switch (predefinedType) {
      case "today":
        return "$today";
      case "yesterday":
        return "$today-1d";
      case "in_7_days":
        if (fieldType === "from") {
          return "$today";
        } else {
          return "$today+7d";
        }
        break;
      case "last_7_days":
        if (fieldType === "from") {
          return "$today-7d";
        } else {
          return "$today";
        }
        break;
      case "in_one_month":
        if (fieldType === "from") {
          return "$today";
        } else {
          return "$today+1M";
        }
        break;
      case "last_month":
        if (fieldType === "from") {
          return "$today-1M";
        } else {
          return "$today";
        }
        break;
      case "custom":
        customAmount = data[key + ":predefined_" + fieldType + "_custom_amount"];
        customDirection = data[key + ":predefined_" + fieldType + "_custom_direction"];
        customUnit = data[key + ":predefined_" + fieldType + "_custom_unit"];
        if (CUI.util.isEmpty(customAmount) || customAmount < 1) {
          return null;
        }
        if (CUI.util.isEmpty(customDirection)) {
          return null;
        }
        if (CUI.util.isEmpty(customUnit)) {
          return null;
        }
        unitSuffix = (function() {
          switch (customUnit) {
            case "days":
              return "d";
            case "weeks":
              return "w";
            case "months":
              return "M";
            case "years":
              return "y";
            default:
              return "d";
          }
        })();
        if (customDirection === "backward") {
          return "$today-" + customAmount + unitSuffix;
        } else {
          return "$today+" + customAmount + unitSuffix;
        }
        break;
      default:
        return null;
    }
  };

  DateRangeColumn.prototype.__clearPredefinedData = function(data, fieldName) {
    data[fieldName + ":predefined_from_type"] = null;
    data[fieldName + ":predefined_to_type"] = null;
    data[fieldName + ":predefined_from_custom_amount"] = null;
    data[fieldName + ":predefined_from_custom_direction"] = null;
    data[fieldName + ":predefined_from_custom_unit"] = null;
    data[fieldName + ":predefined_to_custom_amount"] = null;
    data[fieldName + ":predefined_to_custom_direction"] = null;
    data[fieldName + ":predefined_to_custom_unit"] = null;
  };

  DateRangeColumn.prototype.getSearchField = function(key) {
    var field, ref, remoteInstance, type;
    if (key == null) {
      key = this.name();
    }
    type = key.split(":")[1];
    if (!type) {
      field = DateRangeColumn.__super__.getSearchField.call(this);
      if (!CUI.util.isEmpty(this.table.getInstance())) {
        remoteInstance = (ref = ez5.connector) != null ? ref.getRemoteEasydbByInstance(this.table.getInstance()) : void 0;
        return this.getSearchFieldForRemoteInstance(remoteInstance, field);
      }
      if (ez5.version("6")) {
        return field;
      } else if (ez5.version("5.96")) {
        type = "from_to";
      } else {
        return field;
      }
    }
    return DateRangeColumn.__super__.getSearchField.call(this, this.name(), type);
  };

  DateRangeColumn.prototype.getSearchFieldForRemoteInstance = function(remoteInstance, field) {
    if (typeof remoteInstance.isFylr === "function" ? remoteInstance.isFylr() : void 0) {
      return field + ".range";
    }
    return field + ".from_to";
  };

  return DateRangeColumn;

})(DateColumn);
// Generated by CoffeeScript 1.12.7
var DateTimeColumn,
  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;

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

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

  DateTimeColumn.prototype.getDateTimeInputTypes = function() {
    return ["date_time", "date"];
  };

  DateTimeColumn.prototype.renderDateValue = function(value) {
    return CUI.DateTime.format(value, "display", "date_time", false, this.getDataLocale());
  };

  DateTimeColumn.prototype.__formatBareValue = function(v) {
    return this.renderDateValue(v);
  };

  DateTimeColumn.prototype.getCSVDestinationFields = function(csvImporter) {
    var opts;
    opts = {
      csvImporter: csvImporter,
      field: this
    };
    return [new DateTimeColumnCSVImporterDestinationField(opts)];
  };

  DateTimeColumn.prototype.getInvalidKey = function() {
    return "date.time.column.check.invalid";
  };

  DateTimeColumn.prototype.__getPlaceholder = function() {
    return this.getCustomPlaceholder() || this.getFormattedPlaceholder("date.time.column.formatted.placeholder", "date_time");
  };

  return DateTimeColumn;

})(DateColumn);
// Generated by CoffeeScript 1.12.7
var TextColumn,
  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;

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

  function TextColumn() {
    this.getQueryFieldBadge = bind(this.getQueryFieldBadge, this);
    return TextColumn.__super__.constructor.apply(this, arguments);
  }

  TextColumn.prototype.getQueryFieldBadge = function(data) {
    var badge, value;
    badge = data[(this.name()) + ":badge"];
    if (badge) {
      value = badge;
    } else if (data[(this.name()) + ":unset"]) {
      value = $$("text.column.badge.without");
    } else if (data[(this.name()) + ":has_value"]) {
      value = $$("field.search.badge.has_value");
    } else {
      value = data[this.name()];
    }
    return {
      name: this.nameLocalized(),
      value: value
    };
  };

  TextColumn.prototype.getSearchFilter = function(data, key) {
    var filter;
    if (key == null) {
      key = this.name();
    }
    filter = TextColumn.__super__.getSearchFilter.call(this, data, key);
    if (filter) {
      return filter;
    }
    if (!CUI.util.isEmpty(data[key])) {
      return this._getSearchFilter(data, key);
    }
  };

  TextColumn.prototype._getSearchFilter = function(data, key) {
    return TextColumn.getSearchFilter(this.fullName(), data, key, data[key]);
  };

  TextColumn.prototype.allowFullWildcard = function() {
    return true;
  };

  TextColumn.getSearchFilter = function(fname, data, key, val) {
    var filter, phrase, ref, str;
    ref = Search.getPhrase(val), str = ref[0], phrase = ref[1];
    switch (data[key + ":type"]) {
      case "token":
      case "fulltext":
        filter = {
          type: "match",
          mode: data[key + ":mode"],
          fields: [fname],
          string: str,
          phrase: phrase
        };
        break;
      case "exact":
        filter = {
          type: "text",
          query: "exact",
          fields: [fname],
          string: str
        };
        break;
      case "field":
        filter = {
          type: "in",
          fields: [fname],
          "in": [str]
        };
        break;
      default:
        console.error("Unknown filter :type", data, key);
    }
    return filter;
  };

  TextColumn.prototype.renderSearchInput = function(data, opts) {
    if (opts == null) {
      opts = {};
    }
    return (new SearchToken({
      column: this,
      data: data,
      fields: opts.fields
    })).getInput().DOM;
  };

  TextColumn.prototype.getSortFunction = function() {
    return (function(_this) {
      return function(a, b) {
        return (a[_this.name()] || "").localeCompare(b[_this.name()] || "");
      };
    })(this);
  };

  TextColumn.prototype.isDataEqualsValue = function(data, compareValue) {
    var ref;
    return ((ref = data[this.name()]) != null ? ref.trim() : void 0) === compareValue;
  };

  TextColumn.prototype.updateValue = function(data, value) {
    var domInput, element, fieldData, inputElement, newLabel, valueLabel;
    this.setValue(data, value);
    fieldData = data[this.name() + ":rendered"];
    element = fieldData != null ? fieldData.getElement() : void 0;
    if (!element) {
      return;
    }
    if (this.isReadOnly(data)) {
      valueLabel = CUI.dom.matchSelector(element, ".cui-label.ez5-field-value")[0];
      newLabel = this.renderDetailOutput(data);
      CUI.dom.replace(valueLabel, newLabel);
    } else {
      domInput = CUI.dom.matchSelector(element, ".ez5-field-value.cui-data-field-input")[0];
      inputElement = CUI.dom.data(domInput, "element");
      inputElement.updateData(data);
      CUI.Events.trigger({
        node: inputElement,
        type: "editor-changed"
      });
    }
    return this;
  };

  TextColumn.prototype.setValue = function(data, value) {
    return data[this.name()] = value;
  };

  TextColumn.prototype.emptyEditorInputValue = function(value, top_level_data) {
    var data;
    data = top_level_data[top_level_data._objecttype];
    if (this.isEmpty(data)) {
      return;
    }
    value = this.__getEditorInputValue(value);
    value = ez5.replaceMap(value, this.getMainMask().getReplacementRecord(top_level_data));
    if (this.isDataEqualsValue(data, value)) {
      this.updateValue(data, "");
    }
  };

  TextColumn.prototype.updateEditorInputValue = function(value, top_level_data) {
    var currentValue, data, objectReplacements, sessionReplacements;
    data = top_level_data[top_level_data._objecttype];
    value = this.__getEditorInputValue(value);
    objectReplacements = this.getMainMask().getReplacementRecord(top_level_data);
    sessionReplacements = ez5.session.getReplacementRecord();
    value = ez5.replaceMap(value, CUI.util.mergeMap(objectReplacements, sessionReplacements));
    if (this.isEmpty(data)) {
      this.updateValue(data, value);
      return;
    }
    if (this.isDataEqualsValue(data, value)) {
      this.updateValue(data, value);
      return;
    }
    currentValue = data[this.name()];
    CUI.confirm({
      markdown: true,
      text: $$("text.column.update.value.confirm", {
        name: this.nameLocalized(),
        current_value: this.formatValue(currentValue),
        new_value: this.formatValue(value)
      })
    }).done((function(_this) {
      return function() {
        return _this.updateValue(data, value);
      };
    })(this));
  };

  TextColumn.prototype.__getEditorInputValue = function(value) {
    value = value != null ? value.trim() : void 0;
    if (CUI.util.isEmpty(value)) {
      return "";
    }
    return value;
  };

  TextColumn.prototype.getPlaceholder = function(data, opts) {
    var ph;
    ph = this.getFallbackValue(data, opts);
    if (CUI.util.isEmpty(ph)) {
      return this.getPlaceholderText();
    }
    return ph;
  };

  TextColumn.prototype.getPlaceholderText = function() {
    var ph;
    ph = this.getCustomPlaceholder();
    if (!CUI.util.isEmpty(ph)) {
      return ph;
    }
    if (this.ColumnSchema.check === "email") {
      return $$('data.column.email_input.placeholder');
    }
    return "";
  };

  TextColumn.prototype.getElementOpts = function(mode, data) {
    var opts;
    opts = TextColumn.__super__.getElementOpts.call(this, mode, data);
    if (this.ColumnSchema.check === "email") {
      opts.type = CUI.EmailInput;
      opts.invalidHint = {
        text: $$('data.column.email_input.invalid_hint')
      };
    }
    return opts;
  };

  TextColumn.prototype.renderEditorInput = function(data, top_level_data, render_opts) {
    var bulk_form, element, opts, ref;
    opts = this.getElementOpts("editor", data);
    opts.placeholder = this.getPlaceholder(data, render_opts);
    if (CUI.util.isNumber(opts.placeholder)) {
      opts.placeholder = '' + opts.placeholder;
    }
    opts.spellcheck = ez5.session.getPref("spellcheck");
    if (ez5.version("6") && this.hasFallbackValue(data, render_opts)) {
      opts.copyPlaceholder = true;
    }
    opts.data = data;
    opts.onDataChanged = (function(_this) {
      return function() {
        return CUI.Events.trigger({
          node: element,
          type: "editor-changed"
        });
      };
    })(this);
    opts.ui = "text_column:" + render_opts.mode + ":" + this.idAttribute(data);
    opts.id = this.idAttribute(data);
    element = CUI.DataField["new"](opts).start().DOM;
    if ((ref = render_opts.mode) !== "editor-bulk" && ref !== "editor-header-bulk") {
      return element;
    }
    if (render_opts.nested_level === void 0) {
      bulk_form = this.getBulkForm(data, element);
    }
    if (bulk_form) {
      return new CUI.VerticalList({
        content: [element, bulk_form]
      });
    } else {
      return element;
    }
  };

  TextColumn.prototype.getBulkForm = function(data, element) {
    var bulk_data, bulk_fields, bulk_form, update_bulk_form;
    bulk_data = data[(this.name()) + ":options"];
    if (!bulk_data) {
      bulk_data = data[(this.name()) + ":options"] = {};
    }
    update_bulk_form = (function(_this) {
      return function() {
        var appendCheckbox, i, j, k, len, len1, n, ref, ref1;
        ref = ["search", "replace", "full_words", "case_sensitive"];
        for (i = 0, len = ref.length; i < len; i++) {
          k = ref[i];
          if (bulk_data.search_and_replace) {
            bulk_form.getFieldsByName(k)[0].show(true);
            if (ez5.version("6.7")) {
              ref1 = ["append", "append_with_space"];
              for (j = 0, len1 = ref1.length; j < len1; j++) {
                n = ref1[j];
                appendCheckbox = bulk_form.getFieldsByName(n)[0];
                appendCheckbox.hide(true);
                appendCheckbox.setValue(false);
              }
            }
          } else if (bulk_data.append) {
            bulk_form.getFieldsByName(k)[0].hide(true);
            if (ez5.version("6.7")) {
              bulk_form.getFieldsByName("append_with_space")[0].show(true);
            }
          } else {
            bulk_form.getFieldsByName(k)[0].hide(true);
            if (ez5.version("6.7")) {
              bulk_form.getFieldsByName("append")[0].show(true);
              bulk_form.getFieldsByName("append_with_space")[0].hide(true);
              bulk_form.getFieldsByName("append_with_space")[0].setValue(false);
            }
          }
        }
        if (bulk_data.search_and_replace) {
          CUI.dom.hideElement(element);
        } else {
          CUI.dom.showElement(element);
        }
        CUI.Events.trigger({
          node: element,
          type: "editor-changed"
        });
      };
    })(this);
    bulk_fields = [
      {
        type: CUI.Checkbox,
        undo_and_changed_support: false,
        name: "search_and_replace",
        text: $$("text.column.bulk.form.search_and_replace")
      }, {
        type: CUI.Input,
        undo_and_changed_support: false,
        name: "search",
        placeholder: $$("text.column.bulk.form.search")
      }, {
        type: CUI.Input,
        undo_and_changed_support: false,
        name: "replace",
        placeholder: $$("text.column.bulk.form.replace")
      }, {
        type: CUI.Checkbox,
        undo_and_changed_support: false,
        name: "full_words",
        text: $$("text.column.bulk.form.full_words")
      }, {
        type: CUI.Checkbox,
        undo_and_changed_support: false,
        name: "case_sensitive",
        text: $$("text.column.bulk.form.case_sensitive")
      }
    ];
    if (ez5.version("6.7")) {
      bulk_fields.push({
        type: CUI.Checkbox,
        undo_and_changed_support: false,
        name: "append",
        text: $$("text.column.bulk.form.append")
      });
      bulk_fields.push({
        type: CUI.Checkbox,
        undo_and_changed_support: false,
        form: {
          label: $$("text.column.bulk.form.append.options")
        },
        name: "append_with_space",
        text: $$("text.column.bulk.form.append_with_space")
      });
    }
    bulk_form = new CUI.Form({
      data: bulk_data,
      onDataChanged: update_bulk_form,
      undo_and_changed_support: false,
      "class": "ez5-form-search-and-replace",
      fields: bulk_fields
    }).start();
    update_bulk_form();
    return bulk_form;
  };

  TextColumn.prototype.hasFallbackValue = function(data, opts) {
    return !CUI.util.isEmpty(this.getFallbackValue(data, opts));
  };

  TextColumn.prototype.getFallbackValue = function(data, opts) {
    var mv, ref, tv;
    tv = (ref = data._template) != null ? ref[this.name()] : void 0;
    mv = data[this.name() + ":mapped_metadata"];
    if (CUI.util.isString(tv)) {
      tv = tv.trim();
    }
    if (CUI.util.isString(mv)) {
      mv = mv.trim();
    }
    if (this.preferTemplateOverMapping(opts)) {
      if (!CUI.util.isEmpty(tv)) {
        return tv;
      } else {
        return mv;
      }
    } else {
      if (!CUI.util.isEmpty(mv)) {
        return mv;
      } else {
        return tv;
      }
    }
  };

  TextColumn.prototype.getSaveData = function(data, save_data, opts) {
    var preTrimmedValue, ref, ref1, ref2;
    if (opts.copy && this.isUnique()) {
      if (this.isReadOnly(data, save_data, opts) || !this.isVisible(opts.mode || "editor")) {
        return;
      }
    }
    if (opts.demo_data) {
      if (((ref = this.ColumnSchema) != null ? ref.check : void 0) === "email") {
        save_data[this.name()] = "email@example.com";
      } else {
        save_data[this.name()] = "<" + this.fullNameLocalized();
        if ((ref1 = save_data._top_level) != null ? ref1._system_object_id : void 0) {
          save_data[this.name()] += " [" + save_data._top_level._system_object_id + "]>";
        } else {
          save_data[this.name()] += ">";
        }
      }
    } else {
      if (CUI.util.isEmpty(data[this.name()])) {
        save_data[this.name()] = this.getFallbackValue(data, opts);
      } else {
        save_data[this.name()] = data[this.name()];
        if (CUI.util.isString(save_data[this.name()])) {
          preTrimmedValue = CUI.util.copyObject(save_data[this.name()]);
          save_data[this.name()] = save_data[this.name()].trim();
        }
      }
    }
    if (CUI.util.isNull(save_data[this.name()])) {
      save_data[this.name()] = null;
    }
    if (opts.bulk && this.hasOption(data, "bulk") && data[this.name() + ":options"].append_with_space) {
      save_data[this.name() + ":append"] = " " + ((ref2 = save_data[this.name()]) != null ? ref2.trim() : void 0) || save_data[this.name()];
      return;
    }
    if (opts.bulk && this.hasOption(data, "bulk") && data[this.name() + ":options"].append) {
      save_data[this.name() + ":append"] = preTrimmedValue || save_data[this.name()];
      delete save_data[this.name()];
      return;
    }
    this.getSearchAndReplaceSaveData(data, save_data, opts);
  };

  TextColumn.prototype.getSearchAndReplaceSaveData = function(data, save_data, opts) {
    var bulk_key, i, k, len, ref;
    if (opts.bulk && this.hasOption(data, "bulk") && data[this.name() + ":options"].search_and_replace) {
      ref = ["search", "replace", "full_words", "case_sensitive"];
      for (i = 0, len = ref.length; i < len; i++) {
        k = ref[i];
        bulk_key = this.name() + ":" + k;
        save_data[bulk_key] = data[this.name() + ":options"][k];
      }
      delete save_data[this.name()];
    }
  };

  TextColumn.prototype.checkValue = function(data, top_level_data, opts) {
    if (this.hasOption(data, "bulk") && data[this.name() + ":options"].search_and_replace) {
      if (!CUI.util.isEmpty(data[this.name() + ":options"].search)) {
        return true;
      } else {
        return false;
      }
    }
    return TextColumn.__super__.checkValue.call(this, data, top_level_data, opts);
  };

  TextColumn.prototype.renderDetailOutput = function(data, top_level_data, opts) {
    var html, jsonValue, manage_overflow, multi_opts, ref, ref1, ref2, value;
    if (opts == null) {
      opts = {};
    }
    if (!this.hasUserData(data)) {
      return;
    }
    if (opts.for_print) {
      manage_overflow = false;
    } else {
      manage_overflow = this.getManageOverflow();
    }
    ref = this.renderData(data), value = ref[0], html = ref[1];
    if (html) {
      return new CUI.MultilineLabel({
        content: html,
        manage_overflow: manage_overflow
      }).DOM;
    }
    if (!opts.no_objectdumper && CUI.util.isString(value) && value.trim().startsWith("{")) {
      try {
        jsonValue = JSON.parse(value);
        return new CUI.ObjectDumper({
          object: jsonValue
        });
      } catch (error) {}
    }
    if (CUI.util.isNull(value)) {
      multi_opts = {
        text: "",
        manage_overflow: manage_overflow
      };
    } else {
      multi_opts = {
        text: value + "",
        manage_overflow: manage_overflow
      };
    }
    if ((ref1 = this.FieldSchema) != null ? (ref2 = ref1.custom_settings) != null ? ref2.render_markdown : void 0 : void 0) {
      multi_opts.markdown = true;
      multi_opts["class"] = "ez5-field-value--markdown";
    } else {
      multi_opts.text_node_func = CUI.Label.parseLinks;
    }
    return new CUI.MultilineLabel(multi_opts);
  };

  TextColumn.prototype.isExpertCommon = function(mode) {
    return true;
  };

  TextColumn.prototype.getManageOverflow = function() {
    return false;
  };

  TextColumn.prototype.mergeData = function(top_level_data, top_level_data_new, replace) {
    var data, dataNew, newValue, value;
    if (replace == null) {
      replace = false;
    }
    data = top_level_data[top_level_data._objecttype];
    dataNew = top_level_data_new[top_level_data_new._objecttype];
    if (replace) {
      return TextColumn.__super__.mergeData.call(this, top_level_data, top_level_data_new, replace);
    }
    value = data[this.name()];
    newValue = dataNew[this.name()];
    if ((value != null ? value.trim().length : void 0) > 0 && (newValue != null ? newValue.trim().length : void 0) > 0) {
      data[this.name()] += " " + newValue;
    } else {
      data[this.name()] = newValue;
    }
    return this;
  };

  TextColumn.prototype.getXMLFormWrapperFields = function(wrapperField) {
    if (wrapperField.getXMLFormWrapper().usedForImport()) {
      return [
        {
          type: CUI.Input,
          textarea: true,
          form: {
            hint: $$("text.column.metadata.output_template|hint"),
            label: $$("text.column.metadata.output_template|text")
          },
          name: "output_template"
        }
      ];
    } else {
      return [];
    }
  };

  return TextColumn;

})(DataColumn);
// Generated by CoffeeScript 1.12.7
var NumberColumn,
  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;

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

  function NumberColumn(mask, fieldSchema) {
    NumberColumn.__super__.constructor.call(this, mask, fieldSchema);
    this.SEARCH_REGEXP = new RegExp(this.__getSearchInputRegexp());
  }

  NumberColumn.prototype._getSearchFilter = function(data, key) {
    return this.getSearchFilterTokenized(data[key] + "");
  };

  NumberColumn.prototype.getTokenizer = function() {
    return new NumberTokenizer();
  };

  NumberColumn.prototype.getSaveData = function(data, save_data, opts) {
    if (opts.demo_data) {
      save_data[this.name()] = Math.floor(Math.random() * 100) + 1;
    } else {
      NumberColumn.__super__.getSaveData.call(this, data, save_data, opts);
      if (CUI.util.isEmpty(save_data[this.name()])) {
        save_data[this.name()] = null;
      }
    }
  };


  /*
  	 * Returns the localized decimal point character.
  	 * If the ez5 version is Fylr, it retrieves the decimal point from the first database language's numbers settings.
  	 * If not found, it falls back to the frontend locale's numbers settings.
  	 * If the ez5 version is not Fylr, it directly retrieves the decimal point from the frontend locale's numbers settings.
  	 * @returns {String} The localized decimal point character.
   */

  NumberColumn.prototype.getLocalizedDecimalPoint = function() {
    if (ez5.version("6")) {
      return ez5.session.getFirstDatabaseLanguage().numbers.decimal || ez5.session.frontend_locale.numbers.decimal;
    }
    return ez5.session.frontend_locale.numbers.decimal;
  };


  /*
  	 * Returns the localized grouping separator character.
  	 * If the ez5 version is 6, it retrieves the grouping separator from the first database language's numbers settings.
  	 * If not found, it falls back to the frontend locale's numbers settings.
  	 * If the ez5 version is not 6, it directly retrieves the grouping separator from the frontend locale's numbers settings.
  	 * @returns {String} The localized grouping separator character.
   */

  NumberColumn.prototype.getLocalizedGroupingSeparator = function() {
    if (ez5.version("6")) {
      return ez5.session.getFirstDatabaseLanguage().numbers.grouping || ez5.session.frontend_locale.numbers.grouping;
    }
    return ez5.session.frontend_locale.numbers.grouping;
  };

  NumberColumn.prototype.renderSearchInput = function(data, opts) {
    var input;
    if (opts == null) {
      opts = {};
    }
    if (opts.bulk_expert) {
      return this.renderEditorInput(data, {}, opts);
    }
    input = new CUI.Input({
      name: this.name(),
      placeholder: this.__getSearchPlaceholder(),
      regexp: this.__getSearchInputRegexp(),
      id: this.idAttribute(data),
      onDataChanged: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            node: input,
            type: "search-input-change"
          });
        };
      })(this),
      data: data
    }).start();
    return input.DOM;
  };

  NumberColumn.prototype.allowFullWildcard = function() {
    return false;
  };

  NumberColumn.prototype.getSearchFilter = function(data, key) {
    if (key == null) {
      key = this.name();
    }
    if (!this.SEARCH_REGEXP.test(data[key])) {
      return false;
    }
    return NumberColumn.__super__.getSearchFilter.call(this, data, key);
  };

  NumberColumn.prototype.__getSearchPlaceholder = function() {
    return $$("data.field.number-column.search.placeholder");
  };

  NumberColumn.prototype.__getSearchInputRegexp = function() {
    return "^([0-9](\\s-\\s)?[,]{0,3}?)*$";
  };

  NumberColumn.prototype.getBulkForm = function() {};

  NumberColumn.prototype.getSortFunction = function() {
    return (function(_this) {
      return function(a, b) {
        return CUI.util.compareIndex(a[_this.name()], b[_this.name()]);
      };
    })(this);
  };

  NumberColumn.prototype.getElementOpts = function(mode) {
    return {
      name: this.name(),
      type: CUI.NumberInput,
      decimals: 0
    };
  };

  NumberColumn.prototype.getPlaceholderText = function() {
    var ph;
    ph = this.getCustomPlaceholder();
    if (!CUI.util.isEmpty(ph)) {
      return ph;
    }
    return $$("data.column.number_input.placeholder");
  };

  NumberColumn.prototype.getCSVDestinationFields = function(csvImporter) {
    var opts;
    opts = {
      csvImporter: csvImporter,
      field: this,
      fixed: 0
    };
    return [new NumberColumnCSVImporterDestinationField(opts)];
  };

  NumberColumn.prototype.mergeData = function(top_level_data, top_level_data_new) {
    return NumberColumn.__super__.mergeData.call(this, top_level_data, top_level_data_new, true);
  };

  NumberColumn.prototype.isDataEqualsValue = function(data, compareValue) {
    var value;
    value = data[this.name()];
    return value && compareValue && value === compareValue;
  };

  NumberColumn.prototype.__getEditorInputValue = function(value) {
    if (CUI.util.isEmpty(value)) {
      return;
    }
    return value;
  };

  NumberColumn.prototype.updateValue = function(data, value) {
    return NumberColumn.__super__.updateValue.call(this, data, value === "" ? null : value);
  };

  return NumberColumn;

})(TextColumn);
// Generated by CoffeeScript 1.12.7
var DecimalColumn,
  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;

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

  function DecimalColumn(_mask, _field_schema, fixed, store_as_integer) {
    this.fixed = fixed;
    this.store_as_integer = store_as_integer;
    DecimalColumn.__super__.constructor.call(this, _mask, _field_schema);
  }

  DecimalColumn.prototype.getTokenizer = function() {
    return new DecimalTokenizer();
  };

  DecimalColumn.prototype.getSignature = function() {
    var sig;
    sig = DecimalColumn.__super__.getSignature.call(this);
    sig.fixed = this.fixed;
    return sig;
  };

  DecimalColumn.prototype.getElementOpts = function(mode) {
    return {
      name: this.name(),
      type: CUI.NumberInput,
      decimals: this.fixed,
      store_as_integer: this.store_as_integer,
      decimalpoint: this.getLocalizedDecimalPoint(),
      separator: this.getLocalizedGroupingSeparator()
    };
  };

  DecimalColumn.prototype.getPlaceholderText = function() {
    var ph;
    ph = this.getCustomPlaceholder();
    if (!CUI.util.isEmpty(ph)) {
      return ph;
    }
    return $$("data.column.decimal_input.placeholder");
  };

  DecimalColumn.prototype.getSaveData = function(data, save_data, opts) {
    if (opts.demo_data) {
      return save_data[this.name()] = (Math.floor(Math.random() * 10000) + 1) / 100;
    } else {
      return DecimalColumn.__super__.getSaveData.call(this, data, save_data, opts);
    }
  };

  DecimalColumn.prototype.__formatBareValue = function(v) {
    if (this.store_as_integer) {
      return v / Math.pow(10, this.fixed);
    }
    return v;
  };

  DecimalColumn.prototype.renderDetailOutput = function(data, top_level_data) {
    var opts, out;
    opts = this.getElementOpts();
    delete opts.type;
    out = CUI.NumberInput.format(data[this.name()], opts);
    if (CUI.util.isEmpty(out)) {
      out = "";
    }
    return new CUI.Label({
      text: out
    }).DOM;
  };

  DecimalColumn.prototype.getCSVDestinationFields = function(csvImporter) {
    var opts;
    opts = {
      csvImporter: csvImporter,
      field: this,
      fixed: this.fixed
    };
    return [new NumberColumnCSVImporterDestinationField(opts)];
  };

  DecimalColumn.prototype.__getSearchPlaceholder = function() {
    return $$("data.field.decimal-column.search.placeholder");
  };

  DecimalColumn.prototype.__getSearchInputRegexp = function() {
    return "^([0-9](\\s-\\s)?[,;\\.]{0,3}?)*$";
  };

  return DecimalColumn;

})(NumberColumn);
// Generated by CoffeeScript 1.12.7
var DoubleColumn,
  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;

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

  function DoubleColumn(_mask, _field_schema) {
    DoubleColumn.__super__.constructor.call(this, _mask, _field_schema);
  }

  DoubleColumn.prototype.getTokenizer = function() {
    return new DoubleTokenizer();
  };

  DoubleColumn.prototype.getElementOpts = function(mode) {
    return {
      name: this.name(),
      type: CUI.NumberInput,
      json_number: true,
      decimalpoint: this.getLocalizedDecimalPoint(),
      separator: this.getLocalizedGroupingSeparator()
    };
  };

  DoubleColumn.prototype.getPlaceholderText = function() {
    var ph;
    ph = this.getCustomPlaceholder();
    if (!CUI.util.isEmpty(ph)) {
      return ph;
    }
    return $$("data.column.double_input.placeholder");
  };

  DoubleColumn.prototype.getSaveData = function(data, save_data, opts) {
    if (opts.demo_data) {
      return save_data[this.name()] = Math.floor(Math.random() * 10000);
    } else {
      return DoubleColumn.__super__.getSaveData.call(this, data, save_data, opts);
    }
  };

  DoubleColumn.prototype.renderDetailOutput = function(data, top_level_data) {
    var out, value;
    value = data[this.name()];
    if (CUI.util.isEmpty(value)) {
      return new CUI.Label({
        text: ""
      }).DOM;
    }
    out = this.formatDouble(value);
    return new CUI.Label({
      text: out
    }).DOM;
  };

  DoubleColumn.prototype.formatDouble = function(value) {
    var decimalPart, decimalpoint, digit, digits, formatted, i, idx, integerPart, isNegative, len, parts, result, separator, str;
    decimalpoint = this.getLocalizedDecimalPoint();
    separator = this.getLocalizedGroupingSeparator();
    str = value + "";
    isNegative = str.startsWith("-");
    if (isNegative) {
      str = str.substr(1);
    }
    parts = str.split(".");
    integerPart = parts[0];
    decimalPart = parts[1] || "";
    if (separator) {
      digits = integerPart.split("").reverse();
      formatted = [];
      for (idx = i = 0, len = digits.length; i < len; idx = ++i) {
        digit = digits[idx];
        if (idx > 0 && idx % 3 === 0) {
          formatted.push(separator);
        }
        formatted.push(digit);
      }
      integerPart = formatted.reverse().join("");
    }
    result = integerPart;
    if (decimalPart.length > 0) {
      result += decimalpoint + decimalPart;
    }
    if (isNegative) {
      result = "-" + result;
    }
    return result;
  };

  DoubleColumn.prototype.getCSVDestinationFields = function(csvImporter) {
    var opts;
    opts = {
      csvImporter: csvImporter,
      field: this,
      fixed: -1
    };
    return [new NumberColumnCSVImporterDestinationField(opts)];
  };

  DoubleColumn.prototype.__getSearchPlaceholder = function() {
    return $$("data.field.double-column.search.placeholder");
  };

  DoubleColumn.prototype.__getSearchInputRegexp = function() {
    return "^(-?(0|[1-9]\\d*)(\\.\\d+)?([eE][+-]?\\d+)?(\\s-\\s)?[,;\\.]{0,3}?)*$";
  };

  return DoubleColumn;

})(NumberColumn);
// Generated by CoffeeScript 1.12.7
var GeoJsonColumn,
  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;

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

  function GeoJsonColumn(_mask, _field_schema) {
    GeoJsonColumn.__super__.constructor.call(this, _mask, _field_schema);
  }

  GeoJsonColumn.prototype.getTokenizer = function() {
    return null;
  };

  GeoJsonColumn.prototype.isEmpty = function(data, top_level_data, opts) {
    var isEmpty, ref, ref1, ref2;
    if (!this.__pluginInstalled()) {
      return CUI.util.isEmpty(data[this.name() + ":json"]);
    }
    isEmpty = GeoJsonColumn.__super__.isEmpty.call(this, data, top_level_data, opts);
    if (!isEmpty && ((ref = data[this.name()]) != null ? ref.type : void 0) === "FeatureCollection" && ((ref1 = data[this.name()]) != null ? (ref2 = ref1.features) != null ? ref2.length : void 0 : void 0) === 0) {
      return true;
    }
    return isEmpty;
  };

  GeoJsonColumn.prototype.getSaveData = function(data, save_data, opts) {
    var e, fieldData, jsonData, metadata_mapping_data;
    if (opts.demo_data) {
      return save_data[this.name()] = {
        type: "FeatureCollection",
        features: [
          {
            type: "Feature",
            geometry: {
              type: "Point",
              coordinates: [Math.floor(Math.random() * 10000), Math.floor(Math.random() * 10000)]
            },
            properties: {
              name: "Random Point",
              description: "This is a random point"
            }
          }
        ]
      };
    } else {
      metadata_mapping_data = data[this.name() + ":mapped_metadata"];
      if (this.__pluginInstalled()) {
        if (CUI.util.isEmpty(data[this.name()])) {
          return save_data[this.name()] = metadata_mapping_data;
        }
        return save_data[this.name()] = CUI.util.copyObject(data[this.name()], true);
      } else {
        fieldData = data[this.name()];
        jsonData = data[this.name() + ":json"];
        if (jsonData != null ? jsonData.json : void 0) {
          try {
            return save_data[this.name()] = JSON.parse(jsonData.json);
          } catch (error1) {
            e = error1;
            throw new InvalidSaveDataException();
          }
        } else if ((jsonData != null ? jsonData.json : void 0) === "") {
          return save_data[this.name()] = metadata_mapping_data;
        }
        return save_data[this.name()] = fieldData || null;
      }
    }
  };

  GeoJsonColumn.renderFeature = function(feature) {
    var featureInfo, featureResume, nameAndType, renderedFeature;
    nameAndType = new CUI.HorizontalLayout({
      maximize_horizontal: true,
      center: {
        content: new CUI.Label({
          text: GeoJsonColumn.getFeatureName(feature),
          "class": "ez5-geo-column-feature-name"
        })
      }
    }, featureInfo = GeoJsonColumn.getFeatureDisplayInfo(feature));
    featureResume = new CUI.VerticalList({
      maximize_horizontal: true,
      content: [nameAndType, featureInfo]
    });
    renderedFeature = new CUI.HorizontalLayout({
      "class": "ez5-geo-column-feature",
      maximize_horizontal: true,
      left: {
        content: new CUI.Icon({
          "class": "ez5-geo-column-feature-icon",
          icon: "fa-map-marker"
        })
      },
      center: {
        content: featureResume
      }
    });
    return renderedFeature;
  };

  GeoJsonColumn.prototype.renderTableOutput = function(data, top_level_data, opts) {
    var feature, fieldData, i, len, output_text, ref;
    output_text = "";
    fieldData = data[this.name()];
    if (((fieldData != null ? fieldData.type : void 0) != null) && (fieldData != null ? fieldData.type : void 0) !== "FeatureCollection") {
      output_text = GeoJsonColumn.getFeatureDisplayInfo(fieldData, false);
    } else {
      ref = (fieldData != null ? fieldData.features : void 0) || [];
      for (i = 0, len = ref.length; i < len; i++) {
        feature = ref[i];
        output_text += GeoJsonColumn.getFeatureDisplayInfo(feature, false) + "\n";
      }
    }
    return new CUI.Label({
      text: output_text,
      multiline: true
    });
  };

  GeoJsonColumn.prototype.renderDetailOutput = function(data, top_level_data, opts) {
    var feature, fieldData, i, len, ref, renderedFeatures;
    fieldData = data[this.name()];
    renderedFeatures = [];
    if (((fieldData != null ? fieldData.type : void 0) != null) && (fieldData != null ? fieldData.type : void 0) !== "FeatureCollection") {
      renderedFeatures.push(GeoJsonColumn.renderFeature(fieldData));
    } else {
      ref = (fieldData != null ? fieldData.features : void 0) || [];
      for (i = 0, len = ref.length; i < len; i++) {
        feature = ref[i];
        renderedFeatures.push(GeoJsonColumn.renderFeature(feature));
      }
    }
    return new CUI.VerticalList({
      "class": "ez5-geo-column",
      maximize_horizontal: true,
      content: renderedFeatures
    });
  };

  GeoJsonColumn.prototype.renderSearchInput = function(data, opts) {
    var form, mapFormPopover;
    if (opts == null) {
      opts = {};
    }
    if (!this.__pluginInstalled()) {
      return new CUI.Label({
        text: "GeoJsonColumn: No search input available"
      });
    } else if (GeoJsonMap.getMapClass() !== OpenLayersMap) {
      return new CUI.Label({
        text: "GeoJsonColumn: Only OpenLayers maps are supported for search input"
      });
    }
    mapFormPopover = new MapFormPopover({
      data: data,
      button: {
        loca_key: "geo.column.search.button"
      },
      popover: {
        onHide: (function(_this) {
          return function() {
            return CUI.Events.trigger({
              node: mapFormPopover,
              type: "search-input-change"
            });
          };
        })(this)
      },
      renderDisplayContent: (function(_this) {
        return function() {
          return ez5.renderFormPopoverInfo([_this.getSearchInfo(data)]);
        };
      })(this)
    });
    if (opts.query_editor) {
      form = new CUI.Form({
        fields: mapFormPopover._getFields(),
        data: data
      });
      form.start();
      return form.DOM;
    } else {
      return mapFormPopover.start();
    }
  };

  GeoJsonColumn.prototype.getQueryFieldBadge = function(data) {
    var value;
    if (CUI.util.isEmpty(data)) {
      return null;
    }
    if (data[(this.name()) + ":unset"]) {
      value = $$("text.column.badge.without");
    } else if (data[(this.name()) + ":has_value"]) {
      value = $$("field.search.badge.has_value");
    } else {
      value = this.getSearchInfo(data);
    }
    return {
      name: this.nameLocalized(),
      value: value
    };
  };

  GeoJsonColumn.prototype.getSearchFilter = function(data, key, for_collection) {
    var bbox, feature, filter, i, j, len, len1, points, polygon, ref, ref1, ref2, ref3, ref4, ref5, ref6, search;
    if (key == null) {
      key = this.name();
    }
    if (for_collection == null) {
      for_collection = false;
    }
    if (data[(this.name()) + ":unset"] || data[(this.name()) + ":has_value"]) {
      return GeoJsonColumn.__super__.getSearchFilter.call(this, data, key);
    }
    filter = null;
    search = [];
    if (data.feature && ((ref = data.feature) != null ? (ref1 = ref.features) != null ? ref1.length : void 0 : void 0) > 0) {
      ref2 = data.feature.features;
      for (i = 0, len = ref2.length; i < len; i++) {
        feature = ref2[i];
        if ((ref3 = feature.properties) != null ? ref3.use_bbox : void 0) {
          bbox = (ref4 = feature.properties) != null ? ref4.bbox : void 0;
          if (CUI.util.isEmpty(bbox)) {
            console.warn("GeoJsonColumn - getSearchFilter(): No bounding box found for feature");
            continue;
          }
          search.push({
            type: "geo_bounding_box",
            field: this.fullName(),
            bool: "should",
            geo_bounding_box: {
              top_left: {
                lat: bbox[3],
                lon: bbox[0]
              },
              bottom_right: {
                lat: bbox[1],
                lon: bbox[2]
              }
            }
          });
        } else {
          if (GeoJsonColumn.getFeatureType(feature) === "MultiPolygon") {
            ref5 = GeoJsonColumn.getFeatureCoordinates(feature);
            for (j = 0, len1 = ref5.length; j < len1; j++) {
              polygon = ref5[j];
              points = polygon[0].map(function(coord) {
                return {
                  lat: coord[1],
                  lon: coord[0]
                };
              });
              if (points.length > 2) {
                if (points[0].lat === points[points.length - 1].lat && points[0].lon === points[points.length - 1].lon) {
                  points.pop();
                }
              } else {
                console.warn("GeoJsonColumn - getSearchFilter(): Polygon with less than 3 points, skipping search");
                continue;
              }
              search.push({
                type: "geo_shape",
                field: this.fullName(),
                bool: "should",
                geo_shape: {
                  points: points
                }
              });
            }
          } else if (GeoJsonColumn.getFeatureType(feature) === "Polygon") {
            points = (ref6 = GeoJsonColumn.getFeatureCoordinates(feature)) != null ? ref6[0].map(function(coord) {
              return {
                lat: coord[1],
                lon: coord[0]
              };
            }) : void 0;
            if (points.length > 2) {
              if (points[0].lat === points[points.length - 1].lat && points[0].lon === points[points.length - 1].lon) {
                points.pop();
              }
            } else {
              console.warn("GeoJsonColumn - getSearchFilter(): Polygon with less than 3 points, skipping search");
              continue;
            }
            search.push({
              type: "geo_shape",
              field: this.fullName(),
              bool: "should",
              geo_shape: {
                points: points
              }
            });
          } else {
            continue;
          }
        }
      }
      filter = {
        type: "complex",
        search: search
      };
    }
    return filter;
  };

  GeoJsonColumn.prototype.getSearchInfo = function(data) {
    var info, numberOfFeatures, ref, ref1;
    if (CUI.util.isEmpty(data) || (data.features == null) || ((ref = data.feature) != null ? (ref1 = ref.features) != null ? ref1.length : void 0 : void 0) === 0) {
      if ((data != null ? data.feature : void 0) != null) {
        return $$("geoJsonColumn.search.info.single");
      }
      return "";
    }
    numberOfFeatures = data.feature.features.length;
    if (numberOfFeatures === 1) {
      info = $$("geoJsonColumn.search.info.single");
    } else {
      info = $$("geoJsonColumn.search.info", {
        count: numberOfFeatures
      });
    }
    return info;
  };

  GeoJsonColumn.prototype.__getPlaceholder = function(data) {
    var metadata_mapping_data;
    metadata_mapping_data = data[this.name() + ":mapped_metadata"];
    if (!CUI.util.isEmpty(metadata_mapping_data)) {
      return GeoJsonColumn.getFeatureDisplayInfo(metadata_mapping_data, false);
    }
    return $$("geoJsonColumn.map-editor.input.placeholder");
  };

  GeoJsonColumn.prototype.renderEditorInput = function(data, top_level_data, opts) {
    var element, form;
    if (!this.__pluginInstalled()) {
      return this.__renderJsonEditor(data, top_level_data, opts);
    }
    form = new CUI.Form({
      data: data[this.name()],
      fields: [
        {
          type: CUI.DataFieldProxy,
          element: (function(_this) {
            return function(dataField) {
              var autocompletion, featureList, fieldData, inputData, inputField, inputHelp, mapButton, name;
              fieldData = data[name = _this.name()] != null ? data[name] : data[name] = {};
              featureList = _this.renderDetailOutput(data, top_level_data, opts);
              inputData = {
                input: ""
              };
              mapButton = new CUI.Button({
                text: $$("geoJsonColumn.map-editor.button"),
                onClick: function() {
                  _this.__openMap(fieldData, function(geoJson) {
                    data[_this.name()] = geoJson;
                    CUI.Events.trigger({
                      node: element,
                      type: "editor-changed"
                    });
                    return dataField.reload();
                  }, {
                    popover_element: mapButton
                  });
                }
              });
              inputField = new CUI.Input({
                data: inputData,
                type: "text",
                placeholder: _this.__getPlaceholder(data),
                name: "input",
                controlElement: mapButton,
                onDataChanged: function() {
                  var aitem, i, len, option, options;
                  if (CUI.util.isEmpty(inputData.input)) {
                    return;
                  }
                  options = GeoJsonColumn.parse(inputData.input, true);
                  if (options.length > 0) {
                    autocompletion.emptyContainer();
                    for (i = 0, len = options.length; i < len; i++) {
                      option = options[i];
                      aitem = autocompletion.appendItem("all", new CUI.VerticalList({
                        content: [
                          new CUI.Label({
                            text: option.text
                          })
                        ]
                      }));
                      CUI.Events.listen({
                        type: "click",
                        node: aitem,
                        call: function() {
                          data[_this.name()] = _this.addGeoJson(data[_this.name()], option.value);
                          CUI.Events.trigger({
                            node: element,
                            type: "editor-changed"
                          });
                          dataField.reload();
                          autocompletion.hide();
                        }
                      });
                    }
                    autocompletion.show();
                  } else {
                    autocompletion.hide();
                  }
                }
              });
              autocompletion = new AutocompletionPopup({
                element: inputField
              });
              autocompletion.addContainer("all");
              inputHelp = new CUI.FormButton({
                text: $$("objecttype.list.view.item.export_asset_filenames.help"),
                appearance: "flat",
                onClick: function() {
                  var pop;
                  pop = new ez5.HintPopover({
                    element: inputHelp,
                    content: new CUI.Label({
                      multiline: true,
                      text: $$("geoJsonColumn.map-editor.input.help")
                    }),
                    padded: true
                  });
                  return pop.show().start();
                }
              });
              return new CUI.VerticalList({
                maximize_horizontal: true,
                content: [featureList, inputField]
              });
            };
          })(this)
        }
      ]
    });
    element = form.start().DOM;
    return element;
  };

  GeoJsonColumn.prototype.__renderSimpleMapEditor = function(data, top_level_data, opts) {
    var autocompletion, element, featureList, fieldData, form, inputData, inputField, inputHelp, name, sm;
    fieldData = data[name = this.name()] != null ? data[name] : data[name] = {};
    featureList = this.renderDetailOutput(data, top_level_data, opts);
    inputData = {
      input: ""
    };
    element = null;
    sm = new SimpleMapEditor({
      field: this,
      button: {
        loca_key: "geo.column.search.button"
      },
      data: data[this.name()],
      done: (function(_this) {
        return function(geoJson) {
          data[_this.name()] = geoJson;
          CUI.dom.replace(featureList, _this.renderDetailOutput(data, top_level_data, opts));
          console.log(featureList);
          CUI.Events.trigger({
            node: element,
            type: "editor-changed"
          });
        };
      })(this)
    });
    sm.start();
    inputField = new CUI.Input({
      data: inputData,
      type: "text",
      placeholder: this.__getPlaceholder(data),
      name: "input",
      controlElement: sm
    });
    autocompletion = new AutocompletionPopup({
      element: inputField
    });
    autocompletion.addContainer("all");
    inputHelp = new CUI.FormButton({
      text: $$("objecttype.list.view.item.export_asset_filenames.help"),
      appearance: "flat",
      onClick: (function(_this) {
        return function() {
          var pop;
          pop = new ez5.HintPopover({
            element: inputHelp,
            content: new CUI.Label({
              multiline: true,
              text: $$("geoJsonColumn.simple-map-editor.input.help")
            }),
            padded: true
          });
          return pop.show();
        };
      })(this)
    });
    form = new CUI.Form({
      data: data[this.name()],
      fields: [
        {
          type: CUI.DataFieldProxy,
          element: (function(_this) {
            return function(dataField) {
              element = new CUI.VerticalList({
                maximize_horizontal: true,
                content: [featureList, inputField]
              });
              return element;
            };
          })(this)
        }
      ]
    });
    element = form.start().DOM;
    return element;
  };

  GeoJsonColumn.prototype.addFeature = function(data, feature) {
    if (!this.__pluginInstalled()) {
      return;
    }
    if (CUI.util.isEmpty(data)) {
      data = GeoJsonColumn.emptyFeatureCollection();
    }
    return data.features.push(feature);
  };

  GeoJsonColumn.prototype.addGeoJson = function(data, geoJson) {
    var feature, i, len, ref;
    if (!this.__pluginInstalled()) {
      return data;
    }
    if (CUI.util.isEmpty(data)) {
      data = GeoJsonColumn.emptyFeatureCollection();
    }
    switch (geoJson.type) {
      case "Feature":
        data.features.push(geoJson);
        break;
      case "FeatureCollection":
        ref = geoJson.features;
        for (i = 0, len = ref.length; i < len; i++) {
          feature = ref[i];
          data.features.push(feature);
        }
        break;
      case "Point":
      case "LineString":
      case "Polygon":
      case "MultiPoint":
      case "MultiLineString":
      case "MultiPolygon":
      case "GeometryCollection":
        feature = {
          type: "Feature",
          geometry: geoJson,
          properties: {}
        };
        data.features.push(feature);
    }
    return data;
  };

  GeoJsonColumn.parse = function(string, asOptions) {
    var displayText, featureName, featureType, options, point, rawGeoJson;
    if (asOptions == null) {
      asOptions = false;
    }
    options = [];
    point = GeoJsonColumn.extractCoordinates(string);
    if (point && asOptions) {
      options.push({
        text: "Create Point With Coordinates " + point.geometry.coordinates[1] + ", " + point.geometry.coordinates[0],
        value: point
      });
    } else if (point) {
      return point;
    }
    rawGeoJson = GeoJsonColumn.parseRawGeoJson(string);
    if (rawGeoJson && asOptions) {
      featureType = GeoJsonColumn.getFeatureType(rawGeoJson);
      featureName = GeoJsonColumn.getFeatureName(rawGeoJson);
      displayText = featureName !== GeoJsonColumn.getLocalizedFeatureType(rawGeoJson) ? "Add " + featureType + ": " + featureName : "Add " + featureType;
      options.push({
        text: displayText,
        value: rawGeoJson
      });
    } else if (rawGeoJson) {
      return rawGeoJson;
    }
    return options;
  };

  GeoJsonColumn.prototype.__renderJsonEditor = function(data, top_level_data, opts) {
    var fieldData, form, jsonData, metadata_mapping_data;
    metadata_mapping_data = data[this.name() + ":mapped_metadata"];
    fieldData = data[this.name()] || metadata_mapping_data;
    jsonData = {};
    jsonData.json = JSON.stringify(fieldData, null, 2);
    data[this.name() + ":json"] = jsonData;
    form = new CUI.Form({
      data: jsonData,
      maximize_horizontal: true,
      fields: [
        {
          type: CUI.CodeInput,
          mode: "json",
          name: "json",
          checkInput: (function(_this) {
            return function(value) {
              var e, object;
              try {
                object = JSON.parse(value);
                if (CUI.util.isPlainObject(object) || null) {
                  return true;
                } else {
                  return false;
                }
              } catch (error1) {
                e = error1;
                return false;
              }
            };
          })(this)
        }
      ],
      onDataChanged: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            node: form,
            type: "editor-changed"
          });
        };
      })(this)
    });
    form.start();
    return new CUI.VerticalList({
      content: [form]
    });
  };

  GeoJsonColumn.prototype.__getInitialEditorZoom = function() {
    var e, ot, ref, ref1, ref2, ref3, ref4, ref5, zoom;
    zoom = null;
    try {
      ot = this.mask.getTopLevelObjecttypeName();
      zoom = (ref = ez5.schema.CURRENT._table_by_name[ot]) != null ? (ref1 = ref._objecttype) != null ? (ref2 = ref1.objecttype) != null ? (ref3 = ref2.custom_data) != null ? (ref4 = ref3.webfrontend) != null ? (ref5 = ref4.geo_json) != null ? ref5.zoom : void 0 : void 0 : void 0 : void 0 : void 0 : void 0;
    } catch (error1) {
      e = error1;
      console.info("No zoom defined for objecttype " + ot);
    }
    return zoom;
  };

  GeoJsonColumn.prototype.__getInitialEditorCenter = function() {
    var center, e, ot, ref, ref1, ref2, ref3;
    center = null;
    try {
      ot = this.mask.getTopLevelObjecttypeName();
      center = (ref = ez5.schema.CURRENT._table_by_name[ot]._objecttype.objecttype) != null ? (ref1 = ref.custom_data) != null ? (ref2 = ref1.webfrontend) != null ? (ref3 = ref2.geo_json) != null ? ref3.center : void 0 : void 0 : void 0 : void 0;
    } catch (error1) {
      e = error1;
      console.info("No center defined for objecttype " + ot);
    }
    return center;
  };

  GeoJsonColumn.prototype.__openMap = function(data, onDone, opts) {
    var mapEditor, mapEditorOpts;
    if (opts == null) {
      opts = {};
    }
    if (!ez5.session.getCapability("geo_support")) {
      this.__basic_mode = true;
    }
    mapEditorOpts = {
      field: this,
      data: data,
      initial_zoom: this.__getInitialEditorZoom(),
      initial_center: this.__getInitialEditorCenter(),
      basic_mode: this.__basic_mode,
      single_feature: this.__isSingleFeature(),
      allowed_feature_types: this.__getAllowedFeatureTypes(),
      done: (function(_this) {
        return function(geoJson) {
          if (typeof onDone === "function") {
            onDone(geoJson);
          }
        };
      })(this),
      mode: "editor"
    };
    if (this.__basic_mode && opts.popover_element) {
      mapEditorOpts.popover_element = opts.popover_element;
    }
    return mapEditor = new MapEditor(mapEditorOpts);
  };

  GeoJsonColumn.prototype.__isSingleFeature = function() {
    var cs;
    if (this.__basic_mode) {
      return true;
    }
    cs = this.FieldSchema._column.custom_settings["geo-json"];
    if ((cs != null ? cs.allow_multiple_features : void 0) == null) {
      return false;
    }
    return !(cs != null ? cs.allow_multiple_features : void 0);
  };

  GeoJsonColumn.prototype.__getAllowedFeatureTypes = function() {
    var allowed, cs;
    if (this.__basic_mode) {
      return "points";
    }
    allowed = [];
    cs = this.FieldSchema._column.custom_settings["geo-json"];
    if (((cs != null ? cs.allow_points_feature : void 0) == null) || (cs != null ? cs.allow_points_feature : void 0)) {
      allowed.push("points");
    }
    if (((cs != null ? cs.allow_lines_feature : void 0) == null) || (cs != null ? cs.allow_lines_feature : void 0)) {
      allowed.push("lines");
    }
    if (((cs != null ? cs.allow_polygons_feature : void 0) == null) || (cs != null ? cs.allow_polygons_feature : void 0)) {
      allowed.push("polygons");
    }
    if (((cs != null ? cs.allow_geocoder : void 0) == null) || (cs != null ? cs.allow_geocoder : void 0)) {
      allowed.push("geocoder");
    }
    return allowed;
  };

  GeoJsonColumn.getFeatureCoordinates = function(feature) {
    var ref;
    if (feature.coordinates != null) {
      return feature.coordinates;
    } else if (((ref = feature.geometry) != null ? ref.coordinates : void 0) != null) {
      return feature.geometry.coordinates;
    }
    return null;
  };

  GeoJsonColumn.getFeatureType = function(feature) {
    var ref;
    if (((ref = feature.geometry) != null ? ref.type : void 0) != null) {
      return feature.geometry.type;
    } else if (feature.type != null) {
      return feature.type;
    }
    return null;
  };

  GeoJsonColumn.getFeatureName = function(feature) {
    var ref, ref1;
    if ((ref = feature.properties) != null ? ref.name : void 0) {
      return feature.properties.name;
    } else if ((ref1 = feature.properties) != null ? ref1.display_name : void 0) {
      return feature.properties.display_name;
    } else {
      return this.getLocalizedFeatureType(feature);
    }
  };

  GeoJsonColumn.getFeatureDisplayInfo = function(feature, asLabel) {
    var text, type;
    if (asLabel == null) {
      asLabel = true;
    }
    type = GeoJsonColumn.getFeatureType(feature);
    text = "Unknown feature type: " + type;
    switch (type) {
      case "Point":
        text = "Lat: " + (GeoJsonColumn.getFeatureCoordinates(feature)[1]) + ", Lon: " + (GeoJsonColumn.getFeatureCoordinates(feature)[0]);
        break;
      case "Polygon":
        text = "Area with " + (GeoJsonColumn.getFeatureCoordinates(feature)[0].length) + " points";
        break;
      case "LineString":
        text = "Line with " + (GeoJsonColumn.getFeatureCoordinates(feature).length) + " points";
        break;
      case "MultiPolygon":
        text = "MultiPolygon with " + (GeoJsonColumn.getFeatureCoordinates(feature)[0].length) + " polygons";
        break;
      case "MultiLineString":
        text = "MultiLineString with " + (GeoJsonColumn.getFeatureCoordinates(feature)[0].length) + " lines";
        break;
      case "MultiPoint":
        text = "MultiPoint with " + (GeoJsonColumn.getFeatureCoordinates(feature).length) + " points";
        break;
      case "GeometryCollection":
        text = "GeometryCollection with " + feature.geometry.geometries.length + " geometries";
    }
    if (!asLabel) {
      return text;
    }
    return new CUI.Label({
      text: text
    });
  };

  GeoJsonColumn.getLocalizedFeatureType = function(feature) {
    return $$("geoJsonColumn.feature.type." + (GeoJsonColumn.getFeatureType(feature)));
  };

  GeoJsonColumn.emptyFeatureCollection = function() {
    return {
      type: "FeatureCollection",
      features: []
    };
  };

  GeoJsonColumn.createPointFeature = function(lng, lat, properties) {
    if (properties == null) {
      properties = {};
    }
    return {
      type: "Feature",
      geometry: {
        type: "Point",
        coordinates: [lng, lat]
      },
      properties: properties
    };
  };

  GeoJsonColumn.createPolygonFeature = function(coordinates, properties) {
    if (properties == null) {
      properties = {};
    }
    return {
      type: "Feature",
      geometry: {
        type: "Polygon",
        coordinates: [coordinates]
      },
      properties: properties
    };
  };

  GeoJsonColumn.createLineFeature = function(coordinates, properties) {
    if (properties == null) {
      properties = {};
    }
    return {
      type: "Feature",
      geometry: {
        type: "LineString",
        coordinates: coordinates
      },
      properties: properties
    };
  };

  GeoJsonColumn.prototype.getCSVDestinationFields = function(csvImporter) {
    var opts;
    opts = {
      csvImporter: csvImporter,
      field: this
    };
    return [new GeoJsonColumnCSVImporterDestinationField(opts)];
  };

  GeoJsonColumn.isPluginInstalled = function() {
    return !CUI.util.isEmpty(ez5.pluginManager.getPlugin("geo-json"));
  };

  GeoJsonColumn.prototype.__pluginInstalled = function() {
    return GeoJsonColumn.isPluginInstalled();

    /*
    		Supported formats:
    		Input: lat: 40.7128, lng: -74.0060
    		Input: latitude=40.7128 longitude=-74.0060
    		Input: 40.7128, -74.0060
    		Input: lat 40.7128 lng -74.0060
    		Input: 40.7128 N, 74.0060 W
    		Input: 35.6895 S, 139.6917 E
          Google Maps URLs
     */
  };

  GeoJsonColumn.extractCoordinates = function(string) {
    var gm, i, lat, len, lng, match, pattern, patterns;
    gm = GeoJsonColumn.parseGoogleMapsUrl(string);
    if (gm != null) {
      return gm;
    }
    string = string.trim().toLowerCase();
    lat = void 0;
    lng = void 0;
    patterns = [/(lat(?:itude)?[:=])\s*([+-]?\d+(\.\d+)?)\s*[,;]\s*(lon(?:gitude)?|lng)[:=]\s*([+-]?\d+(\.\d+)?)/, /^([+-]?\d+(\.\d+)?)\s*[,;]\s*([+-]?\d+(\.\d+)?)$/, /([+-]?\d+(\.\d+)?)\s*([ns])\s*[,;]\s*([+-]?\d+(\.\d+)?)\s*([ew])/];
    for (i = 0, len = patterns.length; i < len; i++) {
      pattern = patterns[i];
      match = string.match(pattern);
      if (match) {
        if (pattern === patterns[0]) {
          lat = parseFloat(match[2]);
          lng = parseFloat(match[5]);
        } else if (pattern === patterns[1]) {
          lat = parseFloat(match[1]);
          lng = parseFloat(match[3]);
        } else if (pattern === patterns[2]) {
          lat = parseFloat(match[1]);
          lng = parseFloat(match[4]);
          if (match[3] === 's') {
            lat = -lat;
          }
          if (match[6] === 'w') {
            lng = -lng;
          }
        }
        break;
      }
    }
    if ((lat != null) && (lng != null) && !isNaN(lat) && !isNaN(lng)) {
      if (lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180) {
        return GeoJsonColumn.createPointFeature(lng, lat);
      }
    }
    return null;
  };

  GeoJsonColumn.parseGoogleMapsUrl = function(urlString) {
    var domainRegex, error, fallback, host, lat, lng, nameMatch, parsedUrl, path, placeName, precise, str, validLatLng;
    validLatLng = function(lat, lng) {
      if (isNaN(lat) || isNaN(lng)) {
        return false;
      }
      return lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180;
    };
    str = urlString.trim();
    parsedUrl = null;
    try {
      parsedUrl = new URL(str);
    } catch (error1) {
      error = error1;
      return null;
    }
    host = parsedUrl.host.toLowerCase();
    domainRegex = /^(?:www\.)?(?:maps\.)?google\.[a-z\.]+$/;
    if (!domainRegex.test(host)) {
      return null;
    }
    path = parsedUrl.pathname.toLowerCase();
    if (!path.startsWith('/maps')) {
      return null;
    }
    placeName = null;
    nameMatch = str.match(/\/maps\/place\/([^\/]+)\//);
    if (nameMatch != null) {
      placeName = decodeURIComponent(nameMatch[1].replace(/\+/g, ' '));
    }
    precise = str.match(/!3d(-?\d+\.\d+)!4d(-?\d+\.\d+)/);
    if (precise != null) {
      lat = parseFloat(precise[1]);
      lng = parseFloat(precise[2]);
      if (validLatLng(lat, lng)) {
        return GeoJsonColumn.createPointFeature(lng, lat, {
          name: placeName
        });
      }
    }
    fallback = str.match(/@(-?\d+\.\d+),(-?\d+\.\d+),(\d+)m/);
    if (fallback != null) {
      lat = parseFloat(fallback[1]);
      lng = parseFloat(fallback[2]);
      if (validLatLng(lat, lng)) {
        return GeoJsonColumn.createPointFeature(lng, lat, {
          name: placeName
        });
      }
    }
    return null;
  };

  GeoJsonColumn.parseRawGeoJson = function(string) {
    var error, parsed;
    if (CUI.util.isEmpty(string != null ? string.trim() : void 0)) {
      return null;
    }
    try {
      parsed = JSON.parse(string.trim());
      if (GeoJsonColumn.isValidGeoJson(parsed)) {
        return parsed;
      } else {
        return null;
      }
    } catch (error1) {
      error = error1;
      return null;
    }
  };

  GeoJsonColumn.isValidGeoJson = function(obj) {
    if (!CUI.util.isPlainObject(obj)) {
      return false;
    }
    if (!obj.type) {
      return false;
    }
    switch (obj.type) {
      case "Feature":
        return GeoJsonColumn.isValidFeature(obj);
      case "FeatureCollection":
        return GeoJsonColumn.isValidFeatureCollection(obj);
      case "Point":
      case "LineString":
      case "Polygon":
      case "MultiPoint":
      case "MultiLineString":
      case "MultiPolygon":
      case "GeometryCollection":
        return GeoJsonColumn.isValidGeometry(obj);
      default:
        return false;
    }
  };

  GeoJsonColumn.isValidFeature = function(feature) {
    if (!CUI.util.isPlainObject(feature)) {
      return false;
    }
    if (feature.type !== "Feature") {
      return false;
    }
    if (!feature.geometry && feature.geometry !== null) {
      return false;
    }
    if (feature.geometry && !GeoJsonColumn.isValidGeometry(feature.geometry)) {
      return false;
    }
    if (feature.properties && !CUI.util.isPlainObject(feature.properties)) {
      return false;
    }
    return true;
  };

  GeoJsonColumn.isValidFeatureCollection = function(collection) {
    var feature, i, len, ref;
    if (!CUI.util.isPlainObject(collection)) {
      return false;
    }
    if (collection.type !== "FeatureCollection") {
      return false;
    }
    if (!CUI.util.isArray(collection.features)) {
      return false;
    }
    ref = collection.features;
    for (i = 0, len = ref.length; i < len; i++) {
      feature = ref[i];
      if (!GeoJsonColumn.isValidFeature(feature)) {
        return false;
      }
    }
    return true;
  };

  GeoJsonColumn.isValidGeometry = function(geometry) {
    if (!CUI.util.isPlainObject(geometry)) {
      return false;
    }
    if (!geometry.type) {
      return false;
    }
    if (!geometry.coordinates && geometry.type !== "GeometryCollection") {
      return false;
    }
    switch (geometry.type) {
      case "Point":
        return GeoJsonColumn.isValidPointCoordinates(geometry.coordinates);
      case "LineString":
        return GeoJsonColumn.isValidLineStringCoordinates(geometry.coordinates);
      case "Polygon":
        return GeoJsonColumn.isValidPolygonCoordinates(geometry.coordinates);
      case "MultiPoint":
        return GeoJsonColumn.isValidMultiPointCoordinates(geometry.coordinates);
      case "MultiLineString":
        return GeoJsonColumn.isValidMultiLineStringCoordinates(geometry.coordinates);
      case "MultiPolygon":
        return GeoJsonColumn.isValidMultiPolygonCoordinates(geometry.coordinates);
      case "GeometryCollection":
        return GeoJsonColumn.isValidGeometryCollection(geometry);
      default:
        return false;
    }
  };

  GeoJsonColumn.isValidPointCoordinates = function(coords) {
    if (!CUI.util.isArray(coords)) {
      return false;
    }
    if (coords.length < 2) {
      return false;
    }
    if (!CUI.util.isNumber(coords[0]) || !CUI.util.isNumber(coords[1])) {
      return false;
    }
    if (isNaN(coords[0]) || isNaN(coords[1])) {
      return false;
    }
    if (coords[0] < -180 || coords[0] > 180) {
      return false;
    }
    if (coords[1] < -90 || coords[1] > 90) {
      return false;
    }
    return true;
  };

  GeoJsonColumn.isValidLineStringCoordinates = function(coords) {
    var i, len, point;
    if (!CUI.util.isArray(coords)) {
      return false;
    }
    if (coords.length < 2) {
      return false;
    }
    for (i = 0, len = coords.length; i < len; i++) {
      point = coords[i];
      if (!GeoJsonColumn.isValidPointCoordinates(point)) {
        return false;
      }
    }
    return true;
  };

  GeoJsonColumn.isValidPolygonCoordinates = function(coords) {
    var firstPoint, i, j, lastPoint, len, len1, point, ring;
    if (!CUI.util.isArray(coords)) {
      return false;
    }
    if (coords.length < 1) {
      return false;
    }
    for (i = 0, len = coords.length; i < len; i++) {
      ring = coords[i];
      if (!CUI.util.isArray(ring)) {
        return false;
      }
      if (ring.length < 4) {
        return false;
      }
      for (j = 0, len1 = ring.length; j < len1; j++) {
        point = ring[j];
        if (!GeoJsonColumn.isValidPointCoordinates(point)) {
          return false;
        }
      }
      firstPoint = ring[0];
      lastPoint = ring[ring.length - 1];
      if (firstPoint[0] !== lastPoint[0] || firstPoint[1] !== lastPoint[1]) {
        return false;
      }
    }
    return true;
  };

  GeoJsonColumn.isValidMultiPointCoordinates = function(coords) {
    var i, len, point;
    if (!CUI.util.isArray(coords)) {
      return false;
    }
    if (coords.length < 1) {
      return false;
    }
    for (i = 0, len = coords.length; i < len; i++) {
      point = coords[i];
      if (!GeoJsonColumn.isValidPointCoordinates(point)) {
        return false;
      }
    }
    return true;
  };

  GeoJsonColumn.isValidMultiLineStringCoordinates = function(coords) {
    var i, len, lineString;
    if (!CUI.util.isArray(coords)) {
      return false;
    }
    if (coords.length < 1) {
      return false;
    }
    for (i = 0, len = coords.length; i < len; i++) {
      lineString = coords[i];
      if (!GeoJsonColumn.isValidLineStringCoordinates(lineString)) {
        return false;
      }
    }
    return true;
  };

  GeoJsonColumn.isValidMultiPolygonCoordinates = function(coords) {
    var i, len, polygon;
    if (!CUI.util.isArray(coords)) {
      return false;
    }
    if (coords.length < 1) {
      return false;
    }
    for (i = 0, len = coords.length; i < len; i++) {
      polygon = coords[i];
      if (!GeoJsonColumn.isValidPolygonCoordinates(polygon)) {
        return false;
      }
    }
    return true;
  };

  GeoJsonColumn.isValidGeometryCollection = function(collection) {
    var geometry, i, len, ref;
    if (!CUI.util.isPlainObject(collection)) {
      return false;
    }
    if (collection.type !== "GeometryCollection") {
      return false;
    }
    if (!CUI.util.isArray(collection.geometries)) {
      return false;
    }
    ref = collection.geometries;
    for (i = 0, len = ref.length; i < len; i++) {
      geometry = ref[i];
      if (!GeoJsonColumn.isValidGeometry(geometry)) {
        return false;
      }
    }
    return true;
  };

  return GeoJsonColumn;

})(DataColumn);
// Generated by CoffeeScript 1.12.7
var EASColumn, EASColumnSearchOriginalFilename,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  EASColumn.prototype.renderStandard = function(standard, data) {
    var os;
    os = this.getOutputStandardEAS();
    if (!os) {
      return;
    }
    return standard.push({
      field: this,
      data: data,
      render_info: os
    });
  };

  EASColumn.prototype.getClass = function() {
    return "ez5-eas-column";
  };

  EASColumn.prototype.isEASFieldEnabled = function() {
    return true;
  };

  EASColumn.prototype.getEASFieldOption = function() {
    return {
      value: this,
      text: this.fullNameLocalized()
    };
  };

  EASColumn.prototype.nameForCollectionSave = function() {
    return this.fullName(false);
  };

  EASColumn.prototype.getCSVDestinationFields = function(csvImporter) {
    var opts;
    opts = {
      csvImporter: csvImporter,
      field: this
    };
    return [new EASColumnCSVImporterDestinationField(opts)];
  };

  EASColumn.prototype.supportsSeries = function() {
    if (this.insideNested()) {
      return true;
    } else {
      return false;
    }
  };

  EASColumn.prototype.isSourceForMapping = function(required_type) {
    return false;
  };

  EASColumn.prototype.getReplacementRecord = function() {};

  EASColumn.prototype.getSaveData = function(data, save_data, opts) {
    var arr, i, img, j, len, len1, new_obj, obj, ref, ref1, ref2, set_preferred, value;
    if (save_data == null) {
      save_data = {};
    }
    if (opts == null) {
      opts = {};
    }
    if (opts.demo_data) {
      img = ez5.session.getConfigPicture("background");
      if (!img) {
        save_data[this.name()] = null;
        return;
      }
      img.preferred = true;
      save_data[this.name()] = [img];
      return;
    }
    if (opts.copy) {
      return;
    }
    if (!data[this.name()]) {
      return;
    }
    arr = save_data[this.name()] = [];
    set_preferred = null;
    ref = data[this.name()];
    for (i = 0, len = ref.length; i < len; i++) {
      value = ref[i];
      obj = {
        preferred: value.preferred,
        frontend_prefs: CUI.util.copyObject(value.frontend_prefs, true),
        name: value.name,
        _id: value._id
      };
      arr.push(obj);
      if (!((ref1 = value.transform) != null ? ref1.length : void 0)) {
        continue;
      }
      new_obj = {
        frontend_prefs: obj.frontend_prefs,
        __transform: value.transform,
        eas_parent_id: obj._id,
        _id: null
      };
      arr.push(new_obj);
      if (set_preferred === null) {
        set_preferred = arr.length - 1;
      }
      if ((ref2 = opts.produce_assets) != null) {
        ref2.push(new_obj);
      }
      delete obj.frontend_prefs;
    }
    if (set_preferred !== null) {
      for (j = 0, len1 = arr.length; j < len1; j++) {
        obj = arr[j];
        obj.preferred = false;
      }
      arr[set_preferred].preferred = true;
    }
    return arr;
  };

  EASColumn.prototype.UNUSEDgetScaleAndPos = function(value) {
    var ref, ref1;
    return (ref = value.frontend_prefs) != null ? (ref1 = ref.webfrontend) != null ? ref1.scale_and_pos : void 0 : void 0;
  };

  EASColumn.prototype.UNUSEDsetScaleAndPos = function(value, scale_and_pos) {
    if (!value.frontend_prefs) {
      value.frontend_prefs = {};
    }
    if (scale_and_pos) {
      value.frontend_prefs.webfrontend = {
        scale_and_pos: scale_and_pos
      };
    } else if (value.frontend_prefs.webfrontend) {
      delete value.frontend_prefs.webfrontend.scale_and_pos;
    }
    return value;
  };

  EASColumn.prototype.getDataAsString = function(data) {
    return JSON.stringify(this.getSaveData(data));
  };

  EASColumn.prototype.isEmpty = function(data) {
    return !this.getImgValuePreferred(data);
  };

  EASColumn.prototype.hasUserData = function(data, top_level_data, opts) {
    var info, ref;
    if (opts == null) {
      opts = {};
    }
    if (opts.mode === "expert") {
      info = this.__getSearchFilterAndInfo(data, this.name()).info;
      return info.length > 0;
    } else {
      return ((ref = data[this.name()]) != null ? ref.length : void 0) > 0;
    }
  };

  EASColumn.prototype.checkValue = function(data, top_level_data, opts) {
    if (this.isEmpty(data) && this.ColumnSchema.check === "not_empty") {
      return false;
    } else {
      return true;
    }
  };

  EASColumn.prototype.isExpertCommon = function(mode) {
    switch (mode) {
      case "sort":
        return true;
      default:
        return false;
    }
  };

  EASColumn.prototype.getExpertLabelButtons = function(data, opts) {
    var buttons, field, radioElement;
    if (opts == null) {
      opts = {};
    }
    if (!ez5.version("6")) {
      return [];
    }
    if (opts.readonly) {
      return [];
    }
    buttons = [];
    field = new CUI.Checkbox({
      name: (this.name()) + ":multiple_files",
      radio: (this.name()) + ":unset",
      ui: "field.search.multiple_files.checkbox:" + (this.name()),
      "class": 'ez5-field-control-button ez5-field-control-button--unset',
      data: data,
      icon_active: "fa-files-o",
      icon_inactive: "fa-files-o",
      radio_allow_null: true,
      tooltip: {
        text: $$("eas.column.search.multiple_files_tooltip")
      },
      onDataChanged: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            type: "search-input-change",
            node: field
          });
        };
      })(this)
    }).start();
    radioElement = field.DOM.querySelector('[role="radio"]');
    if (radioElement != null) {
      radioElement.removeAttribute('role');
    }
    buttons.push(field);
    return buttons;
  };

  EASColumn.prototype.getQueryFieldBadge = function(data, fields) {
    var filter_and_info;
    filter_and_info = this.__getSearchFilterAndInfo(data, this.name());
    return {
      name: fields ? $$("eas.column.search.badge.name") : this.nameLocalized(),
      value: filter_and_info.info.join("; ")
    };
  };

  EASColumn.prototype.getSearchFilter = function(data, key) {
    if (key == null) {
      key = this.name();
    }
    return this.__getSearchFilterAndInfo(data, key).filter;
  };

  EASColumn.prototype.__getSearchFilterAndInfo = function(data, key) {
    var _complex_filter, _fileClass, _filter, _part_filter, addStatusFilter, add_range, allVersions, dateFieldName, dateFilter, dateKind, exts, factor, fileClass, filenameParts, filenameValue, filter, from, i, inArray, info, j, k, l, len, len1, len2, name, part, ref, ref1, status, statusLabel, to, version;
    info = [];
    if (data[key + ":multiple_files"]) {
      filter = {
        type: "range",
        field: (this.fullName()) + ":count",
        from: "2"
      };
      return {
        filter: filter,
        info: [$$("eas.column.search.multiple_files")]
      };
    }
    filter = Field.prototype.getSearchFilter.call(this, data, key);
    if (filter) {
      k = ((ref = filter.search) != null ? ref[0]._has_value_filter : void 0) ? $$("field.search.badge.has_value") : $$("eas.column.search.without");
      return {
        filter: filter,
        info: [k]
      };
    }
    if (!data[key]) {
      return {
        filter: null,
        info: []
      };
    }
    add_range = (function(_this) {
      return function(name, es_key, key_min, key_max, factor) {
        var f, from, to, v;
        if (factor == null) {
          factor = null;
        }
        if (CUI.util.isString(key_min)) {
          v = data[key][key_min];
        } else {
          v = key_min;
        }
        if (!CUI.util.isEmpty(v)) {
          if (factor !== null) {
            v = Math.floor(v * factor);
          }
          from = v;
        }
        if (CUI.util.isString(key_max)) {
          v = data[key][key_max];
        } else {
          v = key_max;
        }
        if (!CUI.util.isEmpty(v)) {
          if (factor !== null) {
            v = Math.ceil(v * factor);
          }
          to = v;
        }
        if (CUI.util.isEmpty(from) && CUI.util.isEmpty(to)) {
          return;
        }
        f = {
          type: "range",
          field: (_this.fullName()) + "." + es_key,
          from: from,
          to: to
        };
        info.push(name);
        return filter.search.push(f);
      };
    })(this);
    filter = {
      type: "complex",
      search: []
    };
    fileClass = data[key].fileclass;
    if (!CUI.util.isNull(fileClass)) {
      filter.search.push({
        type: "in",
        fields: [(this.fullName()) + ".class"],
        "in": [data[key].fileclass],
        bool: "must"
      });
      exts = data[key]["extension_" + fileClass] || [];
      if (!exts.length) {
        info.push($$("server.eas.fileclass." + data[key].fileclass));
      }
      if (exts.length) {
        filter.search.push({
          type: "in",
          fields: [(this.fullName()) + ".extension"],
          "in": exts,
          bool: "must"
        });
        info.push(exts.join(", "));
      }
    }
    if (!CUI.util.isNull(data[key].status)) {
      status = data[key].status;
      allVersions = [];
      inArray = [];
      addStatusFilter = (function(_this) {
        return function(classname) {
          var i, len, ref1, version;
          ref1 = Asset.getVersionNamesForClass(classname);
          for (i = 0, len = ref1.length; i < len; i++) {
            version = ref1[i];
            if (version === "original" && status === "done") {
              continue;
            }
            inArray.push(classname + "." + version + "." + status);
            CUI.util.pushOntoArray(version, allVersions);
          }
        };
      })(this);
      if (!CUI.util.isNull(fileClass)) {
        addStatusFilter(fileClass);
      } else {
        ref1 = this.__getFileClasses();
        for (i = 0, len = ref1.length; i < len; i++) {
          _fileClass = ref1[i];
          if (_fileClass === "unknown") {
            continue;
          }
          addStatusFilter(_fileClass);
        }
      }
      if (CUI.util.isNull(fileClass) || fileClass === "unknown") {
        if (status === "failed") {
          for (j = 0, len1 = allVersions.length; j < len1; j++) {
            version = allVersions[j];
            inArray.push("unknown." + version + "." + status);
          }
        } else {
          inArray.push("unknown.original." + status);
        }
      }
      filter.search.push({
        type: "in",
        fields: [(this.fullName()) + ".class_version_status"],
        "in": inArray,
        bool: "must"
      });
      statusLabel = $$("eas.column.status." + status);
      info.push($$("eas.column.status.label", {
        status: statusLabel
      }));
    }
    switch (data[key].unit) {
      case "px":
      case "mm":
      case "cm":
        switch (data[key].unit) {
          case "cm":
            factor = data[key].unit_dpi / 2.54;
            name = $$("eas.column.eas.column.unit.cm");
            break;
          case "mm":
            factor = data[key].unit_dpi / 2.54 / 10;
            name = $$("eas.column.unit.mm");
            break;
          case "px":
            factor = null;
            name = $$("eas.column.unit.px");
        }
        add_range(name, "technical_metadata.width", "min_width", "max_width", factor);
        add_range(name, "technical_metadata.height", "min_height", "max_height", factor);
        break;
      case "filesize_kb":
        add_range($$("eas.column.unit.filesize_kb"), "filesize", "min_filesize", "max_filesize", 1000);
        break;
      case "filesize_mb":
        add_range($$("eas.column.unit.filesize_mb"), "filesize", "min_filesize", "max_filesize", 1000 * 1000);
        break;
      case "filesize_gb":
        add_range($$("eas.column.unit.filesize_gb"), "filesize", "min_filesize", "max_filesize", 1000 * 1000 * 1000);
    }
    if (!CUI.util.isEmpty(data[key].original_filename)) {
      filenameValue = data[key].original_filename;
      filenameParts = filenameValue.split(",").map(function(s) {
        return s.trim();
      }).filter(function(s) {
        return s.length > 0;
      });
      if (filenameParts.length > 1) {
        _complex_filter = {
          type: "complex",
          search: [],
          bool: "must"
        };
        for (l = 0, len2 = filenameParts.length; l < len2; l++) {
          part = filenameParts[l];
          _part_filter = TextColumn.getSearchFilter(this.fullName() + ".original_filename", data[key], key, part);
          _part_filter.bool = "should";
          _complex_filter.search.push(_part_filter);
        }
        filter.search.push(_complex_filter);
      } else {
        _filter = TextColumn.getSearchFilter(this.fullName() + ".original_filename", data[key], key, filenameValue);
        filter.search.push(_filter);
      }
      info.push($$("main.search.expert.original_filename"));
    }
    if (!CUI.util.isEmpty(data[key].aspect)) {
      filter.search.push({
        type: "in",
        fields: [(this.fullName()) + ".technical_metadata.format"],
        "in": [data[key].aspect],
        bool: "must"
      });
      info.push($$("eas.column.aspect.opt." + data[key].aspect));
    }
    if (!CUI.util.isEmpty(data[key].id) && /^([0-9][\-,]?)*$/.test(data[key].id)) {
      filter.search.push(this.getSearchFilterTokenized(data[key].id));
      info.push($$("eas.column.status.id", {
        id: data[key].id
      }));
    }
    from = data[key].date_from || "";
    to = data[key].date_to || "";
    if (!CUI.util.isEmpty(from) || !CUI.util.isEmpty(to)) {
      dateKind = data[key].date_kind;
      if (dateKind === "create") {
        dateFieldName = "technical_metadata.date_time_original";
      } else {
        dateFieldName = "date_uploaded";
      }
      dateFilter = {
        type: "range",
        field: (this.fullName()) + "." + dateFieldName
      };
      if (!CUI.util.isEmpty(from)) {
        dateFilter.from = from;
      }
      if (!CUI.util.isEmpty(to)) {
        dateFilter.to = to;
      }
      info.push($$("eas.column.date." + data[key].date_kind, {
        from: from,
        to: to
      }));
      filter.search.push(dateFilter);
    }
    if (!CUI.util.isEmpty(data[key].metadata_fulltext) && ez5.version("6.7")) {
      _filter = TextColumn.getSearchFilter(this.fullName() + ".metadata_fulltext", data[key], key, data[key].metadata_fulltext);
      filter.search.push(_filter);
      info.push($$("eas.column.search.metadata_fulltext"));
    }
    if (filter.search.length) {
      return {
        filter: filter,
        info: info
      };
    } else {
      return {
        filter: null,
        info: []
      };
    }
  };

  EASColumn.prototype.renderSearchInput = function(search_data, opts) {
    var searchPopoverForm, searchPopoverFormFields, searchPopoverSetState, search_key;
    search_key = this.name();
    if (!search_data[search_key]) {
      search_data[search_key] = {};
    }
    searchPopoverFormFields = this.getSearchPopoverFormFields(search_data, search_key, opts);
    searchPopoverSetState = (function(_this) {
      return function() {
        var f, fileclass, hor_forms, i, innerField, j, l, len, len1, len2, ref, ref1, ref2, show, trigger_visibility_check, visible;
        show = ["id", "fileclass", "status", "filename", "date_kind", "date_from", "date_to"];
        if (ez5.version("6.7")) {
          show.push("metadata_fulltext");
        }
        fileclass = search_data[search_key].fileclass;
        switch (fileclass) {
          case "image":
          case "video":
            show.push("unit");
            show.push("aspect");
        }
        if (!CUI.util.isNull(fileclass)) {
          show.push("extension_" + fileclass);
        }
        if (show.indexOf("unit") > -1) {
          switch (search_data[search_key].unit) {
            case "filesize_kb":
            case "filesize_mb":
            case "filesize_gb":
              show.push("min_filesize", "max_filesize");
              break;
            case "px":
              show.push("min_width", "max_width", "min_height", "max_height");
              break;
            case "mm":
            case "cm":
              show.push("min_width", "max_width", "min_height", "max_height", "unit_dpi");
          }
        }
        hor_forms = [];
        ref = searchPopoverForm.getDataFields();
        for (i = 0, len = ref.length; i < len; i++) {
          f = ref[i];
          if (f.getForm().getForm()) {
            CUI.util.pushOntoArray(f.getForm(), hor_forms);
            trigger_visibility_check = false;
          } else {
            trigger_visibility_check = true;
          }
          if (show.indexOf(f.getName()) > -1) {
            f.show(trigger_visibility_check);
          } else {
            f.hide(trigger_visibility_check);
          }
        }
        for (j = 0, len1 = hor_forms.length; j < len1; j++) {
          f = hor_forms[j];
          visible = false;
          ref1 = f.getDataFields();
          for (l = 0, len2 = ref1.length; l < len2; l++) {
            innerField = ref1[l];
            if (!innerField.isHidden()) {
              visible = true;
            }
            if (ref2 = innerField.getName(), indexOf.call(show, ref2) >= 0) {
              innerField.show(true);
            } else {
              innerField.hide(true);
            }
          }
          if (visible) {
            f.show(true);
          } else {
            f.hide(true);
          }
        }
        searchPopoverForm.getPopover().position();
      };
    })(this);
    searchPopoverForm = new CUI.FormPopover({
      popover: {
        pane: {
          padded: true
        },
        onShow: (function(_this) {
          return function() {
            return searchPopoverSetState();
          };
        })(this),
        onHide: (function(_this) {
          return function() {
            return CUI.Events.trigger({
              node: searchPopoverForm.getButton(),
              type: "search-input-change"
            });
          };
        })(this)
      },
      button: {
        loca_key: "eas.column.search.button",
        ui: "eas.column.search.button"
      },
      fields: searchPopoverFormFields,
      data: search_data[search_key],
      trigger_data_changed_while_open: true,
      onDataChanged: (function(_this) {
        return function(data, field) {
          var fields, form, i, idField, len;
          form = field.getRootForm();
          idField = form.getFieldsByName("id")[0];
          fields = form.getFields();
          for (i = 0, len = fields.length; i < len; i++) {
            field = fields[i];
            if (field === idField) {
              continue;
            }
            if (data["id"]) {
              field.disable();
            } else {
              field.enable();
            }
          }
          if (["fileclass", "status", "date_from", "date_to", "original_filename"].some(function(key) {
            return data[key];
          })) {
            idField.disable();
          } else {
            idField.enable();
          }
          return searchPopoverSetState();
        };
      })(this),
      renderDisplayContent: (function(_this) {
        return function() {
          return ez5.renderFormPopoverInfo(_this.__getSearchFilterAndInfo(search_data, search_key).info);
        };
      })(this)
    }).start();
    return searchPopoverForm;
  };

  EASColumn.prototype.__getFileClasses = function() {
    return ["image", "vector3d", "video", "audio", "office", "archive", "unknown"];
  };

  EASColumn.prototype.__getEASStatus = function() {
    return ["pending", "processing", "failed", "done"];
  };

  EASColumn.prototype.getSearchPopoverFormFields = function(search_data, search_key, opts) {
    var aspect, aspect_opts, dateKindOptions, dpi, easColumn, easSearchColumn, eas_status, eas_types, ext, f, fc, fc_opt, fc_opts, ff, fileclass_opts, find_field_by_name, i, j, key, known_status, l, len, len1, len10, len2, len3, len4, len5, len6, len7, len8, len9, m, n, o, option, p, q, r, ref, ref1, ref10, ref11, ref12, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, searchPopoverFormFields, search_token_original_filename, status, statusOptions, status_loca_key, status_otps, status_text, t, u, unit, unit_dpi_opts, v, wrappedFields;
    easSearchColumn = new EASColumnSearchOriginalFilename(this.mask, this.FieldSchema);
    if (opts.fields) {
      wrappedFields = [];
      ref = opts.fields;
      for (i = 0, len = ref.length; i < len; i++) {
        f = ref[i];
        easColumn = null;
        if (f instanceof LinkedObject) {
          easColumn = (ref1 = f.getFirstStandardEASColumn()) != null ? ref1.fullName() : void 0;
        }
        wrappedFields.push(new EASColumnSearchOriginalFilename(f.mask, f.FieldSchema, easColumn));
      }
    }
    search_data[search_key]._fields = {};
    search_token_original_filename = new SearchToken({
      tokenize: true,
      supportsRange: false,
      column: easSearchColumn,
      data: search_data[search_key],
      fields: wrappedFields
    });
    fileclass_opts = [
      {
        text: $$("eas.column.fileclass.opt.all"),
        value: null,
        ui: "eas.column.search.form.fileclass.option:all"
      }
    ];
    ref2 = this.__getFileClasses();
    for (j = 0, len1 = ref2.length; j < len1; j++) {
      fc = ref2[j];
      fileclass_opts.push({
        text: $$("eas.column.fileclass.opt." + fc),
        value: fc,
        ui: "eas.column.search.form.fileclass.option:" + fc
      });
    }
    aspect_opts = [];
    ref3 = ["", "portrait", "landscape", "square"];
    for (l = 0, len2 = ref3.length; l < len2; l++) {
      aspect = ref3[l];
      if (aspect === "") {
        key = "all";
      } else {
        key = aspect;
      }
      aspect_opts.push({
        text: $$("eas.column.aspect.opt." + key),
        value: aspect,
        ui: "eas.column.search.form.aspect.option:" + key
      });
    }
    unit_dpi_opts = [];
    ref4 = ["150", "300", "600", "1200"];
    for (m = 0, len3 = ref4.length; m < len3; m++) {
      dpi = ref4[m];
      unit_dpi_opts.push({
        text: $$("eas.column.unit_dpi", {
          dpi: dpi
        }),
        value: dpi,
        ui: "eas.column.search.form.unit_dpi.option:" + dpi
      });
    }
    status_otps = [
      {
        text: $$("eas.column.status.all"),
        value: null,
        ui: "eas.column.search.form.status.option:all"
      }
    ];
    known_status = this.__getEASStatus();
    if (ez5.version("6")) {
      ref7 = opts != null ? (ref5 = opts.search) != null ? (ref6 = ref5.getSearchBasics()) != null ? ref6.easEASStatus() : void 0 : void 0 : void 0;
      for (status in ref7) {
        v = ref7[status];
        if (known_status.indexOf(status) === -1) {
          known_status.push(status);
        }
      }
    }
    for (n = 0, len4 = known_status.length; n < len4; n++) {
      status = known_status[n];
      status_loca_key = "eas.column.status." + status;
      if (ez5.loca.has(status_loca_key)) {
        status_text = $$("eas.column.status." + status);
      } else {
        status_text = status.charAt(0).toUpperCase() + status.slice(1);
      }
      status_otps.push({
        value: status,
        text: status_text,
        ui: "eas.column.search.form.status.option:" + status
      });
    }
    dateKindOptions = [
      {
        text: $$("eas.column.date_kind.opt.upload"),
        value: "upload"
      }
    ];
    if (ez5.version("6")) {
      dateKindOptions.push({
        text: $$("eas.column.date_kind.opt.create"),
        value: "create"
      });
    }
    searchPopoverFormFields = [
      {
        type: CUI.Select,
        form: {
          label: $$("main.search.expert.fileclass")
        },
        ui: "eas.column.search.form.fileclass.select",
        name: "fileclass",
        options: fileclass_opts,
        maximize_horizontal: true
      }, {
        type: CUI.Form,
        form: {
          label: $$("eas.column.unit")
        },
        horizontal: true,
        fields: [
          {
            type: CUI.Select,
            options: [],
            name: "unit",
            ui: "eas.column.search.form.unit.select"
          }, {
            type: CUI.Select,
            name: "unit_dpi",
            options: unit_dpi_opts,
            ui: "eas.column.search.form.unit_dpi.select"
          }
        ]
      }, {
        type: CUI.Form,
        form: {
          label: $$("main.search.expert.width")
        },
        horizontal: true,
        fields: [
          {
            type: CUI.Input,
            placeholder: $$("main.search.expert.from"),
            name: "min_width",
            ui: "eas.column.search.form.min_width.input"
          }, {
            type: CUI.Input,
            name: "max_width",
            placeholder: $$("main.search.expert.to"),
            ui: "eas.column.search.form.max_width.input"
          }
        ]
      }, {
        type: CUI.Form,
        form: {
          label: $$("main.search.expert.height")
        },
        horizontal: true,
        fields: [
          {
            type: CUI.Input,
            placeholder: $$("main.search.expert.from"),
            name: "min_height",
            ui: "eas.column.search.form.min_height.input"
          }, {
            type: CUI.Input,
            placeholder: $$("main.search.expert.to"),
            name: "max_height",
            ui: "eas.column.search.form.max_height.input"
          }
        ]
      }, {
        type: CUI.Form,
        form: {
          label: $$("main.search.expert.filesize")
        },
        horizontal: true,
        fields: [
          {
            type: CUI.Input,
            placeholder: $$("main.search.expert.from"),
            name: "min_filesize",
            ui: "eas.column.search.form.min_filesize.input"
          }, {
            type: CUI.Input,
            name: "max_filesize",
            placeholder: $$("main.search.expert.to"),
            ui: "eas.column.search.form.max_filesize.input"
          }
        ]
      }, {
        type: CUI.Form,
        form: {
          label: $$("main.search.expert.dpi")
        },
        horizontal: true,
        fields: [
          {
            type: CUI.Input,
            placeholder: $$("main.search.expert.from"),
            name: "min_dpi",
            ui: "eas.column.search.form.min_dpi.input"
          }, {
            type: CUI.Input,
            name: "max_dpi",
            placeholder: $$("main.search.expert.to"),
            ui: "eas.column.search.form.max_dpi.input"
          }
        ]
      }, {
        type: CUI.Select,
        form: {
          label: $$("main.search.expert.aspect")
        },
        name: "aspect",
        ui: "eas.column.search.form.aspect.select",
        options: aspect_opts,
        maximize_horizontal: true
      }, {
        type: CUI.Select,
        form: {
          label: $$("main.search.expert.status")
        },
        name: "status",
        ui: "eas.column.search.form.status.select",
        options: status_otps,
        maximize_horizontal: true
      }, {
        type: CUI.DataFieldProxy,
        form: {
          label: $$("main.search.expert.original_filename")
        },
        element: search_token_original_filename.getInput(),
        name: "filename",
        ui: "eas.column.search.form.filename.input",
        maximize_horizontal: true
      }, {
        type: CUI.Form,
        horizontal: true,
        form: {
          label: $$("main.search.expert.date.kind")
        },
        fields: [
          {
            type: CUI.Select,
            name: "date_kind",
            ui: "eas.column.search.form.date_kind.select",
            options: dateKindOptions
          }, {
            type: CUI.Form,
            fields: [
              {
                name: "date_from",
                type: CUI.DateTime,
                input_types: ["date"],
                display_type: "short",
                placeholder: $$("main.search.expert.from"),
                ui: "eas.column.search.form.date_from.datetime"
              }, {
                name: "date_to",
                type: CUI.DateTime,
                display_type: "short",
                input_types: ["date"],
                placeholder: $$("main.search.expert.to"),
                ui: "eas.column.search.form.date_to.datetime"
              }
            ]
          }
        ]
      }, {
        type: CUI.Input,
        form: {
          label: $$("main.search.expert.id")
        },
        name: "id",
        ui: "eas.column.search.form.id.input",
        regexp: "^([0-9][\\-,]?)*$",
        maximize_horizontal: true
      }
    ];
    if (ez5.version("6.7")) {
      searchPopoverFormFields.push({
        type: CUI.Input,
        form: {
          label: $$("main.search.expert.metadata_fulltext")
        },
        name: "metadata_fulltext",
        maximize_horizontal: true
      });
    }
    find_field_by_name = (function(_this) {
      return function(name, fields) {
        var _ff, ff, len5, o;
        if (fields == null) {
          fields = searchPopoverFormFields;
        }
        for (o = 0, len5 = fields.length; o < len5; o++) {
          ff = fields[o];
          if (ff.fields) {
            _ff = find_field_by_name(name, ff.fields);
            if (_ff) {
              return _ff;
            }
          }
          if (ff.name === name) {
            return ff;
          }
        }
        return null;
      };
    })(this);
    fc_opts = searchPopoverFormFields[0].options;
    eas_types = (ref8 = opts.search) != null ? ref8.getSearchBasics().getEASTypes() : void 0;
    ref9 = this.__getFileClasses();
    for (o = 0, len5 = ref9.length; o < len5; o++) {
      fc = ref9[o];
      ff = {
        type: CUI.Options,
        form: {
          label: $$("main.search.expert.extension")
        },
        name: "extension_" + fc,
        ui: "eas.column.search.form.extension.option:" + fc,
        options: []
      };
      searchPopoverFormFields.splice(1, 0, ff);
      if (opts.search) {
        if (!((ref10 = eas_types[fc]) != null ? ref10.length : void 0)) {
          for (p = 0, len6 = fc_opts.length; p < len6; p++) {
            fc_opt = fc_opts[p];
            if (fc_opt.value === fc) {
              fc_opt.disabled = true;
            }
          }
        } else {
          ref11 = eas_types[fc];
          for (q = 0, len7 = ref11.length; q < len7; q++) {
            ext = ref11[q];
            ff.options.push({
              text: ext || $$("eas.column.option.no_extension"),
              value: ext,
              ui: "eas.column.search.form.extension.option:no_extension"
            });
          }
        }
      }
    }
    if (opts.search) {
      statusOptions = searchPopoverFormFields.filter(function(field) {
        return field.name === "status";
      })[0].options;
      eas_status = opts.search.getSearchBasics().easEASStatus();
      for (r = 0, len8 = statusOptions.length; r < len8; r++) {
        option = statusOptions[r];
        if (option.value && !eas_status[option.value]) {
          option.disabled = true;
        }
      }
    }
    ref12 = ["px", "mm", "cm", "filesize_kb", "filesize_mb", "filesize_gb"];
    for (t = 0, len9 = ref12.length; t < len9; t++) {
      unit = ref12[t];
      find_field_by_name("unit").options.push({
        text: $$("eas.column.unit." + unit),
        value: unit,
        ui: "eas.column.search.form.unit.option:" + unit
      });
    }
    for (u = 0, len10 = searchPopoverFormFields.length; u < len10; u++) {
      f = searchPopoverFormFields[u];
      f.mark_changed = false;
      f.undo_support = false;
    }
    return searchPopoverFormFields;
  };

  EASColumn.prototype.uploadAdd = function(data, file) {
    var i, len, ref, value;
    if (!data[this.name()]) {
      data[this.name()] = [];
    }
    ref = data[this.name()];
    for (i = 0, len = ref.length; i < len; i++) {
      value = ref[i];
      value._old_preferred = value.preferred;
      value.preferred = false;
    }
    value = {
      preferred: true,
      _file_upload: file
    };
    file._value = value;
    data[this.name()].push(value);
    return value;
  };

  EASColumn.prototype.updateData = function(data) {};

  EASColumn.prototype.uploadDone = function(data, file) {
    file._value._id = file.getData()[0]._id;
    file._value.original_filename = file.getName();
    delete file._file_upload;
    return this.updateData(data);
  };

  EASColumn.prototype.uploadFail = function(data, file) {
    var i, len, ref, value;
    delete file._file_upload;
    CUI.util.removeFromArray(file._value, data[this.name()]);
    ref = data[this.name()];
    for (i = 0, len = ref.length; i < len; i++) {
      value = ref[i];
      if (value._old_preferred) {
        delete value._old_preferred;
        value.preferred = true;
      }
    }
    return this.updateData(data);
  };

  EASColumn.prototype.getImgValueByIdx = function(data, idx) {
    var ref;
    return (ref = data[this.name()]) != null ? ref[idx] : void 0;
  };

  EASColumn.prototype.removeAsset = function(data) {
    var idx;
    idx = CUI.util.idxInArray(void 0, data[this.name()], function(v) {
      return !!v.preferred;
    });
    if (idx === -1) {
      data[this.name()].splice(0);
    } else {
      data[this.name()].splice(idx, 1);
      if (idx === data[this.name()].length) {
        idx--;
      }
      if (idx >= 0) {
        data[this.name()][idx].preferred = true;
      }
    }
    return this.updateData(data);
  };

  EASColumn.prototype.getImgValuePreferred = function(data) {
    var i, len, list, value;
    list = data[this.name()];
    if (!list || list.length === 0) {
      return null;
    }
    CUI.util.assert(CUI.util.isArray(list), "EASColumn.getImgValuePreferred", "Data for EAS field is not an Array", {
      data: data,
      name: this.name()
    });
    for (i = 0, len = list.length; i < len; i++) {
      value = list[i];
      if (value.preferred) {
        return value;
      }
    }
    return list[0];
  };

  EASColumn.prototype.hasMetadataSelector = function() {
    return true;
  };

  EASColumn.prototype.hasManageVersions = function() {
    if (ez5.version("6.8") && !ez5.session.hasSystemRight("root", "frontend_features[asset_variants]")) {
      return false;
    }
    return true;
  };

  EASColumn.prototype.hasButtonDownloadOriginal = function(data) {
    return true;
  };

  EASColumn.prototype.forceButtonDownloadOriginal = function() {
    return false;
  };

  EASColumn.prototype.hasButtonShareUrl = function() {
    return true;
  };

  EASColumn.prototype.hasAssetBrowser = function() {
    return true;
  };

  EASColumn.prototype.hasInstantRotate = function(value) {
    var ref, ref1;
    return (value != null ? (ref = value.versions) != null ? (ref1 = ref.original) != null ? ref1["class"] : void 0 : void 0 : void 0) === "image" && Asset.canProduceNewVersion(value);
  };

  EASColumn.prototype.scaleAndPosition = function() {
    return false;
  };

  EASColumn.prototype.getUploadUrl = function() {
    return ez5.eas.getUploadUrl();
  };

  EASColumn.prototype.renderEditorInput = function(data, top_level_data, opts) {
    var $img_el, content, current_value, default_pic, dupDialog, get_btn_items, get_img_el, get_multiple, lay, menubtn, setButtonClass, sp, summary, trigger_events, updateSummary, update_eas, upload;
    if (opts == null) {
      opts = {};
    }
    menubtn = null;
    summary = null;
    if (opts.default_pic_name) {
      default_pic = ez5.session.getDefaultPicture(opts.default_pic_name);
    }
    updateSummary = (function(_this) {
      return function() {
        if (current_value) {
          summary = Asset.getSummary(current_value);
          return lay.replace(summary, "center");
        } else if (summary) {
          return CUI.dom.remove(summary);
        }
      };
    })(this);
    get_multiple = (function(_this) {
      return function() {
        if (opts.appendMultipleRows && data._new && !_this.__inside_nested_popup) {
          return true;
        } else {
          return false;
        }
      };
    })(this);
    dupDialog = new DuplicatesDialog({
      ui: "eas.column.duplicates.dialog"
    });
    content = null;
    trigger_events = (function(_this) {
      return function() {
        CUI.Events.trigger({
          node: content,
          type: "editor-reload-asset-browser"
        });
      };
    })(this);
    upload = new CUI.FileUpload({
      url: this.getUploadUrl(),
      onAdd: (function(_this) {
        return function(file) {};
      })(this),
      onBeforeDone: (function(_this) {
        return function(file) {
          return dupDialog.addFile(file);
        };
      })(this),
      onAdd: (function(_this) {
        return function(file) {
          var imgElement, value;
          if (get_multiple()) {
            file._new_data = {};
            _this.uploadAdd(file._new_data, file);
            content = opts.appendMultipleRows(file._new_data);
            trigger_events();
            return;
          }
          value = _this.uploadAdd(data, file);
          imgElement = get_img_el(value);
          lay.replace(imgElement, "left");
          menubtn.disable();
          CUI.Events.trigger({
            node: lay,
            type: "editor-reload-asset-browser"
          });
        };
      })(this),
      onDone: (function(_this) {
        return function(file) {
          if (get_multiple()) {
            _this.uploadDone(file._new_data, file);
            trigger_events();
            return;
          }
          _this.uploadDone(data, file);
          menubtn.enable();
          CUI.Events.trigger({
            node: lay,
            type: "editor-reload-asset-browser"
          });
          CUI.Events.trigger({
            node: lay,
            type: "editor-changed"
          });
        };
      })(this),
      onFail: (function(_this) {
        return function(file) {
          if (get_multiple()) {
            _this.uploadFail(file._new_data, file);
            if (file.getStatus() === "FAILED") {
              EAS.presentUploadError(file);
            }
            trigger_events();
            return;
          }
          _this.uploadFail(data, file);
          menubtn.enable();
          if (file.getStatus() === "FAILED") {
            ez5.error_handler(file.getErrorXHR());
          }
        };
      })(this)
    });
    lay = new CUI.HorizontalLayout({
      maximize_horizontal: true,
      maximize_vertical: true,
      ui: "ez5-eas-column-editor-" + this.name() + "-horizontal-layout",
      "class": "ez5-eas-column ez5-eas-column-editor-input",
      right: {},
      center: {},
      left: {}
    });
    CUI.dom.setAttribute(lay.DOM, "tabindex", "0");
    CUI.Events.listen({
      type: "eas_update",
      node: lay,
      call: (function(_this) {
        return function(ev, info) {
          if (info.thumbnailUpdate) {
            opts = {
              waitForOriginal: true
            };
            update_eas(true, true, opts);
            return;
          }
          updateSummary();
          update_eas(true, false);
          return menubtn.enable();
        };
      })(this)
    });
    current_value = null;
    CUI.Events.listen({
      type: "keyup",
      node: lay,
      call: (function(_this) {
        return function(ev) {
          var ref, value;
          if (ev.hasModifierKey()) {
            return;
          }
          if (ev.getTarget() === lay.DOM && ((ref = ev.keyCode()) === 8 || ref === 46)) {
            ev.stopPropagation();
            value = _this.getImgValuePreferred(data);
            if (value && !value._file_upload) {
              _this.removeAsset(data);
              update_eas(true);
            }
          }
        };
      })(this)
    });
    get_btn_items = (function(_this) {
      return function() {
        var _asset, items, ref, ref1, ref2, showInAssetBrowserDisabled, value;
        value = _this.getImgValuePreferred(data);
        if (!value) {
          return [];
        }
        if (value._file_upload && !value._id) {
          console.debug("get btn items...", value, value._file_upload);
          return [
            {
              loca_key: "eas.column.upload.abort",
              onClick: function() {
                return value._file_upload.abort();
              }
            }
          ];
        }
        _asset = new Asset(_this, value, data[_this.name()], opts.top_level_data);
        items = [
          new CUI.FileUploadButton({
            ui: "eas-column-menu-option-upload-button",
            fileUpload: upload,
            multiple: false,
            text: ez5.loca.str_default("main.editor.eas_asset_upload|text", null),
            icon: ez5.loca.str_default("main.editor.eas_asset_upload|icon", "search"),
            onClick: function() {
              return CUI.setTimeout((function(_this) {
                return function() {
                  return menubtn.getMenu().hideAll();
                };
              })(this));
            },
            tooltip: {
              text: ez5.loca.str_default("main.editor.eas_asset_upload|tooltip", null)
            }
          }), {
            ui: "eas-column-menu-option-asset-remove-button",
            icon: "trash",
            loca_key: "eas.column.button.asset_remove",
            onClick: function() {
              _this.removeAsset(data);
              return update_eas(true);
            }
          }, _this.hasButtonDownloadOriginal(data) ? _asset.getButtonDownloadOriginal(null, _this.forceButtonDownloadOriginal()) : void 0, _this.hasButtonShareUrl() ? _asset.getButtonShareUrl() : void 0
        ];
        if (_this.hasAssetBrowser() && _this.__hasAssetBrowser(lay.DOM)) {
          showInAssetBrowserDisabled = false;
          if (opts.editor && ((ref = opts.editor.assetBrowser) != null ? (ref1 = ref.getCurrentAsset()) != null ? ref1.getId() : void 0 : void 0) === _asset.getId()) {
            showInAssetBrowserDisabled = true;
          }
          items.push({
            loca_key: "eas.column.show_asset",
            ui: "eas-column-menu-option-show-asset-button",
            disabled: showInAssetBrowserDisabled,
            onClick: function() {
              _this.__showInAssetBrowser(lay.DOM, current_value);
              return menubtn.getMenu().hideAll();
            }
          });
        }
        if (_this.hasManageVersions()) {
          items.push({
            ui: "eas-column-menu-option-manage-versions-button",
            loca_key: "eas.column.button.manage_versions",
            onClick: function() {
              return new AssetVersions({
                field: _this,
                data: data,
                object_data: opts.top_level_data,
                done: function() {
                  return update_eas(true);
                }
              });
            }
          });
        }
        if (_this.hasInstantRotate(value)) {
          items.push({
            icon: "rotate_right",
            ui: "eas-column-menu-option-rotate-right-button",
            loca_key: "eas.column.button.rotate_right",
            onClick: function() {
              value = _this.getImgValuePreferred(data);
              value.transform = AssetVersions.addTransform(value.transform, 90);
              return update_eas();
            }
          });
          items.push({
            icon: "rotate_left",
            ui: "eas-column-menu-option-rotate-left-button",
            loca_key: "eas.column.button.rotate_left",
            onClick: function() {
              value = _this.getImgValuePreferred(data);
              value.transform = AssetVersions.addTransform(value.transform, -90);
              return update_eas();
            }
          });
          items.push({
            icon: "refresh",
            disabled: !((ref2 = value.transform) != null ? ref2.length : void 0),
            ui: "eas-column-menu-option-rotate-reset-button",
            loca_key: "eas.column.button.rotate_reset",
            onClick: function() {
              value = _this.getImgValuePreferred(data);
              value.transform = [];
              return update_eas();
            }
          });
        }
        return items;
      };
    })(this);
    menubtn = new CUI.FileUploadButton({
      ui: "eas-column-editor-" + this.name() + "-button",
      icon: "ellipsis_v",
      icon_right: false,
      appearance: "flat",
      fileUpload: upload,
      multiple: get_multiple,
      tooltip: {
        text: (function(_this) {
          return function() {
            if (!_this.getImgValuePreferred(data)) {
              return ez5.loca.str_default("main.editor.eas_asset_upload|tooltip", null);
            } else {
              return ez5.loca.str_default("eas.column.upload.file_upload_menu|tooltip", null);
            }
          };
        })(this)
      },
      menu: {
        items: get_btn_items
      }
    });
    get_img_el = (function(_this) {
      return function(value) {
        var asset, div, lkey, ll, ref, version, versions_indicator;
        if (value) {
          current_value = value;
        } else {
          current_value = null;
          updateSummary();
        }
        if (!value && default_pic) {
          value = default_pic;
          version = "original";
        } else if (value != null ? value._id : void 0) {
          version = Asset.getStandardVersionName(value);
          updateSummary();
        } else if (value != null ? value._file_upload : void 0) {
          version = null;
        } else {
          if (opts.appendMultipleRows) {
            lkey = "eas.column.upload.zone.multiple";
          } else {
            lkey = "eas.column.upload.zone";
          }
          ll = new LocaLabel({
            "class": "ez5-eas-column-upload-zone",
            loca_key: lkey
          });
          div = ll.DOM;
        }
        if (!div) {
          if (opts.text_only) {
            value._is_text_only = true;
          }
          asset = new Asset(_this, value);
          div = asset.getImgElement(function(file) {
            switch (file.getStatus()) {
              case "DONE":
                return menubtn.enable();
              case "FAILED":
              case "ABORT":
                update_eas(true);
                return menubtn.enable();
              default:
                if (!file.isDone()) {
                  return menubtn.enable();
                } else {
                  return menubtn.disable();
                }
            }
          }, version, {
            resize_placeholder: true
          });
        }
        upload.resetDropZones().initDropZone({
          dropZone: div,
          multiple: get_multiple
        });
        if (((ref = data[_this.name()]) != null ? ref.length : void 0) > 1 && _this.hasManageVersions()) {
          versions_indicator = CUI.dom.div("ez-asset-multiple-indicator", {
            ui: "eas.column.multiple_indicator.icon"
          });
          CUI.dom.append(versions_indicator, new CUI.Icon({
            icon: "svg-multiple"
          }));
          CUI.dom.append(div, versions_indicator);
        }
        return div;
      };
    })(this);
    update_eas = (function(_this) {
      return function(fullReload, updateEvent, opts) {
        var oldImgElement, value;
        if (fullReload == null) {
          fullReload = false;
        }
        if (updateEvent == null) {
          updateEvent = true;
        }
        if (opts == null) {
          opts = {};
        }
        value = _this.getImgValuePreferred(data);
        if (opts.waitForOriginal) {
          value.__waitForOriginal = true;
        }
        oldImgElement = CUI.dom.matchSelector(lay.DOM, ".ez5-asset-element")[0];
        if (oldImgElement) {
          ez5.eas.replaceImgElement(oldImgElement, get_img_el(value), updateEvent);
        }
        if (fullReload) {
          CUI.Events.trigger({
            node: lay,
            type: "editor-reload-asset-browser"
          });
        } else {
          CUI.Events.trigger({
            node: lay,
            type: "editor-update-asset-browser"
          });
        }
        return CUI.Events.trigger({
          node: lay,
          type: "editor-changed"
        });
      };
    })(this);
    $img_el = get_img_el(this.getImgValuePreferred(data));
    CUI.Events.listen({
      node: $img_el,
      type: "click",
      call: (function(_this) {
        return function(ev) {
          if (!current_value) {
            return;
          }
          if (ev.altKey()) {
            return;
          }
          return _this.__showInAssetBrowser(lay, current_value);
        };
      })(this)
    });
    CUI.Events.listen({
      node: $img_el,
      type: "dblclick",
      call: (function(_this) {
        return function(ev) {
          if (!current_value) {
            return;
          }
          if (!ev.altKey()) {
            return;
          }
          if (!_this.hasManageVersions()) {
            return;
          }
          ev.stopPropagation();
          ev.preventDefault();
          new AssetVersions({
            field: _this,
            data: data,
            object_data: opts.top_level_data,
            done: function() {
              return update_eas(true);
            }
          });
        };
      })(this)
    });
    CUI.Events.listen({
      node: lay,
      type: "click",
      call: (function(_this) {
        return function(ev) {
          if (!current_value) {
            return menubtn.DOM.click();
          }
        };
      })(this)
    });
    setButtonClass = (function(_this) {
      return function() {
        if (!current_value) {
          return lay.addClass("cui-button");
        } else {
          return lay.removeClass("cui-button");
        }
      };
    })(this);
    setButtonClass();
    CUI.Events.listen({
      node: lay,
      type: "editor-changed",
      call: (function(_this) {
        return function(ev) {
          return setButtonClass();
        };
      })(this)
    });
    if (sp = this.scaleAndPosition()) {
      lay.addClass("ez5-eas-image-scalable");
    }
    lay.addClass(this.getClass());
    lay.append($img_el, "left");
    lay.append(menubtn, "right");
    return lay.DOM;
  };

  EASColumn.prototype.__showInAssetBrowser = function(img_el, value) {
    CUI.Events.trigger({
      node: img_el,
      type: "asset-browser-show-asset",
      info: {
        value: value
      }
    });
  };

  EASColumn.prototype.__hasAssetBrowser = function(el) {
    var _el, i, j, len, len1, listener, listeners, ref;
    ref = CUI.dom.parents(el);
    for (i = 0, len = ref.length; i < len; i++) {
      _el = ref[i];
      listeners = CUI.dom.data(_el, "listeners");
      if (!((listeners != null ? listeners.length : void 0) > 0)) {
        continue;
      }
      for (j = 0, len1 = listeners.length; j < len1; j++) {
        listener = listeners[j];
        if (indexOf.call(listener.getTypes(), "asset-browser-show-asset") >= 0) {
          return true;
        }
      }
    }
    return false;
  };

  EASColumn.prototype.renderDetailOutput = function(data, top_level_data, opts) {
    var asset, asset_el, get_btn_items, hl, isDeleted, menubtn, ref, value, versions_indicator;
    if (opts == null) {
      opts = {};
    }
    value = this.getImgValuePreferred(data);
    if (!value) {
      return;
    }
    isDeleted = value.status === "deleted";
    asset = new Asset(this, value, data[this.name()], opts.top_level_data);
    if (opts.for_print || asset.isDeleted()) {
      menubtn = null;
    } else {
      menubtn = new LocaButton({
        icon: "ellipsis_v",
        appearance: "flat",
        icon_right: false,
        ui: "eas.column.detail.menu.button:" + (this.name()),
        loca_key: "eas.column.detail.menu",
        appearance: "flat",
        menu: {
          items: (function(_this) {
            return function() {
              return get_btn_items();
            };
          })(this)
        }
      });
    }
    hl = asset.renderDetailOutput({
      ui: "eas.column.detail.output:" + (this.name()),
      for_print: opts.for_print,
      resize_placeholder: true,
      alt: StandardField.getStandardText(top_level_data),
      right: {
        content: menubtn
      }
    });
    if (!opts.for_print) {
      get_btn_items = (function(_this) {
        return function() {
          var items, ref, ref1, ref2, ref3, ref4, showInAssetBrowserDisabled, top_level_deleted;
          items = [];
          if (_this.hasAssetBrowser() && _this.__hasAssetBrowser(hl.DOM) && !isDeleted) {
            showInAssetBrowserDisabled = false;
            if (opts.detail && ((ref = opts.detail.getAssetBrowserPlugin()) != null ? (ref1 = ref.getCurrentAsset()) != null ? ref1.getId() : void 0 : void 0) === asset.getId()) {
              showInAssetBrowserDisabled = true;
            }
            if (opts.history) {
              showInAssetBrowserDisabled = true;
            }
            items.push(new LocaButton({
              loca_key: "eas.column.show_asset",
              ui: "eas.column.detail.show_asset.button",
              disabled: showInAssetBrowserDisabled,
              onClick: function() {
                _this.__showInAssetBrowser(hl.DOM, value);
                return menubtn.getMenu().hideAll();
              }
            }));
          }
          if (!((ref2 = opts.top_level_data) != null ? ref2._instance : void 0) && !isDeleted) {
            items.push(asset.getButtonDownloadOriginal());
          }
          top_level_deleted = (opts != null ? (ref3 = opts.top_level_data) != null ? ref3._latest_version_deleted_at : void 0 : void 0) != null;
          if ((!isDeleted && !opts.history) && !top_level_deleted) {
            items.push(asset.getButtonShareUrl());
          }
          if (!((ref4 = opts.top_level_data) != null ? ref4._instance : void 0)) {
            items.push(asset.getAssetVersionsButton());
          }
          return items;
        };
      })(this);
    }
    if (!opts.for_print && opts.mode !== "table" && !isDeleted) {
      CUI.Events.listen({
        type: "click",
        node: hl,
        call: (function(_this) {
          return function(ev) {
            _this.__showInAssetBrowser(hl.DOM, value);
            return ev.stop();
          };
        })(this)
      });
    }
    if (((ref = data[this.name()]) != null ? ref.length : void 0) > 1 && this.hasManageVersions()) {
      versions_indicator = CUI.dom.div("ez-asset-multiple-indicator", {
        ui: "eas.column.multiple_indicator.icon"
      });
      CUI.dom.append(versions_indicator, new CUI.Icon({
        icon: "svg-multiple"
      }));
      asset_el = CUI.dom.matchSelector(hl, ".ez5-asset-element")[0];
      if (asset_el) {
        CUI.dom.append(asset_el, versions_indicator);
      }
    }
    return hl.DOM;
  };

  EASColumn.prototype.renderTableOutput = function(data, top_level_data, opts) {
    if (opts == null) {
      opts = {};
    }
    opts.mode = "table";
    return this.renderDetailOutput(data, top_level_data, opts);
  };

  EASColumn.containImage = function(img) {
    var _img, contain_image, deferred;
    _img = new Image();
    _img.src = img.src;
    contain_image = (function(_this) {
      return function() {
        var dim, height, left, ref, scale, top, vp_height, vp_width, width;
        dim = CUI.dom.getDimensions(img.parentNode);
        if (_img.width * _img.height * dim.contentBoxWidth * dim.contentBoxHeight === 0) {
          console.warn("EASColumn.containImage: Some sizes are 0, unable to contain image.", img, _img, _img.width, _img.height, dim);
          return;
        }
        if (img.hasAttribute("turned90")) {
          vp_width = dim.contentBoxHeight;
          vp_height = dim.contentBoxWidth;
        } else {
          vp_width = dim.contentBoxWidth;
          vp_height = dim.contentBoxHeight;
        }
        if (img.hasAttribute("scale")) {
          scale = parseFloat(img.getAttribute("scale"));
        } else {
          scale = 1;
        }
        ref = ez5.fitRectangle(_img.width, _img.height, vp_width, vp_height), width = ref[0], height = ref[1], top = ref[2], left = ref[3];
        CUI.dom.setStyle(img, {
          position: "absolute",
          top: top / scale,
          left: left / scale,
          width: width / scale,
          height: height / scale,
          transform: "none"
        });
        CUI.dom.setStyle(img.parentNode, {
          position: "relative"
        });
      };
    })(this);
    if (_img.width === 0) {
      deferred = new CUI.Deferred();
      CUI.Events.listen({
        type: "load",
        node: _img,
        only_once: true,
        call: (function(_this) {
          return function() {
            contain_image();
            deferred.resolve();
          };
        })(this)
      });
      return deferred.promise();
    }
    contain_image();
    return CUI.resolvedPromise();
  };

  EASColumn.prototype.getImgElementForValue = function(value, version, onUpdate, opts) {
    var _version, assetInfoDiv, attr, blurData, blurhashString, checkOriginal, cls, compiled, file, img, imgPlaceholder, img_div, img_el, img_el_transform, instance, original_filename, pollOpts, ref, ref1, ref10, ref11, ref12, ref13, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, remoteEasydb, status_original, svg, svgHeight, svgWidth, urlWithToken, versionUrl;
    if (opts == null) {
      opts = {};
    }
    CUI.util.assert(CUI.util.isPlainObject(value) && !CUI.util.isEmptyObject(value), "EASColumn.getImgElementForValue", "Value needs to be plain object.", {
      value: value,
      version: version
    });
    CUI.util.assert(value._error || version || value._file_upload || value._id || value.status === "deleted", "EASColumn.getImgElementForValue", "value and/or version needs to be given.", {
      value: value,
      version: version
    });
    checkOriginal = (function(_this) {
      return function() {
        if (!ez5.version("6") || !value.__waitForOriginal) {
          return true;
        }
        return status_original === "done";
      };
    })(this);
    status_original = value != null ? value.status : void 0;
    compiled = value != null ? value.compiled : void 0;
    original_filename = value != null ? value.original_filename : void 0;
    if (!CUI.util.isEmpty(original_filename)) {
      if (!CUI.util.isEmpty(compiled)) {
        compiled = compiled + ", " + original_filename;
      } else {
        compiled = original_filename;
      }
    }
    _version = (ref = value.versions) != null ? ref[version] : void 0;
    if (value._error) {
      img_el = CUI.dom.div();
      CUI.dom.append(img_el, EAS.getErrorPlaceholder(value._error).DOM);
    } else if (status_original === "deleted") {
      img_el = CUI.dom.div();
      CUI.dom.append(img_el, EAS.getDeletedPlaceholder().DOM);
    } else if (status_original === "failed" || (_version != null ? _version.status : void 0) === "failed") {
      img_el = CUI.dom.div();
      CUI.dom.append(img_el, EAS.getFailedPlaceholder().DOM);
    } else if (_version != null ? _version._not_allowed : void 0) {
      console.info("EASColumn.getImgElementForValue: version " + version + " not allowed.");
      img_el = CUI.dom.div();
      CUI.dom.append(img_el, EAS.getNoRightPlaceholder().DOM);
    } else if (status_original === "done" && !_version || ((_version != null ? _version["class"] : void 0) === "image" && (ref1 = _version != null ? _version.extension : void 0, indexOf.call(Asset.getImageValidExtensionsForBrowser(), ref1) < 0))) {
      img_el = CUI.dom.div();
      CUI.dom.append(img_el, EAS.getNoThumbPlaceholder(value).DOM);
      assetInfoDiv = CUI.dom.div("ez5-asset-info");
      assetInfoDiv.textContent = compiled;
      CUI.dom.setAttribute(assetInfoDiv, "ui", "eas.column.asset_info");
      CUI.dom.append(img_el, assetInfoDiv);
    } else if ((_version != null ? _version.status : void 0) === "done" && CUI.util.isEmpty(_version.url)) {
      console.info("EASColumn.getImgElementForValue: version " + version + " url is empty.");
      img_el = CUI.dom.div();
      CUI.dom.append(img_el, EAS.getNoUrlPlaceholder().DOM);
    } else if ((_version != null ? _version.status : void 0) === "done" && checkOriginal()) {
      if (_version.width > _version.height) {
        cls = "eas-image landscape";
      } else {
        cls = "eas-image portrait";
      }
      img_div = CUI.dom.div(cls, {
        "real-width": _version.width || (_version != null ? (ref2 = _version.technical_metadata) != null ? (ref3 = ref2.dimensions) != null ? ref3.width : void 0 : void 0 : void 0),
        "real-height": _version.height || (_version != null ? (ref4 = _version.technical_metadata) != null ? (ref5 = ref4.dimensions) != null ? ref5.height : void 0 : void 0 : void 0),
        version: version
      });
      CUI.dom.setAttribute(img_div, "ui", "eas.column.version:" + version);
      CUI.dom.setStyle(img_div, {
        "--real-width": _version != null ? (ref6 = _version.technical_metadata) != null ? (ref7 = ref6.dimensions) != null ? ref7.width : void 0 : void 0 : void 0,
        "--real-height": _version != null ? (ref8 = _version.technical_metadata) != null ? (ref9 = ref8.dimensions) != null ? ref9.height : void 0 : void 0 : void 0
      }, "");
      if (!opts.background_image) {
        if (!opts.for_print) {
          attr = {};
          attr["data-observer-src"] = _version.url;
          if (("" + value._id).includes("@")) {
            instance = value._id.split('@')[1];
            remoteEasydb = (ref10 = ez5.connector) != null ? ref10.getRemoteEasydbByInstance(instance) : void 0;
            if (remoteEasydb) {
              attr["data-remote-instance"] = instance;
            }
          }
          if (opts.alt) {
            attr.alt = opts.alt;
          }
          img = CUI.dom.element("IMG", attr);
          img_div.appendChild(img);
          blurhashString = value != null ? (ref11 = value.versions) != null ? (ref12 = ref11[version]) != null ? ref12.blurhash : void 0 : void 0 : void 0;
          if (blurhashString) {
            imgPlaceholder = CUI.dom.$element("img");
            blurData = blurhash.decode(blurhashString, 20, 20, 1);
            blurhash.getImageDataAsImage(blurData, 20, 20, (function(_this) {
              return function(event, blurImg) {
                return CUI.dom.setAttribute(imgPlaceholder, "src", blurImg.src);
              };
            })(this));
          } else {
            svgWidth = _version.width || 100;
            svgHeight = _version.height || 100;
            svg = "<svg width='" + svgWidth + "' height='" + svgHeight + "'> <rect width=\"100%\" height=\"100%\" fill='#eee'></rect> </svg>";
            svg = CUI.dom.htmlToNodes(svg)[0];
            imgPlaceholder = CUI.dom.div();
            CUI.dom.append(imgPlaceholder, svg);
          }
          CUI.dom.setStyle(imgPlaceholder, {
            position: "absolute",
            aspectRatio: _version.width + "/" + _version.height
          });
          CUI.dom.addClass(imgPlaceholder, "asset-blurhash");
          img.__placeholder = imgPlaceholder;
          img_div.appendChild(imgPlaceholder);
          if (!opts.force_no_observer) {
            EAS.IntersectionObserver.add(img);
          }
        } else {
          versionUrl = _version.url;
          if (ez5.version("6")) {
            versionUrl = Session.addToken(versionUrl);
          }
          img = CUI.dom.element("IMG", {
            src: versionUrl
          });
          CUI.dom.setAttribute(img, "loading", "lazy");
          img_div.appendChild(img);
        }
      }
      if (opts.for_print) {
        img_el = img_div;
      } else {
        if (opts.background_image) {
          urlWithToken = _version.url;
          CUI.dom.setStyleOne(img_div, "backgroundImage", "url(" + urlWithToken + ")");
        }
        img_el_transform = CUI.dom.div("ez5-asset-element-transform");
        CUI.dom.append(img_el_transform, img_div);
        if (((ref13 = value.transform) != null ? ref13.length : void 0) > 0) {
          EAS.setTransformStyle(img_el_transform, value.transform);
        } else {
          value.transform = [];
        }
        img_el = CUI.dom.div();
        CUI.dom.append(img_el, img_el_transform);
      }
      img_el;
    } else if (value._id) {
      if (opts.for_print || (opts.show_hourglass && !value._file_upload)) {
        img_el = CUI.dom.div();
        CUI.dom.append(img_el, EAS.getProcessingPlaceholder(value));
        assetInfoDiv = CUI.dom.div("ez5-asset-info");
        assetInfoDiv.textContent = compiled;
        CUI.dom.setAttribute(assetInfoDiv, "ui", "eas.column.asset_info");
        CUI.dom.append(img_el, assetInfoDiv);
      } else {
        if (ez5.version("6") && opts.obj_data) {
          pollOpts = {
            obj_data: opts.obj_data
          };
        }
        if (ez5.version("6") && status_original !== "done" && value.__waitForOriginal) {
          if (pollOpts == null) {
            pollOpts = {};
          }
          pollOpts["listenForVersionsChanges"] = true;
          pollOpts["loadVersion"] = version;
          version = "original";
        }
        img_el = ez5.eas.getPollingPlaceholder(this, value, version, pollOpts);
      }
    } else if ((file = value._file_upload)) {
      if (!file._divs) {
        file._update_state = function() {
          var _div, i, idx, len, ref14;
          ref14 = file._divs;
          for (idx = i = 0, len = ref14.length; i < len; idx = ++i) {
            _div = ref14[idx];
            if (_div.onUpdate) {
              _div.onUpdate(file);
            }
          }
        };
        file._divs = [];
        file.getPromise().done((function(_this) {
          return function() {
            var _div, i, idx, len, new_img_el, ref14;
            file._update_state();
            ref14 = file._divs;
            for (idx = i = 0, len = ref14.length; i < len; idx = ++i) {
              _div = ref14[idx];
              if (CUI.dom.isInDOM(_div)) {
                new_img_el = _this.getImgElementForValue(value, version, onUpdate, opts);
                ez5.eas.replaceImgElement(_div, new_img_el);
                file._divs[idx] = new_img_el;
              }
            }
          };
        })(this)).progress(function() {
          return file._update_state();
        }).fail((function(_this) {
          return function() {
            value.status = "failed";
            return file._update_state();
          };
        })(this));
      }
      img_el = ez5.eas.getFileUploadMeter(file);
      img_el.onUpdate = onUpdate;
      file._divs.push(img_el);
      file._update_state();
    } else {
      CUI.util.assert(false, "EASColumn.getImgElementForValue", "Unknown state for value", {
        value: value
      });
    }
    CUI.dom.addClass(img_el, "ez5-asset-element");
    if (cls = this.getClass()) {
      CUI.dom.addClass(img_el, cls);
    }
    return img_el;
  };

  EASColumn.prototype.isVisible = function(mode, opts) {
    if (!EASColumn.__super__.isVisible.call(this, mode, opts)) {
      return false;
    }
    switch (mode) {
      case "editor-template":
        if (this.mask.nestedTableField) {
          throw new NestedTableIsVisibleException;
        } else {
          return false;
        }
        break;
      case "editor-header-bulk":
      case "editor-bulk":
      case "editor-header":
      case "detail-header":
      case 'fulltext':
        return false;
      default:
        return true;
    }
  };

  EASColumn.prototype.sortExtraOpts = function(data) {
    var date_options, i, len, opts, sort_options, v;
    opts = [];
    sort_options = ["filesize", "class_extension", "extension", "original_filename"];
    if (ez5.version("6.12")) {
      date_options = ["best_date", "best_date:day", "best_date:week", "best_date:month", "best_date:year"];
      sort_options = sort_options.concat(date_options);
    }
    for (i = 0, len = sort_options.length; i < len; i++) {
      v = sort_options[i];
      opts.push({
        text: $$("eas.column.sort." + v),
        value: v
      });
    }
    return opts;
  };

  EASColumn.prototype.getSortFields = function(filter) {
    var f, ref;
    if (ez5.version("6.12") && ((ref = filter._extra) === "best_date:day" || ref === "best_date:month" || ref === "best_date:week" || ref === "best_date:year")) {
      f = {
        field: this.fullName() + ".best_date",
        group_field: this.fullName() + ".best_date",
        order: filter._order,
        width: filter._extra.split("best_date:")[1]
      };
      return f;
    }
    f = {
      field: this.fullName() + "." + filter._extra,
      group_field: this.fullName() + "." + filter._extra,
      order: filter._order
    };
    if (filter._extra === "filesize") {
      f.mode = "max";
      f.group_mode = "max";
    }
    return f;
  };

  EASColumn.prototype.isSortGroupable = function(filter) {
    var ref;
    return (ref = filter._extra) !== "original_filename" && ref !== "best_date";
  };

  EASColumn.prototype.formatSortGroupable = function(item, filter) {
    var bytes, bytes_before, i, kb, len, locale, locales, mb, ref, steps;
    if (filter._extra === "filesize") {
      kb = 1024;
      mb = kb * kb;
      steps = [10 * kb, 100 * kb, mb, 100 * mb, 500 * mb];
      for (i = 0, len = steps.length; i < len; i++) {
        bytes = steps[i];
        if (item < bytes) {
          if (bytes_before) {
            return ez5.format_filesize(bytes_before) + " - " + ez5.format_filesize(bytes);
          } else {
            return "< " + ez5.format_filesize(bytes);
          }
        }
        bytes_before = bytes;
      }
      return "> " + ez5.format_filesize(bytes_before);
    } else if (ez5.version("6.12") && ((ref = filter._extra) === "best_date:day" || ref === "best_date:week" || ref === "best_date:month" || ref === "best_date:year")) {
      locale = CUI.DateTime.getLocale();
      locales = ez5.session.getPref("database_languages") || [];
      if (CUI.util.isEmpty(locales)) {
        locales = ez5.session.getConfigDatabaseLanguages();
      }
      locale = locales[0] || locale;
      return CUI.DateTime.formatGroupLabel(item, filter._extra.split("best_date:")[1], locale);
    } else {
      return item;
    }
  };

  EASColumn.prototype.isSortUnique = function() {
    return true;
  };

  EASColumn.prototype.allowAppendMultipleRows = function() {
    return true;
  };

  EASColumn.prototype.getXMLFormWrapperFields = function() {
    return this.getExportOptions();
  };

  EASColumn.prototype.getXMLFormWrapperType = function() {
    return "text_eas_url";
  };

  EASColumn.prototype.getTokenizer = function() {
    if (!this.__tokenizer) {
      this.__tokenizer = new NumberTokenizer();
    }
    return this.__tokenizer;
  };

  EASColumn.prototype.getSearchField = function() {
    return this.fullName() + "._id";
  };

  return EASColumn;

})(DataColumn);

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

  function EASColumnSearchOriginalFilename(mask, FieldSchema, linkedEASColumnName) {
    this.mask = mask;
    this.FieldSchema = FieldSchema;
    this.linkedEASColumnName = linkedEASColumnName;
    EASColumnSearchOriginalFilename.__super__.constructor.call(this, this.mask, this.FieldSchema);
  }

  EASColumnSearchOriginalFilename.prototype.fullName = function() {
    if (this.linkedEASColumnName) {
      return (EASColumnSearchOriginalFilename.__super__.fullName.call(this)) + "." + this.linkedEASColumnName + ".original_filename";
    }
    return (EASColumnSearchOriginalFilename.__super__.fullName.call(this)) + ".original_filename";
  };

  EASColumnSearchOriginalFilename.prototype.getElementOpts = function() {
    return {
      type: CUI.Input,
      name: "original_filename"
    };
  };

  EASColumnSearchOriginalFilename.prototype.getTokenizer = function() {
    if (!this.__textTokenizer) {
      this.__textTokenizer = new Tokenizer();
    }
    return this.__textTokenizer;
  };

  EASColumnSearchOriginalFilename.prototype.getFieldOptsForSuggest = function() {
    var opts;
    opts = {
      tokens_dont_split_query: true
    };
    return opts;
  };

  return EASColumnSearchOriginalFilename;

})(EASColumn);
// Generated by CoffeeScript 1.12.7
var EASColumnLinkedObject,
  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;

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

  function EASColumnLinkedObject(mask, FieldSchema, __linkedObject) {
    this.mask = mask;
    this.FieldSchema = FieldSchema;
    this.__linkedObject = __linkedObject;
    CUI.util.assert(this.__linkedObject instanceof LinkedObject, 'new EASColumnLinkedObject', 'LinkedObject needs to be instance of LinkedObject.');
    EASColumnLinkedObject.__super__.constructor.call(this, this.mask, this.FieldSchema);
    this.__dbInfo = new DbInfo();
    this.__fieldEnabled = false;
  }

  EASColumnLinkedObject.prototype.getLinkedObject = function() {
    return this.__linkedObject;
  };

  EASColumnLinkedObject.prototype.fullNameLocalized = function() {
    return this.__linkedObject.fullNameLocalized() + ' / ' + EASColumnLinkedObject.__super__.fullNameLocalized.call(this, true, true);
  };

  EASColumnLinkedObject.prototype.nameForCollectionSave = function() {
    return this.__linkedObject.fullName(false) + '.' + this.fullName();
  };

  EASColumnLinkedObject.prototype.supportsSeries = function() {
    return this.__linkedObject.insideNested();
  };

  EASColumnLinkedObject.prototype.getDbInfo = function() {
    return this.__dbInfo;
  };

  EASColumnLinkedObject.prototype.isEASFieldEnabled = function() {
    return this.__fieldEnabled;
  };

  EASColumnLinkedObject.prototype.getEASFieldOption = function(callback) {
    var deferred;
    if (callback == null) {
      callback = function() {};
    }
    deferred = new CUI.Deferred();
    this.loadDbInfo().done((function(_this) {
      return function() {
        var option;
        _this.__fieldEnabled = true;
        option = {
          value: _this,
          text: _this.fullNameLocalized()
        };
        return deferred.resolve(option);
      };
    })(this)).fail(deferred.reject);
    return deferred.promise();
  };

  EASColumnLinkedObject.prototype.loadDbInfo = function() {
    var link_mask;
    if (this.__dbInfoLoadPromise) {
      return this.__dbInfoLoadPromise;
    }
    link_mask = this.__linkedObject.linkMask();
    this.__dbInfoLoadPromise = this.__dbInfo.load({
      ignore_not_found: true,
      table: link_mask.table,
      pool_id: null,
      tag_ids: null
    });
    return this.__dbInfoLoadPromise;
  };

  return EASColumnLinkedObject;

})(EASColumn);
// Generated by CoffeeScript 1.12.7
var EASField,
  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;

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

  function EASField(opts1) {
    this.opts = opts1 != null ? opts1 : {};
  }

  EASField.prototype.name = function() {
    return this.opts.name;
  };

  EASField.prototype.hasMetadataSelector = function() {
    return false;
  };

  EASField.prototype.hasAssetBrowser = function() {
    return false;
  };

  EASField.prototype.hasManageVersions = function() {
    return false;
  };

  EASField.prototype.hasButtonShareUrl = function() {
    return false;
  };

  EASField.prototype.forceButtonDownloadOriginal = function() {
    return true;
  };

  EASField.prototype.hasInstantRotate = function() {
    return false;
  };

  EASField.prototype.scaleAndPosition = function() {
    return this.opts.scale_and_position;
  };

  EASField.prototype.getClass = function() {
    return this.opts["class"];
  };

  EASField.prototype.fullNameLocalized = false;

  EASField.prototype.getUploadUrl = function() {
    var opts;
    opts = {
      check_for_duplicates: void 0
    };
    if (ez5.version("6")) {
      opts.produce_versions = "[true]";
    } else {
      opts.skip_extension_check = 1;
    }
    return ez5.eas.getUploadUrl(opts);
  };

  EASField.prototype.renderEditorInput = function(data, default_pic) {
    var div, fd, fdata, save_data;
    CUI.util.assert(CUI.util.isPlainObject(data), "EASField.renderEditorInput", "data needs to be plain object", {
      data: data
    });
    if (!data[this.name()]) {
      data[this.name()] = {};
    }
    fdata = {};
    fd = data[this.name()];
    if (fd._id) {
      fdata[this.name()] = [
        {
          _id: fd._id,
          frontend_prefs: fd.frontend_prefs,
          preferred: true
        }
      ];
    }
    fdata._eas_field_data = data;
    div = EASField.__super__.renderEditorInput.call(this, fdata, null, {
      default_pic_name: default_pic
    });
    CUI.dom.addClass(div, "ez5-event-poller");
    save_data = JSON.stringify(data[this.name()]);
    CUI.Events.listen({
      type: "editor-changed",
      call: (function(_this) {
        return function() {
          if (JSON.stringify(data[_this.name()]) !== save_data) {
            save_data = JSON.stringify(data[_this.name()]);
            return CUI.Events.trigger({
              type: "data-changed",
              node: div
            });
          }
        };
      })(this)
    });
    return div;
  };

  EASField.prototype.updateData = function(data) {
    var i, len, list, value;
    list = this.getSaveData(data);
    data._eas_field_data[this.name()] = null;
    for (i = 0, len = list.length; i < len; i++) {
      value = list[i];
      if (value.preferred) {
        data._eas_field_data[this.name()] = value;
        break;
      }
    }
  };

  EASField.prototype.fullName = function() {
    var ref;
    return (ref = this._originField) != null ? ref.fullName() : void 0;
  };

  return EASField;

})(EASColumn);
// Generated by CoffeeScript 1.12.7
var LinkColumn,
  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;

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

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

  return LinkColumn;

})(NumberColumn);
// Generated by CoffeeScript 1.12.7
var LinkedObject,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function LinkedObject(mask, FieldSchema) {
    this.mask = mask;
    this.FieldSchema = FieldSchema;
    LinkedObject.__super__.constructor.call(this, this.mask, this.FieldSchema);
    if (!this.FieldSchema) {
      CUI.util.assert(false, "new LinkedObject", "LinkedObject(mask, FieldSchema) needs to be called with FieldSchema.");
    }
  }

  LinkedObject.prototype.mergeData = function(top_level_data, top_level_data_new, replace, is_restore) {
    var data_new, fdata_new;
    if (replace == null) {
      replace = false;
    }
    if (is_restore == null) {
      is_restore = false;
    }
    if (ez5.version("6") && is_restore) {
      data_new = top_level_data_new[top_level_data_new._objecttype];
      fdata_new = this.getDataForFieldData(data_new, top_level_data_new);
      if (!CUI.util.isEmpty(fdata_new[this.name()]) && ResultObject.dataFromDeletedOrPurgedObject(fdata_new[this.name()])) {
        return;
      }
    }
    return LinkedObject.__super__.mergeData.call(this, top_level_data, top_level_data_new, replace, is_restore);
  };

  LinkedObject.prototype.linkMask = function() {
    var mask_id, mask_name, ref, ref1;
    mask_id = this.__getLinkMaskId();
    if (mask_id === "PREFERRED") {
      mask_name = (ref = ez5.schema[this.mask.version]._table_by_id[this.__getLinkMaskTableId()]._preferred_mask) != null ? ref.name : void 0;
    } else if (mask_id === "ALL_FIELDS") {
      mask_name = '_all_fields';
    } else {
      mask_name = (ref1 = ez5.mask[this.mask.version]._mask_by_id[mask_id]) != null ? ref1.name : void 0;
    }
    CUI.util.assert(mask_name, "LinkedObject.linkMask()", "Mask for LinkedObject not found.", {
      mask_id: mask_id,
      linkedObject: this
    });
    return Mask.getMaskByMaskName(mask_name, this.__getLinkMaskTableId(), this.mask.version);
  };

  LinkedObject.prototype.getMappingSourceFullNameLocalized = function(useTableName) {
    var mappingSourceFullNameLocalized;
    mappingSourceFullNameLocalized = LinkedObject.__super__.getMappingSourceFullNameLocalized.call(this, useTableName);
    return mappingSourceFullNameLocalized + " [" + $$("linked.object.mapping_source_name") + "]";
  };

  LinkedObject.prototype.hasMappingChildFields = function() {
    return true;
  };

  LinkedObject.prototype.getMappingChildFields = function(mode) {
    var f, fields, i, len, ref;
    fields = [];
    ref = this.linkMask().getFields(mode);
    for (i = 0, len = ref.length; i < len; i++) {
      f = ref[i];
      if ((f instanceof TreeColumn && mode !== "export") || f instanceof ReverseLinkedTable || f instanceof MaskSplitter) {
        continue;
      }
      fields.push(f);
    }
    return fields;
  };

  LinkedObject.prototype.__getLinkMaskId = function() {
    return this.FieldSchema.mask_id;
  };

  LinkedObject.prototype.__getLinkMaskTableId = function() {
    return this.FieldSchema.other_table_id;
  };

  LinkedObject.prototype.__getLinkMaskInline = function() {
    return this.FieldSchema.inline;
  };

  LinkedObject.prototype.__getMaskCustomSetting = function(name, defaultValue) {
    var ref, value;
    value = (ref = this.FieldSchema.custom_settings) != null ? ref[name] : void 0;
    if (CUI.util.isUndef(value) && !CUI.util.isUndef(defaultValue)) {
      return defaultValue;
    }
    return value;
  };

  LinkedObject.prototype.maskName = function() {
    return this.mask.name();
  };

  LinkedObject.prototype.maskNameLocalized = function() {
    return this.mask.nameLocalized();
  };

  LinkedObject.prototype.getCSVDestinationFields = function(csvImporter) {
    var opts;
    opts = {
      csvImporter: csvImporter,
      field: this
    };
    return [new LinkedObjectCSVImporterDestinationField(opts)];
  };

  LinkedObject.prototype.supportsFacet = function() {
    return true;
  };

  LinkedObject.prototype.getFacet = function(opts) {
    opts.field = this;
    return new LinkedObjectFieldFacet(opts);
  };

  LinkedObject.prototype.getReplacementRecord = function(data, key_prefix, use_array, record) {
    var _data;
    if (use_array == null) {
      use_array = false;
    }
    _data = data[this.name()];
    if (!_data) {
      return;
    }
    this.linkMask().getReplacementRecord(_data, key_prefix + this.name() + ".", use_array, record);
    return record;
  };

  LinkedObject.prototype.renderStandard = function(standard, data) {
    var os;
    if (this.isEmpty(data)) {
      return;
    }
    os = this.getOutputStandard();
    if (os) {
      standard.push({
        field: this,
        value: (new ResultObject()).setData(data[this.name()]).renderText(),
        render_info: os
      });
    }
    os = this.getOutputStandardEAS();
    if (os) {
      data[this.name()]._standard = (new ResultObject()).setData(data[this.name()]).getStandard();
      standard.push({
        field: this,
        data: data,
        render_info: os,
        eas: true
      });
    }
  };

  LinkedObject.prototype.getQueryFieldBadge = function(data, multi_field) {
    var co, col_objs, dfr, gid, i, len, linked_objs, ref, resolve;
    dfr = new CUI.Deferred();
    resolve = (function(_this) {
      return function(value) {
        var badge, ref;
        badge = {
          value: value,
          popoverContent: CUI.util.dump(_this.getSearchFilter(data))
        };
        if (multi_field) {
          if (multi_field._ot_name === "_COMMONS") {
            badge.name = multi_field.nameLocalized();
          } else {
            badge.name = multi_field.nameLocalized();
          }
        } else {
          badge.name = _this.nameLocalized();
        }
        if ((ref = data[_this.name()]) != null ? ref.isSubsearch : void 0) {
          badge.value = $$("linked.object.badge.subsearch");
        }
        return dfr.resolve(badge);
      };
    })(this);
    if (data[(this.name()) + ":unset"]) {
      resolve($$("linked.object.badge.without"));
    } else if (data[(this.name()) + ":has_value"]) {
      resolve($$("field.search.badge.has_value"));
    } else {
      linked_objs = data[this.name()];
      if (!linked_objs) {
        resolve();
      } else {
        co = new CollectionMemory();
        col_objs = [];
        for (i = 0, len = linked_objs.length; i < len; i++) {
          gid = linked_objs[i];
          if (!gid) {
            continue;
          }
          if ((ref = data.__result_object) != null ? ref[gid] : void 0) {
            col_objs.push(data.__result_object[gid].getCollectionObject());
          } else {
            col_objs.push(new CollectionObject({
              _global_object_id: gid
            }));
          }
        }
        co.insertObjects(col_objs).done((function(_this) {
          return function() {
            return co.getBadgeText().done(resolve);
          };
        })(this));
      }
    }
    return dfr.promise();
  };

  LinkedObject.prototype.renderSearchInput = function(data, top_level_data) {
    var collection, collectionPromise, gid, node, searchMiniOpts, trigger_change;
    collection = new CollectionMemory();
    if (top_level_data.bulk_expert) {
      collection.setSingleMode(true);
    } else {
      collection.setSingleMode(false);
    }
    if (data[this.name()] && data[this.name()].length > 0) {
      collectionPromise = collection.insertObjects((function() {
        var i, len, ref, results;
        ref = data[this.name()];
        results = [];
        for (i = 0, len = ref.length; i < len; i++) {
          gid = ref[i];
          results.push(new CollectionObject({
            _global_object_id: "" + gid
          }));
        }
        return results;
      }).call(this));
    } else {
      if (data[this.name()] && data[this.name()].isSubsearch) {
        collection.addSubsearchData(data[this.name()]);
      }
      collectionPromise = CUI.resolvedPromise();
    }
    searchMiniOpts = {
      placeholder_text: this.getPlaceholderTextForEditor(data, top_level_data),
      searchPopoverOpts: {
        searchInputOpts: {
          scope: ["fulltext", "token", "tokens"]
        },
        allowSubsearch: ez5.version("6")
      }
    };
    node = this.__renderInput({
      mode: "search",
      collection: collection,
      collectionPromise: collectionPromise,
      searchMini: searchMiniOpts,
      onUpdate: (function(_this) {
        return function(_opts) {
          var _co, linked_ids, obj;
          if (!CUI.util.isEmpty(collection.getSubsearchData())) {
            data[_this.name()] = collection.getSubsearchData();
            data[_this.name()].isSubsearch = true;
            if (node) {
              trigger_change();
            }
            return;
          }
          linked_ids = (function() {
            var i, len, ref, results;
            ref = collection.getObjects();
            results = [];
            for (i = 0, len = ref.length; i < len; i++) {
              _co = ref[i];
              results.push(_co.getGlobalObjectId());
            }
            return results;
          })();
          if (linked_ids.length > 0) {
            if (top_level_data.bulk_expert) {
              obj = collection.getObjects()[0].getObject();
              data[_this.name()] = {
                _global_object_id: obj._global_object_id,
                _objecttype: obj._objecttype,
                _mask: obj._mask
              };
              data[_this.name()][obj._objecttype] = {
                _id: obj[obj._objecttype]._id
              };
              return;
            }
            data[_this.name()] = linked_ids;
          } else {
            data[_this.name()] = null;
          }
          if (node) {
            return trigger_change();
          }
        };
      })(this)
    });
    trigger_change = (function(_this) {
      return function() {
        return CUI.Events.trigger({
          node: node,
          type: "search-input-change"
        });
      };
    })(this);
    if (this.linkMask().table.isHierarchy() || this.linkMask().table.isPolyhierarchy()) {
      return new CUI.HorizontalLayout({
        maximize_horizontal: true,
        maximize_vertical: false,
        "class": "ez5-linked-object-search-hierarchy",
        center: {
          content: node
        },
        right: {
          content: (new CUI.Checkbox({
            data: data,
            active: true,
            hidden: (top_level_data != null ? top_level_data.bulk_expert : void 0) ? true : false,
            name: this.name() + ":include_children",
            tooltip: {
              text: $$("linked.object.include_children.tooltip")
            },
            onDataChanged: (function(_this) {
              return function() {
                return trigger_change();
              };
            })(this)
          })).start()
        }
      }).DOM;
    } else {
      CUI.dom.addClass(node, "ez5-linked-object-search");
      return node;
    }
  };

  LinkedObject.prototype.addToCollection = function(data, top_level_data, collection) {
    return this.__addToCollection(data[this.name()], collection);
  };

  LinkedObject.prototype.__addToCollection = function(data, collection) {
    if (!data._mask) {
      data._mask = this.linkMask().name();
      data._objecttype = this.linkMask().table.name();
    }
    if (data._mask !== this.linkMask().name()) {
      CUI.util.assert(data._objecttype === this.linkMask().table.name(), (CUI.util.getObjectClass(this)) + ".renderEditorInput", "Objecttype in data does not match objecttype of schema.", {
        data: data,
        schema: this.linkMask().schema
      });
      delete data._format;
      data._mask = this.linkMask().name();
    }
    return collection.insertObjects([new CollectionObject(data)]);
  };

  LinkedObject.prototype.setData = function(data, top_level_data, linked_object_data) {
    return data[this.name()] = linked_object_data;
  };

  LinkedObject.prototype.getDataAsString = function(data) {
    var sd;
    sd = this.getSaveData(data);
    if (!sd) {
      return;
    }
    delete sd._mask;
    delete sd._objecttype;
    return JSON.stringify(sd);
  };

  LinkedObject.prototype.hasEditorToolsButton = function(opts) {
    return true;
  };

  LinkedObject.prototype.__renderInput = function(_opts) {
    var btn, filterLabel, filterSelect, filters, getSearchFilters, globalObjectIdsInSearch, lay, name, node, open_editor, opts, popoverShown, searchMini, selectData, selectLayout, selectOptions, show_collection, sopts, tmpl;
    opts = CUI.Element.readOpts(_opts, "LinkedObject.__renderInput", {
      path: {
        "default": true
      },
      mode: {
        check: ["editor", "search"]
      },
      collection: {
        mandatory: true,
        check: Collection
      },
      collectionPromise: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isPromise(v);
        }
      },
      allowMultipleRows: {
        check: Boolean
      },
      data: {
        check: "PlainObject"
      },
      searchMini: {
        "default": {},
        check: "PlainObject"
      },
      onUpdate: {
        check: Function
      }
    });
    opts.searchMini.input_opts = {
      id: this.idAttribute(opts.data)
    };
    sopts = CUI.util.copyObject(opts.searchMini);
    if (ez5.version("6")) {
      sopts.placeholder_text = this.getCustomPlaceholder();
    }
    show_collection = (function(_this) {
      return function() {
        var append_to_div, div, i, len, obj, objs, promises, tagholder;
        objs = opts.collection.getObjects();
        if (objs.length > 0 || opts.collection.hasSubsearchData()) {
          if (typeof btn !== "undefined" && btn !== null) {
            btn.show();
          }
          CUI.dom.hideElement(tmpl.map.search);
          CUI.dom.showElement(tmpl.map.object);
          lay.DOM.setAttribute("tabindex", "0");
          CUI.dom.removeClass(lay, "ez5-linked-object-search-active");
        } else {
          if (typeof btn !== "undefined" && btn !== null) {
            btn.hide();
          }
          CUI.dom.hideElement(tmpl.map.object);
          CUI.dom.showElement(tmpl.map.search);
          lay.DOM.removeAttribute("tabindex");
          CUI.dom.addClass(lay, "ez5-linked-object-search-active");
        }
        tmpl.empty("object");
        promises = [];
        if (typeof btn !== "undefined" && btn !== null) {
          btn.disable();
        }
        if (opts.collection.hasSubsearchData()) {
          div = CUI.dom.div("ez5-linked-object-container");
          tagholder = CUI.dom.div("ez5-tag-holder");
          tagholder.appendChild(new CUI.Label({
            "class": "ez5-tag",
            text: $$("linked.object.badge.subsearch")
          }).DOM);
          div.appendChild(tagholder);
          tmpl.append(div, "object");
        }
        for (i = 0, len = objs.length; i < len; i++) {
          obj = objs[i];
          div = CUI.dom.div("ez5-linked-object-container");
          tmpl.append(div, "object");
          append_to_div = function(div, mode) {
            var dfr;
            dfr = _this.__loadFromData(obj.getObject(), mode);
            promises.push(dfr);
            return dfr.done(function(ro) {
              var _div, ref, showHierarchyPath, showObjecttype, showPool, showSystemObjectId, showTags;
              showTags = _this.__getMaskCustomSetting("show_tags_inline", false);
              if (showTags) {
                showTags = ((ref = _this.linkMask().schema.system_fields) != null ? ref.tags.output.mode : void 0) !== "off";
              }
              showPool = _this.__getMaskCustomSetting("show_pool_inline", false);
              showObjecttype = _this.__getMaskCustomSetting("show_objecttype_inline", false);
              showSystemObjectId = _this.__getMaskCustomSetting("show_system_object_id_inline", false);
              showHierarchyPath = _this.__getMaskCustomSetting("show_hierarchy_path_inline", false);
              _div = (function() {
                switch (mode) {
                  case "short":
                    return ro.renderCardLinkedObjectShort({
                      path: opts.path
                    });
                  case "text":
                    return ro.renderTextDetail({
                      hide_tags: !showTags,
                      hide_hierarchy_path: !showHierarchyPath,
                      hide_objecttype: !showObjecttype,
                      hide_system_object_id: !showSystemObjectId,
                      hide_pool: !showPool,
                      path: opts.path,
                      mode: mode,
                      sourceType: "link"
                    });
                  default:
                    return ro.renderCardLinkedObjectStandard({
                      tags: showTags,
                      path: opts.path
                    });
                }
              })();
              CUI.dom.setAttribute(_div, "ui", "linked.object.field:" + (ro.objecttype()) + "_" + (ro.getId()));
              CUI.dom.append(div, _div);
              CUI.dom.append(div, _this.__getMaskNotMatchWarning(ro, obj.getObject()));
              if (ro.isMappedMetadataCreated()) {
                CUI.dom.addClass(_div, "ez5-linked-object-mapped-metadata-created");
                new CUI.Tooltip({
                  element: _div,
                  text: $$("linked.object.mapped_metadata_created.tooltip")
                });
              }
            }).fail(function(error) {
              var lbl;
              if (error instanceof UserError) {
                lbl = new CUI.Label({
                  multiline: true,
                  text: error.getError(),
                  "class": "ez5-linked-object-warning cui-label-warning"
                });
                CUI.dom.append(div, lbl);
              }
            });
          };
          append_to_div(div, _this.__getLinkMaskInline(opts));
        }
        CUI.when(promises).done(function() {
          CUI.Events.trigger({
            node: tmpl,
            type: "content-resize"
          });
          return typeof btn !== "undefined" && btn !== null ? btn.enable() : void 0;
        });
      };
    })(this);
    open_editor = (function(_this) {
      return function() {
        var co, ed, ol, params, ro;
        co = opts.collection.getObjects()[0];
        params = {
          table_id: _this.linkMask().table.id(),
          format: 'long',
          onCancel: function() {
            return typeof ed !== "undefined" && ed !== null ? ed.destroy() : void 0;
          },
          onDelete: function() {
            opts.collection.removeObjects();
            return typeof ed !== "undefined" && ed !== null ? ed.destroy() : void 0;
          },
          onSaveReadOnly: function(editor, new_objs) {
            co.setObject(new_objs[0]);
            sopts.onUpdate();
            return typeof ed !== "undefined" && ed !== null ? ed.destroy() : void 0;
          },
          onSave: function(editor, new_objs) {
            co.setObject(new_objs[0]);
            sopts.onUpdate();
            return typeof ed !== "undefined" && ed !== null ? ed.destroy() : void 0;
          },
          popover_element: lay.center()
        };
        if (co.getGlobalObjectId()) {
          params.mode = "single";
          params.global_object_id = co.getGlobalObjectId();
        } else {
          params.mode = "new";
          ro = new ResultObject();
          ro.setData(co.getObject());
          ol = new ObjectList();
          ol.push(ro);
          params.object_list = ol;
        }
        ed = new EditorPopover(params);
        return ed.open();
      };
    })(this);
    tmpl = new CUI.Template({
      name: "linked-object-edit",
      map: {
        search: true,
        object: true
      }
    });
    lay = new CUI.HorizontalLayout({
      maximize_horizontal: true,
      maximize_vertical: false,
      "class": "ez5-linked-object-edit",
      right: {},
      center: {
        content: tmpl
      }
    });
    if (this.hasEditorToolsButton(opts)) {
      btn = new LocaButton({
        loca_key: "linked.object.button.menu",
        ui: "linked.object.menu.button",
        disabled: true,
        icon: "ellipsis_v",
        icon_right: false,
        menu: {
          items: (function(_this) {
            return function() {
              var appendOnlyMode, co, editBtn, fn1, i, idx, items, len, ref, ref1, ref2;
              if (opts.mode === "editor") {
                if (opts.allowMultipleRows && opts.data._new) {
                  opts.collection.setSingleMode(false);
                } else {
                  opts.collection.setSingleMode(true);
                }
              }
              items = [
                {
                  icon: "search",
                  loca_key: "linked.object.search",
                  ui: "linked.object.menu.search_button",
                  onClick: function() {
                    return searchMini.openSearch(btn);
                  }
                }, opts.mode === "editor" ? editBtn = new LocaButton({
                  icon: "edit",
                  disabled: true,
                  loca_key: "linked.object.editor",
                  ui: "linked.object.menu.edit_button",
                  group: "tools",
                  onClick: function() {
                    return open_editor();
                  }
                }) : void 0
              ];
              ref = opts.collection.getObjects();
              fn1 = function(co) {
                if (co.getGlobalObjectId() === "0") {
                  return;
                }
                return items.push({
                  loca_key: "linked.object.detail",
                  loca_key_attrs: {
                    number: idx + 1
                  },
                  ui: "linked.object.menu.detail_button",
                  group: "tools",
                  onClick: function() {
                    return ResultObject.showCollectionObjectInPopover({
                      collectionObject: co,
                      element: lay
                    });
                  }
                });
              };
              for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
                co = ref[idx];
                fn1(co);
              }
              appendOnlyMode = !!((ref1 = _this.mask) != null ? (ref2 = ref1.nestedTableField) != null ? ref2.isAppendOnly() : void 0 : void 0);
              if (!appendOnlyMode) {
                items.push({
                  icon: "fa-chain-broken",
                  group: "tools",
                  loca_key: "linked.object.trash",
                  ui: "linked.object.menu.delete_button",
                  onClick: function() {
                    return opts.collection.removeObjects().done((function(_this) {
                      return function() {
                        return sopts.onUpdate();
                      };
                    })(this));
                  }
                });
              }
              if (editBtn) {
                co = opts.collection.getObjects()[0];
                if (co.isMappedMetadataCreated()) {
                  editBtn.enable();
                } else {
                  DbInfo.canWrite({
                    object: co.getObject()
                  }).done(function() {
                    return editBtn.enable();
                  });
                }
              }
              return items;
            };
          })(this)
        }
      });
    }
    sopts.element = tmpl.map.search;
    sopts.popover_element = tmpl.DOM;
    sopts.link_mask = this.linkMask();
    sopts.link_mask_inline = this.__getLinkMaskInline(opts);
    sopts.collection = opts.collection;
    sopts.preventOntheflySuggestion = this.__getMaskCustomSetting("prevent_onthefly_create", false);
    sopts.onUpdate = (function(_this) {
      return function(_opts) {
        var co, i, idx, len, ref;
        if (_opts == null) {
          _opts = {};
        }
        ref = opts.collection.getObjects();
        for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
          co = ref[idx];
          CUI.Events.trigger({
            type: "linked-object-data-changed",
            info: {
              linked_object_collection_object: co,
              origin_node: lay.DOM
            }
          });
          if (co.getObject()._mask !== _this.linkMask().name()) {
            if (!co.getObject()._new_object) {
              co.getObject()._format_incomplete = true;
            }
            co.getObject()._mask = _this.linkMask().name();
          }
        }
        if (typeof opts.onUpdate === "function") {
          opts.onUpdate(_opts, searchMini);
        }
        return show_collection();
      };
    })(this);
    searchMini = null;
    if (opts.mode === "editor" || opts.mode === "search") {
      filters = this.__getFilters();
      if (!CUI.util.isEmpty(filters)) {
        selectOptions = [
          {
            text: $$("linked.objecttype.editor.filters.option.empty"),
            value: null,
            disabled: true
          }
        ];
        selectData = {
          filterName: Object.keys(filters)[0]
        };
        for (name in filters) {
          selectOptions.push({
            value: name
          });
        }
        filterSelect = new CUI.Select({
          name: "filterName",
          data: selectData,
          options: selectOptions,
          ui: "linked.object.filter_name.select",
          onDataChanged: function() {
            var searchPopover;
            searchMini.getAutocompletion().hide();
            searchPopover = searchMini.getSearchPopover();
            if (searchPopover != null ? searchPopover.getSearchInput() : void 0) {
              searchPopover.emptyCollection();
              searchPopover.execute();
            }
          }
        });
        filterSelect.start();
        filterLabel = new CUI.Label({
          text: $$("linked.objecttype.editor.filters.title"),
          appearance: "secondary"
        });
        selectLayout = new CUI.HorizontalLayout({
          center: {
            content: filterLabel
          },
          right: {
            content: filterSelect
          }
        });
        getSearchFilters = function() {
          var _searchFilters;
          if (!selectData.filterName) {
            return;
          }
          _searchFilters = [].concat(filters[selectData.filterName].filters);
          if (popoverShown) {
            return _searchFilters;
          }
          if (filters[selectData.filterName].config.only_allow_select_last_children) {
            _searchFilters.push({
              type: "in",
              "in": [false],
              bool: "must",
              fields: ["_has_children"]
            });
          }
          return _searchFilters;
        };
        sopts.searchManagers = [
          new LinkedObjectFiltersSearchManager({
            getSearchFilters: getSearchFilters
          })
        ];
        sopts.onAddToRequest = function(request) {
          if (!request.search) {
            request.search = [];
          }
        };
        globalObjectIdsInSearch = new Set();
        sopts.onRequestDone = function(data) {
          var i, len, object, ref;
          ref = data.objects;
          for (i = 0, len = ref.length; i < len; i++) {
            object = ref[i];
            globalObjectIdsInSearch.add(object._global_object_id);
          }
        };
        popoverShown = false;
        sopts.isSelectable = function(object) {
          var ref;
          if (selectData.filterName && (searchMini != null ? (ref = searchMini.popover_search) != null ? ref.getLastData() : void 0 : void 0)) {
            if (!globalObjectIdsInSearch.has(object._global_object_id)) {
              return false;
            }
          }
          if (opts.mode === "search") {
            return true;
          }
          if (!selectData.filterName || !filters[selectData.filterName].config.only_allow_select_last_children) {
            return true;
          }
          return !object._has_children;
        };
        sopts.searchPopoverOpts.onShow = function() {
          var searchPopover;
          popoverShown = true;
          searchPopover = searchMini.getSearchPopover();
          searchPopover.getButtonToolbar().append(filterLabel, "left");
          searchPopover.getButtonToolbar().append(filterSelect, "left");
        };
        sopts.searchPopoverOpts.onHide = function() {
          popoverShown = false;
          selectLayout.append(filterLabel, "center");
          selectLayout.append(filterSelect, "right");
        };
      }
    }
    opts.collectionPromise.done((function(_this) {
      return function() {
        var autocompletion;
        searchMini = new SearchMini(sopts);
        if (selectOptions) {
          if (ez5.session.hasSystemRight("root", "frontend_features[enable_ignore_linked_objects_filter]")) {
            filterSelect.enableOption(null);
          }
          autocompletion = searchMini.getAutocompletion();
          autocompletion.addContainerBefore("filters", "all");
          autocompletion.getContainer("filters").append(selectLayout);
        }
        return show_collection();
      };
    })(this));
    if (btn) {
      lay.append(btn, "right");
    }
    CUI.Events.listen({
      type: "keyup",
      node: lay,
      call: function(ev) {
        var el, ref;
        if (ev.hasModifierKey()) {
          return;
        }
        if ((ref = ev.keyCode()) === 8 || ref === 46) {
          ev.stopPropagation();
          el = CUI.dom.findNextVisibleElement(lay.DOM, "[tabindex]");
          opts.collection.removeObjects().done((function(_this) {
            return function() {
              sopts.onUpdate();
              return CUI.setTimeout(function() {
                return el.focus();
              });
            };
          })(this));
        }
      }
    });
    node = lay.DOM;
    CUI.Events.listen({
      node: node,
      type: "linked-object-data-changed",
      call: (function(_this) {
        return function(ev, info) {
          var i, len, obj, objecttype, ref;
          if (info.origin_node === node) {
            return;
          }
          objecttype = _this.linkMask().table.name();
          ref = opts.collection.getObjects();
          for (i = 0, len = ref.length; i < len; i++) {
            obj = ref[i];
            if (info.linked_object_collection_object.getGlobalObjectId() === obj.getGlobalObjectId()) {
              if (info.linked_object_collection_object.getVersion() !== obj.getVersion()) {
                obj.__object = info.linked_object_collection_object.__object;
                show_collection();
              }
              return;
            }
          }
        };
      })(this)
    });
    return node;
  };

  LinkedObject.prototype.getPlaceholderTextForEditor = function(data, top_level_data) {
    var ref;
    if ((ref = data._template) != null ? ref[this.name()] : void 0) {
      return new ResultObject().setData(data._template[this.name()]).renderText();
    } else {
      return null;
    }
  };

  LinkedObject.prototype.renderEditorInput = function(data, top_level_data, opts) {
    var collection, collectionPromise, node, searchMiniOpts;
    if (opts == null) {
      opts = {};
    }
    CUI.util.assert(this.linkMask() instanceof Mask, (CUI.util.getObjectClass(this)) + ".renderEditorInput", "LinkMask not found", {
      data: data
    });
    if (this.__isUseSelectActivated()) {
      return this.__getObjectsSelect(data, opts);
    }
    collection = this.getCollectionMemory(data, top_level_data);
    if (opts.appendMultipleRows) {
      collection.setSingleMode(false);
    } else {
      collection.setSingleMode(true);
    }
    if (!CUI.util.isEmpty(data[this.name()])) {
      collectionPromise = this.addToCollection(data, top_level_data, collection);
    } else {
      collectionPromise = CUI.resolvedPromise();
    }
    searchMiniOpts = {
      placeholder_text: this.getPlaceholderTextForEditor(data, top_level_data),
      searchPopoverOpts: {
        searchInputOpts: {
          scope: ["fulltext", "token", "tokens"]
        },
        allowTopLevelPlaceholder: this.mask.isPolyhierarchy()
      }
    };
    node = this.__renderInput({
      collection: collection,
      collectionPromise: collectionPromise,
      mode: "editor",
      allowMultipleRows: !!opts.appendMultipleRows,
      data: data,
      searchMini: searchMiniOpts,
      path: this.__showPathInEditor(opts),
      onUpdate: (function(_this) {
        return function(_opts, searchMini) {
          var rootData;
          switch (collection.getCount()) {
            case 0:
              _this.setData(data, top_level_data, null);
              if (node) {
                CUI.Events.trigger({
                  node: node,
                  type: "editor-changed"
                });
              }
              break;
            case 1:
              if (collection.getObjects()[0].getObject()._global_object_id === "0") {
                rootData = collection.getObjects()[0].getObject();
                if (!rootData._objecttype) {
                  rootData = ParentRootResultObject.getSaveDataFromMask(_this.mask);
                }
                _this.setData(data, top_level_data, rootData);
                if (node) {
                  CUI.Events.trigger({
                    node: node,
                    type: "editor-changed"
                  });
                }
                return;
              }
              ResultObject.loadFromData(collection.getObjects()[0].getObject(), "standard", false).done(function(result_object) {
                _this.setData(data, top_level_data, result_object.getData());
                if (node) {
                  return CUI.Events.trigger({
                    node: node,
                    type: "editor-changed"
                  });
                }
              });
              break;
            default:
              CUI.util.assert(opts.appendMultipleRows, "LinkedObject.renderEditorInput", "collection contains more than 1 object and opts.appendMultipleRows is not set.", {
                opts: opts,
                linkedObject: _this
              });
              _this.__addFromCollection(opts.appendMultipleRows, collection);
              collection.removeObjects();
              searchMini.update({
                callback: false
              });
          }
          if (!_opts.init && collection.getCount() > 0) {
            return CUI.setTimeout(function() {
              return Field.focusNextField(node);
            });
          }
        };
      })(this)
    });
    return node;
  };

  LinkedObject.prototype.formatSortGroupable = function(item, filter, idx, resdata, object) {
    var i, idxS, j, len, len1, obj, objID, objSort, os, os2, ref, regKey, sortKey, sorter, sorter2;
    if (idx > 0) {
      return;
    }
    regKey = filter._key;
    sortKey = filter._key + ":sort";
    objSort = object._fields[sortKey];
    if (objSort.length !== object._fields[regKey].length) {
      console.warn("LinkedObject :: FormatSortGroupable -> API response is wrong for attribute '_fields', different length.", object._fields);
    }
    sorter = [];
    for (idxS = i = 0, len = objSort.length; i < len; idxS = ++i) {
      os = objSort[idxS];
      if (CUI.util.isArray(os)) {
        if (os.length === 0) {
          sorter.push({
            item: "",
            idx: idxS
          });
        } else if (CUI.util.isArray(os[0])) {
          sorter2 = [];
          for (j = 0, len1 = os.length; j < len1; j++) {
            os2 = os[j];
            sorter2.push(os2.join(" > "));
          }
          sorter2.sort(function(a, b) {
            if (filter._order === "ASC") {
              return a.localeCompare(b);
            } else {
              return b.localeCompare(a);
            }
          });
          sorter.push({
            item: sorter2[0],
            idx: idxS
          });
        } else {
          sorter.push({
            item: os.join(" > "),
            idx: idxS
          });
        }
      } else {
        sorter.push({
          item: os,
          idx: idxS
        });
      }
    }
    sorter.sort(function(a, b) {
      var data_lang, ref;
      data_lang = ((ref = ez5.session.getConfigDatabaseLanguages()) != null ? ref[0] : void 0) || null;
      if (filter._order === "ASC") {
        return a.item.localeCompare(b.item, data_lang);
      } else {
        return b.item.localeCompare(a.item, data_lang);
      }
    });
    obj = object._fields[regKey];
    idx = ((ref = sorter[0]) != null ? ref.idx : void 0) || 0;
    objID = obj[idx];
    if (CUI.util.isArray(objID)) {
      objID = objID[objID.length - 1];
      if (CUI.util.isArray(objID)) {
        return objID[objID.length - 1];
      } else {
        return objID;
      }
    } else {
      return objID;
    }
  };

  LinkedObject.prototype.getSortFunctions = function(opts) {
    var field, i, len, nestedSortField, ref, ref1, sortFunctions;
    if (opts == null) {
      opts = {};
    }
    sortFunctions = [];
    ref = opts.nested_sort_fields;
    for (i = 0, len = ref.length; i < len; i++) {
      nestedSortField = ref[i];
      if ((ref1 = nestedSortField.sort_field) === ((this.name()) + "-standard") || ref1 === "standard") {
        sortFunctions.push({
          nested_sort_field: nestedSortField,
          func: (function(_this) {
            return function(a, b) {
              var a_txt, b_txt, ref2, ref3, ref4, ref5, ref6, ref7;
              a_txt = ez5.loca.getBestFrontendValue((ref2 = a[_this.name()]) != null ? (ref3 = ref2._standard) != null ? (ref4 = ref3[1]) != null ? ref4.text : void 0 : void 0 : void 0) || "";
              b_txt = ez5.loca.getBestFrontendValue((ref5 = b[_this.name()]) != null ? (ref6 = ref5._standard) != null ? (ref7 = ref6[1]) != null ? ref7.text : void 0 : void 0 : void 0) || "";
              return a_txt.localeCompare(b_txt);
            };
          })(this)
        });
      } else if (nestedSortField.sort_field === ((this.name()) + "-pool")) {
        field = this.__getPoolField();
        if (!field) {
          continue;
        }
        sortFunctions.push({
          nested_sort_field: nestedSortField,
          func: (function(_this) {
            return function(dataA, dataB) {
              var poolA, poolB;
              poolA = _this.__getPoolName(field, dataA);
              poolB = _this.__getPoolName(field, dataB);
              return poolA.localeCompare(poolB);
            };
          })(this)
        });
      }
    }
    return sortFunctions;
  };

  LinkedObject.prototype.__getPoolName = function(poolField, data) {
    var linkedObjecttypeName, poolName, ref, ref1, ref2, ref3;
    linkedObjecttypeName = this.linkMask().table.name();
    poolName = (ref = data[this.name()]) != null ? (ref1 = ref[linkedObjecttypeName]) != null ? (ref2 = ref1[poolField.name()]) != null ? (ref3 = ref2.pool) != null ? ref3.name : void 0 : void 0 : void 0 : void 0;
    return ez5.loca.getBestFrontendValue(poolName) || "";
  };

  LinkedObject.prototype.__getPoolField = function() {
    return this.linkMask().fields.filter(function(field) {
      return field instanceof PoolField;
    })[0];
  };

  LinkedObject.prototype.getCollectionMemory = function(data, top_level_data) {
    return new CollectionMemory({
      hasEASFields: this.linkMask().getEASFields("detail").length > 0
    });
  };

  LinkedObject.prototype.getClass = function() {
    return [LinkedObject.__super__.getClass.call(this), "ez5-linked-object-inline-" + this.__getLinkMaskInline(), this.linkMask().table.getCapabilityClasses("ez5-linked-object-"), !this.linkMask().table.isHierarchy() ? "ez5-linked-object-no-hierarchy" : ""].join(" ");
  };

  LinkedObject.prototype.allowsList = function(data, top_level_data, opts) {
    if (opts.nested_fields.length === 1 && this.__getLinkMaskInline(opts) !== 'short') {
      return false;
    } else {
      return true;
    }
  };

  LinkedObject.prototype.allowsCondensed = function(opts) {
    return this.__getLinkMaskInline(opts) !== 'text';
  };

  LinkedObject.prototype.getSaveData = function(data, save_data, opts) {
    var data_ref, k, link_mask_opts, new_data, new_opts, obj, object, objecttype, opts2, ot_name, pool, rec, ref, ref1, ref2, ref3, ref4, resultObject, ro, saveData, tbl_name, topLevelData, v;
    if (save_data == null) {
      save_data = {};
    }
    if (opts == null) {
      opts = {};
    }
    if (opts.demo_data) {
      if (opts.__demo_skip_next_linked_object) {
        return;
      }
      objecttype = opts.top_level_data._objecttype;
      if ((ref = opts.top_level_data[objecttype]) != null ? ref._top_level : void 0) {
        topLevelData = opts.top_level_data[objecttype]._top_level;
        opts.top_level_data[objecttype]._top_level = null;
      }
      opts2 = CUI.util.copyObject(opts, true);
      opts2.top_level_data[objecttype]._top_level = topLevelData;
      opts2.__demo_skip_next_linked_object = true;
      ro = new ResultObjectDemo({
        mask: this.linkMask(),
        version: opts.demo_version,
        demo_skip_path_create: true,
        format: opts.demo_format_linked_object,
        opts: opts2
      });
      save_data[this.name()] = ro.getData();
      if (opts.demo_format_linked_object === "standard") {
        ot_name = this.linkMask().table.name();
        obj = save_data[this.name()];
        ref1 = obj[ot_name];
        for (k in ref1) {
          v = ref1[k];
          if (!k.startsWith("_")) {
            delete obj[ot_name][k];
          }
        }
      }
      return;
    }
    link_mask_opts = CUI.util.copyObject(opts, false);
    delete link_mask_opts.bulk;
    tbl_name = this.linkMask().table.name();
    if (data[this.name()]) {
      data_ref = data[this.name()];
    } else if ((ref2 = data._template) != null ? ref2[this.name()] : void 0) {
      data_ref = data._template[this.name()];
    } else {
      save_data[this.name()] = null;
      return save_data[this.name()];
    }
    save_data[this.name()] = rec = {};
    rec._objecttype = tbl_name;
    if (!opts.init_save_data && !opts.check_changed) {
      rec._mask = data_ref._mask || this.linkMask().name();
    }
    rec._global_object_id = data_ref._global_object_id;
    if (opts.copy) {
      rec._standard = data_ref._standard;
      if (data_ref._path) {
        rec._path = data_ref._path;
      }
      rec._format = data_ref._format;
    }
    if (!data_ref[tbl_name]) {
      if (!CUI.util.isEmpty(data_ref)) {
        resultObject = new ResultObject();
        resultObject.setData(data_ref);
        if (!resultObject.isPurged() && !resultObject.isDeleted()) {
          console.error("LinkedObject.getSaveData: Inconsistent data from server received, ignoring Linked Object. Data: ", data, "Name: ", this.name(), "Linked Data:", data_ref);
        }
      }
      save_data[this.name()] = null;
      return null;
    }
    if (data_ref[tbl_name]._id) {
      rec[tbl_name] = {
        _id: data_ref[tbl_name]._id
      };
    } else {
      if (opts.create_objects) {
        new_data = CUI.util.copyObject(rec, true);
        for (k in data_ref) {
          v = data_ref[k];
          if (new_data[k] === void 0 || k === tbl_name) {
            new_data[k] = v;
          }
        }
        obj = {
          _save_data: null,
          _data_ref: null
        };
        new_opts = {
          editor: opts.editor,
          "new": true,
          bulk: false,
          base_fields_only: false,
          render_mode: "editor",
          render_mode_header: "editor-header",
          create_objects: opts.create_objects,
          parent_create_object: obj
        };
        object = new ResultObject().setData(new_data);
        objecttype = object.objecttype();
        if (this.linkMask().table.poolLink() && !object.data[objecttype]._pool && object.isMappedMetadataCreated() && ((ref3 = opts.editor) != null ? ref3.editor_data : void 0)) {
          if (pool = opts.editor.editor_data["_pool_" + (this.fullName())]) {
            object.data[objecttype]._pool = pool;
          }
        }
        saveData = object.getSaveData(new_opts);
        for (k in saveData) {
          v = saveData[k];
          rec[k] = v;
        }
        if (ez5.version("6") && object.isMappedMetadataCreated() && ((ref4 = rec._tags) != null ? ref4.length : void 0) === 0) {
          delete rec._tags;
        }
        obj._save_data = rec;
        obj._data_ref = data_ref;
        if (opts.parent_create_object) {
          obj._parent_create_object = opts.parent_create_object;
          obj._parent_create_object._field_name = this.name();
        }
        new_data = null;
        opts.create_objects.push(obj);
      } else {
        if (opts.copy_for_template) {
          throw new InvalidSaveDataException();
        } else {
          rec[tbl_name] = {
            _id: null
          };
        }
      }
    }
    return save_data[this.name()];
  };

  LinkedObject.prototype.__addFromCollection = function(append_row_func, collection) {
    var co, data, i, idx, len, ref;
    ref = collection.getObjects();
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      co = ref[idx];
      data = {};
      data[this.name()] = co.getObject();
      append_row_func(data);
    }
    return this;
  };

  LinkedObject.prototype.isEmpty = function(data) {
    return CUI.util.isEmpty(data[this.name()]);
  };

  LinkedObject.prototype.checkValue = function(data, top_level_data, opts) {
    var data_ref, ref;
    if (data[this.name()]) {
      data_ref = data[this.name()];
    } else if ((ref = data._template) != null ? ref[this.name()] : void 0) {
      data_ref = data._template[this.name()];
    } else {
      data_ref = null;
    }
    if (!data_ref && this.ColumnSchema.check === "not_empty" && this.isVisible(opts.render_mode, opts)) {
      return false;
    } else {
      return true;
    }
  };

  LinkedObject.showInSearch = function(_opts) {
    var f, gid, i, idx, len, mf, name_localized, names_added, opts, qf, ref, search_data;
    if (_opts == null) {
      _opts = {};
    }
    opts = CUI.Element.readOpts(_opts, "LinkedObject.showInSearch", {
      search_fields: {
        mandatory: true,
        check: function(v) {
          return (v != null ? v.length : void 0) > 0;
        }
      },
      search: {
        mandatory: true,
        check: SearchMain
      },
      result_object: {
        mandatory: true,
        check: ResultObject
      }
    });
    names_added = {};
    mf = new MultipleFieldsContainer();
    ref = opts.search_fields;
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      f = ref[idx];
      if (idx === 0) {
        name_localized = f.linkMask().table.nameLocalized();
      }
      if (names_added[f.fullName()]) {
        continue;
      }
      names_added[f.fullName()] = true;
      mf.addField(f);
    }
    mf.setNameLocalized(name_localized);
    gid = opts.result_object.getGlobalObjectId();
    search_data = {
      __result_object: {}
    };
    search_data[opts.search_fields[0].name()] = [gid];
    search_data.__result_object[gid] = opts.result_object;
    qf = new QueryElementField({
      data: search_data,
      field: mf
    });
    return opts.search.showInSearch(qf);
  };

  LinkedObject.prototype.getResultObject = function(data, top_level_data, opts) {
    return new ResultObject().setData(data[this.name()]);
  };

  LinkedObject.prototype.renderTableOutput = function(data, top_level_data, opts) {
    if (opts == null) {
      opts = {};
    }
    opts.inline_mode = "short";
    if (this.linkMask().table.isHierarchy()) {
      opts.path = this.__showPathInDetail(opts);
    }
    if (this.getFirstStandardEASColumn()) {
      opts.inline_mode = "";
    }
    return LinkedObject.__super__.renderTableOutput.call(this, data, top_level_data, opts);
  };

  LinkedObject.prototype.renderDetailOutput = function(data, top_level_data, opts) {
    var append_to_div, deferred, detail, div, i, j, k, key, lay, len, len1, mode, ref, ref1, result_div, ro, showPath, tool, tools, toolsBtn;
    if (opts == null) {
      opts = {};
    }
    if (!data[this.name()]) {
      return;
    }
    showPath = opts.path;
    if (CUI.util.isUndef(showPath) && this.linkMask().table.isHierarchy()) {
      showPath = this.__showPathInDetail(opts);
    }
    if (opts.detail instanceof DetailSidebar) {
      detail = opts.detail;
    }
    ro = this.getResultObject(data, top_level_data, opts);
    tools = ro.getDetailTools({
      detail: detail,
      getElement: (function(_this) {
        return function() {
          return lay;
        };
      })(this)
    });
    mode = opts.inline_mode || this.__getLinkMaskInline(opts);
    if (opts.history && !data[this.name()]._global_object_id && data[this.name()]._format) {
      mode = data[this.name()]._format;
    }
    if (mode !== 'short') {
      lay = new CUI.HorizontalLayout({
        maximize_horizontal: true,
        maximize_vertical: false,
        "class": "ez5-linked-object-detail ez5-linked-object linked-object-popover",
        attr: {
          inline: this.__getLinkMaskInline(opts)
        },
        right: {}
      });
      toolsBtn = Toolbox.getFlyoutButtonbar(tools, {
        appearance: "flat"
      });
      if (!ro.detailToolsEnabled()) {
        toolsBtn.disable();
      }
      lay.replace(toolsBtn, "right");
    }
    deferred = new CUI.Deferred();
    if ((ref = opts.__waits) != null) {
      ref.push(deferred.promise());
    }
    append_to_div = (function(_this) {
      return function(div, mode) {
        return _this.__loadFromData(data[_this.name()], mode).done(function(ro) {
          var _div, _opts, _path, ref1, showHierarchyPath, showObjecttype, showPool, showSystemObjectId, showTags;
          _opts = {
            for_print: opts.for_print,
            hierarchy_path_reverse: opts.hierarchy_path_reverse,
            detail: detail
          };
          showTags = _this.__getMaskCustomSetting("show_tags_inline", false);
          if (showTags) {
            showTags = ((ref1 = _this.linkMask().schema.system_fields) != null ? ref1.tags.output.mode : void 0) !== "off";
          }
          showPool = _this.__getMaskCustomSetting("show_pool_inline", false);
          showObjecttype = _this.__getMaskCustomSetting("show_objecttype_inline", false);
          showSystemObjectId = _this.__getMaskCustomSetting("show_system_object_id_inline", false);
          showHierarchyPath = _this.__getMaskCustomSetting("show_hierarchy_path_inline", false);
          _div = (function() {
            switch (mode) {
              case "short":
                _opts.path = showPath;
                return ro.renderCardLinkedObjectShort(_opts);
              case "text":
                if (opts._path) {
                  _path = opts._path + "." + this.fullName();
                } else {
                  _path = this.fullName();
                }
                _opts._path = _path;
                _opts.path = showPath;
                _opts.hideHierarchyPath = !showHierarchyPath;
                _opts.hide_tags = !showTags;
                _opts.hide_objecttype = !showObjecttype;
                _opts.hide_pool = !showPool;
                _opts.hide_system_object_id = !showSystemObjectId;
                _opts.isVisible = opts.isVisible;
                _opts.getLabel = opts.getLabel;
                return ro.renderTextDetail(_opts);
              case "standard":
                _opts.path = showPath;
                _opts.tags = showTags;
                return ro.renderCardLinkedObjectStandard(_opts);
            }
          }).call(_this);
          CUI.dom.append(div, _div);
          CUI.dom.append(div, _this.__getMaskNotMatchWarning(ro, data[_this.name()]));
          CUI.dom.setAttribute(div, "ez5-linked-object-mask", _this.linkMask().name());
          CUI.dom.setAttribute(div, "ez5-linked-object-rendered-mask", data[_this.name()]._mask);
          CUI.dom.setAttribute(div, "ez5-linked-object-mode", mode);
          CUI.dom.setAttribute(div, "ui", "linked.object.field:" + (ro.objecttype()) + "_" + (ro.getId()));
        }).fail(function(error) {
          var lbl;
          if (error instanceof UserError) {
            lbl = new CUI.Label({
              multiline: true,
              text: error.getError(),
              "class": "ez5-linked-object-warning cui-label-warning"
            });
            CUI.dom.append(div, lbl);
          }
        }).always(function() {
          deferred.resolve();
        });
      };
    })(this);
    if (mode === 'short') {
      div = CUI.dom.element("DIV");
      append_to_div(div, mode);
      result_div = div.children[0];
      ref1 = ["mask", "rendered-mask", "mode"];
      for (i = 0, len = ref1.length; i < len; i++) {
        k = ref1[i];
        key = "ez5-linked-object-" + k;
        CUI.dom.setAttribute(result_div, key, CUI.dom.getAttribute(div, key));
      }
      for (j = 0, len1 = tools.length; j < len1; j++) {
        tool = tools[j];
        if (tool.getName() === 'result.object.show_in_search') {
          (function(_this) {
            return (function(tool) {
              CUI.Events.listen({
                type: ['click', 'keyup'],
                node: result_div,
                call: function(ev) {
                  var ref2;
                  ev.preventDefault();
                  if (ev.getType() === 'click' || ((ref2 = ev.keyCode()) === 32 || ref2 === 13)) {
                    tool.run();
                  }
                }
              });
              CUI.dom.setAttribute(result_div, 'tabindex', '0');
              return CUI.dom.addClass(result_div, "ez5-card--clickable");
            });
          })(this)(tool);
          break;
        }
      }
      return result_div;
    }
    append_to_div(lay.center(), mode);
    return lay;
  };

  LinkedObject.prototype.__loadFromData = function(data, mode) {
    var best_mask_filter;
    if (data._format_incomplete) {
      best_mask_filter = false;
    } else if (mode === "text") {
      best_mask_filter = false;
    } else {
      best_mask_filter = true;
    }
    return ResultObject.loadFromData(data, mode, false, best_mask_filter);
  };

  LinkedObject.prototype.__getMaskNotMatchWarning = function(ro, data) {
    var ref;
    if (ro.getMask().name() === data._mask) {
      return;
    }
    return new LocaLabel({
      multiline: true,
      markdown: true,
      loca_key: "linked.object.loaded_with_wrong_mask",
      loca_key_attrs: {
        output_mask: ro.getMask().nameLocalized(),
        wanted_mask: ((ref = ez5.mask.CURRENT._mask_instance_by_name[data._mask]) != null ? ref.nameLocalized() : void 0) || data._mask
      },
      "class": "ez5-linked-object-warning cui-label-warning"
    }).DOM;
  };

  LinkedObject.prototype.getSearchFilter = function(data, key) {
    var filter, includeChildren, isSubsearch, ss;
    if (key == null) {
      key = this.name();
    }
    filter = LinkedObject.__super__.getSearchFilter.call(this, data, key);
    if (filter) {
      return filter;
    }
    isSubsearch = CUI.util.isPlainObject(data[key]) && data[key].isSubsearch;
    if (CUI.util.isEmpty(data[key]) || (!data[key].length && !isSubsearch)) {
      return;
    }
    includeChildren = data[key + ":include_children"];
    if (isSubsearch) {
      ss = {
        objecttypes: data[key].objecttypes,
        field: "_global_object_id",
        search: data[key].search,
        limit: -1
      };
      if (includeChildren && this.linkMask().table.isPolyhierarchy()) {
        filter = {
          type: "complex",
          bool: "should",
          search: [
            {
              type: "in",
              fields: this.getSearchField(includeChildren),
              subsearch: ss,
              bool: "should"
            }, {
              type: "in",
              fields: [(this.fullName()) + "._global_object_id"],
              subsearch: ss,
              bool: "should"
            }
          ]
        };
      } else {
        filter = {
          type: "in",
          fields: this.getSearchField(includeChildren),
          subsearch: ss
        };
      }
    } else if (includeChildren && this.linkMask().table.isPolyhierarchy()) {
      filter = {
        type: "complex",
        bool: "should",
        search: [
          {
            type: "in",
            fields: this.getSearchField(includeChildren),
            "in": data[key],
            bool: "should"
          }, {
            type: "in",
            fields: [(this.fullName()) + "._global_object_id"],
            "in": data[key],
            bool: "should"
          }
        ]
      };
    } else {
      filter = {
        type: "in",
        fields: this.getSearchField(includeChildren),
        "in": data[key]
      };
    }
    return filter;
  };

  LinkedObject.prototype.getSearchField = function(include_children) {
    var fn;
    if (include_children) {
      if (this.linkMask().table.isPolyhierarchy()) {
        fn = (this.fullName()) + "._paths._global_object_id";
      } else {
        fn = (this.fullName()) + "._path._global_object_id";
      }
    } else {
      fn = (this.fullName()) + "._global_object_id";
    }
    return [fn];
  };

  LinkedObject.prototype.getNotInheritedSearchField = function() {
    return (this.fullName()) + ":inherited";
  };

  LinkedObject.prototype.isExpertCommon = function(mode) {
    return true;
  };

  LinkedObject.prototype.isSortGroupable = function() {
    return true;
  };

  LinkedObject.prototype.isVisible = function(mode, opts) {
    if (!LinkedObject.__super__.isVisible.call(this, mode, opts)) {
      return false;
    }
    switch (mode) {
      case "detail-header":
      case "editor-header":
      case "editor-header-bulk":
      case "editor-header-template":
        return false;
      default:
        return true;
    }
  };

  LinkedObject.prototype.getFirstStandardEASColumn = function() {
    var ref;
    if (!(((ref = this.FieldSchema.output.standard_eas) != null ? ref.order : void 0) > 0)) {
      return null;
    }
    return this.linkMask().getEASFields("standard")[0];
  };

  LinkedObject.prototype.sortExtraOpts = function() {
    var i, len, opts, ref, v;
    if (!this.linkMask().table.isHierarchy() && !this.linkMask().table.isPolyhierarchy()) {
      return;
    }
    opts = [];
    ref = ["hierarchical", "flat"];
    for (i = 0, len = ref.length; i < len; i++) {
      v = ref[i];
      opts.push({
        text: $$("linked.object.sort." + v),
        value: v
      });
    }
    return opts;
  };

  LinkedObject.prototype.sortRenderContent = function(path, renderDynamic) {
    var div;
    div = CUI.dom.element("div", {
      "class": "ez5-linked-object-group-div"
    });
    (new ResultObject()).loadFromSystemObjectId(parseInt(path[0]), "standard", this.linkMask().name(), true, false, this.linkMask().table.name()).done((function(_this) {
      return function(ro) {
        var col, p, ref, tools;
        if (_this.linkMask().table.isHierarchy()) {
          path = (function() {
            var i, len, ref, results;
            ref = ro.data._path;
            results = [];
            for (i = 0, len = ref.length; i < len; i++) {
              p = ref[i];
              results.push(ez5.loca.getBestDatabaseValue(p._standard["1"].text));
            }
            return results;
          })();
        } else {
          path = [ez5.loca.getBestDatabaseValue(ro.data._standard["1"].text)];
        }
        CUI.dom.replace(div, ResultObject.renderPath(path));
        tools = [
          new ToolboxTool({
            loca_key: "result.object.show_info",
            name: "result.object.show_info",
            run: function() {
              return ResultObject.showCollectionObjectInPopover({
                collectionObject: new CollectionObject({
                  _global_object_id: ro.getGlobalObjectId()
                }),
                element: div
              });
            }
          })
        ];
        col = renderDynamic != null ? (ref = renderDynamic._selectable_opts) != null ? ref.collection : void 0 : void 0;
        if (col && col._sidebar) {
          tools.push(new ToolboxTool({
            loca_key: "result.object.show_in_sidebar",
            name: "result.object.show_in_sidebar",
            run: function() {
              return col.loadInSidebar({
                global_object_id: ro.getGlobalObjectId()
              });
            }
          }));
        }
        CUI.dom.append(div, CUI.dom.space());
        return CUI.dom.append(div, Toolbox.getFlyoutButtonbar(tools));
      };
    })(this));
    if (!this.linkMask().table.isHierarchy()) {
      CUI.dom.append(div, ResultObject.renderPath(path));
    } else {
      CUI.dom.append(div, path[0]);
    }
    return div;
  };

  LinkedObject.prototype.getSortFields = function(filter) {
    var f, f2;
    f = {
      field: this.fullName(),
      group_field: this.fullName() + "._system_object_id",
      order: filter._order
    };
    f2 = {
      group_key_suffix: ":sort",
      group_field: this.fullName(),
      order: filter._order
    };
    if (filter._extra === "hierarchical") {
      f.with_path = true;
      f2.with_path = true;
    }
    return [f, f2];
  };

  LinkedObject.prototype.allowAppendMultipleRows = function() {
    return true;
  };

  LinkedObject.prototype.__isUseSelectActivated = function() {
    return this.__getMaskCustomSetting("use_select") && !this.linkMask().table.isHierarchy();
  };

  LinkedObject.prototype.__getObjectsSelect = function(data, opts) {
    var _filters, filters, limit, loadMore, loadMoreOptions, loadOneOption, objecttype, offset, options, select;
    limit = 100;
    objecttype = this.linkMask().table.name();
    loadOneOption = true;
    loadMore = false;
    offset = 0;
    options = null;
    if (opts.mode === "editor") {
      _filters = this.__getFilters();
      if (!CUI.util.isEmpty(_filters)) {
        filters = Object.values(_filters)[0].filters;
      }
    }
    select = new CUI.Select({
      name: this.name(),
      data: data,
      id: this.idAttribute(data),
      ui: "linked.object.dropdown.select",
      onScrollToBottom: (function(_this) {
        return function() {
          if (loadMore) {
            return loadMoreOptions();
          }
        };
      })(this),
      onDataChanged: function() {
        return CUI.Events.trigger({
          node: select,
          type: "editor-changed"
        });
      },
      options: (function(_this) {
        return function() {
          var _options, addOption, currentObjectId, deferred, ref, ref1, resultObject;
          if (options && !loadMore) {
            return options;
          }
          currentObjectId = (ref = data[_this.name()]) != null ? (ref1 = ref[objecttype]) != null ? ref1._id : void 0 : void 0;
          resultObject = new ResultObject();
          if (loadMore) {
            loadMore = false;
            _options = options;
          } else {
            _options = [
              {
                text: $$("linked.object.editor.select.placeholder", {
                  objecttype: _this.linkMask().table.nameLocalized()
                }),
                value: null
              }
            ];
          }
          addOption = function(object) {
            var text;
            if (CUI.util.isEmpty(object)) {
              return;
            }
            resultObject.setData(object);
            if (resultObject.isDeleted() || resultObject.isPurged()) {
              return;
            }
            resultObject.setMask(_this.linkMask().name());
            text = resultObject.renderText();
            if (currentObjectId && object[objecttype]._id === currentObjectId) {
              data[_this.name()] = object;
            }
            _options.push({
              text: text,
              value: object
            });
          };
          if (loadOneOption) {
            loadOneOption = false;
            if (data[_this.name()]) {
              addOption(data[_this.name()]);
            }
            return _options;
          }
          deferred = new CUI.Deferred();
          ez5.api.search({
            json_data: {
              objecttypes: [objecttype],
              offset: offset,
              limit: limit,
              generate_rights: false,
              format: "standard",
              sort: [
                {
                  field: "_standard.1.text",
                  order: "ASC"
                }
              ],
              search: filters || []
            }
          }).done(function(_data) {
            var i, len, object, ref2;
            if (_data.count > _data.offset + _data.limit) {
              loadMore = true;
            }
            ref2 = _data.objects;
            for (i = 0, len = ref2.length; i < len; i++) {
              object = ref2[i];
              addOption(object);
            }
            options = _options;
            deferred.resolve(options);
          });
          return deferred.promise();
        };
      })(this)
    }, loadMoreOptions = (function(_this) {
      return function() {
        offset += limit;
        return select.reloadMenu(true);
      };
    })(this));
    return select;
  };

  LinkedObject.prototype.__getFilters = function() {
    var filter, filters, fullName, getObjecttypeName, i, len, linkedObjectsFilters, objecttype;
    filters = {};
    getObjecttypeName = function(table) {
      var ownerTable, tableId;
      if (table.owned_by) {
        if (table._instance) {
          tableId = table.owned_by.other_table_id + "@" + table._instance;
        } else {
          tableId = table.owned_by.other_table_id;
        }
        ownerTable = ez5.schema.CURRENT._table_by_id[tableId];
        return getObjecttypeName(ownerTable);
      } else {
        return table.name;
      }
    };
    fullName = this.fullName();
    objecttype = getObjecttypeName(this.table.schema);
    linkedObjectsFilters = ez5.objecttypes.getLinkedObjectsFilters(objecttype);
    for (i = 0, len = linkedObjectsFilters.length; i < len; i++) {
      filter = linkedObjectsFilters[i];
      if (indexOf.call(filter.fields, fullName) >= 0 && (filter.filters.length > 0 || filter.only_allow_select_last_children)) {
        filters[filter.internal_name] = {
          filters: filter.filters,
          config: {
            only_allow_select_last_children: filter.only_allow_select_last_children
          }
        };
      }
    }
    return filters;
  };

  LinkedObject.prototype.__showPathInDetail = function(opts) {
    var ref, ref1;
    return this.__getLinkMaskInline(opts) !== "short" && ((ref = this.linkMask().schema.system_fields) != null ? (ref1 = ref.parent) != null ? ref1.output.mode : void 0 : void 0) !== "off";
  };

  LinkedObject.prototype.__showPathInEditor = function(opts) {
    var ref, ref1;
    return this.__getLinkMaskInline(opts) !== "short" && ((ref = this.linkMask().schema.system_fields) != null ? (ref1 = ref.parent) != null ? ref1.edit.mode : void 0 : void 0) !== "off";
  };

  return LinkedObject;

})(Field);

CUI.ready(function() {
  return CUI.Events.registerEvent({
    type: "linked-object-data-changed",
    sink: true
  });
});
// Generated by CoffeeScript 1.12.7
var LinkedObjecttype,
  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;

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

  function LinkedObjecttype(_opts) {
    this.opts = CUI.Element.prototype.readOpts.call(this, _opts, "new LinkedObjecttype", {
      objecttype: {
        mandatory: true,
        check: Objecttype
      }
    });
    Field.prototype.constructor.call(this, this._objecttype.getMask());
  }

  LinkedObjecttype.prototype.__getLinkMaskId = function() {
    return this._objecttype.getMask().id();
  };

  LinkedObjecttype.prototype.__getLinkMaskTableId = function() {
    return this._objecttype.getTable().id();
  };

  LinkedObjecttype.prototype.__getLinkMaskInline = function() {
    return "standard";
  };

  LinkedObjecttype.prototype.getQueryFieldBadge = function(data) {
    var badge, dfr;
    dfr = new CUI.Deferred();
    badge = {
      name: this._objecttype.nameLocalized(),
      popoverContent: CUI.util.dump(this.getSearchFilter(data))
    };
    ResultObject.loadFromId(this._objecttype.name(), data[this.name()][0], "standard", this.getMask().name()).done((function(_this) {
      return function(ro) {
        badge.value = ro.renderText();
        return dfr.resolve(badge);
      };
    })(this)).fail((function(_this) {
      return function() {
        badge.value = $$("linked.objecttype.badge.not_found");
        return dfr.resolve(badge);
      };
    })(this));
    return dfr.promise();
  };

  LinkedObjecttype.prototype.getSearchFilter = function(data, key) {
    var sf;
    if (key == null) {
      key = this.name();
    }
    sf = {
      type: "in",
      objecttype: this._objecttype.name(),
      "in": data[key],
      include_path: this._objecttype.isHierarchy() || this._objecttype.isPolyhierarchy()
    };
    return sf;
  };

  LinkedObjecttype.prototype.fullName = function() {
    return this.name();
  };

  LinkedObjecttype.prototype.getObjecttype = function() {
    return this._objecttype;
  };

  LinkedObjecttype.prototype.name = function() {
    return "_linked_objecttype_" + this._objecttype.name();
  };

  LinkedObjecttype.prototype.nameLocalized = function() {
    return this._objecttype.nameLocalized();
  };

  LinkedObjecttype.prototype.getSignature = function() {
    var sig;
    sig = {
      "class": CUI.util.getObjectClass(this),
      mask: {
        name: this.getMask().name()
      }
    };
    return sig;
  };

  LinkedObjecttype.fromSignature = function(signature) {
    var mask_id, ot;
    CUI.util.assert(window[signature["class"]] === this, "Field.newFromSignature", "Function mismatch", {
      signature: signature
    });
    mask_id = ez5.mask.CURRENT._mask_by_name[signature.mask.name].mask_id;
    ot = new Objecttype(new Mask("CURRENT", mask_id));
    return new LinkedObjecttype({
      objecttype: ot
    });
  };

  return LinkedObjecttype;

})(LinkedObject);
// Generated by CoffeeScript 1.12.7
var LocaTextColumn,
  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;

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

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

  LocaTextColumn.prototype.isVisible = function(mode, opts) {
    if (!LocaTextColumn.__super__.isVisible.call(this, mode, opts)) {
      return false;
    }
    switch (mode) {
      case "sort":
        return true;
      default:
        return true;
    }
  };

  LocaTextColumn.prototype.getSaveData = function(data, save_data, opts) {
    var appendData, culture, i, j, len, len1, ref, ref1, ref2, ref3, ref4, ref5, ref6, v;
    save_data[this.name()] = {};
    ref = ez5.session.getConfigDatabaseLanguages();
    for (i = 0, len = ref.length; i < len; i++) {
      culture = ref[i];
      if (opts.demo_data) {
        save_data[this.name()][culture] = (this.nameLocalized()) + " [" + culture + "]";
      } else if (CUI.util.isEmpty((ref1 = data[this.name()]) != null ? ref1[culture] : void 0)) {
        save_data[this.name()][culture] = this.getFallbackValue(data, opts, culture);
      } else {
        save_data[this.name()][culture] = (ref2 = data[this.name()]) != null ? ref2[culture] : void 0;
        if (CUI.util.isString(save_data[this.name()][culture])) {
          save_data[this.name()][culture] = save_data[this.name()][culture].trim();
        }
      }
      if (ez5.version("6")) {
        if (opts.bulk) {
          if (data[this.name() + ":options"] && !data[this.name() + ":options"][culture]) {
            delete save_data[this.name()][culture];
          }
        }
      } else {
        if (CUI.util.isEmpty(save_data[this.name()][culture])) {
          delete save_data[this.name()][culture];
        }
      }
    }
    if (opts.bulk && this.hasOption(data, "bulk") && ((ref3 = data[this.name() + ":options"]) != null ? ref3.append_with_space : void 0)) {
      appendData = {};
      ref4 = ez5.session.getConfigDatabaseLanguages();
      for (j = 0, len1 = ref4.length; j < len1; j++) {
        culture = ref4[j];
        v = (ref5 = save_data[this.name()]) != null ? ref5[culture] : void 0;
        if (!CUI.util.isEmpty(v)) {
          appendData[culture] = " " + v.trim();
        }
      }
      save_data[this.name() + ":append"] = appendData;
      delete save_data[this.name()];
      return;
    }
    if (opts.bulk && this.hasOption(data, "bulk") && ((ref6 = data[this.name() + ":options"]) != null ? ref6.append : void 0)) {
      save_data[this.name() + ":append"] = save_data[this.name()];
      delete save_data[this.name()];
      return;
    }
    this.getSearchAndReplaceSaveData(data, save_data, opts);
    if (CUI.util.isEmpty(save_data[this.name()])) {
      if (opts.bulk) {
        save_data[this.name()] = null;
      } else {
        delete save_data[this.name()];
      }
    }
  };

  LocaTextColumn.prototype.hasFallbackValue = function(data, opts) {
    var i, lang, len, ref;
    ref = ez5.session.getConfigDatabaseLanguages();
    for (i = 0, len = ref.length; i < len; i++) {
      lang = ref[i];
      if (!CUI.util.isEmpty(this.getFallbackValue(data, opts, lang))) {
        return true;
      }
    }
    return false;
  };

  LocaTextColumn.prototype.getFallbackValue = function(data, opts, lang) {
    var has_value, mv, ref, tv;
    has_value = (function(_this) {
      return function(v) {
        var ref;
        if (!CUI.util.isPlainObject(v)) {
          return false;
        }
        if (!CUI.util.isEmpty((ref = v[lang]) != null ? ref.trim() : void 0)) {
          return true;
        }
        return false;
      };
    })(this);
    tv = (ref = data._template) != null ? ref[this.name()] : void 0;
    mv = data[this.name() + ":mapped_metadata"];
    if (this.preferTemplateOverMapping(opts)) {
      if (has_value(tv)) {
        return tv[lang];
      } else if (has_value(mv)) {
        return mv[lang];
      }
    } else {
      if (has_value(mv)) {
        return mv[lang];
      } else if (has_value(tv)) {
        return tv[lang];
      }
    }
    return null;
  };

  LocaTextColumn.prototype.value = function(data, val) {
    if (CUI.util.isUndef(val)) {
      return data[this.name()] && data[this.name()][ez5.loca.culture];
    } else {
      if (CUI.util.isUndef(data[this.name()])) {
        data[this.name()] = {};
      }
      return data[this.name()][ez5.loca.culture] = val;
    }
  };

  LocaTextColumn.prototype.setValue = function(data, val) {
    var i, language, len, ref;
    if (CUI.util.isUndef(data[this.name()])) {
      data[this.name()] = {};
    }
    ref = ez5.loca.getDatabaseLanguages();
    for (i = 0, len = ref.length; i < len; i++) {
      language = ref[i];
      data[this.name()][language] = val[language];
    }
  };

  LocaTextColumn.prototype.isTextarea = function() {
    return false;
  };

  LocaTextColumn.prototype.getBulkForm = function(data, element) {
    var bulk_data, bulk_fields, bulk_form, multiInputControl, update_bulk_form, useTextarea;
    if (!ez5.version("6")) {
      return;
    }
    bulk_data = data[(this.name()) + ":options"];
    if (!bulk_data) {
      bulk_data = data[(this.name()) + ":options"] = {};
    }
    if (!bulk_data.search) {
      bulk_data.search = {};
    }
    if (!bulk_data.replace) {
      bulk_data.replace = {};
    }
    useTextarea = this.isTextarea();
    multiInputControl = new LanguageControlCustom({
      getEnabledKeys: (function(_this) {
        return function() {
          return _this.__getEnabledKeys(data);
        };
      })(this),
      hasUserControl: true
    });
    update_bulk_form = (function(_this) {
      return function() {
        var cb, f, i, j, k, l, len, len1, len2, n, ref, ref1, ref2;
        ref = ["search", "replace", "full_words", "case_sensitive"];
        for (i = 0, len = ref.length; i < len; i++) {
          k = ref[i];
          if (bulk_data.search_and_replace) {
            bulk_form.getFieldsByName(k)[0].show(true);
            if (ez5.version("6.7")) {
              ref1 = ["append", "append_with_space"];
              for (j = 0, len1 = ref1.length; j < len1; j++) {
                n = ref1[j];
                f = bulk_form.getFieldsByName(n)[0];
                f.hide(true);
                f.setValue(false);
              }
            }
          } else if (bulk_data.append) {
            bulk_form.getFieldsByName(k)[0].hide(true);
            if (ez5.version("6.7")) {
              bulk_form.getFieldsByName("append_with_space")[0].show(true);
            }
          } else {
            bulk_form.getFieldsByName(k)[0].hide(true);
            if (ez5.version("6.7")) {
              bulk_form.getFieldsByName("append")[0].show(true);
              bulk_form.getFieldsByName("append_with_space")[0].hide(true);
              bulk_form.getFieldsByName("append_with_space")[0].setValue(false);
            }
          }
        }
        if (bulk_data.search_and_replace) {
          CUI.dom.hideElement(element);
        } else {
          CUI.dom.showElement(element);
        }
        ref2 = bulk_data.__langCheckboxes || [];
        for (l = 0, len2 = ref2.length; l < len2; l++) {
          cb = ref2[l];
          if (bulk_data.search_and_replace || bulk_data.append) {
            CUI.dom.hideElement(cb.DOM);
          } else {
            CUI.dom.showElement(cb.DOM);
          }
        }
        CUI.Events.trigger({
          node: element,
          type: "editor-changed"
        });
      };
    })(this);
    bulk_fields = [
      {
        type: CUI.Checkbox,
        undo_and_changed_support: false,
        name: "search_and_replace",
        text: $$("text.column.bulk.form.search_and_replace")
      }, {
        type: CUI.MultiInput,
        undo_and_changed_support: false,
        name: "search",
        textarea: useTextarea,
        control: multiInputControl,
        placeholder: {
          "default": $$("text.column.bulk.form.search")
        },
        copyPlaceholder: true
      }, {
        type: CUI.MultiInput,
        undo_and_changed_support: false,
        name: "replace",
        textarea: useTextarea,
        control: multiInputControl,
        placeholder: {
          "default": $$("text.column.bulk.form.replace")
        },
        copyPlaceholder: true
      }, {
        type: CUI.Checkbox,
        undo_and_changed_support: false,
        name: "full_words",
        text: $$("text.column.bulk.form.full_words")
      }, {
        type: CUI.Checkbox,
        undo_and_changed_support: false,
        name: "case_sensitive",
        text: $$("text.column.bulk.form.case_sensitive")
      }
    ];
    if (ez5.version("6.7")) {
      bulk_fields.push({
        type: CUI.Checkbox,
        undo_and_changed_support: false,
        name: "append",
        text: $$("text.column.bulk.form.append")
      });
      bulk_fields.push({
        type: CUI.Checkbox,
        undo_and_changed_support: false,
        form: {
          label: $$("text.column.bulk.form.append.options")
        },
        name: "append_with_space",
        text: $$("text.column.bulk.form.append_with_space")
      });
    }
    bulk_form = new CUI.Form({
      data: bulk_data,
      onDataChanged: update_bulk_form,
      undo_and_changed_support: false,
      "class": "ez5-form-search-and-replace",
      fields: bulk_fields
    }).start();
    update_bulk_form();
    return bulk_form;
  };

  LocaTextColumn.prototype.checkValue = function(data, top_level_data, opts) {
    var culture, i, lang, len, ref, ref1, ref2, search, v;
    if (this.hasOption(data, "bulk") && ((ref = data[this.name() + ":options"]) != null ? ref.search_and_replace : void 0)) {
      search = data[this.name() + ":options"].search;
      if (CUI.util.isPlainObject(search)) {
        for (lang in search) {
          v = search[lang];
          if (!CUI.util.isEmpty(v)) {
            return true;
          }
        }
      }
      return false;
    }
    ref1 = ez5.session.getConfigDatabaseLanguages();
    for (i = 0, len = ref1.length; i < len; i++) {
      culture = ref1[i];
      v = (ref2 = data[this.name()]) != null ? ref2[culture] : void 0;
      if (CUI.util.isEmpty(v)) {
        v = this.getFallbackValue(data, opts, culture);
        if (!CUI.util.isEmpty(v)) {
          break;
        }
      } else {
        break;
      }
    }
    return this.checkBareValue(v, data, top_level_data, opts);
  };

  LocaTextColumn.prototype.getSearchAndReplaceSaveData = function(data, save_data, opts) {
    var bulk_key, i, j, k, lang, len, len1, ref, ref1, ref2, ref3, ref4, replaceData, searchData;
    if (opts.bulk && this.hasOption(data, "bulk") && ((ref = data[this.name() + ":options"]) != null ? ref.search_and_replace : void 0)) {
      searchData = {};
      replaceData = {};
      ref1 = ez5.session.getConfigDatabaseLanguages();
      for (i = 0, len = ref1.length; i < len; i++) {
        lang = ref1[i];
        if (!CUI.util.isEmpty((ref2 = data[this.name() + ":options"].search) != null ? ref2[lang] : void 0)) {
          searchData[lang] = data[this.name() + ":options"].search[lang];
          replaceData[lang] = ((ref3 = data[this.name() + ":options"].replace) != null ? ref3[lang] : void 0) || "";
        }
      }
      save_data[this.name() + ":search"] = searchData;
      save_data[this.name() + ":replace"] = replaceData;
      ref4 = ["full_words", "case_sensitive"];
      for (j = 0, len1 = ref4.length; j < len1; j++) {
        k = ref4[j];
        bulk_key = this.name() + ":" + k;
        save_data[bulk_key] = data[this.name() + ":options"][k];
      }
      delete save_data[this.name()];
    }
  };

  LocaTextColumn.prototype.getSortFunction = function() {
    return (function(_this) {
      return function(a, b) {
        var a_txt, b_txt;
        a_txt = ez5.loca.getBestFrontendValue(a[_this.name()]) || "";
        b_txt = ez5.loca.getBestFrontendValue(b[_this.name()]) || "";
        return a_txt.localeCompare(b_txt);
      };
    })(this);
  };

  LocaTextColumn.prototype.isEmpty = function(data) {
    return !this.hasUserData(data);
  };

  LocaTextColumn.prototype.hasUserData = function(data, _, opts) {
    var k, ref, v;
    if (opts == null) {
      opts = {};
    }
    if (opts.mode === "expert") {
      return !CUI.util.isEmpty(data[this.name()]);
    }
    if (CUI.util.isPlainObject(data[this.name()])) {
      ref = data[this.name()];
      for (k in ref) {
        v = ref[k];
        if (!CUI.util.isEmpty(v)) {
          return true;
        }
      }
    }
    return false;
  };

  LocaTextColumn.prototype.renderSearchInput = function(data, opts) {
    if (opts == null) {
      opts = {};
    }
    if (opts.bulk_expert) {
      return this.renderEditorInput(data, {}, opts);
    }
    return LocaTextColumn.__super__.renderSearchInput.call(this, data, opts);
  };

  LocaTextColumn.prototype.renderData = function(data) {
    var html, text, v;
    if (this.isEmpty(data)) {
      return "";
    }
    v = data[this.name()];
    html = ez5.loca.getBestDatabaseValue(v, true, true);
    text = ez5.loca.getBestDatabaseValue(v);
    return [text, html];
  };

  LocaTextColumn.prototype.__getEnabledKeys = function(data) {
    var enabled_keys, lang, ref, value;
    enabled_keys = ez5.loca.getDatabaseLanguages().slice(0);
    ref = data[this.name()] || {};
    for (lang in ref) {
      value = ref[lang];
      if (CUI.util.isEmpty(value)) {
        continue;
      }
      enabled_keys.push(lang);
    }
    return enabled_keys;
  };

  LocaTextColumn.prototype.getElementOpts = function(mode, data) {
    var opts;
    if (mode === "expert") {
      opts = {
        type: CUI.Input,
        name: this.name()
      };
    } else {
      opts = {
        type: CUI.MultiInput,
        name: this.name(),
        attr: {
          "aria-labelledby": this.fullName()
        },
        spellcheck: ez5.session.getPref("spellcheck"),
        control: new LanguageControlCustom({
          getEnabledKeys: (function(_this) {
            return function() {
              return _this.__getEnabledKeys(data);
            };
          })(this),
          hasUserControl: true
        }),
        user_selectable: ez5.session.getPref("languages_user_selection"),
        onInit: (function(_this) {
          return function(field) {
            if (mode !== "editor") {
              return;
            }
            return CUI.Events.listen({
              type: "multi-input-control-update",
              node: field,
              call: function() {
                return CUI.Events.trigger({
                  type: "editor-changed",
                  node: field
                });
              }
            });
          };
        })(this)
      };
    }
    return opts;
  };

  LocaTextColumn.prototype.renderEditorInput = function(data, top_level_data, render_opts) {
    var dom, result;
    result = LocaTextColumn.__super__.renderEditorInput.call(this, data, top_level_data, render_opts);
    if (result instanceof HTMLElement) {
      dom = result;
    } else {
      dom = result.DOM;
    }
    this.__addLangAttributes(dom, "input");
    if (render_opts.mode === "editor-bulk") {
      this.__addLangBulkCheckbox(dom, data);
    }
    return result;
  };

  LocaTextColumn.prototype.getCustomPlaceholder = function(lang) {
    var ph, ref, ref1;
    ph = (ref = this.FieldSchema) != null ? (ref1 = ref.custom_settings) != null ? ref1.edit_user_placeholder_l10n : void 0 : void 0;
    if (CUI.util.isEmpty(ph)) {
      return null;
    }
    return ph[lang];
  };

  LocaTextColumn.prototype.getPlaceholder = function(data, opts) {
    var i, lang, len, placeholder, ref, v;
    placeholder = {};
    ref = ez5.session.getConfigDatabaseLanguages();
    for (i = 0, len = ref.length; i < len; i++) {
      lang = ref[i];
      v = this.getFallbackValue(data, opts, lang) || this.getCustomPlaceholder(lang);
      if (v === null) {
        continue;
      }
      placeholder[lang] = v;
    }
    return placeholder;
  };

  LocaTextColumn.prototype.getCSVDestinationFields = function(csvImporter) {
    var opts;
    opts = {
      csvImporter: csvImporter,
      field: this
    };
    return [new LocaTextColumnCSVImporterDestinationField(opts)];
  };

  LocaTextColumn.prototype.isDataEqualsValue = function(data, compareValue) {
    var value;
    value = ez5.loca.getBestFrontendValue(data[this.name()]);
    compareValue = ez5.loca.getBestFrontendValue(compareValue);
    return value && compareValue && value === compareValue;
  };

  LocaTextColumn.prototype.formatValue = function(value) {
    return ez5.loca.getBestFrontendValue(value);
  };

  LocaTextColumn.prototype.__getEditorInputValue = function(value) {
    if (CUI.util.isEmpty(value)) {
      return {};
    }
    return value;
  };

  LocaTextColumn.prototype.mergeData = function(top_level_data, top_level_data_new, replace) {
    var data, data_new, lang, ref, ref1, value;
    if (replace == null) {
      replace = false;
    }
    data = top_level_data[top_level_data._objecttype];
    data_new = top_level_data_new[top_level_data_new._objecttype];
    if (replace) {
      return LocaTextColumn.__super__.mergeData.call(this, top_level_data, top_level_data_new, replace);
    }
    ref = data[this.name()] || {};
    for (lang in ref) {
      value = ref[lang];
      if ((value != null ? value.trim().length : void 0) > 0 && ((ref1 = data_new[this.name()][lang]) != null ? ref1.trim().length : void 0) > 0) {
        data[this.name()][lang] += " " + data_new[this.name()][lang];
      } else {
        data[this.name()][lang] = data_new[this.name()][lang];
      }
    }
    return this;
  };

  LocaTextColumn.prototype.renderDetailOutput = function(data, top_level_data, opts) {
    var cls, element, enabledKeys, getEnabledKeys, i, index, j, language, languages, len, len1, manage_overflow, multi_opts, output, ref, ref1, ref2, ref3;
    if (opts == null) {
      opts = {};
    }
    languages = ez5.session.getConfigDatabaseLanguages();
    if (languages.length === 1) {
      opts.no_objectdumper = true;
      return LocaTextColumn.__super__.renderDetailOutput.call(this, data, top_level_data, opts);
    }
    if (!this.hasUserData(data)) {
      return;
    }
    if (opts.for_print) {
      manage_overflow = false;
    } else {
      manage_overflow = this.getManageOverflow();
    }
    for (i = 0, len = languages.length; i < len; i++) {
      language = languages[i];
      data[this.name()][language] = (ref = data[this.name()][language]) != null ? ref.trim() : void 0;
    }
    getEnabledKeys = (function(_this) {
      return function() {
        var show_languages_with_data;
        show_languages_with_data = ez5.session.getPref("show_languages_with_data");
        if (CUI.util.isTrue(show_languages_with_data)) {
          return languages;
        } else {
          return ez5.loca.getDatabaseLanguages();
        }
      };
    })(this);
    multi_opts = {
      name: this.name(),
      ui: "loca.text.column:" + (this.name()),
      data: data,
      control: new LanguageControlCustom({
        getEnabledKeys: getEnabledKeys,
        hasUserControl: false
      }),
      showOnlyPreferredKey: false
    };
    if ((ref1 = this.FieldSchema) != null ? (ref2 = ref1.custom_settings) != null ? ref2.render_markdown : void 0 : void 0) {
      multi_opts.markdown = true;
      cls = "ez5-field-value--markdown";
    } else {
      multi_opts.text_node_func = CUI.Label.parseLinks;
      cls = void 0;
    }
    output = new CUI.MultiOutput(multi_opts);
    output = output.start();
    enabledKeys = getEnabledKeys();
    ref3 = CUI.dom.findElements(output.DOM, ".cui-label-content > span");
    for (index = j = 0, len1 = ref3.length; j < len1; index = ++j) {
      element = ref3[index];
      CUI.dom.setAttribute(element, "lang", enabledKeys[index]);
    }
    return new CUI.MultilineLabel({
      "class": cls,
      content: output,
      manage_overflow: manage_overflow
    });
  };

  LocaTextColumn.prototype.getXMLFormWrapperFields = function() {
    return [];
  };

  LocaTextColumn.prototype.__addLangAttributes = function(element, selector) {
    var i, input, inputWrapper, inputs, language, len, ref;
    if (!element) {
      return;
    }
    inputs = CUI.dom.findElements(element, selector);
    for (i = 0, len = inputs.length; i < len; i++) {
      input = inputs[i];
      inputWrapper = (ref = input.parentElement) != null ? ref.parentElement : void 0;
      if (!inputWrapper) {
        continue;
      }
      language = CUI.dom.getAttribute(inputWrapper, "cui-data-field-name");
      if (language) {
        CUI.dom.setAttribute(input, "lang", language);
      }
    }
  };

  LocaTextColumn.prototype.__addLangBulkCheckbox = function(element, data, selector) {
    var i, input, inputWrapper, inputs, len, ref, results;
    if (data == null) {
      data = {};
    }
    if (selector == null) {
      selector = "input";
    }
    if (!ez5.version("6")) {
      return;
    }
    if (!data[(this.name()) + ":options"]) {
      data[(this.name()) + ":options"] = {};
    }
    data[(this.name()) + ":options"].__langCheckboxes = [];
    inputs = CUI.dom.findElements(element, selector);
    results = [];
    for (i = 0, len = inputs.length; i < len; i++) {
      input = inputs[i];
      inputWrapper = (ref = input.parentElement) != null ? ref.parentElement : void 0;
      if (!inputWrapper) {
        continue;
      }
      results.push((function(_this) {
        return function(input, inputWrapper) {
          var checkbox, language;
          language = CUI.dom.getAttribute(inputWrapper, "cui-data-field-name");
          checkbox = new CUI.Checkbox({
            name: language,
            data: data[(_this.name()) + ":options"],
            onDataChanged: function(ev) {
              return CUI.Events.trigger({
                type: "editor-changed",
                node: input
              });
            }
          });
          checkbox.start();
          input.addEventListener("input", function(ev) {
            if (!checkbox.isActive() && !CUI.util.isEmpty(data[_this.name()][language])) {
              checkbox.activate();
              return checkbox.reload();
            }
          });
          inputWrapper.prepend(checkbox.DOM);
          return data[(_this.name()) + ":options"].__langCheckboxes.push(checkbox);
        };
      })(this)(input, inputWrapper));
    }
    return results;
  };

  return LocaTextColumn;

})(TextColumn);
// Generated by CoffeeScript 1.12.7
var LocaTextMultiColumn,
  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;

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

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

  LocaTextMultiColumn.prototype.getElementOpts = function(mode, data) {
    switch (mode) {
      case "expert":
        return {
          name: this.name(),
          type: CUI.Input
        };
      default:
        return {
          name: this.name(),
          control: new LanguageControlCustom({
            getEnabledKeys: (function(_this) {
              return function() {
                return _this.__getEnabledKeys(data);
              };
            })(this),
            hasUserControl: true
          }),
          textarea: true,
          content_size: false,
          type: CUI.MultiInput,
          user_selectable: ez5.session.getPref("languages_user_selection"),
          onInit: (function(_this) {
            return function(field) {
              if (mode !== "editor") {
                return;
              }
              return CUI.Events.listen({
                type: "multi-input-control-update",
                node: field,
                call: function() {
                  return CUI.Events.trigger({
                    type: "editor-changed",
                    node: field
                  });
                }
              });
            };
          })(this)
        };
    }
  };

  LocaTextMultiColumn.prototype.isTextarea = function() {
    return true;
  };

  LocaTextMultiColumn.prototype.getManageOverflow = function() {
    return true;
  };

  LocaTextMultiColumn.prototype.renderEditorInput = function(data, top_level_data, render_opts) {
    var dom, result;
    result = LocaTextMultiColumn.__super__.renderEditorInput.call(this, data, top_level_data, render_opts);
    if (result instanceof HTMLElement) {
      dom = result;
    } else {
      dom = result.DOM;
    }
    this.__addLangAttributes(dom, "textarea");
    if (render_opts.mode === "editor-bulk") {
      this.__addLangBulkCheckbox(dom, data, "textarea");
    }
    return result;
  };

  return LocaTextMultiColumn;

})(LocaTextColumn);
// Generated by CoffeeScript 1.12.7
var NestedRow,
  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;

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

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

  NestedRow.prototype.initOpts = function() {
    NestedRow.__super__.initOpts.call(this);
    return this.addOpts({
      field: {
        check: function(v) {
          return v instanceof Field;
        }
      },
      nested_table_data: {
        check: "PlainObject"
      },
      row_data: {
        check: "PlainObject"
      },
      append_only: {
        check: Boolean
      },
      inside_nested_popup: {
        check: Boolean
      },
      render_as_summary: {
        check: Boolean
      },
      force_summary: {
        check: Boolean
      }
    });
  };

  NestedRow.prototype.render = function(opts) {
    var isReadOnly, ref, rf;
    switch (opts.nestedTableFunc) {
      case "renderForEditor":
        if (this._inside_nested_popup) {
          this._field.__inside_nested_popup = true;
        }
        isReadOnly = this._field.isReadOnly(this._row_data, this._nested_table_data, opts);
        if (this._append_only && this._row_data._in_db) {
          isReadOnly = true;
        }
        if (this._render_as_summary) {
          if (!((ref = this._field.FieldSchema.custom_settings) != null ? ref.show_in_summary : void 0) && !this._force_summary) {
            return;
          }
          if (this._field.isEmpty(this._row_data, this._nested_table_data, opts)) {
            return;
          }
          isReadOnly = true;
          this._field.__is_nested_summary = true;
        }
        rf = RenderedField.initField({
          field: this._field,
          data: this._row_data,
          top_level_data: this._nested_table_data,
          opts: opts
        });
        if (isReadOnly) {
          return rf.renderForEditorReadOnly();
        } else {
          return rf.renderForEditor();
        }
        break;
      case "renderForDetail":
        if (this._field.isEmpty(this._row_data, this._nested_table_data, opts)) {
          return;
        }
        return this._field.renderForDetail(this._row_data, null, opts);
      default:
        return this._field.renderForExpert(this._row_data, opts);
    }
  };

  NestedRow.prototype.getField = function() {
    return this._field;
  };

  return NestedRow;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var NestedTable, NestedTableIsVisibleException,
  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,
  slice = [].slice,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function NestedTable(fatherMask, FieldSchema) {
    this.fatherMask = fatherMask;
    this.FieldSchema = FieldSchema;
    this.getMaskPath = bind(this.getMaskPath, this);
    this.table = new Table(this.fatherMask.version, this.FieldSchema.other_table_id);
    if (this.fatherMask.nestedTableField && CUI.util.getObjectClass(this.fatherMask.nestedTableField) !== "TreeColumn") {
      this.mainMask = this.fatherMask.nestedTableField.mainMask;
    } else {
      this.mainMask = this.fatherMask;
    }
    this.mask = new Mask(this.mainMask.version, null, this.FieldSchema.mask, this);
    this.version = this.fatherMask.version;
    this.__cls = "ez5-" + CUI.util.toDash(CUI.util.getObjectClass(this));
    this.ColumnSchema = this.FieldSchema._other_column;
    this;
  }

  NestedTable.prototype.init = function() {
    var f, j, len1, ref;
    CUI.util.assert(this.table, "new " + (CUI.util.getObjectClass(this)), "table must be set", {
      fatherMask: this.fatherMask,
      FieldSchema: this.FieldSchema
    });
    CUI.util.assert(this.mainMask, "new " + (CUI.util.getObjectClass(this)), "mainMak could not be found", {
      fatherMask: this.fatherMask,
      FieldSchema: this.FieldSchema
    });
    CUI.util.assert(this.mask, "new " + (CUI.util.getObjectClass(this)), "mask was not set", {
      fatherMask: this.fatherMask,
      FieldSchema: this.FieldSchema
    });
    ref = this.mask.fields;
    for (j = 0, len1 = ref.length; j < len1; j++) {
      f = ref[j];
      f.init();
    }
  };

  NestedTable.prototype.navigationLimit = 50;

  NestedTable.prototype.depth = function() {
    return this.fatherMask.depth;
  };

  NestedTable.prototype.getFatherField = function() {
    if (this.fatherMask.nestedTableField) {
      return this.fatherMask.nestedTableField;
    } else {
      return null;
    }
  };

  NestedTable.prototype.insideNested = function() {
    if (this.getFatherField()) {
      return true;
    } else {
      return false;
    }
  };

  NestedTable.prototype.getSearchFilter = function(data, key, return_fields_with_filter) {
    var _data, _f, f, fields_with_filter, filter, idx, j, l, len1, len2, len3, m, main_filter, ref, ref1, ref2;
    if (key == null) {
      key = this.name();
    }
    if (return_fields_with_filter == null) {
      return_fields_with_filter = false;
    }
    filter = NestedTable.__super__.getSearchFilter.call(this, data, key);
    if (filter) {
      return filter;
    }
    if (!data[key] || data[key].length === 0) {
      return;
    }
    fields_with_filter = [];
    main_filter = {
      type: "complex",
      _unnest_counter: 0,
      _is_nested_index: this.isNestedIndex(),
      search: []
    };
    ref = data[key];
    for (idx = j = 0, len1 = ref.length; j < len1; idx = ++j) {
      _data = ref[idx];
      if (this.isNestedIndex()) {
        filter = {
          type: "nested",
          _unnest_counter: 0,
          path: this.fullName(),
          search: []
        };
      } else {
        filter = {
          type: "complex",
          _unnest_counter: 0,
          search: []
        };
      }
      main_filter.search.push(filter);
      ref1 = this.getFields("expert");
      for (l = 0, len2 = ref1.length; l < len2; l++) {
        f = ref1[l];
        if (f instanceof MaskSplitter) {
          continue;
        }
        _f = f.getSearchFilter(_data);
        if (_f) {
          fields_with_filter.push(f);
          filter.search.push(_f);
          if (_f._unnest) {
            filter._unnest_counter++;
          }
        }
      }
      if (filter.search.length === filter._unnest_counter) {
        main_filter.search.pop();
        ref2 = filter.search;
        for (m = 0, len3 = ref2.length; m < len3; m++) {
          _f = ref2[m];
          main_filter._unnest_counter++;
          main_filter.search.push(_f);
        }
      }
    }
    if (main_filter.search.length === main_filter._unnest_counter) {
      main_filter._unnest = true;
    }
    if (!fields_with_filter.length) {
      return null;
    } else if (return_fields_with_filter) {
      return fields_with_filter;
    } else {
      return main_filter;
    }
  };

  NestedTable.prototype.getFields = function(mode, opts, level) {
    if (opts == null) {
      opts = {};
    }
    if (level == null) {
      level = 0;
    }
    return this.mask.getFields(mode, opts);
  };

  NestedTable.prototype.getCSVDestinationFields = function(csvImporter, level, maxLevel) {
    var f, field, fields, idx, j, l, len1, len2, ref, ref1;
    if (level == null) {
      level = 0;
    }
    if (maxLevel == null) {
      maxLevel = 10;
    }
    if (level > maxLevel) {
      console.error("NestedTable.getCSVDestinationFields: ***recursion protection***");
      return [];
    }
    fields = [];
    ref = this.getFields("csv-import", {}, level);
    for (idx = j = 0, len1 = ref.length; j < len1; idx = ++j) {
      field = ref[idx];
      if (!(field instanceof Field)) {
        continue;
      }
      if (field instanceof MaskSplitter) {
        continue;
      }
      if (field.isReadOnly()) {
        continue;
      }
      ref1 = field.getCSVDestinationFields(csvImporter, level + 1);
      for (l = 0, len2 = ref1.length; l < len2; l++) {
        f = ref1[l];
        fields.push(f);
      }
    }
    return fields;
  };

  NestedTable.prototype.getSearchField = function() {
    return this.fullName();
  };

  NestedTable.prototype.invokeOnFields = function(mode, dive_nested, callback, data, depth) {
    var _data, _values, j, len1, value;
    if (depth == null) {
      depth = 0;
    }
    if (CUI.util.isArray(data)) {
      if (data.length === 1 && data[0][this.name()]) {
        this.mask.invokeOnFields(mode, dive_nested, callback, data[0][this.name()], depth + 1);
        return;
      }
      _data = [];
      for (j = 0, len1 = data.length; j < len1; j++) {
        value = data[j];
        _values = value != null ? value[this.name()] : void 0;
        if (!CUI.util.isArray(_values)) {
          continue;
        }
        _values = _values.filter(function(val) {
          return !!val;
        });
        if (!_values) {
          continue;
        }
        _data = _data.concat(_values);
      }
      return this.mask.invokeOnFields(mode, dive_nested, callback, _data, depth + 1);
    } else {
      return this.mask.invokeOnFields(mode, dive_nested, callback, data != null ? data[this.name()] : void 0, depth + 1);
    }
  };

  NestedTable.prototype.getMaskPath = function(path) {
    if (path == null) {
      path = [];
    }
    if (this.fatherMask.nestedTableField) {
      if (this.fatherMask.nestedTableField instanceof NestedTable) {
        this.fatherMask.nestedTableField.getMaskPath(path);
      }
    } else {
      path.push(this.fatherMask);
    }
    return path;
  };

  NestedTable.prototype.fullName = function() {
    if (this.fatherMask.nestedTableField) {
      return this.fatherMask.nestedTableField.fullName() + "." + this.name();
    } else {
      return this.fatherMask.table.name() + "." + this.name();
    }
  };

  NestedTable.prototype.getCSVName = function() {
    var csvName, fatherField, name;
    name = this.table.name().split("__").pop() + "[]";
    if (fatherField = this.getFatherField()) {
      csvName = fatherField.getCSVName();
      csvName = csvName.replace("[]", "[<n>]");
      name = csvName + "." + name;
    }
    return name;
  };

  NestedTable.prototype.getCSVRecordKeyPath = function() {
    if (this.fatherMask.nestedTableField) {
      return this.fatherMask.nestedTableField.getCSVRecordKeyPath() + "." + this.name() + "[]";
    } else {
      return this.fatherMask.table.name() + "." + this.name() + "[]";
    }
  };

  NestedTable.prototype.getQueryFieldBadge = function(data) {
    var badge, badgeDeferred, fields, hasValue, promiseValues, ref, ref1, sf, withoutValue;
    sf = this.getSearchFilter(data, null, true);
    badge = {
      name: this.fullNameLocalized(true),
      popoverContent: CUI.util.dump(sf)
    };
    withoutValue = $$("field.search.badge.without");
    hasValue = $$("field.search.badge.has_value");
    if (sf._has_value_filter || ((ref = sf.search) != null ? ref[0]._has_value_filter : void 0)) {
      badge.value = hasValue;
      return badge;
    } else if (sf._unset_filter || ((ref1 = data[this.name()]) != null ? ref1.length : void 0) === 0) {
      badge.value = withoutValue;
      return badge;
    }
    badgeDeferred = new CUI.Deferred();
    fields = this.getFields("expert");
    promiseValues = data[this.name()].map((function(_this) {
      return function(rowData) {
        var _promiseValues;
        _promiseValues = fields.map(function(field) {
          var badgeOrBadgePromise, isSingleNested, ref2, ref3;
          if (field instanceof NestedTable) {
            isSingleNested = field.getFields("expert").length === 1;
            if ((isSingleNested && ((ref2 = rowData[field.name()]) != null ? ref2.length : void 0)) || ((ref3 = rowData[field.name()]) != null ? ref3.some(function(_data) {
              return !_data._new;
            }) : void 0)) {
              return CUI.resolvedPromise(field.nameLocalized());
            }
            if (rowData[field.name() + ":unset"]) {
              return CUI.resolvedPromise(withoutValue + (" " + (field.nameLocalized())));
            }
            if (rowData[field.name() + ":has_value"]) {
              return CUI.resolvedPromise(hasValue + (" " + (field.nameLocalized())));
            }
            return CUI.resolvedPromise();
          }
          if (field instanceof MaskSplitter) {
            return CUI.resolvedPromise();
          }
          badgeOrBadgePromise = field.getQueryFieldBadge(rowData);
          return (function(_this) {
            return function(field) {
              var badgeValue, deferred;
              if (CUI.util.isPromise(badgeOrBadgePromise)) {
                deferred = new CUI.Deferred();
                badgeOrBadgePromise.done(function(badge) {
                  var badgeValue;
                  badgeValue = badge.value;
                  if (badgeValue === withoutValue) {
                    badgeValue += " " + (field.nameLocalized());
                  }
                  return deferred.resolve(badgeValue);
                });
                return deferred.promise();
              } else {
                badgeValue = badgeOrBadgePromise.value;
                if (badgeValue === withoutValue) {
                  badgeValue += " " + (field.nameLocalized());
                }
                return CUI.resolvedPromise(badgeValue);
              }
            };
          })(this)(field);
        });
        return CUI.whenAll(_promiseValues);
      };
    })(this));
    CUI.whenAll(promiseValues).done((function(_this) {
      return function() {
        var args;
        args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
        badge.value = args.map(function(argument) {
          return argument.args.map(function(_arg) {
            return _arg.args.map(function(__arg) {
              var ref2;
              return (__arg != null ? (ref2 = __arg.args) != null ? ref2[0] : void 0 : void 0) || __arg;
            }).filter(function(value) {
              return !CUI.util.isEmpty(value);
            }).join(",");
          }).filter(function(value) {
            return !CUI.util.isEmpty(value);
          });
        }).join(";");
        return badgeDeferred.resolve(badge);
      };
    })(this));
    return badgeDeferred.promise();
  };

  NestedTable.prototype.fullNameLocalized = function(include_top_level_mask, use_table_name, return_path) {
    return NestedTable.__super__.fullNameLocalized.call(this, include_top_level_mask, use_table_name, return_path, this.fatherMask);
  };

  NestedTable.prototype.name = function() {
    return "_nested:" + this.table.name();
  };

  NestedTable.prototype.nameLocalized = function() {
    return this.table.nameLocalizedWithoutInstance();
  };

  NestedTable.prototype.maskName = function() {
    return this.mainMask.name();
  };

  NestedTable.prototype.maskNameLocalized = function() {
    return this.mainMask.nameLocalized();
  };

  NestedTable.prototype.isEmpty = function(data, top_level_data, opts) {
    var ref;
    if (top_level_data == null) {
      top_level_data = {};
    }
    if (opts == null) {
      opts = {};
    }
    if (!CUI.util.isEmpty(top_level_data) && !CUI.util.isEmpty(opts.mode)) {
      return this.__allVisibleRowsAreEmpty(data, top_level_data, opts);
    }
    return !((ref = data[this.name()]) != null ? ref.length : void 0);
  };

  NestedTable.prototype.__allVisibleRowsAreEmpty = function(data, top_level_data, opts) {
    var j, l, len1, len2, nestedData, ref, ref1, rowField, rowFields;
    if (top_level_data == null) {
      top_level_data = {};
    }
    if (opts == null) {
      opts = {};
    }
    if (!((ref = data[this.name()]) != null ? ref.length : void 0)) {
      return true;
    }
    ref1 = data[this.name()];
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      nestedData = ref1[j];
      rowFields = this.getFields(opts.mode, opts);
      if (!rowFields) {
        continue;
      }
      for (l = 0, len2 = rowFields.length; l < len2; l++) {
        rowField = rowFields[l];
        if (rowField instanceof MaskSplitter) {
          continue;
        }
        if (!rowField.isEmpty(nestedData, top_level_data, opts)) {
          return false;
        }
      }
    }
    return true;
  };

  NestedTable.prototype.checkValue = function(data, top_level_data, opts) {
    var c, check_value, cv, f, j, l, len1, len2, len3, m, ref, ref1, ref2, row;
    if (opts == null) {
      opts = {};
    }
    if (this.isReadOnly()) {
      return true;
    }
    if (this.getOption(data, "bulk") && ((ref = this.getOption(data, "mode")) === "bulk_remove_all" || ref === "bulk_match_merge")) {
      if (data[this.name()].length === 0) {
        return true;
      } else {
        return false;
      }
    }
    if (!data[this.name()] || data[this.name()].length === 0) {
      if (this.isRequired() || this.getOption(data, "bulk")) {
        return false;
      } else {
        return true;
      }
    }
    check_value = true;
    ref1 = data[this.name()];
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      row = ref1[j];
      if (this._isRenderedAsPopup() && opts.check && row._new && !row._user_added_row && !this.__rowHasData(row, opts)) {
        continue;
      }
      ref2 = this.getFields("all");
      for (l = 0, len2 = ref2.length; l < len2; l++) {
        f = ref2[l];
        if (f instanceof MaskSplitter) {
          continue;
        }
        if (!(f.isVisible(opts.render_mode_header) || f.isVisible(opts.render_mode))) {
          continue;
        }
        cv = f.checkValue(row, null, opts);
        if (cv !== true) {
          if (CUI.util.isArray(cv)) {
            for (m = 0, len3 = cv.length; m < len3; m++) {
              c = cv[m];
              if (c !== true) {
                opts.problems.push(new CheckDataProblem({
                  field: f,
                  text: c || void 0,
                  renderedField: row[f.name() + ':rendered']
                }));
              }
            }
          } else {
            opts.problems.push(new CheckDataProblem({
              field: f,
              text: cv || void 0,
              renderedField: row[f.name() + ':rendered']
            }));
          }
          check_value = false;
        }
      }
    }
    if (check_value === false) {
      return $$("nested.table.check_value_failed", {
        field: this.fullNameLocalized()
      });
    } else {
      return true;
    }
  };

  NestedTable.prototype.getRowSaveData = function(row_data, opts) {
    var data_row, f, j, len1, ref, ref1;
    if (opts == null) {
      opts = {};
    }
    data_row = {};
    ref = this.getFields("all");
    for (j = 0, len1 = ref.length; j < len1; j++) {
      f = ref[j];
      if (f instanceof MaskSplitter) {
        continue;
      }
      if (ez5.version("6")) {
        if (!(f instanceof PrimaryKeyColumn) && (f.isReadOnly() || !f.isVisible("editor", opts)) && (!(f instanceof PoolField))) {
          if (f instanceof NestedTable) {
            if (!f.isReadOnly() || f.FieldSchema.edit.mode !== "off") {
              f.getSaveData(row_data, data_row, opts);
              if (((ref1 = data_row[f.name()]) != null ? ref1.length : void 0) === 0) {
                delete data_row[f.name()];
              }
            }
          }
          continue;
        }
      }
      if (opts.check) {
        data_row[f.name() + ':rendered'] = row_data[f.name() + ':rendered'];
      }
      if (row_data[f.name() + ":unset"]) {
        data_row[f.name() + ":unset"] = true;
      }
      if (row_data[f.name() + ":has_value"]) {
        data_row[f.name() + ":has_value"] = true;
      }
      f.getSaveData(row_data, data_row, opts);
    }
    return data_row;
  };

  NestedTable.prototype.getSaveData = function(data, save_data, opts) {
    var _data, add_data, bulk_key, clean_match_merge_data, i, idx, isRowEquals, j, k, l, len1, len2, len3, m, n, nested, ref, ref1, ref2, ref3, search_data, skip_from_mapping, v;
    if (opts == null) {
      opts = {};
    }
    this.initData(data, 'editor');
    save_data[this.name()] = [];
    isRowEquals = (function(_this) {
      return function(rowData, newRowData) {
        var f, j, len1, ref;
        ref = _this.getFields("all");
        for (j = 0, len1 = ref.length; j < len1; j++) {
          f = ref[j];
          if (f instanceof MaskSplitter) {
            continue;
          }
          if (!CUI.util.isEqual(rowData[f.name()], newRowData[f.name()])) {
            return false;
          }
        }
        return true;
      };
    })(this);
    add_data = (function(_this) {
      return function(_data, for_demo) {
        var f, found, have_not_empty, have_uniques, idx, j, l, len1, len2, newRowData, ref, ref1, rowData;
        if (for_demo == null) {
          for_demo = false;
        }
        if (!for_demo && !_this.__rowHasData(_data, opts)) {
          if (ez5.version("6") && _data._new && _data._user_added_row && !for_demo) {
            save_data[_this.name()].push({});
          }
          return;
        }
        found = false;
        newRowData = _this.getRowSaveData(_data, opts);
        ref = save_data[_this.name()];
        for (idx = j = 0, len1 = ref.length; j < len1; idx = ++j) {
          rowData = ref[idx];
          if (isRowEquals(rowData, newRowData)) {
            found = true;
            break;
          }
        }
        if (found) {
          have_not_empty = false;
          have_uniques = false;
          ref1 = _this.getFields("all");
          for (l = 0, len2 = ref1.length; l < len2; l++) {
            f = ref1[l];
            if (f instanceof MaskSplitter) {
              continue;
            }
            if (f.isUnique()) {
              have_uniques = true;
              continue;
            }
            if (!f.isEmpty(newRowData, {}, opts)) {
              have_not_empty = true;
              continue;
            }
          }
          if (have_uniques && !have_not_empty) {
            return;
          }
        }
        save_data[_this.name()].push(newRowData);
      };
    })(this);
    if (opts.demo_data) {
      for (i = j = 1; j <= 2; i = ++j) {
        add_data({}, true);
      }
      return;
    }
    if (((ref = data._template) != null ? ref[this.name()] : void 0) && this.getOption(data, "mode") === "append") {
      ref1 = data._template[this.name()];
      for (l = 0, len1 = ref1.length; l < len1; l++) {
        _data = ref1[l];
        add_data(_data);
      }
    }
    if (data[this.name()]) {
      if (save_data[this.name()].length > 0 && opts.prefer_template_over_mapping) {
        skip_from_mapping = true;
      } else {
        skip_from_mapping = false;
      }
      ref2 = data[this.name()];
      for (idx = m = 0, len2 = ref2.length; m < len2; idx = ++m) {
        _data = ref2[idx];
        if (_data._mapped_metadata_created && skip_from_mapping) {
          continue;
        }
        add_data(_data);
      }
    }
    bulk_key = this.getBulkSaveData(data, save_data, opts, "mode");
    if (!bulk_key) {
      return;
    }
    if (ez5.version("6.8")) {
      if (save_data[bulk_key] === "remove") {
        ref3 = save_data[this.name()];
        for (n = 0, len3 = ref3.length; n < len3; n++) {
          nested = ref3[n];
          for (k in nested) {
            v = nested[k];
            if (v === null) {
              delete nested[k];
            }
          }
        }
      } else if (save_data[bulk_key] === "remove_full_match") {
        save_data[bulk_key] = "remove";
      }
      if (save_data[bulk_key] === "match_merge") {
        clean_match_merge_data = function(inData) {
          var d, keys, unsets;
          d = CUI.util.copyObject(inData, true);
          unsets = [];
          keys = Object.keys(d);
          keys.forEach((function(_this) {
            return function(unsetKey) {
              var value;
              value = d[unsetKey];
              if (unsetKey.endsWith(":unset") && value) {
                unsets.push(unsetKey.replace(":unset", ""));
                return delete d[unsetKey];
              } else if (unsetKey.endsWith(":has_value") && value) {
                unsets.push(unsetKey.replace(":has_value", ""));
                return delete d[unsetKey];
              }
            };
          })(this));
          keys = Object.keys(d);
          keys.forEach((function(_this) {
            return function(key) {
              var len4, o, row, value;
              value = d[key];
              if (indexOf.call(unsets, key) >= 0) {
                return;
              }
              if (CUI.util.isEmpty(value)) {
                delete d[key];
                return;
              }
              if (CUI.util.isArray(value) && key.startsWith("_nested:")) {
                for (idx = o = 0, len4 = value.length; o < len4; idx = ++o) {
                  row = value[idx];
                  value[idx] = clean_match_merge_data(row);
                }
                return;
              }
              if (key.indexOf(":") > -1) {
                delete d[key];
                return;
              }
              if (key === "_DOM" || key === "_row_number" || key === "_new" || key === "_user_added_row") {
                delete d[key];
              }
              if (CUI.util.isString(value)) {
                value = value.trim();
                value = SearchUtil.removeQuotes(value, true);
                value = SearchUtil.removeSingleQuotes(value, true);
                return d[key] = value;
              }
            };
          })(this));
          return d;
        };
        save_data[this.name() + ":merge"] = save_data[this.name()][0];
        save_data[this.name()] = [];
        if (!CUI.util.isEmpty(save_data[this.name() + ":merge"])) {
          save_data[this.name() + ":merge"] = clean_match_merge_data(save_data[this.name() + ":merge"]);
        }
        search_data = CUI.util.copyObject(data[this.name() + ":options"]["search_data"], true);
        save_data[this.name() + ":match"] = clean_match_merge_data(search_data);
      }
    }
    if (save_data[bulk_key] === "remove_all") {
      if (save_data[this.name()].length) {
        throw new UserError({
          label: "main.editor.nested.bulk_remove_all.error",
          label_attrs: [this.nameLocalized()]
        });
      }
      return save_data[bulk_key] = "replace";
    }
  };

  NestedTable.prototype.hasUUIDOnAnyRow = function(data, opts) {
    var ex, j, len1, ref, row, tmp_save_data;
    try {
      tmp_save_data = {};
      this.getSaveData(data, tmp_save_data, opts);
      ref = tmp_save_data[this.name()];
      for (j = 0, len1 = ref.length; j < len1; j++) {
        row = ref[j];
        if (row._uuid) {
          return true;
        }
      }
    } catch (error) {
      ex = error;
      console.error("NestedTable.hasUUIDOnAnyRow: Error while checking for _uuid", ex);
    }
    return false;
  };

  NestedTable.prototype.isVisibleToSaveData = function(mode, header_mode, opts) {
    var data, visible;
    visible = NestedTable.__super__.isVisibleToSaveData.call(this, mode, header_mode, opts);
    if (ez5.version("6") && !visible && (opts != null ? opts.top_level_data : void 0) && !opts.check) {
      data = opts.top_level_data[opts.top_level_data._objecttype];
      return this.hasUUIDOnAnyRow(data, opts);
    }
    return visible;
  };

  NestedTable.prototype.isReadOnly = function(data, top_level_data, opts) {
    var ref, ref1, ref2;
    if (opts == null) {
      opts = {};
    }
    if (((ref = this.FieldSchema) != null ? ref.edit.mode : void 0) !== "edit") {
      return true;
    }
    if (((ref1 = this.FieldSchema) != null ? (ref2 = ref1.custom_settings) != null ? ref2.editor_frontend_mode : void 0 : void 0) === "readonly") {
      if (opts.get_save_data) {
        return false;
      } else {
        return true;
      }
    }
    return false;
  };

  NestedTable.prototype.isCondensedOutput = function(data, top_level_data, opts) {
    var ref, ref1, ref2, ref3;
    if (opts == null) {
      opts = {};
    }
    if (opts.nestedTableFunc === 'renderForDetail' && (((ref = this.FieldSchema) != null ? (ref1 = ref.custom_settings) != null ? ref1.condensed_output : void 0 : void 0) || opts.nested_condensed_output || ((ref2 = this.FieldSchema) != null ? (ref3 = ref2.custom_settings) != null ? ref3.format_output : void 0 : void 0) === "condensed")) {
      return true;
    } else {
      return false;
    }
  };

  NestedTable.prototype.isTableFormatOutput = function(opts) {
    var ref, ref1;
    if (opts.hasOwnProperty("nested_display_as_table")) {
      return !!opts.nested_display_as_table;
    }
    if (opts.nestedTableFunc === 'renderForDetail' && ((ref = this.FieldSchema) != null ? (ref1 = ref.custom_settings) != null ? ref1.format_output : void 0 : void 0) === "table") {
      return true;
    } else {
      return false;
    }
  };

  NestedTable.prototype.getSortFields = function() {
    return this.fullName();
  };

  NestedTable.prototype.isAppendOnly = function(data) {
    return this.FieldSchema.edit.append_only;
  };

  NestedTable.prototype.getReplacementRecord = function(data, key_prefix, use_array, record) {
    var add_row, j, len1, ref, ref1, row;
    if (!(data != null ? (ref = data[this.name()]) != null ? ref.length : void 0 : void 0)) {
      return;
    }
    key_prefix = key_prefix + this.name() + ".";
    add_row = (function(_this) {
      return function(row) {
        var f, j, len1, ref1, results;
        ref1 = _this.getFields("all");
        results = [];
        for (j = 0, len1 = ref1.length; j < len1; j++) {
          f = ref1[j];
          if (f instanceof MaskSplitter) {
            continue;
          }
          results.push(f.getReplacementRecord(row, key_prefix, true, record));
        }
        return results;
      };
    })(this);
    ref1 = data[this.name()];
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      row = ref1[j];
      if (this.__rowHasData(row)) {
        add_row(row);
        continue;
      }
    }
    return record;
  };

  NestedTable.prototype.getCheckInfo = function(mode) {
    var fields, warn, warnings;
    if (mode === "detail" || mode === "text") {
      return [];
    }
    warnings = NestedTable.__super__.getCheckInfo.call(this, mode);
    if (!this.FieldSchema.edit.as_table) {
      return warnings;
    }
    fields = this.getFields(mode);
    if (fields.length === 1) {
      if (fields[0].isRequired()) {
        warn = fields[0].getCheckInfo();
        if (warn.length > 0) {
          warnings.push($$("nested.table.explain_one_required_field", {
            warnings: warn.join("\n")
          }));
        }
      }
    }
    return warnings;
  };

  NestedTable.prototype.getInfoLabels = function(data, top_level_data, opts) {
    var _opts, field, j, lbls, len1, ref;
    lbls = NestedTable.__super__.getInfoLabels.call(this, data, top_level_data, opts);
    if (!opts.nested_single_column) {
      return lbls;
    }
    _opts = {
      mode: opts.mode
    };
    ref = opts.nested_fields;
    for (j = 0, len1 = ref.length; j < len1; j++) {
      field = ref[j];
      if (field instanceof MaskSplitter) {
        continue;
      }
      lbls.push.apply(lbls, field.getInfoLabels(data, top_level_data, _opts));
    }
    return lbls;
  };

  NestedTable.prototype.allowsCondensed = function(data, top_level_data, opts) {
    return false;
  };

  NestedTable.prototype.supportsEmptyRowAdd = function(opts) {
    return true;
  };

  NestedTable.prototype.nestedFieldAllowsCondensed = function(data, top_level_data, opts) {
    var field, j, l, len1, len2, ref, ref1, ref2, row;
    ref = opts.nested_fields;
    for (j = 0, len1 = ref.length; j < len1; j++) {
      field = ref[j];
      if (field instanceof MaskSplitter) {
        continue;
      }
      if (!((ref1 = data[this.name()]) != null ? ref1.length : void 0)) {
        if (!field.allowsCondensed(data, top_level_data, opts)) {
          return false;
        }
      } else {
        ref2 = data[this.name()];
        for (l = 0, len2 = ref2.length; l < len2; l++) {
          row = ref2[l];
          if (!field.allowsCondensed(data, top_level_data, opts)) {
            return false;
          }
        }
      }
    }
    return true;
  };

  NestedTable.prototype.nestedFieldAllowsList = function(data, top_level_data, opts) {
    var field, j, l, len1, len2, ref, ref1, ref2, row;
    ref = opts.nested_fields;
    for (j = 0, len1 = ref.length; j < len1; j++) {
      field = ref[j];
      if (field instanceof MaskSplitter) {
        continue;
      }
      if (!((ref1 = data[this.name()]) != null ? ref1.length : void 0)) {
        if (!field.allowsList(data, top_level_data, opts)) {
          return false;
        }
      } else {
        ref2 = data[this.name()];
        for (l = 0, len2 = ref2.length; l < len2; l++) {
          row = ref2[l];
          if (!field.allowsList(data, top_level_data, opts)) {
            return false;
          }
        }
      }
    }
    return true;
  };

  NestedTable.prototype._isRenderedAsPopup = function() {
    var ref;
    if (!ez5.version("6")) {
      return false;
    }
    return ((ref = this.FieldSchema.custom_settings) != null ? ref.editor_frontend_mode : void 0) === "popup";
  };

  NestedTable.prototype.__appendRowData = function(content, row_data, data, opts) {
    data[this.name()].push(row_data);
    return row_data._row_number = ++NestedTable.rowsAppended;
  };

  NestedTable.prototype.renderForDetail = function(data, top_level_data, opts) {
    if (opts == null) {
      opts = {};
    }
    opts.nestedTableFunc = 'renderForDetail';
    if (this.isTableFormatOutput(opts)) {
      return this.renderAsTable(data, top_level_data, opts);
    }
    return this.renderNestedRow(data, top_level_data, opts);
  };

  NestedTable.prototype.renderForTable = function(data, top_level_data, opts) {
    if (opts == null) {
      opts = {};
    }
    if (this.isEmpty(data, top_level_data, opts)) {
      return;
    }
    opts.render_value_only = true;
    return this.renderForDetail(data, top_level_data, opts);
  };

  NestedTable.prototype.renderForEditor = function(data, top_level_data, opts) {
    if (opts == null) {
      opts = {};
    }
    opts.nestedTableFunc = 'renderForEditor';
    if (this._isRenderedAsPopup()) {
      return this.renderAsPopup(data, top_level_data, opts);
    }
    return this.renderNestedRow(data, top_level_data, opts);
  };

  NestedTable.prototype.renderAsPopup = function(data, top_level_data, opts) {
    if (opts == null) {
      opts = {};
    }
    return this.renderNestedRow(data, top_level_data, opts);
  };

  NestedTable.prototype.renderForExpert = function(data, opts) {
    var row;
    if (opts == null) {
      opts = {};
    }
    opts.nestedTableFunc = 'renderForExpert';
    opts.fieldRenderType = 'expert';
    row = this.renderNestedRow(data, null, opts);
    data._DOM = row.DOM || row;
    return row;
  };

  NestedTable.prototype.renderForSort = function(data, _opts) {
    var field, fieldRendered, fieldsRendered, j, key, len1, opts, ref, value;
    fieldsRendered = [];
    if (ez5.version("6")) {
      fieldsRendered.push(NestedTable.__super__.renderForSort.call(this, data, _opts));
    }
    if (_opts.nested_level > 0) {
      return fieldsRendered;
    }
    opts = {};
    for (key in _opts) {
      value = _opts[key];
      opts[key] = value;
    }
    opts.nested_level = 1;
    ref = this.getFields(opts.mode);
    for (j = 0, len1 = ref.length; j < len1; j++) {
      field = ref[j];
      if (field instanceof MaskSplitter) {
        continue;
      }
      if (!(field instanceof LinkedObject) && !(field instanceof CustomDataType) && !(field instanceof TextColumn) && !(field instanceof DateColumn)) {
        continue;
      }
      data[field.fullName()] = {
        field: field,
        _fields: {},
        data: {}
      };
      fieldRendered = field.renderForSort(data, opts);
      if (fieldRendered) {
        fieldsRendered.push(fieldRendered);
      }
    }
    return fieldsRendered;
  };

  NestedTable.prototype.renderAsTable = function(data, top_level_data, opts) {
    var columns, field, fields, j, l, len1, len2, len3, m, ref, renderedField, row, row_data, rows, table;
    if (opts == null) {
      opts = {};
    }
    columns = [];
    fields = this.getFields(opts.mode);
    for (j = 0, len1 = fields.length; j < len1; j++) {
      field = fields[j];
      if (field instanceof MaskSplitter) {
        continue;
      }
      columns.push({
        name: field.fullName(),
        text: field.nameLocalized()
      });
    }
    rows = [];
    ref = data[this.name()];
    for (l = 0, len2 = ref.length; l < len2; l++) {
      row_data = ref[l];
      row = {};
      for (m = 0, len3 = fields.length; m < len3; m++) {
        field = fields[m];
        renderedField = null;
        if (field instanceof MaskSplitter) {
          continue;
        }
        if (field instanceof LinkedObject) {
          renderedField = field.renderDetailOutput(row_data, top_level_data, opts);
        }
        if (!renderedField) {
          renderedField = field.renderForTable(row_data, top_level_data, CUI.util.copyObject(opts));
        }
        row[field.fullName()] = renderedField;
      }
      rows.push(row);
    }
    table = new CUI.Table({
      rows: rows,
      maximize_horizontal: true,
      columns: columns
    });
    return this.renderRow(((function(_this) {
      return function() {
        return table;
      };
    })(this)), data, top_level_data, opts);
  };

  NestedTable.prototype.renderNestedRow = function(data, top_level_data, _opts) {
    var add_btn, cls, content, contentEl, fields, hl_opts, k, limit, opts, output, v;
    opts = {};
    for (k in _opts) {
      v = _opts[k];
      opts[k] = v;
    }
    this.initData(data, opts.mode);
    fields = this.getFields(opts.mode);
    opts.nested_fields = fields;
    if (opts.nested_level === void 0) {
      opts.nested_level = 0;
    } else {
      opts.nested_level = opts.nested_level + 1;
    }
    cls = ["ez5-nested"];
    if (this._isRenderedAsPopup()) {
      cls.push("ez5-nested--popup");
    }
    opts.nested_condensed_output = this.isCondensedOutput(data, top_level_data, opts);
    if (fields.length === 1 && !(fields[0] instanceof NestedTable)) {
      opts.nested_single_column = true;
      if (fields[0] instanceof NestedUUID) {
        opts.nested_single_column = false;
      }
    }
    if (opts.nested_condensed_output && !this.nestedFieldAllowsCondensed(data, top_level_data, opts)) {
      opts.nested_condensed_output = false;
    }
    opts.nested_render_as_block = !opts.nested_single_column;
    if (opts.nestedTableFunc === 'renderForEditor' || opts.nestedTableFunc === 'renderForExpert') {
      opts.nested_has_add_button = opts.nested_render_as_block || !this.supportsEmptyRowAdd(opts);
    }
    if (opts.nested_condensed_output) {
      if (opts.nested_render_as_block) {
        cls.push("ez5-nested--condensed-multi-column");
      } else {
        cls.push("ez5-nested--condensed");
      }
    }
    if (opts.nested_single_column) {
      if (!opts.nested_condensed_output && this.nestedFieldAllowsList(data, top_level_data, opts)) {
        cls.push("ez5-nested--list");
      }
      cls.push("ez5-nested--single-column");
    }
    if (opts.nested_render_as_block && !opts.nested_condensed_output) {
      cls.push("ez5-nested--has-groups");
    }
    if (opts.nestedTableFunc === 'renderForEditor' && this.supportsRowMove()) {
      cls.push("cui-data-form--movable-rows");
    }
    if (opts.mode === "editor-bulk" && this.depth() === 0) {
      CUI.Events.listen({
        type: "nested-bulk-option-changed",
        node: content,
        call: (function(_this) {
          return function(ev, info) {
            var ref, ref1;
            if (_this.getOption(data, "mode") === "bulk_match_merge" && ((ref = data[_this.name()]) != null ? ref.length : void 0) > 1) {
              data[_this.name()] = [data[_this.name()][0]];
            }
            if (_this.getOption(data, "mode") === "bulk_match_merge" && ((ref1 = data[_this.name()]) != null ? ref1.length : void 0) === 0) {
              data[_this.name()] = [
                {
                  "new": true,
                  _user_added_row: true
                }
              ];
            }
            return _this.__loadPage(content, 0, data, opts);
          };
        })(this)
      });
    }
    opts.appendMultipleRows = (function(_this) {
      return function(row_data) {
        var last_row;
        last_row = data[_this.name()][data[_this.name()].length - 1];
        if (opts.nested_has_add_button && (last_row != null ? last_row._new : void 0)) {
          _this.__removeRow(content, last_row, data, opts, false);
        }
        _this.__appendRowData(content, row_data, data, opts);
        if (content.__page !== _this.__getLastPage(content, data)) {
          _this.__loadLastPage(content, data, opts);
        } else {
          _this.appendRow(content, row_data, data, opts);
        }
        _this.__updateView(content, data, opts);
        CUI.Events.trigger({
          type: "editor-changed",
          node: content
        });
        return content;
      };
    })(this);
    content = CUI.dom.element("DIV", {
      "class": cls.join(" ")
    });
    output = this.renderRow(((function(_this) {
      return function() {
        return content;
      };
    })(this)), data, top_level_data, opts);
    if (!content.parentNode) {
      console.warn("NestedTable.__render: Content does not have a parent node", this.fullName(), data);
    }
    content.__navigation = new NavigationToolbar({
      size: "mini",
      append_count_label: false,
      onLoadPage: (function(_this) {
        return function(page) {
          _this.__loadPage(content, page, data, opts);
          return CUI.Events.trigger({
            type: "editor-changed",
            node: content
          });
        };
      })(this)
    });
    content.__navigation2 = new NavigationToolbar({
      size: "mini",
      append_count_label: false,
      onLoadPage: (function(_this) {
        return function(page) {
          _this.__loadPage(content, page, data, opts);
          return CUI.Events.trigger({
            type: "editor-changed",
            node: content
          });
        };
      })(this)
    });
    if (output instanceof CUI.Template) {
      output.append(content.__navigation, 'header_right');
      hl_opts = {
        "class": "ez5-nested-table-bottom-layout",
        maximize: true
      };
      hl_opts.right = {
        content: content.__navigation2
      };
      if (opts.nested_has_add_button && opts.nestedTableFunc !== "renderForDetail") {
        add_btn = new LocaButton({
          "class": 'ez5-nested-add-button',
          ui: "nested.table.add.button",
          icon: 'plus',
          text: $$("nested.table.add_button.label"),
          onClick: (function(_this) {
            return function() {
              _this.__appendNewRow(content, data, opts, true);
              _this.__updateView(content, data, opts);
              return CUI.Events.trigger({
                type: "editor-changed",
                node: content.parentNode
              });
            };
          })(this)
        });
        hl_opts.left = {
          content: add_btn
        };
        if (this.depth() === 0) {
          this.__top_level_add_button = add_btn;
        }
      }
      if (opts.mode === "editor-bulk") {
        contentEl = output.get("content");
        this.__bulkOptions = contentEl.querySelector(".cui-options.cui-data-field");
        contentEl.insertBefore((new CUI.HorizontalLayout(hl_opts)).DOM, this.__bulkOptions);
        if (!this.__shouldShowFirstEmptyRow() && !this._isRenderedAsPopup()) {
          CUI.dom.hideElement(this.__bulkOptions);
        }
      } else {
        output.append(new CUI.HorizontalLayout(hl_opts), 'content');
        output.get("content");
      }
    } else {
      CUI.dom.insertBefore(content, content.__navigation.DOM);
      CUI.dom.insertAfter(content, content.__navigation2.DOM);
    }
    if (opts.nested_single_column || opts.nested_condensed_output) {
      opts.render_value_only = true;
    } else {
      opts.render_value_only = false;
    }
    if (!_opts.for_print && this.supportsRowMove()) {
      new CUI.Sortable({
        element: content,
        axis: 'y',
        selector: ".cui-drag-handle-row",
        create: function(ev, target) {
          var row_data;
          row_data = CUI.dom.data(target, "row_data");
          if (!row_data) {
            return false;
          }
          if (row_data._new) {
            ev.stopPropagation();
            return false;
          }
          return true;
        },
        allowSort: (function(_this) {
          return function(ev, from_idx, to_idx) {
            if (content.__offset > 0) {
              from_idx += content.__offset - 1;
              to_idx += content.__offset - 1;
            }
            if (!!data[_this.name()][to_idx]) {
              if (!_this.isAppendOnly() || !data[_this.name()][to_idx]._in_db) {
                return true;
              }
            }
            return false;
          };
        })(this),
        sorted: (function(_this) {
          return function(ev, from_idx, to_idx) {
            if (content.__offset > 0) {
              from_idx += content.__offset - 1;
              to_idx += content.__offset - 1;
            }
            CUI.util.moveInArray(from_idx, to_idx, data[_this.name()], from_idx < to_idx);
            CUI.Events.trigger({
              type: "editor-changed",
              node: content
            });
            _this.__disableFirstRow(content);
          };
        })(this)
      });
    }
    CUI.dom.removeClass(content, "no-user-select");
    CUI.dom.setAttribute(output.DOM || output, "data-nested-level", opts.nested_level);
    if (opts.nestedTableFunc !== 'renderForDetail') {
      CUI.Events.listen({
        type: ["editor-changed", "search-input-change"],
        node: content,
        call: (function(_this) {
          return function(ev, info) {
            var div_row, div_rows, idx, j, last_page, ref, ref1, ref2, row_data;
            div_rows = CUI.dom.parents(ev.getTarget(), ".cui-data-form-row", content);
            if (div_rows.length === 0) {
              return;
            }
            div_row = div_rows[div_rows.length - 1];
            row_data = CUI.dom.data(div_row, "row_data");
            if (!row_data) {
              return;
            }
            if (opts.nested_has_add_button) {
              if (!_this.__rowHasData(row_data, opts)) {
                row_data._new = true;
              } else {
                delete row_data._new;
              }
              return;
            }
            if (!row_data._new) {
              return;
            }
            if (!_this.__rowHasData(row_data, opts)) {
              return;
            }
            delete row_data._new;
            _this.__appendRowData(content, row_data, data, opts);
            if (opts.mode === "editor-bulk" && ((ref = data[_this.name() + ":options"]) != null ? ref.mode : void 0) === "bulk_match_merge") {
              return;
            }
            last_page = _this.__getLastPage(content, data);
            if (content.__page !== last_page) {
              while (content.children.length >= 2) {
                CUI.dom.remove(content.firstElementChild);
              }
              content.__offset = last_page * content.__limit;
              content.__page = last_page;
              for (idx = j = ref1 = data[_this.name()].length - 2, ref2 = content.__offset; j >= ref2; idx = j += -1) {
                _this.prependRow(content, data[_this.name()][idx], data, opts);
              }
            }
            _this.__appendNewRow(content, data, opts);
            _this.__updateView(content, data, opts);
            CUI.Events.trigger({
              type: "editor-changed",
              node: content.parentNode
            });
          };
        })(this)
      });
    }
    this.initLoadedData(data, top_level_data, opts);
    if (opts.nested_page_size) {
      limit = opts.nested_page_size;
    } else {
      limit = this.navigationLimit;
    }
    content.__offset = 0;
    content.__limit = limit;
    this.__loadPage(content, 0, data, opts);
    return output;
  };

  NestedTable.prototype.initLoadedData = function(data, top_level_data, opts) {
    var idx, j, len1, ref, row_data;
    ref = data[this.name()];
    for (idx = j = 0, len1 = ref.length; j < len1; idx = ++j) {
      row_data = ref[idx];
      row_data._row_number = ++NestedTable.rowsAppended;
      row_data._in_db = true;
    }
    return this;
  };

  NestedTable.prototype.__getLastPage = function(content, data) {
    return Math.max(0, Math.floor((data[this.name()].length - 1) / content.__limit));
  };

  NestedTable.prototype.__loadLastPage = function(content, data, opts) {
    var last_page;
    last_page = this.__getLastPage(content, data);
    return this.__loadPage(content, last_page, data, opts);
  };

  NestedTable.prototype.__disableFirstRow = function(content) {
    var j, len1, row, rows;
    if (content.__offset === 0) {
      return;
    }
    rows = content.querySelectorAll(".cui-data-form-row .ez5-nested-fields");
    for (j = 0, len1 = rows.length; j < len1; j++) {
      row = rows[j];
      CUI.dom.removeClass(row, "cui-disabled");
    }
    CUI.dom.addClass(rows[0], "cui-disabled");
  };

  NestedTable.prototype.__loadPage = function(content, page, data, opts) {
    var idx, j, len, previousIndex, ref, ref1, row_data;
    content.__offset = content.__limit * page;
    content.__page = page;
    len = Math.min(content.__offset + content.__limit, data[this.name()].length);
    CUI.dom.empty(content);
    if (opts.mode === "editor" && this.supportsRowMove() && !opts.nested_only_first_row) {
      previousIndex = content.__offset - 1;
      if (previousIndex > 0) {
        row_data = data[this.name()][previousIndex];
        this.appendRow(content, row_data, data, opts);
        this.__disableFirstRow(content);
      }
    }
    for (idx = j = ref = content.__offset, ref1 = len; ref <= ref1 ? j < ref1 : j > ref1; idx = ref <= ref1 ? ++j : --j) {
      row_data = data[this.name()][idx];
      this.appendRow(content, row_data, data, opts);
      if (opts.nested_only_first_row) {
        break;
      }
    }
    if ((len === 0 || !opts.nested_has_add_button) && this.supportsEmptyRowAdd(opts)) {
      if (ez5.version("6") && opts.mode === "editor") {
        if (!this.isLimitedNested()) {
          if (this.__shouldShowFirstEmptyRow()) {
            this.__appendNewRow(content, data, opts);
          }
        }
      } else if (ez5.version("6") && opts.mode === "editor-bulk") {
        if (this.__shouldShowFirstEmptyRow()) {
          if (this.getOption(data, "mode") === "bulk_match_merge" && data[this.name()].length > 0) {
            return;
          }
          this.__appendNewRow(content, data, opts);
        }
      } else {
        this.__appendNewRow(content, data, opts);
      }
    }
    this.__updateView(content, data, opts);
  };

  NestedTable.prototype.__shouldShowFirstEmptyRow = function() {
    var ref, show_first_empty_row;
    show_first_empty_row = (ref = this.FieldSchema.custom_settings) != null ? ref.show_first_empty_nested : void 0;
    return show_first_empty_row || CUI.util.isNull(show_first_empty_row);
  };

  NestedTable.prototype.__shouldAutoReplaceLastRow = function(opts) {
    return this.supportsEmptyRowAdd(opts) && this.__shouldShowFirstEmptyRow() && !this.isLimitedNested();
  };

  NestedTable.prototype.isLimitedNested = function() {
    var field, fields, j, len1;
    fields = this.getFields("editor");
    for (j = 0, len1 = fields.length; j < len1; j++) {
      field = fields[j];
      if (field instanceof MaskSplitter) {
        continue;
      }
      if (!field.isReadOnly()) {
        return false;
      }
    }
    return true;
  };

  NestedTable.prototype.__findRowByData = function(content, row_data) {
    var child, j, len1, ref;
    ref = content.children;
    for (j = 0, len1 = ref.length; j < len1; j++) {
      child = ref[j];
      if (CUI.dom.data(child, "row_data") === row_data) {
        return child;
      }
    }
    return null;
  };

  NestedTable.prototype.__removeRow = function(content, row_data, data, opts, auto_append_new_row) {
    var wasLastRow;
    if (auto_append_new_row == null) {
      auto_append_new_row = true;
    }
    wasLastRow = data[this.name()].length === 1;
    CUI.dom.remove(this.__findRowByData(content, row_data, data));
    CUI.util.removeFromArray(row_data, data[this.name()]);
    if (wasLastRow && this.__shouldAutoReplaceLastRow(opts) && auto_append_new_row) {
      this.__appendNewRow(content, data, opts, false);
    }
    if (opts.mode === "editor-bulk" && this.__bulkOptions && !this.__shouldShowFirstEmptyRow() && data[this.name()].length === 0) {
      CUI.dom.hideElement(this.__bulkOptions);
    }
    return this;
  };

  NestedTable.prototype.__appendNewRow = function(content, data, opts, user_added) {
    var hl, popupElement, row_data;
    if (user_added == null) {
      user_added = false;
    }
    if (opts.nestedTableFunc === "renderForDetail") {
      return;
    }
    row_data = {
      _new: true,
      _row_number: NestedTable.rowsAppended
    };
    if (user_added) {
      row_data._user_added_row = true;
    }
    if (opts.nested_has_add_button) {
      this.__appendRowData(content, row_data, data);
    }
    if (opts.nested_has_add_button && content.__offset + content.__limit < data[this.name()].length) {
      this.__loadPage(content, Math.floor((data[this.name()].length - 1) / content.__limit), data, opts);
    } else {
      hl = this.appendRow(content, row_data, data, opts);
    }
    if (user_added && opts.nestedTableFunc === 'renderForEditor' && this._isRenderedAsPopup() && opts.nested_has_add_button) {
      popupElement = CUI.dom.data(hl, "edit") || content;
      this.__showNestedPopup(content, row_data, data, popupElement, true, opts);
    }
  };

  NestedTable.prototype.__showNestedPopup = function(content, row_data, data, popupElement, newElement, opts) {
    var __cancel, __removeRenderedFields, applyButton, checkData, checkServerValidation, checkStatus, copyOpts, currentEditorChangedListener, currentProblems, detailsButton, editorChangedListener, elem, ex, initialData, initialSaveData, j, len1, popover, popoverContent, popupRowOpts, ref, registerEditorChangedListener, validationLabel, validationWrapper;
    initialSaveData = {};
    try {
      this.getSaveData(data, initialSaveData, {
        copy: true
      });
    } catch (error) {
      ex = error;
      console.error("NestedTable.__showNestedPopup: Error while getting initial save data", ex);
    }
    currentProblems = [];
    if (opts.__waits) {
      opts.__waits.splice(0);
    }
    copyOpts = CUI.util.copyObjectV2(opts, true);
    popupRowOpts = CUI.util.copyObjectV2(opts, true);
    popupRowOpts.nestedTableFunc = 'renderForEditor';
    popupRowOpts.rendered_in_popup = true;
    initialData = CUI.util.copyObjectV2(row_data, true);
    __removeRenderedFields = function(d) {
      var k, obj, results, v;
      results = [];
      for (k in d) {
        v = d[k];
        if (k.indexOf(":rendered") > -1) {
          results.push(delete d[k]);
        } else if (CUI.util.isArray(v)) {
          results.push((function() {
            var j, len1, results1;
            results1 = [];
            for (j = 0, len1 = v.length; j < len1; j++) {
              obj = v[j];
              results1.push(__removeRenderedFields(obj));
            }
            return results1;
          })());
        } else {
          results.push(void 0);
        }
      }
      return results;
    };
    __cancel = (function(_this) {
      return function() {
        var k, ref, v;
        for (k in row_data) {
          v = row_data[k];
          delete row_data[k];
        }
        ref = CUI.util.copyObjectV2(initialData, true);
        for (k in ref) {
          v = ref[k];
          row_data[k] = v;
        }
        __removeRenderedFields(row_data);
        if (newElement) {
          _this.__removeRow(content, row_data, data, opts);
        }
        popover.destroy();
        delete _this.__nested_popover;
        return CUI.Events.trigger({
          type: "editor-changed",
          node: content
        });
      };
    })(this);
    applyButton = new LocaButton({
      text: $$("base.apply"),
      primary: true,
      onClick: (function(_this) {
        return function() {
          var page;
          popover.destroy();
          delete _this.__nested_popover;
          page = Math.min(_this.__getLastPage(content, data), content.__page);
          _this.__loadPage(content, page, data, copyOpts);
          return CUI.Events.trigger({
            type: "editor-changed",
            node: content
          });
        };
      })(this)
    });
    applyButton.disable();
    validationLabel = new LocaLabel({
      "class": "ez5-editor-required-message",
      loca_key: "editor.required_input_message",
      group: "required"
    });
    detailsButton = new LocaButton({
      loca_key: "editor.required_details_btn",
      size: "mini",
      group: "required",
      onClick: (function(_this) {
        return function() {
          var j, len1, p, problemLabel, problemPopover, problems;
          if (currentProblems.length === 0) {
            return;
          }
          problems = [];
          for (j = 0, len1 = currentProblems.length; j < len1; j++) {
            p = currentProblems[j];
            problems.push("* " + p.getProblemText());
          }
          problemLabel = new CUI.Label({
            text: problems.join("\n"),
            markdown: true,
            multiline: true
          });
          problemPopover = new CUI.Popover({
            element: detailsButton,
            backdrop: {
              policy: "click"
            },
            placement: "n",
            placements: ["n", "ne", "nw"],
            pane: {
              padded: true,
              title: $$("editor.required_details.popover.title"),
              content: problemLabel
            }
          });
          return problemPopover.show();
        };
      })(this)
    });
    validationWrapper = CUI.dom.div("ez5-required-message");
    CUI.dom.append(validationWrapper, [
      validationLabel, new CUI.Buttonbar({
        buttons: [detailsButton]
      }).DOM
    ]);
    CUI.dom.hideElement(validationWrapper);
    popoverContent = CUI.dom.div("ez5-nested-fields");
    ref = this.renderRowCenter(row_data, data, popupRowOpts);
    for (j = 0, len1 = ref.length; j < len1; j++) {
      elem = ref[j];
      if (elem) {
        if (elem.DOM) {
          elem = elem.DOM;
        }
        popoverContent.appendChild(elem);
      }
    }
    checkServerValidation = (function(_this) {
      return function(_data, opts) {
        var f, fname, l, len2, problem, ref1, ref2, ref3, serverError, validationOpts;
        ref1 = _this.getFields("editor");
        for (l = 0, len2 = ref1.length; l < len2; l++) {
          f = ref1[l];
          if (f instanceof MaskSplitter) {
            continue;
          }
          fname = f.name();
          problem = (ref2 = _data[fname + ":serverValidationProblem"]) != null ? ref2.problem : void 0;
          serverError = (ref3 = _data[fname + ":serverValidationProblem"]) != null ? ref3.serverError : void 0;
          if (problem) {
            validationOpts = {
              rowIndex: serverError.row_index,
              field: serverError.field
            };
            if (problem && !f.checkServerValidationProblemHandled(_data, data, serverError.message, validationOpts)) {
              problem.setRenderedField(_data[fname + ":rendered"]);
              problem.setProblemClass('ez5-check-failed-column');
            }
          }
        }
      };
    })(this);
    checkData = (function(_this) {
      return function(_data, _save_data, _opts) {
        var check_data, check_opts, cv, el, key, l, len2, len3, len4, m, n, problem, ref1, ref2, ref3, targetDOM;
        targetDOM = popover.getPane().getFillScreenState() ? popover.getPane().DOM : popover.DOM;
        ref1 = ['ez5-check-failed-column', 'has-failed-content', 'ez5-check-failed-row'];
        for (l = 0, len2 = ref1.length; l < len2; l++) {
          key = ref1[l];
          ref2 = CUI.dom.matchSelector(targetDOM, '.' + key);
          for (m = 0, len3 = ref2.length; m < len3; m++) {
            el = ref2[m];
            el.classList.remove(key);
          }
        }
        checkServerValidation(row_data, _opts);
        check_opts = CUI.util.copyObjectV2(_opts, true);
        check_opts.check = true;
        check_opts.render_mode = "editor";
        check_opts.render_mode_header = "editor-header";
        check_opts.problems = [];
        check_opts.check_server_validation_errors = true;
        check_data = CUI.util.copyObjectV2(data, true);
        check_data[_this.name()] = [row_data];
        cv = _this.checkValue(check_data, {}, check_opts);
        currentProblems.length = 0;
        if (check_opts.problems.length > 0) {
          ref3 = check_opts.problems;
          for (n = 0, len4 = ref3.length; n < len4; n++) {
            problem = ref3[n];
            problem.setProblemClass('ez5-check-failed-column');
            currentProblems.push(problem);
          }
          return false;
        }
        return true;
      };
    })(this);
    popover = new CUI.Popover({
      "class": "ez5-nested-editor-popover",
      element: popupElement,
      placement: "w",
      placements: ["w", "e", "n", "s"],
      backdrop: {
        policy: "modal"
      },
      pane: {
        header_left: new CUI.Label({
          text: $$("nested.table.popup.editor.header", {
            field_name: this.nameLocalized()
          })
        }),
        maximize: true,
        content: popoverContent,
        header_right: [
          CUI.Pane.getToggleFillScreenButton(), new LocaButton({
            loca_key: "editor.popover.button.close",
            icon: "close",
            onClick: (function(_this) {
              return function(ev) {
                return __cancel();
              };
            })(this)
          })
        ],
        footer_right: (function(_this) {
          return function() {
            return [
              validationWrapper, new LocaButton({
                text: $$("base.cancel"),
                onClick: function() {
                  return __cancel();
                }
              }), applyButton
            ];
          };
        })(this)
      }
    });
    checkStatus = (function(_this) {
      return function() {
        var actualSaveData, hasChanges, hasValidationErrors;
        actualSaveData = {};
        try {
          _this.getSaveData(data, actualSaveData, {});
        } catch (error) {
          ex = error;
          console.error("NestedTable.__showNestedPopup: Error while getting actual save data", ex);
        }
        hasValidationErrors = !checkData(data, actualSaveData, popupRowOpts);
        hasChanges = !CUI.util.isEqual(initialSaveData, actualSaveData);
        if (!hasValidationErrors && hasChanges) {
          applyButton.enable();
        } else {
          applyButton.disable();
        }
        if (currentProblems.length > 0) {
          return CUI.dom.showElement(validationWrapper);
        } else {
          return CUI.dom.hideElement(validationWrapper);
        }
      };
    })(this);
    this.__nested_popover = popover;
    popover.show();
    checkStatus();
    editorChangedListener = (function(_this) {
      return function() {
        return checkStatus();
      };
    })(this);
    currentEditorChangedListener = null;
    registerEditorChangedListener = (function(_this) {
      return function(node) {
        if (currentEditorChangedListener) {
          currentEditorChangedListener.destroy();
        }
        return currentEditorChangedListener = CUI.Events.listen({
          type: "editor-changed",
          node: node,
          call: editorChangedListener
        });
      };
    })(this);
    registerEditorChangedListener(popover);
    CUI.Events.listen({
      type: "start-fill-screen",
      node: popover.getPane(),
      call: (function(_this) {
        return function() {
          return registerEditorChangedListener(popover.getPane());
        };
      })(this)
    });
    CUI.Events.listen({
      type: "end-fill-screen",
      node: popover.getPane(),
      call: (function(_this) {
        return function() {
          return registerEditorChangedListener(popover);
        };
      })(this)
    });
  };

  NestedTable.prototype.resizeNestedPopup = function(content) {
    if (this.__nested_popover) {
      this.__nested_popover.autoSize();
    }
  };

  NestedTable.prototype.getNestedPopup = function() {
    return this.__nested_popover;
  };

  NestedTable.prototype.getDataAsString = function(data, top_level_data) {
    var row_data;
    return ((function() {
      var j, len1, ref, results;
      ref = data[this.name()];
      results = [];
      for (j = 0, len1 = ref.length; j < len1; j++) {
        row_data = ref[j];
        results.push(row_data != null ? row_data._row_number : void 0);
      }
      return results;
    }).call(this)).join(",");
  };

  NestedTable.rowsAppended = 0;

  NestedTable.prototype.__updateView = function(content, data, opts) {
    var child, disableTrashButton, idx, info, j, len, ref, ref1, ref2;
    if (opts.nestedTableFunc === 'renderForEditor' || opts.nestedTableFunc === 'renderForExpert') {
      len = content.children.length;
      for (idx = j = 0, ref = len; 0 <= ref ? j < ref : j > ref; idx = 0 <= ref ? ++j : --j) {
        child = content.children[idx];
        info = CUI.dom.data(child);
        if (!(info != null ? info.row_data : void 0)) {
          continue;
        }
        disableTrashButton = this.supportsEmptyRowAdd(opts) && info.row_data._new && !opts.nested_has_add_button;
        if (disableTrashButton) {
          CUI.dom.addClass(info.move, 'is-hidden');
          if ((ref1 = info.trash) != null) {
            ref1.disable();
          }
        } else {
          if ((ref2 = info.trash) != null) {
            ref2.enable();
          }
          if (data[this.name()].length >= 2) {
            CUI.dom.removeClass(info.move, 'is-hidden');
          } else {
            CUI.dom.addClass(info.move, 'is-hidden');
          }
        }
      }
    }
    content.__navigation.update({
      offset: content.__offset,
      limit: content.__limit,
      count: data[this.name()].length
    });
    content.__navigation2.update({
      offset: content.__offset,
      limit: content.__limit,
      count: data[this.name()].length
    });
  };

  NestedTable.prototype.prependRow = function(content, row_data, data, opts) {
    return this.appendRow(content, row_data, data, opts, 0);
  };

  NestedTable.prototype.appendRow = function(content, row_data, data, opts, pos) {
    var center, div, editbutton, hl, moreRowTools, move, name1, read_only, ref, ref1, ref2, replace_wrapper, rowCenterContent, rowTools, searchData, search_hl, search_opts, search_wrapper, trash;
    if (pos == null) {
      pos = null;
    }
    CUI.util.assert(CUI.util.isPlainObject(row_data) && CUI.util.isPlainObject(data), "NestedTable.appendRow", "row_data and data need to be PlainObject");
    if (opts.nestedTableFunc === 'renderForDetail') {
      div = CUI.dom.element("DIV", {
        "class": "ez5-nested-fields"
      });
      if (opts.nested_render_as_block && !opts.nested_condensed_output) {
        CUI.dom.addClass(div, "ez5-field-group");
      }
      CUI.dom.append(div, this.renderRowCenter(row_data, data, opts));
      CUI.dom.setAttribute(div, "ui", "nested.table.row:" + opts.mode);
      content.appendChild(div);
      return div;
    }
    read_only = (this.isAppendOnly() && row_data._in_db && opts.nestedTableFunc === 'renderForEditor') || false;
    opts.read_only = read_only;
    if (opts.nestedTableFunc === 'renderForEditor' && this.supportsRowMove()) {
      move = CUI.dom.element("DIV", {
        "class": "cui-drag-handle-row is-hidden",
        ui: "nested.table.drag.handle"
      });
    }
    if (opts.nestedTableFunc === 'renderForEditor' && this._isRenderedAsPopup()) {
      editbutton = new LocaButton({
        icon: "fa-pencil",
        appearance: "flat",
        ui: "nested.table.edit.button",
        onClick: (function(_this) {
          return function() {
            return _this.__showNestedPopup(content, row_data, data, editbutton.DOM, false, opts);
          };
        })(this)
      });
    }
    if (!read_only) {
      trash = new LocaButton({
        icon: "fa-trash-o",
        appearance: "flat",
        ui: "nested.table.trash.button",
        tooltip: {
          text: $$("nested.table.trash.button.tooltip." + opts.mode)
        },
        onMouseenter: (function(_this) {
          return function() {
            if (!trash.isDisabled()) {
              return CUI.dom.addClass(hl, "cui-data-form-row--trash");
            }
          };
        })(this),
        onMouseleave: (function(_this) {
          return function() {
            if (!trash.isDisabled()) {
              return CUI.dom.removeClass(hl, "cui-data-form-row--trash");
            }
          };
        })(this),
        onClick: (function(_this) {
          return function() {
            var page, wasLastRow;
            wasLastRow = data[_this.name()].length === 1;
            _this.__removeRow(content, row_data, data, opts);
            if (wasLastRow && data[_this.name()].length > 0) {
              _this.__loadPage(content, content.__page, data, opts);
            } else {
              page = Math.min(_this.__getLastPage(content, data), content.__page);
              _this.__loadPage(content, page, data, opts);
            }
            return CUI.Events.trigger({
              type: "editor-changed",
              node: content
            });
          };
        })(this)
      });
      trash.disable();
    }
    rowTools = [trash];
    if (editbutton) {
      rowTools.unshift(editbutton);
    }
    moreRowTools = this.renderRowTools(row_data, data, opts);
    if (moreRowTools) {
      rowTools = rowTools.concat(moreRowTools);
    }
    hl = new CUI.HorizontalLayout({
      maximize_vertical: false,
      maximize_horizontal: true,
      "class": "cui-data-form-row",
      left: {
        content: move
      },
      right: {
        "class": "ez5-nested-buttonbar-vertical",
        content: rowTools
      },
      center: {
        "class": "ez5-nested-fields"
      }
    });
    CUI.dom.data(hl.DOM, "row_data", row_data);
    if (!read_only) {
      CUI.dom.data(hl.DOM, "move", move);
      CUI.dom.data(hl.DOM, "trash", trash);
      if (editbutton) {
        CUI.dom.data(hl.DOM, "edit", editbutton);
      }
    } else {
      CUI.dom.addClass(hl, "cui-data-form-row--read-only");
    }
    center = hl.center();
    if (opts.nested_render_as_block) {
      CUI.dom.addClass(center, "ez5-field-group");
    }
    if (opts.mode === "editor-bulk" && ((ref = data[this.name() + ":options"]) != null ? ref.mode : void 0) === "bulk_match_merge") {
      opts.include_unset_btn = true;
    }
    rowCenterContent = this.renderRowCenter(row_data, data, opts);
    if (this._isRenderedAsPopup() && rowCenterContent.every(function(el) {
      return !el;
    })) {
      rowCenterContent = [
        new CUI.EmptyLabel({
          text: $$("nested.table.summary.empty")
        })
      ];
    }
    CUI.dom.append(center, rowCenterContent);
    CUI.dom.setAttribute(center, "ui", "nested.table.row:" + opts.mode);
    if (pos !== null) {
      CUI.dom.insertChildAtPosition(content, hl.DOM, pos);
    } else if (((ref1 = CUI.dom.data(content.lastElementChild, "row_data")) != null ? ref1._new : void 0) && !opts.nested_has_add_button) {
      CUI.dom.insertBefore(content.lastElementChild, hl.DOM);
    } else {
      content.appendChild(hl.DOM);
    }
    if (opts.mode === "editor-bulk" && this.__bulkOptions) {
      CUI.dom.showElement(this.__bulkOptions);
    }
    if (this.depth() === 0 && opts.mode === "editor-bulk" && ((ref2 = data[this.name() + ":options"]) != null ? ref2.mode : void 0) === "bulk_match_merge") {
      search_hl = new CUI.HorizontalLayout({
        maximize_vertical: false,
        maximize_horizontal: true,
        "class": "cui-data-form-row",
        center: {
          "class": "ez5-nested-fields"
        }
      });
      search_opts = CUI.util.copyObject(opts, true);
      search_opts.nestedTableFunc = 'renderForExpert';
      search_opts.bulk_expert = true;
      search_opts.nestedSearchAndReplace = true;
      searchData = {};
      if (data[name1 = this.name() + ":options"] == null) {
        data[name1] = {};
      }
      data[this.name() + ":options"]["search_data"] = searchData;
      search_hl.append(this.renderRowCenter(searchData, null, search_opts), "center");
      if (opts.nested_render_as_block) {
        CUI.dom.addClass(search_hl.center(), "ez5-field-group");
      }
      search_wrapper = CUI.dom.wrapWithDiv(search_hl.DOM, CUI.dom.div("search-and-replace-wrapper search-and-replace-wrapper--search"));
      search_wrapper.prepend(new CUI.Label({
        text: $$("nested.table.search_and_replace.search.label"),
        icon: "search",
        appearance: "title"
      }).DOM);
      replace_wrapper = CUI.dom.wrapWithDiv(hl.DOM, CUI.dom.div("search-and-replace-wrapper search-and-replace-wrapper--replace"));
      replace_wrapper.prepend(new CUI.Label({
        text: $$("nested.table.search_and_replace.replace.label"),
        icon: "fa-pencil-square-o",
        appearance: "title"
      }).DOM);
      content.prepend(search_wrapper);
      CUI.dom.addClass(content, "is-bulk-search-and-replace");
    } else {
      if (CUI.dom.hasClass(content, "is-bulk-search-and-replace")) {
        CUI.dom.removeClass(content, "is-bulk-search-and-replace");
      }
    }
    return hl;
  };

  NestedTable.prototype.renderRowTools = function(row_data, data, opts) {};

  NestedTable.prototype.renderRowCenter = function(row_data, data, opts) {
    var arr, f, fieldMatchesFilter, filterText, force_summary, j, len1, nestedFields, nestedFieldsRenderer, nestedRow, ownNameMatches, rendered_in_popup, rowContent, show_as_summary, simpleSplitContent, splitter, splitterContent, splitterOpts, splitters;
    show_as_summary = false;
    force_summary = false;
    if (ez5.version("6")) {
      show_as_summary = opts.nestedTableFunc === 'renderForEditor' && this._isRenderedAsPopup() && !opts.rendered_in_popup;
      rendered_in_popup = opts.rendered_in_popup;
      opts.rendered_in_popup = false;
      if (show_as_summary) {
        force_summary = this.getFields(opts.mode, opts).every(function(f) {
          var ref, ref1;
          return !((ref = f.FieldSchema) != null ? (ref1 = ref.custom_settings) != null ? ref1.show_in_summary : void 0 : void 0);
        });
      }
    }
    splitterOpts = CUI.util.copyObject(opts);
    splitterOpts.data = row_data;
    splitterOpts.__is_in_nested_summary = show_as_summary || force_summary;
    splitters = [];
    arr = [];
    nestedFields = this.getFields(opts.mode, opts);
    if (opts.fieldFilterText) {
      filterText = opts.fieldFilterText;
      ownNameMatches = (ez5.session.isDebug() && this.name && this.name().toLowerCase().indexOf(filterText) >= 0) || (this.nameLocalized && this.nameLocalized().toLowerCase().indexOf(filterText) >= 0);
      if (!ownNameMatches) {
        fieldMatchesFilter = function(f) {
          var childField, j, len1, ref;
          if (ez5.session.isDebug() && f.name && f.name().toLowerCase().indexOf(filterText) >= 0) {
            return true;
          }
          if (f.nameLocalized && f.nameLocalized().toLowerCase().indexOf(filterText) >= 0) {
            return true;
          }
          if (f instanceof NestedTable) {
            ref = f.getFields(opts.mode, opts) || [];
            for (j = 0, len1 = ref.length; j < len1; j++) {
              childField = ref[j];
              if (childField instanceof MaskSplitter) {
                continue;
              }
              if (fieldMatchesFilter(childField)) {
                return true;
              }
            }
          }
          return false;
        };
        nestedFields = nestedFields.filter(function(f) {
          if (f instanceof MaskSplitter) {
            return true;
          }
          return fieldMatchesFilter(f);
        });
      }
    }
    for (j = 0, len1 = nestedFields.length; j < len1; j++) {
      f = nestedFields[j];
      if (f instanceof MaskSplitter) {
        if (typeof f.isSimpleSplit === "function" ? f.isSimpleSplit() : void 0) {
          simpleSplitContent = f.getFieldsRenderer({
            field: f
          }).render(splitterOpts);
          arr.push(simpleSplitContent);
          continue;
        } else if (f instanceof MaskSplitterBegin) {
          nestedFieldsRenderer = new NestedFieldsRenderer();
          splitter = f.getFieldsRenderer({
            field: f
          });
          splitter.addField(nestedFieldsRenderer);
          splitter.__is_in_nested_summary = show_as_summary || force_summary;
          splitters.push(nestedFieldsRenderer);
          continue;
        } else if (f instanceof MaskSplitterEnd) {
          splitter = splitters.pop();
          if (!splitter) {
            continue;
          }
          splitterContent = splitter.getFather().render(splitterOpts);
          arr.push(splitterContent);
          continue;
        } else {
          console.warn("NestedTable.renderRowCenter :: Ignored MaskSplitter.", f);
          continue;
        }
      }
      nestedRow = new NestedRow({
        field: f,
        nested_table_data: data,
        row_data: row_data,
        render_as_summary: show_as_summary,
        force_summary: force_summary,
        inside_nested_popup: rendered_in_popup
      });
      splitter = splitters[splitters.length - 1];
      if (splitter) {
        splitter.addField(nestedRow);
      } else {
        rowContent = nestedRow.render(opts);
        arr.push(rowContent);
      }
    }
    return arr;
  };

  NestedTable.prototype.supportsRowMove = function() {
    return this.__getNestedSortFields().length === 0;
  };

  NestedTable.prototype.__getNestedSortFields = function() {
    var nestedSortFields;
    nestedSortFields = this.FieldSchema.nested_sort;
    if (!nestedSortFields) {
      return [];
    }
    nestedSortFields = nestedSortFields.filter(function(nestedSortField) {
      return !CUI.util.isEmpty(nestedSortField.order) && !CUI.util.isEmpty(nestedSortField.field);
    });
    return nestedSortFields;
  };

  NestedTable.prototype.initData = function(data, mode) {
    CUI.util.assert(CUI.util.isPlainObject(data), "NestedTable.initData", "data needs to be PlainObject", {
      data: data
    });
    if (!data[this.name()]) {
      data[this.name()] = [];
    }
    if (data._template) {
      if (!data._template[this.name()]) {
        data._template[this.name()] = [];
      }
      if (!this.hasOption(data, "mode")) {
        this.setOption(data, "mode", "append");
      }
    }
    return this;
  };

  NestedTable.prototype.__rowHasData = function(row, opts) {
    var field, j, len1, ref;
    if (opts == null) {
      opts = {};
    }
    ref = this.getFields("all");
    for (j = 0, len1 = ref.length; j < len1; j++) {
      field = ref[j];
      if (field instanceof MaskSplitter) {
        continue;
      }
      if (row[field.name() + ":unset"]) {
        return true;
      }
      if (row[field.name() + ":has_value"]) {
        return true;
      }
      if (field.hasUserData(row, null, opts)) {
        return true;
      }
    }
    return false;
  };

  NestedTable.prototype.__cleanNestedUUIDs = function(row_data) {
    var cleaned_row, field, idx, j, l, len1, len2, nested_row, ref, ref1, ref2;
    cleaned_row = CUI.util.copyObject(row_data, true);
    ref = this.getFields("all");
    for (j = 0, len1 = ref.length; j < len1; j++) {
      field = ref[j];
      if (field instanceof NestedUUID) {
        delete cleaned_row[field.name()];
      } else if (field instanceof NestedTable && CUI.util.getObjectClass(field) !== "ReverseLinkedTable") {
        if (((ref1 = cleaned_row[field.name()]) != null ? ref1.length : void 0) > 0) {
          ref2 = cleaned_row[field.name()];
          for (idx = l = 0, len2 = ref2.length; l < len2; idx = ++l) {
            nested_row = ref2[idx];
            cleaned_row[field.name()][idx] = field.__cleanNestedUUIDs(nested_row);
          }
        }
      }
    }
    return cleaned_row;
  };

  NestedTable.prototype.mergeData = function(top_level_data, top_level_data_new, replace, is_restore) {
    var data, data_new, existing_rows, j, l, len1, len2, ref, ref1, ref2, row, sdata;
    if (replace == null) {
      replace = false;
    }
    if (is_restore == null) {
      is_restore = false;
    }
    data = top_level_data[top_level_data._objecttype];
    data_new = top_level_data_new[top_level_data_new._objecttype];
    if (!data[this.name()]) {
      data[this.name()] = [];
    }
    if (replace) {
      data[this.name()].splice(0);
    }
    existing_rows = [];
    ref = data[this.name()];
    for (j = 0, len1 = ref.length; j < len1; j++) {
      row = ref[j];
      existing_rows.push(JSON.stringify(this.getRowSaveData(row, {
        top_level_data: top_level_data
      })));
    }
    ref1 = data_new[this.name()] || [];
    for (l = 0, len2 = ref1.length; l < len2; l++) {
      row = ref1[l];
      if (is_restore) {
        row = this.__cleanNestedUUIDs(row);
      }
      sdata = this.getRowSaveData(row, {
        top_level_data: top_level_data_new,
        copy_for_template: true
      });
      if (ref2 = JSON.stringify(sdata), indexOf.call(existing_rows, ref2) >= 0) {
        continue;
      }
      data[this.name()].push(row);
    }
    return this;
  };

  NestedTable.prototype.hasUserData = function(data, top_level_data, opts) {
    return this.countUserData(data, opts) > 0;
  };

  NestedTable.prototype.countUserData = function(data, opts) {
    var count, j, len1, ref, row;
    if (!data) {
      return 0;
    }
    if (!data[this.name()]) {
      return 0;
    }
    count = 0;
    ref = data[this.name()];
    for (j = 0, len1 = ref.length; j < len1; j++) {
      row = ref[j];
      if (this.__rowHasData(row, opts)) {
        count = count + 1;
      }
    }
    return count;
  };

  NestedTable.prototype.onBulkOptionsChanged = function(data, form) {
    NestedTable.__super__.onBulkOptionsChanged.call(this, data, form);
    if (data.mode === "bulk_match_merge") {
      CUI.dom.hideElement(this.__top_level_add_button);
    } else {
      CUI.dom.showElement(this.__top_level_add_button);
    }
    return CUI.Events.trigger({
      type: "nested-bulk-option-changed",
      node: form
    });
  };

  NestedTable.prototype.getBulkOptions = function(data, opts) {
    var count, count_hint, fields, j, len1, lo_data, options, ref, ref1, row, values;
    if (this.isReadOnly(data, opts.top_level_data, opts)) {
      return [];
    }
    if (this.depth() > 0) {
      return [];
    }
    switch (opts.mode) {
      case "editor-bulk":
      case "editor-header-bulk":
        options = ["bulk_append", "bulk_prepend", "bulk_replace", "bulk_remove", "bulk_remove_all"];
        if (ez5.version("6.8") && ez5.session.isDebug()) {
          options.push("bulk_match_merge");
          if (this.table.schema.columns.length > 1) {
            options.splice(4, 0, "bulk_remove_full_match");
          }
        }
        break;
      default:
        if (((ref = data._template) != null ? ref[this.name()].length : void 0) > 0) {
          count = this.countUserData(data._template);
          values = [];
          fields = this.getFields(opts.mode);
          if (fields.length === 1 && fields[0] instanceof LinkedObject) {
            ref1 = data._template[this.name()];
            for (j = 0, len1 = ref1.length; j < len1; j++) {
              row = ref1[j];
              lo_data = row[fields[0].name()];
              if (!lo_data) {
                continue;
              }
              values.push(new ResultObject().setData(lo_data).renderText());
            }
          }
          if (values.length > 0) {
            count_hint = "(" + values.join(", ") + ")";
          } else if (count > 0) {
            count_hint = "(" + count + ")";
          } else {
            count_hint = "";
          }
          options = [
            {
              text: $$("main.editor.option.append", {
                fieldname: this.nameLocalized(),
                count_hint: count_hint
              }),
              value: "append"
            }
          ];
          options.min_checked = 0;
        } else {
          options = [];
        }
    }
    return options;
  };

  NestedTable.prototype.needsDirectRender = function(opts) {
    var field, j, len1, ref;
    if (NestedTable.__super__.needsDirectRender.call(this, opts)) {
      return true;
    }
    ref = this.getFields(opts.mode, opts);
    for (j = 0, len1 = ref.length; j < len1; j++) {
      field = ref[j];
      if (field !== this && (typeof field.needsDirectRender === "function" ? field.needsDirectRender(opts) : void 0)) {
        return true;
      }
    }
    return false;
  };

  NestedTable.prototype.isVisible = function(mode, opts) {
    var e;
    if (opts == null) {
      opts = {};
    }
    if (opts.for_export) {
      return NestedTable.__super__.isVisible.call(this, mode);
    }
    switch (mode) {
      case 'detail-header':
      case 'editor-header':
      case 'editor-header-template':
      case 'editor-header-bulk':
      case 'fulltext':
        return false;
    }
    if (!NestedTable.__super__.isVisible.call(this, mode)) {
      return false;
    }
    if (this.FieldSchema.hierarchical_mask_hint) {
      return true;
    }
    try {
      return this.hasVisibleFields(mode, opts);
    } catch (error) {
      e = error;
      if (e instanceof NestedTableIsVisibleException) {
        return false;
      }
      throw e;
    }
  };

  NestedTable.prototype.hasVisibleFields = function(mode, opts) {
    return this.getFields(mode, opts).length > 0;
  };

  NestedTable.prototype.isNestedIndex = function() {
    return !!this.FieldSchema.search.nested;
  };

  NestedTable.prototype.isExpertCommon = function(mode) {
    if (mode === "sort") {
      return false;
    } else {
      return NestedTable.__super__.isExpertCommon.call(this, mode);
    }
  };

  NestedTable.prototype.checkServerValidationProblemHandled = function(data, top_level_data, message, opts) {
    var ref, save_data;
    if (!CUI.util.isNumber(opts.rowIndex)) {
      return NestedTable.__super__.checkServerValidationProblemHandled.call(this, data, top_level_data, message, opts);
    }
    save_data = {};
    this.getSaveData(data, save_data, {});
    if (((ref = data[this.name() + ":validation_data"]) != null ? ref.length : void 0) <= opts.rowIndex && save_data.length <= opts.rowIndex) {
      return !CUI.util.isEqual(data[this.name() + ":validation_data"][opts.rowIndex], save_data[opts.rowIndex]);
    } else {
      return NestedTable.__super__.checkServerValidationProblemHandled.call(this, data, top_level_data, message, opts);
    }
  };

  NestedTable.prototype.supportsNestedUUID = function() {
    return true;
  };

  return NestedTable;

})(Field);

NestedTableIsVisibleException = (function() {
  function NestedTableIsVisibleException() {}

  return NestedTableIsVisibleException;

})();

CUI.ready((function(_this) {
  return function() {
    return CUI.Events.registerEvent({
      type: "nested-bulk-option-changed",
      bubble: true
    });
  };
})(this));
// Generated by CoffeeScript 1.12.7
var ObjecttypeField,
  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;

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

  function ObjecttypeField() {
    this.getSortFields = bind(this.getSortFields, this);
    return ObjecttypeField.__super__.constructor.apply(this, arguments);
  }

  ObjecttypeField.prototype.name = function() {
    return "_objecttype";
  };

  ObjecttypeField.prototype.nameLocalized = function() {
    return $$("base.objecttype.name");
  };

  ObjecttypeField.prototype.isExpertCommon = function(mode) {
    return true;
  };

  ObjecttypeField.prototype.isExpertCommonOnly = function(mode) {
    return false;
  };

  ObjecttypeField.prototype.getSaveData = function() {};

  ObjecttypeField.prototype.isVisible = function(mode, opts) {
    var isVisible;
    if (opts == null) {
      opts = {};
    }
    if (CUI.util.isFunction(opts.isVisible)) {
      isVisible = opts.isVisible(this, mode, opts);
      if (CUI.util.isBoolean(isVisible)) {
        return isVisible;
      }
    }
    if (opts.hide_other_system_fields) {
      return false;
    }
    if (opts.hide_objecttype) {
      return false;
    }
    switch (mode) {
      case "sort":
      case "detail-footer":
      case "editor-footer":
      case "table":
      case "text":
      case "export":
        return true;
      default:
        return false;
    }
  };

  ObjecttypeField.prototype.getMappingSourceFullNameLocalized = function() {
    return this.fullNameLocalized();
  };

  ObjecttypeField.prototype.isSourceForMapping = function(required_type) {
    return false;
  };

  ObjecttypeField.prototype.isSortGroupable = function() {
    return true;
  };

  ObjecttypeField.prototype.getSortFields = function() {
    return "_pool";
  };

  ObjecttypeField.prototype.isEmpty = function() {
    return false;
  };

  ObjecttypeField.prototype.renderEditorInput = function(data, top_level_data) {
    var span;
    span = CUI.dom.span();
    span.textContent = this.mask.table.nameLocalized();
    return span;
  };

  ObjecttypeField.prototype.renderDetailOutput = function(data, top_level_data) {
    return new CUI.Label({
      text: this.mask.table.nameLocalized()
    });
  };

  ObjecttypeField.prototype.getSortFields = function(data) {
    return this.name();
  };

  ObjecttypeField.prototype.isSortUnique = function() {
    return true;
  };

  ObjecttypeField.prototype.formatSortGroupable = function(item) {
    var data, displayName;
    data = ez5.schema.CURRENT._objecttype_by_name[item];
    displayName = data._name_localized;
    if (data._instance) {
      displayName += "@" + (ez5.connector.displaynameByInstance(data._instance));
    }
    return displayName;
  };

  ObjecttypeField.prototype.isTopLevelField = function() {
    return true;
  };

  ObjecttypeField.prototype.getDataAsString = function() {
    return this.mask.table.nameLocalized();
  };

  ObjecttypeField.prototype.fullName = function() {
    return this.name();
  };

  return ObjecttypeField;

})(Field);
// Generated by CoffeeScript 1.12.7
var OwnerField,
  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;

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

  function OwnerField() {
    this.getSearchFilter = bind(this.getSearchFilter, this);
    this.getQueryFieldBadge = bind(this.getQueryFieldBadge, this);
    return OwnerField.__super__.constructor.apply(this, arguments);
  }

  OwnerField.prototype.name = function() {
    return "_owner";
  };

  OwnerField.prototype.nameLocalized = function() {
    return "Owner";
  };

  OwnerField.prototype.getDataForFieldData = function(data, top_level_data) {
    return top_level_data;
  };

  OwnerField.prototype.isExpertCommon = function(mode) {
    return true;
  };

  OwnerField.prototype.isEmpty = function() {
    return false;
  };

  OwnerField.prototype.renderHalfWidth = function() {
    return true;
  };

  OwnerField.prototype.isVisible = function(mode, opts) {
    var isVisible;
    if (opts == null) {
      opts = {};
    }
    if (CUI.util.isFunction(opts.isVisible)) {
      isVisible = opts.isVisible(this, mode, opts);
      if (CUI.util.isBoolean(isVisible)) {
        return isVisible;
      }
    }
    if (!opts.get_save_data && this.isFilteredByRights(opts)) {
      return false;
    }
    if (mode === "editor-header" || mode === "editor-header-template" || mode === "editor-header-bulk") {
      if (this.mask.schema.system_fields.owner.edit.mode === "off") {
        return false;
      } else {
        return true;
      }
    } else if ((mode === "detail-footer" || mode === "expert") && this.mask.schema.system_fields.owner.output.mode !== "off") {
      return true;
    } else {
      return false;
    }
  };

  OwnerField.prototype.isReadOnly = function(data, top_level_data) {
    var ref;
    if (this.mask.schema.system_fields.owner.edit.mode !== "edit") {
      return true;
    } else if ((top_level_data != null ? top_level_data._owner : void 0) && !(top_level_data != null ? (ref = top_level_data._generated_rights) != null ? ref.change_owner : void 0 : void 0)) {
      return true;
    } else {
      return false;
    }
  };

  OwnerField.prototype.isSortUnique = function() {
    return true;
  };

  OwnerField.prototype.fullName = function() {
    return this.name();
  };

  OwnerField.prototype.getQueryFieldBadge = function(data) {
    var who;
    who = AclWho.newInstance(data[this.name()]);
    return {
      name: this.nameLocalized(),
      value: who != null ? who.getDisplayText() : void 0
    };
  };

  OwnerField.prototype.renderSearchInput = function(data) {
    var ownerSelector;
    ownerSelector = new UserGroupSelector({
      name: this.name(),
      aclWhoManager: new AclWhoManager({
        filter_system_groups: true,
        who_filter: ["user", "group"]
      }),
      data: data,
      id: this.idAttribute(data),
      onDataChanged: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            node: ownerSelector,
            type: "search-input-change"
          });
        };
      })(this)
    });
    return ownerSelector.start();
  };

  OwnerField.prototype.getMappingSourceFullNameLocalized = function() {
    return this.fullNameLocalized();
  };

  OwnerField.prototype.isSourceForMapping = function(required_type) {
    return false;
  };

  OwnerField.prototype.getSearchFilter = function(data) {
    if (CUI.util.isEmptyObject(data[this.name()])) {
      return;
    }
    return AclWho.newInstance(data[this.name()]).getSearchFilter(this.name());
  };

  OwnerField.prototype.renderEditorInput = function(data, top_level_data, opts) {
    var ownerSelector, ref;
    if (top_level_data._owner || ((ref = opts.mode) === "editor-bulk")) {
      ownerSelector = new UserGroupSelector({
        name: this.name(),
        aclWhoManager: new AclWhoManager({
          filter_system_groups: true
        }),
        data: top_level_data,
        id: this.idAttribute(data),
        onDataChanged: function() {
          return CUI.Events.trigger({
            node: ownerSelector,
            type: "editor-changed"
          });
        }
      });
      return ownerSelector.start();
    } else {
      return new CUI.EmptyLabel({
        text: $$("main.editor.new.pk")
      });
    }
  };

  OwnerField.prototype.renderDetailOutput = function(data, top_level_data) {
    var who;
    if (top_level_data[this.name()]) {
      who = AclWho.newInstance(top_level_data[this.name()]);
    }
    if (who) {
      return new CUI.Label({
        text: who.getDisplayText()
      }).DOM;
    } else {
      return new CUI.EmptyLabel({
        text: $$("tool.detail.view.field.owner.no-owner")
      }).DOM;
    }
  };

  OwnerField.prototype.getDataAsString = function(data, top_level_data) {
    return JSON.stringify(top_level_data[this.name()]);
  };

  OwnerField.prototype.getSaveData = function(data, save_data, opts) {
    var owner, sd_owner;
    if (opts.copy) {
      return;
    }
    if (opts.demo_data) {
      save_data._top_level._owner = ez5.session.user.getData();
      return;
    }
    if (this.isReadOnly(data, data._top_level)) {
      return;
    }
    owner = data._top_level[this.name()];
    if (owner) {
      if (owner.user) {
        sd_owner = {
          _basetype: "user",
          user: {
            _id: owner.user._id
          }
        };
      }
      if (owner.group) {
        sd_owner = {
          _basetype: "group",
          group: {
            _id: owner.group._id
          }
        };
      }
    }
    if (sd_owner) {
      save_data._top_level[this.name()] = sd_owner;
    }
    return save_data;
  };

  OwnerField.prototype.getSearchUnsetElement = function(data, listViewColumn) {};

  OwnerField.prototype.isTopLevelField = function() {
    return true;
  };

  OwnerField.prototype.getKeyInRights = function() {
    return "owner";
  };

  return OwnerField;

})(Field);
// Generated by CoffeeScript 1.12.7
var PoolField, PoolFieldForEditor,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  PoolField.prototype.name = function() {
    return "_pool";
  };

  PoolField.prototype.nameLocalized = function() {
    return $$("main.editor.pool");
  };

  PoolField.prototype.getOutputStandard = function() {
    return null;
  };

  PoolField.prototype.checkBareValue = function(v) {
    if (!v) {
      return false;
    } else {
      return true;
    }
  };

  PoolField.prototype.renderHalfWidth = function() {
    return true;
  };

  PoolField.prototype.getReplacementRecord = function() {};

  PoolField.prototype.renderDetailOutput = function(data, top_level_data, opts) {
    var div, infoButton, pool, poolPath, ref;
    if (opts == null) {
      opts = {};
    }
    CUI.util.assert(!opts.text, "PoolField.renderDetailOutput", "opts.text is obsolete", {
      opts: opts
    });
    pool = data[this.name()];
    if (!pool) {
      pool = (ref = data._template) != null ? ref[this.name()] : void 0;
    }
    if (!pool) {
      if (this.isInReverseLinkedTableReadOnly()) {
        return new CUI.EmptyLabel({
          multiline: true,
          text: $$("pool.field.reverse_pool_from_parent")
        });
      }
      if (opts.footer_mode === "detail-footer" || opts.footer_mode === "editor-footer") {
        return new CUI.EmptyLabel({
          multiline: true,
          text: $$("pool.field.without_pool")
        });
      }
      return;
    }
    poolPath = Pool.renderPoolPath(pool._path);
    infoButton = new LocaButton({
      ui: "pool.field.info.button",
      loca_key: "search.type.selector.node.button.info",
      appearance: "flat",
      "class": "ez5-path-info-button",
      onClick: (function(_this) {
        return function() {
          var poolObject, popover, popoverContent;
          poolObject = ez5.pools.findPoolById(pool.pool._id);
          if (!poolObject) {
            poolObject = new Pool();
            poolObject.setData(pool);
          }
          popoverContent = poolObject.getInfoDiv();
          popover = new ez5.HintPopover({
            element: infoButton,
            content: popoverContent,
            padded: false
          });
          return popover.show();
        };
      })(this)
    });
    div = CUI.dom.div("ez5-path-holder");
    CUI.dom.append(div, poolPath);
    CUI.dom.append(div, infoButton);
    return div;
  };

  PoolField.prototype.isVisible = function(mode, opts) {
    var isVisible, ref;
    if (opts == null) {
      opts = {};
    }
    if (CUI.util.isFunction(opts.isVisible)) {
      isVisible = opts.isVisible(this, mode, opts);
      if (CUI.util.isBoolean(isVisible)) {
        return isVisible;
      }
    }
    if (opts.hide_pool) {
      return false;
    }
    if (mode === "export") {
      return true;
    }
    if (mode === "editor-header" || mode === "editor-header-template" || mode === "editor-header-bulk" || mode === "sort" || mode === "result-card-info-detail" || mode === "csv-import" || mode === "detail-footer" || mode === "editor-footer" || mode === "standard" || mode === "table" || mode === "text") {
      if ((mode === "table" || mode === "result-card-info-detail" || mode === "standard" || mode === "text" || mode === "detail-footer") && ((ref = this.mask.schema.system_fields) != null ? ref.pool.output.mode : void 0) === "off") {
        return false;
      } else {
        return true;
      }
    }
    if ((mode === "editor" || mode === "editor-bulk") && this.isInReverseLinkedTable()) {
      return true;
    } else {
      return false;
    }
  };

  PoolField.prototype.isEmpty = function(data, top_level_data, opts) {
    if (opts.footer_mode === "detail-footer") {
      return false;
    }
    return PoolField.__super__.isEmpty.call(this, data, top_level_data, opts);
  };

  PoolField.prototype.hasUserData = function(data, top_level_data, opts) {
    var objectData, pool, ref, ref1;
    if (opts == null) {
      opts = {};
    }
    if (this.isInReverseLinkedTableReadOnly()) {
      return false;
    }
    objectData = this.getObjectSaveData(data, top_level_data);
    pool = objectData[this.name()];
    if (!pool || (((ref = opts.editor) != null ? ref.hasTemplate() : void 0) && objectData._template)) {
      pool = (ref1 = objectData._template) != null ? ref1[this.name()] : void 0;
    }
    return !!pool;
  };

  PoolField.prototype.isReadOnly = function(data, top_level_data, opts) {
    var enough_pool_ids, ref, ref1, ref2, topLevelData;
    if (opts == null) {
      opts = {};
    }
    if (((ref = opts.editor) != null ? ref.hasTemplate() : void 0) && opts.mode === "editor" && (!this.isInReverseLinkedTable() && ez5.version("6"))) {
      return true;
    } else if (this.isInReverseLinkedTableReadOnly()) {
      return true;
    } else {
      if (((ref1 = opts.mode) === "editor-bulk" || ref1 === "editor-header-bulk") && opts.pool_ids.length === 0) {
        return false;
      }
      enough_pool_ids = true;
      if (opts.pool_ids && opts.pool_ids.length < 2) {
        enough_pool_ids = false;
      }
      topLevelData = top_level_data || opts.top_level_data;
      if (ez5.version("6") && this.isInReverseLinkedTable()) {
        topLevelData = opts.top_level_data;
      }
      if ((data != null ? data._version : void 0) && (!(topLevelData != null ? (ref2 = topLevelData._generated_rights) != null ? ref2.unlink : void 0 : void 0) || !enough_pool_ids)) {
        if (opts.get_save_data) {
          return false;
        } else {
          return true;
        }
      } else {
        return false;
      }
    }
  };

  PoolField.prototype.isInReverseLinkedTable = function() {
    var ref;
    return ((ref = this.mask) != null ? ref.nestedTableField : void 0) instanceof ReverseLinkedTable;
  };

  PoolField.prototype.isInReverseLinkedTableReadOnly = function() {
    var ref;
    return this.isInReverseLinkedTable() && this.getMainMask().table.poolLink() && (ref = this.getMainMask().getPoolEditMode(), indexOf.call(this.__getReverseEditableModes(), ref) < 0);
  };

  PoolField.prototype.isSortGroupable = function() {
    return true;
  };

  PoolField.prototype.getSortFields = function() {
    return "_pool";
  };

  PoolField.prototype.isSortUnique = function() {
    return true;
  };

  PoolField.prototype.isInPopoverTopLevel = function() {
    return true;
  };

  PoolField.prototype.isExpertCommon = function(mode) {
    return true;
  };

  PoolField.prototype.hasBulkCheckbox = function(opts) {
    if (opts.bulk && opts.pool_ids.length === 0) {
      return false;
    } else {
      return true;
    }
  };

  PoolField.prototype.checkValue = function(data, top_level_data, opts) {
    if (this.isInReverseLinkedTableReadOnly()) {
      return true;
    } else {
      return PoolField.__super__.checkValue.call(this, data, top_level_data, opts);
    }
  };

  PoolField.prototype.checkField = function(data, top_level_data, opts) {
    if (opts.bulk && opts.pool_ids.length === 0) {
      return true;
    } else {
      return PoolField.__super__.checkField.call(this, data, top_level_data, opts);
    }
  };

  PoolField.prototype.renderEditorInput = function(data, top_level_data, opts) {
    var bottom, checkHintVisibility, f, field_is_reverse_pool, i, lbl, len, old_pool, original_pool_id, poolSelector, ref, ref1, ref2, ref3, ref4, resultObject, reverse, triggerPoolChange, ui;
    if (((ref = opts.fieldsRenderer) != null ? ref.getFather() : void 0) instanceof FieldsRendererFooter) {
      this.__footerField = true;
      return this.renderDetailOutput(data, top_level_data, opts);
    }
    if (opts.bulk && opts.pool_ids.length === 0) {
      return new CUI.EmptyLabel({
        multiline: true,
        text: $$("editor.load.no_pool_change_in_bulk")
      });
    }
    CUI.util.assert(CUI.util.isPlainObject(opts), "PoolField.renderEditorInput", "opts must be set", {
      data: data,
      top_level_data: top_level_data,
      opts: opts
    });
    field_is_reverse_pool = (function(_this) {
      return function(f) {
        var ref1, ref2;
        if (!(f instanceof ReverseLinkedTable)) {
          return false;
        }
        if (f.isHierarchical() && !ez5.version("6")) {
          return false;
        }
        if (!f.getMask().table.poolLink()) {
          return false;
        }
        if (!f.getMainMask().table.poolLink()) {
          return false;
        }
        if (ref1 = (ref2 = f.getMainMask()) != null ? ref2.getPoolEditMode() : void 0, indexOf.call(_this.__getReverseEditableModes(), ref1) >= 0) {
          return false;
        }
        return true;
      };
    })(this);
    resultObject = (ref1 = opts.editor) != null ? ref1.object : void 0;
    bottom = void 0;
    lbl = void 0;
    if (resultObject != null ? resultObject.mask : void 0) {
      lbl = new LocaLabel({
        loca_key: "pool.field.reverse_pool_change_hint",
        multiline: true,
        appearance: "secondary",
        "class": "ez5-pool-field-hint"
      });
      lbl.hide();
      ref2 = resultObject.mask.getFields("editor");
      for (i = 0, len = ref2.length; i < len; i++) {
        f = ref2[i];
        if (!field_is_reverse_pool(f)) {
          continue;
        }
        bottom = {
          content: lbl
        };
        break;
      }
    }
    old_pool = data != null ? data[this.name()] : void 0;
    original_pool_id = old_pool != null ? old_pool.pool._id : void 0;
    checkHintVisibility = (function(_this) {
      return function() {
        var bf, new_pool, ref3, save_opts;
        if (!data[_this.name() + ":hint_listener"]) {
          if (opts.editor.__pane) {
            data[_this.name() + ":hint_listener"] = CUI.Events.listen({
              type: "editor-changed",
              node: opts.editor.__pane.DOM,
              call: function() {
                return checkHintVisibility();
              }
            });
          }
        }
        new_pool = data[_this.name()];
        if (!new_pool || ((ref3 = new_pool.pool) != null ? ref3._id : void 0) === original_pool_id) {
          lbl.hide();
          return;
        }
        if (opts.bulk) {
          bf = opts.editor.getBulkFields();
          if (bf.length === 0) {
            lbl.hide();
            return;
          }
          save_opts = {};
          opts.editor.getSaveDataBulkMode(save_opts);
          if (save_opts.base_fields_only) {
            return lbl.show();
          } else {
            return lbl.hide();
          }
        } else {
          return lbl.show();
        }
      };
    })(this);
    triggerPoolChange = (function(_this) {
      return function(newPool) {
        var ref3, ref4, ref5;
        if (CUI.util.isEmpty(newPool)) {
          return;
        }
        CUI.Events.trigger({
          node: poolSelector,
          type: "pool-field-changed",
          info: {
            old_pool: old_pool,
            new_pool: newPool,
            editor_has_changes: (ref3 = opts.editor) != null ? typeof ref3.hasChanges === "function" ? ref3.hasChanges() : void 0 : void 0,
            editor: opts.editor,
            editor_data: (ref4 = opts.editor) != null ? ref4.editor_data : void 0,
            object: (ref5 = opts.editor) != null ? ref5.object : void 0
          }
        });
        old_pool = newPool;
      };
    })(this);
    if (opts.ui) {
      ui = opts.ui;
    } else {
      ui = "pool.field:" + (this.name());
    }
    reverse = this.isInReverseLinkedTable();
    if (reverse && !((ref3 = opts.editor) != null ? (ref4 = ref3.editor_data) != null ? ref4.table.poolLink() : void 0 : void 0) && !opts.placeholder) {
      opts.placeholder = $$("pool.field.placeholder");
    }
    poolSelector = new PoolSelector({
      "class": "ez5-pool-field",
      maximize_horizontal: true,
      name: this.name(),
      placeholder: opts.placeholder,
      id: this.idAttribute(data),
      ui: ui,
      pool_ids: opts.pool_ids,
      form: {
        label: this.__getSelectorLabel(),
        hint: this.__getSelectorHint()
      },
      data: data,
      bottom: bottom,
      reverse: reverse,
      omit_root_pool: this.omitRootPool(),
      onDataChanged: (function(_this) {
        return function(data, df, ev, info) {
          var new_pool, pool_changed, showHint;
          if (typeof opts.onDataChanged === "function") {
            opts.onDataChanged(data, df, ev, info);
          }
          new_pool = data[_this.name()];
          if (!bottom) {
            triggerPoolChange(new_pool);
            return;
          }
          pool_changed = false;
          showHint = false;
          resultObject.mask.invokeOnFields(opts.mode, true, (function(f, _data) {
            var _row, index, j, len1, ref5, rf;
            if (!field_is_reverse_pool(f) || !_data) {
              return;
            }
            pool_changed = true;
            ref5 = _data[f.name()] || [];
            for (index = j = 0, len1 = ref5.length; j < len1; index = ++j) {
              _row = ref5[index];
              if (_row._new) {
                continue;
              }
              _row[_this.name()] = new_pool;
              if (!_row[_this.name()]) {
                continue;
              }
              rf = _row[_this.name() + ":rendered"];
              if (!rf) {
                continue;
              }
              showHint = true;
              CUI.dom.replace(rf.getElement(), _this.renderDetailOutput(_row, _data, opts));
            }
          }), data);
          lbl.hide();
          if (pool_changed || opts.bulk) {
            triggerPoolChange(new_pool);
            if (showHint) {
              checkHintVisibility();
            }
          }
        };
      })(this)
    });
    return poolSelector;
  };

  PoolField.prototype.__getSelectorLabel = function() {
    return $$("pool.field.form.label");
  };

  PoolField.prototype.__getSelectorHint = function() {
    return null;
  };

  PoolField.prototype.formatSortGroupable = function(_, filter, __, responseData, object) {
    var hasConnectorObjecttype, i, idInstance, index, len, poolName, ref, regKey, value, values;
    regKey = filter._key;
    values = object._fields[regKey];
    if (!(values != null ? values[0] : void 0)) {
      return;
    }
    hasConnectorObjecttype = responseData.objecttypes.some((function(_this) {
      return function(objecttype) {
        return objecttype.indexOf('@') > -1;
      };
    })(this));
    if (CUI.util.isArray(values[0])) {
      values = values[0];
    }
    if (hasConnectorObjecttype) {
      values = CUI.util.copyObject(values);
      for (index = i = 0, len = values.length; i < len; index = ++i) {
        value = values[index];
        if (value.indexOf('@') === -1) {
          continue;
        }
        ref = value.split('@'), poolName = ref[0], idInstance = ref[1];
        if (index === 0) {
          values[index] = poolName + "@" + (ez5.connector.displaynameByInstance(idInstance));
        } else {
          values[index] = poolName;
        }
      }
    } else {
      values.shift();
    }
    return values.join(" > ");
  };

  PoolField.prototype.omitRootPool = function() {
    return true;
  };

  PoolField.prototype.getObjectSaveData = function(ownData, topLevelData) {
    var father, mainMask;
    father = this.getFatherField();
    if (!father) {
      return ownData;
    }
    mainMask = this.getMainMask();
    if (!mainMask.table.poolLink()) {
      return ownData;
    }
    if (!ez5.version("6")) {
      return topLevelData[topLevelData != null ? topLevelData._objecttype : void 0];
    }
    if (father instanceof ReverseLinkedTable) {
      return ownData;
    }
    return topLevelData[topLevelData != null ? topLevelData._objecttype : void 0];
  };

  PoolField.prototype.getSaveData = function(data, save_data, opts) {
    var fatherField, i, len, objectData, objecttype, pool, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, topLevelId, topleveldata;
    if (opts.demo_data) {
      ref = ez5.pools.getList();
      for (i = 0, len = ref.length; i < len; i++) {
        pool = ref[i];
        if (pool.isStandardPool()) {
          save_data[this.name()] = pool.data;
          break;
        }
      }
      return;
    }
    if (opts.copy_for_template) {
      return;
    }
    fatherField = this.getFatherField();
    if (fatherField instanceof ReverseLinkedTable && fatherField.isHierarchical()) {
      if (data[this.name()]) {
        return save_data[this.name()] = data[this.name()];
      } else {
        return save_data[this.name()] = {
          pool: {
            _id: (ref1 = opts.top_level_data[opts.top_level_data._objecttype]) != null ? (ref2 = ref1._pool) != null ? ref2.pool._id : void 0 : void 0
          }
        };
      }
    }
    objectData = this.getObjectSaveData(data, opts.top_level_data);
    pool = objectData[this.name()];
    if (!pool || (((ref3 = opts.editor) != null ? ref3.hasTemplate() : void 0) && objectData._template)) {
      pool = (ref4 = objectData._template) != null ? ref4[this.name()] : void 0;
    }
    if (pool) {
      if (opts.copy) {
        save_data[this.name()] = CUI.util.copyObject(pool, true);
      } else {
        save_data[this.name()] = {
          pool: {
            _id: pool.pool._id
          }
        };
      }
    } else {
      if (fatherField instanceof ReverseLinkedTable && ez5.version("6")) {
        topleveldata = opts.top_level_data[opts.top_level_data._objecttype];
        topLevelId = (topleveldata != null ? (ref5 = topleveldata._pool) != null ? ref5.pool._id : void 0 : void 0) || (topleveldata != null ? (ref6 = topleveldata._template) != null ? (ref7 = ref6._pool) != null ? ref7.pool._id : void 0 : void 0 : void 0);
        if (topLevelId) {
          return save_data[this.name()] = {
            pool: {
              _id: topLevelId
            }
          };
        }
      }
      if (opts.bulk) {
        return save_data;
      }
      objecttype = this.table.nameLocalized();
      throw new InvalidSaveDataException({
        text: $$("pool.field.no_pool_available", {
          objecttype: objecttype
        })
      });
    }
    return save_data;
  };

  PoolField.prototype.isSystemField = function() {
    return true;
  };

  PoolField.prototype.__getReverseEditableModes = function() {
    return ["reverse_pool_changed_ask", "reverse_pool_changed_never"];
  };

  PoolField.prototype.getCSVDestinationFields = function(csvImporter) {
    var opts;
    opts = {
      csvImporter: csvImporter,
      field: this
    };
    return [new PoolFieldCSVImporterDestinationField(opts)];
  };

  return PoolField;

})(DataColumn);

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

  function PoolFieldForEditor(opts) {
    if (opts == null) {
      opts = {};
    }
    this.opts = CUI.Element.readOpts(opts, "new PoolFieldForEditor", {
      omitRootPool: {
        "default": true,
        check: Boolean
      },
      name: {
        check: String
      },
      label: {
        check: String
      },
      hint: {
        check: String
      }
    });
  }

  PoolFieldForEditor.prototype.omitRootPool = function() {
    return this.opts.omitRootPool;
  };

  PoolFieldForEditor.prototype.name = function() {
    if (this.opts.name) {
      return this.opts.name;
    }
    return PoolFieldForEditor.__super__.name.call(this);
  };

  PoolFieldForEditor.prototype.fullName = function() {
    return this.name();
  };

  PoolFieldForEditor.prototype.__getSelectorLabel = function() {
    if (this.opts.label) {
      return this.opts.label;
    }
    return PoolFieldForEditor.__super__.__getSelectorLabel.call(this);
  };

  PoolFieldForEditor.prototype.__getSelectorHint = function() {
    if (this.opts.hint) {
      return this.opts.hint;
    }
    return PoolFieldForEditor.__super__.__getSelectorHint.call(this);
  };

  return PoolFieldForEditor;

})(PoolField);

CUI.ready(function() {
  return CUI.Events.registerEvent({
    type: "pool-field-changed",
    bubble: true
  });
});
// Generated by CoffeeScript 1.12.7
var PrimaryKeyColumn,
  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;

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

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

  PrimaryKeyColumn.prototype.nameLocalized = function() {
    return $$("base.primary_key_column.name");
  };

  PrimaryKeyColumn.prototype.isVisibleToSaveData = function() {
    return true;
  };

  PrimaryKeyColumn.prototype.isVisible = function(mode, opts) {
    var edit_mode, isVisible, output_mode, ref, ref1;
    if (opts == null) {
      opts = {};
    }
    if (CUI.util.isFunction(opts.isVisible)) {
      isVisible = opts.isVisible(this, mode, opts);
      if (CUI.util.isBoolean(isVisible)) {
        return isVisible;
      }
    }
    if (!this.insideNested()) {
      edit_mode = (ref = this.getMainMask().schema.system_fields.object_id) != null ? ref.edit.mode : void 0;
      output_mode = (ref1 = this.getMainMask().schema.system_fields.object_id) != null ? ref1.output.mode : void 0;
    }
    switch (mode) {
      case "editor-header":
      case "editor-header-template":
      case "editor-footer":
        if (edit_mode === "show") {
          return true;
        }
        break;
      case "expert":
        if (edit_mode === "show" || output_mode === "show") {
          return true;
        }
        break;
      case "detail-footer":
        if (output_mode === "show") {
          return true;
        }
        break;
      case "export":
        return true;
      case "csv-import":
        return !this.insideNested();
    }
    return false;
  };

  PrimaryKeyColumn.prototype.renderEditorInput = function(data) {
    var i, span;
    if (this.isEmpty(data)) {
      i = CUI.dom.i();
      i.textContent = $$("main.editor.new.pk");
      return i;
    } else {
      span = CUI.dom.span();
      span.textContent = data[this.name()];
      return span;
    }
  };

  PrimaryKeyColumn.prototype.getOutputStandard = function() {
    return null;
  };

  PrimaryKeyColumn.prototype.name = function() {
    return "_id";
  };

  PrimaryKeyColumn.prototype.isSourceForMapping = function(required_type) {
    return false;
  };

  PrimaryKeyColumn.prototype.hasUserData = function(data) {
    return false;
  };

  PrimaryKeyColumn.prototype.getSaveData = function(data, save_data, opts) {
    if (opts.copy_for_template) {
      return;
    }
    if (opts.copy) {
      save_data[this.name()] = null;
      return;
    }
    return PrimaryKeyColumn.__super__.getSaveData.call(this, data, save_data, opts);
  };

  PrimaryKeyColumn.prototype.getSearchUnsetElement = function(data, listViewColumn) {};

  PrimaryKeyColumn.prototype.getElementOpts = function(mode) {
    return {
      name: this.name(),
      type: CUI.NumberInput,
      decimals: 0
    };
  };

  PrimaryKeyColumn.prototype.getCSVDestinationFields = function(csvImporter) {
    var dest_field;
    dest_field = {
      format: "number",
      field: this,
      use_for_match_existing: true,
      supports_hierarchy: false,
      read_only: true,
      csvImporter: csvImporter
    };
    return [new ObjecttypeCSVImporterDestinationField(dest_field)];
  };

  PrimaryKeyColumn.prototype.renderDetailOutput = function(data) {
    return this.renderEditorInput(data);
  };

  PrimaryKeyColumn.prototype.isSystemField = function() {
    return true;
  };

  return PrimaryKeyColumn;

})(NumberColumn);
// Generated by CoffeeScript 1.12.7
var ReverseLinkedTable,
  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;

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

  function ReverseLinkedTable(fatherMask, FieldSchema) {
    this.fatherMask = fatherMask;
    this.FieldSchema = FieldSchema;
    this.version = this.fatherMask.version;
    if (this.fatherMask.nestedTableField) {
      this.mainMask = this.fatherMask.nestedTableField.mainMask;
    } else {
      this.mainMask = this.fatherMask;
    }
    if (this.isHierarchical()) {
      this.table = new Table(this.version, this.fatherMask.table.id());
    } else {
      this.table = new Table(this.version, this.FieldSchema.other_table_id);
    }
    if (this.FieldSchema.hierarchical_mask_hint) {
      this.__hierarchy_edit = this.FieldSchema.edit.mode === "edit";
      if (!ez5.version("6")) {
        this.FieldSchema.edit = this.fatherMask.nestedTableField.FieldSchema.edit;
      }
      return;
    }
    this.__hierarchy_edit = false;
    this.__cls = "ez5-" + CUI.util.toDash(CUI.util.getObjectClass(this));
    this.mask = new Mask(this.mainMask.version, null, this.FieldSchema.mask, this);
  }

  ReverseLinkedTable.prototype.getFields = function(mode, opts, level) {
    var field, fields, fs, i, len, ref;
    if (opts == null) {
      opts = {};
    }
    if (level == null) {
      level = 0;
    }
    if (opts.get_save_data) {
      mode = "all";
    }
    if (mode !== "csv-import") {
      return ReverseLinkedTable.__super__.getFields.call(this, mode, opts);
    }
    fields = [];
    ref = this.mask.getFields(mode, opts);
    for (i = 0, len = ref.length; i < len; i++) {
      field = ref[i];
      if (field instanceof ReverseLinkedTable) {
        if (level > 5) {
          continue;
        }
        if (field.__hierarchy_edit || field.__csv_level !== void 0) {
          fs = CUI.util.copyObject(this.FieldSchema, false);
          fs.hierarchial_mask_hint = false;
          field.__csv_level = level;
          fields.push(new ReverseLinkedTable(this.mask, fs));
        }
      } else {
        fields.push(field);
      }
    }
    return fields;
  };

  ReverseLinkedTable.prototype.navigationLimit = 25;

  ReverseLinkedTable.prototype.init = function() {
    var i, len, mask, ref;
    if (this.FieldSchema.hierarchical_mask_hint) {
      CUI.util.assert(!this.mask, "ReverseLinkedTable", "mask is expected to be null");
      ref = this.fatherMask.getMaskPath();
      for (i = 0, len = ref.length; i < len; i++) {
        mask = ref[i];
        if (mask.schema.table_id === this.table.id()) {
          this.mask = mask;
          break;
        }
      }
      return CUI.util.assert(this.mask, "ReverseLinkedTable", "mask is expected to be set");
    } else {
      return ReverseLinkedTable.__super__.init.call(this);
    }
  };

  ReverseLinkedTable.prototype.getTable = function() {
    return this.table;
  };

  ReverseLinkedTable.prototype.isVisible = function(mode, opts) {
    if (mode === "editor-header-bulk" || mode === "editor-bulk") {
      return false;
    } else if (mode === "expert" && this.FieldSchema.hierarchical_mask_hint) {
      return false;
    } else {
      return ReverseLinkedTable.__super__.isVisible.call(this, mode, opts);
    }
  };

  ReverseLinkedTable.prototype.hasVisibleFields = function(mode, opts) {
    var fields;
    fields = this.getFields(mode, opts).filter((function(_this) {
      return function(field) {
        if (field instanceof ReverseLinkedTable && field.FieldSchema.hierarchical_mask_hint) {
          return false;
        }
        return true;
      };
    })(this));
    return fields.length > 0;
  };

  ReverseLinkedTable.prototype.renderFieldLabel = function() {
    return true;
  };

  ReverseLinkedTable.prototype.__searchObjectById = function(id) {
    var dfr;
    dfr = new CUI.Deferred();
    ez5.api.search({
      data: {
        debug: "ReverseLinkedTable.showObject"
      },
      json_data: {
        best_mask_filter: true,
        format: "standard",
        objecttypes: [this.table.name()],
        search: [
          {
            type: "in",
            "in": [id],
            fields: [this.table.name() + "._id"]
          }
        ]
      }
    }).done(function(data) {
      var obj;
      obj = data.objects[0];
      if (!obj) {
        return dfr.reject();
      } else {
        return dfr.resolve(obj);
      }
    }).fail(dfr.reject);
    return dfr.promise();
  };

  ReverseLinkedTable.prototype.loadCurrentTools = function(_opts) {
    var dfr, opts;
    opts = CUI.Element.readOpts(_opts, "ReverseLinkedTable.loadCurrentToolsDetail", {
      detail: {
        check: DetailSidebar
      },
      data: {
        mandatory: true,
        check: "PlainObject"
      },
      getElement: {
        mandatory: true,
        check: Function
      }
    });
    dfr = new CUI.Deferred();
    if (!opts.data._id) {
      dfr.resolve([]);
    } else {
      this.__searchObjectById(opts.data._id).done((function(_this) {
        return function(obj) {
          var ro, tools;
          ro = new ResultObject().setData(obj);
          tools = ro.getDetailTools({
            detail: opts.detail,
            getElement: opts.getElement
          });
          return dfr.resolve(tools);
        };
      })(this)).fail((function(_this) {
        return function() {
          return dfr.resolve([
            new ToolboxTool({
              disabled: true,
              name: "object_not_found",
              loca_key: "reverse.linked.table.show_info.object_not_found"
            })
          ]);
        };
      })(this));
    }
    return dfr.promise();
  };

  ReverseLinkedTable.prototype.getCSVName = function() {
    var csvName, fatherField, name;
    name = this.name().replace("_reverse_nested:", "") + "[]";
    if (fatherField = this.getFatherField()) {
      csvName = fatherField.getCSVName();
      csvName = csvName.replace("[]", "[<n>]");
      name = csvName + "." + name;
    }
    return "" + name;
  };

  ReverseLinkedTable.prototype.supportsEmptyRowAdd = function(opts) {
    if (opts.nested_level === 0) {
      return true;
    } else {
      return false;
    }
  };

  ReverseLinkedTable.prototype.rowToolsVisible = function(row_data, data, opts) {
    var ref;
    if (opts.nestedTableFunc === 'renderForExpert') {
      return false;
    }
    if ((ref = this.FieldSchema.custom_settings) != null ? ref.hide_reverse_info : void 0) {
      return false;
    }
    return true;
  };

  ReverseLinkedTable.prototype.renderForEditor = function(data, top_level_data, opts) {
    var poll_listener, ref;
    if (opts.editor && ((ref = data[this.name()]) != null ? ref.length : void 0) > 0) {
      opts.editor.clearPollListener(this.fullName());
      poll_listener = EventPoller.listen({
        instance: data[this.name() + ":rendered"],
        filter: {
          type: ['OBJECT_UPDATE', 'OBJECT_DELETE']
        },
        call: (function(_this) {
          return function(events) {
            var asked, event, event_gid, i, idx, j, len, len1, obj, objs;
            if (!opts.editor || opts.editor.isDestroyed()) {
              _this.__poll_listener.destroy();
              return;
            }
            asked = false;
            for (i = 0, len = events.length; i < len; i++) {
              event = events[i];
              if (asked) {
                return;
              }
              event_gid = event.global_object_id;
              if (!event_gid) {
                return;
              }
              objs = data[_this.name()];
              for (idx = j = 0, len1 = objs.length; j < len1; idx = ++j) {
                obj = objs[idx];
                if (obj._global_object_id === event_gid) {
                  if (obj._version !== event.object_version) {
                    asked = true;
                    _this.__askForVersionChanged(data, top_level_data, opts.editor);
                    break;
                  }
                  return;
                }
              }
            }
          };
        })(this)
      });
      opts.editor.registerPollListener(this.fullName(), poll_listener);
    }
    return ReverseLinkedTable.__super__.renderForEditor.call(this, data, top_level_data, opts);
  };

  ReverseLinkedTable.prototype.__askForVersionChanged = function(data, top_level_data, editor) {
    var ro;
    ro = new ResultObject().setData(top_level_data);
    if (!ro.getId()) {
      console.warn("ReverseLinkedTable.__askForVersionChanged: no id found");
      return;
    }
    ro.loadFromDb().done((function(_this) {
      return function() {
        var comment, lastChange, mod, ref, replace;
        lastChange = (ref = ro.getData()._changelog) != null ? ref.slice(-1)[0] : void 0;
        replace = {
          user: (lastChange != null ? lastChange.user.user._generated_displayname : void 0) || "unknown",
          fieldname: _this.fullNameLocalized()
        };
        if (CUI.util.isEmpty(typeof last_change !== "undefined" && last_change !== null ? last_change.comment : void 0)) {
          comment = new CUI.EmptyLabel({
            text: $$("main.editor.version_changed.no_comment")
          });
        } else {
          comment = new CUI.EmptyLabel({
            text: last_change.comment
          });
        }
        mod = new CUI.ConfirmationDialog({
          title: $$("main.editor.reverse_version_changed.title"),
          content: [
            new CUI.MultilineLabel({
              text: $$("main.editor.reverse_version_changed.explain", replace),
              markdown: true
            }), comment
          ],
          buttons: [
            {
              text: $$("main.editor.version_changed.button.discard_changes"),
              primary: true,
              onClick: function(ev) {
                var new_initial_data, objecttype, ref1, ref2;
                mod.destroy();
                objecttype = ro.objecttype();
                top_level_data[objecttype][_this.name()] = CUI.util.copyObject(ro.getData()[objecttype][_this.name()], true);
                editor.updateData(top_level_data);
                _this.getSaveData(data, new_initial_data = {}, {
                  init_save_data: true
                });
                if ((ref1 = editor.object.__initSaveData) != null) {
                  if ((ref2 = ref1[objecttype]) != null) {
                    ref2[_this.name()] = new_initial_data[_this.name()];
                  }
                }
                return editor.reloadEditor();
              }
            }
          ]
        });
        mod.show();
        return editor != null ? editor.onAskForVersionChanged(function() {
          if (mod) {
            return mod.destroy();
          }
        }) : void 0;
      };
    })(this));
  };

  ReverseLinkedTable.prototype.renderRowTools = function(row_data, data, opts) {
    var tools_btn;
    if (!this.rowToolsVisible(row_data, data, opts)) {
      return;
    }
    tools_btn = new LocaButton({
      hidden: true,
      appearance: "flat",
      icon_right: false,
      loca_key: "toolbox.flyout_buttonbar_side_menu_button",
      menu: {
        has_items: true,
        items: (function(_this) {
          return function() {
            var current_tools, dfr;
            if (current_tools) {
              return current_tools;
            }
            dfr = new CUI.Deferred();
            _this.loadCurrentTools({
              data: row_data,
              detail: opts.detail,
              getElement: function() {
                return tools_btn;
              }
            }).done(function(tools) {
              return dfr.resolve(Toolbox.getMenuItemsWithFallback(tools));
            }).fail(function() {
              return dfr.resolve([]);
            });
            current_tools = dfr.promise();
            return current_tools;
          };
        })(this)
      }
    }, this.__searchObjectById(row_data._id).done((function(_this) {
      return function() {
        return tools_btn.show();
      };
    })(this)));
    return [tools_btn];
  };

  ReverseLinkedTable.prototype.appendRow = function(content, row_data, data, opts, pos) {
    var hl_wrap, nestedTableFunction, output;
    if (pos == null) {
      pos = null;
    }
    nestedTableFunction = opts.nestedTableFunc;
    output = ReverseLinkedTable.__super__.appendRow.call(this, content, row_data, data, opts, pos);
    opts.nestedTableFunc = nestedTableFunction;
    if (opts.for_print) {
      return output;
    }
    if (opts.nestedTableFunc === 'renderForDetail') {
      hl_wrap = new CUI.HorizontalLayout({
        "class": "ez5-linked-object-container ez5-linked-object-container--reverse-detail",
        center: {
          "class": "fields-renderer-plain fields-renderer-plain--multi-column",
          content: output.childNodes
        },
        right: {
          content: this.renderRowTools(row_data, data, opts)
        }
      });
      CUI.dom.append(output, hl_wrap);
      CUI.dom.removeClass(output, "ez5-field-group");
    } else {
      CUI.dom.addClass(output, "ez5-linked-object-container ez5-linked-object-container--reverse-editor");
      CUI.dom.addClass(output.center(), "fields-renderer-plain fields-renderer-plain--multi-column");
      CUI.dom.removeClass(output.center(), "ez5-field-group");
    }
    return output;
  };

  ReverseLinkedTable.prototype.supportsRowMove = function() {
    return true;
  };

  ReverseLinkedTable.prototype.renderEditorInput = function(data, top_level_data) {
    var mode;
    mode = "editor-reverse-linked-table";
    return ReverseLinkedTable.__super__.renderEditorInput.call(this, data, top_level_data, mode);
  };

  ReverseLinkedTable.prototype.invokeOnFields = function(mode, dive_nested, callback, data, depth) {
    if (depth == null) {
      depth = 0;
    }
    if (this.FieldSchema.hierarchical_mask_hint) {
      return;
    }
    return ReverseLinkedTable.__super__.invokeOnFields.call(this, mode, dive_nested, callback, data, depth);
  };

  ReverseLinkedTable.prototype.__rowHasData = function(row, opts) {
    if (opts == null) {
      opts = {};
    }
    if (row._id) {
      return true;
    }
    return ReverseLinkedTable.__super__.__rowHasData.call(this, row, opts);
  };

  ReverseLinkedTable.prototype.getSaveData = function(data, save_data, opts) {
    var i, idx, j, k, len, len1, len2, ref, ref1, ref2, ref3, ref4, remove_keys, row, row_on_load, version;
    if (opts.demo_data) {
      return;
    }
    ReverseLinkedTable.__super__.getSaveData.call(this, data, save_data, opts);
    if (this.supportsRowMove()) {
      ref = save_data[this.name()];
      for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
        row = ref[idx];
        row.__idx = idx;
      }
    }
    if (opts.init_save_data && !opts.new_mode) {
      ref1 = save_data[this.name()];
      for (idx = j = 0, len1 = ref1.length; j < len1; idx = ++j) {
        row = ref1[idx];
        data[this.name()][idx]._row_on_load = CUI.util.copyObject(row, true);
      }
    }
    if (opts.bulk || opts.check) {
      return;
    }
    remove_keys = (function(_this) {
      return function(row) {
        var key, value;
        for (key in row) {
          value = row[key];
          if (key === "_id" || key === "_version") {
            continue;
          }
          delete row[key];
        }
      };
    })(this);
    ref2 = save_data[this.name()];
    for (idx = k = 0, len2 = ref2.length; k < len2; idx = ++k) {
      row = ref2[idx];
      row_on_load = (ref3 = data[this.name()][idx]) != null ? ref3._row_on_load : void 0;
      version = (ref4 = data[this.name()][idx]) != null ? ref4._version : void 0;
      if (opts.copy) {
        delete row._version;
        delete row._id;
        continue;
      }
      if (!row_on_load) {
        if (!version) {
          row._version = 1;
        } else {
          row._version = version;
          remove_keys(row);
        }
        continue;
      }
      if (!CUI.util.isEqual(row, row_on_load)) {
        if (version) {
          row._version = version + 1;
        } else {
          row._version = 1;
        }
      } else {
        if (!version) {
          row._version = 1;
        } else {
          row._version = version;
          remove_keys(row);
        }
      }
    }
  };

  ReverseLinkedTable.prototype.isHierarchical = function() {
    return this.FieldSchema.is_hierarchical;
  };

  ReverseLinkedTable.prototype.name = function() {
    if (this.isHierarchical()) {
      return "_reverse_nested:" + this.table.name() + ":_id_parent";
    } else {
      return "_reverse_nested:" + this.table.name() + ":" + this.FieldSchema._reverse_link_column._other_column.name;
    }
  };

  ReverseLinkedTable.prototype.nameLocalized = function() {
    return this.FieldSchema._name_localized;
  };

  ReverseLinkedTable.prototype.hasRenderForSort = function() {
    return false;
  };

  ReverseLinkedTable.prototype.getCSVDestinationFields = function(csvImporter, level, maxLevel) {
    if (level == null) {
      level = 0;
    }
    if (maxLevel == null) {
      maxLevel = 0;
    }
    return ReverseLinkedTable.__super__.getCSVDestinationFields.call(this, csvImporter, level, maxLevel);
  };

  ReverseLinkedTable.showInSearch = function(_opts) {
    var data, field, linkedOtherTableId, linkedTableName, objecttype, objecttypeName, opts, queryElementField, resultObject, reverseLinkedField, search_data, systemObjectIds;
    if (_opts == null) {
      _opts = {};
    }
    opts = CUI.Element.readOpts(_opts, "ReverseLinkedTable.showInSearch", {
      search: {
        mandatory: true,
        check: SearchMain
      },
      result_object: {
        mandatory: true,
        check: ResultObject
      },
      reverse_linked_field: {
        mandatory: true,
        check: ReverseLinkedTable
      }
    });
    reverseLinkedField = opts.reverse_linked_field;
    resultObject = opts.result_object;
    search_data = {};
    objecttypeName = resultObject.objecttype();
    if (objecttypeName === reverseLinkedField.mask.schema.table_name_hint) {
      field = new SystemObjectIdColumn(reverseLinkedField.mask);
      data = opts.result_object.getData();
      systemObjectIds = data[objecttypeName][reverseLinkedField.name()].map(function(_data) {
        return _data._system_object_id;
      }).join(",");
      search_data[field.name()] = systemObjectIds;
    } else {
      linkedOtherTableId = reverseLinkedField.FieldSchema.other_table_id;
      linkedTableName = reverseLinkedField.FieldSchema.other_column_name_hint;
      objecttype = new Objecttype(Mask.getMaskByMaskName("_all_fields", linkedOtherTableId));
      field = objecttype.getFields("all", false, function(f) {
        return f.name() === linkedTableName;
      })[0];
      if (!field) {
        CUI.util.assert(false, "ReverseLinkedTable.showInSearch", "Linked object in the reverse field not found.", {
          reverse_linked_field: reverseLinkedField
        });
        return;
      }
      data = opts.result_object.getData();
      search_data[field.name()] = [data._global_object_id];
    }
    queryElementField = new QueryElementField({
      data: search_data,
      field: field
    });
    opts.search.showInSearch(queryElementField);
  };

  ReverseLinkedTable.prototype.supportsNestedUUID = function() {
    return false;
  };

  return ReverseLinkedTable;

})(NestedTable);
// Generated by CoffeeScript 1.12.7
var StandardField,
  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;

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

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

  StandardField.prototype.name = function() {
    if (this.__standardVersion) {
      return "_standard." + this.__standardVersion + ".text";
    }
    return "_standard";
  };

  StandardField.prototype.fullName = function() {
    return this.name();
  };

  StandardField.prototype.getSaveData = function() {};

  StandardField.prototype.nameLocalized = function() {
    if (this.__standardVersion) {
      return $$("standard.field." + this.__standardVersion + ".name");
    }
    return $$("standard.field.name");
  };

  StandardField.prototype.isExpertCommon = function(mode) {
    return true;
  };

  StandardField.prototype.renderDetailOutput = function(data, top_level_data, opts) {
    return this.renderTableOutput(data, top_level_data, opts);
  };

  StandardField.prototype.getDataForReplacementRecord = function(data) {
    var ref, standardData, txt;
    if (!data) {
      return;
    }
    standardData = data[this.name()];
    txt = ez5.loca.getBestDatabaseValue(standardData != null ? (ref = standardData["1"]) != null ? ref.text : void 0 : void 0);
    if (CUI.util.isEmpty(txt)) {
      return;
    }
    data = {};
    data["1.text"] = txt;
    return data;
  };

  StandardField.prototype.isTopLevelField = function() {
    return true;
  };

  StandardField.prototype.renderTableOutput = function(data, top_level_data, opts) {
    var resultObject;
    resultObject = (new ResultObject()).setData(top_level_data);
    opts.path = false;
    return resultObject.renderCardResultTable(opts);
  };

  StandardField.prototype.isVisible = function(mode, opts) {
    var isVisible;
    if (opts == null) {
      opts = {};
    }
    if (CUI.util.isFunction(opts.isVisible)) {
      isVisible = opts.isVisible(this, mode, opts);
      if (CUI.util.isBoolean(isVisible)) {
        return isVisible;
      }
    }
    switch (mode) {
      case "sort":
      case "export":
      case "table":
        return true;
      default:
        return false;
    }
  };

  StandardField.prototype.isSortUnique = function() {
    return true;
  };

  StandardField.prototype.getSortFields = function() {
    return [1, 2, 3].map(function(key) {
      return "_standard." + key + ".text";
    });
  };

  StandardField.prototype.getMappingSourceFullNameLocalized = function() {
    return this.fullNameLocalized();
  };

  StandardField.prototype.getMappingTargetName = function() {
    if (ez5.version("6")) {
      return this.name();
    }
    return this.name() + ".1";
  };

  StandardField.prototype.isSourceForMapping = function(requiredType) {
    return !requiredType["import"];
  };

  StandardField.prototype.isSystemField = function() {
    return true;
  };

  StandardField.prototype.isEmpty = function(_, top_level_data, opts) {
    if (!opts.for_print) {
      return StandardField.__super__.isEmpty.call(this, _, top_level_data, opts);
    }
    return CUI.util.isEmpty(StandardField.getStandardText(top_level_data));
  };

  StandardField.prototype.setStandardVersion = function(version) {
    return this.__standardVersion = version;
  };

  StandardField.getExportFields = function(standardField) {
    var field, fields, i, len, ref, version;
    if (!(standardField instanceof StandardField)) {
      return [];
    }
    fields = [];
    ref = [1, 2, 3];
    for (i = 0, len = ref.length; i < len; i++) {
      version = ref[i];
      field = new StandardField(standardField.getMask(), standardField.FieldSchema);
      field.setStandardVersion(version);
      fields.push(field);
    }
    return fields;
  };

  StandardField.getStandardText = function(data) {
    var i, key, len, ref, ref1, ref2, text;
    if (!data) {
      return;
    }
    ref = ["1", "2"];
    for (i = 0, len = ref.length; i < len; i++) {
      key = ref[i];
      text = ez5.loca.getBestDatabaseValue((ref1 = data[StandardField.prototype.name()]) != null ? (ref2 = ref1[key]) != null ? ref2.text : void 0 : void 0);
      if (text) {
        return text;
      }
    }
  };

  StandardField.getSeparatorsMap = function() {
    var separators;
    if (ez5.version("6")) {
      separators = this.separatorsMap;
      delete separators["newline"];
      return separators;
    }
    return this.separatorsMap;
  };

  StandardField.separatorsMap = {
    "comma": [", "],
    "space": [" "],
    "colon": [": "],
    "semicolon": ["; "],
    "newline": ["\n"],
    "brackets": ["{", "}"],
    "round-parentheses": ["(", ")"],
    "square-brackets": ["[", "]"],
    "dash": [" - "],
    "pipe": [" | "]
  };

  return StandardField;

})(Field);
// Generated by CoffeeScript 1.12.7
var StringColumn,
  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;

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

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

  StringColumn.prototype._getSearchFilter = function(data, key) {
    if (data[key + ":mode"] === "range") {
      return this.getSearchFilterTokenized(data[key]);
    }
    return StringColumn.__super__._getSearchFilter.call(this, data, key);
  };

  StringColumn.prototype.getFieldOptsForSuggest = function() {
    var opts;
    opts = {
      tokens_dont_split_query: true
    };
    return opts;
  };

  StringColumn.prototype.getTokenizer = function() {
    return new Tokenizer();
  };

  StringColumn.prototype.renderSearchInput = function(data, opts) {
    if (opts == null) {
      opts = {};
    }
    return (new SearchToken({
      column: this,
      data: data,
      fields: opts.fields,
      types: ["fulltext", "token", "tokens"],
      placeholder: $$("data.field.string-column.search.placeholder")
    })).getInput().DOM;
  };

  StringColumn.prototype.sortExtraOpts = function(data) {
    return [
      {
        text: $$("string.column.sort.alphanumeric"),
        value: true
      }, {
        text: $$("string.column.sort.alphabetically"),
        value: false
      }
    ];
  };

  StringColumn.prototype.getSortFields = function(filter, keys) {
    var field, fieldName;
    fieldName = StringColumn.__super__.getSortFields.call(this);
    field = {
      field: fieldName,
      order: filter._order,
      numeric: filter._extra
    };
    return field;
  };

  StringColumn.prototype.getInfoLabels = function(data, top_level_data, opts) {
    var arr, fn;
    if (opts == null) {
      opts = {};
    }
    arr = StringColumn.__super__.getInfoLabels.call(this, data, top_level_data, opts);
    if (!ez5.session.isDebug() || this.insideNested() || opts.mode !== "detail") {
      return arr;
    }
    fn = top_level_data._objecttype + "." + data[this.name()] + ".json";
    arr.push(new CUI.Button({
      icon: "download",
      appearance: "flat",
      tooltip: {
        text: "Download " + fn + ". Hold ALT to display in new window."
      },
      onClick: (function(_this) {
        return function(ev) {
          var wx;
          if (ev.altKey()) {
            wx = window.open("", "_blank");
          }
          ez5.api.db({
            type: "GET",
            api: "/" + top_level_data._objecttype + "/" + top_level_data._mask + "/" + data._id,
            data: {
              format: "long"
            }
          }).fail(function() {
            if (wx != null) {
              wx.close();
            }
            return CUI.problem({
              text: "Error downloading: " + fn
            });
          }).done(function(dbdata) {
            var jdata, pre, ref;
            console.debug("received data", dbdata);
            if (!((ref = dbdata[0]) != null ? ref._system_object_id : void 0)) {
              CUI.problem({
                text: "Error downloading: " + fn
              });
              if (wx != null) {
                wx.close();
              }
              return;
            }
            jdata = JSON.stringify(dbdata[0], "", "    ");
            if (ev.altKey()) {
              pre = CUI.dom.element("PRE");
              pre.innerText = jdata;
              if (wx != null) {
                wx.document.title = fn;
              }
              if (wx != null) {
                wx.document.body.appendChild(pre);
              }
            } else {
              CUI.downloadData(jdata, fn);
            }
          });
        };
      })(this)
    }));
    return arr;
  };

  return StringColumn;

})(TextColumn);
// Generated by CoffeeScript 1.12.7
var MaskField,
  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;

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

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

  MaskField.prototype.isVisible = function(mode, opts) {
    var isVisible;
    if (opts == null) {
      opts = {};
    }
    if (opts.hide_other_system_fields) {
      return false;
    }
    if (CUI.util.isFunction(opts.isVisible)) {
      isVisible = opts.isVisible(this, mode, opts);
      if (CUI.util.isBoolean(isVisible)) {
        return isVisible;
      }
    }
    switch (mode) {
      case "detail-footer":
      case "editor-footer":
      case "export":
        return true;
    }
    return false;
  };

  MaskField.prototype.getReplacementRecord = function() {};

  MaskField.prototype.getDataForFieldData = function(data, top_level_data) {
    return top_level_data;
  };

  MaskField.prototype.isEmpty = function() {
    return false;
  };

  MaskField.prototype.nameLocalized = function() {
    return $$("mask_field.label");
  };

  MaskField.prototype.fillReplacementRecord = function() {};

  MaskField.prototype.getDataAsString = function() {
    return true;
  };

  MaskField.prototype.name = function() {
    return "_mask";
  };

  MaskField.prototype.isTopLevelField = function() {
    return true;
  };

  MaskField.prototype.fullName = function() {
    return this.name();
  };

  MaskField.prototype.getOutputStandard = function() {};

  MaskField.prototype.renderEditorInput = function(data, top_level_data, opts) {
    return this.renderDetailOutput(data, top_level_data, opts);
  };

  MaskField.prototype.renderDetailOutput = function(data, top_level_data, opts) {
    var span;
    span = CUI.dom.span();
    span.textContent = this.getMainMask().nameLocalized();
    return span;
  };

  MaskField.prototype.isSourceForMapping = function(required_type) {
    return false;
  };

  return MaskField;

})(DataColumn);
// Generated by CoffeeScript 1.12.7
var SystemObjectIdColumn,
  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;

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

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

  SystemObjectIdColumn.prototype.nameLocalized = function() {
    return $$("base.system_object_id_column.name");
  };

  SystemObjectIdColumn.prototype.isVisible = function(mode, opts) {
    var isVisible;
    if (opts == null) {
      opts = {};
    }
    if (CUI.util.isFunction(opts.isVisible)) {
      isVisible = opts.isVisible(this, mode, opts);
      if (CUI.util.isBoolean(isVisible)) {
        return isVisible;
      }
    }
    if (opts.hide_system_object_id) {
      return false;
    }
    if (opts.for_print) {
      return false;
    }
    if (opts.hide_other_system_fields) {
      return false;
    }
    switch (mode) {
      case "sort":
        if (this.mask.nestedTableField) {
          return false;
        }
        return true;
      case "expert":
      case "csv-import":
      case "export":
      case "detail-footer":
      case "editor-footer":
      case "table":
        return true;
    }
    if (mode === "text") {
      return true;
    }
    return false;
  };

  SystemObjectIdColumn.prototype.renderEditorInput = function(data, top_level_data) {
    if (this.isEmpty(data, top_level_data)) {
      return SystemObjectIdColumn.__super__.renderEditorInput.call(this, top_level_data);
    }
    return this.renderDetailOutput(data, top_level_data);
  };

  SystemObjectIdColumn.prototype.renderData = function(data) {
    var html, ref, value;
    ref = SystemObjectIdColumn.__super__.renderData.call(this, data), value = ref[0], html = ref[1];
    value = "#" + value;
    return [value, html];
  };

  SystemObjectIdColumn.prototype.renderDetailOutput = function(data, top_level_data, opts) {
    var _system_object_id;
    _system_object_id = top_level_data != null ? top_level_data._system_object_id : void 0;
    if (!top_level_data) {
      _system_object_id = data._system_object_id;
    }
    return new CUI.Label({
      text: "#" + _system_object_id
    });
  };

  SystemObjectIdColumn.prototype.getSaveData = function(data, save_data, opts) {
    if (opts.demo_data) {
      save_data._top_level[this.name()] = this.__getDemoData();
      return;
    }
  };

  SystemObjectIdColumn.prototype.__getDemoData = function() {
    return Math.floor(Math.random() * 100) + 1;
  };

  SystemObjectIdColumn.prototype.name = function() {
    return "_system_object_id";
  };

  SystemObjectIdColumn.prototype.fullName = function() {
    if (this.mask.nestedTableField) {
      return SystemObjectIdColumn.__super__.fullName.call(this);
    }
    return this.name();
  };

  SystemObjectIdColumn.prototype.isEmpty = function(data, top_level_data) {
    return CUI.util.isEmpty(top_level_data != null ? top_level_data[this.name()] : void 0);
  };

  SystemObjectIdColumn.prototype.isExpertCommon = function(mode) {
    return true;
  };

  SystemObjectIdColumn.prototype.isSortUnique = function() {
    return true;
  };

  SystemObjectIdColumn.prototype.isSortGroupable = function() {
    return false;
  };

  SystemObjectIdColumn.prototype.isTopLevelField = function() {
    return true;
  };

  SystemObjectIdColumn.prototype.getMappingSourceFullNameLocalized = function() {
    return this.fullNameLocalized();
  };

  SystemObjectIdColumn.prototype.isSourceForMapping = function(required_type) {
    if (required_type["export"]) {
      return true;
    } else {
      return false;
    }
  };

  return SystemObjectIdColumn;

})(PrimaryKeyColumn);
// Generated by CoffeeScript 1.12.7
var UuidColumn,
  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;

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

  function UuidColumn() {
    this.getQueryFieldBadge = bind(this.getQueryFieldBadge, this);
    return UuidColumn.__super__.constructor.apply(this, arguments);
  }

  UuidColumn.prototype.nameLocalized = function() {
    return $$("base.uuid_column.name");
  };

  UuidColumn.prototype.name = function() {
    return "_uuid";
  };

  UuidColumn.prototype.isTopLevelField = function() {
    return true;
  };

  UuidColumn.prototype.isSystemField = function() {
    return true;
  };

  UuidColumn.prototype.isReadOnly = function() {
    return true;
  };

  UuidColumn.prototype.isVisible = function(mode, opts) {
    if (opts == null) {
      opts = {};
    }
    if (opts.for_print) {
      return false;
    }
    if (opts.hide_other_system_fields) {
      return false;
    }
    switch (mode) {
      case "export":
      case "expert":
      case "detail-footer":
      case "editor-footer":
        return true;
    }
    return false;
  };

  UuidColumn.prototype.renderEditorInput = function(data, top_level_data) {
    return this.renderDetailOutput(data, top_level_data);
  };

  UuidColumn.prototype.renderDetailOutput = function(data, top_level_data) {
    return new CUI.Label({
      text: "" + top_level_data[this.name()]
    });
  };

  UuidColumn.prototype.renderSearchInput = function(data) {
    var input;
    input = new CUI.Input({
      name: this.name(),
      placeholder: "57730baa-1342-4d77-971e-8c83e9241ac8",
      id: this.idAttribute(data),
      onDataChanged: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            node: input,
            type: "search-input-change"
          });
        };
      })(this),
      data: data
    }).start();
    return input.DOM;
  };

  UuidColumn.prototype.getTokenizer = function() {
    return new Tokenizer();
  };

  UuidColumn.prototype.getSearchFilter = function(data, key) {
    var f, filter, i, len, t, tokens;
    if (key == null) {
      key = this.name();
    }
    if (!data[this.name()]) {
      return;
    }
    tokens = (this.getTokenizer()).tokenize(data[this.name()]);
    if (tokens.length === 0) {
      return;
    }
    if (tokens.length > 1) {
      filter = {
        type: "complex",
        search: []
      };
      for (i = 0, len = tokens.length; i < len; i++) {
        t = tokens[i];
        f = this._getSearchFilter(t.text);
        f.bool = "should";
        filter.search.push(f);
      }
      if (filter.length === 0) {
        return;
      } else {
        return filter;
      }
    } else {
      return this._getSearchFilter(tokens[0].text);
    }
  };

  UuidColumn.prototype.getSearchUnsetElement = function(data) {};

  UuidColumn.prototype._getSearchFilter = function(val) {
    if (!val) {
      return false;
    }
    return {
      type: "in",
      fields: [this.name()],
      "in": [val]
    };
  };

  UuidColumn.prototype.getDataAsString = function(data) {
    if (CUI.util.isEmpty(data[this.name()])) {
      return "";
    } else {
      return "" + data[this.name()];
    }
  };

  UuidColumn.prototype.getQueryFieldBadge = function(data) {
    return {
      name: "UUID",
      value: data[this.name()]
    };
  };

  UuidColumn.prototype.isEmpty = function(data, top_level_data) {
    return CUI.util.isEmpty(top_level_data != null ? top_level_data[this.name()] : void 0);
  };

  UuidColumn.prototype.isExpertCommon = function(mode) {
    return true;
  };

  UuidColumn.prototype.isSourceForMapping = function(requiredType) {
    return !requiredType["import"];
  };

  UuidColumn.prototype.isVisibleToSaveData = function() {
    return false;
  };

  return UuidColumn;

})(Field);
// Generated by CoffeeScript 1.12.7
var CreatedColumn,
  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;

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

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

  CreatedColumn.prototype.nameLocalized = function() {
    return $$("base.created_column.name");
  };

  CreatedColumn.prototype.name = function() {
    return "_created";
  };

  CreatedColumn.prototype.isTopLevelField = function() {
    return true;
  };

  CreatedColumn.prototype.isSystemField = function() {
    return true;
  };

  CreatedColumn.prototype.isReadOnly = function() {
    return true;
  };

  CreatedColumn.prototype.isVisible = function(mode, opts) {
    var isVisible, ref;
    if (opts == null) {
      opts = {};
    }
    if (!((ref = opts.top_level_data) != null ? ref._created : void 0)) {
      return false;
    }
    if (opts.hide_other_system_fields) {
      return false;
    }
    if (CUI.util.isFunction(opts.isVisible)) {
      isVisible = opts.isVisible(this, mode, opts);
      if (CUI.util.isBoolean(isVisible)) {
        return isVisible;
      }
    }
    switch (mode) {
      case "detail-footer":
      case "editor-footer":
      case "export":
        return true;
    }
    return false;
  };

  CreatedColumn.prototype.isSourceForMapping = function() {
    return false;
  };

  CreatedColumn.prototype.isVisibleToSaveData = function() {
    return false;
  };

  CreatedColumn.prototype.isValidMappingField = function(level) {
    return level === 0;
  };

  CreatedColumn.prototype.getDataAsString = function(data) {
    return ez5.format_date_and_time(data._created, false);
  };

  CreatedColumn.prototype.renderDetailOutput = function(data, top_level_data) {
    return new CUI.Label({
      text: this.getDataAsString(top_level_data)
    });
  };

  CreatedColumn.prototype.renderEditorInput = function(data, top_level_data) {
    return new CUI.Label({
      text: this.getDataAsString(top_level_data)
    });
  };

  CreatedColumn.prototype.getOutputStandard = function() {
    return null;
  };

  CreatedColumn.prototype.fullName = function() {
    return this.name();
  };

  CreatedColumn.prototype.isEmpty = function() {
    return false;
  };

  return CreatedColumn;

})(Field);
// Generated by CoffeeScript 1.12.7
var FormatColumn,
  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;

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

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

  FormatColumn.prototype.nameLocalized = function() {
    return $$("base.format_column.name");
  };

  FormatColumn.prototype.name = function() {
    return "_format";
  };

  FormatColumn.prototype.isTopLevelField = function() {
    return true;
  };

  FormatColumn.prototype.isSystemField = function() {
    return true;
  };

  FormatColumn.prototype.isReadOnly = function() {
    return true;
  };

  FormatColumn.prototype.isVisible = function(mode) {
    if (mode === "export" && ez5.version("6")) {
      return true;
    }
    return false;
  };

  FormatColumn.prototype.isSourceForMapping = function() {
    return false;
  };

  FormatColumn.prototype.isVisibleToSaveData = function() {
    return false;
  };

  return FormatColumn;

})(Field);
// Generated by CoffeeScript 1.12.7
var HasChildrenColumn,
  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;

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

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

  HasChildrenColumn.prototype.nameLocalized = function() {
    return $$("base.has_children_column.name");
  };

  HasChildrenColumn.prototype.name = function() {
    return "_has_children";
  };

  HasChildrenColumn.prototype.isTopLevelField = function() {
    return true;
  };

  HasChildrenColumn.prototype.isSystemField = function() {
    return true;
  };

  HasChildrenColumn.prototype.isReadOnly = function() {
    return true;
  };

  HasChildrenColumn.prototype.isVisible = function(mode) {
    if (mode === "export") {
      return true;
    }
    return false;
  };

  HasChildrenColumn.prototype.isSourceForMapping = function() {
    return false;
  };

  HasChildrenColumn.prototype.isVisibleToSaveData = function() {
    return false;
  };

  HasChildrenColumn.prototype.isValidMappingField = function(level) {
    return level === 0;
  };

  return HasChildrenColumn;

})(Field);
// Generated by CoffeeScript 1.12.7
var SystemObjectIdParentColumn,
  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;

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

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

  SystemObjectIdParentColumn.prototype.nameLocalized = function() {
    return $$("base.system_object_id_parent_column.name");
  };

  SystemObjectIdParentColumn.prototype.name = function() {
    return "_system_object_id_parent";
  };

  SystemObjectIdParentColumn.prototype.isTopLevelField = function() {
    return true;
  };

  SystemObjectIdParentColumn.prototype.isSystemField = function() {
    return true;
  };

  SystemObjectIdParentColumn.prototype.isReadOnly = function() {
    return true;
  };

  SystemObjectIdParentColumn.prototype.isVisible = function(mode) {
    if (mode === "export") {
      return true;
    }
    return false;
  };

  SystemObjectIdParentColumn.prototype.isSourceForMapping = function() {
    return false;
  };

  SystemObjectIdParentColumn.prototype.isVisibleToSaveData = function() {
    return false;
  };

  return SystemObjectIdParentColumn;

})(Field);
// Generated by CoffeeScript 1.12.7
var PathColumn,
  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;

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

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

  PathColumn.prototype.nameLocalized = function() {
    return $$("base.path_column.name");
  };

  PathColumn.prototype.name = function() {
    return "_path";
  };

  PathColumn.prototype.isTopLevelField = function() {
    return true;
  };

  PathColumn.prototype.isSystemField = function() {
    return true;
  };

  PathColumn.prototype.isReadOnly = function() {
    return true;
  };

  PathColumn.prototype.isVisible = function(mode) {
    if (mode === "export") {
      return true;
    }
    return false;
  };

  PathColumn.prototype.isSourceForMapping = function() {
    return false;
  };

  PathColumn.prototype.isVisibleToSaveData = function() {
    return false;
  };

  PathColumn.prototype.isValidMappingField = function(level) {
    return level > 0;
  };

  return PathColumn;

})(Field);
// Generated by CoffeeScript 1.12.7
var PathsColumn,
  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;

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

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

  PathsColumn.prototype.nameLocalized = function() {
    return $$("base.paths_column.name");
  };

  PathsColumn.prototype.name = function() {
    return "_paths";
  };

  PathsColumn.prototype.isTopLevelField = function() {
    return true;
  };

  PathsColumn.prototype.isSystemField = function() {
    return true;
  };

  PathsColumn.prototype.isReadOnly = function() {
    return true;
  };

  PathsColumn.prototype.isVisible = function(mode) {
    if (mode === "export") {
      return true;
    }
    return false;
  };

  PathsColumn.prototype.isSourceForMapping = function() {
    return false;
  };

  PathsColumn.prototype.isVisibleToSaveData = function() {
    return false;
  };

  PathsColumn.prototype.isValidMappingField = function(level) {
    return level > 0;
  };

  return PathsColumn;

})(Field);
// Generated by CoffeeScript 1.12.7
var ParentChildIdxColumn,
  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;

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

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

  ParentChildIdxColumn.prototype.nameLocalized = function() {
    return $$("base.parent_child_idx_column.name");
  };

  ParentChildIdxColumn.prototype.name = function() {
    return "_parent_child_idx";
  };

  ParentChildIdxColumn.prototype.isTopLevelField = function() {
    return false;
  };

  ParentChildIdxColumn.prototype.isSystemField = function() {
    return true;
  };

  ParentChildIdxColumn.prototype.isReadOnly = function() {
    return true;
  };

  ParentChildIdxColumn.prototype.isVisible = function(mode) {
    if (mode === "export") {
      return true;
    }
    return false;
  };

  ParentChildIdxColumn.prototype.isSourceForMapping = function() {
    return false;
  };

  ParentChildIdxColumn.prototype.isVisibleToSaveData = function() {
    return false;
  };

  ParentChildIdxColumn.prototype.isValidMappingField = function() {
    return ez5.version("6");
  };

  return ParentChildIdxColumn;

})(Field);
// Generated by CoffeeScript 1.12.7
var GlobalObjectIdColumn,
  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;

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

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

  GlobalObjectIdColumn.prototype.nameLocalized = function() {
    return $$("base.global_object_id_column.name");
  };

  GlobalObjectIdColumn.prototype.isVisible = function(mode, opts) {
    var isVisible;
    if (opts == null) {
      opts = {};
    }
    if (CUI.util.isFunction(opts.isVisible)) {
      isVisible = opts.isVisible(this, mode, opts);
      if (CUI.util.isBoolean(isVisible)) {
        return isVisible;
      }
    }
    switch (mode) {
      case "csv-import":
      case "export":
        return true;
      default:
        return false;
    }
  };

  GlobalObjectIdColumn.prototype.__getDemoData = function() {
    return GlobalObjectIdColumn.__super__.__getDemoData.call(this) + "@local";
  };

  GlobalObjectIdColumn.prototype.name = function() {
    return "_global_object_id";
  };

  GlobalObjectIdColumn.prototype.getCSVDestinationFields = function(csvImporter) {
    var dest_field;
    dest_field = {
      format: "string",
      field: this,
      use_for_match_existing: true,
      supports_hierarchy: false,
      read_only: true,
      csvImporter: csvImporter
    };
    return [new ObjecttypeCSVImporterDestinationField(dest_field)];
  };

  GlobalObjectIdColumn.prototype.isSourceForMapping = function() {
    return false;
  };

  return GlobalObjectIdColumn;

})(SystemObjectIdColumn);
// Generated by CoffeeScript 1.12.7
var PublishColumn,
  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;

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

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

  PublishColumn.prototype.isTopLevelField = function() {
    return true;
  };

  PublishColumn.prototype.isExpertCommon = function() {
    return true;
  };

  PublishColumn.prototype.nameLocalized = function() {
    return $$("publish.column.name");
  };

  PublishColumn.prototype.isVisibleToSaveData = function() {
    return false;
  };

  PublishColumn.prototype.isVisible = function(mode, opts) {
    var isVisible;
    if (opts == null) {
      opts = {};
    }
    if (CUI.util.isFunction(opts.isVisible)) {
      isVisible = opts.isVisible(this, mode, opts);
      if (CUI.util.isBoolean(isVisible)) {
        return isVisible;
      }
    }
    return PublishColumn.isVisible(mode, this.getMainMask());
  };

  PublishColumn.isVisible = function(mode, mask) {
    var output_mode, ref, ref1;
    output_mode = (ref = mask.schema) != null ? (ref1 = ref.system_fields.publish) != null ? ref1.output.mode : void 0 : void 0;
    switch (mode) {
      case "detail-header":
      case "expert":
        if (output_mode === "show") {
          return true;
        }
    }
    return false;
  };

  PublishColumn.prototype.getOutputStandard = function() {
    return null;
  };

  PublishColumn.prototype.name = function() {
    return "_published";
  };

  PublishColumn.prototype.fullName = function() {
    return this.name();
  };

  PublishColumn.prototype.getSearchUnsetElement = function() {};

  PublishColumn.prototype.getSearchFilter = function(data, key) {
    var _data, dateFrom, dateTo, filters, searchFilter, value;
    if (key == null) {
      key = this.name();
    }
    filters = [];
    dateFrom = data.timestamp_created_from;
    dateTo = data.timestamp_created_to;
    if (dateFrom || dateTo) {
      filters.push({
        type: "range",
        field: this.name() + ".timestamp_created",
        from: dateFrom,
        to: dateTo
      });
    }
    _data = {};
    if (data.publish_uri) {
      _data.publish_uri = data.publish_uri;
    }
    if (data.collector) {
      _data.collector = data.collector.internalname;
    }
    for (key in _data) {
      value = _data[key];
      _data[key + ":type"] = "fulltext";
      _data[key + ":mode"] = "fulltext";
      filters.push(TextColumn.getSearchFilter((this.name()) + "." + key, _data, key, _data[key]));
    }
    if (filters.length === 0) {
      return;
    }
    searchFilter = {
      type: "complex",
      search: filters
    };
    return searchFilter;
  };

  PublishColumn.prototype.renderSearchInput = function(data) {
    var form;
    form = new CUI.Form({
      data: data,
      fields: [
        {
          type: CUI.Form,
          "class": "ez5-date-range-form",
          fields: [
            {
              type: CUI.DateTime,
              input_types: ["date"],
              display_type: "short",
              placeholder: $$("publish.column.search.placeholder.timestamp_created.from"),
              name: "timestamp_created_from"
            }, {
              type: CUI.DateTime,
              input_types: ["date"],
              display_type: "short",
              placeholder: $$("publish.column.search.placeholder.timestamp_created.to"),
              name: "timestamp_created_to"
            }
          ]
        }, ez5.PublishDetailPlugin.getCollectorSelect({
          placeholder: $$("publish.column.search.placeholder.collector")
        }), {
          type: CUI.Input,
          name: "publish_uri",
          placeholder: $$("publish.column.search.placeholder.publish_uri")
        }
      ],
      onDataChanged: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            node: form,
            type: "search-input-change"
          });
        };
      })(this)
    });
    form.start();
    return form;
  };

  PublishColumn.prototype.renderDetailOutput = function(_, top_level_data) {
    var fn, i, len, list, publication, publications;
    publications = PublishColumn.getPublications(top_level_data[this.name()]);
    list = CUI.dom.ul();
    fn = (function(_this) {
      return function(publication) {
        var collector, displayFormat, displayNameValue, infoButton, internalname, item, label, url;
        item = CUI.dom.li();
        url = publication.url;
        internalname = publication.collector;
        collector = PublishColumn.getCollectorFromBaseConfig(internalname);
        if (collector) {
          displayNameValue = ez5.loca.getBestFrontendValue(collector.displayname) || collector.internalname;
          infoButton = new LocaButton({
            loca_key: "publish.detail.button.info",
            appearance: "flat",
            "class": "ez5-path-info-button",
            onClick: function() {
              var asset, copyButton, logoDiv, popover, popoverContent, prefixButton, ref, urlButton;
              popoverContent = new CUI.Template({
                name: "publish-column-popover",
                map: {
                  logo: true,
                  displayname: true,
                  prefix_url: true,
                  type: true,
                  url: true,
                  timestamp_created: true,
                  copy_button: true
                }
              });
              if ((ref = collector.logo) != null ? ref._id : void 0) {
                logoDiv = popoverContent.get("logo");
                asset = new AssetPlain({
                  value: collector.logo
                });
                CUI.dom.append(logoDiv, asset.getImgElement(null, "original"));
              }
              popoverContent.append(new CUI.Label({
                size: "big",
                appearance: "title",
                text: displayNameValue
              }), "displayname");
              if (collector.prefix) {
                prefixButton = new CUI.ButtonHref({
                  appearance: "link",
                  target: "_blank",
                  text: collector.prefix,
                  href: collector.prefix
                });
                popoverContent.append(prefixButton, "prefix_url");
              }
              if (collector.type) {
                popoverContent.append(new CUI.Label({
                  text: collector.type + ":"
                }), "type");
              }
              urlButton = new CUI.ButtonHref({
                appearance: "link",
                target: "_blank",
                text: url,
                href: url
              });
              popoverContent.append(urlButton, "url");
              copyButton = new LocaButton({
                size: "mini",
                loca_key: "publish.detail.popover.field.copy_button",
                onClick: function() {
                  return CUI.util.copyToClipboard(url);
                }
              });
              popoverContent.append(copyButton, "copy_button");
              popoverContent.append(new CUI.Label({
                text: $$("publish.detail.popover.field.timestamp_created", {
                  value: ez5.format_date_and_time(publication.timestamp_created)
                })
              }), "timestamp_created");
              popoverContent.removeEmptySlots();
              popover = new ez5.HintPopover({
                padded: false,
                element: infoButton,
                content: popoverContent
              });
              return popover.show();
            }
          });
          displayFormat = collector.display_format || "name_type_doi";
          label = new CUI.Label({
            text: $$("publish.column.detail.list-item." + displayFormat + ".md", {
              url: url,
              uri: publication.publish_uri,
              type: collector.type || "-",
              name: displayNameValue
            }),
            markdown: true
          });
          CUI.dom.append(item, infoButton);
        } else {
          label = new CUI.Label({
            text: url
          });
        }
        CUI.dom.prepend(item, label);
        return CUI.dom.append(list, item);
      };
    })(this);
    for (i = 0, len = publications.length; i < len; i++) {
      publication = publications[i];
      fn(publication);
    }
    return list;
  };

  PublishColumn.getPublications = function(data) {
    var _, collector, i, internalname, len, publication, publications, publicationsMap, timestamp, url, value;
    if (!data) {
      return [];
    }
    publicationsMap = {};
    for (i = 0, len = data.length; i < len; i++) {
      publication = data[i];
      internalname = publication.collector;
      if (!internalname) {
        continue;
      }
      url = publication.publish_uri;
      collector = PublishColumn.getCollectorFromBaseConfig(internalname);
      if (collector != null ? collector.prefix : void 0) {
        url = collector.prefix + url;
      }
      if (publicationsMap[url]) {
        timestamp = publicationsMap[url].timestamp_created;
        if (CUI.util.moment(timestamp).isAfter(publication.timestamp_created)) {
          continue;
        }
      }
      publication.url = url;
      publicationsMap[url] = publication;
    }
    publications = [];
    for (_ in publicationsMap) {
      value = publicationsMap[_];
      publications.push(value);
    }
    publications.sort((function(_this) {
      return function(a, b) {
        if (CUI.util.moment(a.timestamp_created).isBefore(b.timestamp_created)) {
          return 1;
        } else {
          return -1;
        }
      };
    })(this));
    return publications;
  };

  PublishColumn.prototype.isEmpty = function(_, top_level_data) {
    var ref;
    if (((ref = top_level_data[this.name()]) != null ? ref.length : void 0) > 0) {
      return false;
    } else {
      return true;
    }
  };

  PublishColumn.prototype.isSourceForMapping = function(required_type) {
    return false;
  };

  PublishColumn.prototype.getQueryFieldBadge = function(data) {
    var badge, dateFrom, dateRangeValue, dateTo, value, values;
    values = [];
    dateFrom = ez5.format_date(data.timestamp_created_from);
    dateTo = ez5.format_date(data.timestamp_created_to);
    if (dateFrom && dateTo) {
      dateRangeValue = $$("publish.column.search.badge.value.timestamp_created.from-to", {
        from: dateFrom,
        to: dateTo
      });
    } else if (dateFrom) {
      dateRangeValue = $$("publish.column.search.badge.value.timestamp_created.from", {
        date: dateFrom
      });
    } else if (dateTo) {
      dateRangeValue = $$("publish.column.search.badge.value.timestamp_created.to", {
        date: dateTo
      });
    }
    if (dateRangeValue) {
      values.push($$("publish.column.search.badge.value.timestamp_created", {
        dateRange: dateRangeValue
      }));
    }
    if (data.publish_uri) {
      values.push($$("publish.column.search.badge.value.publish_uri", {
        value: data.publish_uri
      }));
    }
    if (data.collector) {
      value = ez5.loca.getBestFrontendValue(data.collector.displayname) || data.collector.internalname;
      values.push($$("publish.column.search.badge.value.collector", {
        value: value
      }));
    }
    badge = {
      name: $$("publish.column.search.badge.name"),
      value: values.join(", ")
    };
    return badge;
  };

  PublishColumn.getCollectorFromBaseConfig = function(collectionName) {
    var _collector, i, len, ref, ref1;
    ref1 = ((ref = ez5.session.getBaseConfig().publish) != null ? ref.collectors : void 0) || [];
    for (i = 0, len = ref1.length; i < len; i++) {
      _collector = ref1[i];
      if (_collector.internalname === collectionName) {
        return _collector;
      }
    }
    return null;
  };

  return PublishColumn;

})(DataColumn);
// Generated by CoffeeScript 1.12.7
var TagsField, TagsFieldForBaseConfig, TagsFieldForEditor,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  TagsField.prototype.name = function() {
    return "_tags";
  };

  TagsField.prototype.nameLocalized = function() {
    return $$("tags.field.name");
  };

  TagsField.prototype.getReplacementRecord = function() {};

  TagsField.prototype.getMappingSourceFullNameLocalized = function() {};

  TagsField.prototype.getMappingSourceFullNameLocalized = function() {
    return this.fullNameLocalized();
  };

  TagsField.prototype.isExpertCommon = function(mode) {
    return true;
  };

  TagsField.prototype.getDataAsString = function(data, top_level_data) {
    var str;
    str = JSON.stringify(top_level_data[this.name()]);
    return str;
  };

  TagsField.prototype.getDataForFieldData = function(data, top_level_data) {
    return top_level_data;
  };

  TagsField.prototype.getSaveData = function(data, save_data, opts) {
    var i, j, len, len1, ref, tag, tagData, tags;
    if (opts.demo_data) {
      tags = [];
      ref = ez5.tagForm.getAllTags();
      for (i = 0, len = ref.length; i < len; i++) {
        tag = ref[i];
        if (tag.getDisplayType() === "hidden") {
          continue;
        }
        tags.push({
          _id: tag.getId()
        });
      }
      save_data._top_level._tags = tags;
      return;
    }
    if (this.insideNested()) {
      return;
    }
    tags = data._top_level[this.name()] || [];
    if (tags.length === 0 && data._top_level._template) {
      tags = data._top_level._template[this.name()] || [];
    }
    if (ez5.version("6") && tags.length > 0) {
      save_data._top_level._tags = [];
      for (j = 0, len1 = tags.length; j < len1; j++) {
        tag = tags[j];
        tagData = {
          _id: tag._id
        };
        if (tag.valid_from) {
          tagData.valid_from = tag.valid_from;
        }
        if (tag.valid_to) {
          tagData.valid_to = tag.valid_to;
        }
        if (tag.email_notification) {
          tagData.email_notification = tag.email_notification;
        }
        if (tag.email_recipients) {
          tagData.email_recipients = tag.email_recipients;
        }
        save_data._top_level._tags.push(tagData);
      }
    } else {
      save_data._top_level._tags = CUI.util.copyObject(tags, true);
    }
    return this.getBulkSaveData(data, save_data._top_level, opts, "mode");
  };

  TagsField.prototype.isEmpty = function(data, top_level_data, opts) {
    var ref, ref1;
    if (top_level_data != null ? top_level_data.versionTagsDiff : void 0) {
      return false;
    }
    if (this.insideNested()) {
      if (((ref = data[this.name()]) != null ? ref.length : void 0) > 0) {
        return false;
      } else {
        return true;
      }
    } else if (((ref1 = top_level_data[this.name()]) != null ? ref1.length : void 0) > 0) {
      return false;
    } else {
      return true;
    }
  };

  TagsField.prototype.isTopLevelField = function() {
    return true;
  };

  TagsField.prototype.checkValue = function(data, top_level_data, opts) {
    var ref;
    if (this.getOption(data, "bulk")) {
      if (this.getOption(data, "mode") !== "bulk_tag_remove_all") {
        if (!((ref = top_level_data[this.name()]) != null ? ref.length : void 0)) {
          return false;
        }
      }
    }
    return TagsField.__super__.checkValue.call(this, data, top_level_data, opts);
  };

  TagsField.prototype.isVisible = function(mode, opts) {
    var atLeastOneTagVisible, editEnabled, edit_mode, i, isVisible, j, len, len1, outputEnabled, output_mode, ref, ref1, ref2, ref3, ref4, ref5, tag, tg;
    if (opts == null) {
      opts = {};
    }
    if (CUI.util.isFunction(opts.isVisible)) {
      isVisible = opts.isVisible(this, mode, opts);
      if (CUI.util.isBoolean(isVisible)) {
        return isVisible;
      }
    }
    if (opts.hide_tags) {
      return false;
    }
    if (mode === "csv-import") {
      return true;
    }
    if (mode === "export") {
      return true;
    }
    output_mode = (ref = this.mask.schema.system_fields) != null ? ref.tags.output.mode : void 0;
    edit_mode = (ref1 = this.mask.schema.system_fields) != null ? ref1.tags.edit.mode : void 0;
    outputEnabled = output_mode !== "off";
    editEnabled = edit_mode !== "off";
    if (this.insideNested()) {
      return outputEnabled && (mode === "detail" || mode === "editor") && ((ref2 = this.mask.nestedTableField) != null ? (ref3 = ref2.FieldSchema.custom_settings) != null ? ref3.show_tags_reverse : void 0 : void 0);
    }
    atLeastOneTagVisible = false;
    ref4 = ez5.tagForm.tagGroups;
    for (i = 0, len = ref4.length; i < len; i++) {
      tg = ref4[i];
      ref5 = tg.children;
      for (j = 0, len1 = ref5.length; j < len1; j++) {
        tag = ref5[j];
        if (!tag.isVisible(mode)) {
          continue;
        }
        atLeastOneTagVisible = true;
        break;
      }
      if (atLeastOneTagVisible) {
        break;
      }
    }
    if (!atLeastOneTagVisible) {
      return false;
    }
    if (editEnabled && (mode === "editor-header" || mode === "editor-header-bulk" || mode === "editor-header-template")) {
      return true;
    }
    if (outputEnabled) {
      if (mode === "detail-header" && opts.history) {
        return true;
      }
      if (mode === "text" && (opts.sourceType === "link" || !CUI.util.isEmpty(opts._path))) {
        return true;
      }
      return mode === "expert" || mode === "result-card-info-detail" || mode === "table" || mode === "standard";
    }
    return false;
  };

  TagsField.prototype.isReadOnly = function(data, top_level_data) {
    var ref;
    if (this.insideNested()) {
      return true;
    } else if (((ref = this.mask.schema.system_fields) != null ? ref.tags.edit.mode : void 0) !== "edit") {
      return true;
    } else {
      return false;
    }
  };

  TagsField.prototype.getQueryFieldBadge = function(data) {
    var i, len, ref, tag, txt, value;
    if (data[(this.name()) + ":unset"]) {
      value = $$("field.search.badge.without");
    } else if (data[(this.name()) + ":has_value"]) {
      value = $$("field.search.badge.has_value");
    } else {
      txt = [];
      ref = ez5.tagForm.getTagsByData(data[this.name()]);
      for (i = 0, len = ref.length; i < len; i++) {
        tag = ref[i];
        txt.push(tag.getDisplayName());
      }
      value = txt.join(", ");
    }
    return {
      name: this.nameLocalized(),
      value: value
    };
  };

  TagsField.prototype.getSearchFilter = function(data) {
    var filter, ref, tag;
    filter = {
      type: "complex",
      search: [
        {
          type: "in",
          bool: "must",
          fields: ["_objecttype"],
          "in": [this.path()]
        }, {
          type: "in",
          bool: "must",
          fields: [this.name() + "._id"]
        }
      ]
    };
    if (data[(this.name()) + ":unset"] || data[(this.name()) + ":has_value"]) {
      filter.search[1]["in"] = [null];
    } else if (((ref = data[this.name()]) != null ? ref.length : void 0) > 0) {
      filter.search[1]["in"] = (function() {
        var i, len, ref1, results;
        ref1 = data[this.name()];
        results = [];
        for (i = 0, len = ref1.length; i < len; i++) {
          tag = ref1[i];
          results.push(tag._id);
        }
        return results;
      }).call(this);
    } else {
      filter = null;
    }
    if (data[(this.name()) + ":has_value"]) {
      filter.search[1].bool = "must_not";
    }
    return filter;
  };

  TagsField.prototype.fullName = function() {
    return this.name();
  };

  TagsField.prototype.__getFormPopover = function(data, opts) {
    var _data, dataSource, empty_loca_key, expirationData, fields, form, i, initialDataLength, j, l, len, len1, len2, len3, m, options, ref, ref1, ref2, ref3, ref4, tag, tag_id, tg, title, useTemplate;
    if (opts == null) {
      opts = {};
    }
    CUI.Element.readOpts(opts, "TagsField.__getFormPopover", {
      render_choice: {
        mandatory: true,
        check: Boolean
      },
      show_tag: {
        mandatory: true,
        check: Function
      },
      mode: {
        check: String
      },
      tags_mode: {
        check: String
      },
      has_template: {
        check: Boolean
      },
      set_default_only: {
        check: Boolean
      },
      dbinfo: {
        mandatory: false
      }
    });
    dataSource = data[this.name()].length === 0 ? (ref = data._template) != null ? ref[this.name()] : void 0 : data[this.name()];
    if (dataSource == null) {
      dataSource = data[this.name()];
    }
    _data = {
      ids: []
    };
    for (i = 0, len = dataSource.length; i < len; i++) {
      tag = dataSource[i];
      _data.ids.push(tag._id);
    }
    fields = [];
    expirationData = {};
    ref1 = ez5.tagForm.tagGroups;
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      tg = ref1[j];
      options = [];
      ref2 = tg.children;
      for (l = 0, len2 = ref2.length; l < len2; l++) {
        tag = ref2[l];
        if (!tag.isVisible(opts.mode) && !opts.set_default_only) {
          continue;
        }
        if (!opts.show_tag(tag, _data.ids)) {
          if (!_data.ids.includes(tag.getId()) && opts.set_default_only && ((ref3 = opts.dbinfo.availableTagById(tag.getId())) != null ? ref3.is_default : void 0)) {
            _data.ids.push(tag.getId());
          }
          continue;
        }
        if (options.length === 0) {
          fields.push({
            type: CUI.Options,
            ui: "tags.field.form.options",
            name: "ids",
            horizontal: false,
            radio: tg.isChoice() && opts.render_choice,
            min_checked: 0,
            title: tg.getDisplayName(),
            options: options
          });
        }
        expirationData[tag.getId()] = {};
        options.push({
          content: tag.getLabelWithExpirationForm({
            data: expirationData[tag.getId()]
          }),
          value: tag.getId(),
          ui: "tags.field.form.options:" + (tag.getId())
        });
      }
    }
    if (opts.set_default_only) {
      data[this.name()].splice(0);
      ref4 = _data.ids;
      for (m = 0, len3 = ref4.length; m < len3; m++) {
        tag_id = ref4[m];
        data[this.name()].push({
          _id: tag_id
        });
      }
      return;
    }
    if (fields.length === 0) {
      return new CUI.EmptyLabel({
        text: $$("tag.form-popover.no_tags_available")
      });
    }
    if (opts.tags_mode === "new" && opts.has_template) {
      empty_loca_key = "tags.field.set_by_template";
    } else {
      empty_loca_key = "tag.form-popover.empty";
    }
    title = $$("tags.field.popover.title");
    useTemplate = true;
    initialDataLength = _data.ids.length;
    form = new CUI.FormPopover({
      "class": "ez5-modify-tags-form",
      popover: {
        "class": "ez5-modify-tags-modal",
        pane: {
          ui: "tags.field.popover.pane",
          padded: true,
          header_left: title ? new CUI.Label({
            text: title
          }) : void 0
        }
      },
      button: {
        ui: "tags.field.form.button",
        loca_key: "tags.field.button.open_popover"
      },
      data: _data,
      renderDisplayContent: (function(_this) {
        return function() {
          var k, len4, len5, n, p, ref5, ref6, tagData, v;
          if (useTemplate && _data.ids.length !== initialDataLength) {
            useTemplate = false;
          }
          if (!useTemplate) {
            data[_this.name()].length = 0;
            ref5 = _data.ids;
            for (n = 0, len4 = ref5.length; n < len4; n++) {
              tag_id = ref5[n];
              tagData = {
                _id: tag_id
              };
              if (ez5.session.isDebug() && expirationData[tag_id]) {
                ref6 = ["valid_from", "valid_to", "email_notification", "email_recipients"];
                for (v = p = 0, len5 = ref6.length; p < len5; v = ++p) {
                  k = ref6[v];
                  if (expirationData[tag_id][k]) {
                    tagData[k] = expirationData[tag_id][k];
                  }
                }
              }
              data[_this.name()].push(tagData);
            }
          }
          if (!useTemplate && ez5.tagForm.getTagsByData(data[_this.name()]).filter(function(tag) {
            return tag.isVisible();
          }).length === 0) {
            useTemplate = true;
            initialDataLength = _data.ids.length;
            data[_this.name()].length = 0;
          }
          return _this.renderDetailOutput(null, data, {
            empty_loca_key: empty_loca_key
          });
        };
      })(this),
      fields: fields
    });
    form.start();
    data[this.name() + ":popover"] = form;
    return form;
  };

  TagsField.prototype.updateTags = function(data, tags) {
    var __tag, _tag, current_tags, group, i, j, len, len1, popover, ref, tag;
    popover = data[this.name() + ":popover"];
    current_tags = popover.getData().ids;
    for (i = 0, len = tags.length; i < len; i++) {
      _tag = tags[i];
      tag = ez5.tagForm.findTagByAnyId(_tag._id);
      group = tag.tagFormGroup;
      if (group.getType() === "choice") {
        ref = group.children;
        for (j = 0, len1 = ref.length; j < len1; j++) {
          __tag = ref[j];
          CUI.util.removeFromArray(__tag.getId(), current_tags);
        }
      }
      CUI.util.pushOntoArray(tag.getId(), current_tags);
    }
    popover.displayValue();
    popover.triggerDataChanged();
    return this;
  };

  TagsField.prototype.__showTag = function(tag, arr, _opts) {
    var _tag, av_tag, i, len, opts, ref, ref1, show, tag_id;
    if (_opts == null) {
      _opts = {};
    }
    opts = CUI.Element.readOpts(_opts, 'TagsField.__showTag', {
      dbInfo: {
        mandatory: !_opts.demo,
        check: DbInfo
      },
      set_default_data: {
        mandatory: !_opts.demo,
        check: Boolean,
        "default": false
      },
      demo: {
        mandatory: true,
        check: Boolean,
        "default": false
      }
    });
    show = (ref = tag.getDisplayType()) === "facet" || ref === "search" || ref === "detail" || ref === "editor";
    if (!show) {
      return false;
    }
    if (opts.demo) {
      return true;
    }
    tag_id = tag.getId();
    av_tag = opts.dbInfo.availableTagById(tag.getId());
    if (!av_tag) {
      if (arr) {
        CUI.util.removeFromArray(tag.getId(), arr);
      }
      return false;
    }
    if (!arr) {
      return true;
    }
    if (av_tag.is_default && opts.set_default_data) {
      if (tag.tagFormGroup.isChoice()) {
        ref1 = tag.tagFormGroup.children;
        for (i = 0, len = ref1.length; i < len; i++) {
          _tag = ref1[i];
          CUI.util.removeFromArray(_tag.getId(), arr);
        }
      }
      if (indexOf.call(arr, tag_id) < 0) {
        arr.push(tag_id);
      }
    }
    return true;
  };

  TagsField.prototype.initData = function(top_level_data, _opts) {
    var opts, set_default_data;
    if (_opts == null) {
      _opts = {};
    }
    opts = CUI.Element.readOpts(_opts, 'TagsField.initData', {
      dbInfo: {
        mandatory: !_opts.demo && !top_level_data._example_object,
        check: DbInfo
      },
      mode: {
        mandatory: !_opts.demo && !top_level_data._example_object,
        check: String
      },
      demo: {
        mandatory: true,
        check: Boolean,
        "default": false
      }
    });
    if (top_level_data[this.name()]) {
      return;
    }
    top_level_data[this.name()] = [];
    if (opts.mode !== "new") {
      return;
    }
    set_default_data = null;
    if (top_level_data._template) {
      if (!top_level_data._template[this.name()]) {
        top_level_data._template[this.name()] = [];
        set_default_data = top_level_data._template;
      }
    } else {
      set_default_data = top_level_data;
    }
    if (!set_default_data) {
      return;
    }
    return this.__getFormPopover(set_default_data, {
      set_default_only: true,
      dbinfo: opts.dbInfo,
      render_choice: true,
      show_tag: (function(_this) {
        return function(tag, arr) {
          return _this.__showTag(tag, arr, {
            dbInfo: opts.dbInfo,
            demo: opts.demo || top_level_data._example_object,
            set_default_data: true
          });
        };
      })(this),
      tags_mode: opts.mode
    });
  };

  TagsField.prototype.renderEditorInput = function(data, top_level_data, renderOpts) {
    var form, old_tags, opts, ref, ref1;
    opts = {
      dbInfo: (ref = renderOpts.editor) != null ? ref.editor_data.dbInfo : void 0,
      mode: (ref1 = renderOpts.editor) != null ? ref1.editor_data.mode : void 0,
      demo: top_level_data.__version === "TEMP"
    };
    this.initData(top_level_data, opts);
    old_tags = CUI.util.copyObject(top_level_data[this.name()], true);
    form = this.__getFormPopover(top_level_data, {
      render_choice: true,
      show_tag: (function(_this) {
        return function(tag, arr) {
          return _this.__showTag(tag, arr, {
            dbInfo: opts.dbInfo,
            demo: opts.demo || top_level_data._example_object
          });
        };
      })(this),
      mode: renderOpts.mode,
      tags_mode: opts.mode,
      has_template: !!top_level_data._template
    });
    CUI.Events.listen({
      type: "data-changed",
      node: form,
      call: (function(_this) {
        return function() {
          var ref2;
          return CUI.Events.trigger({
            type: "tags-field-changed",
            node: form,
            info: {
              old_tags: old_tags,
              new_tags: top_level_data[_this.name()],
              editor_has_changes: (ref2 = renderOpts.editor) != null ? ref2.hasChanges() : void 0
            }
          });
        };
      })(this)
    });
    switch (renderOpts.mode) {
      case "editor-bulk":
      case "editor-header-bulk":
        form.addClass("ez5-tags-field-group-mode");
    }
    return form;
  };

  TagsField.prototype.getBulkOptions = function(data, opts) {
    var o;
    switch (opts.mode) {
      case "editor-bulk":
      case "editor-header-bulk":
        return (function() {
          var i, len, ref, results;
          ref = ["add", "replace", "remove", "remove_all"];
          results = [];
          for (i = 0, len = ref.length; i < len; i++) {
            o = ref[i];
            results.push("bulk_tag_" + o);
          }
          return results;
        })();
    }
  };

  TagsField.prototype.renderSearchInput = function(data, opts) {
    var form;
    if (opts == null) {
      opts = {};
    }
    if (!data[this.name()]) {
      data[this.name()] = [];
    }
    form = this.__getFormPopover(data, {
      render_choice: false,
      mode: opts.mode,
      show_tag: (function(_this) {
        return function(tag) {
          var ref;
          return (ref = tag.getDisplayType()) === "facet" || ref === "search" || ref === "detail" || ref === "editor";
        };
      })(this)
    });
    CUI.Events.listen({
      type: "data-changed",
      node: form,
      call: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            type: "search-input-change",
            node: form
          });
        };
      })(this)
    });
    return form;
  };

  TagsField.prototype.getVirtualTags = function(data, top_level_data, opts) {
    var pool, pool_virtual_tag, ref;
    if (ez5.version("6") && (opts != null ? opts.fieldRenderType : void 0) === "table" && data._pool) {
      pool = ez5.pools.findPoolById((ref = data._pool) != null ? ref.pool._id : void 0);
      if (pool) {
        pool_virtual_tag = pool.getVirtualTags(top_level_data);
        if (pool_virtual_tag) {
          return pool_virtual_tag;
        }
      }
    }
    return null;
  };

  TagsField.prototype.renderDetailOutput = function(data, top_level_data, opts) {
    var container, div, empty_loca_key, getExpirationDate, i, len, pool_virtual_tag, tag, tags, tagsData, topLevelTagsData;
    if (opts == null) {
      opts = {};
    }
    topLevelTagsData = top_level_data != null ? top_level_data[this.name()] : void 0;
    tagsData = this.insideNested() ? data[this.name()] : (top_level_data != null ? top_level_data._template : void 0) && (topLevelTagsData != null ? topLevelTagsData.length : void 0) === 0 ? top_level_data._template[this.name()] : topLevelTagsData;
    tags = ez5.tagForm.getTagsByData(tagsData);
    pool_virtual_tag = this.getVirtualTags(data, top_level_data, opts);
    if (pool_virtual_tag) {
      tags = pool_virtual_tag.concat(tags);
    }
    getExpirationDate = (function(_this) {
      return function(tag) {
        var i, len, t;
        if (!ez5.session.isDebug()) {
          return null;
        }
        for (i = 0, len = tagsData.length; i < len; i++) {
          t = tagsData[i];
          if (t._id === tag.getId()) {
            if (t.valid_from || t.valid_to) {
              return t;
            } else {
              return null;
            }
          }
        }
        return null;
      };
    })(this);
    container = CUI.dom.div("tags-field-container");
    if (tags.length > 0) {
      div = CUI.dom.div("tags-field");
      if ((top_level_data != null ? top_level_data._template : void 0) && (topLevelTagsData != null ? topLevelTagsData.length : void 0) === 0) {
        div.style.opacity = 0.5;
      }
      for (i = 0, len = tags.length; i < len; i++) {
        tag = tags[i];
        if (tag.getDisplayType() === "hidden") {
          continue;
        }
        CUI.dom.append(div, tag.getLabel(true, true, getExpirationDate(tag)).DOM);
      }
      CUI.dom.append(container, div);
    } else if (!(top_level_data != null ? top_level_data.versionTagsDiff : void 0)) {
      if (opts.hide_empty_label) {
        return;
      }
      empty_loca_key = opts.empty_loca_key || "tag.form-popover.empty";
      return new CUI.EmptyLabel({
        text: $$(empty_loca_key)
      }).DOM;
    }
    if (top_level_data != null ? top_level_data.versionTagsDiff : void 0) {
      this.__renderTagsDiffRows(top_level_data.versionTagsDiff, container);
    }
    return container;
  };

  TagsField.prototype.__renderTagsDiffRows = function(diff, container) {
    var addedRow, addedTags, i, j, len, len1, removedRow, removedTags, results, tag;
    addedTags = ez5.tagForm.getTagsByData(diff.addedTagIds.map(function(id) {
      return {
        _id: id
      };
    }));
    removedTags = ez5.tagForm.getTagsByData(diff.removedTagIds.map(function(id) {
      return {
        _id: id
      };
    }));
    if (addedTags.length > 0) {
      for (i = 0, len = addedTags.length; i < len; i++) {
        tag = addedTags[i];
        addedRow = CUI.dom.div("tags-field-diff-row ez5-block-field-history-added");
        CUI.dom.append(addedRow, tag.getLabel(true, true).DOM);
        CUI.dom.append(container, addedRow);
      }
    }
    if (removedTags.length > 0) {
      results = [];
      for (j = 0, len1 = removedTags.length; j < len1; j++) {
        tag = removedTags[j];
        removedRow = CUI.dom.div("tags-field-diff-row ez5-block-field-history-deleted");
        CUI.dom.append(removedRow, tag.getLabel(true, true).DOM);
        results.push(CUI.dom.append(container, removedRow));
      }
      return results;
    }
  };

  TagsField.prototype.isSourceForMapping = function(required_type) {
    return false;
  };

  TagsField.prototype.isValidMappingField = function(level) {
    return level === 0;
  };

  TagsField.prototype.getCSVDestinationFields = function(csvImporter) {
    var opts;
    opts = {
      csvImporter: csvImporter,
      field: this
    };
    return [new TagsFieldCSVImporterDestinationField(opts)];
  };

  return TagsField;

})(Field);

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

  function TagsFieldForEditor() {}

  return TagsFieldForEditor;

})(TagsField);

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

  function TagsFieldForBaseConfig(opts) {
    if (opts == null) {
      opts = {};
    }
    CUI.Element.readOpts.call(this, opts, "new TagsField", {
      name: {
        mandatory: true,
        check: String
      }
    });
  }

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

  TagsFieldForBaseConfig.prototype.render = function(data) {
    return this.renderSearchInput(data);
  };

  return TagsFieldForBaseConfig;

})(TagsField);

CUI.ready(function() {
  return CUI.Events.registerEvent({
    type: "tags-field-changed",
    bubble: true
  });
});
// Generated by CoffeeScript 1.12.7
var SystemTagsField,
  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;

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

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

  SystemTagsField.prototype.name = function() {
    return "_system_tags";
  };

  SystemTagsField.prototype.nameLocalized = function() {
    return $$("system_tags.field.name");
  };

  SystemTagsField.prototype.isVisible = function(mode, opts) {
    if (opts == null) {
      opts = {};
    }
    if (!ez5.session.hasSystemRight("root", "frontend_features[show_system_tags]")) {
      return false;
    }
    return mode === "result-card-info-detail" || mode === "facet" || mode === "expert";
  };

  SystemTagsField.prototype.isEmpty = function(data) {
    var systemTagsData;
    systemTagsData = data[this.name()];
    if (!systemTagsData) {
      return true;
    }
    if (!CUI.util.isArray(systemTagsData)) {
      return true;
    }
    return false;
  };

  SystemTagsField.prototype.getTags = function(data) {
    var i, len, ref, systemTagData, systemTags;
    if (data == null) {
      data = {};
    }
    if (this.isEmpty(data)) {
      return [];
    }
    systemTags = [];
    ref = data[this.name()];
    for (i = 0, len = ref.length; i < len; i++) {
      systemTagData = ref[i];
      systemTags.push(this.__getTagLabel(systemTagData));
    }
    return systemTags;
  };

  SystemTagsField.prototype.renderSearchInput = function(data, opts) {
    var form, ref, searchBasics, systemTagNames;
    if (opts == null) {
      opts = {};
    }
    if (!data[this.name()]) {
      data[this.name()] = [];
    }
    searchBasics = (ref = opts.search) != null ? ref.getSearchBasics() : void 0;
    systemTagNames = searchBasics != null ? searchBasics.getSystemTagNames() : void 0;
    form = this.__getFormPopover(data, systemTagNames);
    CUI.Events.listen({
      type: "data-changed",
      node: form,
      call: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            type: "search-input-change",
            node: form
          });
        };
      })(this)
    });
    return form;
  };

  SystemTagsField.prototype.getQueryFieldBadge = function(data) {
    var badge, i, len, ref, systemTag, txt, value;
    if (data[(this.name()) + ":unset"]) {
      value = $$("field.search.badge.without");
    } else if (data[(this.name()) + ":has_value"]) {
      value = $$("field.search.badge.has_value");
    } else {
      txt = [];
      ref = data[this.name()] || [];
      for (i = 0, len = ref.length; i < len; i++) {
        systemTag = ref[i];
        txt.push($$("system.tags.tag." + systemTag.system_tag + "|label"));
      }
      value = txt.join(", ");
    }
    badge = {
      name: this.nameLocalized(),
      value: value
    };
    return badge;
  };

  SystemTagsField.prototype.getSearchFilter = function(data) {
    var filter, ref, systemTag;
    filter = {
      type: "complex",
      search: [
        {
          type: "in",
          bool: "must",
          fields: ["_objecttype"],
          "in": [this.path()]
        }, {
          type: "in",
          bool: "must",
          fields: [this.name() + ".system_tag"]
        }
      ]
    };
    if (data[(this.name()) + ":unset"] || data[(this.name()) + ":has_value"]) {
      filter.search[1]["in"] = [null];
    } else if (((ref = data[this.name()]) != null ? ref.length : void 0) > 0) {
      filter.search[1]["in"] = (function() {
        var i, len, ref1, results;
        ref1 = data[this.name()];
        results = [];
        for (i = 0, len = ref1.length; i < len; i++) {
          systemTag = ref1[i];
          results.push(systemTag.system_tag);
        }
        return results;
      }).call(this);
    } else {
      filter = null;
    }
    return filter;
  };

  SystemTagsField.prototype.__getFormPopover = function(data, systemTagNames) {
    var _data, form, i, index, j, len, len1, options, ref, systemTag, systemTagName;
    if (!systemTagNames || systemTagNames.length === 0) {
      return new CUI.EmptyLabel({
        text: $$("system.tag.form-popover.no_tags_available")
      });
    }
    _data = {
      systemTagNames: []
    };
    ref = data[this.name()];
    for (i = 0, len = ref.length; i < len; i++) {
      systemTag = ref[i];
      _data.systemTagNames.push(systemTag.system_tag);
    }
    options = [];
    for (index = j = 0, len1 = systemTagNames.length; j < len1; index = ++j) {
      systemTagName = systemTagNames[index];
      options.push({
        content: this.__getTagLabel({
          system_tag: systemTagName
        }),
        value: systemTagName,
        ui: "system.tags.field.form.options:" + index
      });
    }
    form = new CUI.FormPopover({
      "class": "ez5-modify-tags-form",
      popover: {
        "class": "ez5-modify-tags-modal",
        pane: {
          ui: "system.tags.field.popover.pane",
          padded: true,
          header_left: new CUI.Label({
            text: $$("system.tags.field.popover.title")
          })
        }
      },
      button: {
        ui: "system.tags.field.form.button",
        loca_key: "system.tags.field.button.open_popover"
      },
      data: _data,
      renderDisplayContent: (function(_this) {
        return function() {
          var div, k, len2, ref1;
          data[_this.name()].splice(0);
          if (_data.systemTagNames.length === 0) {
            return new CUI.EmptyLabel({
              text: $$("system.tag.form-popover.empty")
            });
          }
          ref1 = _data.systemTagNames;
          for (k = 0, len2 = ref1.length; k < len2; k++) {
            systemTagName = ref1[k];
            data[_this.name()].push({
              system_tag: systemTagName
            });
          }
          div = CUI.dom.div("tags-field");
          CUI.dom.append(div, _this.getTags(data));
          return div;
        };
      })(this),
      fields: [
        {
          type: CUI.Options,
          ui: "system.tags.field.form.options",
          name: "systemTagNames",
          horizontal: false,
          min_checked: 0,
          title: $$("system.tags.field.popover.options.title"),
          options: options
        }
      ]
    });
    form.start();
    data[this.name() + ":popover"] = form;
    return form;
  };

  SystemTagsField.prototype.__getTagLabel = function(systemTagData) {
    var systemTag;
    systemTag = new SystemTagSimple({
      data: systemTagData
    });
    return systemTag.getLabel(true, true);
  };

  SystemTagsField.prototype.isSystemField = function() {
    return true;
  };

  return SystemTagsField;

})(Field);
// Generated by CoffeeScript 1.12.7
var TextMultiColumn,
  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;

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

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

  TextMultiColumn.prototype.getElementOpts = function(mode) {
    switch (mode) {
      case "expert":
        return {
          name: this.name(),
          type: CUI.Input
        };
      default:
        return {
          name: this.name(),
          textarea: true,
          content_size: false,
          type: CUI.Input
        };
    }
  };

  TextMultiColumn.prototype.getManageOverflow = function() {
    return true;
  };

  TextMultiColumn.prototype.isVisible = function(mode, opts) {
    if (!TextMultiColumn.__super__.isVisible.call(this, mode, opts) || mode === 'fulltext') {
      return false;
    } else {
      return true;
    }
  };

  TextMultiColumn.prototype.mergeData = function(top_level_data, top_level_data_new, replace) {
    var data, data_new, ref, ref1;
    if (replace == null) {
      replace = false;
    }
    data = top_level_data[top_level_data._objecttype];
    data_new = top_level_data_new[top_level_data_new._objecttype];
    if (replace) {
      return TextMultiColumn.__super__.mergeData.call(this, top_level_data, top_level_data_new, replace);
    }
    if (((ref = data[this.name()]) != null ? ref.trim().length : void 0) > 0 && ((ref1 = data_new[this.name()]) != null ? ref1.trim().length : void 0) > 0) {
      data[this.name()] += " " + data_new[this.name()];
    } else {
      data[this.name()] = data_new[this.name()];
    }
    return this;
  };

  return TextMultiColumn;

})(TextColumn);
// Generated by CoffeeScript 1.12.7
var TreeColumn,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function TreeColumn(mask) {
    this.mask = mask;
    Field.prototype.constructor.call(this, this.mask);
    this.__parentInfo = this.mask.schema.system_fields.parent;
  }

  TreeColumn.prototype.name = function() {
    return "_id_parent";
  };

  TreeColumn.prototype.addToCollection = function(data, top_level_data, collection) {
    return this.__addToCollection(this.__getObjectFromPath(top_level_data), collection);
  };

  TreeColumn.prototype.getOutputStandard = function() {
    return {
      design: "normal",
      format: "comma"
    };
  };

  TreeColumn.prototype.isInPopoverTopLevel = function() {
    return true;
  };

  TreeColumn.prototype.nameLocalized = function() {
    return $$("main.editor.parent");
  };

  TreeColumn.prototype.renderStandard = function() {};

  TreeColumn.prototype.renderSearchInput = function(data, opts) {
    var base, collection, collectionPromise, form, i, len, node, obj, path, pathKey, ref, ref1, searchInput, searchOptionsField;
    if ((opts.search && (typeof (base = opts.search).getExpertOptionsCurrentMode === "function" ? base.getExpertOptionsCurrentMode() : void 0) !== "_COMMONS") || opts.objecttypeSearchExpert) {
      collection = this.getCollectionMemory(data);
      pathKey = this.name() + "_path";
      if ((data != null ? data[pathKey] : void 0) && ((ref = data[pathKey]) != null ? ref.length : void 0) > 0) {
        collectionPromise = collection.insertObjects((function() {
          var i, len, ref1, results;
          ref1 = data[pathKey];
          results = [];
          for (i = 0, len = ref1.length; i < len; i++) {
            path = ref1[i];
            results.push(new CollectionObject({
              _global_object_id: path.globalObjectId
            }));
          }
          return results;
        })());
      }
      if (opts.objecttypeSearchExpert) {
        if (data[pathKey] && data[pathKey].length > 0) {
          ref1 = data[pathKey];
          for (i = 0, len = ref1.length; i < len; i++) {
            obj = ref1[i];
            collection.insertObjects([
              new CollectionObject({
                _global_object_id: obj.globalObjectId
              })
            ]);
          }
        }
      }
      node = this.__renderInput({
        collection: collection,
        collectionPromise: collectionPromise || CUI.resolvedPromise(),
        mode: "editor",
        allowMultipleRows: true,
        data: {
          _new: true
        },
        onUpdate: (function(_this) {
          return function() {
            var objects;
            objects = collection.getObjects().map(function(collectionObject) {
              var object;
              object = {
                globalObjectId: collectionObject.getGlobalObjectId(),
                standardText: StandardField.getStandardText(collectionObject.getObject())
              };
              return object;
            });
            if (objects.length === 0) {
              delete data[pathKey];
            } else {
              data[pathKey] = objects;
            }
            CUI.Events.trigger({
              node: searchInput,
              type: "search-input-change"
            });
          };
        })(this)
      });
      searchInput = new CUI.DataFieldProxy({
        element: node
      });
      if (opts.skip_extra_options) {
        searchInput.start();
        return searchInput;
      }
    }
    searchOptionsField = TreeColumn.getSearchOptionsField(this.name(), data);
    if (!searchInput) {
      searchOptionsField.start();
      return searchOptionsField;
    }
    form = new CUI.Form({
      fields: [searchInput, searchOptionsField]
    });
    form.start();
    return form;
  };

  TreeColumn.getSearchOptionsField = function(name, data) {
    var i, inp, k, len, opts, ref;
    opts = [];
    ref = ["without_children", "with_children", "without_parent", "with_parent"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      opts.push({
        text: $$("tree.column.search.input.option." + k),
        value: k
      });
    }
    inp = new CUI.FormPopover({
      data: data,
      undo_and_changed_support: false,
      button: {
        loca_key: "tree.column.search.button"
      },
      trigger_data_changed_while_open: true,
      popover: {
        pane: {
          padded: true
        },
        onHide: (function(_this) {
          return function() {
            return CUI.Events.trigger({
              node: inp,
              type: "search-input-change"
            });
          };
        })(this)
      },
      fields: (function(_this) {
        return function() {
          return [
            {
              type: CUI.Options,
              name: name,
              title: $$("tree.column.search.input.options.title"),
              horizontal: false,
              options: opts
            }
          ];
        };
      })(this),
      renderDisplayContent: (function(_this) {
        return function() {
          var div, j, key, len1, ref1;
          div = CUI.dom.element("DIV", {
            "class": "ez5-tag-holder"
          });
          ref1 = data[name] || [];
          for (j = 0, len1 = ref1.length; j < len1; j++) {
            key = ref1[j];
            div.appendChild(new CUI.Label({
              "class": "ez5-tag",
              text: $$("tree.column.search.input.tag." + key)
            }).DOM);
          }
          if (div.children.length > 0) {
            return div;
          } else {
            return null;
          }
        };
      })(this)
    });
    return inp;
  };

  TreeColumn.prototype.nameForCommonField = function() {
    return this.name();
  };

  TreeColumn.prototype.getSearchUnsetElement = function(data) {};

  TreeColumn.prototype.getSearchFilter = function(data, key) {
    var _entrySearch, _search, entryFilter, entrySearch, i, j, k, l, len, len1, len2, pathSearch, pathSearchData, ref, s, search;
    if (key == null) {
      key = this.name();
    }
    search = [];
    entrySearch = [];
    ref = data[key] || [];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      switch (k) {
        case "with_parent":
          entrySearch.push({
            type: "in",
            fields: [this.fullName()],
            "in": [null],
            bool: "must_not"
          });
          break;
        case "without_parent":
          entrySearch.push({
            type: "in",
            fields: [this.fullName()],
            "in": [null],
            bool: "must"
          });
          break;
        case "with_children":
          entrySearch.push({
            type: "in",
            fields: ["_has_children"],
            "in": [true],
            bool: "must"
          });
          break;
        case "without_children":
          entrySearch.push({
            type: "in",
            fields: ["_has_children"],
            "in": [true],
            bool: "must_not"
          });
      }
    }
    if (entrySearch.length > 0) {
      entryFilter = [];
      for (j = 0, len1 = entrySearch.length; j < len1; j++) {
        _entrySearch = entrySearch[j];
        entryFilter.push({
          type: "complex",
          bool: "should",
          search: [_entrySearch]
        });
      }
      search.push(entryFilter);
    }
    pathSearch = [];
    pathSearchData = data[this.name() + "_path"];
    if (pathSearchData) {
      pathSearchData.forEach((function(_this) {
        return function(object) {
          pathSearch.push({
            type: "complex",
            bool: "should",
            search: [
              {
                type: "in",
                "in": [object.globalObjectId],
                fields: ["_path._global_object_id"],
                bool: "must"
              }, {
                type: "in",
                "in": [object.globalObjectId],
                fields: ["_global_object_id"],
                bool: "must_not"
              }
            ]
          });
        };
      })(this));
    }
    if (pathSearch.length > 0) {
      search.push(pathSearch);
    }
    if (search.length > 0) {
      _search = [];
      for (l = 0, len2 = search.length; l < len2; l++) {
        s = search[l];
        _search.push({
          type: "complex",
          search: s
        });
      }
      return {
        type: "complex",
        search: _search
      };
    } else {
      return null;
    }
  };

  TreeColumn.prototype.getQueryFieldBadge = function(data) {
    var key, pathSearchData, txt;
    txt = (function() {
      var i, len, ref, results;
      ref = data[this.name()] || [];
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        key = ref[i];
        results.push($$("tree.column.search.input.tag." + key));
      }
      return results;
    }).call(this);
    pathSearchData = data[this.name() + "_path"];
    if (pathSearchData) {
      pathSearchData.forEach((function(_this) {
        return function(object) {
          return txt.push(object.standardText || object.globalObjectId.split("@")[0]);
        };
      })(this));
    }
    return {
      name: this.nameLocalized(),
      value: txt.join(", ")
    };
  };

  TreeColumn.prototype.getFirstStandardEASColumn = function() {};

  TreeColumn.prototype.__getLinkMaskId = function() {
    if (this.mask.name() === "_all_fields") {
      return "ALL_FIELDS";
    } else if (this.__parentInfo.mask_id === "SAME") {
      return this.mask.id();
    } else {
      return this.__parentInfo.mask_id;
    }
  };

  TreeColumn.prototype.__getLinkMaskTableId = function() {
    return this.mask.table.id();
  };

  TreeColumn.prototype.__getLinkMaskInline = function() {
    if (!this.__parentInfo.inline) {
      console.warn("TreeColumn::__getLinkMaskInline - No mask inline available, returning 'standard' as default.");
      return "standard";
    }
    return this.__parentInfo.inline;
  };

  TreeColumn.prototype.__getMaskCustomSetting = function(name) {};

  TreeColumn.prototype.isReadOnly = function(data, top_level_data) {
    return TreeColumn.isReadOnly(this.__parentInfo);
  };

  TreeColumn.isReadOnly = function(parentInfo) {
    var ref;
    return parentInfo.edit.mode !== "edit" || ((ref = parentInfo.custom_settings) != null ? ref.editor_frontend_mode : void 0) === "readonly";
  };

  TreeColumn.prototype.getReplacementRecord = function(data, key_prefix, use_array, record) {
    if (use_array == null) {
      use_array = false;
    }
    return Field.prototype.getReplacementRecord.call(this, data, key_prefix, use_array, record);
  };

  TreeColumn.prototype.checkValue = function(data, top_level_data, opts) {
    return true;
  };

  TreeColumn.prototype.isVisible = function(mode, opts) {
    var isVisible, ref;
    if (opts == null) {
      opts = {};
    }
    if (CUI.util.isFunction(opts.isVisible)) {
      isVisible = opts.isVisible(this, mode, opts);
      if (CUI.util.isBoolean(isVisible)) {
        return isVisible;
      }
    }
    if (this.isFilteredByRights(opts)) {
      return false;
    }
    switch (mode) {
      case "editor-header":
      case "editor-header-template":
      case "editor-header-bulk":
        if (this.__parentInfo.edit.mode !== "off" && ((ref = this.__parentInfo.custom_settings) != null ? ref.editor_frontend_mode : void 0) !== "hide") {
          return true;
        }
        break;
      case "sort":
      case "detail-header":
        if (this.__parentInfo.output.mode === "show") {
          return true;
        }
        break;
      case "expert":
      case "export":
      case "csv-import":
        return true;
      case "text":
        if (opts.hide_hierarchy_path) {
          return false;
        }
        return true;
    }
    return false;
  };

  TreeColumn.prototype.getPlaceholderTextForEditor = function(data, top_level_data) {
    var ref;
    if ((ref = data._template) != null ? ref[this.name()] : void 0) {
      return new ResultObject().setData(this.__getObjectFromPath(top_level_data._template)).renderText();
    } else {
      return null;
    }
  };

  TreeColumn.prototype.__getObjectFromPath = function(top_level_data) {
    var pdata;
    pdata = CUI.util.copyObject(top_level_data._path[top_level_data._path.length - 2], true);
    pdata._path = CUI.util.copyObject(top_level_data._path.slice(0, top_level_data._path.length - 1), true);
    return pdata;
  };

  TreeColumn.prototype.renderDetailOutput = function(data, top_level_data, opts) {
    if (opts == null) {
      opts = {};
    }
    if (opts.polyhierarchical) {
      return TreeColumn.__super__.renderDetailOutput.call(this, {
        _parent: data
      }, top_level_data, opts);
    }
    if (!(top_level_data != null ? top_level_data._path : void 0) || (top_level_data != null ? top_level_data._path.length : void 0) === 1) {
      return new CUI.EmptyLabel({
        text: $$("tree.column.no_parent_object")
      }).DOM;
    } else {
      return TreeColumn.__super__.renderDetailOutput.call(this, {
        _id_parent: this.__getObjectFromPath(top_level_data)
      }, null, opts);
    }
  };

  TreeColumn.prototype.setData = function(data, top_level_data, linked_object_data) {
    var i, key, keys, len, path_obj, path_obj2, ref, value;
    keys = ["_format", "_global_object_id", "_system_object_id", "_mask", "_objecttype", "_standard"];
    path_obj = {};
    for (i = 0, len = keys.length; i < len; i++) {
      key = keys[i];
      path_obj[key] = CUI.util.copyObject(top_level_data[key], true);
    }
    path_obj2 = path_obj[top_level_data._objecttype] = {};
    ref = top_level_data[top_level_data._objecttype];
    for (key in ref) {
      value = ref[key];
      if (key === "_top_level") {
        continue;
      }
      path_obj2[key] = CUI.util.copyObject(value, true);
    }
    if (!linked_object_data) {
      top_level_data._path = [path_obj];
      return data[this.name()] = null;
    } else {
      data[this.name()] = linked_object_data[linked_object_data._objecttype]._id;
      CUI.util.assert(linked_object_data._path, "TreeColumn.setData", "_path not set in data", {
        data: data,
        top_level_data: top_level_data,
        linked_object_data: linked_object_data,
        TreeColumn: this
      });
      top_level_data._path = linked_object_data._path.slice(0);
      return top_level_data._path.push(path_obj);
    }
  };

  TreeColumn.prototype.getCollectionMemory = function(data, top_level_data) {
    return new CollectionMemory({
      hasEASFields: this.mask.getEASFields("detail").length > 0,
      isObjectInsertable: (function(_this) {
        return function(collectionObject) {
          var ids, p_el, ref;
          if (!collectionObject.getObject()._path) {
            return true;
          }
          ids = (function() {
            var i, len, ref, results;
            ref = collectionObject.getObject()._path;
            results = [];
            for (i = 0, len = ref.length; i < len; i++) {
              p_el = ref[i];
              results.push(p_el[p_el._objecttype]._id);
            }
            return results;
          })();
          if (ref = data._id, indexOf.call(ids, ref) >= 0) {
            return false;
          } else {
            return true;
          }
        };
      })(this)
    });
  };

  TreeColumn.prototype.getSaveData = function(data, save_data, opts) {
    var ref;
    if (save_data == null) {
      save_data = {};
    }
    if (opts == null) {
      opts = {};
    }
    if (opts.copy_for_template) {
      return;
    }
    if (ez5.version("6")) {
      if (!CUI.util.isEmpty(data["_parent_child_idx"])) {
        save_data["_parent_child_idx"] = data["_parent_child_idx"];
      } else {
        save_data["_parent_child_idx"] = null;
      }
    }
    if (!CUI.util.isNull(data[this.name()]) || opts.bulk) {
      save_data[this.name()] = data[this.name()];
    } else if ((ref = data._template) != null ? ref[this.name()] : void 0) {
      save_data[this.name()] = data._template[this.name()];
    }
    if (opts.copy) {
      save_data._top_level._path = CUI.util.copyObject(data._top_level._path, true);
      save_data._top_level._path[save_data._top_level._path.length - 1][save_data._top_level._objecttype]._id = null;
    }
    if (CUI.util.isEmpty(save_data[this.name()])) {
      save_data[this.name()] = null;
    }
    return save_data;
  };

  TreeColumn.prototype.getCSVDestinationFields = function(csvImporter) {
    var opts;
    opts = {
      csvImporter: csvImporter,
      field: this
    };
    return [new HierarchyCSVImporterDestinationField(opts)];
  };

  TreeColumn.prototype.getMappingTargetName = function() {
    return this.name();
  };

  TreeColumn.prototype.isSystemField = function() {
    return true;
  };

  TreeColumn.prototype.getKeyInRights = function() {
    return "parent";
  };

  TreeColumn.prototype.getSortFields = function(filter) {
    var sortField;
    sortField = {
      field: this.fullName(),
      group_field: this.fullName(),
      order: filter._order
    };
    return sortField;
  };

  TreeColumn.prototype.sortExtraOpts = function() {};

  TreeColumn.prototype.formatSortGroupable = function(idParent, _, idx, data, object) {
    var parentObject, path, ref, ref1, ref2, standard;
    if (CUI.util.isEmpty(idParent)) {
      return;
    }
    idParent = "" + idParent;
    path = object != null ? object._path : void 0;
    if (!path) {
      return idParent;
    }
    parentObject = (ref = path.filter(function(_object) {
      return ("" + _object[_object._objecttype]._id) === idParent;
    })) != null ? ref[0] : void 0;
    if (!parentObject) {
      return idParent;
    }
    standard = ez5.loca.getBestDatabaseValue((ref1 = parentObject._standard) != null ? (ref2 = ref1[1]) != null ? ref2.text : void 0 : void 0);
    if (!standard) {
      return idParent;
    }
    return standard;
  };

  TreeColumn.prototype.renderRow = function(func, data, top_level_data, opts) {
    var row;
    if (opts == null) {
      opts = {};
    }
    row = TreeColumn.__super__.renderRow.call(this, func, data, top_level_data, opts);
    if (this.hasStandardNumbering()) {
      CUI.dom.setAttribute(row, "data-block-width", "75%");
    }
    return row;
  };

  TreeColumn.prototype.hasStandardNumbering = function() {
    return ez5.version("6") && this.linkMask().schema.standard_numbering && this.linkMask().getTable().hasHierarchicalReverse();
  };

  TreeColumn.prototype.hasMappingChildFields = function() {
    return false;
  };

  return TreeColumn;

})(LinkedObject);
// Generated by CoffeeScript 1.12.7
var ChildNumberingColumn,
  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;

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

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

  ChildNumberingColumn.prototype.nameLocalized = function() {
    return $$("base.child_numbering_column.name");
  };

  ChildNumberingColumn.prototype.name = function() {
    return "_child_numbering";
  };

  ChildNumberingColumn.prototype.isVisible = function(mode, opts) {
    return this.hasStandardNumbering() && (mode !== "expert" && mode !== "export") && ChildNumberingColumn.__super__.isVisible.call(this, mode, opts);
  };

  ChildNumberingColumn.prototype.renderEditorInput = function(data) {
    var disabled, select;
    if (!ez5.version("6")) {
      return;
    }
    if (!this.hasStandardNumbering()) {
      return;
    }
    disabled = !this.table.schema.columns.find((function(_this) {
      return function(arg) {
        var kind;
        kind = arg.kind;
        return kind === "reverse_link";
      };
    })(this));
    select = new CUI.Select({
      name: this.name(),
      form: {
        label: $$("tree.column.numbering.label")
      },
      options: ChildNumberingColumn.numberingOptions(),
      tooltip: {
        text: disabled ? $$("tree.column.numbering.require_reverse_edit") : void 0
      },
      data: data,
      disabled: disabled,
      id: this.idAttribute(data),
      onDataChanged: (function(_this) {
        return function() {
          CUI.Events.trigger({
            node: select,
            type: "editor-changed"
          });
        };
      })(this)
    });
    select.start();
    return select;
  };

  ChildNumberingColumn.prototype.getSaveData = function(data, save_data) {
    if (save_data == null) {
      save_data = {};
    }
    if (this.hasStandardNumbering()) {
      save_data[this.name()] = data[this.name()];
    }
    return save_data;
  };

  ChildNumberingColumn.prototype.isTopLevelField = function() {
    return true;
  };

  ChildNumberingColumn.prototype.isSystemField = function() {
    return true;
  };

  ChildNumberingColumn.prototype.hasRenderForSort = function() {
    return false;
  };

  ChildNumberingColumn.prototype.isSourceForMapping = function() {
    return false;
  };

  ChildNumberingColumn.prototype.isVisibleToSaveData = function() {
    return true;
  };

  ChildNumberingColumn.prototype.renderRow = function(func, data, top_level_data, opts) {
    var row;
    if (opts == null) {
      opts = {};
    }
    row = ChildNumberingColumn.__super__.renderRow.call(this, func, data, top_level_data, opts);
    if (this.hasStandardNumbering()) {
      CUI.dom.setAttribute(row, "data-block-width", "25%");
    }
    return row;
  };

  ChildNumberingColumn.numberingOptions = function(empty_key) {
    if (empty_key == null) {
      empty_key = "tree.column.numbering.off";
    }
    return [
      {
        value: "",
        text: $$(empty_key)
      }, {
        value: "none",
        text: $$("tree.column.numbering.none")
      }, {
        value: "123",
        text: $$("tree.column.numbering.123")
      }, {
        value: "abc",
        text: $$("tree.column.numbering.abc")
      }
    ];
  };

  return ChildNumberingColumn;

})(TreeColumn);
// 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.ParentsNestedTable = (function(superClass) {
  extend(ParentsNestedTable, superClass);

  ParentsNestedTable.prototype.invokeOnFields = null;

  function ParentsNestedTable(mask) {
    this.mask = mask;
    TreeColumn.prototype.constructor.call(this, this.mask);
    this.fatherMask = {};
    this.FieldSchema = {};
    this.ColumnSchema = {};
    return;
  }

  ParentsNestedTable.prototype.name = function() {
    return "_parents";
  };

  ParentsNestedTable.prototype.fullName = function() {
    return (this.mask.table.name()) + "." + (this.name());
  };

  ParentsNestedTable.prototype.nameLocalized = function() {
    return $$("main.editor.parents");
  };

  ParentsNestedTable.prototype.fullNameLocalized = function() {
    return (this.mask.table.nameLocalized()) + " / " + (this.nameLocalized());
  };

  ParentsNestedTable.prototype.init = function() {
    this.__fields = [new ez5.ParentLinkedObject(this.mask)];
  };

  ParentsNestedTable.prototype.getFields = function() {
    return this.__fields;
  };

  ParentsNestedTable.prototype.renderNestedRow = function(data, top_level_data, _opts) {
    _opts.polyhierarchical = true;
    return ParentsNestedTable.__super__.renderNestedRow.call(this, data, top_level_data, _opts);
  };

  ParentsNestedTable.prototype.renderForExpert = function(data, opts) {
    var parentTemplate, searchOptionsField;
    if (opts == null) {
      opts = {};
    }
    parentTemplate = ParentsNestedTable.__super__.renderForExpert.call(this, data, opts);
    if (!data._searchOptionsData) {
      data._searchOptionsData = {};
      data._searchOptionsData[this.name()] = [];
    }
    searchOptionsField = TreeColumn.getSearchOptionsField(this.name(), data._searchOptionsData);
    searchOptionsField.start();
    parentTemplate.append(searchOptionsField, "content");
    return parentTemplate;
  };

  ParentsNestedTable.prototype.getSearchUnsetElement = function(data) {};

  ParentsNestedTable.prototype.getSearchFilter = function(data, key) {
    var _entrySearch, entrySearch, filter, i, inOpt, j, k, len, len1, ref, ref1;
    if (key == null) {
      key = this.name();
    }
    filter = ParentsNestedTable.__super__.getSearchFilter.call(this, data, key);
    entrySearch = [];
    ref1 = ((ref = data._searchOptionsData) != null ? ref[this.name()] : void 0) || [];
    for (i = 0, len = ref1.length; i < len; i++) {
      k = ref1[i];
      switch (k) {
        case "with_parent":
          entrySearch.push({
            type: "in",
            fields: [this.mask.objecttype.name() + "._parents._system_object_id"],
            "in": [null],
            bool: "must_not"
          });
          break;
        case "without_parent":
          inOpt = ez5.version("6.12") ? [null, "0"] : [null];
          entrySearch.push({
            type: "in",
            fields: [this.mask.objecttype.name() + "._parents._system_object_id"],
            "in": inOpt,
            bool: "must"
          });
          break;
        case "with_children":
          entrySearch.push({
            type: "in",
            fields: ["_has_children"],
            "in": [true],
            bool: "must"
          });
          break;
        case "without_children":
          entrySearch.push({
            type: "in",
            fields: ["_has_children"],
            "in": [true],
            bool: "must_not"
          });
      }
    }
    if (!filter && entrySearch.length > 0) {
      filter = {
        type: "complex",
        bool: "must",
        search: []
      };
    }
    if (entrySearch.length > 0) {
      for (j = 0, len1 = entrySearch.length; j < len1; j++) {
        _entrySearch = entrySearch[j];
        filter.search.push({
          type: "complex",
          bool: "should",
          search: [_entrySearch]
        });
      }
    }
    return filter;
  };

  ParentsNestedTable.prototype.getQueryFieldBadge = function(data) {
    var badgePromise, deferred;
    deferred = new CUI.Deferred();
    badgePromise = ParentsNestedTable.__super__.getQueryFieldBadge.call(this, data);
    if (!CUI.util.isPromise(badgePromise)) {
      delete badgePromise.value;
      badgePromise = CUI.resolvedPromise(badgePromise);
    }
    badgePromise.done((function(_this) {
      return function(badge) {
        var nestedBadge;
        nestedBadge = TreeColumn.prototype.getQueryFieldBadge.call(_this, data._searchOptionsData);
        if (nestedBadge != null ? nestedBadge.value : void 0) {
          if (badge.value) {
            badge.value = nestedBadge.value + ", " + badge.value;
          } else {
            badge.value = nestedBadge.value;
          }
        }
        return deferred.resolve(badge);
      };
    })(this)).fail(deferred.reject);
    return deferred.promise();
  };

  ParentsNestedTable.prototype.isVisible = function(mode, opts) {
    if (opts == null) {
      opts = {};
    }
    return TreeColumn.prototype.isVisible.call(this, mode, opts);
  };

  ParentsNestedTable.prototype.insideNested = function() {
    return Field.prototype.insideNested.call(this);
  };

  ParentsNestedTable.prototype.isReadOnly = function(data, top_level_data, opts) {
    var mask_read_only, ref;
    if (opts == null) {
      opts = {};
    }
    mask_read_only = TreeColumn.isReadOnly(this.mask.schema.system_fields.parent);
    return ((ref = opts.mode) !== "editor" && ref !== "editor-bulk") || mask_read_only;
  };

  ParentsNestedTable.prototype.getBulkOptions = function(data, opts) {
    var options;
    return [];
    options = [];
    if (this.isReadOnly(data, opts.top_level_data, opts)) {
      return options;
    }
    if (this.depth() > 0) {
      return options;
    }
    switch (opts.mode) {
      case "editor-bulk":
      case "editor-header-bulk":
        options = ["bulk_replace", "bulk_append", "bulk_remove", "bulk_remove_all"];
    }
    return options;
  };

  ParentsNestedTable.prototype.getBulkSaveData = function(data, save_data, opts, key) {};

  ParentsNestedTable.prototype.getSaveData = function(data, save_data, opts) {
    if (opts == null) {
      opts = {};
    }
    ParentsNestedTable.__super__.getSaveData.call(this, data, save_data, opts);
    if (opts.init_save_data) {
      save_data[this.name()] = data[this.name()];
      data[this.name()] = data[this.name()].map((function(_this) {
        return function(_parent, index) {
          return {
            _parent: _parent,
            _row_number: index
          };
        };
      })(this));
      return save_data;
    }
    if (save_data[this.name()]) {
      save_data[this.name()] = data[this.name()].map((function(_this) {
        return function(_parent) {
          return _parent._parent;
        };
      })(this)).filter(function(_object) {
        return !!_object;
      });
      if (opts.for_server) {
        save_data[this.name()].forEach(function(object) {
          delete object._sort;
          delete object._orig_mask;
          delete object.__offset;
          delete object.__idx;
        });
      }
    }
    return save_data;
  };

  ParentsNestedTable.prototype.getFatherField = function() {
    return Field.prototype.getFatherField.call(this);
  };

  ParentsNestedTable.prototype.getCheckInfo = function(mode) {
    return [];
  };

  ParentsNestedTable.prototype.isSystemField = function() {
    return true;
  };

  ParentsNestedTable.prototype.supportsRowMove = function() {
    return true;
  };

  ParentsNestedTable.prototype.isAppendOnly = function() {
    return false;
  };

  ParentsNestedTable.prototype.supportsEmptyRowAdd = function(opts) {
    return false;
  };

  ParentsNestedTable.prototype.isNestedIndex = function() {
    return false;
  };

  ParentsNestedTable.prototype.getInfoLabels = function() {
    return [];
  };

  ParentsNestedTable.prototype.supportsNestedUUID = function() {
    return false;
  };

  return ParentsNestedTable;

})(NestedTable);
// 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.ParentLinkedObject = (function(superClass) {
  extend(ParentLinkedObject, superClass);

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

  ParentLinkedObject.prototype.isSystemField = function() {
    return true;
  };

  ParentLinkedObject.prototype.allowsList = function() {
    return false;
  };

  ParentLinkedObject.prototype.isVisible = function() {
    return true;
  };

  ParentLinkedObject.prototype.name = function() {
    return "_parent";
  };

  ParentLinkedObject.prototype.isReadOnly = function(data, top_level_data, opts) {
    var ref;
    if (opts == null) {
      opts = {};
    }
    return (ref = opts.mode) !== "editor" && ref !== "editor-bulk";
  };

  ParentLinkedObject.prototype.__getLinkMaskInline = function() {
    return "standard";
  };

  ParentLinkedObject.prototype.setData = function(data, nestedData, linked_object_data) {
    return data[this.name()] = linked_object_data;
  };

  ParentLinkedObject.prototype.addToCollection = function(data, top_level_data, collection) {
    return this.__addToCollection(data[this.name()], collection);
  };

  ParentLinkedObject.prototype.__addToCollection = function(data, collection) {
    if (CUI.util.isEmpty(data._global_object_id)) {
      data._global_object_id = "0";
    }
    return ParentLinkedObject.__super__.__addToCollection.call(this, data, collection);
  };

  ParentLinkedObject.prototype.isEmpty = function(data) {
    return CUI.util.isEmpty(data);
  };

  ParentLinkedObject.prototype.renderSearchInput = function(data, opts) {
    opts.skip_extra_options = true;
    return ParentLinkedObject.__super__.renderSearchInput.call(this, data, opts);
  };

  ParentLinkedObject.prototype.getSearchFilter = function(data, key) {
    var _search, i, len, pathSearch, pathSearchData, s, search;
    if (key == null) {
      key = this.name();
    }
    search = [];
    pathSearch = [];
    pathSearchData = data[this.name() + "_path"];
    if (pathSearchData) {
      pathSearchData.forEach((function(_this) {
        return function(object) {
          pathSearch.push({
            type: "complex",
            bool: "should",
            search: [
              {
                type: "in",
                "in": [object.globalObjectId],
                fields: [(_this.mask.objecttype.name()) + "._parents._global_object_id"],
                bool: "must"
              }, {
                type: "in",
                "in": [object.globalObjectId],
                fields: ["_global_object_id"],
                bool: "must_not"
              }
            ]
          });
        };
      })(this));
    }
    if (pathSearch.length > 0) {
      search.push(pathSearch);
    }
    if (search.length > 0) {
      _search = [];
      for (i = 0, len = search.length; i < len; i++) {
        s = search[i];
        _search.push({
          type: "complex",
          search: s
        });
      }
      return {
        type: "complex",
        bool: "must",
        search: _search
      };
    } else {
      return null;
    }
  };

  ParentLinkedObject.prototype.renderRow = function(func, data, top_level_data, opts) {
    if (opts == null) {
      opts = {};
    }
    return ParentLinkedObject.__super__.renderRow.call(this, func, data, top_level_data, opts);
  };

  ParentLinkedObject.prototype.getResultObject = function(data, top_level_data, opts) {
    var ref;
    if ((data != null ? (ref = data._parent) != null ? ref._system_object_id : void 0 : void 0) === 0) {
      return new ParentRootResultObject().setData(data[this.name()]);
    } else {
      return ParentLinkedObject.__super__.getResultObject.call(this, data, top_level_data, opts);
    }
  };

  ParentLinkedObject.prototype.__loadFromData = function(data, mode) {
    if (data._system_object_id === 0) {
      if (!data._objecttype) {
        data = ParentRootResultObject.getSaveDataFromMask(this.linkMask());
      }
      return ParentRootResultObject.loadFromData(data, mode);
    } else {
      return ParentLinkedObject.__super__.__loadFromData.call(this, data, mode);
    }
  };

  return ParentLinkedObject;

})(TreeColumn);
// Generated by CoffeeScript 1.12.7
var VersionColumn,
  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;

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

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

  VersionColumn.prototype.name = function() {
    return "_version";
  };

  VersionColumn.prototype.nameLocalized = function() {
    return $$("base.version_column.name");
  };

  VersionColumn.prototype.getSaveData = function(data, save_data, opts) {
    if (opts.copy) {
      return;
    }
    if (this.insideNested()) {
      return;
    }
    if (data._version) {
      CUI.util.assert(data._id, "VersionColumn.getSaveData", "data._version is set, but data._id is not: unable to get save data.", {
        data: data,
        save_data: save_data
      });
      return save_data._version = data._version + 1;
    } else {
      CUI.util.assert(!data._id, "VersionColumn.getSaveData", "data._version is not set, but data._id is: unable to get save data.", {
        data: data,
        save_data: save_data
      });
      return save_data._version = 1;
    }
  };

  VersionColumn.prototype.isVisibleToSaveData = function() {
    return true;
  };

  VersionColumn.prototype.isVisible = function(mode, opts) {
    var isVisible;
    if (opts == null) {
      opts = {};
    }
    if (CUI.util.isFunction(opts.isVisible)) {
      isVisible = opts.isVisible(this, mode, opts);
      if (CUI.util.isBoolean(isVisible)) {
        return isVisible;
      }
    }
    if (opts.hide_other_system_fields) {
      return false;
    }
    switch (mode) {
      case "export":
      case "detail-footer":
      case "editor-footer":
        return true;
      case "csv-import":
        return this.insideNested();
    }
    return false;
  };

  VersionColumn.prototype.isSourceForMapping = function(required_type) {
    return false;
  };

  VersionColumn.prototype.isEmpty = function() {
    return false;
  };

  VersionColumn.prototype.hasUserData = function(data) {
    return false;
  };

  VersionColumn.prototype.getDataAsString = function(data) {
    return data._version;
  };

  VersionColumn.prototype.createChangeHistoryDisplay = function(data, opts) {
    var btn, container, span, span_text;
    if (opts == null) {
      opts = {};
    }
    span_text = "" + (data._version || 1);
    if (ez5.version("6") && this.canShowChangeHistory(data, opts)) {
      span_text += " – ";
      span = new CUI.Label({
        text: span_text
      });
      btn = new CUI.ButtonHref({
        "class": "ez5-inline-change-history-button",
        text: $$("detail.sidebar.view-change-history.button|text"),
        appearance: "link",
        onClick: (function(_this) {
          return function() {
            return CUI.Events.trigger({
              type: "show-change-history",
              info: {
                object_id: data._id
              }
            });
          };
        })(this)
      });
      btn.setIconRight(null);
      container = CUI.dom.div();
      container.appendChild(span.DOM);
      container.appendChild(btn.DOM);
      return container;
    }
    span = new CUI.Label({
      text: span_text
    });
    return span;
  };

  VersionColumn.prototype.canShowChangeHistory = function(data, opts) {
    var base, base1, has_right;
    if (opts == null) {
      opts = {};
    }
    if (!ez5.version("6") || !data._id) {
      return false;
    }
    has_right = ez5.session.hasSystemRight("root", "frontend_features[changelog]", "frontend_features[changelog_with_user]");
    if (opts.editor != null) {
      return has_right && (typeof (base = opts.editor).changeHistoryAvailable === "function" ? base.changeHistoryAvailable() : void 0) && opts.editor.changeHistoryAvailable();
    }
    if (opts.detail != null) {
      return has_right && (typeof (base1 = opts.detail).changeHistoryAvailable === "function" ? base1.changeHistoryAvailable() : void 0) && opts.detail.changeHistoryAvailable();
    }
    return has_right;
  };

  VersionColumn.prototype.renderDetailOutput = function(data, top_level_data, opts) {
    if (opts == null) {
      opts = {};
    }
    return this.createChangeHistoryDisplay(data, opts);
  };

  VersionColumn.prototype.renderEditorInput = function(data, top_level_data, opts) {
    return this.createChangeHistoryDisplay(data, opts);
  };

  VersionColumn.prototype.getOutputStandard = function() {
    return null;
  };

  VersionColumn.prototype.getCSVDestinationFields = function(csvImporter) {
    var dest_field;
    dest_field = {
      format: "number",
      field: this,
      use_for_match_existing: true,
      supports_hierarchy: false,
      csvImporter: csvImporter
    };
    return [new ObjecttypeCSVImporterDestinationField(dest_field)];
  };

  VersionColumn.prototype.isSystemField = function() {
    return true;
  };

  return VersionColumn;

})(Field);

CUI.ready(function() {
  return CUI.Events.registerEvent({
    type: "show-change-history",
    bubble: true
  });
});
// Generated by CoffeeScript 1.12.7
var LastModifiedColumn,
  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;

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

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

  LastModifiedColumn.prototype.name = function() {
    return "_last_modified";
  };

  LastModifiedColumn.prototype.isTopLevelField = function() {
    return true;
  };

  LastModifiedColumn.prototype.nameLocalized = function() {
    return $$("last.modified.column.name");
  };

  LastModifiedColumn.prototype.getSaveData = function(data, save_data, opts) {};

  LastModifiedColumn.prototype.isVisible = function(mode, opts) {
    var isVisible, ref;
    if (opts == null) {
      opts = {};
    }
    if (mode === "export") {
      return true;
    }
    if (!((ref = opts.top_level_data) != null ? ref._last_modified : void 0)) {
      return false;
    }
    if (opts.hide_other_system_fields) {
      return false;
    }
    if (CUI.util.isFunction(opts.isVisible)) {
      isVisible = opts.isVisible(this, mode, opts);
      if (CUI.util.isBoolean(isVisible)) {
        return isVisible;
      }
    }
    switch (mode) {
      case "detail-footer":
      case "editor-footer":
        return true;
    }
    return false;
  };

  LastModifiedColumn.prototype.isEmpty = function() {
    return false;
  };

  LastModifiedColumn.prototype.hasUserData = function(data) {
    return false;
  };

  LastModifiedColumn.prototype.getDataAsString = function(data) {
    return ez5.format_date_and_time(data._last_modified, false);
  };

  LastModifiedColumn.prototype.renderDetailOutput = function(data, top_level_data) {
    return new CUI.Label({
      text: this.getDataAsString(top_level_data)
    });
  };

  LastModifiedColumn.prototype.renderEditorInput = function(data, top_level_data) {
    return new CUI.Label({
      text: this.getDataAsString(top_level_data)
    });
  };

  LastModifiedColumn.prototype.getOutputStandard = function() {
    return null;
  };

  LastModifiedColumn.prototype.isSystemField = function() {
    return true;
  };

  LastModifiedColumn.prototype.fullName = function() {
    return this.name();
  };

  LastModifiedColumn.prototype.isSourceForMapping = function(required_type) {
    return false;
  };

  LastModifiedColumn.prototype.isValidMappingField = function(level) {
    return level === 0;
  };

  return LastModifiedColumn;

})(Field);
// Generated by CoffeeScript 1.12.7
var MultipleFieldsContainer,
  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;

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

  function MultipleFieldsContainer(fields1) {
    var fn1, i, len, method, ref;
    this.fields = fields1 != null ? fields1 : [];
    this.sortExtraOpts = bind(this.sortExtraOpts, this);
    ref = ['renderForSort', 'renderRow', 'renderFieldAsGroup', 'renderFieldLabel', 'renderSortInput'];
    fn1 = (function(_this) {
      return function(method) {
        return _this[method] = function() {
          return Field.prototype[method].apply(_this, arguments);
        };
      };
    })(this);
    for (i = 0, len = ref.length; i < len; i++) {
      method = ref[i];
      fn1(method);
    }
    return;
  }

  MultipleFieldsContainer.prototype.addLinkedObjecttype = function(lot, filter_by_ot_name, filter_by_mask_name) {
    var count, fn, i, len, lf, lfs, matching, ref;
    if (filter_by_ot_name == null) {
      filter_by_ot_name = null;
    }
    if (filter_by_mask_name == null) {
      filter_by_mask_name = null;
    }
    this.setNameLocalized(lot.nameLocalized());
    count = 0;
    ref = lot._linked_object_fields_by_name;
    for (fn in ref) {
      lfs = ref[fn];
      if (filter_by_ot_name && lfs[0].getMainMask().table.name() !== filter_by_ot_name) {
        continue;
      }
      if (filter_by_mask_name) {
        matching = null;
        for (i = 0, len = lfs.length; i < len; i++) {
          lf = lfs[i];
          if (lf.getMainMask().name() === filter_by_mask_name) {
            matching = lf;
            break;
          }
        }
        if (!matching) {
          continue;
        }
        count++;
        this.addField(matching);
      } else {
        count++;
        this.addField(lfs[0]);
      }
    }
    return count;
  };

  MultipleFieldsContainer.prototype.setNameLocalized = function(__nameLocalized) {
    this.__nameLocalized = __nameLocalized;
  };

  MultipleFieldsContainer.prototype.addField = function(f) {
    return this.fields.push(f);
  };

  MultipleFieldsContainer.prototype.id = function() {};

  MultipleFieldsContainer.prototype.getBulkCheckbox = function() {};

  MultipleFieldsContainer.prototype.getBulkOptions = function() {};

  MultipleFieldsContainer.prototype.getBulkOptionsForm = function() {};

  MultipleFieldsContainer.prototype.getSearchFilter = function(data, key) {
    var f, filter, has_value_filter, i, idx, len, multi_filter, ref, search;
    if (key == null) {
      key = this.fields[0].name();
    }
    search = [];
    has_value_filter = false;
    ref = this.fields;
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      f = ref[idx];
      filter = f.getSearchFilterWithNested(data, key);
      if (!filter) {
        continue;
      }
      filter.bool = filter._unnest ? "must" : "should";
      if (filter._has_value_filter) {
        has_value_filter = true;
      }
      idx = CUI.util.idxInArray(null, search, function(v) {
        return CUI.util.isEqual(v, filter);
      });
      if (idx === -1) {
        search.push(filter);
      }
    }
    if (search.length) {
      multi_filter = {
        type: "complex",
        search: search
      };
      if (has_value_filter) {
        multi_filter.bool = "must_not";
      }
      return multi_filter;
    } else {
      return null;
    }
  };

  MultipleFieldsContainer.prototype.getSearchFilterWithNested = function(data, key) {
    return this.getSearchFilter(data, key);
  };

  MultipleFieldsContainer.prototype.getSortFields = function(data, keys, activeFilters) {
    var f, i, len, ref, sort_fields;
    sort_fields = [];
    ref = this.fields;
    for (i = 0, len = ref.length; i < len; i++) {
      f = ref[i];
      sort_fields.push(f.getSortFields(data, keys, activeFilters));
      if (f.isSortUnique()) {
        break;
      }
    }
    return sort_fields;
  };

  MultipleFieldsContainer.prototype.fullName = function() {
    var f;
    if (this.fields[0].isTopLevelField()) {
      return this.fields[0].fullName();
    } else {
      return ((function() {
        var i, len, ref, results;
        ref = this.fields;
        results = [];
        for (i = 0, len = ref.length; i < len; i++) {
          f = ref[i];
          results.push(f.fullName());
        }
        return results;
      }).call(this)).join("-");
    }
  };

  MultipleFieldsContainer.prototype.fullNameLocalized = function() {
    return this.fields[0].fullNameLocalized();
  };

  MultipleFieldsContainer.prototype.name = function() {
    return this.fields[0].name();
  };

  MultipleFieldsContainer.prototype.getLabel = function(data, top_level_data, opts) {
    var f;
    if (opts == null) {
      opts = {};
    }
    return new CUI.Label({
      text: this.nameLocalized(),
      multiline: true,
      tooltip: ez5.version("6") && opts.mode === "sort" ? {
        text: ((function() {
          var i, len, ref, results;
          ref = this.fields;
          results = [];
          for (i = 0, len = ref.length; i < len; i++) {
            f = ref[i];
            results.push(f.table.nameLocalized());
          }
          return results;
        }).call(this)).join("\n"),
        placement: "w"
      } : void 0
    });
  };

  MultipleFieldsContainer.prototype.getDataForFieldData = function() {
    return Field.prototype.getDataForFieldData.apply(this.fields[0], arguments);
  };

  MultipleFieldsContainer.prototype.getSearchUnsetElement = function(data, listViewRow) {
    return this.fields[0].getSearchUnsetElement(data, listViewRow);
  };

  MultipleFieldsContainer.prototype.getClass = function() {
    return this.fields[0].getClass() + " multiple-fields-container";
  };

  MultipleFieldsContainer.prototype.isSortGroupable = function(filter) {
    return this.fields[0].isSortGroupable(filter);
  };

  MultipleFieldsContainer.prototype.formatSortGroupable = function(item, filter, idx, data, object) {
    return this.fields[0].formatSortGroupable(item, filter, idx, data, object);
  };

  MultipleFieldsContainer.prototype.isInPopoverTopLevel = function() {
    return this.fields[0].isInPopoverTopLevel();
  };

  MultipleFieldsContainer.prototype.sortRenderContent = function(path, renderDynamic) {
    return this.fields[0].sortRenderContent(path, renderDynamic);
  };

  MultipleFieldsContainer.prototype.isTopLevelField = function() {
    return this.fields[0].isTopLevelField();
  };

  MultipleFieldsContainer.prototype.isSystemField = function() {
    var base;
    return typeof (base = this.fields[0]).isSystemField === "function" ? base.isSystemField() : void 0;
  };

  MultipleFieldsContainer.prototype.nameLocalized = function() {
    if (!CUI.util.isEmpty(this.__nameLocalized)) {
      return this.__nameLocalized;
    } else {
      return this.fields[0].nameLocalized();
    }
  };

  MultipleFieldsContainer.prototype.getNoInheritedQueryFieldBadge = function(data) {
    return this.fields[0].getNoInheritedQueryFieldBadge(data);
  };

  MultipleFieldsContainer.prototype.getQueryFieldBadge = function(data) {
    return this.fields[0].getQueryFieldBadge(data, this);
  };

  MultipleFieldsContainer.prototype.renderForExpert = function(data, opts) {
    if (opts == null) {
      opts = {};
    }
    opts.fields = this.fields;
    if (ez5.session.isDebug()) {
      opts.overwriteLabel = this.nameLocalized() + " [" + this.fields.length + "]";
    } else {
      opts.overwriteLabel = this.nameLocalized();
    }
    opts.forceShowLabel = true;
    return this.fields[0].renderForExpert(data, opts);
  };

  MultipleFieldsContainer.prototype.sortExtraOpts = function(data) {
    return this.fields[0].sortExtraOpts(data);
  };

  MultipleFieldsContainer.prototype.getSignature = function() {
    var f;
    return {
      "class": "MultipleFieldsContainer",
      fields: (function() {
        var i, len, ref, results;
        ref = this.fields;
        results = [];
        for (i = 0, len = ref.length; i < len; i++) {
          f = ref[i];
          results.push(f.getSignature());
        }
        return results;
      }).call(this)
    };
  };

  MultipleFieldsContainer.prototype.renderHalfWidth = function() {
    return false;
  };

  MultipleFieldsContainer.fromSignature = function(signature) {
    var f, fields, i, len, ref;
    fields = [];
    ref = signature.fields;
    for (i = 0, len = ref.length; i < len; i++) {
      f = ref[i];
      fields.push(window[f["class"]].fromSignature(f));
    }
    fields;
    return new window[signature["class"]](fields);
  };

  MultipleFieldsContainer.prototype.hasRenderForSort = function() {
    return this.fields[0].hasRenderForSort();
  };

  MultipleFieldsContainer.prototype.getObjecttypes = function() {
    var f, i, len, objs, ref;
    objs = [];
    ref = this.fields || [];
    for (i = 0, len = ref.length; i < len; i++) {
      f = ref[i];
      objs.push(f.table.name());
    }
    return objs;
  };

  return MultipleFieldsContainer;

})(CUI.Dummy);
// Generated by CoffeeScript 1.12.7
var MaskFieldSelector, MaskFieldSelectorDetail,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  MaskFieldSelector.prototype.initOpts = function() {
    MaskFieldSelector.__super__.initOpts.call(this);
    return this.addOpts({
      dbInfo: {
        mandatory: true,
        check: DbInfo
      },
      mask_name: {
        mandatory: true,
        "default": {},
        check: String
      },
      onChanged: {
        mandatory: true,
        check: Function
      },
      form: {
        check: "PlainObject"
      },
      show_all_fields_mask: {
        "default": false,
        check: Boolean
      },
      select_opts: {
        check: "PlainObject"
      },
      filter: {
        check: Function
      },
      ui: {
        check: String
      }
    });
  };

  MaskFieldSelector.prototype.getSelect = function() {
    var current_mask_name, data, i, len, mask, mask_options, opts, ref, tooltip;
    mask_options = [];
    ref = this.availableMasks();
    for (i = 0, len = ref.length; i < len; i++) {
      mask = ref[i];
      if (mask.name() === "_all_fields" && !this._show_all_fields_mask) {
        continue;
      }
      mask_options.push({
        value: mask.name(),
        text: mask.nameLocalizedWithoutInstance()
      });
    }
    mask_options.sort(function(a, b) {
      if (a.value === "_all_fields") {
        return -1;
      }
      if (b.value === "_all_fields") {
        return -1;
      }
      return a.text.localeCompare(b.text);
    });
    data = {
      mask_name: this._mask_name
    };
    current_mask_name = data.mask_name;
    if (mask_options.length > 1) {
      tooltip = {
        text: $$("mask.field.selector.tooltip")
      };
    } else {
      tooltip = void 0;
    }
    opts = {
      name: "mask_name",
      "class": "ez5-mask-field-selector",
      ui: this._ui || "mask.field.selector",
      form: this._form,
      data: data,
      tooltip: tooltip,
      undo_and_changed_support: false,
      onDataChanged: (function(_this) {
        return function(_, df) {
          var ret;
          ret = _this._onChanged(current_mask_name, data.mask_name);
          CUI.util.assert(CUI.util.isPromise(ret), "MaskFieldSelector.renderInput", "onChanged needs to return Promise", {
            ret: ret
          });
          ret.done(function() {
            return current_mask_name = data.mask_name;
          });
          ret.fail(function() {
            data.mask_name = current_mask_name;
            return df.displayValue();
          });
        };
      })(this),
      options: mask_options,
      data: data
    };
    CUI.util.mergeMap(opts, this._select_opts);
    return CUI.Select.newSelectOrOutput(opts);
  };

  MaskFieldSelector.prototype.availableMasks = function() {
    var masks;
    masks = this._dbInfo.availableMasks();
    if (this._filter) {
      masks = masks.filter(this._filter);
    }
    return masks;
  };

  MaskFieldSelector.getFormSelect = function(search, formOpts, opts) {
    var deferred, request, requestData;
    if (formOpts == null) {
      formOpts = {};
    }
    if (opts == null) {
      opts = {};
    }
    if (search instanceof Search) {
      request = new Request();
      search.addToRequest(request);
      requestData = request.cleanRequestForSearch();
    } else if (CUI.util.isPlainObject(search)) {
      requestData = search;
    } else {
      requestData = {};
    }
    requestData.aggregations = {
      _mask: {
        type: "term",
        limit: 100000,
        field: "_mask"
      }
    };
    requestData.limit = 0;
    requestData.offset = 0;
    requestData.generate_rights = false;
    requestData.best_mask_filter = false;
    if (opts.removeMaskFilter) {
      CUI.util.removeFromArray(null, requestData.search, function(item) {
        return item.__mask_filter;
      });
    }
    deferred = new CUI.Deferred();
    ez5.api.search({
      json_data: requestData
    }).done((function(_this) {
      return function(data) {
        var defaultOpts, existing_ots, field, i, info, j, len, len1, mas_name, mask, mask_by_ot, mask_filter_fields, mask_filter_form, masks, ot, ot_name, ref, ref1, sel_opts;
        mask_by_ot = {};
        ref = data.aggregations._mask.terms;
        for (i = 0, len = ref.length; i < len; i++) {
          info = ref[i];
          mask = ez5.mask.CURRENT._mask_instance_by_name[info.term];
          if (opts.filter && !(typeof opts.filter === "function" ? opts.filter(mask) : void 0)) {
            continue;
          }
          ot_name = mask.getTable().name();
          if (!mask_by_ot[ot_name]) {
            mask_by_ot[ot_name] = [];
          }
          mask_by_ot[ot_name].push(mask);
        }
        mask_filter_fields = [];
        existing_ots = [];
        for (ot_name in mask_by_ot) {
          masks = mask_by_ot[ot_name];
          ot = ez5.schema.CURRENT._objecttype_by_name[ot_name];
          CUI.util.pushOntoArray(ot_name, existing_ots);
          sel_opts = [];
          for (j = 0, len1 = masks.length; j < len1; j++) {
            mask = masks[j];
            sel_opts.push({
              text: mask.nameLocalized(),
              value: mask.name()
            });
          }
          sel_opts.sort(function(a, b) {
            return a.text.localeCompare(b.text.localeCompare);
          });
          field = {
            type: CUI.Select,
            name: ot.name,
            options: sel_opts,
            form: {
              label: ot._name_localized
            }
          };
          mask_filter_fields.push(field);
        }
        mask_filter_fields.sort(function(a, b) {
          return a.form.label.localeCompare(b.form.label.localeCompare);
        });
        defaultOpts = {
          name: "mask",
          data: {},
          fields: mask_filter_fields
        };
        CUI.util.mergeMap(formOpts, defaultOpts);
        if (formOpts.data.mask) {
          ref1 = formOpts.data.mask;
          for (ot_name in ref1) {
            mas_name = ref1[ot_name];
            if (indexOf.call(existing_ots, ot_name) < 0) {
              delete formOpts.data.mask[ot_name];
            }
          }
        }
        mask_filter_form = new CUI.Form(formOpts);
        return deferred.resolve(mask_filter_form);
      };
    })(this)).fail(deferred.reject);
    return deferred.promise();
  };

  MaskFieldSelector.getSearchFilter = function(mask_filter) {
    var filter, mask_name, ot_name, sf;
    sf = [];
    filter = {
      __mask_filter: true,
      type: "complex",
      bool: "must",
      search: sf
    };
    for (ot_name in mask_filter) {
      mask_name = mask_filter[ot_name];
      if (mask_name === null) {
        continue;
      }
      sf.push({
        type: "complex",
        bool: "should",
        search: [
          {
            bool: "must",
            type: "in",
            "in": [ot_name],
            fields: ["_objecttype"]
          }, {
            bool: "must",
            type: "in",
            "in": [mask_name],
            fields: ["_mask"]
          }
        ]
      });
    }
    return filter;
  };

  return MaskFieldSelector;

})(CUI.Element);

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

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

  MaskFieldSelectorDetail.prototype.initOpts = function() {
    MaskFieldSelectorDetail.__super__.initOpts.call(this);
    this.removeOpt("dbInfo");
    return this.addOpts({
      masks: {
        check: function(v) {
          return (v != null ? v.length : void 0) > 0;
        }
      }
    });
  };

  MaskFieldSelectorDetail.prototype.availableMasks = function() {
    return this._masks;
  };

  return MaskFieldSelectorDetail;

})(MaskFieldSelector);
// Generated by CoffeeScript 1.12.7

/*
  This is a special system field to identify a nested row in a nested table.
  If this is present we must send it to the server to identify the row.
 */
var NestedUUID,
  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;

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

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

  NestedUUID.prototype.nameLocalized = function() {
    return $$("base.nested_uuid.name");
  };

  NestedUUID.prototype.isVisible = function(mode, opts) {
    if (opts == null) {
      opts = {};
    }
    if (opts.skip_uuid_field && opts.skip_uuid_field === this) {
      return false;
    }
    if (mode === "editor" && this.__noVisibleFieldsInEditor()) {
      return true;
    }
    return false;
  };

  NestedUUID.prototype.isReadOnly = function() {
    return true;
  };

  NestedUUID.prototype.isVisibleToSaveData = function() {
    return true;
  };

  NestedUUID.prototype.name = function() {
    if (ez5.version("6")) {
      return "_uuid";
    } else {
      return "_id";
    }
  };

  NestedUUID.prototype.getSaveData = function(data, save_data, opts) {
    if (opts.copy) {
      return;
    }
    if (opts.copy_for_template) {
      return;
    }
    if (data[this.name()]) {
      save_data[this.name()] = data[this.name()];
    }
    return save_data;
  };

  NestedUUID.prototype.isSourceForMapping = function() {
    return false;
  };

  NestedUUID.prototype.__noVisibleFieldsInEditor = function() {
    var fields;
    fields = this.mask.getFields("editor", {
      skip_uuid_field: this
    });
    return fields.length === 0;
  };

  NestedUUID.prototype.renderEditorInput = function(data) {
    var i, span;
    if (!this.isEmpty(data)) {
      span = CUI.dom.span();
      span.textContent = data[this.name()];
      return span;
    } else {
      i = CUI.dom.i();
      i.textContent = $$("main.editor.nested.uuid.empty");
      return i;
    }
  };

  NestedUUID.prototype.hasUserData = function(data, _, opts) {
    if (opts == null) {
      opts = {};
    }
    return !this.isEmpty(data, _, opts);
  };

  return NestedUUID;

})(PrimaryKeyColumn);
// Generated by CoffeeScript 1.12.7
var Toolbox,
  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,
  slice = [].slice;

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

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

  Toolbox.getMenuItems = function(tools, toolboxInst, empty_fallback) {
    var i, items, last_group, len, ref, tool;
    if (empty_fallback == null) {
      empty_fallback = false;
    }
    items = [];
    last_group = null;
    ref = ToolboxTool.sortTools(tools.slice(0));
    for (i = 0, len = ref.length; i < len; i++) {
      tool = ref[i];
      if (tool.isHidden()) {
        continue;
      }
      if (last_group && last_group !== tool.getSortGroup()) {
        items.push({
          divider: true
        });
      }
      last_group = tool.getSortGroup();
      items.push(tool.getMenuItem(toolboxInst));
    }
    if (empty_fallback && items.length === 0) {
      items.push(new LocaLabel({
        loca_key: "toolbox.no_menu_item",
        "class": "ez5-toolbox-no-menu-item"
      }));
    }
    return items;
  };

  Toolbox.getMenuItemsWithFallback = function(tools) {
    return this.getMenuItems(tools, null, true);
  };

  Toolbox.prototype.showContextMenu = function(ev, tools) {
    var grouped_tools, groups, grp, i, items, items_per_group, j, len, len1, ref, t, tls;
    groups = [];
    grouped_tools = {};
    for (i = 0, len = tools.length; i < len; i++) {
      t = tools[i];
      t.setToolbox(this);
      if (t.isHidden()) {
        continue;
      }
      grp = t.getGroup();
      if (!grp) {
        console.error("Toolbox.showContextMenu: not showing tool, group not set. tool: ", t);
        continue;
      }
      if (!grouped_tools[grp]) {
        grouped_tools[grp] = [];
        groups.push(grp);
      }
      grouped_tools[grp].push(t);
    }
    groups.sort(function(a, b) {
      return CUI.util.compareIndex(grouped_tools[a][0].getSortGroup(), grouped_tools[b][0].getSortGroup());
    });
    items = [];
    for (j = 0, len1 = groups.length; j < len1; j++) {
      grp = groups[j];
      tls = grouped_tools[grp];
      items.push({
        label: {
          text: tls[0].getGroupText()
        }
      });
      items_per_group = Toolbox.getMenuItems(tls, this);
      items.push.apply(items, items_per_group);
    }
    if (ez5.session.isDebug()) {
      items.push({
        label: new CUI.EmptyLabel({
          size: "mini",
          "class": "ez5-toolbox-hint-browser-context-menu",
          markdown: true,
          text: $$("toolbox.use_crtl_for_browser_context_menu")
        })
      });
    }
    if (items.length === 0) {
      if ((ref = this.__menu) != null) {
        ref.destroy();
      }
      this.__menu = null;
      return;
    }
    if (this.__menu) {
      return this.__menu.setItemList({
        items: items
      });
    } else {
      this.__menu = new CUI.Menu({
        "class": "ez5-toolbox-menu",
        itemList: {
          items: items
        },
        show_at_position: {
          top: ev.clientY(),
          left: ev.clientX()
        },
        onHide: (function(_this) {
          return function(menu, ev) {
            return _this.__menu = null;
          };
        })(this)
      });
      this.__menu.show(ev);
      return this;
    }
  };

  Toolbox.findToolByName = function(name, tools) {
    var i, len, tool;
    for (i = 0, len = tools.length; i < len; i++) {
      tool = tools[i];
      if (tool.getName() === name) {
        return tool;
      }
    }
    return null;
  };

  Toolbox.removeToolByName = function(name, tools) {
    return CUI.util.removeFromArray(name, tools, function(v) {
      return v.getName() === name;
    });
  };

  Toolbox.__group = 0;

  Toolbox.getFlyoutButtons = function(tools, btn_opts) {
    var buttons, fav, flyouts, i, item, len, opts;
    if (btn_opts == null) {
      btn_opts = {};
    }
    buttons = [];
    flyouts = this.getMenuItems(tools);
    for (i = 0, len = flyouts.length; i < len; i++) {
      item = flyouts[i];
      if (!item._tool) {
        continue;
      }
      opts = CUI.util.mergeMap({
        group: "toolbox-group-" + this.__group
      }, CUI.util.copyObject(btn_opts, true));
      fav = item._tool.getAsFavoriteButton(opts);
      if (!fav) {
        continue;
      }
      buttons.push(fav);
    }
    if (flyouts.length > 0 && flyouts.length >= buttons.length) {
      opts = CUI.util.mergeMap({
        ui: "toolbox.flyout.button",
        group: "toolbox-group-" + this.__group,
        loca_key: "toolbox.flyout_buttonbar_side_menu_button",
        "class": "toolbox-flyout-button",
        icon_right: false,
        menu: {
          onShow: (function(_this) {
            return function(lay, ev) {
              var _tools, j, k, len1, len2, t;
              _tools = [];
              for (j = 0, len1 = flyouts.length; j < len1; j++) {
                item = flyouts[j];
                if (item._tool) {
                  _tools.push(item._tool);
                }
              }
              for (k = 0, len2 = _tools.length; k < len2; k++) {
                t = _tools[k];
                if (!t) {
                  continue;
                }
                t.onFlyoutMenuShow(ev, _tools);
              }
            };
          })(this),
          items: flyouts,
          "class": "ez5-toolbox-menu"
        }
      }, CUI.util.copyObject(btn_opts, true));
      buttons.push(opts);
    }
    this.__group++;
    return buttons;
  };

  Toolbox.getFlyoutButtonbar = function(tools, btn_opts) {
    if (btn_opts == null) {
      btn_opts = {};
    }
    return new CUI.Buttonbar({
      buttons: this.getFlyoutButtons(tools, btn_opts)
    });
  };

  Toolbox.mergeFlyoutButtons = function() {
    var _last_btn, btn, btns, i, idx, items, j, k, last_btn, last_btns, len, len1, len2, source_btn, source_btns, sources;
    sources = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    btns = [];
    last_btns = sources.pop();
    last_btn = last_btns[last_btns.length - 1];
    if (!last_btn) {
      return btns;
    }
    items = last_btn.menu.items;
    items.splice(0, 0, {
      label: last_btn.menu.items[0]._tool.getGroupText()
    });
    for (i = 0, len = sources.length; i < len; i++) {
      source_btns = sources[i];
      if (!((source_btns != null ? source_btns.length : void 0) > 0)) {
        continue;
      }
      _last_btn = source_btns.pop();
      for (j = 0, len1 = source_btns.length; j < len1; j++) {
        source_btn = source_btns[j];
        btns.push(source_btn);
      }
      items.push({
        label: _last_btn.menu.items[0]._tool.getGroupText()
      });
      items.push.apply(items, _last_btn.menu.items);
    }
    for (idx = k = 0, len2 = last_btns.length; k < len2; idx = ++k) {
      btn = last_btns[idx];
      btns.push(btn);
    }
    return btns;
  };

  return Toolbox;

})(CUI.Element);

CUI.ready(function() {
  CUI.Events.registerEvent({
    type: "toolbox",
    bubble: true
  });
  CUI.Events.registerEvent({
    type: "toolbox-sink",
    sink: true,
    bubble: false,
    exclude_self: true
  });
  return CUI.Events.registerEvent({
    type: "toolbox-before-show",
    bubble: false,
    sink: false
  });
});

ez5.session_ready(function() {
  var tb;
  tb = new Toolbox();
  CUI.Events.listen({
    type: "contextmenu",
    node: document,
    call: function(ev) {
      var info, target, tools;
      if (ev.ctrlKey()) {
        return;
      }
      ev.preventDefault();
      tools = [];
      target = CUI.dom.closest(ev.getTarget(), "a");
      if (target != null ? target.href : void 0) {
        tools.push(new ToolboxTool({
          group: "commons",
          name: "copy.commons",
          sort: "Z:1",
          loca_key: "tool.href.copy",
          run: (function(_this) {
            return function() {
              return CUI.util.copyToClipboard(target.href);
            };
          })(this)
        }));
      }
      info = {
        tools: tools
      };
      CUI.Events.trigger({
        type: 'toolbox',
        node: ev.getTarget(),
        info: info
      }).done((function(_this) {
        return function() {
          return CUI.Events.trigger({
            type: "toolbox-before-show",
            info: info
          }).done(function() {
            return tb.showContextMenu(ev, tools);
          });
        };
      })(this));
    }
  });
  CUI.Events.listen({
    type: "mousedown",
    call: (function(_this) {
      return function(ev) {
        var node;
        node = CUI.dom.closest(ev.getTarget(), "[tabindex]");
        if (!node) {
          return;
        }
        if (node.hasAttribute("tabindex-prevent-default")) {
          ev.preventDefault();
        }
      };
    })(this)
  });
});
// Generated by CoffeeScript 1.12.7
var ToolboxTool,
  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;

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

  function ToolboxTool() {
    this.setToolbox = bind(this.setToolbox, this);
    return ToolboxTool.__super__.constructor.apply(this, arguments);
  }

  ToolboxTool.prototype.initOpts = function() {
    ToolboxTool.__super__.initOpts.call(this);
    return this.addOpts({
      text: {
        check: String
      },
      group: {
        check: String
      },
      sort: {
        check: String
      },
      tools: {
        check: Array
      },
      label: {
        check: String
      },
      label_attrs: {},
      loca_key: {
        check: String
      },
      loca_key_attrs: {},
      hidden: {
        "default": false,
        check: function(v) {
          return CUI.util.isBoolean(v) || CUI.util.isFunction(v);
        }
      },
      disabled: {
        "default": false,
        check: function(v) {
          return CUI.util.isBoolean(v) || CUI.util.isFunction(v);
        }
      },
      loading: {
        "default": false,
        check: function(v) {
          return CUI.util.isBoolean(v) || CUI.util.isFunction(v);
        }
      },
      active: {
        check: Boolean
      },
      favorite: {
        "default": false,
        check: function(v) {
          return v === false || v === true || CUI.util.isPlainObject(v);
        }
      },
      left: {},
      center: {},
      name: {
        mandatory: true,
        check: String
      },
      run: {
        mandatory: true,
        "default": function() {},
        check: Function
      },
      icon: {
        check: function(v) {
          return CUI.util.isString(v) || v instanceof CUI.Icon;
        }
      },
      onFlyoutMenuShow: {
        check: Function
      }
    });
  };

  ToolboxTool.prototype.readOpts = function() {
    var number, parts;
    ToolboxTool.__super__.readOpts.call(this);
    if (CUI.util.isString(this._icon)) {
      this.__icon = new CUI.Icon({
        icon: this._icon
      });
    } else {
      this.__icon = this._icon;
    }
    this.__disabled = false;
    this.__hidden = false;
    if (this._hidden && (this._hidden === true || this._hidden.call(this, this))) {
      this.setHidden(true);
    }
    if (this._disabled && (this._disabled === true || this._disabled.call(this, this))) {
      this.disable();
    }
    this.__loading = this._loading;
    if (this._sort) {
      parts = this._sort.split(":");
      number = parseInt(parts[1]);
      CUI.util.assert(parts.length === 2 && parts[0].length === 1 && number < 100 && number > 0, "new ToolboxTool", "opts.sort needs to be of format: A:<1-99>", {
        opts: this.opts
      });
      this.__sort_group = parts[0];
      this.__sort_string = parts[0] + "_" + String.fromCharCode(65 + number);
    } else {
      this.__sort_group = "z";
      this.__sort_string = "z_z";
    }
    this.__group_text = $$("toolbox.class." + this.getGroup());
    return this;
  };

  ToolboxTool.prototype.getTools = function() {
    return this._tools;
  };

  ToolboxTool.prototype.getSortGroup = function() {
    return this.__sort_group;
  };

  ToolboxTool.prototype.getGroup = function() {
    return this._group;
  };

  ToolboxTool.prototype.getGroupText = function() {
    return this.__group_text;
  };

  ToolboxTool.prototype.setToolbox = function(toolbox1) {
    var i, len, ref, results, t;
    this.toolbox = toolbox1;
    if (this._tools) {
      ref = this._tools;
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        t = ref[i];
        results.push(typeof t.setToolbox === "function" ? t.setToolbox(this.toolbox) : void 0);
      }
      return results;
    }
  };

  ToolboxTool.prototype.getSort = function() {
    return this._sort;
  };

  ToolboxTool.prototype.getName = function() {
    return this._name;
  };

  ToolboxTool.prototype.getIcon = function() {
    var key;
    if (this.__icon) {
      return this.__icon.copy();
    } else {
      key = this.__getCsvKey() + "|icon";
      if (ez5.loca.has(key)) {
        return $$(key);
      } else {
        return null;
      }
    }
  };

  ToolboxTool.prototype.getText = function() {
    var keys;
    keys = this.getLabelKeys();
    if (keys.text) {
      return keys.text;
    } else {
      return $$(keys.loca_key + "|text", keys.loca_key_attrs);
    }
  };

  ToolboxTool.prototype.getLabelKeys = function() {
    var key;
    key = this.__getCsvKey();
    if (!CUI.util.isEmpty(this._text)) {
      return {
        text: this._text
      };
    } else if (this._label) {
      return {
        text: $$(key, this._label_attrs)
      };
    } else if (ez5.loca.has(key + "|text")) {
      return {
        loca_key: key,
        loca_key_attrs: this._loca_key_attrs,
        _sort_text: $$(key + "|text")
      };
    } else {
      return {
        text: $$(key, this._loca_key_attrs)
      };
    }
  };

  ToolboxTool.prototype.__getCsvKey = function() {
    if (this._loca_key) {
      return this._loca_key;
    } else if (this._label) {
      return "tool." + this._label;
    } else {
      return "tool." + this._name;
    }
  };

  ToolboxTool.prototype.toString = function() {
    return "ToolboxTool." + this._name;
  };

  ToolboxTool.prototype.run = function() {
    return this._run.apply(this, arguments);
  };

  ToolboxTool.prototype.getAsFavoriteButton = function(btn_opts) {
    var button_class, key, menuButton, nameSplit;
    if (btn_opts == null) {
      btn_opts = {};
    }
    if (!this._favorite) {
      return;
    }
    if (CUI.util.isPlainObject(this._favorite)) {
      CUI.util.mergeMap(btn_opts, this._favorite);
    }
    CUI.util.mergeMap(btn_opts, this.getMenuItem());
    key = this.__getCsvKey();
    if (ez5.loca.has(key + "|favorite")) {
      btn_opts.text = $$(key + "|favorite", btn_opts.loca_key_attrs);
    }
    btn_opts.icon = this.getIcon();
    if (!btn_opts.ui) {
      nameSplit = this._name.split(".").join("_");
      btn_opts.ui = "toolbox.tool.button:" + nameSplit;
    }
    if (ez5.loca.has(key + "|tooltip")) {
      btn_opts.tooltip = {
        text: $$(key + "|tooltip")
      };
    }
    if (ez5.loca.has(key + "|favorite_tooltip")) {
      btn_opts.tooltip = {
        text: $$(key + "|favorite_tooltip")
      };
    }
    btn_opts.loca_key = null;
    if (this._tools) {
      btn_opts.menu_on_hover = false;
    }
    nameSplit = this._name.split(".").join("_");
    button_class = "toolbox_tool.button:" + nameSplit;
    if (btn_opts["class"]) {
      btn_opts["class"] += " " + button_class;
    } else {
      btn_opts["class"] = button_class;
    }
    if (!(btn_opts.icon || ez5.loca.has(btn_opts.loca_key + "|icon"))) {
      btn_opts.icon = "fa-question";
    }
    menuButton = this.__button;
    this.__favButton = new CUI.defaults["class"].Button(btn_opts);
    this.__button = menuButton;
    return this.__favButton;
  };

  ToolboxTool.prototype.enable = function() {
    return this.setDisabled(false);
  };

  ToolboxTool.prototype.disable = function() {
    return this.setDisabled(true);
  };

  ToolboxTool.prototype.setDisabled = function(__disabled) {
    var ref, ref1, ref2, ref3;
    this.__disabled = __disabled;
    if (this.__disabled) {
      if ((ref = this.__button) != null) {
        ref.disable();
      }
      if ((ref1 = this.__favButton) != null) {
        ref1.disable();
      }
    } else {
      if ((ref2 = this.__button) != null) {
        ref2.enable();
      }
      if ((ref3 = this.__favButton) != null) {
        ref3.enable();
      }
    }
    return this;
  };

  ToolboxTool.prototype.setLoading = function(__loading) {
    var ref, ref1;
    this.__loading = __loading;
    if ((ref = this.__button) != null) {
      ref.setLoading(this.__loading);
    }
    if ((ref1 = this.__favButton) != null) {
      ref1.setLoading(this.__loading);
    }
    return this;
  };

  ToolboxTool.prototype.isDisabled = function() {
    return this.__disabled;
  };

  ToolboxTool.prototype.setHidden = function(__hidden) {
    var ref, ref1, ref2, ref3, ref4;
    this.__hidden = __hidden;
    if (this.__hidden) {
      if ((ref = this.__button) != null) {
        ref.hide();
      }
      if ((ref1 = this.__favButton) != null) {
        ref1.hide();
      }
    } else {
      if ((ref2 = this.__button) != null) {
        ref2.show();
      }
      if ((ref3 = this.__favButton) != null) {
        ref3.show();
      }
    }
    if ((ref4 = this.__button) != null ? ref4.DOM : void 0) {
      CUI.Events.trigger({
        type: "content-resize",
        node: this.__button.DOM
      });
    }
    return this;
  };

  ToolboxTool.prototype.isHidden = function() {
    if (CUI.util.isFunction(this._hidden)) {
      return this._hidden.call(this, this);
    }
    return this.__hidden;
  };

  ToolboxTool.prototype.destroy = function() {};

  ToolboxTool.prototype.getButton = function() {
    return this.__button;
  };

  ToolboxTool.prototype.onFlyoutMenuShow = function(ev, tools) {
    return typeof this._onFlyoutMenuShow === "function" ? this._onFlyoutMenuShow(ev, tools) : void 0;
  };

  ToolboxTool.prototype.getMenuItem = function(toolbox) {
    var item, nameSplit;
    nameSplit = this._name.split(".").join("_");
    item = {
      ui: "toolbox.tool.button:" + nameSplit,
      _tool: this,
      hidden: (function(_this) {
        return function() {
          return _this.isHidden();
        };
      })(this),
      onConstruct: (function(_this) {
        return function(element) {
          return _this.__button = element;
        };
      })(this),
      onDestroy: (function(_this) {
        return function() {
          var ref;
          if ((ref = _this.__button) != null) {
            ref.destroy();
          }
          return delete _this.__button;
        };
      })(this),
      disabled: (function(_this) {
        return function() {
          if (CUI.util.isFunction(_this._disabled)) {
            return _this._disabled.call(_this, _this);
          } else {
            return _this.__disabled;
          }
        };
      })(this),
      loading: (function(_this) {
        return function() {
          return _this.__loading;
        };
      })(this),
      active: this._active,
      onClick: (function(_this) {
        return function(ev, btn) {
          return _this.run(ev, btn);
        };
      })(this)
    };
    if (this._left) {
      item.left = this._left;
    } else if (this.__icon) {
      item.icon = this.__icon.copy();
    }
    if (this._center) {
      item.center = this._center;
    } else {
      CUI.util.mergeMap(item, this.getLabelKeys());
    }
    if (!this._text && !this._loca_key && !ez5.loca.has("tool." + this._name + "|text")) {
      console.error("new ToolboxTool \"" + this._name + "\" needs loca_key or \"tool." + this._name + "|text\" in CSV.");
    }
    if (this._tools) {
      item.menu_on_hover = true;
      item.menu = {
        items: (function(_this) {
          return function() {
            var i, idx, items, len, mi, ref, t;
            items = [];
            ref = _this._tools;
            for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
              t = ref[idx];
              if (!t) {
                continue;
              }
              if (t instanceof ToolboxTool) {
                mi = t.getMenuItem(toolbox);
                items.push(mi);
              } else {
                items.push(t);
              }
            }
            return items;
          };
        })(this)
      };
    }
    return item;
  };

  ToolboxTool.sortTools = function(tools) {
    tools.sort(function(a, b) {
      return CUI.util.compareIndex(a.__sort_string, b.__sort_string);
    });
    return tools;
  };

  return ToolboxTool;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var ToolboxToolButton,
  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;

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

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

  ToolboxToolButton.prototype.initOpts = function() {
    ToolboxToolButton.__super__.initOpts.call(this);
    this.mergeOpts({
      name: {
        mandatory: false
      }
    });
    return this.addOpts({
      button: {
        mandatory: true,
        check: function(v) {
          return v instanceof CUI.Button || CUI.util.isPlainObject(v);
        }
      },
      favorite: {
        check: function(v) {
          return v instanceof CUI.Button || CUI.util.isPlainObject(v);
        }
      }
    });
  };

  ToolboxToolButton.prototype.readOpts = function() {
    ToolboxToolButton.__super__.readOpts.call(this);
    if (this._button instanceof CUI.Button) {
      this.__button = this._button;
    } else {
      this.__button = new CUI.defaults["class"].Button(this._button);
    }
    if (this._favorite) {
      if (this._favorite instanceof CUI.Button) {
        return this.__favorite = this._favorite;
      } else {
        return this.__favorite = new CUI.defaults["class"].Button(this._favorite);
      }
    } else {
      return this.__favorite = null;
    }
  };

  ToolboxToolButton.prototype.getMenuItem = function() {
    return this.__button;
  };

  ToolboxToolButton.prototype.getAsFavoriteButton = function(opts) {
    var k, v;
    if (opts == null) {
      opts = {};
    }
    if (!this.__favorite) {
      return;
    }
    for (k in opts) {
      v = opts[k];
      switch (k) {
        case "group":
          this.__favorite.setGroup(v);
          break;
        case "size":
          this.__favorite.setSize(v);
          break;
        default:
          CUI.util.assert(false, "ToolboxToolButton.getAsFavoriteButton", "opts." + k + " not supported.", {
            opts: opts,
            toolboxToolButton: this
          });
      }
    }
    return this.__favorite;
  };

  return ToolboxToolButton;

})(ToolboxTool);
// Generated by CoffeeScript 1.12.7
var Mask,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function Mask(version1, _id, schema, nestedTableField) {
    var col_obj, column_schema, f, field_schema, i, idx, j, len1, len2, ref, ref1, ref2, ref3, type, type_map;
    this.version = version1;
    this._id = _id;
    this.schema = schema;
    this.nestedTableField = nestedTableField;
    this.getMaskPath = bind(this.getMaskPath, this);
    CUI.util.assert(this._id || this.schema, "new " + (CUI.util.getObjectClass(this)), "schema or id must be set", {
      version: this.version,
      id: this._id,
      schema: this.schema,
      nestedTableField: this.nestedTableField
    });
    if (this._id) {
      this.schema = ez5.mask[this.version]._mask_by_id[this._id];
    } else {
      CUI.util.assert(!this.schema.__version || this.schema.__version === this.version, "new Mask", "schema.__version mismatch.");
      this._id = this.schema.mask_id;
    }
    CUI.util.assert(!this.nestedTableField || this.nestedTableField instanceof NestedTable, "new Mask", "nestedTableField needs to be instanceof NestedTable", {
      version: this.version,
      id: this._id,
      schema: this.schema,
      nestedTableField: this.nestedTableField
    });
    this.table = new Table(this.version, this.schema.table_id);
    type_map = {
      text_oneline: TextColumn,
      text: TextMultiColumn,
      text_l10n_oneline: LocaTextColumn,
      text_l10n: LocaTextMultiColumn,
      string: StringColumn,
      date: DateColumn,
      daterange: DateRangeColumn,
      datetime: DateTimeColumn,
      number: NumberColumn,
      "integer.2": [DecimalColumn, 2, true],
      double: DoubleColumn,
      eas: EASColumn,
      boolean: BooleanColumn,
      link: LinkColumn,
      geo_json: GeoJsonColumn,
      text_1: TextColumn,
      text_multi: TextMultiColumn,
      l10ntext: LocaTextColumn,
      "decimal.2": [DecimalColumn, 2, false]
    };
    if (this.nestedTableField) {
      this.depth = this.nestedTableField.depth() + 1;
    } else {
      this.depth = 0;
    }
    this.fields = [];
    if (this.nestedTableField) {
      if (this.nestedTableField.supportsNestedUUID()) {
        this.fields.push(new NestedUUID(this));
      }
    }
    if (!this.nestedTableField) {
      this.fields.push(new SystemObjectIdColumn(this));
      this.fields.push(new UuidColumn(this));
      if (ez5.version("6")) {
        this.fields.push(new FormatColumn(this));
      }
    }
    if (this.table.poolLink()) {
      this.fields.push(new PoolField(this));
    }
    if (!this.nestedTableField) {
      this.fields.push(new ObjecttypeField(this));
      this.fields.push(new MaskField(this));
      this.fields.push(new GlobalObjectIdColumn(this));
      this.fields.push(new PrimaryKeyColumn(this));
      this.fields.push(new CreatedColumn(this));
      this.fields.push(new LastModifiedColumn(this));
      this.fields.push(new VersionColumn(this));
      this.fields.push(new StandardField(this));
      this.fields.push(new ChangelogColumn(this));
    }
    if (this.nestedTableField instanceof ReverseLinkedTable) {
      this.fields.push(new PrimaryKeyColumn(this));
      this.fields.push(new GlobalObjectIdColumn(this));
      this.fields.push(new SystemObjectIdColumn(this));
      this.fields.push(new VersionColumn(this));
      if (this.hasTags()) {
        this.fields.push(new TagsField(this));
      }
      if (ez5.version("6")) {
        this.fields.push(new SystemTagsField(this));
      }
    }
    if (!this.nestedTableField) {
      this.fields.push(new OwnerField(this));
      this.fields.push(new PublishColumn(this));
      if (this.aclTable()) {
        this.fields.push(new AclField(this));
      }
      if (this.hasTags()) {
        this.fields.push(new TagsField(this));
      }
      if (ez5.version("6")) {
        this.fields.push(new SystemTagsField(this));
      }
      if (this.inMainSearch()) {
        this.fields.push(new CollectionsField(this));
      }
    }
    if (!this.nestedTableField && this.table.isHierarchy()) {
      this.fields.push(new TreeColumn(this));
      if (ez5.version("6")) {
        this.fields.push(new ChildNumberingColumn(this));
      }
      if (ez5.version("6")) {
        this.fields.push(new SystemObjectIdParentColumn(this));
      }
      this.fields.push(new HasChildrenColumn(this));
      this.fields.push(new ParentChildIdxColumn(this));
      this.fields.push(new PathColumn(this));
    }
    if (ez5.version("6") && !this.nestedTableField && this.isPolyhierarchy()) {
      this.fields.push(new ez5.ParentsNestedTable(this));
      this.fields.push(new PathsColumn(this));
      this.fields.push(new HasChildrenColumn(this));
    }
    ref = this.schema.fields;
    for (idx = i = 0, len1 = ref.length; i < len1; idx = ++i) {
      field_schema = ref[idx];
      switch (field_schema.kind) {
        case "field":
          column_schema = this.table.schema._column_by_id[field_schema.column_id];
          col_obj = type_map[column_schema.type];
          if (!col_obj) {
            col_obj = (ref1 = CustomDataType.get(column_schema.type)) != null ? ref1.getClassFunction() : void 0;
          }
          if (col_obj === CustomDataTypeUnknown) {
            if (ref2 = column_schema.type, indexOf.call(Mask.warnTypes, ref2) < 0) {
              console.error("Unsuported Column Type in Mask: \"" + this.schema.name + "\": Column \"" + column_schema.name + "\" has column type: \"" + column_schema.type + "\".", this.schema, column_schema);
              Mask.warnTypes.push(column_schema.type);
            }
          }
          if (CUI.util.isArray(col_obj)) {
            f = new col_obj[0](this, field_schema, col_obj[1], col_obj[2]);
          } else {
            f = new col_obj(this, field_schema);
          }
          break;
        case "link":
          f = new LinkedObject(this, field_schema);
          break;
        case "linked-table":
          f = new NestedTable(this, field_schema);
          break;
        case "reverse-linked-table":
          f = new ReverseLinkedTable(this, field_schema);
          break;
        case "splitter":
          f = MaskSplitter.getFromField({
            l10n_prefix: (function(_this) {
              return function() {
                var fatherMask, idTable, name, ref3;
                fatherMask = (ref3 = _this.nestedTableField) != null ? ref3.fatherMask : void 0;
                if (fatherMask && fatherMask.table && fatherMask.name()) {
                  idTable = _this.nestedTableField.fatherMask.table.id();
                  name = fatherMask.name();
                } else {
                  idTable = _this.table.id();
                  name = _this.name();
                }
                return "mask." + idTable + "." + name + ".";
              };
            })(this),
            version: this.version,
            field: field_schema
          });
          if (f instanceof MaskSplitterUnknown) {
            type = f.opts.field.type;
            if (!MaskSplitterUnknown["errorShown_" + type]) {
              MaskSplitterUnknown["errorShown_" + type] = true;
              CUI.alert({
                text: "The mask: **" + (this.nameLocalized()) + " (" + (this.name()) + ")** of the Object type: **" + (this.table.nameLocalized()) + " (" + (this.table.name()) + ")** has an unknown Mask Splitter type: **" + f.opts.field.type + "**.",
                markdown: true
              });
            }
          }
          break;
        default:
          CUI.util.assert(false, "new Mask", "field.kind \"" + field_schema.kind + "\" unknown", {
            field: field_schema
          });
      }
      this.fields.push(f);
    }
    ref3 = this.fields;
    for (idx = j = 0, len2 = ref3.length; j < len2; idx = ++j) {
      f = ref3[idx];
      if (this.depth === 0) {
        f.init();
      }
      f.idx = idx;
    }
    this.__dbg_name = this.name();
    this.__dbg_table_name = this.table.name();
  }

  Mask.prototype.copy = function() {
    return new Mask(this.version, this._id, this.schema, this.nestedTableField);
  };

  Mask.prototype.getVersion = function() {
    return this.version;
  };

  Mask.prototype.getMaskPath = function(path) {
    if (path == null) {
      path = [];
    }
    path.push(this);
    if (this.nestedTableField) {
      this.nestedTableField.fatherMask.getMaskPath(path);
    }
    return path;
  };

  Mask.prototype.getFields = function(mode, opts) {
    var f, fields, i, len1, ref;
    if (mode == null) {
      mode = this.mode();
    }
    if (opts == null) {
      opts = {};
    }
    fields = [];
    ref = this.fields;
    for (i = 0, len1 = ref.length; i < len1; i++) {
      f = ref[i];
      if (mode === "all" || f.isVisible(mode, opts)) {
        fields.push(f);
      }
    }
    return fields;
  };

  Mask.prototype.getHiddenFields = function(mode, opts) {
    var f, fields, i, len1, ref;
    if (mode == null) {
      mode = this.mode();
    }
    if (opts == null) {
      opts = {};
    }
    fields = [];
    ref = this.fields;
    for (i = 0, len1 = ref.length; i < len1; i++) {
      f = ref[i];
      if (!f.isVisible(mode, opts)) {
        fields.push(f);
      }
    }
    return fields;
  };

  Mask.prototype.getHierarchyField = function() {
    var f, i, len1, ref;
    ref = this.fields;
    for (i = 0, len1 = ref.length; i < len1; i++) {
      f = ref[i];
      if (f instanceof TreeColumn) {
        return f;
      }
    }
    return null;
  };

  Mask.prototype.getPoolField = function() {
    var f, i, len1, ref;
    ref = this.fields;
    for (i = 0, len1 = ref.length; i < len1; i++) {
      f = ref[i];
      if (f instanceof PoolField) {
        return f;
      }
    }
    return null;
  };

  Mask.prototype.getTable = function() {
    return this.table;
  };

  Mask.prototype.inMainSearch = function() {
    return this.table.inMainSearch();
  };

  Mask.prototype.hasTags = function() {
    return this.table.hasTags();
  };

  Mask.prototype.poolLink = function() {
    return this.table.poolLink();
  };

  Mask.prototype.aclTable = function() {
    return this.table.aclTable();
  };

  Mask.prototype.isHierarchy = function() {
    return this.table.isHierarchy();
  };

  Mask.prototype.isPolyhierarchy = function() {
    return this.table.isPolyhierarchy();
  };

  Mask.prototype.id = function() {
    return this._id;
  };

  Mask.prototype.isAllFieldsMask = function() {
    if (this.schema._is_all_fields) {
      return true;
    } else {
      return false;
    }
  };

  Mask.prototype.hideInEditor = function() {
    return !!this.schema.hide_in_editor;
  };

  Mask.prototype.hideInDetail = function() {
    return !!this.schema.hide_in_detail;
  };

  Mask.prototype.hideInPrintDialog = function() {
    return !!this.schema.hide_in_print_dialog;
  };

  Mask.prototype.hasReverseFields = function() {
    return this.schema.fields.some((function(_this) {
      return function(field) {
        return field.kind === "reverse-linked-table";
      };
    })(this));
  };

  Mask.prototype.getPoolEditMode = function() {
    var ref, ref1, ref2;
    if (!ez5.version("6") || !this.hasReverseFields()) {
      return;
    }
    return ((ref = this.schema.system_fields) != null ? (ref1 = ref.pool) != null ? (ref2 = ref1.edit) != null ? ref2.mode : void 0 : void 0 : void 0) || "reverse_pool_changed_never";
  };

  Mask.prototype.name = function() {
    return this.schema.name;
  };

  Mask.prototype.nameSort = function() {
    if (this.schema.name === "_all_fields") {
      return "ZZZZZ";
    } else {
      return this.nameLocalized();
    }
  };

  Mask.prototype.nameLocalized = function() {
    if (this.table.getInstance()) {
      return this.schema._name_localized + "@" + ez5.connector.displaynameByInstance(this.table.getInstance());
    } else {
      return this.schema._name_localized;
    }
  };

  Mask.prototype.nameLocalizedWithoutInstance = function() {
    return this.schema._name_localized;
  };

  Mask.prototype.requireComment = function() {
    return this.schema.require_comment;
  };

  Mask.prototype.isStandard = function() {
    return this.schema.is_preferred;
  };

  Mask.prototype.getReplacementRecord = function(data, key_prefix, use_array, record) {
    var f, i, len1, ref;
    if (key_prefix == null) {
      key_prefix = "";
    }
    if (use_array == null) {
      use_array = false;
    }
    if (record == null) {
      record = {};
    }
    ref = this.getFields("all");
    for (i = 0, len1 = ref.length; i < len1; i++) {
      f = ref[i];
      if (f instanceof MaskSplitter) {
        continue;
      }
      if (f.isTopLevelField()) {
        f.getReplacementRecord(data, key_prefix, use_array, record);
      } else {
        f.getReplacementRecord(data[data._objecttype], key_prefix + data._objecttype + ".", use_array, record);
      }
    }
    return record;
  };

  Mask.prototype.invokeOnFields = function(mode, dive_nested, callback, data, depth) {
    var f, i, len1, ref, ret;
    if (dive_nested == null) {
      dive_nested = false;
    }
    if (depth == null) {
      depth = 0;
    }
    if (!mode || !callback) {
      throw "invokeOnFields needs to be called with mode and callback.";
    }
    ref = this.getFields(mode);
    for (i = 0, len1 = ref.length; i < len1; i++) {
      f = ref[i];
      ret = callback(f, data, depth);
      if (dive_nested && ret !== false && f.invokeOnFields) {
        f.invokeOnFields(mode, dive_nested, callback, data, depth);
      }
    }
    return this;
  };

  Mask.prototype.renderEditor = function(top_level_data, mode, header_mode, opts) {
    var _data, f, fields, fields2, footer_mode, hide_other_system_fields, i, k, len1, mainDiv, mainFieldsRenderer, ref, ref1, ref2, ref3, ref4, ref5, ref6, tag_opts, v;
    if (top_level_data._template) {
      top_level_data[this.table.name()]._template = top_level_data._template[this.table.name()];
    }
    fields = [];
    mainFieldsRenderer = new FieldsRendererTopLevel();
    if (mode.startsWith("editor")) {
      ref = this.fields;
      for (i = 0, len1 = ref.length; i < len1; i++) {
        f = ref[i];
        if (f instanceof TagsField) {
          tag_opts = {
            dbInfo: (ref1 = opts.editor) != null ? ref1.editor_data.dbInfo : void 0,
            mode: (ref2 = opts.editor) != null ? ref2.editor_data.mode : void 0,
            demo: top_level_data.__version === "TEMP"
          };
          f.initData(top_level_data, tag_opts);
          break;
        }
      }
    }
    if (header_mode) {
      fields = this.getFields(header_mode, {
        top_level_data: top_level_data,
        history: opts.history,
        bulk: opts.bulk,
        new_mode: opts.new_mode,
        skip_columnfilter: opts.skip_columnfilter,
        hide_tags: opts.hide_tags,
        hide_pool: opts.hide_pool,
        hide_objecttype: opts.hide_objecttype,
        hide_system_object_id: opts.hide_system_object_id,
        isVisible: opts.isVisible
      });
      fields.splice(0, 0, new MaskSplitterHeadInternal());
      fields.push(new MaskSplitterHeadInternalEnd());
    } else {
      fields = [];
    }
    fields.push.apply(fields, this.getFields(mode, {
      top_level_data: top_level_data,
      history: opts.history,
      bulk: opts.bulk,
      new_mode: opts.new_mode,
      for_print: opts.for_print,
      skip_columnfilter: opts.skip_columnfilter,
      hide_tags: opts.hide_tags,
      hide_pool: opts.hide_pool,
      hide_objecttype: opts.hide_objecttype,
      hide_system_object_id: opts.hide_system_object_id,
      hide_hierarchy_path: opts.hideHierarchyPath,
      getLabel: opts.getLabel,
      isVisible: opts.isVisible,
      _path: opts._path,
      sourceType: opts.sourceType
    }));
    if (ez5.version("6") && opts.is_purged) {
      fields = fields.filter(function(field) {
        return !(field instanceof StandardField);
      });
    }
    hide_other_system_fields = false;
    switch (header_mode) {
      case "detail-header":
        footer_mode = "detail-footer";
        hide_other_system_fields = ((ref3 = this.getMaskCustomSettings()) != null ? (ref4 = ref3.system_fields) != null ? ref4.other_fields_output : void 0 : void 0) === "off";
        break;
      case "editor-header":
        footer_mode = "editor-footer";
        hide_other_system_fields = ((ref5 = this.getMaskCustomSettings()) != null ? (ref6 = ref5.system_fields) != null ? ref6.other_fields_edit : void 0 : void 0) === "off";
    }
    if (footer_mode) {
      fields2 = this.getFields(footer_mode, {
        top_level_data: top_level_data,
        history: opts.history,
        bulk: opts.bulk,
        new_mode: opts.new_mode,
        skip_columnfilter: opts.skip_columnfilter,
        hide_tags: opts.hide_tags,
        hide_pool: opts.hide_pool,
        hide_objecttype: opts.hide_objecttype,
        hide_system_object_id: opts.hide_system_object_id,
        isVisible: opts.isVisible,
        hide_other_system_fields: hide_other_system_fields,
        is_purged: opts.is_purged
      });
      if (fields2.length > 0) {
        fields.push(new MaskSplitterFooter());
        fields.push.apply(fields, fields2);
        fields.push(new MaskSplitterFooterEnd());
      }
    }
    if (ez5.version("6") && mode === "detail") {
      CUI.util.removeFromArray(null, fields, (function(_this) {
        return function(field) {
          if (field instanceof MaskSplitter) {
            return false;
          }
          if (field.isInherited() && !field.isInheritanceVisibleInDetail()) {
            return top_level_data[top_level_data._objecttype][field.name() + ":inherited"];
          }
        };
      })(this));
    }
    if (ez5.version("6") && mode === "editor" && top_level_data._format === "long_inheritance" && top_level_data[top_level_data._objecttype]) {
      _data = top_level_data[top_level_data._objecttype];
      for (k in _data) {
        v = _data[k];
        if (_data[k + ":inherited"] && _data[k] !== void 0) {
          _data[k + ":parent"] = _data[k];
          delete _data[k];
        }
      }
    }
    mainFieldsRenderer.read(fields);
    mainDiv = mainFieldsRenderer.render({
      data: top_level_data[this.table.name()],
      top_level_data: top_level_data,
      mode: mode,
      history: opts.history,
      for_print: opts.for_print,
      onDone: opts.onDone,
      onFail: opts.onFail,
      onProgress: opts.onProgress,
      editor: opts.editor,
      bulk: opts.bulk,
      new_mode: opts.new_mode,
      pool_ids: opts.pool_ids,
      detail: opts.detail,
      cols: mode === "editor-bulk" ? ["auto", "auto", "auto"] : ["auto", "maximize"],
      colClasses: mode === "editor-bulk" ? ["ez5-fields-renderer-option", "ez5-fields-renderer-key", "ez5-fields-renderer-value"] : ["ez5-fields-renderer-key", "ez5-fields-renderer-value"],
      maximize_horizontal: true,
      selectable: opts.selectable,
      isVisible: opts.isVisible,
      getLabel: opts.getLabel,
      _path: opts._path,
      inline_mode: opts.inline_mode,
      onFieldRender: opts.onFieldRender
    });
    CUI.Events.listen({
      type: ["editor-changed", "pool-field-changed", "tags-field-changed", "editor-reload-asset-browser", "editor-update-asset-browser"],
      node: mainDiv,
      call: (function(_this) {
        return function(ev, info) {
          if (typeof opts.onChange === "function") {
            opts.onChange(ev, top_level_data, info);
          }
        };
      })(this)
    });
    return mainDiv;
  };

  Mask.prototype.renderDetail = function(data, mode, header_mode, opts) {
    opts.maximize = false;
    opts.selectable = false;
    return this.renderEditor(data, mode, header_mode, opts);
  };

  Mask.prototype.renderText = function(data, mode, header_mode, opts) {
    opts.maximize = false;
    opts.selectable = false;
    return this.renderEditor(data, mode, header_mode, opts);
  };

  Mask.prototype.checkSaveData = function(data, opts) {
    var problems;
    if (opts == null) {
      opts = {};
    }
    opts.check = true;
    problems = this.__getSaveData(data, opts);
    return problems;
  };

  Mask.prototype.getSaveData = function(data, opts) {
    if (opts == null) {
      opts = {};
    }
    return this.__getSaveData(data, opts);
  };

  Mask.prototype.__getSaveData = function(data, opts) {
    var _data, base_fields_only, bulk_fields_count, c, check_failed, check_fields, cv, ex, f, fields, i, j, l, len1, len2, len3, ref, ref1, rf_data, rn, save_data;
    if (opts == null) {
      opts = {};
    }
    CUI.util.assert(CUI.util.isPlainObject(data), "Mask.getSaveData", "data is not a plain object", {
      data: data,
      opts: opts
    });
    save_data = {};
    save_data[this.table.name()] = {};
    save_data._mask = this.name();
    save_data._objecttype = this.table.name();
    save_data[this.table.name()]._top_level = save_data;
    data[this.table.name()]._top_level = data;
    if (data._template) {
      data[this.table.name()]._template = data._template[this.table.name()];
    }
    check_fields = [];
    bulk_fields_count = 0;
    base_fields_only = null;
    fields = this.getFields('all', opts);
    opts.top_level_data = data;
    fields.sort(function(a, b) {
      if (a instanceof TagsField) {
        return 1;
      } else {
        return 0;
      }
    });
    if (opts.check) {
      opts.problems = [];
    }
    for (i = 0, len1 = fields.length; i < len1; i++) {
      f = fields[i];
      if (f instanceof MaskSplitter) {
        continue;
      }
      if (opts.bulk && !f.getOption(data[this.table.name()], "bulk")) {
        continue;
      }
      if (opts.skipFields && (ref = f.fullName(), indexOf.call(opts.skipFields, ref) >= 0)) {
        continue;
      }
      bulk_fields_count += 1;
      if (!(f instanceof PoolField || f instanceof TagsField)) {
        base_fields_only = false;
      }
      if (f.isReadOnly(data[this.table.name()], data, {
        mode: "editor",
        get_save_data: true
      })) {
        continue;
      }
      if (opts.copy_for_template && !f.hasUserData(data[this.table.name()], data, opts)) {
        continue;
      }
      if (opts.render_mode && !f.isVisibleToSaveData(opts.render_mode, opts.render_mode_header, {
        top_level_data: data,
        get_save_data: true
      })) {
        continue;
      }
      if (!opts.check) {
        if (opts.init_save_data && ez5.version("6") && ((ref1 = data[this.table.name()]) != null ? ref1[f.name() + ":inherited"] : void 0)) {
          f.getSaveData({}, save_data[this.table.name()], opts);
          continue;
        }
        f.getSaveData(data[this.table.name()], save_data[this.table.name()], opts);
        continue;
      }
      try {
        f.getSaveData(data[this.table.name()], save_data[this.table.name()], opts);
        check_failed = false;
      } catch (error) {
        ex = error;
        if (ex instanceof InvalidSaveDataException) {
          check_failed = ex;
        } else {
          throw ex;
        }
      }
      rf_data = f.getDataForFieldData(data[this.table.name()], data);
      rn = f.name() + ':rendered';
      if (rf_data === data) {
        save_data[rn] = rf_data[rn];
        save_data[f.name() + ':options'] = rf_data[f.name() + ':options'];
      } else {
        save_data[this.table.name()][rn] = rf_data[rn];
      }
      save_data[this.table.name()][f.name() + ':options'] = data[this.table.name()][f.name() + ':options'];
      if (check_failed) {
        opts.problems.push(new CheckDataProblem({
          field: f,
          text: "**" + f.fullNameLocalized() + "**: " + check_failed.getError(),
          renderedField: rf_data[rn]
        }));
      }
      check_fields.push(f);
    }
    if (bulk_fields_count > 0 && base_fields_only === null) {
      base_fields_only = true;
    }
    opts.base_fields_only = base_fields_only;
    delete save_data[this.table.name()]._top_level;
    delete data[this.table.name()]._top_level;
    if (opts.check) {
      _data = save_data[this.table.name()];
      for (j = 0, len2 = check_fields.length; j < len2; j++) {
        f = check_fields[j];
        rf_data = f.getDataForFieldData(_data, save_data);
        rn = f.name() + ':rendered';
        cv = f.checkValue(_data, save_data, opts);
        if (cv !== true) {
          if (CUI.util.isArray(cv)) {
            for (l = 0, len3 = cv.length; l < len3; l++) {
              c = cv[l];
              if (c !== true) {
                opts.problems.push(new CheckDataProblem({
                  field: f,
                  text: c || void 0,
                  renderedField: rf_data[rn]
                }));
              }
            }
          } else {
            opts.problems.push(new CheckDataProblem({
              field: f,
              text: cv || void 0,
              renderedField: rf_data[rn]
            }));
          }
        }
      }
      return opts.problems;
    }
    return save_data;
  };

  Mask.prototype.renderStandard = function(data) {
    var callback, standard;
    standard = [];
    callback = (function(_this) {
      return function(f, data, depth) {
        var i, len1, results, row;
        if (depth > 0) {
          if (data !== void 0) {
            CUI.util.assert(CUI.util.isArray(data, "Mask.renderStandard", "Depth > 0 and data is not an Array", {
              data: data,
              depth: depth
            }));
            results = [];
            for (i = 0, len1 = data.length; i < len1; i++) {
              row = data[i];
              results.push(f.renderStandard(standard, row));
            }
            return results;
          }
        } else {
          return f.renderStandard(standard, data);
        }
      };
    })(this);
    this.invokeOnFields("all", true, callback, data[this.table.name()]);
    return standard;
  };

  Mask.prototype.getEASFields = function(mode) {
    return this.getFieldsByType(mode, EASColumn);
  };

  Mask.prototype.getReverseLinkedTableFields = function(mode) {
    return this.getFieldsByType(mode, ReverseLinkedTable);
  };

  Mask.prototype.getTagsField = function(mode) {
    return this.getFieldsByType(mode, TagsField, false)[0];
  };

  Mask.prototype.getFieldsByType = function(mode, type, dive_nested) {
    var fields;
    if (dive_nested == null) {
      dive_nested = true;
    }
    CUI.util.assert(mode && type, "Mask.getFieldsByType", "mode, type must be set", {
      mode: mode,
      type: type
    });
    fields = [];
    this.invokeOnFields(mode, dive_nested, (function(_this) {
      return function(f) {
        if (f instanceof type) {
          return fields.push(f);
        }
      };
    })(this));
    return fields;
  };

  Mask.prototype.hasStandardEASFields = function() {
    var has;
    has = false;
    this.invokeOnFields("all", true, ((function(_this) {
      return function(f) {
        if ((f instanceof EASColumn || f instanceof LinkedObject) && f.getOutputStandardEAS()) {
          has = true;
        }
      };
    })(this)));
    return has;
  };

  Mask.prototype.getStandardTextFields = function(filterOrder) {
    var f, fields, i, len1, ref, ref1, standard;
    if (filterOrder == null) {
      filterOrder = null;
    }
    fields = [];
    ref = this.getFields("all");
    for (i = 0, len1 = ref.length; i < len1; i++) {
      f = ref[i];
      if (!(f instanceof TextColumn)) {
        continue;
      }
      standard = f.getOutputStandard();
      if (!standard) {
        continue;
      }
      if (!filterOrder || (ref1 = standard.order, indexOf.call(filterOrder, ref1) >= 0)) {
        fields.push({
          standard: standard,
          field: f
        });
      }
    }
    return fields;
  };

  Mask.prototype.isPluginSupported = function(plugin, mode) {
    var isSupported;
    isSupported = false;
    this.invokeOnFields(mode, true, ((function(_this) {
      return function(field) {
        if (!isSupported && field instanceof Field && field.isPluginSupported(plugin, mode)) {
          return isSupported = true;
        }
      };
    })(this)));
    return isSupported;
  };

  Mask.prototype.getAssetsForBrowser = function(_data, _mode) {
    var append_asset, asset_browser_idx, browse_assets, eas_data, eas_fields, ef, i, idx, j, len1, len2, row;
    eas_fields = [];
    this.invokeOnFields(_mode, true, ((function(_this) {
      return function(f, data) {
        if (f instanceof EASColumn || (f instanceof LinkedObject && f.getOutputStandardEAS())) {
          return eas_fields.push({
            field: f,
            data: data || []
          });
        }
      };
    })(this)), _data[this.table.name()]);
    if (eas_fields.length === 0) {
      return false;
    }
    eas_fields.sort(function(a, b) {
      var a_standard, b_standard, ref, ref1;
      a_standard = ((ref = a.field.getOutputStandardEAS()) != null ? ref.order : void 0) || 4;
      b_standard = ((ref1 = b.field.getOutputStandardEAS()) != null ? ref1.order : void 0) || 4;
      return CUI.util.compareIndex(a_standard, b_standard);
    });
    browse_assets = [];
    asset_browser_idx = 0;
    append_asset = function(field, data, idx, len) {
      var _value, add_value, assetField, eas_column, eas_values, fieldName, forceIdx, i, index, len1, name, nestedFieldName, ref, ref1, ref2, value;
      add_value = (function(_this) {
        return function(field, value) {
          var values;
          if (!value) {
            return;
          }
          value._field = field;
          value._asset_browser_idx = asset_browser_idx++;
          value._idx = idx;
          value._len = len;
          if (field instanceof EASColumn && field._originField) {
            values = data[field._originField.name()];
          } else {
            values = data[field.name()];
          }
          return browse_assets.push(new Asset(field, value, values, _data));
        };
      })(this);
      if (field instanceof LinkedObject) {
        fieldName = field.nameLocalized();
        eas_column = new EASField({
          name: fieldName
        });
        eas_column.FieldSchema = {};
        eas_column._originField = field;
        eas_values = (ref = data[field.name()]) != null ? (ref1 = ref._standard) != null ? (ref2 = ref1.eas) != null ? ref2["1"] : void 0 : void 0 : void 0;
        if (!eas_values || eas_values.length === 0) {
          return;
        }
        if (!len && eas_values.length > 1) {
          len = eas_values.length;
          forceIdx = true;
          idx = 0;
        }
        for (index = i = 0, len1 = eas_values.length; i < len1; index = ++i) {
          _value = eas_values[index];
          value = CUI.util.copyObject(_value);
          if (field.mask.nestedTableField) {
            nestedFieldName = field.mask.nestedTableField.fullNameLocalized();
            if (eas_values.length > 1) {
              name = nestedFieldName + " (" + (idx + 1) + "/" + len + ") / " + field.nameLocalized() + " (" + (index + 1) + "/" + eas_values.length + ")";
            } else {
              name = nestedFieldName + " (" + (idx + 1) + "/" + len + ") / " + field.nameLocalized();
            }
            eas_column = new EASField({
              name: name
            });
            value._hideIdx = true;
            eas_column.FieldSchema = {};
            eas_column._originField = field;
          }
          value._incomplete_versions = true;
          value._linked_object_data = data[field.name()];
          value._linked_object = field;
          add_value(eas_column, value);
          if (forceIdx) {
            idx++;
          }
        }
      } else {
        value = field.getImgValuePreferred(data);
        assetField = field;
        if ((len != null) && (idx != null) && value) {
          fieldName = field.mask.nestedTableField.fullNameLocalized() + " (" + (idx + 1) + "/" + len + ") / " + field.nameLocalized();
          eas_column = new EASField({
            name: fieldName
          });
          eas_column.FieldSchema = {};
          eas_column._originField = field;
          value._hideIdx = true;
          assetField = eas_column;
        }
        add_value(assetField, value);
      }
    };
    for (i = 0, len1 = eas_fields.length; i < len1; i++) {
      ef = eas_fields[i];
      if (ef.field.mask.nestedTableField) {
        eas_data = ef.data;
        for (idx = j = 0, len2 = eas_data.length; j < len2; idx = ++j) {
          row = eas_data[idx];
          append_asset(ef.field, row, idx, eas_data.length);
        }
      } else {
        append_asset(ef.field, ef.data);
      }
    }
    return browse_assets;
  };

  Mask.prototype.getMaskCustomSettings = function() {
    if (ez5.version("6.7")) {
      return this.schema.custom_settings;
    }
    return null;
  };

  Mask.getMaskByMaskName = function(mask_name, table_id, version, all_fields_preferred) {
    var mask, type;
    if (table_id == null) {
      table_id = null;
    }
    if (version == null) {
      version = "CURRENT";
    }
    if (all_fields_preferred == null) {
      all_fields_preferred = true;
    }
    if (CUI.util.isEmpty(mask_name)) {
      return null;
    }
    if (table_id === null && mask_name !== '_all_fields') {
      table_id = ez5.mask[version]._mask_by_name[mask_name].table_id;
    }
    if (mask_name === '_all_fields') {
      CUI.util.assert(CUI.util.isString(mask_name) && CUI.util.isInteger(table_id), "Mask.getMaskByName", "for _all_fields: mask_name must be String and table_id Integer", {
        mask_name: mask_name,
        table_id: table_id
      });
      if (all_fields_preferred) {
        type = 'all_fields_mask_preferred';
      } else {
        type = 'all_fields_mask';
      }
      CUI.util.assert(ez5[type][version], "Mask.getMaskByName", "_all_fields mask not available for version " + version + " and type " + type + ".");
      mask = new Mask(version, null, ez5[type][version]._masks_by_table_id[table_id][0]);
    } else {
      mask = ez5.mask[version]._mask_instance_by_name[mask_name];
    }
    CUI.util.assert(mask instanceof Mask, "Mask.getMaskByMaskName", "mask not found: \"" + mask_name + "\"", {
      table_id: table_id,
      version: version
    });
    return mask;
  };

  Mask.prototype.getTopLevelObjecttypeName = function() {
    var getObjecttypeName;
    getObjecttypeName = function(table) {
      var ownerTable, tableId;
      if (table.owned_by) {
        if (table._instance) {
          tableId = table.owned_by.other_table_id + "@" + table._instance;
        } else {
          tableId = table.owned_by.other_table_id;
        }
        ownerTable = ez5.schema.CURRENT._table_by_id[tableId];
        return getObjecttypeName(ownerTable);
      } else {
        return table.name;
      }
    };
    return getObjecttypeName(this.table.schema);
  };

  Mask.warnTypes = [];

  return Mask;

})(CUI.Dummy);
// Generated by CoffeeScript 1.12.7
var ListViewEditTreeMaskRowNode,
  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;

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

  function ListViewEditTreeMaskRowNode(opts) {
    this.opts = opts != null ? opts : {};
    ListViewEditTreeMaskRowNode.__super__.constructor.call(this, this.opts);
    this.data = this.getData();
  }

  ListViewEditTreeMaskRowNode.prototype.allowRowMove = function(to_node, new_father, after) {
    var c, childIdx, children, err, f, f_idx, fields, fieldsRenderer, i, id_array, id_array_sort, idx, j, len, len1, new_child_idx, ref;
    if (new_father && !this.isEnabledForNested()) {
      return false;
    }
    fields = typeof this.getRowsToMove === "function" ? this.getRowsToMove() : void 0;
    if (new_father && (fields != null ? fields.length : void 0) > 1) {
      return false;
    }
    if (new_father) {
      children = new_father.children.slice(0);
      children.unshift(this);
      childIdx = 0;
    } else {
      children = this.father.children.slice(0);
      childIdx = this.getChildIdx();
    }
    id_array = [];
    for (idx = i = 0, len = children.length; i < len; idx = ++i) {
      c = children[idx];
      id_array[idx] = idx;
    }
    id_array_sort = id_array.slice(0);
    CUI.util.moveInArray(childIdx, to_node.getChildIdx(), children, after);
    CUI.util.moveInArray(childIdx, to_node.getChildIdx(), id_array_sort, after);
    if (fields != null ? fields.length : void 0) {
      ref = fields.reverse();
      for (j = 0, len1 = ref.length; j < len1; j++) {
        f = ref[j];
        f_idx = CUI.util.idxInArray(f, children);
        new_child_idx = CUI.util.idxInArray(this, children);
        CUI.util.moveInArray(f_idx, new_child_idx, children, true);
        CUI.util.moveInArray(f_idx, new_child_idx, id_array_sort, true);
      }
    }
    if (id_array_sort.join(",") === id_array.join(",") && !new_father) {
      return false;
    }
    fieldsRenderer = new FieldsRendererTopLevel();
    try {
      fieldsRenderer.read(children);
      return true;
    } catch (error) {
      err = error;
      console.debug("allowRowMove not allowed", err);
      return false;
    }
  };

  ListViewEditTreeMaskRowNode.prototype.isEnabledForNested = function() {
    return false;
  };

  return ListViewEditTreeMaskRowNode;

})(ListViewEditTreeNode);
// Generated by CoffeeScript 1.12.7
var FieldsRenderer,
  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;

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

  function FieldsRenderer() {
    this.dumpId = bind(this.dumpId, this);
    return FieldsRenderer.__super__.constructor.apply(this, arguments);
  }

  FieldsRenderer.prototype.initOpts = function() {
    FieldsRenderer.__super__.initOpts.call(this);
    return this.addOpts({
      field: {
        check: function(v) {
          return v instanceof Field || v instanceof ListViewEditTreeMaskRowNode || v instanceof MultipleFieldsContainer || v instanceof NestedRow;
        }
      }
    });
  };

  FieldsRenderer.prototype.readOpts = function() {
    FieldsRenderer.__super__.readOpts.call(this);
    return this.fields = [];
  };

  FieldsRenderer.prototype.getField = function() {
    return this._field;
  };

  FieldsRenderer.prototype.addField = function(field) {
    if (!this.isFieldAllowed(field)) {
      throw (CUI.util.getObjectClass(this)) + ".addField: Field of instance " + (CUI.util.getObjectClass(field)) + " is not allowed.";
    }
    if (field instanceof FieldsRenderer) {
      field.setFather(this);
    }
    this.fields.push(field);
    return this;
  };

  FieldsRenderer.prototype.setFather = function(__father) {
    this.__father = __father;
  };

  FieldsRenderer.prototype.getFather = function() {
    return this.__father;
  };

  FieldsRenderer.prototype.addFields = function(fields) {
    var f, j, len;
    for (j = 0, len = fields.length; j < len; j++) {
      f = fields[j];
      this.addField(f);
    }
    return this;
  };

  FieldsRenderer.prototype.beginSplitterType = function() {
    return this.type() + "-begin";
  };

  FieldsRenderer.prototype.endSplitterType = function() {
    return this.type() + "-end";
  };

  FieldsRenderer.prototype.renderFields = function(opts, div) {
    var content, f, j, len, ref;
    ref = this.fields;
    for (j = 0, len = ref.length; j < len; j++) {
      f = ref[j];
      if (f instanceof MaskSplitterEnd) {
        continue;
      }
      content = f.render(opts);
      if (opts != null) {
        if (typeof opts.onFieldRender === "function") {
          opts.onFieldRender(f, content);
        }
      }
      CUI.dom.append(div, content);
    }
    return div;
  };

  FieldsRenderer.prototype.read = function(fields, idx) {
    var base, base1, field, fieldsRenderer, type;
    if ((typeof (base = fields[idx]).splitterType === "function" ? base.splitterType() : void 0) !== this.beginSplitterType()) {
      throw "Cannot read " + (this.beginSplitterType()) + " from field type " + (typeof (base1 = fields[idx]).splitterType === "function" ? base1.splitterType() : void 0);
    }
    idx++;
    while (idx < fields.length) {
      field = fields[idx];
      type = typeof field.splitterType === "function" ? field.splitterType() : void 0;
      if (type) {
        if (type === this.endSplitterType()) {
          this.addField(fields[idx++]);
          break;
        }
        fieldsRenderer = field.getFieldsRenderer({
          field: field
        });
        this.addField(fieldsRenderer);
        idx = fieldsRenderer.read(fields, idx);
      } else {
        this.addField(fields[idx++]);
      }
    }
    return idx;
  };

  FieldsRenderer.prototype.findPlain = function() {
    var check_fields, f, j, k, len, len1, plain, ref;
    ref = this.fields;
    for (j = 0, len = ref.length; j < len; j++) {
      f = ref[j];
      if (f instanceof FieldsRenderer) {
        f.findPlain();
      }
    }
    check_fields = this.fields.splice(0);
    plain = null;
    for (k = 0, len1 = check_fields.length; k < len1; k++) {
      f = check_fields[k];
      if ((f instanceof ListViewEditTreeMaskRowNode || f instanceof Field || f instanceof MultipleFieldsContainer) && !(f instanceof MaskSplitterEnd)) {
        if (!plain) {
          plain = new FieldsRendererPlain();
          this.addField(plain);
        }
        plain.addField(f);
      } else {
        plain = null;
        this.addField(f);
      }
    }
    return this;
  };

  FieldsRenderer.prototype.hasContent = function(opts) {
    var f, has_content, j, len, ref;
    ref = this.fields;
    for (j = 0, len = ref.length; j < len; j++) {
      f = ref[j];
      has_content = typeof f.hasContent === "function" ? f.hasContent(opts) : void 0;
      if (has_content) {
        return true;
      }
    }
    return false;
  };

  FieldsRenderer.prototype.dump = function(lines, depth, fields, skipSelf) {
    var f, i, idx, j, k, len, ref, ref1, ref2, schema, spc;
    if (lines == null) {
      lines = [];
    }
    if (depth == null) {
      depth = 0;
    }
    if (fields == null) {
      fields = this.fields;
    }
    if (skipSelf == null) {
      skipSelf = false;
    }
    spc = "";
    for (i = j = 0, ref = depth; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      spc += "  ";
    }
    if (!skipSelf) {
      lines.push("" + spc + (this.dumpId()));
    }
    for (idx = k = 0, len = fields.length; k < len; idx = ++k) {
      f = fields[idx];
      if (f instanceof FieldsRenderer) {
        f.dump(lines, depth + 1);
      } else if (f instanceof MaskSplitter) {
        lines.push(spc + "  " + (f.splitterType()) + " [" + (CUI.util.getObjectClass(f)) + "]");
      } else if (f instanceof MultipleFieldsContainer) {
        lines.push(spc + "  " + (f.fullName()) + " [" + (CUI.util.getObjectClass(f)) + "]");
      } else {
        if (f instanceof Field) {
          schema = f.FieldSchema;
        } else if (CUI.util.isPlainObject(f) && f.kind) {
          schema = f;
        } else {
          schema = f.opts.data.field;
        }
        if (schema != null ? schema._other_table : void 0) {
          lines.push(spc + "  " + schema._other_table.name + " [" + schema.kind + "]");
          if (((ref1 = schema.mask) != null ? (ref2 = ref1.fields) != null ? ref2.length : void 0 : void 0) > 0) {
            this.dump(lines, ++depth, schema.mask.fields, true);
          }
        } else if (schema != null ? schema._column : void 0) {
          lines.push(spc + "  " + schema._column.name + " [" + schema._column.type + "]");
        } else if ((schema != null ? schema.kind : void 0) === "splitter") {
          lines.push(spc + "  " + schema.type + " [" + schema.options + "]");
        } else {
          lines.push(spc + "  " + (CUI.util.getObjectClass(f)));
        }
      }
    }
    if (depth === 0) {
      return "\n" + lines.join("\n");
    } else {
      return null;
    }
  };

  FieldsRenderer.prototype.needsDirectRender = function(opts) {
    var field, j, len, ref;
    ref = this.fields;
    for (j = 0, len = ref.length; j < len; j++) {
      field = ref[j];
      if (typeof field.needsDirectRender === "function" ? field.needsDirectRender(opts) : void 0) {
        return true;
      }
    }
    return false;
  };

  FieldsRenderer.prototype.dumpId = function() {
    var s;
    s = CUI.util.getObjectClass(this);
    if (this.opts.field instanceof MaskSplitter) {
      s += " [" + (CUI.util.getObjectClass(this.opts.field)) + " / " + (this.opts.field.splitterType()) + "]";
    } else if (this.opts.field) {
      s += " [" + (CUI.util.getObjectClass(this.opts.field)) + "]";
    }
    return s;
  };

  FieldsRenderer.prototype.getAllFields = function(fields, depth) {
    var _f, f, idx, j, len, ref;
    if (fields == null) {
      fields = [];
    }
    if (depth == null) {
      depth = 0;
    }
    ref = this.fields;
    for (idx = j = 0, len = ref.length; j < len; idx = ++j) {
      f = ref[idx];
      if (f instanceof FieldsRenderer) {
        _f = f.getField();
        if (_f && _f !== this.getField()) {
          fields.push(_f);
        }
        f.getAllFields(fields, depth + 1);
      } else {
        fields.push(f);
      }
    }
    return fields;
  };

  FieldsRenderer.prototype.getFields = function() {
    return this.fields;
  };

  FieldsRenderer.prototype.findField = function(field) {
    var f, found, j, len, ref;
    if (this.opts.field === field) {
      return this;
    }
    ref = this.fields;
    for (j = 0, len = ref.length; j < len; j++) {
      f = ref[j];
      if (f === field) {
        return this;
      }
      if (f.findField) {
        found = f.findField(field);
        if (found) {
          return found;
        }
      }
    }
    return null;
  };

  return FieldsRenderer;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var RenderedField,
  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;

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

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

  RenderedField.prototype.initOpts = function() {
    RenderedField.__super__.initOpts.call(this);
    return this.addOpts({
      field: {
        mandatory: true,
        check: Field
      },
      data: {
        mandatory: true,
        check: "PlainObject"
      },
      top_level_data: {
        check: "PlainObject"
      },
      opts: {
        mandatory: true,
        check: "PlainObject"
      }
    });
  };

  RenderedField.prototype.initHasChanges = function() {
    this.__initData = this._field.getDataAsString(this._data, this._top_level_data);
    return this;
  };

  RenderedField.prototype.hasChanges = function() {
    var same;
    same = this._field.getDataAsString(this._data, this._top_level_data) !== this.__initData;
    return same;
  };

  RenderedField.prototype.renderForEditor = function() {
    var el;
    el = this._field.renderForEditor(this._data, this._top_level_data, this._opts);
    if (this.__initData === void 0) {
      this.initHasChanges();
    }
    this.initListener(el);
    return this.setElement((el != null ? el.DOM : void 0) || el);
  };

  RenderedField.prototype.renderForExpert = function() {
    var el;
    el = this._field.renderForExpert(this._data, this._opts);
    return this.setElement((el != null ? el.DOM : void 0) || el);
  };

  RenderedField.prototype.renderForEditorReadOnly = function() {
    var copyOpts, el;
    copyOpts = CUI.util.copyObject(this._opts);
    el = this._field.renderForDetail(this._data, this._top_level_data, copyOpts);
    return this.setElement((el != null ? el.DOM : void 0) || el);
  };

  RenderedField.prototype.setElement = function(__element) {
    this.__element = __element;
    this.setChanges();
    return this.__element;
  };

  RenderedField.prototype.getElement = function() {
    return this.__element;
  };

  RenderedField.prototype.initListener = function(el) {
    return CUI.Events.listen({
      type: ["pool-field-changed", "tags-field-changed", "editor-changed", "editor-update-asset-browser", "editor-reload-asset-browser"],
      node: el,
      call: (function(_this) {
        return function(ev) {
          _this.setChanges();
        };
      })(this)
    });
  };

  RenderedField.prototype.setChanges = function() {
    var changed, ex;
    try {
      changed = this.hasChanges();
    } catch (error) {
      ex = error;
      if (ex instanceof InvalidSaveDataException) {
        changed = true;
      } else {
        throw ex;
      }
    }
    if (changed) {
      this.addClass("data-changed");
    } else {
      this.removeClass("data-changed");
    }
    return this;
  };

  RenderedField.prototype.addClass = function(cls) {
    return CUI.dom.addClass(this.__element, cls);
  };

  RenderedField.prototype.removeClass = function(cls) {
    return CUI.dom.removeClass(this.__element, cls);
  };

  RenderedField.prototype.getField = function() {
    return this._field;
  };

  RenderedField.initField = function(opts) {
    var checkHeaderAndFooterField, rf_data, rn;
    checkHeaderAndFooterField = (function(_this) {
      return function() {
        var ref, ref1, ref2, ref3;
        return ((ref = rf_data[rn].opts) != null ? (ref1 = ref.opts) != null ? ref1.footer_mode : void 0 : void 0) && ((ref2 = rf_data[rn].opts) != null ? (ref3 = ref2.opts) != null ? ref3.header_mode : void 0 : void 0);
      };
    })(this);
    rf_data = opts.field.getDataForFieldData(opts.data, opts.top_level_data);
    rn = opts.field.name() + ":rendered";
    if (!rf_data[rn] || checkHeaderAndFooterField()) {
      rf_data[rn] = new RenderedField(opts);
    } else {
      rf_data[rn]._field = opts.field;
    }
    return rf_data[rn];
  };

  return RenderedField;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var FieldsRendererTopLevel,
  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;

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

  function FieldsRendererTopLevel(opts1) {
    this.opts = opts1 != null ? opts1 : {};
    FieldsRendererTopLevel.__super__.constructor.call(this, this.opts);
    this.div = CUI.dom.div("fields-renderer");
  }

  FieldsRendererTopLevel.prototype.render = function(opts) {
    var content_resize, f, i, len, mode, ref, wait_dfr;
    wait_dfr = new CUI.Deferred();
    CUI.setTimeout({
      ms: 0,
      call: wait_dfr.resolve
    });
    opts.__waits = [wait_dfr.promise()];
    opts.__idx = 0;
    ref = this.fields;
    for (i = 0, len = ref.length; i < len; i++) {
      f = ref[i];
      CUI.dom.append(this.div, f.render(opts));
    }
    switch (opts.mode) {
      case "editor":
      case "editor-template":
      case "editor-bulk":
      case "editor-header":
      case "editor-header-bulk":
      case "expert":
        mode = "input";
        break;
      default:
        mode = "output";
    }
    CUI.dom.addClass(this.div, "fields-renderer--" + mode);
    content_resize = (function(_this) {
      return function() {
        return CUI.Events.trigger({
          type: "content-resize",
          node: _this.div
        });
      };
    })(this);
    CUI.when(opts.__waits).progress((function(_this) {
      return function() {
        return typeof opts.onProgress === "function" ? opts.onProgress({
          idx: opts.__idx
        }) : void 0;
      };
    })(this)).done((function(_this) {
      return function() {
        content_resize();
        opts.__waits.splice(0);
        return typeof opts.onDone === "function" ? opts.onDone() : void 0;
      };
    })(this)).fail((function(_this) {
      return function() {
        return typeof opts.onFail === "function" ? opts.onFail() : void 0;
      };
    })(this));
    return this.div;
  };

  FieldsRendererTopLevel.prototype.read = function(read_fields) {
    var _fields, body, bodyAdded, f, field, i, idx, j, len, len1, new_fr, read_field;
    this.__read_fields = [];
    for (idx = i = 0, len = read_fields.length; i < len; idx = ++i) {
      read_field = read_fields[idx];
      this.__read_fields.push(read_field);
      if (read_field instanceof MaskSplitter && read_field.isSimpleSplit(read_fields, idx)) {
        this.__read_fields.push(read_field.getSplitterEnd());
      }
    }
    idx = 0;
    _fields = [];
    while (idx < this.__read_fields.length) {
      field = this.__read_fields[idx];
      if (field instanceof MaskSplitter && !(field.isSimpleSplit(this.__read_fields, idx) && field.renderAsField())) {
        new_fr = field.getFieldsRenderer({
          field: field
        });
      } else {
        new_fr = new FieldsRendererPlain({
          field: field
        });
      }
      _fields.push(new_fr);
      idx = new_fr.read(this.__read_fields, idx);
    }
    body = new FieldsRendererBody();
    bodyAdded = false;
    for (j = 0, len1 = _fields.length; j < len1; j++) {
      f = _fields[j];
      if (f instanceof FieldsRendererHead || f instanceof FieldsRendererFooter) {
        this.addField(f);
      } else {
        if (!bodyAdded) {
          bodyAdded = true;
          this.addField(body);
        }
        body.addField(f);
      }
    }
    this.findPlain();
    return this;
  };

  FieldsRendererTopLevel.prototype.dump = function() {
    var f, i, idx, len, lines, ref;
    lines = [];
    ref = this.__read_fields;
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      f = ref[idx];
      if (f.nameLocalized) {
        if (f instanceof MaskSplitter) {
          lines.push("#" + idx + " ----- " + f.nameLocalized() + " ----- ");
        } else {
          lines.push("#" + idx + ": field: " + (typeof f.nameLocalized === "function" ? f.nameLocalized() : void 0));
        }
      } else if (!(f instanceof MaskSplitter)) {
        switch (f.type) {
          case "field":
            lines.push("#" + idx + ": field: " + f.data.field_name + " [" + f.data.field_displayname + "]");
            break;
          default:
            if (!f.type) {
              console.debug(f);
            }
            lines.push("#" + idx + ": " + f.type);
        }
      } else {
        lines.push("#" + idx + ": " + f.fullName());
      }
    }
    lines.push("");
    lines.push("");
    return FieldsRendererTopLevel.__super__.dump.call(this, lines);
  };

  FieldsRendererTopLevel.prototype.isFieldAllowed = function(field) {
    return field instanceof FieldsRendererHead || field instanceof FieldsRendererBody || field instanceof FieldsRendererFooter;
  };

  return FieldsRendererTopLevel;

})(FieldsRenderer);
// Generated by CoffeeScript 1.12.7
var FieldsRendererPlain,
  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;

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

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

  FieldsRendererPlain.prototype.render = function(opts) {
    var div, el, f, fields, i, len, ref, rf;
    fields = this.getFieldsWithContent(opts);
    if (fields.length === 0) {
      return;
    }
    div = CUI.dom.element("DIV", {
      "class": "fields-renderer-plain"
    });
    if (opts.mode === 'sort') {
      CUI.dom.addClass(div, 'ez5-sort-manager-body');
    }
    if (opts.mode === 'editor' || opts.mode === 'editor-header' || opts.mode === 'detail' || opts.mode === 'editor-template' || opts.mode === 'text') {
      CUI.dom.addClass(div, 'fields-renderer-plain--multi-column');
    }
    if (opts.mode === 'expert') {
      CUI.dom.addClass(div, 'fields-renderer-plain--multi-column-when-fillscreen');
    }
    for (i = 0, len = fields.length; i < len; i++) {
      f = fields[i];
      if (f instanceof MaskSplitter) {
        if (f instanceof MaskSplitterEnd || ((ref = opts.mode) === "sort" || ref === "expert")) {
          continue;
        }
        el = f.renderSplitter(opts);
      } else {
        el = (function() {
          switch (opts.mode) {
            case "detail":
            case "detail-header":
            case "text":
            case "table":
              return f.renderForDetail(opts.data, opts.top_level_data, opts);
            case "expert":
              return f.renderForExpert(opts.data[f._ot_name][f.fullName()].data, opts);
            case "sort":
              return f.renderForSort(opts.data[f._ot_name], opts);
            default:
              if (opts.mode.startsWith("editor")) {
                rf = RenderedField.initField({
                  field: f,
                  data: opts.data,
                  top_level_data: opts.top_level_data,
                  opts: opts
                });
                opts.fieldsRenderer = this;
                if (f.isReadOnly(opts.data, opts.top_level_data, opts)) {
                  return rf.renderForEditorReadOnly();
                } else {
                  return rf.renderForEditor();
                }
              } else {
                return console.warn("FieldsRendererPlain: Unsupported mode:", f.fullName(), opts.mode);
              }
          }
        }).call(this);
      }
      CUI.dom.append(div, el);
    }
    if (opts.header) {
      return [opts.header, div];
    } else {
      return div;
    }
  };

  FieldsRendererPlain.prototype.hasContent = function(opts) {
    return this.getFieldsWithContent(opts, true);
  };

  FieldsRendererPlain.prototype.getFieldsWithContent = function(opts, has_content_check) {
    var empty, f, fields, filter, i, len, readonly, ref;
    if (has_content_check == null) {
      has_content_check = false;
    }
    filter = opts.fieldsRendererFilter;
    if (!filter) {
      switch (opts.mode) {
        case "detail":
        case "detail-header":
        case "text":
          filter = "empty";
          break;
        case "editor":
          filter = "empty+readonly";
          break;
        case "editor-bulk":
        case "editor-template":
          filter = "readonly";
          break;
        default:
          filter = null;
      }
    }
    if (!has_content_check) {
      fields = [];
    }
    ref = this.fields;
    for (i = 0, len = ref.length; i < len; i++) {
      f = ref[i];
      if (filter && !(f instanceof MaskSplitter)) {
        empty = f.isEmpty(opts.data, opts.top_level_data, opts);
        readonly = f.isReadOnly(opts.data, opts.top_level_data, opts);
        if (filter === "empty" && empty) {
          continue;
        }
        if (filter === "readonly" && readonly) {
          continue;
        }
        if (filter === "empty+readonly" && empty && readonly) {
          continue;
        }
      }
      if (has_content_check) {
        return true;
      } else {
        fields.push(f);
      }
    }
    if (has_content_check) {
      return false;
    } else {
      return fields;
    }
  };

  FieldsRendererPlain.prototype.findPlain = function() {};

  FieldsRendererPlain.prototype.read = function(fields, idx) {
    var field, nextField;
    while (idx < fields.length) {
      field = fields[idx];
      if ((typeof field.splitterType === "function" ? field.splitterType() : void 0) && !(field.isSimpleSplit() && field.renderAsField())) {
        return idx;
      }
      if (!(field instanceof MaskSplitter)) {
        this.addField(fields[idx++]);
        continue;
      }
      nextField = fields[idx + 1];
      if (!(nextField instanceof MaskSplitterEnd)) {
        return idx;
      }
      this.addField(fields[idx++]);
      this.addField(fields[idx++]);
    }
    return idx;
  };

  FieldsRendererPlain.prototype.isFieldAllowed = function(field) {
    return field instanceof ListViewEditTreeMaskRowNode || field instanceof FieldsRendererSplit || field instanceof Field || field instanceof MultipleFieldsContainer;
  };

  return FieldsRendererPlain;

})(FieldsRenderer);
// Generated by CoffeeScript 1.12.7
var FieldsRendererHead,
  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;

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

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

  FieldsRendererHead.prototype.render = function(opts) {
    var div;
    div = CUI.dom.div("ez5-fields-renderer-head-container");
    opts.header_mode = opts.mode + "-header";
    this.renderFields(opts, div);
    return div;
  };

  FieldsRendererHead.prototype.type = function() {
    return "head";
  };

  FieldsRendererHead.prototype.isFieldAllowed = function(field) {
    return field instanceof FieldsRendererPlain || field instanceof MaskSplitterHeadEnd || field instanceof ListViewEditTreeMaskRowNode || field instanceof Field;
  };

  return FieldsRendererHead;

})(FieldsRenderer);
// Generated by CoffeeScript 1.12.7
var FieldsRendererHeadInternal,
  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;

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

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

  FieldsRendererHeadInternal.prototype.type = function() {
    return "head-internal";
  };

  return FieldsRendererHeadInternal;

})(FieldsRendererHead);
// Generated by CoffeeScript 1.12.7
var FieldsRendererFooter,
  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;

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

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

  FieldsRendererFooter.prototype.render = function(opts) {
    var div;
    div = CUI.dom.div("ez5-fields-renderer-footer");
    opts.footer_mode = opts.mode + "-footer";
    this.renderFields(opts, div);
    return div;
  };

  FieldsRendererFooter.prototype.type = function() {
    return "footer";
  };

  FieldsRendererFooter.prototype.isFieldAllowed = function(field) {
    return field instanceof FieldsRendererPlain || field instanceof MaskSplitterFooterEnd || field instanceof ListViewEditTreeMaskRowNode || field instanceof Field;
  };

  return FieldsRendererFooter;

})(FieldsRenderer);
// Generated by CoffeeScript 1.12.7
var FieldsRendererBody,
  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;

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

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

  FieldsRendererBody.prototype.render = function(opts) {
    var div;
    div = CUI.dom.div("fields-renderer-body");
    if (opts.body_header) {
      CUI.dom.prepend(div, opts.body_header);
    }
    return this.renderFields(opts, div);
  };

  FieldsRendererBody.prototype.type = function() {
    return "body";
  };

  FieldsRendererBody.prototype.isFieldAllowed = function(field) {
    return field instanceof FieldsRendererPlain || field instanceof FieldsRendererTabs || field instanceof CustomFieldsRenderer || field instanceof FieldsRendererPanel || field instanceof FieldsRendererBlock || field instanceof FieldsRendererSplit || field instanceof ListViewEditTreeMaskRowNode || field instanceof Field;
  };

  return FieldsRendererBody;

})(FieldsRenderer);
// Generated by CoffeeScript 1.12.7
var FieldsRendererPanel,
  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;

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

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

  FieldsRendererPanel.prototype.getState = function() {
    if (!this.__panel) {
      return false;
    }
    return this.__panel.isOpen();
  };

  FieldsRendererPanel.prototype.restoreState = function(open) {
    if (!this.__panel || open === null) {
      return;
    }
    if (open && !this.__panel.isOpen()) {
      return this.__panel.open();
    } else if (!open && this.__panel.isOpen()) {
      return this.__panel.close();
    }
  };

  FieldsRendererPanel.prototype.__getPanelStateKey = function(opts) {
    var base, maskName, ref;
    maskName = (ref = opts.top_level_data) != null ? ref._mask : void 0;
    if (!maskName || !(typeof (base = this._field).shouldRememberState === "function" ? base.shouldRememberState() : void 0)) {
      return null;
    }
    return this._field.getPanelStateKey(maskName);
  };

  FieldsRendererPanel.prototype.__getSavedPanelState = function(opts) {
    var key, panelStates;
    key = this.__getPanelStateKey(opts);
    if (!key) {
      return null;
    }
    panelStates = CUI.getLocalStorage("mask_panel_states") || {};
    return panelStates[key];
  };

  FieldsRendererPanel.prototype.__savePanelState = function(opts, isOpen) {
    var key, panelStates;
    key = this.__getPanelStateKey(opts);
    if (!key) {
      return;
    }
    panelStates = CUI.getLocalStorage("mask_panel_states") || {};
    panelStates[key] = isOpen;
    return CUI.setLocalStorage("mask_panel_states", panelStates);
  };

  FieldsRendererPanel.prototype.render = function(opts) {
    var base, block, field, i, len, load_on_open, onActivate, onDeactivate, panelClosed, ref, ref1, savedState;
    if (!this.hasContent(opts)) {
      return;
    }
    if (opts.for_print) {
      block = new CUI.Block({
        text: this._field.nameLocalized(),
        content: (function(_this) {
          return function() {
            var div;
            div = CUI.dom.div();
            _this.renderFields(opts, div);
            return div.children;
          };
        })(this)
      }).DOM;
      return block;
    }
    load_on_open = true;
    if (this._field._render_fields_closed) {
      load_on_open = false;
    } else {
      ref = this.fields;
      for (i = 0, len = ref.length; i < len; i++) {
        field = ref[i];
        if (typeof field.needsDirectRender === "function" ? field.needsDirectRender(opts) : void 0) {
          load_on_open = false;
          break;
        }
      }
    }
    panelClosed = this._field.isClosed(opts);
    if (panelClosed && ((ref1 = this._field.getData().options) != null ? ref1.open_editor_with_content : void 0)) {
      opts.fieldsRendererFilter = "empty";
      panelClosed = !this.hasContent(opts);
      delete opts.fieldsRendererFilter;
    }
    if (typeof (base = this._field).shouldRememberState === "function" ? base.shouldRememberState() : void 0) {
      savedState = this.__getSavedPanelState(opts);
      if (savedState !== null && savedState !== void 0) {
        panelClosed = !savedState;
      }
    }
    onActivate = (function(_this) {
      return function() {
        var base1;
        _this._field.onOpen();
        if (typeof (base1 = _this._field).shouldRememberState === "function" ? base1.shouldRememberState() : void 0) {
          return _this.__savePanelState(opts, true);
        }
      };
    })(this);
    onDeactivate = (function(_this) {
      return function() {
        var base1;
        _this._field.onClose();
        if (typeof (base1 = _this._field).shouldRememberState === "function" ? base1.shouldRememberState() : void 0) {
          return _this.__savePanelState(opts, false);
        }
      };
    })(this);
    if (!load_on_open) {
      this.__panel = new CUI.Panel({
        text: this._field.nameLocalized(),
        radio: true,
        closed: panelClosed,
        onActivate: onActivate,
        onDeactivate: onDeactivate,
        "class": "ez5-fields-renderer-panel",
        content: (function(_this) {
          return function() {
            var div;
            div = CUI.dom.div();
            _this.renderFields(opts, div);
            return div.children;
          };
        })(this)
      });
      return this.__panel.DOM;
    } else {
      this.__panel = new CUI.Panel({
        text: this._field.nameLocalized(),
        closed: panelClosed,
        radio: true,
        load_on_open: true,
        onActivate: onActivate,
        onDeactivate: onDeactivate,
        content_placeholder: new LocaLabel({
          loca_key: "fields.renderer.panel.loading"
        }),
        "class": "ez5-fields-renderer-panel",
        content: (function(_this) {
          return function() {
            var dfr, div;
            dfr = new CUI.Deferred();
            div = CUI.dom.div();
            _this.renderFields(opts, div);
            CUI.when(opts.__waits).always(function() {
              dfr.resolve(div.children);
              return CUI.Events.trigger({
                type: "editor-changed",
                node: _this.__panel
              });
            });
            return dfr.promise();
          };
        })(this)
      });
      return this.__panel.DOM;
    }
  };

  FieldsRendererPanel.prototype.read = function(fields, index) {
    var base, base1, block, field, fieldsRenderer, split, type;
    if ((typeof (base = fields[index]).splitterType === "function" ? base.splitterType() : void 0) !== this.beginSplitterType()) {
      throw "Cannot read " + (this.type()) + "-begin from field type " + (typeof (base1 = fields[index]).splitterType === "function" ? base1.splitterType() : void 0);
    }
    index++;
    while (index < fields.length) {
      field = fields[index];
      type = typeof field.splitterType === "function" ? field.splitterType() : void 0;
      if (type) {
        if (type === "panel-end") {
          this.addField(field);
          return index + 1;
        } else if (type === "block-begin") {
          block = new FieldsRendererBlock({
            field: field
          });
          this.addField(block);
          index = block.read(fields, index);
          continue;
        } else if (type === "split") {
          split = new FieldsRendererSplit({
            field: field
          });
          this.addField(split);
          index = split.read(fields, index);
          continue;
        } else {
          if (field instanceof CustomMaskSplitter) {
            fieldsRenderer = field.getFieldsRenderer({
              field: field
            });
            this.addField(fieldsRenderer);
            index = fieldsRenderer.read(fields, index);
            continue;
          } else {
            throw "Cannot read type " + type + " inside " + (this.type());
          }
        }
      }
      this.addField(fields[index]);
      index++;
    }
    return index;
  };

  FieldsRendererPanel.prototype.type = function() {
    return "panel";
  };

  FieldsRendererPanel.prototype.isFieldAllowed = function(field) {
    return field instanceof FieldsRendererPlain || field instanceof FieldsRendererBlock || field instanceof MaskSplitterBlockEnd || field instanceof CustomFieldsRenderer || field instanceof MaskSplitterPanelEnd || field instanceof ListViewEditTreeMaskRowNode || field instanceof MultipleFieldsContainer || field instanceof FieldsRendererSplit || field instanceof Field;
  };

  return FieldsRendererPanel;

})(FieldsRenderer);
// Generated by CoffeeScript 1.12.7
var FieldsRendererBlock,
  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;

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

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

  FieldsRendererBlock.prototype.render = function(opts) {
    var blk, div;
    if (!this.hasContent(opts)) {
      return;
    }
    div = CUI.dom.div();
    this.renderFields(opts, div);
    blk = new CUI.Block({
      padded: false,
      "class": "ez5-fields-renderer-block",
      text: this._field.nameLocalized(),
      content: div.children
    });
    return blk;
  };

  FieldsRendererBlock.prototype.type = function() {
    return "block";
  };

  FieldsRendererBlock.prototype.isFieldAllowed = function(field) {
    return field instanceof FieldsRendererPlain || field instanceof FieldsRendererBlock || field instanceof MaskSplitterBlockEnd || field instanceof CustomFieldsRenderer || field instanceof ListViewEditTreeMaskRowNode || field instanceof MultipleFieldsContainer || field instanceof FieldsRendererSplit || field instanceof FieldsRendererPanel || field instanceof Field;
  };

  return FieldsRendererBlock;

})(FieldsRenderer);
// Generated by CoffeeScript 1.12.7
var FieldsRendererSplit,
  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;

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

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

  FieldsRendererSplit.prototype.type = function() {
    return "split";
  };

  FieldsRendererSplit.prototype.isSimpleSplit = function() {
    return true;
  };

  FieldsRendererSplit.prototype.beginSplitterType = function() {
    return "split";
  };

  FieldsRendererSplit.prototype.endSplitterType = function() {
    return "split-end";
  };

  FieldsRendererSplit.prototype.render = function(opts) {
    return new CUI.Label({
      "class": "ez5-fields-renderer-split",
      text: this.opts.field.nameLocalized()
    });
  };

  FieldsRendererSplit.prototype.isFieldAllowed = function(field) {
    return FieldsRendererSplit.__super__.isFieldAllowed.call(this, field) || field instanceof MaskSplitterSplitEnd;
  };

  FieldsRendererSplit.prototype.read = function(fields, index) {
    var base, base1, endField, type;
    if ((typeof (base = fields[index]).splitterType === "function" ? base.splitterType() : void 0) !== this.beginSplitterType()) {
      throw "Cannot read " + (this.type()) + "-begin from field type " + (typeof (base1 = fields[index]).splitterType === "function" ? base1.splitterType() : void 0);
    }
    index++;
    endField = fields[index];
    type = typeof endField.splitterType === "function" ? endField.splitterType() : void 0;
    if (type !== this.endSplitterType()) {
      throw "read method in FieldsRenderedSplit does not support fields inside.";
    }
    this.addField(endField);
    return index + 1;
  };

  return FieldsRendererSplit;

})(FieldsRendererPanel);
// Generated by CoffeeScript 1.12.7
var FieldsRendererTabs,
  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;

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

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

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

  FieldsRendererTabs.prototype.getState = function() {
    if (!this.__tabs) {
      return null;
    }
    return this.__tabs.getActiveTabIdx();
  };

  FieldsRendererTabs.prototype.restoreState = function(tabIdx) {
    if (!this.__tabs || tabIdx === null) {
      return;
    }
    return this.__tabs.activate(tabIdx);
  };

  FieldsRendererTabs.prototype.render = function(opts) {
    var content, div, field, i, j, lbl, len, len1, load_later, panel, panels, ref, ref1, tabs, txt;
    panels = [];
    tabs = [];
    ref = this.fields;
    for (i = 0, len = ref.length; i < len; i++) {
      field = ref[i];
      if (field instanceof MaskSplitterTabsEnd) {
        continue;
      }
      if (field.hasContent && !field.hasContent(opts)) {
        continue;
      }
      div = CUI.dom.div();
      if (tabs.length === 0 || opts.for_print || field.needsDirectRender(opts)) {
        field.render(opts, div);
        load_later = false;
      } else {
        load_later = true;
      }
      if (opts.for_print) {
        panels.push(new CUI.Panel({
          text: field.getTabTitle(),
          closed: !opts.for_print,
          content: div.children
        }));
      } else if (!load_later) {
        tabs.push({
          text: field.getTabTitle(),
          content: div.children
        });
      } else {
        (function(_this) {
          return (function(field, div) {
            return tabs.push({
              text: field.getTabTitle(),
              load_on_show: true,
              content_placeholder: new EmptyLocaLabel({
                loca_key: "fields.renderer.tab.loading",
                centered: true
              }),
              content: function(tab) {
                var dfr;
                field.render(opts, div);
                if (!tab) {
                  return div.children;
                }
                dfr = new CUI.Deferred();
                CUI.when(opts.__waits).always(function() {
                  dfr.resolve(div.children);
                  CUI.Events.trigger({
                    type: "content-resize",
                    node: tab
                  });
                  return CUI.Events.trigger({
                    type: "editor-changed",
                    node: tab
                  });
                });
                return dfr.promise();
              }
            });
          });
        })(this)(field, div);
      }
    }
    if (opts.for_print) {
      div = CUI.dom.div();
      for (j = 0, len1 = panels.length; j < len1; j++) {
        panel = panels[j];
        CUI.dom.append(div, panel.DOM);
      }
      return div;
    }
    txt = this._field.getDisplaynameLocalized();
    if (txt) {
      lbl = new CUI.Label({
        text: txt,
        "class": "ez5-fields-renderer-tabs-title"
      });
    }
    if (tabs.length) {
      if (tabs.length === 1 && ((ref1 = this._mask_options) != null ? ref1.hide_if_only_one_tab_available : void 0)) {
        content = tabs[0].content;
        if (CUI.util.isFunction(content)) {
          content = content();
        }
        return content;
      } else {
        this.__tabs = new CUI.Tabs({
          "class": "ez5-fields-renderer-tabs",
          tabs: tabs,
          maximize_horizontal: true,
          maximize_vertical: false
        });
        return [lbl, this.__tabs];
      }
    } else {
      return null;
    }
  };

  FieldsRendererTabs.prototype.type = function() {
    return "tabs";
  };

  FieldsRendererTabs.prototype.read = function(fields, idx) {
    var base, base1, block, count, field, fieldsRenderer, panel, split, tab, type;
    if ((typeof (base = fields[idx]).splitterType === "function" ? base.splitterType() : void 0) !== this.beginSplitterType()) {
      throw "Cannot read " + (this.type()) + "-begin from field type " + (typeof (base1 = fields[idx]).splitterType === "function" ? base1.splitterType() : void 0);
    }
    idx++;
    count = 0;
    while (idx < fields.length) {
      field = fields[idx];
      count++;
      type = typeof field.splitterType === "function" ? field.splitterType() : void 0;
      if (count === 1 && (type !== "tab" && type !== "tabs-end")) {
        throw "Wrong content after field " + (this.type());
      }
      if (type) {
        if (type === "tabs-end") {
          this.addField(field);
          return idx + 1;
        } else if (type === "tab") {
          tab = new FieldsRendererTab({
            field: field
          });
          this.addField(tab);
          idx++;
          continue;
        } else if (type === "panel-begin") {
          panel = new FieldsRendererPanel({
            field: field
          });
          tab.addField(panel);
          idx = panel.read(fields, idx);
          continue;
        } else if (type === "split") {
          split = new FieldsRendererSplit({
            field: field
          });
          tab.addField(split);
          idx = split.read(fields, idx);
          continue;
        } else if (type === "block-begin") {
          block = new FieldsRendererBlock({
            field: field
          });
          tab.addField(block);
          idx = block.read(fields, idx);
          continue;
        } else {
          if (field instanceof CustomMaskSplitter) {
            fieldsRenderer = field.getFieldsRenderer({
              field: field
            });
            tab.addField(fieldsRenderer);
            idx = fieldsRenderer.read(fields, idx);
            continue;
          } else {
            console.error("Cannot read type " + type + " inside " + (this.type()));
            idx++;
            continue;
          }
        }
      }
      tab.addField(fields[idx]);
      idx++;
    }
    return idx;
  };

  FieldsRendererTabs.prototype.isFieldAllowed = function(field) {
    return field instanceof FieldsRendererTab || field instanceof MaskSplitterTabsEnd;
  };

  return FieldsRendererTabs;

})(FieldsRenderer);
// Generated by CoffeeScript 1.12.7
var FieldsRendererTab,
  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;

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

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

  FieldsRendererTab.prototype.getTabTitle = function() {
    return this.opts.field.nameLocalized();
  };

  FieldsRendererTab.prototype.render = function(opts, div) {
    return this.renderFields(opts, div);
  };

  FieldsRendererTab.prototype.isFieldAllowed = function(field) {
    return field instanceof FieldsRendererPanel || field instanceof FieldsRendererBlock || field instanceof CustomFieldsRenderer || field instanceof FieldsRendererPlain || field instanceof FieldsRendererSplit || field instanceof ListViewEditTreeMaskRowNode || field instanceof Field;
  };

  return FieldsRendererTab;

})(FieldsRenderer);
// Generated by CoffeeScript 1.12.7
var NestedFieldsRenderer,
  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;

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

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

  NestedFieldsRenderer.prototype.render = function(opts) {
    var div, i, len, nestedRow, ref, row;
    div = CUI.dom.div("ez5-nested-fields-group");
    ref = this.fields;
    for (i = 0, len = ref.length; i < len; i++) {
      nestedRow = ref[i];
      row = nestedRow.render(opts);
      if (row) {
        CUI.dom.append(div, row);
      }
    }
    return div;
  };

  NestedFieldsRenderer.prototype.isFieldAllowed = function(field) {
    return field instanceof NestedRow;
  };

  NestedFieldsRenderer.prototype.getFields = function() {
    return this.fields.map(function(nestedRow) {
      return nestedRow.getField();
    });
  };

  return NestedFieldsRenderer;

})(FieldsRendererPlain);
// Generated by CoffeeScript 1.12.7
var MaskSplitter,
  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;

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

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

  MaskSplitter.prototype.initOpts = function() {
    MaskSplitter.__super__.initOpts.call(this);
    return this.addOpts({
      field: {
        check: function(v) {
          return v.kind === "splitter";
        }
      },
      options: {
        check: "PlainObject"
      },
      version: {
        check: ["CURRENT", "HEAD", "TEMP"]
      },
      l10n_prefix: {
        check: Function
      },
      rows: {
        check: Array
      },
      maskEditor: {
        check: MaskEditor
      },
      data: {
        mandatory: true,
        type: "PlainObject"
      }
    });
  };

  MaskSplitter.prototype.readOpts = function() {
    var defaultOptions, ex;
    if (!this.opts.field) {
      this.opts.field = {
        kind: "splitter"
      };
    }
    if (this.opts.field.options) {
      try {
        this.opts.options = JSON.parse(this.opts.field.options);
      } catch (error) {
        ex = error;
        console.error("Error parsing opts for MaskSplitter:", this.opts.field.options);
      }
    }
    if (!this.opts.options) {
      this.opts.options = {};
    }
    defaultOptions = this.getDefaultOptions();
    CUI.util.mergeMap(this.opts.options, defaultOptions);
    if (!this.opts.options.splitterIdx) {
      this.opts.options.splitterIdx = ++MaskSplitter.maxSplitterIdx;
    } else if (MaskSplitter.maxSplitterIdx < this.opts.options.splitterIdx) {
      MaskSplitter.maxSplitterIdx = this.opts.options.splitterIdx;
    }
    this.opts.data = {
      version: this.opts.version,
      field: this.opts.field,
      options: this.opts.options,
      _fields: {}
    };
    MaskSplitter.__super__.readOpts.call(this);
    if (this._l10n_prefix) {
      CUI.util.assert(this._data.version, "new MaskSplitter", "opts.version needs to be set.");
      this._data.field.displayname_l10n = ez5.loca.get_user_key(this._data.version, this.getLocaKey(this._l10n_prefix));
    }
    return this.maskEditor = this._maskEditor;
  };

  MaskSplitter.prototype.getDefaultOptions = function() {
    return {};
  };

  MaskSplitter.prototype.getColspan = function() {
    var colspan;
    colspan = 18;
    if (ez5.version("6.7")) {
      colspan += 2;
    }
    return colspan;
  };

  MaskSplitter.prototype.getLocaKey = function(l10n_prefix) {
    CUI.util.assert(CUI.util.isFunction(l10n_prefix), (CUI.util.getObjectClass(this)) + ".getLocaKey", "l10n_prefix is not a Function", {
      opts: this.opts
    });
    return (l10n_prefix()) + "splitter." + this._data.options.splitterIdx;
  };

  MaskSplitter.prototype.renderContent = function() {
    return CUI.util.assert(false, CUI.util.getObjectClass(this) + ".renderContent", "Needs implementation.");
  };

  MaskSplitter.prototype.getOptions = function() {
    return [];
  };

  MaskSplitter.prototype.getDefaultMaskOptions = function() {
    if (this.isSimpleSplit() && this.renderAsField()) {
      return [
        {
          name: "blockWidth",
          form: {
            label: $$('admin.mask.col.width.label')
          },
          type: CUI.Select,
          options: (function(_this) {
            return function() {
              var i, len, ref, results, width;
              ref = ["100%", "75%", "50%", "25%"];
              results = [];
              for (i = 0, len = ref.length; i < len; i++) {
                width = ref[i];
                results.push({
                  text: width,
                  value: width
                });
              }
              return results;
            };
          })(this)
        }
      ];
    } else {
      return [];
    }
  };

  MaskSplitter.prototype.renderOptionsDisplayPrefix = function() {
    return 'mask.splitter.option.';
  };

  MaskSplitter.prototype.renderOptions = function() {
    var form_pop, options;
    options = this.getDefaultMaskOptions();
    options = options.concat(this.getOptions());
    if (options != null ? options.length : void 0) {
      form_pop = new CUI.FormPopover({
        button: {
          loca_key: "mask.splitter.options.button"
        },
        data: this._data.options,
        popover: {
          pane: {
            title: $$("mask.splitter.options.popover.title")
          }
        },
        fields: options,
        renderDisplayContent: (function(_this) {
          return function(df, data) {
            var div, i, key, len, tag, tags, txt, value;
            div = CUI.dom.div("ez5-tag-holder");
            tags = [];
            for (key in data) {
              value = data[key];
              if (key === 'splitterIdx') {
                continue;
              }
              if (key === '__customSplitterType') {
                continue;
              }
              if (value) {
                tags.push({
                  key: key,
                  value: value
                });
              }
            }
            if (tags.length === 0) {
              return;
            }
            div = CUI.dom.div("ez5-tag-holder");
            for (i = 0, len = tags.length; i < len; i++) {
              tag = tags[i];
              key = _this.renderOptionsDisplayPrefix() + tag.key;
              if (!ez5.loca.has(key)) {
                continue;
              }
              txt = $$(key, {
                value: tag.value
              });
              if (!txt) {
                continue;
              }
              CUI.dom.append(div, new CUI.Label({
                "class": "ez5-tag ez5-tag-mask-editor-option",
                text: txt
              }));
            }
            return div;
          };
        })(this)
      });
      form_pop.start();
      this.addColumn(new CUI.ListViewColumn({
        element: form_pop.DOM
      }));
      return this.dataFields.push(form_pop);
    } else {
      return this.addColumn(new CUI.ListViewColumnEmpty());
    }
  };

  MaskSplitter.prototype.renderNameInput = function() {
    var loca_key, mi;
    this.renderOptions();
    loca_key = "mask.splitter.panel.spliter_name." + this.splitterType();
    mi = new CUI.MultiInput({
      name: "displayname_l10n",
      control: ez5.loca.getLanguageControlAdmin(),
      user_selectable: ez5.session.getPref("languages_user_selection"),
      data: this._data.field
    }).start();
    this.dataFields.push(mi);
    return new CUI.VerticalList({
      content: [
        new LocaLabel({
          loca_key: loca_key
        }), mi
      ]
    });
  };

  MaskSplitter.prototype.getFieldToSave = function(opts) {
    if (this._data.field.displayname_l10n) {
      opts.l10n_keys[this.getLocaKey(opts.l10n_prefix)] = this._data.field.displayname_l10n;
    }
    return {
      kind: "splitter",
      options: JSON.stringify(this._data.options),
      type: this.splitterType()
    };
  };

  MaskSplitter.prototype.getElementClass = function() {
    return "";
  };

  MaskSplitter.prototype.getClass = function() {
    var cls;
    cls = MaskSplitter.__super__.getClass.call(this);
    cls += " mask-splitter";
    return cls;
  };

  MaskSplitter.prototype.addToMaskEditor = function(maskEditor1) {
    this.maskEditor = maskEditor1;
    this.maskEditor.addNode(this);
    this.select();
    return this;
  };

  MaskSplitter.prototype.splitterType = function() {
    return CUI.util.assert(false, (CUI.util.getObjectClass(this)) + ".splitterType", "Overwrite me");
  };

  MaskSplitter.prototype.getFieldsRenderer = function(opts) {
    if (opts == null) {
      opts = {};
    }
    return CUI.util.assert(false, (CUI.util.getObjectClass(this)) + ".getFieldsRenderer", "Overwrite me");
  };

  MaskSplitter.prototype.isSimpleSplit = function() {
    return false;
  };

  MaskSplitter.prototype.renderAsField = function() {
    return false;
  };

  MaskSplitter.prototype.init = function() {};

  MaskSplitter.prototype.supportsFacet = function() {
    return false;
  };

  MaskSplitter.prototype.isSourceForMapping = function() {
    return false;
  };

  MaskSplitter.prototype.getSaveData = function(data, save_data, opts) {};

  MaskSplitter.prototype.name = function() {
    return this.splitterType();
  };

  MaskSplitter.prototype.nameLocalized = function() {
    return this.getDisplaynameLocalized() || CUI.util.getObjectClass(this).substring("MaskSplitter".length) + (" [" + this._data.options.splitterIdx + "]");
  };

  MaskSplitter.prototype.getDisplaynameLocalized = function() {
    return ez5.loca.getBestFrontendValue(this._data.field.displayname_l10n);
  };

  MaskSplitter.prototype.fullNameLocalized = function() {
    return this.splitterType();
  };

  MaskSplitter.prototype.getOption = function() {
    return false;
  };

  MaskSplitter.prototype.fullName = function() {
    return this.splitterType();
  };

  MaskSplitter.prototype.depth = function() {
    return 0;
  };

  MaskSplitter.prototype.isExpertCommon = function() {
    return false;
  };

  MaskSplitter.prototype.isExpertCommonOnly = function() {
    return false;
  };

  MaskSplitter.prototype.isVisible = function(mode, opts) {
    switch (mode) {
      case "editor-header":
      case "editor-header-bulk":
      case "editor-header-template":
        return false;
      case "detail-header":
      case "detail-footer":
      case "editor-footer":
      case "text":
      case "table":
      case "fulltext":
      case "standard":
      case "facet":
        return false;
      default:
        return true;
    }
  };

  MaskSplitter.prototype.renderStandard = function(standard, data) {};

  MaskSplitter.maxSplitterIdx = -1;

  MaskSplitter.getFromField = function(opts) {
    var _plugin, errorMessage, field_opts, fn, i, j, len, len1, plugin, plugins, ref, type;
    if (opts == null) {
      opts = {};
    }
    fn = "MaskSplitter.getFromField";
    CUI.util.assert(opts.field.kind === "splitter", fn, "opts.field.kind needs to be splitter", {
      opts: opts
    });
    CUI.util.assert(!opts.maskEditor || opts.maskEditor instanceof MaskEditor, fn, "opts.maskEditor needs to be MaskEditor", {
      opts: opts
    });
    ref = [MaskSplitterTabs, MaskSplitterTab, MaskSplitterTabsEnd, MaskSplitterPanel, MaskSplitterPanelEnd, MaskSplitterBlock, MaskSplitterBlockEnd, MaskSplitterHead, MaskSplitterHeadEnd, MaskSplitterSplit];
    for (i = 0, len = ref.length; i < len; i++) {
      type = ref[i];
      if (type.prototype.splitterType() === opts.field.type) {
        return new type(opts);
      }
    }
    plugins = MaskSplitter.plugins.getPlugins();
    if (opts.field.type === "custom-begin" || opts.field.type === "custom-end") {
      field_opts = JSON.parse(opts.field.options);
      for (j = 0, len1 = plugins.length; j < len1; j++) {
        plugin = plugins[j];
        _plugin = new plugin(opts);
        if (_plugin.storeType() === field_opts.__customSplitterType) {
          if (opts.field.type === "custom-end") {
            return _plugin.getSplitterEnd();
          }
          return _plugin;
        }
      }
      if (opts.field.type === "custom-begin") {
        return new CustomMaskSplitterUnknown(opts);
      } else {
        return new CustomMaskSplitterEndUnknown(opts);
      }
    }
    errorMessage = "The Mask Splitter type was not found: " + opts.field.type;
    console.error(errorMessage, opts);
    return new MaskSplitterUnknown(opts);
  };

  MaskSplitter.getMenuItems = function(maskEditor) {
    var fn1, fn2, head, i, items, j, k, kL, l, len, len1, len2, p, plugin, ref, ref1, ref2, row;
    items = [];
    head = false;
    ref = maskEditor.current_mask.getRows();
    for (i = 0, len = ref.length; i < len; i++) {
      row = ref[i];
      if (row instanceof MaskSplitterHead) {
        head = true;
      }
    }
    ref1 = ["Tabs", "Tab", "Panel", "Block", "Split"];
    fn1 = (function(_this) {
      return function(k) {
        var disabled;
        switch (k) {
          case "Tab":
            disabled = !(maskEditor.mask_table.getSelectedNode() instanceof MaskSplitterTabs);
            break;
          default:
            disabled = false;
        }
        return items.push({
          value: k,
          disabled: disabled,
          text: $$("admin.mask.add_" + kL),
          onClick: function() {
            return (new window["MaskSplitter" + k]()).addToMaskEditor(maskEditor);
          }
        });
      };
    })(this);
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      k = ref1[j];
      kL = k.toLowerCase();
      fn1(k);
    }
    if (MaskSplitter.plugins.getPlugins().length > 0) {
      items.push({
        divider: true
      });
      ref2 = MaskSplitter.plugins.getPlugins();
      fn2 = (function(_this) {
        return function(p) {
          return items.push({
            value: p.name(),
            text: p.nameLocalized(),
            onClick: function() {
              return p.addToMaskEditor(maskEditor);
            }
          });
        };
      })(this);
      for (l = 0, len2 = ref2.length; l < len2; l++) {
        plugin = ref2[l];
        p = new plugin();
        fn2(p);
      }
    }
    return items;
  };

  MaskSplitter.prototype.getDataOptions = function() {
    var k, opts, ref, v;
    opts = this.getData().options || {};
    ref = this.getDefaultOptions();
    for (k in ref) {
      v = ref[k];
      if (opts.hasOwnProperty(k)) {
        continue;
      }
      opts[k] = v;
    }
    return opts;
  };

  MaskSplitter.prototype.renderSplitter = function(opts) {
    var attributes, defaultAttributes, div, element;
    if (opts == null) {
      opts = {};
    }
    if (!this.isSimpleSplit() || !this.renderAsField()) {
      console.warn("MaskSplitter :: renderSplitter method can be only used for simple/render-as-field mask splitters.");
      return;
    }
    attributes = this.getFieldAttributes(opts);
    defaultAttributes = {};
    defaultAttributes["ez5-splitter-name"] = this.fullName();
    CUI.util.mergeMap(attributes, defaultAttributes);
    div = CUI.dom.div("ez5-field ez5-field-block", attributes);
    element = this.renderField(opts);
    CUI.dom.append(div, element);
    return div;
  };

  MaskSplitter.prototype.renderField = function() {
    return CUI.util.assert(false, (CUI.util.getObjectClass(this)) + ".renderField", "Overwrite me");
  };

  MaskSplitter.prototype.getFieldAttributes = function() {
    var attributes;
    attributes = {};
    attributes["data-block-width"] = this.getDataOptions().blockWidth;
    return attributes;
  };

  return MaskSplitter;

})(ListViewEditTreeMaskRowNode);
// Generated by CoffeeScript 1.12.7
var MaskSplitterUnknown,
  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;

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

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

  MaskSplitterUnknown.prototype.splitterType = function() {
    return "unknown";
  };

  return MaskSplitterUnknown;

})(MaskSplitter);
// Generated by CoffeeScript 1.12.7
var MaskSplitterSplit,
  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;

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

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

  MaskSplitterSplit.prototype.splitterType = function() {
    return "split";
  };

  MaskSplitterSplit.prototype.isSimpleSplit = function() {
    return true;
  };

  MaskSplitterSplit.prototype.getFieldsRenderer = function(opts) {
    if (opts == null) {
      opts = {};
    }
    return new window.FieldsRendererSplit(opts);
  };

  MaskSplitterSplit.prototype.getSplitterEnd = function() {
    return new window.MaskSplitterSplitEnd();
  };

  MaskSplitterSplit.prototype.renderContent = function() {
    return this.renderNameInput();
  };

  MaskSplitterSplit.prototype.isVisible = function(mode, opts) {
    if (mode === "text") {
      return true;
    }
    return MaskSplitterSplit.__super__.isVisible.call(this, mode, opts);
  };

  MaskSplitterSplit.prototype.trashable = function() {
    return true;
  };

  MaskSplitterSplit.prototype.isEnabledForNested = function() {
    return true;
  };

  return MaskSplitterSplit;

})(MaskSplitter);
// Generated by CoffeeScript 1.12.7
var MaskSplitterSplitFixed,
  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;

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

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

  MaskSplitterSplitFixed.prototype.initOpts = function() {
    MaskSplitterSplitFixed.__super__.initOpts.call(this);
    return this.addOpts({
      text: {
        mandatory: true,
        check: String
      }
    });
  };

  MaskSplitterSplitFixed.prototype.nameLocalized = function() {
    return this._text;
  };

  return MaskSplitterSplitFixed;

})(MaskSplitterSplit);
// Generated by CoffeeScript 1.12.7
var MaskSplitterEnd,
  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;

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

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

  MaskSplitterEnd.prototype.renderContent = function() {
    return new LocaLabel({
      loca_key: "mask.splitter.panel.spliter_name." + this.splitterType()
    });
  };

  MaskSplitterEnd.prototype.getClass = function() {
    var cls;
    cls = MaskSplitterEnd.__super__.getClass.call(this);
    cls += "-end";
    return cls;
  };

  return MaskSplitterEnd;

})(MaskSplitter);
// Generated by CoffeeScript 1.12.7
var MaskSplitterHeadEnd,
  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;

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

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

  MaskSplitterHeadEnd.prototype.splitterType = function() {
    return "head-end";
  };

  return MaskSplitterHeadEnd;

})(MaskSplitterEnd);
// Generated by CoffeeScript 1.12.7
var MaskSplitterFooterEnd,
  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;

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

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

  MaskSplitterFooterEnd.prototype.splitterType = function() {
    return "footer-end";
  };

  MaskSplitterFooterEnd.prototype.getFieldsRenderer = function(opts) {
    if (opts == null) {
      opts = {};
    }
    return new FieldsRendererFooter(opts);
  };

  return MaskSplitterFooterEnd;

})(MaskSplitterEnd);
// Generated by CoffeeScript 1.12.7
var MaskSplitterPanelEnd,
  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;

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

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

  MaskSplitterPanelEnd.prototype.splitterType = function() {
    return "panel-end";
  };

  MaskSplitterPanelEnd.prototype.isVisible = function(mode, opts) {
    if (mode === "text") {
      return true;
    }
    return MaskSplitterPanelEnd.__super__.isVisible.call(this, mode, opts);
  };

  return MaskSplitterPanelEnd;

})(MaskSplitterEnd);
// Generated by CoffeeScript 1.12.7
var MaskSplitterBlockEnd,
  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;

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

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

  MaskSplitterBlockEnd.prototype.isVisible = function(mode, opts) {
    if (mode === "text") {
      return true;
    }
    return MaskSplitterBlockEnd.__super__.isVisible.call(this, mode, opts);
  };

  MaskSplitterBlockEnd.prototype.splitterType = function() {
    return "block-end";
  };

  return MaskSplitterBlockEnd;

})(MaskSplitterEnd);
// Generated by CoffeeScript 1.12.7
var MaskSplitterSplitEnd,
  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;

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

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

  MaskSplitterSplitEnd.prototype.isSimpleSplit = function() {
    return true;
  };

  MaskSplitterSplitEnd.prototype.isVisible = function(mode, opts) {
    if (mode === "text") {
      return true;
    }
    return MaskSplitterSplitEnd.__super__.isVisible.call(this, mode, opts);
  };

  MaskSplitterSplitEnd.prototype.splitterType = function() {
    return "split-end";
  };

  return MaskSplitterSplitEnd;

})(MaskSplitterEnd);
// Generated by CoffeeScript 1.12.7
var MaskSplitterTabsEnd,
  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;

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

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

  MaskSplitterTabsEnd.prototype.isVisible = function(mode, opts) {
    if (mode === "text") {
      return true;
    }
    return MaskSplitterTabsEnd.__super__.isVisible.call(this, mode, opts);
  };

  MaskSplitterTabsEnd.prototype.splitterType = function() {
    return "tabs-end";
  };

  return MaskSplitterTabsEnd;

})(MaskSplitterEnd);
// Generated by CoffeeScript 1.12.7
var MaskSplitterBegin,
  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;

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

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

  MaskSplitterBegin.prototype.renderContent = function() {
    return this.renderNameInput();
  };

  MaskSplitterBegin.prototype.trashable = function() {
    return true;
  };

  MaskSplitterBegin.prototype.remove = function() {
    var f, i, len, ref;
    ref = this.getRowsToMove();
    for (i = 0, len = ref.length; i < len; i++) {
      f = ref[i];
      if (!(f instanceof MaskSplitter)) {
        continue;
      }
      f.remove(true);
    }
    return MaskSplitterBegin.__super__.remove.call(this);
  };

  MaskSplitterBegin.prototype.addToMaskEditor = function(maskEditor) {
    this.maskEditor = maskEditor;
    this.maskEditor.addNode(this);
    this.select();
    this.maskEditor.addNode(this.getSplitterEnd());
    this.maskEditor.update_mask_form();
    return this;
  };

  MaskSplitterBegin.prototype.getSplitterEnd = function() {
    return new window[CUI.util.getObjectClass(this) + "End"]();
  };

  MaskSplitterBegin.prototype.getRowsToMove = function() {
    var e, fr, rows_to_move;
    try {
      fr = (new FieldsRendererTopLevel()).read(this.father.children);
      rows_to_move = fr.findField(this).getAllFields();
      rows_to_move = rows_to_move.filter((function(_this) {
        return function(row) {
          return !((typeof row.isSimpleSplit === "function" ? row.isSimpleSplit() : void 0) && row instanceof MaskSplitterEnd);
        };
      })(this));
    } catch (error) {
      e = error;
      console.error(e);
      rows_to_move = [];
    }
    return rows_to_move;
  };

  MaskSplitterBegin.prototype.moveRow = function(listView, target_node, after) {
    var fields, from_i, to_i;
    fields = this.getRowsToMove();
    from_i = this.getRowIdx();
    to_i = target_node.getRowIdx();
    listView.moveRow(from_i, to_i, after).done((function(_this) {
      return function() {
        var f, i, len, move_rows_i;
        from_i = _this.getRowIdx();
        move_rows_i = [];
        for (i = 0, len = fields.length; i < len; i++) {
          f = fields[i];
          move_rows_i.push(f.getRowIdx());
        }
        return CUI.chunkWork.call(_this, {
          items: move_rows_i.reverse(),
          chunk_size: 1,
          call: function(items) {
            var row_i;
            row_i = items[0];
            return listView.moveRow(row_i, from_i, true);
          }
        });
      };
    })(this));
    return this;
  };

  MaskSplitterBegin.prototype.getClass = function() {
    var cls;
    cls = MaskSplitterBegin.__super__.getClass.call(this);
    if (this.isSimpleSplit()) {
      cls += " mask-splitter-simple";
    }
    return cls;
  };

  return MaskSplitterBegin;

})(MaskSplitter);
// Generated by CoffeeScript 1.12.7
var MaskSplitterTabs,
  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;

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

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

  MaskSplitterTabs.prototype.splitterType = function() {
    return "tabs-begin";
  };

  MaskSplitterTabs.prototype.renderContent = function() {
    return this.renderNameInput();
  };

  MaskSplitterTabs.prototype.getFieldsRenderer = function(opts) {
    var options;
    if (opts == null) {
      opts = {};
    }
    options = this.getDataOptions();
    opts.mask_options = options;
    return new FieldsRendererTabs(opts);
  };

  MaskSplitterTabs.prototype.trashable = function() {
    return true;
  };

  MaskSplitterTabs.prototype.isVisible = function(mode, opts) {
    if (mode === "text") {
      return true;
    }
    return MaskSplitterTabs.__super__.isVisible.call(this, mode, opts);
  };

  MaskSplitterTabs.prototype.getOptions = function() {
    return [
      {
        type: CUI.Checkbox,
        text: $$("mask.splitter.option.hide_if_only_one_tab_available|label"),
        name: "hide_if_only_one_tab_available"
      }
    ];
  };

  MaskSplitterTabs.prototype.getDefaultOptions = function() {
    var options;
    options = {
      hide_if_only_one_tab_available: false
    };
    return options;
  };

  return MaskSplitterTabs;

})(MaskSplitterBegin);
// Generated by CoffeeScript 1.12.7
var MaskSplitterTab,
  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;

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

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

  MaskSplitterTab.prototype.isVisible = function(mode, opts) {
    if (mode === "text") {
      return true;
    }
    return MaskSplitterTab.__super__.isVisible.call(this, mode, opts);
  };

  MaskSplitterTab.prototype.splitterType = function() {
    return "tab";
  };

  MaskSplitterTab.prototype.renderContent = function() {
    return this.renderNameInput();
  };

  MaskSplitterTab.prototype.trashable = function() {
    var i, index, len, nextRow, nodeIndex, ref, row;
    ref = this.father.children;
    for (index = i = 0, len = ref.length; i < len; index = ++i) {
      row = ref[index];
      if (row === this) {
        nodeIndex = index;
        break;
      }
    }
    nextRow = this.father.children[nodeIndex + 1];
    if (nextRow instanceof MaskSplitterTabsEnd || nextRow instanceof MaskSplitterTab) {
      return true;
    }
    return false;
  };

  MaskSplitterTab.prototype.remove = function(force) {
    if (force == null) {
      force = false;
    }
    if (!this.trashable() && !force) {
      return;
    }
    return MaskSplitterTab.__super__.remove.call(this);
  };

  MaskSplitterTab.prototype.addToMaskEditor = function(maskEditor) {
    var tabs_row;
    this.maskEditor = maskEditor;
    tabs_row = this.maskEditor.mask_table.getSelectedNode();
    MaskSplitterTab.__super__.addToMaskEditor.call(this, this.maskEditor);
    this.maskEditor.mask_table.moveRow(this.getRowIdx(), tabs_row.getRowIdx(), true);
    return this;
  };

  return MaskSplitterTab;

})(MaskSplitter);
// Generated by CoffeeScript 1.12.7
var MaskSplitterBlock,
  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;

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

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

  MaskSplitterBlock.prototype.splitterType = function() {
    return "block-begin";
  };

  MaskSplitterBlock.prototype.isVisible = function(mode, opts) {
    if (mode === "text") {
      return true;
    }
    return MaskSplitterBlock.__super__.isVisible.call(this, mode, opts);
  };

  MaskSplitterBlock.prototype.nameLocalized = function() {
    return this.getDisplaynameLocalized();
  };

  MaskSplitterBlock.prototype.getFieldsRenderer = function(opts) {
    if (opts == null) {
      opts = {};
    }
    return new FieldsRendererBlock(opts);
  };

  return MaskSplitterBlock;

})(MaskSplitterBegin);
// Generated by CoffeeScript 1.12.7
var MaskSplitterPanel,
  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;

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

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

  MaskSplitterPanel.prototype.initOpts = function() {
    MaskSplitterPanel.__super__.initOpts.call(this);
    return this.addOpts({
      onClose: {
        check: Function
      },
      onOpen: {
        check: Function
      },
      render_fields_closed: {
        check: Boolean
      }
    });
  };

  MaskSplitterPanel.prototype.splitterType = function() {
    return "panel-begin";
  };

  MaskSplitterPanel.prototype.isVisible = function(mode, opts) {
    if (mode === "text") {
      return true;
    }
    return MaskSplitterPanel.__super__.isVisible.call(this, mode, opts);
  };

  MaskSplitterPanel.prototype.getOptions = function() {
    var options;
    options = [
      {
        form: {
          label: $$("mask.splitter.option.default_open_detail")
        },
        type: CUI.Checkbox,
        name: "default_open_detail"
      }, {
        form: {
          label: $$("mask.splitter.option.default_open_expert")
        },
        type: CUI.Checkbox,
        name: "default_open_expert"
      }, {
        form: {
          label: $$("mask.splitter.option.default_open_editor")
        },
        type: CUI.Checkbox,
        name: "default_open_editor"
      }, {
        form: {
          label: $$("mask.splitter.option.default_open_text_view")
        },
        type: CUI.Checkbox,
        name: "default_open_text_view"
      }, {
        form: {
          label: $$("mask.splitter.option.open_editor_with_content")
        },
        type: CUI.Checkbox,
        name: "open_editor_with_content"
      }
    ];
    if (ez5.version("6")) {
      options.push({
        form: {
          label: $$("mask.splitter.option.remember_panel_state")
        },
        type: CUI.Checkbox,
        name: "remember_panel_state"
      });
    }
    return options;
  };

  MaskSplitterPanel.prototype.getDefaultOptions = function() {
    var options;
    options = MaskSplitterPanel.__super__.getDefaultOptions.call(this);
    CUI.util.mergeMap(options, {
      default_open_detail: false,
      default_open_expert: false,
      default_open_editor: false,
      default_open_text_view: false,
      open_editor_with_content: false,
      remember_panel_state: false
    });
    return options;
  };

  MaskSplitterPanel.prototype.isClosed = function(opts) {
    var fieldDataOptions;
    fieldDataOptions = this.getData().options;
    if (opts.mode === "editor" && (fieldDataOptions != null ? fieldDataOptions.default_open_editor : void 0) || opts.mode === "detail" && (fieldDataOptions != null ? fieldDataOptions.default_open_detail : void 0) || opts.mode === "expert" && (fieldDataOptions != null ? fieldDataOptions.default_open_expert : void 0) || opts.mode === "text" && (fieldDataOptions != null ? fieldDataOptions.default_open_text_view : void 0)) {
      return false;
    } else {
      return true;
    }
  };

  MaskSplitterPanel.prototype.getFieldsRenderer = function(opts) {
    if (opts == null) {
      opts = {};
    }
    return new FieldsRendererPanel(opts);
  };

  MaskSplitterPanel.prototype.shouldRememberState = function() {
    var ref;
    return (ref = this.getData().options) != null ? ref.remember_panel_state : void 0;
  };

  MaskSplitterPanel.prototype.getPanelStateKey = function(maskName) {
    var splitterIdx;
    splitterIdx = this._data.options.splitterIdx;
    return "mask_panel_state_" + maskName + "_" + splitterIdx;
  };

  MaskSplitterPanel.prototype.onOpen = function() {
    return typeof this._onOpen === "function" ? this._onOpen() : void 0;
  };

  MaskSplitterPanel.prototype.onClose = function() {
    return typeof this._onClose === "function" ? this._onClose() : void 0;
  };

  return MaskSplitterPanel;

})(MaskSplitterBegin);
// Generated by CoffeeScript 1.12.7
var MaskSplitterPanelFixed,
  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;

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

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

  MaskSplitterPanelFixed.prototype.initOpts = function() {
    MaskSplitterPanelFixed.__super__.initOpts.call(this);
    return this.addOpts({
      closed: {
        check: Boolean
      },
      text: {
        mandatory: true,
        check: String
      },
      render_fields_closed: {
        check: Boolean
      }
    });
  };

  MaskSplitterPanelFixed.prototype.nameLocalized = function() {
    return this._text;
  };

  MaskSplitterPanelFixed.prototype.isClosed = function() {
    return this._closed === true;
  };

  return MaskSplitterPanelFixed;

})(MaskSplitterPanel);
// Generated by CoffeeScript 1.12.7
var MaskSplitterHead,
  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;

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

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

  MaskSplitterHead.prototype.splitterType = function() {
    return "head-begin";
  };

  MaskSplitterHead.prototype.getFieldsRenderer = function(opts) {
    if (opts == null) {
      opts = {};
    }
    return new FieldsRendererHead(opts);
  };

  MaskSplitterHead.prototype.addToMaskEditor = function(maskEditor) {
    MaskSplitterHead.__super__.addToMaskEditor.call(this, maskEditor);
    this.moveRow(maskEditor.mask_table, this.father.children[0], false);
    return this;
  };

  return MaskSplitterHead;

})(MaskSplitterBegin);
// Generated by CoffeeScript 1.12.7
var MaskSplitterHeadInternal,
  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;

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

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

  MaskSplitterHeadInternal.prototype.splitterType = function() {
    return "head-internal-begin";
  };

  MaskSplitterHeadInternal.prototype.getFieldsRenderer = function(opts) {
    if (opts == null) {
      opts = {};
    }
    return new FieldsRendererHeadInternal(opts);
  };

  return MaskSplitterHeadInternal;

})(MaskSplitterHead);
// Generated by CoffeeScript 1.12.7
var MaskSplitterHeadInternalEnd,
  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;

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

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

  MaskSplitterHeadInternalEnd.prototype.splitterType = function() {
    return "head-internal-end";
  };

  return MaskSplitterHeadInternalEnd;

})(MaskSplitterEnd);
// Generated by CoffeeScript 1.12.7
var MaskSplitterFooter,
  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;

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

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

  MaskSplitterFooter.prototype.splitterType = function() {
    return "footer-begin";
  };

  MaskSplitterFooter.prototype.getFieldsRenderer = function(opts) {
    if (opts == null) {
      opts = {};
    }
    return new FieldsRendererFooter(opts);
  };

  return MaskSplitterFooter;

})(MaskSplitterBegin);
// Generated by CoffeeScript 1.12.7
var CustomMaskSplitter,
  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;

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

  function CustomMaskSplitter(opts1) {
    this.opts = opts1;
    CustomMaskSplitter.__super__.constructor.call(this, this.opts);
    if (this.isSimpleSplit()) {
      this.moveRow = void 0;
    }
    return;
  }

  CustomMaskSplitter.prototype.isSimpleSplit = function() {
    return false;
  };

  CustomMaskSplitter.prototype.readOpts = function() {
    CustomMaskSplitter.__super__.readOpts.call(this);
    this.__type = CUI.util.toDash(this.__cls);
  };

  CustomMaskSplitter.prototype.remove = function() {
    if (this.isSimpleSplit()) {
      return MaskSplitter.prototype.remove.call(this);
    } else {
      return CustomMaskSplitter.__super__.remove.call(this);
    }
  };

  CustomMaskSplitter.prototype.addToMaskEditor = function(maskEditor) {
    this.maskEditor = maskEditor;
    if (this.isSimpleSplit()) {
      return MaskSplitter.prototype.addToMaskEditor.call(this, this.maskEditor);
    } else {
      return CustomMaskSplitter.__super__.addToMaskEditor.call(this, this.maskEditor);
    }
  };

  CustomMaskSplitter.prototype.getRowsToMove = function() {
    if (this.isSimpleSplit()) {
      return MaskSplitter.prototype.getRowsToMove.call(this, this.maskEditor);
    } else {
      return CustomMaskSplitter.__super__.getRowsToMove.call(this);
    }
  };

  CustomMaskSplitter.prototype.name = function() {
    return this.__type;
  };

  CustomMaskSplitter.prototype.storeType = function() {
    return this.__type;
  };

  CustomMaskSplitter.prototype.locaKey = function() {
    return this.__type.replace(/-/g, '.');
  };

  CustomMaskSplitter.prototype.nameLocalized = function() {
    return $$(this.locaKey() + ".name");
  };

  CustomMaskSplitter.prototype.renderOptionsDisplayPrefix = function() {
    return this.locaKey() + ".option.";
  };

  CustomMaskSplitter.prototype.splitterType = function() {
    return this.__type + "-begin";
  };

  CustomMaskSplitter.prototype.getOptions = function() {
    return [
      {
        type: CUI.Output,
        text: "Add options here"
      }
    ];
  };

  CustomMaskSplitter.prototype.getFieldToSave = function(opts) {
    opts = CUI.util.copyObject(this._data.options, true);
    opts.__customSplitterType = this.storeType();
    return {
      kind: "splitter",
      options: JSON.stringify(opts),
      type: "custom-begin"
    };
  };

  CustomMaskSplitter.prototype.renderContent = function() {
    this.renderOptions();
    return new LocaLabel({
      loca_key: this.locaKey() + ".title",
      appearance: "title"
    });
  };

  CustomMaskSplitter.prototype.getFieldsRenderer = function(opts) {
    if (opts == null) {
      opts = {};
    }
    return new CustomFieldsRenderer(opts);
  };

  CustomMaskSplitter.prototype.getSplitterEnd = function() {
    return new CustomMaskSplitterEnd({
      type: this.__type
    });
  };

  CustomMaskSplitter.prototype.renderField = function(opts) {
    var txt;
    txt = this.__type + ".renderField needs to be implemented";
    return this.__renderField(txt, opts);
  };

  CustomMaskSplitter.prototype.__renderField = function(txt, opts) {
    if (this.isSimpleSplit()) {
      return new CUI.Label({
        text: txt
      });
    }
    if (!this.hasContent(opts)) {
      return;
    }
    return new CUI.Block({
      text: txt,
      content: this.renderInnerFields(opts)
    });
  };

  CustomMaskSplitter.prototype.renderInnerFields = function(opts) {
    var div;
    div = CUI.dom.div();
    this.renderFields(opts, div);
    return div.children;
  };

  CustomMaskSplitter.prototype.hasContent = function(opts) {
    var ref;
    return (ref = this.__customFieldsRenderer) != null ? ref.hasContent.call(this.__customFieldsRenderer, opts) : void 0;
  };

  CustomMaskSplitter.prototype.renderFields = function(opts, div) {
    return this.__customFieldsRenderer.renderFields.call(this.__customFieldsRenderer, opts, div);
  };

  CustomMaskSplitter.prototype.setCustomFieldsRenderer = function(__customFieldsRenderer) {
    this.__customFieldsRenderer = __customFieldsRenderer;
  };

  CustomMaskSplitter.prototype.getCustomFieldsRenderer = function() {
    return this.__customFieldsRenderer;
  };

  return CustomMaskSplitter;

})(MaskSplitterBegin);

MaskSplitter.plugins = new CUI.PluginRegistry({
  "class": CustomMaskSplitter
});
// Generated by CoffeeScript 1.12.7
var CustomMaskSplitterEnd,
  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;

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

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

  CustomMaskSplitterEnd.prototype.initOpts = function() {
    CustomMaskSplitterEnd.__super__.initOpts.call(this);
    return this.addOpts({
      type: {
        check: String
      }
    });
  };

  CustomMaskSplitterEnd.prototype.readOpts = function() {
    CustomMaskSplitterEnd.__super__.readOpts.call(this);
    return this.__type = this._type;
  };

  CustomMaskSplitterEnd.prototype.storeType = function() {
    return this.__type;
  };

  CustomMaskSplitterEnd.prototype.splitterType = function() {
    return this._type + "-end";
  };

  CustomMaskSplitterEnd.prototype.getFieldToSave = function(opts) {
    var data;
    data = CustomMaskSplitter.prototype.getFieldToSave.call(this, opts);
    data.type = "custom-end";
    return data;
  };

  return CustomMaskSplitterEnd;

})(MaskSplitterEnd);
// Generated by CoffeeScript 1.12.7
var CustomMaskSplitterUnknown,
  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;

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

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

  CustomMaskSplitterUnknown.prototype.getOriginalCustomSplitterType = function() {
    var ref;
    return (ref = this.getDataOptions()) != null ? ref.__customSplitterType : void 0;
  };

  CustomMaskSplitterUnknown.prototype.isSimpleSplit = function(other_fields, actual_idx) {
    var field, fieldType, i, idx, myType, nest, ref, ref1;
    if (!other_fields) {
      return true;
    }
    myType = this.getOriginalCustomSplitterType();
    nest = 0;
    for (idx = i = ref = actual_idx + 1, ref1 = other_fields.length; ref <= ref1 ? i < ref1 : i > ref1; idx = ref <= ref1 ? ++i : --i) {
      field = other_fields[idx];
      if (field instanceof CustomMaskSplitterEndUnknown) {
        fieldType = field.getOriginalCustomSplitterType();
        if (fieldType === myType) {
          if (nest === 0) {
            return false;
          } else {
            nest--;
          }
        }
        continue;
      }
      if (field instanceof CustomMaskSplitterUnknown) {
        fieldType = field.getOriginalCustomSplitterType();
        if (fieldType === myType) {
          nest++;
        }
        continue;
      }
    }
    return true;
  };

  CustomMaskSplitterUnknown.prototype.remove = function() {
    var f, i, len, myType, rows;
    myType = this.getOriginalCustomSplitterType();
    rows = this.getRowsToMove();
    for (i = 0, len = rows.length; i < len; i++) {
      f = rows[i];
      if (f instanceof CustomMaskSplitterEndUnknown) {
        if (f.getOriginalCustomSplitterType() === myType) {
          f.remove(true);
          break;
        }
      }
    }
    return MaskSplitter.prototype.remove.call(this);
  };

  CustomMaskSplitterUnknown.prototype.getRowsToMove = function() {
    return MaskSplitterBegin.prototype.getRowsToMove.call(this);
  };

  CustomMaskSplitterUnknown.prototype.renderField = function(opts) {
    var div, innerFields, label, ref, storeType, txt;
    storeType = (ref = this.getDataOptions()) != null ? ref.__customSplitterType : void 0;
    txt = $$("custom.mask.splitter.type.not_found", {
      type: storeType
    });
    div = CUI.dom.element("div", {
      "class": "ez5-unknown-mask-splitter-block"
    });
    CUI.dom.setStyle(div, {
      padding: "10px",
      border: "2px solid #FE5824"
    });
    innerFields = this.renderInnerFields(opts);
    if ((innerFields != null ? innerFields.length : void 0) > 0 || opts.mode === "editor") {
      label = new CUI.Label({
        text: txt
      });
      CUI.dom.append(div, label.DOM);
      return CUI.dom.append(div, this.renderInnerFields(opts));
    }
    return this.__renderField(txt, opts);
  };

  CustomMaskSplitterUnknown.prototype.getFieldToSave = function(opts) {
    var ref, ref1;
    opts = CUI.util.copyObject(this._data.options, true);
    opts.__customSplitterType = ((ref = this._data) != null ? (ref1 = ref.options) != null ? ref1.__customSplitterType : void 0 : void 0) || this.storeType();
    return {
      kind: "splitter",
      options: JSON.stringify(opts),
      type: "custom-begin"
    };
  };

  return CustomMaskSplitterUnknown;

})(CustomMaskSplitter);
// Generated by CoffeeScript 1.12.7
var CustomMaskSplitterEndUnknown,
  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;

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

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

  CustomMaskSplitterEndUnknown.prototype.splitterType = function() {
    return "custom-mask-splitter-unknown-end";
  };

  CustomMaskSplitterEndUnknown.prototype.getOriginalCustomSplitterType = function() {
    var ref;
    return (ref = this.getDataOptions()) != null ? ref.__customSplitterType : void 0;
  };

  CustomMaskSplitterEndUnknown.prototype.trashable = function() {
    return true;
  };

  CustomMaskSplitterEndUnknown.prototype.remove = function() {
    var field, foundBegin, i, idx, myIdx, myType, nest, ref;
    myType = this.getOriginalCustomSplitterType();
    myIdx = this.father.children.indexOf(this);
    foundBegin = null;
    nest = 0;
    for (idx = i = ref = myIdx - 1; i >= 0; idx = i += -1) {
      field = this.father.children[idx];
      if (!field) {
        continue;
      }
      if (field instanceof CustomMaskSplitterEndUnknown) {
        if (field.getOriginalCustomSplitterType() === myType) {
          nest++;
        }
        continue;
      }
      if (field instanceof CustomMaskSplitterUnknown) {
        if (field.getOriginalCustomSplitterType() === myType) {
          if (nest === 0) {
            foundBegin = field;
            break;
          } else {
            nest--;
          }
        }
        continue;
      }
    }
    if (foundBegin) {
      MaskSplitter.prototype.remove.call(foundBegin);
    }
    return MaskSplitter.prototype.remove.call(this);
  };

  return CustomMaskSplitterEndUnknown;

})(CustomMaskSplitterEnd);
// Generated by CoffeeScript 1.12.7
var CustomFieldsRenderer,
  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;

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

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

  CustomFieldsRenderer.prototype.initOpts = function() {
    CustomFieldsRenderer.__super__.initOpts.call(this);
    return this.mergeOpt("field", {
      check: CustomMaskSplitter
    });
  };

  CustomFieldsRenderer.prototype.type = function() {
    return this._field.storeType();
  };

  CustomFieldsRenderer.prototype.render = function(opts) {
    this._field.setCustomFieldsRenderer(this);
    if (this._field.isSimpleSplit() && this._field.renderAsField()) {
      return this._field.renderSplitter(opts);
    }
    return this._field.renderField(opts);
  };

  CustomFieldsRenderer.prototype.isFieldAllowed = function(field) {
    return field instanceof FieldsRendererPlain || field instanceof FieldsRendererBlock || field instanceof CustomFieldsRenderer || field instanceof FieldsRendererPanel || field instanceof MaskSplitterPanelEnd || field instanceof ListViewEditTreeMaskRowNode || field instanceof MultipleFieldsContainer || field instanceof FieldsRendererSplit || field instanceof Field;
  };

  CustomFieldsRenderer.prototype.hasContent = function(opts) {
    if (this._field && this._field instanceof CustomMaskSplitter && this._field.getCustomFieldsRenderer() !== this) {
      return this._field.hasContent(opts);
    }
    return CustomFieldsRenderer.__super__.hasContent.call(this, opts);
  };

  return CustomFieldsRenderer;

})(FieldsRenderer);
// Generated by CoffeeScript 1.12.7
var MaskMemoryManager,
  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;

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

  function MaskMemoryManager() {
    MaskMemoryManager.__super__.constructor.call(this);
    this.__initPreferences();
  }

  MaskMemoryManager.prototype.__initPreferences = function() {
    if (!ez5.session.getPref("last_mask_global")) {
      ez5.session.setPref("last_mask_global", {});
    }
    if (!ez5.session.getPref("last_mask_detail_by_objecttype")) {
      ez5.session.setPref("last_mask_detail_by_objecttype", {});
    }
    if (!ez5.session.getPref("last_mask_editor_by_objecttype")) {
      return ez5.session.setPref("last_mask_editor_by_objecttype", {});
    }
  };

  MaskMemoryManager.prototype.getBestMask = function(object, mode, availableMasks) {
    var crossModeMask, crossModeMasks, detailMasks, editorMasks, globalMask, globalMasks, modeSpecificMask, modeSpecificMasks, objecttype;
    CUI.util.assert(object, "MaskMemoryManager.getBestMask", "object is required");
    CUI.util.assert(mode === "detail" || mode === "editor", "MaskMemoryManager.getBestMask", "mode must be 'detail' or 'editor'");
    CUI.util.assert(CUI.util.isArray(availableMasks), "MaskMemoryManager.getBestMask", "availableMasks must be an array");
    objecttype = object.objecttype();
    globalMasks = ez5.session.getPref("last_mask_global") || {};
    detailMasks = ez5.session.getPref("last_mask_detail_by_objecttype") || {};
    editorMasks = ez5.session.getPref("last_mask_editor_by_objecttype") || {};
    globalMask = globalMasks[objecttype];
    if (globalMask && this.__isMaskAvailable(globalMask, availableMasks, mode)) {
      return globalMask;
    }
    modeSpecificMasks = mode === "detail" ? detailMasks : editorMasks;
    modeSpecificMask = modeSpecificMasks[objecttype];
    if (modeSpecificMask && this.__isMaskAvailable(modeSpecificMask, availableMasks, mode)) {
      return modeSpecificMask;
    }
    crossModeMasks = mode === "detail" ? editorMasks : detailMasks;
    crossModeMask = crossModeMasks[objecttype];
    if (crossModeMask && this.__isMaskAvailable(crossModeMask, availableMasks, mode)) {
      return crossModeMask;
    }
    return object.getBestMaskName();
  };

  MaskMemoryManager.prototype.storeMask = function(objecttype, maskName, mode) {
    var globalMasks, modeMasks, prefKey;
    CUI.util.assert(CUI.util.isString(objecttype), "MaskMemoryManager.storeMask", "objecttype must be a string");
    CUI.util.assert(CUI.util.isString(maskName), "MaskMemoryManager.storeMask", "maskName must be a string");
    CUI.util.assert(mode === "detail" || mode === "editor", "MaskMemoryManager.storeMask", "mode must be 'detail' or 'editor'");
    globalMasks = ez5.session.getPref("last_mask_global") || {};
    globalMasks[objecttype] = maskName;
    ez5.session.setPref("last_mask_global", globalMasks);
    prefKey = mode === "detail" ? "last_mask_detail_by_objecttype" : "last_mask_editor_by_objecttype";
    modeMasks = ez5.session.getPref(prefKey) || {};
    modeMasks[objecttype] = maskName;
    ez5.session.setPref(prefKey, modeMasks);
    return ez5.session.savePrefs();
  };

  MaskMemoryManager.prototype.__isMaskAvailable = function(maskName, availableMasks, mode) {
    var i, len, mask;
    for (i = 0, len = availableMasks.length; i < len; i++) {
      mask = availableMasks[i];
      if (mask.name() === maskName) {
        if (mode === "detail") {
          return !mask.hideInDetail();
        } else if (mode === "editor") {
          return !mask.hideInEditor();
        }
      }
    }
    return false;
  };

  MaskMemoryManager.prototype.getLastMaskForMode = function(objecttype, mode) {
    var modeMasks, prefKey;
    prefKey = mode === "detail" ? "last_mask_detail_by_objecttype" : "last_mask_editor_by_objecttype";
    modeMasks = ez5.session.getPref(prefKey) || {};
    return modeMasks[objecttype];
  };

  MaskMemoryManager.prototype.clearAll = function() {
    ez5.session.setPref("last_mask_global", {});
    ez5.session.setPref("last_mask_detail_by_objecttype", {});
    ez5.session.setPref("last_mask_editor_by_objecttype", {});
    return ez5.session.savePrefs();
  };

  return MaskMemoryManager;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var AutocompletionPopup,
  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;

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

  function AutocompletionPopup(opts) {
    this.opts = opts;
    this.emptyContainer = bind(this.emptyContainer, this);
    AutocompletionPopup.__super__.constructor.call(this, this.opts);
    CUI.Events.listen({
      type: "mousedown",
      node: this.getLayer(),
      call: (function(_this) {
        return function(ev) {
          ev.preventDefault();
        };
      })(this)
    });
    CUI.Events.listen({
      type: "keydown",
      node: this.getLayer(),
      call: (function(_this) {
        return function(ev) {
          return _this.keydown(ev);
        };
      })(this)
    });
    CUI.Events.listen({
      type: "keyup",
      node: this.getLayer(),
      call: (function(_this) {
        return function(ev) {
          return _this.keyup(ev);
        };
      })(this)
    });
    this.__popupContent = new CUI.Template({
      name: "autocompletion-popup"
    });
    this.getLayer().append(this.__popupContent);
  }

  AutocompletionPopup.prototype.knownPlacements = ["s", "e", "w", "ws", "wn", "n", "se", "ne", "es", "en", "nw", "sw"];

  AutocompletionPopup.prototype.initOpts = function() {
    AutocompletionPopup.__super__.initOpts.call(this);
    this.mergeOpt("element", {
      mandatory: true
    });
    this.mergeOpt("use_element_width_as_min_width", {
      "default": true
    });
    this.removeOpt("handle_focus");
    return this.removeOpt("placements");
  };

  AutocompletionPopup.prototype.readOpts = function() {
    this.opts.placement = this.opts.placement || "se";
    this.opts.backdrop = {
      policy: "click"
    };
    AutocompletionPopup.__super__.readOpts.call(this);
    this._placements = ["se", "ne"];
    this._handle_focus = false;
    return this.container = {};
  };

  AutocompletionPopup.prototype.getPopupContent = function() {
    return this.__popupContent;
  };

  AutocompletionPopup.prototype.getPlacements = function() {
    return ["se", "sw", "ne", "nw"];
  };

  AutocompletionPopup.prototype.addContainer = function(name) {
    this.createContainer(name, "ez5-autocompletion-popup-container--" + (CUI.util.toCamel(name)));
    return this.__popupContent.append(this.container[name]);
  };

  AutocompletionPopup.prototype.addContainerAfter = function(name, afterName) {
    if (!this.container[afterName]) {
      return this.addContainer(name);
    }
    this.createContainer(name, "ez5-autocompletion-popup-container--" + (CUI.util.toCamel(name)));
    CUI.dom.insertAfter(this.container[afterName], this.container[name].DOM);
  };

  AutocompletionPopup.prototype.addContainerBefore = function(name, beforeName) {
    if (!this.container[beforeName]) {
      return this.addContainer(name);
    }
    this.createContainer(name, "ez5-autocompletion-popup-container--" + (CUI.util.toCamel(name)));
    CUI.dom.insertBefore(this.container[beforeName], this.container[name].DOM);
  };

  AutocompletionPopup.prototype.createContainer = function(name, cls) {
    this.container[name] = new CUI.Template({
      name: "autocompletion-popup-container",
      "class": cls
    });
    CUI.dom.setAttribute(this.container[name].DOM, "ui", "autocompletion.popup.container:" + name);
    CUI.dom.data(this.container[name].DOM, "name", name);
    return this.container[name];
  };

  AutocompletionPopup.prototype.emptyContainer = function(regex) {
    var child, cn, i, len, name, ref;
    if (regex == null) {
      regex = null;
    }
    if (this.getActiveItem()) {
      this.__hadFocus = true;
    }
    for (name in this.container) {
      if (!regex || name.match(regex)) {
        ref = CUI.dom.matchSelector(this.container[name].DOM, ".cui-tmpl-autocompletion-popup-container");
        for (i = 0, len = ref.length; i < len; i++) {
          child = ref[i];
          cn = CUI.dom.data(child, "name");
          delete this.container[cn];
        }
        CUI.dom.empty(this.container[name].DOM);
      }
    }
    return this.container[name];
  };

  AutocompletionPopup.prototype.getContainer = function(name) {
    return this.container[name];
  };

  AutocompletionPopup.prototype.appendItem = function(name, content) {
    return this.__addItem(name, content);
  };

  AutocompletionPopup.prototype.prependItem = function(name, content) {
    return this.__addItem(name, content, true);
  };

  AutocompletionPopup.prototype.__addItem = function(name, content, prepend) {
    var item, ref;
    if (prepend == null) {
      prepend = false;
    }
    item = new CUI.Template({
      name: "autocompletion-popup-item"
    });
    item.append(content);
    CUI.dom.setAttribute((ref = this.container[name]) != null ? ref.DOM : void 0, "ui", "autocompletion.popup.container.item:" + name);
    if (prepend) {
      this.container[name].prepend(item);
    } else {
      this.container[name].append(item);
    }
    return item;
  };

  AutocompletionPopup.prototype.show = function() {
    var items;
    if (!CUI.util.$elementIsInDOM(this.getElement())) {
      this.destroy();
    } else {
      AutocompletionPopup.__super__.show.call(this);
    }
    if (this.__hadFocus) {
      this.__hadFocus = false;
      items = this.getItems();
      CUI.dom.focus(items[0]);
    }
  };

  AutocompletionPopup.prototype.getItems = function() {
    return CUI.dom.matchSelector(this.DOM, "[tabindex]");
  };

  AutocompletionPopup.prototype.removeItems = function() {
    var i, item, items, len, results;
    items = this.getItems();
    results = [];
    for (i = 0, len = items.length; i < len; i++) {
      item = items[i];
      results.push(CUI.dom.remove(item));
    }
    return results;
  };

  AutocompletionPopup.prototype.keydown = function(ev) {
    var activate, active, activeIdx, focusableElement, items, ref;
    if ((ref = ev.keyCode()) !== 38 && ref !== 40) {
      return;
    }
    ev.preventDefault();
    items = this.getItems();
    if (!items.length) {
      this.hide();
      return;
    }
    active = this.getActiveItem();
    if (active) {
      activeIdx = this.getActiveItemIdx();
    }
    if (ev.keyCode() === 40) {
      if (!this.isShown()) {
        this.show();
      } else if (active) {
        if (activeIdx >= 0 && activeIdx < items.length - 1) {
          activate = activeIdx + 1;
        }
      } else {
        activate = 0;
      }
    }
    if (ev.keyCode() === 38) {
      if (!active) {
        return;
      }
      activate = activeIdx - 1;
    }
    if (activate >= 0 && activate < items.length) {
      CUI.dom.blur(this._element);
      CUI.dom.focus(items[activate]);
    } else if (activate === -1) {
      focusableElement = CUI.dom.matchSelector(this._element, "input, [tabindex]", true)[0];
      if (focusableElement) {
        CUI.dom.blur(active);
        CUI.dom.focus(focusableElement);
      }
    }
  };

  AutocompletionPopup.prototype.keyup = function(ev) {
    var ref;
    if (!this.isShown()) {
      return;
    }
    switch (ev.keyCode()) {
      case 13:
        if (this.getActiveItem()) {
          CUI.Events.trigger({
            node: this.getActiveItem(),
            type: "click"
          });
        }
        break;
      case 27:
        if ((ref = this.getActiveItem()) != null) {
          ref.blur();
        }
        CUI.dom.focus(this._element);
        this.hide();
        ev.stopPropagation();
    }
  };

  AutocompletionPopup.prototype.getActiveItemIdx = function() {
    var active, i, idx, item, items, len;
    items = this.getItems();
    active = this.getActiveItem();
    for (idx = i = 0, len = items.length; i < len; idx = ++i) {
      item = items[idx];
      if (item === active) {
        return idx;
      }
    }
    return -1;
  };

  AutocompletionPopup.prototype.getActiveItem = function() {
    var active;
    active = CUI.dom.matchSelector(this.DOM, ":focus")[0];
    if (!active) {
      active = CUI.dom.matchSelector(this.DOM, ".cui-selected")[0];
      if (active) {
        CUI.dom.removeClass(active, "cui-selected");
        CUI.dom.focus(active);
      }
    }
    return active;
  };

  return AutocompletionPopup;

})(CUI.Layer);
// Generated by CoffeeScript 1.12.7
var ObjectList,
  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;

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

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

  ObjectList.chunkSize = 50;

  ObjectList.prototype.initOpts = function() {
    ObjectList.__super__.initOpts.call(this);
    return this.addOpts({
      remove_button_per_object: {
        "default": false,
        check: Boolean
      },
      onRemove: {
        check: Function
      }
    });
  };

  ObjectList.prototype.readOpts = function() {
    ObjectList.__super__.readOpts.call(this);
    this.count = 0;
    this.objects = [];
    this.current_idx = null;
    return this.toolboxCallbacks = [];
  };

  ObjectList.prototype.getCount = function(skip_template) {
    var c, i, len, obj, ref;
    if (skip_template == null) {
      skip_template = false;
    }
    if (!skip_template) {
      return this.objects.length;
    } else {
      c = 0;
      ref = this.objects;
      for (i = 0, len = ref.length; i < len; i++) {
        obj = ref[i];
        if (!(obj instanceof TemplateObject)) {
          c++;
        }
      }
      return c;
    }
  };

  ObjectList.prototype.getCountWithoutTemplate = function() {
    return this.getCount(true);
  };

  ObjectList.prototype.getTemplateIdx = function() {
    var i, idx, len, obj, ref;
    ref = this.objects;
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      obj = ref[idx];
      if (obj instanceof TemplateObject) {
        return idx;
      }
    }
    return null;
  };

  ObjectList.prototype.idxByData = function(data) {
    var i, idx, len, obj, ref;
    ref = this.objects;
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      obj = ref[idx];
      if (obj.getData() === data) {
        return idx;
      }
    }
    return -1;
  };

  ObjectList.prototype.remove = function(idx, keepFocus, callEvent) {
    var current_object_focus, obj;
    if (idx == null) {
      idx = this.current_idx;
    }
    if (keepFocus == null) {
      keepFocus = false;
    }
    if (callEvent == null) {
      callEvent = true;
    }
    if (keepFocus) {
      current_object_focus = this.getObject(this.current_idx);
      if (this.current_idx === idx) {
        keepFocus = false;
      }
    }
    obj = this.objects.splice(idx, 1);
    if (this.browserDiv) {
      this.removeObjectFromBrowser(idx);
    }
    if (!keepFocus) {
      this.setCurrentIdx(idx - 1);
    } else {
      this.setCurrentIdx(this.getObjectIdx(current_object_focus));
    }
    if (this._onRemove && callEvent) {
      this._onRemove(obj, idx);
    }
    return obj;
  };

  ObjectList.prototype.removeAll = function() {
    this.objects = [];
    this.setCurrentIdx(null);
  };

  ObjectList.prototype.push = function(ro) {
    var offset;
    CUI.util.assert(ro instanceof ResultObject, "ObjectList.push", "Object must be instance of ResultObject.", {
      resultObject: ro
    });
    this.objects.push(ro);
    if (this.browserDiv) {
      offset = Math.floor((this.getCountWithoutTemplate() - 1) / ObjectList.chunkSize) * ObjectList.chunkSize;
      if (this.getTemplateIdx() !== null) {
        offset = offset + 1;
      }
      if (offset === this.getStartIdx()) {
        this.appendObjectToBrowser(this.getCount() - 1);
      }
    }
    return this;
  };

  ObjectList.prototype.getObjectIdx = function(ro) {
    return CUI.util.idxInArray(ro, this.objects);
  };

  ObjectList.prototype.getObject = function(idx) {
    if (idx == null) {
      idx = this.current_idx;
    }
    if (idx >= this.objects.length) {
      return this.objects[this.objects.length - 1];
    }
    return this.objects[idx];
  };

  ObjectList.prototype.getObjects = function() {
    return this.objects;
  };

  ObjectList.prototype.setObject = function(obj, idx) {
    if (idx == null) {
      idx = this.current_idx;
    }
    this.objects[idx] = obj;
    return obj;
  };

  ObjectList.prototype.getCurrentIdx = function() {
    return this.current_idx;
  };

  ObjectList.prototype.focusObject = function(object) {
    return this.setCurrentIdx(this.getObjectIdx(object));
  };

  ObjectList.prototype.setCurrentIdx = function(idx) {
    if (!CUI.util.isNull(idx)) {
      idx = parseInt(idx);
      CUI.util.assert(!isNaN(idx), (CUI.util.getObjectClass(this)) + ".setCurrentIdx", "idx is not null and not an integer", {
        idx: idx
      });
    } else {
      idx = null;
    }
    if (this.getCount() === 0 || idx === null) {
      this.current_idx = null;
    } else if (idx < 0) {
      this.current_idx = 0;
    } else if (idx >= this.getCount()) {
      this.current_idx = this.getCount() - 1;
    } else {
      this.current_idx = idx;
    }
    this.focusCurrent();
    return this.current_idx;
  };

  ObjectList.prototype.focusCurrent = function() {
    var el, i, len, ref;
    if (!this.browserDiv) {
      return;
    }
    ref = CUI.dom.matchSelector(this.__verticalLayout, "." + ez5.defaults.focusClass);
    for (i = 0, len = ref.length; i < len; i++) {
      el = ref[i];
      el.classList.remove(ez5.defaults.focusClass);
    }
    if (this.getCurrentIdx() === null) {
      return;
    }
    return CUI.dom.addClass(this.findObjectInBrowser(), ez5.defaults.focusClass);
  };

  ObjectList.prototype.renderBrowser = function() {
    this.browserDiv = CUI.dom.div("ez5-object-list result-standard-format-square");
    this.templateDiv = CUI.dom.div("ez5-object-list result-standard-format-square ez5-object-list-template");
    this.__verticalLayout = new CUI.VerticalLayout({
      top: {
        content: this.templateDiv
      },
      center: {
        content: this.browserDiv
      }
    });
    return this.__verticalLayout;
  };

  ObjectList.prototype.appendObjectToBrowser = function(idx) {
    var div, object;
    object = this.getObject(idx);
    div = CUI.dom.div("ez5-object-list-object");
    CUI.dom.setAttribute(div, "ui", "object.list.object:" + idx);
    if (object instanceof TemplateObject) {
      CUI.dom.append(this.templateDiv, div);
    } else {
      CUI.dom.append(this.browserDiv, div);
      CUI.dom.setAttribute(this.browserDiv, "data-object-count", this.getCountWithoutTemplate());
    }
    CUI.dom.setAttribute(div, "idx", idx);
    return this.appendToDivInBrowser(div, object);
  };

  ObjectList.prototype.findObjectInBrowser = function(idx) {
    var ref;
    if (idx == null) {
      idx = this.getCurrentIdx();
    }
    if (!this.browserDiv) {
      return;
    }
    return (ref = CUI.dom.matchSelector(this.__verticalLayout, "div[idx=\"" + idx + "\"]")) != null ? ref[0] : void 0;
  };

  ObjectList.prototype.updateObjectInBrowser = function(idx) {
    var div, object;
    if (idx == null) {
      idx = this.getCurrentIdx();
    }
    if (!this.browserDiv) {
      return;
    }
    div = this.findObjectInBrowser(idx);
    if (!div) {
      return;
    }
    CUI.dom.empty(div);
    object = this.getObject(idx);
    if (!object) {
      return;
    }
    return this.appendToDivInBrowser(div, object);
  };

  ObjectList.prototype.getStartIdx = function() {
    if (!this.browserDiv) {
      return 0;
    }
    return parseInt(CUI.dom.getAttribute(this.browserDiv, "data-start-idx"));
  };

  ObjectList.prototype.removeObjectFromBrowser = function(idx) {
    var count, d, div, i, last_idx, len, ref, start_idx;
    div = this.findObjectInBrowser(idx);
    if (!div) {
      return;
    }
    CUI.dom.remove(div);
    start_idx = this.getStartIdx();
    count = 0;
    last_idx = null;
    ref = this.browserDiv.children;
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      d = ref[idx];
      count = count + 1;
      last_idx = idx + start_idx;
      CUI.dom.setAttribute(d, "idx", idx + start_idx);
    }
    if (count < ObjectList.chunkSize) {
      if (last_idx < this.getCount() - 1) {
        this.appendObjectToBrowser(last_idx + 1);
      }
    }
    CUI.dom.setAttribute(this.browserDiv, "data-object-count", this.getCountWithoutTemplate());
    return div;
  };

  ObjectList.prototype.appendToDivInBrowser = function(div, object) {
    var card, remove_btn;
    remove_btn = null;
    if (this._remove_button_per_object) {
      remove_btn = new LocaButton({
        loca_key: "editor.modal.new.remove-button",
        ui: "editor.modal.file.remove.button",
        appearance: "flat",
        size: "mini",
        onClick: (function(_this) {
          return function(ev) {
            return _this.remove(_this.getObjectIdx(object), true);
          };
        })(this)
      });
    }
    card = object.renderCardStandard({
      tags: true,
      show_hourglass: false,
      extra_button: remove_btn
    });
    CUI.dom.addClass(card, "ez5-editor-object-list-card");
    return CUI.dom.append(div, card);
  };

  ObjectList.prototype.toggleRemoveButtons = function(enable) {
    var i, len, object, ref, results;
    if (!this._remove_button_per_object) {
      return;
    }
    ref = this.objects || [];
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      object = ref[i];
      if (object.__extra_button == null) {
        continue;
      }
      results.push(object.__extra_button.setEnabled(enable));
    }
    return results;
  };

  ObjectList.prototype.updateBrowserWithNavigation = function(offset) {
    var endIndex, i, idx, ref, ref1, startIndex, templateIdx;
    if (offset == null) {
      offset = 0;
    }
    CUI.dom.empty(this.browserDiv);
    templateIdx = this.getTemplateIdx();
    if (templateIdx !== null) {
      CUI.dom.empty(this.templateDiv);
      this.appendObjectToBrowser(templateIdx);
      startIndex = offset + 1;
      endIndex = offset + ObjectList.chunkSize + 1;
    } else {
      startIndex = offset;
      endIndex = offset + ObjectList.chunkSize;
    }
    if (endIndex > this.getCount()) {
      endIndex = this.getCount();
    }
    CUI.dom.setAttribute(this.browserDiv, "data-start-idx", startIndex);
    for (idx = i = ref = startIndex, ref1 = endIndex; ref <= ref1 ? i < ref1 : i > ref1; idx = ref <= ref1 ? ++i : --i) {
      this.appendObjectToBrowser(idx);
    }
    this.focusCurrent();
    return this.__verticalLayout;
  };

  return ObjectList;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var ResultManagerResult,
  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;

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

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

  ResultManagerResult.prototype.initOpts = function() {
    ResultManagerResult.__super__.initOpts.call(this);
    return this.addOpts({
      pane_absolute: {
        "default": true,
        check: Boolean
      },
      container: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isElement(v);
        }
      },
      ui: {
        check: String
      },
      navigation_buttons_left: {
        check: Array
      },
      allowTopLevelPlaceholder: {
        "default": false,
        check: Boolean
      },
      selectable_opts: {
        check: CollectionSelection.selectableOptsCheck()
      },
      tree_opts: {
        check: "PlainObject"
      }
    });
  };

  ResultManagerResult.prototype.getNavigation = function() {};

  ResultManagerResult.prototype.initSelectable = function(object_selector, container) {
    var sel_opts;
    if (!this._selectable_opts) {
      return;
    }
    sel_opts = CUI.util.copyObject(this._selectable_opts);
    delete sel_opts.collection;
    sel_opts.object_selector = object_selector;
    sel_opts.container = container;
    if (this.getNavigation()) {
      sel_opts.onUpdate = (function(_this) {
        return function(col) {
          var bb, btns, count, lbl;
          if (col.getCount() > 0) {
            btns = [];
            count = ez5.format_number(col.getCount());
            lbl = new LocaLabel({
              loca_key: "result.manager.result.selected_objects",
              loca_key_attrs: {
                count: count
              }
            });
            btns.push(lbl);
            btns.push(new LocaButton({
              loca_key: "result.manager.result.selected_objects_remove",
              size: "mini",
              onClick: function() {
                return col.removeObjects();
              }
            }));
            bb = new CUI.Buttonbar({
              "class": "ez5-selected-objects-badge ez5-navigation-selected-objects-count",
              buttons: btns
            });
            return _this.getNavigation().replace(bb, "center");
          } else {
            return _this.getNavigation().empty("center");
          }
        };
      })(this);
    }
    this._selectable_opts.collection.setSelectableContainer(sel_opts);
    if (typeof sel_opts.onInit === "function") {
      sel_opts.onInit(object_selector, container);
    }
    return this;
  };

  ResultManagerResult.prototype.initSelectableCollection = function() {
    var ref;
    return (ref = this._selectable_opts) != null ? ref.collection.triggerEvent("select") : void 0;
  };

  ResultManagerResult.prototype.getCollectionSelection = function() {
    var ref;
    return (ref = this._selectable_opts) != null ? ref.collection : void 0;
  };

  ResultManagerResult.prototype.addToResultDiv = function(request, result_object, div) {
    var info_btn;
    ResultManagerResult.__super__.addToResultDiv.call(this, request, result_object, div);
    info_btn = new LocaButton({
      "class": "ez5-result-standard-info-button",
      appearance: "flat",
      size: "mini",
      loca_key: "result.manager.result.info_button",
      onClick: (function(_this) {
        return function() {
          return new CUI.Tooltip({
            "class": "ez5-result-standard-tooltip-info",
            element: info_btn,
            on_hover: false,
            on_click: false,
            backdrop: {
              policy: "click"
            },
            content: function() {
              return result_object.renderCardStandard();
            }
          }).show();
        };
      })(this)
    });
    CUI.dom.append(div, info_btn.DOM);
  };

  ResultManagerResult.prototype.hasSearchInput = function(request, excludedSearchManager) {
    if (excludedSearchManager == null) {
      excludedSearchManager = [];
    }
    return this.getSearch().hasUserInput(request, excludedSearchManager);
  };

  ResultManagerResult.prototype.hasPoolFilter = function() {
    var ref, searchTypeSelector;
    searchTypeSelector = (ref = this.getSearch()) != null ? typeof ref.getSearchTypeSelector === "function" ? ref.getSearchTypeSelector() : void 0 : void 0;
    if (!searchTypeSelector) {
      return false;
    }
    return searchTypeSelector.hasPoolFilter();
  };

  ResultManagerResult.prototype.readOpts = function() {
    ResultManagerResult.__super__.readOpts.call(this);
    this.result_container = this._container;
    if (ez5.session.isDebug() && this.result_container && !this.result_container._debug_registered) {
      this.result_container._debug_registered = true;
      CUI.Events.listen({
        node: this.result_container,
        type: "toolbox",
        selector: "[global-object-id]",
        call: function(ev, info) {
          var data, more, sid;
          data = CUI.dom.data(ev.getCurrentTarget());
          if (!data.object) {
            return;
          }
          sid = data.object._system_object_id;
          if (sid) {
            more = " [" + sid + "]";
          } else {
            more = "";
          }
          info.tools.push(new ToolboxTool({
            group: "object",
            name: "object.dump",
            sort: "I:1",
            loca_key: "base.debug.to.console",
            loca_key_attrs: {
              more: more
            },
            run: (function(_this) {
              return function(ev) {
                return console.info("object DUMP. request:", data.request, "data", data);
              };
            })(this)
          }));
        }
      });
    }
    return this;
  };

  ResultManagerResult.prototype.getResultContainer = function() {
    return this.result_container;
  };

  ResultManagerResult.prototype.getName = function() {
    return CUI.util.assert(false, CUI.util.getObjectClass(this) + ".getName needs implementation");
  };

  ResultManagerResult.prototype.setData = function() {};

  ResultManagerResult.prototype.getViewFields = function() {
    return [];
  };

  ResultManagerResult.prototype.destroy = function() {
    this.deinitSelectable();
    return ResultManagerResult.__super__.destroy.call(this);
  };

  ResultManagerResult.prototype.deinitSelectable = function() {
    var ref;
    return (ref = this._selectable_opts) != null ? ref.collection.unsetSelectableContainer() : void 0;
  };

  ResultManagerResult.prototype.getViewDataDefault = function() {
    return {};
  };

  ResultManagerResult.prototype.initView = function(form) {};

  ResultManagerResult.prototype.updateView = function(form) {};

  ResultManagerResult.prototype.saveViewDone = function() {
    return CUI.resolvedPromise();
  };

  ResultManagerResult.prototype.allowExpandHierarchy = function() {
    return true;
  };

  return ResultManagerResult;

})(SearchManager);
// Generated by CoffeeScript 1.12.7
var ResultDynamic,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  ResultDynamic.prototype.initOpts = function() {
    ResultDynamic.__super__.initOpts.call(this);
    return this.addOpts({
      container: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isElement(v);
        }
      },
      page_size: {
        check: "Integer"
      }
    });
  };

  ResultDynamic.prototype.readOpts = function() {
    ResultDynamic.__super__.readOpts.call(this);
    if (this._page_size) {
      this.__page_size = this._page_size;
    }
    return this.setData();
  };

  ResultDynamic.prototype.__page_size = 100;

  ResultDynamic.prototype.getNavigation = function() {
    return this.__navi;
  };

  ResultDynamic.prototype.init = function() {
    var base, resultContainer, scheduleResize, welcome_message;
    ResultDynamic.__super__.init.call(this);
    this.__navi = new ResultNavigationToolbar({
      "class": "ez5-result-dynamic-navigation-toolbar",
      search: this.getSearch(),
      navigation_buttons_left: this._navigation_buttons_left,
      getPageSize: (function(_this) {
        return function() {
          return _this.getRequestPageSize();
        };
      })(this)
    });
    this.__pane = new CUI.Pane({
      "class": "ez5-result-dynamic-pane ez5-result-dynamic-pane-" + this.getRenderType(),
      absolute: this._pane_absolute,
      center: {
        "class": "ez5-result-dynamic-pane-center",
        ui: this._ui
      },
      bottom: {
        content: this.__navi
      }
    });
    this.__pane.center().setAttribute('tabindex', '-1');
    resultContainer = this.getResultContainer();
    CUI.dom.empty(resultContainer);
    CUI.dom.append(resultContainer, this.__pane.DOM);
    this.__standardDummy = this.__buildStandardDummy();
    CUI.dom.append(this.__pane.bottom(), this.__standardDummy);
    welcome_message = typeof (base = this.getSearch()).getWelcomeMessagesDiv === "function" ? base.getWelcomeMessagesDiv(true) : void 0;
    CUI.dom.append(this.__pane.center(), welcome_message);
    this.__objects = this.__pane.center();
    this.__loader = new ResultDynamicLoading({
      container: this.__objects,
      search: this.getSearch()
    });
    this.__current = {
      offset: null,
      pageSize: null,
      autoPageSize: false,
      page: null
    };
    scheduleResize = (function(_this) {
      return function() {
        return _this.__scheduleViewportResize();
      };
    })(this);
    CUI.Events.listen({
      type: "viewport-resize",
      node: this.__pane,
      call: (function(_this) {
        return function(ev) {
          if (CUI.__ng__) {
            return scheduleResize();
          } else {
            return CUI.scheduleCallback({
              call: scheduleResize,
              ms: 200
            });
          }
        };
      })(this)
    });
    return this;
  };

  ResultDynamic.prototype.__scheduleViewportResize = function() {
    var page;
    if (!this.__loader) {
      return;
    }
    if (this.__current.autoPageSize && this.__current.pageSize !== this.calcPageSize()) {
      page = Math.floor(this.__current.offset / this.calcPageSize());
      return this.__navi.loadPage(page);
    } else {
      this.__updateFillViewLayout();
      return this.__loader.markLoadMe();
    }
  };

  ResultDynamic.prototype.destroy = function() {
    var ref, ref1, ref2;
    if ((ref = this.__loader) != null) {
      ref.destroy();
    }
    this.__loader = null;
    if ((ref1 = this.__navi) != null) {
      ref1.destroy();
    }
    this.__navi = null;
    if ((ref2 = this.__pane) != null) {
      ref2.destroy();
    }
    this.__pane = null;
    return ResultDynamic.__super__.destroy.call(this);
  };

  ResultDynamic.prototype.unsetSearch = function() {
    ResultDynamic.__super__.unsetSearch.call(this);
    CUI.dom.empty(this.__objects);
    return this.destroyWaitBlock();
  };

  ResultDynamic.prototype.updateView = function(form) {
    var page;
    if (this.view_data.page_size === "auto" && this.__current.pageSize !== this.calcPageSize()) {
      page = Math.floor(this.__current.offset / this.calcPageSize());
      this.__navi.loadPage(page);
    } else if ((this.view_data.page_size !== "auto" && this.__current.autoPageSize) || (this.__current.pageSize !== this.getRequestPageSize())) {
      page = Math.floor(this.__current.offset / this.view_data.page_size);
      this.__navi.loadPage(page);
    } else {
      this.__updateFillViewLayout();
      this.__loader.markLoadMe();
    }
    return CUI.Events.trigger({
      type: "result-dynamic-update-view",
      node: this.__pane
    });
  };

  ResultDynamic.prototype.setData = function(view_data) {
    var i, k, len1, ref, ref1;
    this.view_data = view_data != null ? view_data : {};
    ref = ["page_size"];
    for (i = 0, len1 = ref.length; i < len1; i++) {
      k = ref[i];
      if (CUI.util.isUndef(this.view_data[k])) {
        this.view_data[k] = this["__" + k];
      }
    }
    if (ref1 = this.view_data.page_size, indexOf.call(this.getPageSizes(), ref1) < 0) {
      this.view_data.page_size = this.__page_size;
    }
    return this;
  };

  ResultDynamic.prototype.getLoader = function() {
    return this.__loader;
  };

  ResultDynamic.prototype.getPageSizes = function() {
    if (ez5.session.isDebug()) {
      return [1, 2, 3, 5, 10, 20, 50, 100, 250, 500, 1000];
    } else {
      return [10, 25, 50, 100, 250, 500, 1000];
    }
  };


  /*
  	filterTopLevel: (request) ->
  		if not @searchHasObjecttypes()
  			false
  		else if @view_data['show_hierarchy']
  			false
  		else
  			true
   */

  ResultDynamic.prototype.searchHasObjecttypes = function() {
    return !(this.getSearch() instanceof SearchCollection);
  };

  ResultDynamic.prototype.getViewFields = function() {
    var fields, i, len1, o, page_sizes, size_opts;
    page_sizes = this.getPageSizes();
    size_opts = [];
    for (i = 0, len1 = page_sizes.length; i < len1; i++) {
      o = page_sizes[i];
      if (o === "auto") {
        size_opts.push({
          text: $$("result.dynamic.page_size.auto"),
          value: o
        });
      } else {
        size_opts.push({
          text: o + "",
          value: o
        });
      }
    }
    fields = [];

    /*
    		if @searchHasObjecttypes()
    			for ot in @getSearch().getSearchObjecttypes(false)
    				if ot.isHierarchy()
    					fields.push
    						type: CUI.Checkbox
    						form: label: $$("result.dynamic.view.show_hierarchy")
    						name: 'show_hierarchy'
    					break
     */
    fields.push({
      type: CUI.Select,
      form: {
        label: $$("result.dynamic.page_size")
      },
      name: "page_size",
      options: size_opts
    });
    return fields;
  };

  ResultDynamic.prototype.calcPageSize = function() {
    var d, dim, pageSize, remove_d, viewport;
    d = this.__current.first_result_div;
    if (!d) {
      d = CUI.dom.div("result-dynamic placeholder " + this.getName());
      CUI.dom.append(this.__objects, d);
      remove_d = true;
    } else {
      remove_d = false;
    }
    dim = {
      width: CUI.dom.getDimensions(d).marginBoxWidth,
      height: CUI.dom.getDimensions(d).marginBoxHeight
    };
    viewport = {
      width: CUI.dom.width(this.__objects),
      height: CUI.dom.height(this.__objects)
    };
    CUI.util.assert(dim.width * dim.height > 0, "ResultDynamic.calcPageSize", "Object dim has a width or height eq 0.", {
      dim: dim,
      viewport: viewport,
      element: d
    });
    if (viewport.width === 0 || viewport.height === 0) {
      pageSize = 10;
    } else {
      pageSize = Math.max(10, Math.floor(viewport.width / dim.width) * Math.floor(viewport.height / dim.height));
    }
    if (remove_d) {
      d.remove();
    }
    return pageSize;
  };

  ResultDynamic.prototype.getRequestPageSize = function() {
    if (this.view_data.page_size === "auto") {
      return this.calcPageSize();
    } else {
      return this.view_data.page_size;
    }
  };

  ResultDynamic.prototype.addToRequest = function(request) {
    request.limit = this.getRequestPageSize();
    if (request.offset < 0) {
      request.offset = 0;
    }
    if (request.offset % request.limit !== 0) {
      request.offset = Math.floor(request.offset / request.limit) * request.limit;
    }
    request.format = "standard";
    if (request.execute) {
      this.deinitSelectable();
      CUI.util.assert(!this.__waitBlock, "ResultDynamic.addRequest", "wait block is already there");
      this.__waitBlock = new CUI.WaitBlock({
        element: this.getResultContainer()
      });
      if (!request.avoid_wait_block) {
        this.__waitBlock.show();
      }
    }
    return this;
  };

  ResultDynamic.prototype.failResult = function() {
    return this.destroyWaitBlock();
  };

  ResultDynamic.prototype.renderObject = function(o, offset) {};

  ResultDynamic.prototype.getRenderType = function() {
    return "standard";
  };

  ResultDynamic.prototype.destroyWaitBlock = function() {
    var ref;
    if ((ref = this.__waitBlock) != null) {
      ref.destroy();
    }
    return delete this.__waitBlock;
  };

  ResultDynamic.prototype.saveViewDone = function() {

    /*
    		if @view_data['show_hierarchy'] != @__show_hierarchy
    			@getSearch().execute()
    		else
    			return CUI.resolvedPromise()
     */
    return CUI.resolvedPromise();
  };

  ResultDynamic.prototype.showResult = function(request, data) {
    var _k, c, chunk, chunk_no, divScrollIntoView, el, finish_render, grouping_badges, i, idx, j, len, len1, len2, object_reload_store, ref, ref1, ref2, render_next_chunk, render_one_object, shc, sk, sort_keys, tempContainer;
    if (!this.__pane || this.__pane.isDestroyed()) {
      return;
    }
    tempContainer = CUI.dom.div();
    if (request.update) {
      ref = this.__objects.children;
      for (i = 0, len1 = ref.length; i < len1; i++) {
        el = ref[i];
        CUI.dom.setAttribute(el, "remove-me", 1);
      }
      object_reload_store = {};
      ref1 = CUI.dom.children(this.__objects, ".result-dynamic:not(.placeholder):not([loading=\"1\"]):not([load-me=\"1\"])");
      for (idx = j = 0, len2 = ref1.length; j < len2; idx = ++j) {
        c = ref1[idx];
        object_reload_store[CUI.dom.getAttribute(c, "global-object-id")] = c;
      }
    }
    shc = new CUI.StickyHeaderControl({
      element: this.__objects
    });
    this.__current.first_result_div = null;
    divScrollIntoView = null;
    if (request.sort_keys) {
      grouping_badges = [];
      sort_keys = [];
      ref2 = request.sort_keys;
      for (_k in ref2) {
        sk = ref2[_k];
        sort_keys.push(sk);
        grouping_badges[sort_keys.length - 1] = null;
      }
    } else {
      sort_keys = null;
    }
    render_one_object = (function(_this) {
      return function(o, idx) {
        var __k, _idx, content, d, deleted_el, item, k, l, len3, len4, m, n, offset, path, ref3, ref4, ref5, ref6, sh, st_opts, v;
        if (o == null) {
          deleted_el = CUI.dom.div("ez5-deleted result-dynamic");
          CUI.dom.append(deleted_el, new LocaLabel({
            "class": "ez5-object-deleted",
            loca_key: "ez5.object.deleted",
            centered: true
          }));
          return deleted_el;
        }
        offset = request.offset + idx;
        o = data.objects[idx];
        o._format = data.format;
        if (sort_keys) {
          for (k = l = 0, len3 = sort_keys.length; l < len3; k = ++l) {
            sk = sort_keys[k];
            path = [];
            if (((ref3 = o._fields[sk._key]) != null ? ref3.length : void 0) > 0) {
              ref4 = o._fields[sk._key];
              for (_idx = m = 0, len4 = ref4.length; m < len4; _idx = ++m) {
                item = ref4[_idx];
                v = sk.field.formatSortGroupable(item, sk, _idx, data, o);
                if (!CUI.util.isNull(v)) {
                  path.push(v);
                }
              }
            }
            content = path.join("|");
            if (content !== grouping_badges[k]) {
              grouping_badges[k] = content;
              for (__k = n = ref5 = k + 1, ref6 = grouping_badges.length; ref5 <= ref6 ? n < ref6 : n > ref6; __k = ref5 <= ref6 ? ++n : --n) {
                grouping_badges[__k] = null;
              }
              st_opts = {
                control: shc,
                level: k
              };
              if (content === "") {
                st_opts.content = new CUI.Label({
                  "class": "ez5-result-dynamic-no-grouping-header",
                  text: $$("result.dynamic.no_grouping_header", {
                    name: sk.field.nameLocalized()
                  })
                });
              } else {
                st_opts.content = sk.field.sortRenderContent(path, _this);
              }
              sh = new CUI.StickyHeader(st_opts);
              _this.__object_divs.push(sh.DOM);
              CUI.dom.append(tempContainer, sh.DOM);
            }
          }
        }
        d = null;
        if (request.update && object_reload_store[o._global_object_id]) {
          d = object_reload_store[o._global_object_id];
          if (CUI.dom.data(d, "request").format === request.format) {
            CUI.dom.removeAttribute(d, "remove-me");
            CUI.dom.data(d, "request", request);
            CUI.dom.setAttribute(d, "offset", request.offset + idx);
            CUI.dom.setAttribute(d, "idx", idx);
          }
        }
        if (!d) {
          d = _this.__loader.getPlaceholder({
            "class": _this.getName(),
            offset: offset,
            object: o,
            request: request,
            idx: offset - request.offset,
            render_type: _this.getRenderType()
          });
        }
        if (idx === 0) {
          _this.__current.first_result_div = d;
        }
        if (request.offset + idx === request.scroll_into_view_offset) {
          divScrollIntoView = d;
        }
        CUI.dom.setAttribute(d, "ui", "result.dynamic.object");
        _this.__object_divs.push(d);
        return d;
      };
    })(this);
    finish_render = (function(_this) {
      return function() {
        CUI.dom.empty(_this.__objects);
        if (shc != null) {
          CUI.dom.append(_this.__objects, shc.__control);
        }
        CUI.dom.append(_this.__objects, tempContainer.children);
        _this.__objects.scrollTop = 0;
        if (request.update) {
          CUI.dom.removeChildren(_this.__objects, "[remove-me]");
        }
        CUI.dom.scrollIntoView(divScrollIntoView);
        object_reload_store = null;
        _this.__updateFillViewLayout();
        _this.__loader.markLoadMe();
        _this.__current.offset = request.offset;
        _this.__current.pageSize = request.limit;
        _this.__current.autoPageSize = _this.view_data.page_size === "auto";
        if (data.count === 0) {
          return CUI.dom.append(_this.__objects, _this.getSearch().getEmptyResultDiv(request));
        } else {
          _this.initSelectable(".result-dynamic:not(.ez5-deleted)", _this.__objects);
          return _this.initSelectableCollection();
        }
      };
    })(this);
    if (this._allowTopLevelPlaceholder) {
      data.objects.unshift({
        _global_object_id: "0",
        _system_object_id: 0
      });
    }
    idx = 0;
    len = data.objects.length;
    chunk = 50;
    chunk_no = 0;
    this.__object_divs = [];
    render_next_chunk = (function(_this) {
      return function() {
        var count, objectRendered;
        if (_this.isDestroyed() || !_this.getSearch()) {
          return;
        }
        count = 0;
        while (idx < len && count < chunk) {
          objectRendered = render_one_object(data.objects[idx], idx);
          CUI.dom.append(tempContainer, objectRendered);
          idx++;
          count++;
        }
        if (chunk_no === 0) {
          _this.__loader.markLoadMe();
          _this.destroyWaitBlock();
        }
        chunk_no++;
        if (idx < len) {
          CUI.setTimeout(render_next_chunk, 0);
        } else {
          finish_render();
        }
      };
    })(this);
    this.__navi.update(data);
    render_next_chunk();
    return this;
  };

  ResultDynamic.prototype.getFillViewMode = function() {
    return "dynamic";
  };

  ResultDynamic.prototype.__updateFillViewLayout = function(relayout_when_scrollbar_changes) {
    var addRow, add_current_row_objects, add_row_as_last_row, aspect_ratio, available_row_width, calcFitRowScaleFactor, check_need_recalc, container, container_dim, current_row_objects, current_row_scale_factor, current_row_width, div, ex, has_scrollbar, i, idx, is_header, len1, marginInner, marginLeft, marginRight, marginTopBottom, max_aspect_ratio, max_obj_count, max_row_scale_factor, measure_dim, min_aspect_ratio, min_height, min_row_scale_factor, mode, new_row_scale_factor, new_row_width, next_div, object_counter, object_width, objects_count, ref, ref1, result_container_client_height, result_container_client_width, row_counter, sticky_dim, used_height, wanted_height;
    if (relayout_when_scrollbar_changes == null) {
      relayout_when_scrollbar_changes = true;
    }
    if (!((ref = this.__object_divs) != null ? ref.length : void 0)) {
      return;
    }
    if (!CUI.dom.isInDOM(this.__object_divs[0])) {
      return;
    }
    mode = this.getFillViewMode();
    container = this.__objects;
    if (container.clientHeight === 0) {
      return;
    }
    CUI.dom.setStyle(this.__standardDummy, {
      width: ""
    });
    measure_dim = CUI.dom.getDimensions(this.__standardDummy);
    container_dim = CUI.dom.getDimensions(container);
    result_container_client_width = container.clientWidth;
    result_container_client_height = container.clientHeight;
    if (container_dim.scrollHeight > container_dim.clientHeight) {
      has_scrollbar = true;
    } else {
      has_scrollbar = false;
    }
    used_height = 0;
    marginInner = measure_dim.marginBottom || 0;
    marginTopBottom = measure_dim.marginTop || 0;
    marginLeft = measure_dim.marginLeft || 0;
    marginRight = measure_dim.marginRight || 0;
    available_row_width = result_container_client_width - marginRight - marginLeft;
    if (mode !== "fill") {
      object_width = measure_dim.contentBoxWidth;
      max_obj_count = Math.floor((available_row_width + marginInner) / (object_width + marginInner));
      if (max_obj_count <= 1) {
        object_width = available_row_width;
      } else {
        object_width = ((available_row_width + marginInner) / max_obj_count) - marginInner;
      }
      CUI.dom.setStyle(this.__standardDummy, {
        width: object_width
      });
      measure_dim = CUI.dom.getDimensions(this.__standardDummy);
    }
    row_counter = 0;
    current_row_width = 0;
    current_row_objects = [];
    object_counter = 0;
    max_aspect_ratio = 4 / 1;
    min_aspect_ratio = 2 / 4;
    wanted_height = measure_dim.contentBoxHeight;
    if (mode === "fill") {
      if (!wanted_height) {
        console.warn("ResultDynamic: Mode:", mode, "Could not a find height for result. Setting height to 100.");
        wanted_height = 100;
      }
      min_height = measure_dim.minHeight;
      if (!min_height) {
        console.warn("ResultDynamic: Mode:", mode, "Could not a find a minimum height for result. Setting minHeight to 50.");
        min_height = CUI.__ng__ ? wanted_height : 50;
      }
      min_row_scale_factor = Math.min(1, measure_dim.minHeight / wanted_height);
    }
    max_row_scale_factor = 1.33;
    objects_count = this.__object_divs.length;
    calcFitRowScaleFactor = (function(_this) {
      return function(num_objects, row_width) {
        var ignore_margin, max, width;
        ignore_margin = (num_objects - 1) * marginInner;
        max = available_row_width - ignore_margin;
        width = row_width - ignore_margin;
        return max / width;
      };
    })(this);
    addRow = (function(_this) {
      return function(last_row) {
        var _marginBottom, _marginLeft, _marginRight, _marginTop, diff, fit_row_scale_factor, i, idx, len1, new_height, new_width, object, used_row_width;
        if (last_row == null) {
          last_row = false;
        }
        new_height = null;
        if (current_row_objects.length > 0) {
          if (mode === "fill") {
            if (last_row && !(current_row_width > available_row_width * (1.0 / max_row_scale_factor))) {
              fit_row_scale_factor = 1;
            } else {
              fit_row_scale_factor = calcFitRowScaleFactor(current_row_objects.length, current_row_width);
            }
            new_height = wanted_height * fit_row_scale_factor;
          } else {
            new_height = wanted_height;
          }
        }
        used_row_width = 0;
        for (idx = i = 0, len1 = current_row_objects.length; i < len1; idx = ++i) {
          object = current_row_objects[idx];
          switch (mode) {
            case "fill":
              new_width = object.width * fit_row_scale_factor;
              break;
            case "sideways":
              new_width = object.width;
              break;
            case "overlay":
              new_width = object.width;
              new_height = new_width;
              break;
            case "underlay":
              new_width = object.width;
              if (!CUI.__ng__) {
                new_height = new_width + wanted_height;
              }
              break;
            default:
              new_width = object.width;
          }
          diff = 0;
          if (idx === 0) {
            _marginLeft = 0;
          } else {
            _marginLeft = marginInner;
          }
          _marginRight = 0;
          if (idx === current_row_objects.length - 1) {
            if (idx > 0 && !last_row) {
              diff = (available_row_width - used_row_width) - (new_width + _marginLeft);
              if (diff !== 0) {
                if (mode === "fill") {
                  new_width = new_width + diff;
                } else {
                  _marginLeft = _marginLeft + diff;
                }
              }
            }
          }
          if (row_counter === 0) {
            _marginTop = marginTopBottom;
          } else {
            _marginTop = marginInner;
          }
          if (last_row) {
            _marginBottom = marginTopBottom;
          } else {
            _marginBottom = 0;
          }
          CUI.dom.setStyle(object.div, {
            top: Math.floor(used_height),
            left: Math.floor(used_row_width + marginLeft),
            height: Math.floor(new_height),
            width: Math.floor(new_width),
            marginLeft: _marginLeft,
            marginTop: _marginTop,
            marginRight: _marginRight,
            marginBottom: _marginBottom
          });
          used_row_width = used_row_width + _marginLeft + new_width + _marginRight;
        }
        if (current_row_objects.length > 0) {
          used_height = used_height + new_height + _marginTop + _marginBottom;
          row_counter++;
        }
        current_row_objects = [];
        current_row_width = 0;
        return _this;
      };
    })(this);
    add_current_row_objects = (function(_this) {
      return function(as_last_in_row, last_row) {
        if (as_last_in_row == null) {
          as_last_in_row = false;
        }
        if (last_row == null) {
          last_row = false;
        }
        addRow(as_last_in_row);
        if (check_need_recalc(last_row)) {
          throw "recalc";
        }
      };
    })(this);
    is_header = function(div) {
      return div && CUI.dom.hasClass(div, "cui-sticky-header");
    };
    aspect_ratio = function(div) {
      var _aspect_ratio, ref1, ref2, ref3, ref4, ref5, result_object, thumb_version, vname;
      result_object = CUI.dom.data(div, "object");
      thumb_version = null;
      if (result_object) {
        ref5 = (ref1 = result_object._standard) != null ? (ref2 = ref1.eas) != null ? (ref3 = ref2[1]) != null ? (ref4 = ref3[0]) != null ? ref4.versions : void 0 : void 0 : void 0 : void 0;
        for (vname in ref5) {
          thumb_version = ref5[vname];
          break;
        }
      }
      if (thumb_version) {
        _aspect_ratio = thumb_version.width / thumb_version.height;
        if (isNaN(_aspect_ratio)) {
          _aspect_ratio = 1;
        } else {
          _aspect_ratio = Math.max(Math.min(max_aspect_ratio, _aspect_ratio), min_aspect_ratio);
        }
      } else {
        _aspect_ratio = 1;
      }
      return _aspect_ratio;
    };
    check_need_recalc = (function(_this) {
      return function(last_row) {
        if (last_row == null) {
          last_row = false;
        }
        if (!relayout_when_scrollbar_changes) {
          return false;
        }
        if ((last_row && has_scrollbar && used_height <= container_dim.clientHeight) || (!has_scrollbar && used_height > result_container_client_height)) {
          return true;
        } else {
          return false;
        }
      };
    })(this);
    try {
      ref1 = this.__object_divs;
      for (idx = i = 0, len1 = ref1.length; i < len1; idx = ++i) {
        div = ref1[idx];
        next_div = this.__object_divs[idx + 1];
        if (CUI.dom.hasClass(div, "ez-sticky-header-control")) {
          continue;
        }
        if (is_header(div)) {
          add_current_row_objects(true);
          CUI.dom.setStyle(div, {
            position: "absolute",
            top: used_height,
            left: 0,
            right: 0
          });
          sticky_dim = CUI.dom.getDimensions(div);
          used_height = used_height + sticky_dim.marginBoxHeight;
          continue;
        }
        if (mode === "fill") {
          object_width = wanted_height * aspect_ratio(div);
        }
        if (current_row_width === 0) {
          new_row_width = current_row_width + object_width;
        } else {
          new_row_width = current_row_width + marginInner + object_width;
        }
        add_row_as_last_row = null;
        if (mode === "fill" && current_row_objects.length > 0) {
          current_row_scale_factor = calcFitRowScaleFactor(current_row_objects.length, current_row_width);
          new_row_scale_factor = calcFitRowScaleFactor(current_row_objects.length + 1, new_row_width);
          if (current_row_scale_factor < max_row_scale_factor || new_row_scale_factor < min_row_scale_factor) {
            add_row_as_last_row = false;
          }
        } else {
          if (Math.floor(new_row_width) > available_row_width) {
            add_row_as_last_row = false;
          }
        }
        if (add_row_as_last_row !== null) {
          add_current_row_objects(add_row_as_last_row);
        }
        if (current_row_width === 0) {
          current_row_width = current_row_width + object_width;
        } else {
          current_row_width = current_row_width + marginInner + object_width;
        }
        current_row_objects.push({
          div: div,
          width: object_width
        });
      }
      add_current_row_objects(true, true);
    } catch (error) {
      ex = error;
      if (ex === "recalc") {
        return this.__updateFillViewLayout(false);
      } else {
        throw ex;
      }
    }
    if (mode === "fill") {
      CUI.Events.trigger({
        type: "result-dynamic-fill-calculated",
        node: this.__pane
      });
    }
    return this;
  };

  ResultDynamic.prototype.__buildStandardDummy = function() {
    var sd;
    sd = new CUI.Template({
      name: "result-card",
      "class": "ez5-card--standard ez5-result-standard-appearance-info-dummy result-standard",
      map: {
        standard_1: true,
        standard_2: true,
        path: true,
        objecttype: true,
        pool: true,
        system_object_id: true,
        tags: true
      }
    });
    sd;
    sd.append("Standard 1 Dummy Text Standard 1 Dummy Text", "standard_1");
    sd.append("Standard 2 Dummy Text Standard 2 Dummy Text", "standard_2");
    sd.append("Dummy Object Type", "objecttype");
    sd.append("Dummy-Pool", "pool");
    sd.append("#1101", "system_object_id");
    sd.append(new CUI.Icon({
      icon: "fa-cloud",
      "class": "ez5-tag-icon"
    }), "tags");
    return sd;
  };

  return ResultDynamic;

})(ResultManagerResult);

CUI.Events.registerEvent({
  type: "result-dynamic-loading-done",
  sink: true
});

CUI.Events.registerEvent({
  type: "result-dynamic-update-view",
  sink: true
});

CUI.Events.registerEvent({
  type: "result-dynamic-fill-calculated",
  sink: true
});
// Generated by CoffeeScript 1.12.7
var ResultDynamicLoading,
  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;

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

  function ResultDynamicLoading(opts1) {
    var mark_load_me;
    this.opts = opts1 != null ? opts1 : {};
    ResultDynamicLoading.__super__.constructor.call(this, this.opts);
    CUI.dom.setAttribute(this._container, "result-dynamic-loading", "1");
    this.__loadingSearchesCount = 0;
    mark_load_me = (function(_this) {
      return function() {
        if (_this.__marking) {
          return;
        }
        _this.__marking = true;
        _this.markLoadMe();
        _this.__marking = false;
      };
    })(this);
    CUI.Events.listen({
      node: this._container,
      instance: this,
      type: "scroll",
      call: (function(_this) {
        return function(ev) {
          CUI.scheduleCallback({
            ms: 250,
            call: mark_load_me
          });
        };
      })(this)
    });
    EventPoller.listen({
      filter: {
        type: ["OBJECT_INDEX", "OBJECT_DELETE", "OBJECT_PURGE", "OBJECT_UNDELETE"]
      },
      instance: this,
      node: this._container,
      call: (function(_this) {
        return function(events) {
          var check_loading, delete_key, el, els, event, gid, i, j, len, len1, notFoundElements, ref;
          check_loading = false;
          for (i = 0, len = events.length; i < len; i++) {
            event = events[i];
            gid = event.global_object_id;
            if (!gid) {
              continue;
            }
            els = CUI.dom.matchSelector(_this._container, "[global-object-id=\"" + gid + "\"]");
            if (ez5.version("6") && els.length === 0) {
              if (!notFoundElements) {
                notFoundElements = [];
              }
              notFoundElements.push(gid);
            }
            for (j = 0, len1 = els.length; j < len1; j++) {
              el = els[j];
              if (event.type === "OBJECT_INDEX" && event.object_version > 0) {
                if (CUI.dom.hasClass(el, "ez5-deleted")) {
                  continue;
                }
                el.removeAttribute("render-from-data");
                el.setAttribute("load-me", 1);
                check_loading = true;
              }
              if ((ref = event.type) === "OBJECT_DELETE" || ref === "OBJECT_PURGE" || ref === "OBJECT_UNDELETE") {
                el.removeAttribute("load-me", 1);
                el.classList.add("ez5-deleted");
                CUI.dom.empty(el);
                delete_key = "ez5.object.deleted";
                if (ez5.version("6")) {
                  if (event.type === "OBJECT_UNDELETE") {
                    delete_key = "ez5.object.undeleted";
                  } else if (event.type === "OBJECT_PURGE") {
                    delete_key = "ez5.object.purged";
                  }
                }
                CUI.dom.append(el, new LocaLabel({
                  "class": "ez5-object-deleted",
                  loca_key: delete_key,
                  centered: true
                }));
              }
            }
          }
          if (!CUI.util.isEmpty(notFoundElements)) {
            CUI.Events.trigger({
              type: "result-dynamic-loading-object-index",
              node: _this.getContainer(),
              info: {
                objects_ids: notFoundElements
              }
            });
          }
          if (check_loading) {
            _this.checkLoading();
          }
        };
      })(this)
    });
    CUI.dom.data(this._container, "loader", this);
  }

  ResultDynamicLoading.prototype.initOpts = function() {
    ResultDynamicLoading.__super__.initOpts.call(this);
    return this.addOpts({
      container: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isElement(v);
        }
      },
      search: {
        check: function(v) {
          return CUI.util.isFunction(v != null ? v.addToResultDiv : void 0);
        }
      }
    });
  };

  ResultDynamicLoading.prototype.destroy = function() {
    CUI.dom.removeAttribute(this._container, "result-dynamic-loading");
    CUI.dom.removeData(this._container, "loader");
    CUI.Events.ignore({
      instance: this
    });
    return ResultDynamicLoading.__super__.destroy.call(this);
  };

  ResultDynamicLoading.prototype.preloadVisiblePages = 1;

  ResultDynamicLoading.loadingChunkSize = 100;

  ResultDynamicLoading.prototype.markLoadMe = function() {
    var bottom, c, c_rect, i, left, len, marked, r, ref, right, top, viewport_height, viewport_width;
    c_rect = CUI.dom.getRect(this._container);
    marked = 0;
    if (c_rect.width === 0 || c_rect.height === 0) {
      return;
    }
    ref = CUI.dom.matchSelector(this._container, '.placeholder:not([loading="1"])');
    for (i = 0, len = ref.length; i < len; i++) {
      c = ref[i];
      CUI.dom.removeAttribute(c, "load-me");
      r = CUI.dom.getRect(c);
      if (r.width > 0 && r.height > 0) {
        top = r.top - c_rect.top;
        bottom = r.bottom - c_rect.top;
        left = r.left - c_rect.left;
        right = r.right - c_rect.left;
        viewport_height = c_rect.height;
        viewport_height += viewport_height * this.preloadVisiblePages;
        viewport_width = c_rect.width;
        viewport_width += viewport_width * this.preloadVisiblePages;
        if (bottom < 0 || right < 0) {
          continue;
        }
        if (top > viewport_height || left > viewport_width) {
          break;
        }
        CUI.dom.setAttribute(c, "load-me", 1);
        marked++;
      }
    }
    if (marked) {
      this.checkLoading().done((function(_this) {
        return function() {
          CUI.Events.trigger;
          return {
            type: "result-dynamic-loading-done",
            node: _this.getContainer()
          };
        };
      })(this));
    }
    return this;
  };

  ResultDynamicLoading.prototype.checkLoading = function(dfr) {
    var counter, el, excluded_fields, excluded_fields_by_objecttype, fields, format, gid, global_ids, hiddenFields, i, idx, j, len, len1, load_me, mask, object, objecttype, ref, ref1, req_data, sm, txt;
    if (dfr == null) {
      dfr = new CUI.Deferred();
    }
    load_me = CUI.dom.matchSelector(this._container, "[load-me=\"1\"]");
    if (load_me.length === 0) {
      return dfr.resolve().promise();
    }
    counter = ++ResultDynamicLoading.counter;
    format = null;
    global_ids = [];
    excluded_fields_by_objecttype = {};
    for (idx = i = 0, len = load_me.length; i < len; idx = ++i) {
      el = load_me[idx];
      CUI.dom.removeAttribute(el, "load-me");
      CUI.dom.setAttribute(el, "loading", 1);
      if (CUI.dom.getAttribute(el, "render-from-data")) {
        this.__renderObject(el);
        continue;
      }
      gid = CUI.dom.getAttribute(el, "global-object-id");
      if (global_ids.indexOf(gid) === -1) {
        global_ids.push(gid);
        switch (CUI.dom.getAttribute(el, "render-type")) {
          case "standard":
            if (format === null) {
              format = "standard";
            }
            break;
          case "text":
            if (format === null || format === "standard") {
              format = "long";
            }
            if (ez5.version("6")) {
              object = CUI.dom.data(el, "object");
              if (object && !excluded_fields_by_objecttype[object._objecttype]) {
                mask = Mask.getMaskByMaskName(object._mask);
                hiddenFields = (ref = mask.getHiddenFields("text")) != null ? ref.filter(function(field) {
                  return field instanceof ReverseLinkedTable || field instanceof LinkedObject;
                }) : void 0;
                if (hiddenFields.length > 0) {
                  excluded_fields_by_objecttype[object._objecttype] = hiddenFields.map(function(field) {
                    return object._objecttype + "." + field.name();
                  });
                }
              }
            }
            break;
          default:
            format = "long";
        }
        if (global_ids.length > ResultDynamicLoading.loadingChunkSize) {
          break;
        }
      }
    }
    if (format === null) {
      format = "long";
    }
    if (global_ids.length === 0) {
      return this.checkLoading(dfr);
    }
    excluded_fields = [];
    if (ez5.version("6") && !CUI.util.isEmpty(excluded_fields_by_objecttype)) {
      for (objecttype in excluded_fields_by_objecttype) {
        fields = excluded_fields_by_objecttype[objecttype];
        excluded_fields = excluded_fields.concat(fields);
      }
    }
    req_data = {
      search: [
        {
          type: "in",
          fields: ["_global_object_id"],
          "in": global_ids
        }
      ],
      format: format,
      generate_rights: ez5.version("6"),
      offset: 0,
      exclude_fields: excluded_fields,
      limit: global_ids.length
    };
    if (TrashSearchManager.canSeeDeleted()) {
      ref1 = this._search.getSearchManagers();
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        sm = ref1[j];
        if (sm instanceof TrashSearchManager) {
          req_data.include_deleted = true;
        }
      }
    }
    txt = "dynamic load [" + counter + "]";
    this.__loadingSearchesCount++;
    ez5.api.search({
      data: {
        debug: "DynamicLoading"
      },
      json_data: req_data
    }).fail((function(_this) {
      return function() {
        _this.__loadingSearchesCount--;
        return dfr.resolve().promise();
      };
    })(this)).done((function(_this) {
      return function(data) {
        var k, l, len2, len3, len4, m, node, nodeList, not_found, not_founds, obj, ref2, show_easydb4_hint, tmpl;
        _this.__loadingSearchesCount--;
        txt = ("ResultDynamicLoading.render [" + counter + "] ") + global_ids.length + " objects, elasticsearch:" + data.took + "ms";
        ref2 = data.objects;
        for (idx = k = 0, len2 = ref2.length; k < len2; idx = ++k) {
          obj = ref2[idx];
          if (ez5.version("6.4") && !obj._instance) {
            if (CUI.util.isEmptyObject(obj._generated_rights)) {
              continue;
            }
          }
          nodeList = CUI.dom.matchSelector(_this._container, "[global-object-id=\"" + obj._global_object_id + "\"]");
          if (nodeList.length === 0) {
            console.warn("Requested Result Object " + obj._global_object_id + " not found in DOM tree.", _this._container);
            continue;
          }
          for (l = 0, len3 = nodeList.length; l < len3; l++) {
            node = nodeList[l];
            obj.__offset = parseInt(node.getAttribute("offset"));
            obj.__idx = parseInt(node.getAttribute("idx"));
            CUI.dom.data(node, "object", obj);
            _this.__renderObject(node);
          }
        }
        if (ez5.version("6")) {
          CUI.Events.trigger({
            type: "result-dynamic-loading-object-index",
            node: _this.getContainer(),
            info: {
              objects: data.objects
            }
          });
        }
        not_founds = CUI.dom.matchSelector(_this._container, "[loading=\"1\"]");
        if (not_founds.length > 0 && !_this.__loadingSearchesCount > 0) {
          console.warn("ResultDynamicLoading: objects not returned by search:", (function() {
            var len4, m, results;
            results = [];
            for (m = 0, len4 = not_founds.length; m < len4; m++) {
              not_found = not_founds[m];
              results.push(CUI.dom.getAttribute(not_found, "global-object-id"));
            }
            return results;
          })());
          show_easydb4_hint = false;
          for (m = 0, len4 = not_founds.length; m < len4; m++) {
            not_found = not_founds[m];
            gid = CUI.dom.getAttribute(not_found, "global-object-id");
            object = CUI.dom.data(not_found, "object");
            object.__notFound = true;
            _this.__resetDiv(not_found);
            tmpl = new CUI.Template({
              name: "result-dynamic-not-found",
              map: {
                browser: true
              }
            });
            if (gid.endsWith("@easydb4")) {
              tmpl.append(new LocaLabel({
                "class": "ez5-result-dynamic-loading-not-found",
                loca_key: "result.dynamic.loading.easydb4_not_found.md",
                loca_key_attrs: {
                  gid: gid
                },
                markdown: true,
                multiline: true,
                centered: true
              }), "browser");
              show_easydb4_hint = true;
            } else {
              tmpl.append(new LocaLabel({
                "class": "ez5-result-dynamic-loading-not-found",
                loca_key: "result.dynamic.loading.not_found",
                tooltip: {
                  text: gid
                },
                multiline: true,
                centered: true
              }), "browser");
            }
            CUI.dom.append(not_found, tmpl);
          }
        }
        if (ez5.connector && show_easydb4_hint && _this._search instanceof SearchCollection && !_this.__easyDb4HintVisible) {
          _this.__easyDb4HintVisible = true;
          CUI.confirm({
            text: $$("result.dynamic.loading.easydb4_objects_hint.md"),
            markdown: true,
            show_inline: _this._search.getResultContainer(),
            button_text_ok: $$("result.dynamic.loading.easydb4_objects_hint.button.search"),
            button_text_cancel: $$("result.dynamic.loading.easydb4_objects_hint.button.ok")
          }).done(function() {
            return ez5.connector.replaceEasydb4Objects(_this._search.getSearchCollection());
          }).always(function() {
            return _this.__easyDb4HintVisible = false;
          });
        }
        return _this.checkLoading(dfr);
      };
    })(this));
    dfr.done((function(_this) {
      return function() {
        return CUI.Events.trigger({
          type: "viewport-resize",
          node: _this._search.getResultContainer()
        });
      };
    })(this));
    return dfr.promise();
  };

  ResultDynamicLoading.prototype.__resetDiv = function(div) {
    CUI.dom.removeClass(div, "placeholder");
    CUI.dom.removeAttribute(div, "loading");
    CUI.dom.empty(div);
    return div;
  };

  ResultDynamicLoading.prototype.__renderObject = function(div) {
    var assetBrowser, assets, assetsCount, dfr, divHeight, divWidth, idx, noEasOnObjecttype, obj, preferred_asset_size, req, resultObject, rt, set_focus, standardOpts;
    this.__resetDiv(div);
    obj = CUI.dom.data(div, "object");
    req = CUI.dom.data(div, "request");
    if (obj._system_object_id === 0) {
      resultObject = new ParentRootResultObject();
    } else {
      resultObject = new ResultObject().setData(obj);
      resultObject.setCSSClasses(div);
    }
    noEasOnObjecttype = false;
    rt = CUI.dom.getAttribute(div, "render-type");
    if (rt !== "none") {
      switch (rt) {
        case "standard":
          divWidth = window.getComputedStyle(div).width;
          divHeight = window.getComputedStyle(div).height;
          if (divWidth && parseInt(divWidth) > 0 && divHeight && parseInt(divHeight) > 0) {
            preferred_asset_size = Math.max(parseInt(divWidth), parseInt(divHeight));
          } else if (this._fullscreen) {
            preferred_asset_size = 100;
          }
          standardOpts = {
            tags: true,
            system_object_id: true,
            mode: "standard",
            path_short_mode: true,
            show_hourglass: true,
            preferred_asset_size: preferred_asset_size,
            custom_resize_events: ["result-dynamic-update-view"],
            waitForResizeEvent: false
          };
          if (!preferred_asset_size) {
            standardOpts.custom_resize_events = ["result-dynamic-update-view", "result-dynamic-fill-calculated"];
            standardOpts.waitForResizeEvent = true;
          }
          CUI.dom.append(div, resultObject.renderCardStandard(standardOpts));
          break;
        case "hires":
          CUI.dom.append(div, resultObject.renderCardHires({
            force_assets: true,
            show_hourglass: true
          }));
          break;
        case "text":
          CUI.dom.append(div, resultObject.renderTextResult({
            system_object_id: true
          }));
          break;
        case "detail":
          assets = resultObject.getAssetsForBrowser("detail");
          if (assets.length === 0) {
            if (!resultObject.mask.hasStandardEASFields()) {
              noEasOnObjecttype = true;
            }
          }
          if (assets) {
            assetBrowser = new AssetBrowser({
              hires: true,
              assets: assets,
              disableWheelForTools: true,
              noEasOnObjecttype: noEasOnObjecttype
            });
            CUI.dom.append(div, assetBrowser);
          }
          CUI.dom.append(div, resultObject.renderCardDetail());
          CUI.dom.append(div, resultObject.renderDetail("detail", "detail-header"));
          break;
        default:
          CUI.util.assert(false, "ResultDynamicLoading.checkLoading", "Unsupported render-type: \"" + rt + "\".");
      }
    }
    if (req) {
      this._search.addToResultDiv(req, resultObject, div);
    }
    if ((idx = parseInt(CUI.dom.getAttribute(div, "asset-browser-idx"))) >= 0) {
      dfr = CUI.dom.data(div, "show-asset-idx-deferred");
      set_focus = CUI.dom.data(div, "show-asset-idx-set-focus");
      if (dfr) {
        this.showAsset(div, idx, set_focus, dfr);
      }
    }
    assetsCount = resultObject.getAssetsCount();
    CUI.dom.setAttribute(div, "ez5-number-of-assets", assetsCount);
  };

  ResultDynamicLoading.prototype.getContainer = function() {
    return this._container;
  };

  ResultDynamicLoading.prototype.getPlaceholder = function(opts) {
    var d, ref, ref1, render_from_data;
    CUI.util.assert((ref = opts.object) != null ? ref._global_object_id : void 0, "ResultDynamicLoading.getPlaceholder", "opts.object._global_object_id not set", {
      opts: opts
    });
    CUI.util.assert(opts.render_type, "ResultDynamicLoading.getPlaceholder", "opts.render_type not set", {
      opts: opts
    });
    CUI.util.assert(!opts.request || opts.request instanceof Request, "ResultDynamicLoading.getPlaceholder", "opts.request not set", {
      opts: opts
    });
    CUI.util.assert(CUI.util.isPlainObject(opts.object), "ResultDynamicLoading.getPlaceholder", "opts.object not set", {
      opts: opts
    });
    render_from_data = void 0;
    switch (opts.object._format) {
      case "standard":
        if ((ref1 = opts.render_type) === "standard") {
          render_from_data = 1;
        }
        break;
      case "long":
        render_from_data = 1;
    }
    if (opts.object._system_object_id === 0) {
      render_from_data = 1;
    }
    d = CUI.dom.div("result-dynamic placeholder " + (opts["class"] || ""));
    CUI.dom.append(d, new CUI.Template({
      name: "result-object-standard-placeholder"
    }).DOM);
    CUI.dom.setAttributeMap(d, {
      "tabindex": "0",
      "global-object-id": opts.object._global_object_id,
      "uuid": opts.object._uuid,
      "render-type": opts.render_type,
      "render-from-data": render_from_data,
      "offset": opts.offset,
      "idx": opts.idx
    });
    CUI.Events.listen({
      node: d,
      type: "toolbox",
      call: (function(_this) {
        return function(ev, info) {
          info.tools.push(new ToolboxTool({
            group: "object",
            name: "object.detail",
            run: function() {
              var colObj;
              colObj = new CollectionObject(opts.object);
              return ResultObject.showCollectionObjectInPopover({
                collectionObject: colObj,
                element: d
              });
            }
          }));
          if (ez5.session.isDebug()) {
            info.tools.push(new ToolboxTool({
              group: "object",
              name: "object.dump",
              sort: "I:1",
              loca_key: "base.debug.to.console",
              loca_key_attrs: {
                more: " [" + opts.object._system_object_id + "]"
              },
              run: function(ev) {
                return console.info("result object DUMP: ", CUI.util.dump(opts.object), _this);
              }
            }));
          }
        };
      })(this)
    });
    opts.object.__offset = opts.offset;
    opts.object.__idx = opts.idx;
    CUI.dom.data(d, "object", opts.object);
    CUI.dom.data(d, "request", opts.request);
    return d;
  };

  ResultDynamicLoading.prototype.showAsset = function(el_or_gid, idx, set_focus, dfr) {
    var ab, el, gid;
    if (set_focus == null) {
      set_focus = false;
    }
    if (dfr == null) {
      dfr = new CUI.Deferred();
    }
    if (CUI.util.isString(el_or_gid)) {
      gid = el_or_gid;
      el = CUI.dom.matchSelector(this._container, "[global-object-id=\"" + gid + "\"]")[0];
      if (!el) {
        console.error("Could not showAsset in container. global_object_id: " + gid + ", asset_browser_idx: " + idx + ", container:", this._container);
        return dfr.reject().promise();
      }
    } else {
      el = el_or_gid;
    }
    if (!el || (!(idx >= 0))) {
      console.error("Could not showAsset in container. elements: " + el.length + ", asset_browser_idx: " + idx + ", container:", this._container, el, idx);
      return dfr.reject().promise();
    }
    if (set_focus) {
      if (this.__last_asset) {
        CUI.dom.removeClass(this.__last_asset, "cui-selected");
        this.__last_asset = null;
      }
      if (this.__last_el) {
        this.__last_el.classList.remove(ez5.defaults.focusClass);
        this.__last_el = null;
      }
      el.classList.add(ez5.defaults.focusClass);
      this.__last_el = el;
    }
    if (CUI.dom.hasClass(el, "placeholder")) {
      CUI.dom.data(el, "show-asset-idx-deferred", dfr);
      CUI.dom.data(el, "show-asset-idx-set-focus", set_focus);
      CUI.dom.setAttribute(el, "asset-browser-idx", idx);
      if (!CUI.dom.getAttribute(el, "loading")) {
        CUI.dom.setAttribute(el, "load-me", 1);
        this.checkLoading();
      }
    } else {
      CUI.dom.removeData(el, "show-asset-idx-deferred");
      CUI.dom.removeData(el, "show-asset-idx-set-focus");
      ab = CUI.dom.data(CUI.dom.matchSelector(el, ".cui-asset-browser")[0], "element");
      if (!ab || ab.getAssets().length === 0) {
        return dfr.resolve().promise();
      }
      if (!CUI.util.isInteger(idx)) {
        console.error("ResultDynamicLoading.showAsset: idx not Integer", idx);
        ab.setIdx(0);
      } else {
        ab.setIdx(Math.min(idx, ab.getAssets().length - 1));
      }
      if (set_focus) {
        this.__last_asset = CUI.dom.addClass(ab.getCurrentAssetEement(), "cui-selected");
      }
      dfr.resolve();
    }
    return dfr.promise();
  };

  ResultDynamicLoading.counter = 0;

  CUI.Events.registerEvent({
    type: "result-dynamic-loading-object-index",
    sink: true
  });

  return ResultDynamicLoading;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var ResultDynamicLoadingFullscreen,
  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;

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

  function ResultDynamicLoadingFullscreen(opts) {
    var mark_load_me;
    this.opts = opts != null ? opts : {};
    ResultDynamicLoadingFullscreen.__super__.constructor.call(this, this.opts);
    CUI.dom.setAttribute(this._container, "result-dynamic-loading", "1");
    this.__loadingSearchesCount = 0;
    mark_load_me = (function(_this) {
      return function() {
        if (_this.__marking) {
          return;
        }
        _this.__marking = true;
        _this.markLoadMe();
        _this.__marking = false;
      };
    })(this);
    CUI.Events.listen({
      node: this._container,
      instance: this,
      type: "scroll",
      call: (function(_this) {
        return function(ev) {
          CUI.scheduleCallback({
            ms: 250,
            call: mark_load_me
          });
        };
      })(this)
    });
    CUI.dom.data(this._container, "loader", this);
  }

  ResultDynamicLoadingFullscreen.prototype.initOpts = function() {
    ResultDynamicLoadingFullscreen.__super__.initOpts.call(this);
    return this.addOpts({
      onElementLoaded: {
        mandatory: false,
        check: Function
      }
    });
  };

  ResultDynamicLoadingFullscreen.prototype.markLoadMe = function() {
    return ResultDynamicLoadingFullscreen.__super__.markLoadMe.call(this);
  };

  ResultDynamicLoadingFullscreen.prototype.__renderObject = function(div) {
    var assetsCount, dfr, divHeight, divWidth, idx, noEasOnObjecttype, obj, preferred_asset_size, req, resultObject, rt, set_focus, standardOpts;
    this.__resetDiv(div);
    obj = CUI.dom.data(div, "object");
    req = CUI.dom.data(div, "request");
    resultObject = new ResultObject().setData(obj);
    noEasOnObjecttype = false;
    resultObject.setCSSClasses(div);
    rt = CUI.dom.getAttribute(div, "render-type");
    if (rt !== "none") {
      switch (rt) {
        case "standard":
          divWidth = window.getComputedStyle(div).width;
          divHeight = window.getComputedStyle(div).height;
          if (divWidth && parseInt(divWidth) > 0 && divHeight && parseInt(divHeight) > 0) {
            preferred_asset_size = Math.max(parseInt(divWidth), parseInt(divHeight));
          } else {
            preferred_asset_size = 100;
          }
          standardOpts = {
            tags: true,
            system_object_id: true,
            mode: "standard",
            path_short_mode: true,
            show_hourglass: true,
            preferred_asset_size: preferred_asset_size,
            waitForResizeEvent: false,
            fullscreen: true
          };
          CUI.dom.append(div, resultObject.renderCardStandard(standardOpts));
          if (typeof this._onElementLoaded === "function") {
            this._onElementLoaded();
          }
          break;
        case "hires":
          CUI.dom.append(div, resultObject.renderCardHires({
            force_assets: true,
            show_hourglass: true,
            fullscreen: true
          }));
          break;
        default:
          CUI.util.assert(false, "ResultDynamicLoadingFullsceen.checkLoading", "Unsupported render-type: \"" + rt + "\".");
      }
    }
    if (req) {
      this._search.addToResultDiv(req, resultObject, div);
    }
    if ((idx = parseInt(CUI.dom.getAttribute(div, "asset-browser-idx"))) >= 0) {
      dfr = CUI.dom.data(div, "show-asset-idx-deferred");
      set_focus = CUI.dom.data(div, "show-asset-idx-set-focus");
      if (dfr) {
        this.showAsset(div, idx, set_focus, dfr);
      }
    }
    assetsCount = resultObject.getAssetsCount();
    CUI.dom.setAttribute(div, "ez5-number-of-assets", assetsCount);
  };

  return ResultDynamicLoadingFullscreen;

})(ResultDynamicLoading);
// Generated by CoffeeScript 1.12.7
var NavigationToolbar,
  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;

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

  function NavigationToolbar(opts1) {
    this.opts = opts1 != null ? opts1 : {};
    NavigationToolbar.__super__.constructor.call(this, this.opts);
    this.count_label = new CUI.Label({
      text: "...",
      attr: {
        role: "status"
      }
    });
    this.__current = {};
    if (this._size) {
      this.addClass("cui-navigation-toolbar--" + this._size);
    }
  }

  NavigationToolbar.prototype.initOpts = function() {
    NavigationToolbar.__super__.initOpts.call(this);
    return this.addOpts({
      navigation_buttons_left: {
        check: Array
      },
      append_count_label: {
        mandatory: true,
        "default": true,
        check: Boolean
      },
      loca_key_prefix: {
        "default": "result.navigation.toolbar",
        mandatory: true,
        check: String
      },
      item_name: {
        check: String
      },
      onLoadPage: {
        "default": function(page, opts) {
          return console.error("NavigationToolbar.onLoadPage", page, opts);
        },
        mandatory: true,
        check: Function
      },
      size: {
        check: ["mini"]
      },
      short: {
        check: Boolean,
        "default": false
      },
      centered: {
        check: Boolean,
        "default": false
      },
      render_on_left: {
        check: Boolean,
        "default": false
      }
    });
  };

  NavigationToolbar.prototype.readOpts = function() {
    NavigationToolbar.__super__.readOpts.call(this);
    if (this._item_name) {
      this.__item_name = this._item_name;
    } else {
      this.__item_name = $$(this._loca_key_prefix + ".item_name.default");
    }
  };

  NavigationToolbar.prototype.getCountLabel = function() {
    return this.count_label;
  };

  NavigationToolbar.prototype.loadPage = function(page, opts) {
    if (opts == null) {
      opts = {};
    }
    return this._onLoadPage(page, opts);
  };

  NavigationToolbar.prototype.getCurrent = function() {
    return this.__current;
  };

  NavigationToolbar.prototype.update = function(data) {
    var lastPage, page, ref;
    if (data == null) {
      data = {};
    }
    if (data.limit === 0) {
      page = 0;
      lastPage = 0;
    } else {
      if (((ref = data.__instances) != null ? ref.length : void 0) > 1 && data.countByInstance) {
        this.updateForMultipleInstances(data);
        return;
      }
      page = Math.floor(data.offset / data.limit);
      lastPage = Math.ceil(data.count / data.limit) - 1;
    }
    this.__current.offset = data.offset;
    if (this.__current.count !== data.count || this.__current.pageSize !== data.limit || this.__current.lastPage !== lastPage || this.__current.page !== page) {
      this.__current.page = page;
      this.__current.count = data.count;
      this.__current.pageSize = data.limit;
      this.__current.lastPage = lastPage;
      return this.__render(data);
    } else {
      return this.__update();
    }
  };

  NavigationToolbar.prototype.updateForMultipleInstances = function(data) {
    var actualPagesize, i, instaceCount, instance, instanceAddition, lastPage, len, localCount, maxCount, page, ref, ref1, singleLimit;
    if (data == null) {
      data = {};
    }
    singleLimit = data.limit / data.__instances.length;
    localCount = data.count;
    maxCount = 0;
    ref = data.countByInstance;
    for (instance in ref) {
      instaceCount = ref[instance];
      if (maxCount < instaceCount) {
        maxCount = instaceCount;
      }
      localCount -= instaceCount;
    }
    if (localCount > maxCount) {
      maxCount = localCount;
    }
    data.countByInstance["local"] = localCount;
    lastPage = Math.ceil(maxCount / singleLimit) - 1;
    page = Math.floor(data.offset / data.limit);
    actualPagesize = 0;
    ref1 = data.__instances;
    for (i = 0, len = ref1.length; i < len; i++) {
      instance = ref1[i];
      instanceAddition = Math.max(data.countByInstance[instance] - (page * singleLimit), 0);
      if (instanceAddition === 0) {
        continue;
      }
      if (instanceAddition < singleLimit) {
        actualPagesize += instanceAddition;
      } else {
        actualPagesize += singleLimit;
      }
    }
    this.__current.instances = data.__instances.length;
    this.__current.page = page;
    this.__current.count = data.count;
    this.__current.pageSize = actualPagesize;
    this.__current.lastPage = lastPage;
    return this.__render(data);
  };

  NavigationToolbar.prototype.__update = function() {
    var csv_key, currentPage, lastPage;
    if (this.__current.instances) {
      this.count_label.setText($$("result.navigation.toolbar.count.multinstance", {
        count: ez5.format_number(this.__current.pageSize),
        instanceCount: ez5.format_number(this.__current.instances)
      }));
    } else {
      if (this.__current.count === 1) {
        csv_key = this._loca_key_prefix + ".count_one";
      } else if (this.__current.lastPage === 0 || this.__current.count === 0 || this.__current.pageSize === 1 || this._size === "mini" || this._short) {
        csv_key = this._loca_key_prefix + ".count";
      } else {
        csv_key = this._loca_key_prefix + ".count_page";
      }
      this.count_label.setText($$(csv_key, {
        from: ez5.format_number(this.__current.page * this.__current.pageSize + 1),
        to: ez5.format_number(Math.min(this.__current.count, (this.__current.page + 1) * this.__current.pageSize)),
        count: ez5.format_number(this.__current.count),
        item_name: this.__item_name
      }));
    }
    if (this.__current.page === 0) {
      this.prev.disable();
      if (!this._short) {
        this.first.disable();
      }
    } else {
      this.prev.enable();
      if (!this._short) {
        this.first.enable();
      }
    }
    lastPage = ez5.format_number(this.__current.lastPage + 1);
    currentPage = ez5.format_number(this.__current.page + 1);
    this.input.setPlaceholder(currentPage + this.__separator + lastPage);
    if (this.__current.page === this.__current.lastPage || this.__current.count === 0) {
      this.next.disable();
      if (!this._short) {
        this.last.disable();
      }
    } else {
      this.next.enable();
      if (!this._short) {
        this.last.enable();
      }
    }
    return this;
  };

  NavigationToolbar.prototype.__separator = " / ";

  NavigationToolbar.prototype.__rescueNavigationButtonsLeft = function() {
    CUI.dom.removeChildren(this.left());
  };

  NavigationToolbar.prototype.__render = function() {
    var buttons, lastPage, load_page, maxInputChars, page_data;
    this.__rescueNavigationButtonsLeft();
    this.replace(this._navigation_buttons_left, "left");
    if (this._append_count_label) {
      this.append(this.count_label, "left");
    }
    lastPage = "" + (this.__current.lastPage + 1);
    this.prev = new LocaButton({
      icon: "left",
      loca_key: this._loca_key_prefix + ".left",
      loca_key_attrs: {
        item_name: this.__item_name
      },
      group: "navi",
      size: this._size,
      onClick: (function(_this) {
        return function(ev) {
          _this.loadPage(_this.__current.page - 1);
        };
      })(this)
    });
    this.next = new LocaButton({
      icon: "right",
      group: "navi",
      size: this._size,
      loca_key: this._loca_key_prefix + ".right",
      loca_key_attrs: {
        item_name: this.__item_name
      },
      onClick: (function(_this) {
        return function(ev) {
          _this.loadPage(_this.__current.page + 1);
        };
      })(this)
    });
    page_data = {
      page: null
    };
    load_page = (function(_this) {
      return function() {
        if (page_data.page === null) {
          return;
        }
        if (_this.__current.page === page_data.page - 1) {
          return;
        }
        return _this.loadPage(page_data.page - 1);
      };
    })(this);
    this.input = new CUI.NumberInput({
      min: 1,
      max: this.__current.lastPage + 1,
      "class": "ez5-navi-input",
      group: "navi",
      name: "page",
      data: page_data,
      onBlur: (function(_this) {
        return function(input) {
          return input.setValue(null);
        };
      })(this),
      onDataChanged: (function(_this) {
        return function() {
          CUI.scheduleCallback({
            ms: 1000,
            call: load_page
          });
        };
      })(this)
    }).start();
    maxInputChars = ez5.format_number(this.__current.lastPage + 1);
    CUI.dom.setAttribute(this.input.getElement(), "data-max-chars", ("" + maxInputChars).length * 2 + 1);
    if (!this._short) {
      this.first = new LocaButton({
        icon: "fa-step-backward",
        loca_key: this._loca_key_prefix + ".first",
        loca_key_attrs: {
          item_name: this.__item_name
        },
        "class": "ez5-navi-first",
        group: "navi",
        size: this._size,
        onClick: (function(_this) {
          return function(ev) {
            _this.loadPage(0);
          };
        })(this)
      });
      this.last = new LocaButton({
        icon: "fa-step-forward",
        loca_key: this._loca_key_prefix + ".last",
        loca_key_attrs: {
          item_name: this.__item_name
        },
        "class": "ez5-navi-last",
        group: "navi",
        size: this._size,
        onClick: (function(_this) {
          return function(ev) {
            _this.loadPage(_this.__current.lastPage);
          };
        })(this)
      });
    }
    if (this.__current.lastPage > 0) {
      if (this._short) {
        buttons = [this.prev, this.input, this.next];
      } else {
        buttons = [this.first, this.prev, this.input, this.next, this.last];
      }
      if (this._centered) {
        this.replace(new CUI.Buttonbar({
          buttons: buttons
        }), "center");
      } else if (this._render_on_left) {
        this.replace(new CUI.Buttonbar({
          buttons: buttons
        }), "left");
      } else {
        this.replace(new CUI.Buttonbar({
          buttons: buttons
        }), "right");
      }
      this.show();
    } else if (this._append_count_label) {
      this.empty("right");
      this.show();
    } else {
      this.hide();
    }
    this.__update();
    CUI.dom.setAttribute(this.DOM, "last-page", this.__current.lastPage);
    CUI.Events.trigger({
      node: this.DOM,
      type: "content-resize"
    });
    return this;
  };

  NavigationToolbar.prototype.getLastPage = function() {
    return this.__current.lastPage;
  };

  NavigationToolbar.prototype.destroy = function() {
    this.__rescueNavigationButtonsLeft();
    return NavigationToolbar.__super__.destroy.call(this);
  };

  NavigationToolbar.prototype.disable = function() {
    var ref, ref1, ref2, ref3, ref4;
    if ((ref = this.first) != null) {
      ref.disable();
    }
    if ((ref1 = this.last) != null) {
      ref1.disable();
    }
    if ((ref2 = this.prev) != null) {
      ref2.disable();
    }
    if ((ref3 = this.next) != null) {
      ref3.disable();
    }
    return (ref4 = this.input) != null ? ref4.disable() : void 0;
  };

  NavigationToolbar.prototype.enable = function() {
    var ref, ref1, ref2, ref3, ref4;
    if ((ref = this.first) != null) {
      ref.enable();
    }
    if ((ref1 = this.last) != null) {
      ref1.enable();
    }
    if ((ref2 = this.prev) != null) {
      ref2.enable();
    }
    if ((ref3 = this.next) != null) {
      ref3.enable();
    }
    return (ref4 = this.input) != null ? ref4.enable() : void 0;
  };

  return NavigationToolbar;

})(CUI.Toolbar);
// Generated by CoffeeScript 1.12.7
var ResultNavigationToolbar,
  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;

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

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

  ResultNavigationToolbar.prototype.initOpts = function() {
    ResultNavigationToolbar.__super__.initOpts.call(this);
    this.addOpts({
      search: {
        mandatory: true,
        check: Search
      },
      getPageSize: {
        mandatory: true,
        check: Function
      }
    });
    return this.removeOpt("onLoadPage");
  };

  ResultNavigationToolbar.prototype.readOpts = function() {
    var ots;
    ResultNavigationToolbar.__super__.readOpts.call(this);
    if (!this._item_name && this._search) {
      if (this._search instanceof SearchCollection) {
        this.__item_name = $$("result.navigation.toolbar.item_name.collection");
        return;
      }
      ots = this.getSearch().getSearchObjecttypes(true);
      if (ots.length === 1) {
        this.__item_name = ots[0].nameLocalized();
      }
    }
  };

  ResultNavigationToolbar.prototype.getSearch = function() {
    return this._search;
  };

  ResultNavigationToolbar.prototype.loadPage = function(page, opts) {
    if (opts == null) {
      opts = {};
    }
    opts.page_request = true;
    opts.offset = page * this._getPageSize();
    return this.getSearch().execute(new Request(opts));
  };

  return ResultNavigationToolbar;

})(NavigationToolbar);
// Generated by CoffeeScript 1.12.7
var ResultObject, ResultObjectDemo,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function ResultObject(opts) {
    CUI.util.assert(!opts, "new ResultObject", "opts are obsolete", {
      opts: opts
    });
    this.history_browser_data = {};
    this.__assetTypes = {};
  }

  ResultObject.prototype.setData = function(_data) {
    var isPurgedData, j, l, last_data, len, len1, p, ref, ref1, ref2, topPath;
    if ((ref = _data._path) != null ? ref.length : void 0) {
      last_data = _data._path[_data._path.length - 1];
      CUI.util.assert(last_data._uuid === _data._uuid || last_data[last_data._objecttype]._id === _data[_data._objecttype]._id, "ResultObject.setData", "Last _path element does not match element.", {
        data: _data
      });
    }
    CUI.util.assert(_data._mask, "ResultObject.setData", "data._mask must be set", {
      data: _data
    });
    CUI.util.assert(_data._objecttype, "ResultObject.setData", "data._objecttype must be set", {
      data: _data
    });
    isPurgedData = _data._uuid && _data._mask && _data._objecttype && !_data._global_object_id && !_data._format && !_data._mapped_metadata_created;
    if (isPurgedData) {
      this.data = _data;
      this.setMask(this.data._mask, this.data.__version);
      return this;
    }
    if (_data._paths && _data[_data._objecttype]._parents) {
      ref1 = _data[_data._objecttype]._parents;
      for (j = 0, len = ref1.length; j < len; j++) {
        p = ref1[j];
        p._paths = [];
        ref2 = _data._paths;
        for (l = 0, len1 = ref2.length; l < len1; l++) {
          topPath = ref2[l];
          if (topPath[topPath.length - 1]._system_object_id !== p._system_object_id) {
            continue;
          }
          if (topPath.length < 2) {
            continue;
          }
          p._paths.push(topPath.slice(0, topPath.length - 1));
        }
      }
    }
    this.data = _data;
    this.setMask(this.data._mask, this.data.__version);
    return this;
  };

  ResultObject.prototype.restoreDataFromVersion = function(version_number, header_mode, mode) {
    var dfr, newObject;
    dfr = new CUI.Deferred();
    newObject = this.copy();
    newObject.loadFromDb(version_number).done((function(_this) {
      return function() {
        _this.mergeData(newObject.getData(), header_mode, mode, true, true, true);
        return dfr.resolve();
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  ResultObject.prototype.setMask = function(mask_name, version) {
    var table_id;
    if (version == null) {
      version = "CURRENT";
    }
    table_id = ez5.schema[version]._objecttype_by_name[this.objecttype()].table_id;
    this.mask = Mask.getMaskByMaskName(mask_name, table_id, version);
    if (CUI.util.isUndef(this.data._orig_mask)) {
      this.data._orig_mask = this.data._mask;
    }
    this.data._mask = this.mask.name();
    return this;
  };

  ResultObject.prototype.mergeData = function(_data, header_mode, mode, replace, replace_empty, is_restore) {
    var top_level_data;
    if (replace == null) {
      replace = false;
    }
    if (replace_empty == null) {
      replace_empty = false;
    }
    if (is_restore == null) {
      is_restore = false;
    }
    top_level_data = CUI.util.copyObject(_data, true);
    this.__mergeData(top_level_data, header_mode, replace, replace_empty, is_restore);
    return this.__mergeData(top_level_data, mode, replace, replace_empty, is_restore);
  };

  ResultObject.prototype.__mergeData = function(top_level_data, mode, replace, replace_empty, is_restore) {
    var field, j, len, ref;
    if (replace == null) {
      replace = false;
    }
    if (replace_empty == null) {
      replace_empty = false;
    }
    if (is_restore == null) {
      is_restore = false;
    }
    ref = this.getMask().getFields(mode);
    for (j = 0, len = ref.length; j < len; j++) {
      field = ref[j];
      if (field instanceof MaskSplitter) {
        continue;
      }
      if (field.isReadOnly(this.data[this.data._objecttype], this.data)) {
        continue;
      }
      if (!field.hasUserData(top_level_data[top_level_data._objecttype], top_level_data, {
        mode: mode
      }) && !replace_empty) {
        continue;
      }
      field.mergeData(this.data, top_level_data, replace, is_restore);
    }
    return this;
  };

  ResultObject.prototype.getMask = function() {
    return this.mask;
  };

  ResultObject.prototype.getData = function() {
    return this.data;
  };

  ResultObject.prototype.hasChildren = function() {
    var ref;
    return !!((ref = this.data) != null ? ref._has_children : void 0);
  };

  ResultObject.prototype.hasParent = function() {
    var ref, ref1, ref2, ref3, ref4, ref5;
    if (ez5.version("6")) {
      return !!(((ref = this.data) != null ? (ref1 = ref._path) != null ? ref1.length : void 0 : void 0) > 1 || ((ref2 = this.data) != null ? (ref3 = ref2._paths) != null ? ref3.length : void 0 : void 0) > 1);
    } else {
      return !!(((ref4 = this.data) != null ? (ref5 = ref4._path) != null ? ref5.length : void 0 : void 0) > 1);
    }
  };

  ResultObject.prototype.getReplacementRecord = function() {
    return this.mask.getReplacementRecord(this.getData());
  };

  ResultObject.prototype.loadFromDbWithMask = function(mask) {
    return this.loadFromDb(null, mask);
  };

  ResultObject.prototype.loadFromDbWithFormat = function(format) {
    return this.loadFromDb(null, null, format);
  };

  ResultObject.prototype.loadFromDb = function(version, mask, format) {
    var url_data;
    if (mask == null) {
      mask = this.maskName();
    }
    if (format == null) {
      format = "long";
    }
    CUI.util.assert(this.id(), "ResultObject.loadFromDb", "Cannot load, no ID set.", {
      resultObject: this
    });
    url_data = {
      format: format
    };
    if (version) {
      url_data.version = version;
    }
    return ez5.api.db({
      type: "GET",
      api: "/" + this.objecttype() + "/" + mask + "/" + this.id(),
      data: url_data
    }).done((function(_this) {
      return function(data) {
        var newData;
        newData = data[0];
        if (newData) {
          _this.setData(newData);
        }
      };
    })(this));
  };

  ResultObject.prototype.loadFromSearch = function(search_data, mask_name) {
    var dfr;
    if (mask_name == null) {
      mask_name = null;
    }
    dfr = new CUI.Deferred();
    if (ez5.version("6")) {
      search_data.include_deleted = true;
    }
    ez5.api.search({
      data: {
        debug: "ResultObject.loadFromSearch"
      },
      json_data: search_data
    }).done((function(_this) {
      return function(searchData) {
        var best_mask_name;
        _this.searchData = searchData;
        if (_this.searchData.objects.length === 0) {
          console.warn("ResultObject.loadFromSearch: No object found for search.", search_data, mask_name);
          dfr.reject(new UserError({
            label: "result_object.error.not_found"
          }));
          return;
        }
        if (_this.searchData.objects.length === 1) {
          _this.setData(_this.searchData.objects[0]);
        } else {
          if (!mask_name) {
            best_mask_name = _this.getBestMaskName();
            if (!best_mask_name) {
              CUI.util.assert(_this.searchData.objects.length === 0, "ResultObject.loadFromSearch", "Object with _best_mask not found in response.", {
                data: _this.searchData
              });
              delete _this.searchData;
              console.warn("ResultObject.loadFromSearch: No best mask found.");
              dfr.reject(new UserError({
                label: "result_object.error.not_found"
              }));
              return;
            }
            mask_name = best_mask_name;
          }
          _this.setDataByMaskName(mask_name);
        }
        return dfr.resolve(_this);
      };
    })(this)).fail((function(_this) {
      return function(xhr) {
        console.warn("ResultObject.loadFromSearch[fail]:", xhr);
        return dfr.reject(new UserError({
          label: "result_object.error.not_found"
        }));
      };
    })(this));
    return dfr.promise();
  };

  ResultObject.prototype.setDataByMaskName = function(mask_name) {
    var best_mask_name, found, j, len, obj, ref, ref1;
    CUI.util.assert(CUI.util.isArray((ref = this.searchData) != null ? ref.objects : void 0), (CUI.util.getObjectClass(this)) + ".setDataByMaskName", "No search data found.", {
      searchData: this.searchData
    });
    best_mask_name = this.getBestMaskName();
    found = null;
    ref1 = this.searchData.objects;
    for (j = 0, len = ref1.length; j < len; j++) {
      obj = ref1[j];
      if (obj._mask === mask_name || (!mask_name && best_mask_name === obj._mask)) {
        this.setData(obj);
        found = obj._mask;
        break;
      }
    }
    if (mask_name && !found) {
      return this.setDataByMaskName();
    }
    CUI.util.assert(found, (CUI.util.getObjectClass(this)) + ".setDataByMaskName", "Mask " + mask_name + " not found in search data.", {
      searchData: this.searchData
    });
    return found;
  };

  ResultObject.prototype.getBestMaskName = function() {
    var j, len, obj, ref, ref1, ref2;
    if (!((ref = this.searchData) != null ? ref.objects : void 0)) {
      return null;
    }
    if (this.searchData.objects.length === 1) {
      return this.searchData.objects[0]._mask;
    }
    ref1 = this.searchData.objects;
    for (j = 0, len = ref1.length; j < len; j++) {
      obj = ref1[j];
      if (obj.__best_mask || obj._best_mask) {
        return obj._mask;
      }
    }
    if (!ez5.version("6")) {
      console.warn("ResultObject.getBestMaskName: Data from server does not contain ._best_mask. Using first object.", this.searchData);
    }
    return (ref2 = this.searchData.objects[0]) != null ? ref2._mask : void 0;
  };

  ResultObject.prototype.getAvailableMasks = function() {
    var j, len, mask, masks, obj, ref;
    masks = [];
    ref = this.searchData.objects;
    for (j = 0, len = ref.length; j < len; j++) {
      obj = ref[j];
      mask = ez5.mask.CURRENT._mask_instance_by_name[obj._mask];
      CUI.util.assert(mask instanceof Mask, "ResultObject.loadFromSearch", "Mask " + obj._mask + " not found in search data.", {
        searchData: this.searchData,
        mask: obj._mask
      });
      masks.push(mask);
    }
    return masks;
  };

  ResultObject.prototype.getArrayForSearchFilter = function() {
    return [this.objecttype(), this.id()];
  };

  ResultObject.prototype.getCollectionObject = function() {
    return new CollectionObject(this.getData());
  };

  ResultObject.prototype.isMappedMetadataCreated = function() {
    return !!this.data._mapped_metadata_created;
  };

  ResultObject.prototype.getGlobalObjectId = function() {
    var ref;
    return (ref = this.data) != null ? ref._global_object_id : void 0;
  };

  ResultObject.prototype.getInstance = function() {
    var ref;
    return ((ref = this.data) != null ? ref._instance : void 0) || "";
  };

  ResultObject.prototype.getBaseConfig = function() {
    var ref;
    return ((ref = this.getSession()) != null ? ref.getBaseConfig() : void 0) || {
      system: {}
    };
  };

  ResultObject.prototype.getSession = function() {
    var ref;
    if (!this.getInstance()) {
      return ez5.session;
    }
    return ((ref = this.getRemoteEasydb()) != null ? ref.getSession() : void 0) || null;
  };

  ResultObject.prototype.getRemoteEasydb = function() {
    if (!this.getInstance()) {
      return null;
    }
    return ez5.connector.getRemoteEasydbByInstance(this.getInstance());
  };

  ResultObject.prototype.getSystemObjectId = function() {
    var ref;
    return (ref = this.data) != null ? ref._system_object_id : void 0;
  };

  ResultObject.prototype.isDeleted = function() {
    var ref;
    return ((ref = this.getData()) != null ? ref._latest_version_deleted_at : void 0) != null;
  };

  ResultObject.prototype.isPurged = function() {
    var data;
    data = this.getData();
    if (data.format === "purged") {
      return true;
    }
    return ResultObject.dataFromPurgedObject(data);
  };

  ResultObject.dataFromPurgedObject = function(data) {
    if (!ez5.version("6")) {
      return false;
    }
    if (data.hasOwnProperty("_uuid") && data._mask && data._objecttype && !data._global_object_id && !data._mapped_metadata_created) {
      return true;
    }
    if (data.hasOwnProperty("_system_object_id") && data._mask && data._objecttype && !data._global_object_id && !data._mapped_metadata_created && !data.hasOwnProperty("_uuid")) {
      return true;
    }
    return false;
  };

  ResultObject.dataFromDeletedObject = function(data) {
    return data._latest_version_deleted_at != null;
  };

  ResultObject.dataFromDeletedOrPurgedObject = function(data) {
    return ResultObject.dataFromPurgedObject(data) || ResultObject.dataFromDeletedObject(data);
  };

  ResultObject.prototype.getUuid = function() {
    var ref;
    return (ref = this.data) != null ? ref._uuid : void 0;
  };

  ResultObject.prototype.uniqueId = function() {
    CUI.util.assert(false, "do not USE unique id");
    if (this.id()) {
      return this.data._objecttype + "-" + (this.id());
    }
  };

  ResultObject.prototype.copy = function() {
    var ro;
    ro = new ResultObject();
    ro.setData(CUI.util.copyObject(this.data, true));
    return ro;
  };

  ResultObject.prototype.initData = function(objecttype, data) {
    var ref;
    if (data == null) {
      data = {};
    }
    data._objecttype = objecttype;
    if (!data[objecttype]) {
      data[objecttype] = {
        _id: null
      };
    }
    if (!data._generated_rights) {
      data._generated_rights = {
        acl: true,
        "delete": true,
        write: true,
        read: true,
        unlink: true,
        change_owner: true
      };
    }
    if (!data._mask) {
      data._mask = (ref = ez5.schema.CURRENT._table_by_name[objecttype]) != null ? ref._preferred_mask.name : void 0;
    }
    return this.setData(data);
  };

  ResultObject.prototype.objecttype = function() {
    return this.data._objecttype;
  };

  ResultObject.prototype.objecttypeLocalized = function(include_instance) {
    var schema;
    if (include_instance == null) {
      include_instance = true;
    }
    schema = ez5.schema[this.mask.version]._objecttype_by_name[this.objecttype()];
    if (schema._instance && include_instance) {
      return schema._name_localized + '@' + ez5.connector.displaynameByInstance(schema._instance);
    } else {
      return schema._name_localized;
    }
  };

  ResultObject.prototype.maskName = function() {
    return this.data._mask;
  };

  ResultObject.prototype.getFormat = function() {
    return this.data._format;
  };

  ResultObject.prototype.getRights = function() {
    return this.data._generated_rights || {};
  };

  ResultObject.prototype.hasRight = function(right_name) {
    return this.getRights()[right_name] || false;
  };

  ResultObject.prototype.id = function(data) {
    var ref;
    if (data == null) {
      data = this.data;
    }
    return data != null ? (ref = data[data._objecttype]) != null ? ref._id : void 0 : void 0;
  };

  ResultObject.prototype.getParentId = function() {
    var ref;
    return ((ref = this.data) != null ? ref[this.objecttype()]._id_parent : void 0) || null;
  };

  ResultObject.prototype.getParents = function() {
    var ref;
    return ((ref = this.data) != null ? ref[this.objecttype()]._parents : void 0) || null;
  };

  ResultObject.prototype.getRootId = function() {
    var ref;
    if (!((ref = this.data._path) != null ? ref.length : void 0)) {
      return this.id();
    }
    return this.data._path[0][this.objecttype()]._id;
  };

  ResultObject.prototype.pool = function() {
    var ref, ref1;
    return (ref = this.data) != null ? (ref1 = ref[this.data._objecttype]) != null ? ref1._pool : void 0 : void 0;
  };

  ResultObject.prototype.changelog = function() {
    var ref;
    return ((ref = this.data) != null ? ref._changelog : void 0) || [];
  };

  ResultObject.prototype.version = function() {
    var ref, ref1;
    return (ref = this.data) != null ? (ref1 = ref[this.data._objecttype]) != null ? ref1._version : void 0 : void 0;
  };

  ResultObject.prototype.getVersion = function() {
    var ref;
    return (ref = this.data) != null ? ref[this.objecttype()]._version : void 0;
  };

  ResultObject.prototype.table = function() {
    return this.mask.table;
  };

  ResultObject.prototype.tableId = function() {
    return this.mask.table.id();
  };

  ResultObject.prototype.renderText = function(data) {
    if (data == null) {
      data = this.data;
    }
    if (data._system_object_id === 0) {
      return $$("base.path_column.root");
    }
    if (this.isPurged()) {
      return "(Purged)";
    }
    return ez5.loca.getBestDatabaseValue(this.__getFirstStandard(data).text);
  };

  ResultObject.prototype.renderCardSearchMini = function(opts) {
    if (opts == null) {
      opts = {};
    }
    opts.tags = true;
    opts.asset = true;
    opts.tags_mode = "search";
    opts.hideNoAssetPlaceholder = true;
    opts.standard2 = ez5.version("6");
    return this.__render("search-mini", opts);
  };

  ResultObject.prototype.renderCardLinkedObjectShort = function(opts) {
    if (opts == null) {
      opts = {};
    }
    opts.hideNoAssetPlaceholder = true;
    return this.__render("linked-object linked-object-short", opts);
  };

  ResultObject.prototype.renderCardLinkedObjectStandard = function(opts) {
    if (opts == null) {
      opts = {};
    }
    opts.asset = true;
    opts.show_hourglass = true;
    opts.standard2 = true;
    return this.__render("linked-object linked-object-standard", opts);
  };

  ResultObject.prototype.renderCardResultList = function(opts) {
    if (opts == null) {
      opts = {};
    }
    opts.asset = true;
    opts.show_hourglass = true;
    opts.standard2 = true;
    opts.tags = true;
    opts.tags_mode = "search";
    opts.system_fields = true;
    opts.path = false;
    return this.__render("result-list", opts);
  };

  ResultObject.prototype.renderCardResultTable = function(opts) {
    if (opts == null) {
      opts = {};
    }
    opts.asset = true;
    opts.show_hourglass = true;
    return this.__render("result-table", opts);
  };

  ResultObject.prototype.renderCardPrint = function(opts) {
    if (opts == null) {
      opts = {};
    }
    opts.asset = true;
    opts.hideNoAssetPlaceholder = true;
    if (opts.tags === void 0) {
      opts.tags = true;
      opts.tags_mode = "detail";
    }
    opts.standard2 = true;
    opts.system_fields = true;
    return this.__render("print", opts);
  };

  ResultObject.prototype.renderCardHierarchy = function(opts) {
    if (opts == null) {
      opts = {};
    }
    opts.asset = true;
    opts.show_hourglass = true;
    return this.__render("hierarchy", opts);
  };

  ResultObject.prototype.renderCardAutocomplete = function(opts) {
    if (opts == null) {
      opts = {};
    }
    opts.asset = true;
    opts.show_hourglass = true;
    opts.system_fields = true;
    return this.__render("autocomplete", opts);
  };

  ResultObject.prototype.renderCardDetail = function(opts) {
    if (opts == null) {
      opts = {};
    }
    if (opts.tags === void 0) {
      opts.tags = true;
      opts.tags_mode = "detail";
    }
    opts.standard2 = true;
    opts.system_fields = true;
    return this.__render("detail info", opts);
  };

  ResultObject.prototype.renderCardEditor = function(opts) {
    if (opts == null) {
      opts = {};
    }
    if (opts.tags === void 0) {
      opts.tags = true;
      opts.tags_mode = "editor";
    }
    opts.standard2 = true;
    opts.system_fields = true;
    opts.path_mode = "editor";
    return this.__render("editor info", opts);
  };

  ResultObject.prototype.renderCardStandard = function(opts) {
    var card;
    if (opts == null) {
      opts = {
        tags: true
      };
    }
    opts.tags_mode = "search";
    opts.lassoable = true;
    opts.asset = true;
    opts.asset_browser = true;
    if (opts.show_hourglass === void 0) {
      opts.show_hourglass = true;
    }
    opts.standard2 = true;
    opts.system_fields = true;
    card = this.__render("standard", opts);
    return card;
  };

  ResultObject.prototype.renderCardHires = function(opts) {
    var ref;
    if (opts == null) {
      opts = {};
    }
    CUI.util.assert((ref = this.getFormat()) === "long" || ref === "long_inheritance", "ResultObject.renderCardHires", "format \"long\" required.", {
      data: this.getData()
    });
    opts.hires = true;
    opts.asset = true;
    opts.asset_browser = true;
    if (opts.force_assets === void 0) {
      opts.force_assets = false;
    }
    if (opts.show_hourglass === void 0) {
      opts.show_hourglass = true;
    }
    opts.standard2 = true;
    opts.system_fields = true;
    return this.__render("hires", opts);
  };

  ResultObject.prototype.getStandard = function(data, force) {
    var standard;
    if (data == null) {
      data = this.data;
    }
    if (force == null) {
      force = false;
    }
    if (this.isPurged()) {
      return {};
    }
    if (!this.id(data) || force || CUI.util.isEmptyObject(data._standard)) {
      standard = this.getStandardData(data);
    } else {
      standard = data._standard;
    }
    return standard;
    CUI.util.assert(CUI.util.isPlainObject(standard), "ResultObject.__getStandard", "Unable to render, _standard not found in data.", {
      data: data
    });
    return standard;
  };

  ResultObject.prototype.getGeoStandard = function(data) {
    var ref;
    if (data == null) {
      data = this.data;
    }
    if (!this.id() || CUI.util.isEmptyObject(data != null ? (ref = data._standard) != null ? ref.geo : void 0 : void 0)) {
      return null;
    } else {
      return data._standard.geo[1];
    }
    CUI.util.assert(CUI.util.isPlainObject(geo_standard), "ResultObject.__getGeoStandard", "Unable to render, _geo_standard not found in data.", {
      data: data
    });
    return geo_standard;
  };

  ResultObject.prototype.__getFirstStandard = function(data) {
    var j, k, len, ref, standard;
    standard = this.getStandard(data);
    ref = [1, 2, 3];
    for (j = 0, len = ref.length; j < len; j++) {
      k = ref[j];
      if (!CUI.util.isEmpty(standard[k])) {
        return standard[k];
      }
    }
    return CUI.util.assert(false, "ResultObject.__getFirstStandard", "No rendered standard found in data", {
      data: data
    });
  };

  ResultObject.prototype.renderAltText = function(data) {
    var standard;
    if (data == null) {
      data = this.data;
    }
    standard = this.getStandard(data);
    return this.__getAltText(standard);
  };

  ResultObject.prototype.__getAltText = function(standard) {
    var j, k, len, ref, ref1, txt, value;
    txt = [];
    ref = [1, 2];
    for (j = 0, len = ref.length; j < len; j++) {
      k = ref[j];
      if (!standard[k]) {
        continue;
      }
      value = ez5.loca.getBestFrontendValue((ref1 = standard[k]) != null ? ref1.text : void 0);
      if (!CUI.util.isEmpty(value)) {
        txt.push(value);
      }
    }
    return txt.join("\n");
  };

  ResultObject.prototype.__render = function(cls, opts) {
    var _path, assetCount, assetElement, assetTypes, asset_browser_instance, assets, cl, container, customIcon, deletedLabel, eas_field, elem, els, fullPathContainer, idx, img_alt, j, l, labelNewerAvailable, len, len1, len2, len3, m, n, objecttypeText, objecttypeTextLocaKey, path, pf, purgedLabel, ref, ref1, ref2, renderPath, showPathButton, sid, sid_output, standard, standard_1, standard_2, tmpl, top_level_data, value, values, versionsIndicator;
    if (opts == null) {
      opts = {};
    }
    tmpl = new CUI.Template({
      name: "result-card",
      map: {
        asset: true,
        tags: true,
        path: true,
        standard_1: true,
        standard_2: true,
        objecttype: true,
        pool: true,
        system_object_id: true
      }
    });
    assetCount = 0;
    assetTypes = {};
    ref = cls.split(/\s+/);
    for (j = 0, len = ref.length; j < len; j++) {
      cl = ref[j];
      tmpl.addClass("ez5-card--" + cl);
    }
    if (CUI.util.isUndef(opts.path) && (this.mask.isHierarchy() || this.mask.isPolyhierarchy())) {
      if (opts.mode === "editor" || opts.path_mode === "editor") {
        opts.path = this.mask.schema.system_fields.parent.edit.mode !== "off";
      } else {
        opts.path = this.mask.schema.system_fields.parent.output.mode !== "off";
      }
    }
    if (opts.path && (this.mask.isHierarchy() || this.mask.isPolyhierarchy())) {
      if (!CUI.util.isArray(this.data._path) && !CUI.util.isArray(this.data._paths)) {
        console.warn("ResultObject.__render", "path_mode needs @data._path or @data._paths to be set. Ignoring.", {
          data: this.data
        });
      } else {
        renderPath = (function(_this) {
          return function(_path, renderTooltip, container) {
            var data, idx, l, len1, path, path_els, renderedPath, standard1, tooltipContent;
            if (renderTooltip == null) {
              renderTooltip = true;
            }
            path_els = [];
            for (idx = l = 0, len1 = _path.length; l < len1; idx = ++l) {
              data = _path[idx];
              if (data._global_object_id === _this.data._global_object_id) {
                continue;
              }
              path_els.push(_this.renderText(data));
            }
            if (path_els.length > 0) {
              renderedPath = ResultObject.renderPath(path_els, false, opts, !ez5.version("6"));
              if (container) {
                CUI.dom.append(container, renderedPath);
              } else {
                CUI.dom.addClass(tmpl.DOM, "ez5-has-path");
                tmpl.append(renderedPath, "path");
              }
              if (ez5.version("6") && renderTooltip) {
                tooltipContent = CUI.dom.div("ez5-tooltip-path-info");
                standard1 = CUI.dom.div("ez5-standard-1");
                CUI.dom.append(standard1, _this.renderText());
                path = ResultObject.renderPath(path_els, false, opts, !ez5.version("6"));
                CUI.dom.append(tooltipContent, [standard1, path]);
                return new CUI.Tooltip({
                  on_hover: true,
                  element: _this.mask.isPolyhierarchy() ? renderedPath : tmpl.get("path").parentElement,
                  content: tooltipContent
                });
              }
            }
          };
        })(this);
        path = this.getPathData(false);
        if (this.mask.isPolyhierarchy()) {
          for (l = 0, len1 = path.length; l < len1; l++) {
            _path = path[l];
            renderPath(_path);
            if (opts.path_short_mode && path.length > 1) {
              fullPathContainer = CUI.dom.div("ez5-result-card-path");
              for (m = 0, len2 = path.length; m < len2; m++) {
                _path = path[m];
                renderPath(_path, false, fullPathContainer);
              }
              CUI.dom.addClass(tmpl.get("path"), "ez5-path-short");
              showPathButton = new CUI.ButtonHref({
                text: "...",
                onClick: (function(_this) {
                  return function() {
                    var popover;
                    popover = new CUI.Popover({
                      element: showPathButton,
                      onHide: function() {
                        return popover.destroy();
                      },
                      pane: {
                        maximize: false,
                        content: fullPathContainer
                      }
                    });
                    popover.show();
                  };
                })(this)
              });
              tmpl.append(showPathButton, "path");
              break;
            }
          }
        } else {
          renderPath(path);
        }
      }
    }
    img_alt = null;
    value = null;
    sid = this.getSystemObjectId();
    if (this.isPurged()) {
      standard = {};
      standard_1 = null;
    } else {
      standard = this.getStandard(this.data, false);
      standard_1 = standard["1"] ? standard_1 = ez5.loca.getBestDatabaseValue(standard["1"].text) : sid ? standard_1 = "#" + sid : void 0;
    }
    if (sid) {
      sid_output = "#" + sid;
    } else {
      sid_output = "";
      tmpl.addClass("ez5-card--new");
      if (this.data.__isCopy) {
        if (!standard_1) {
          standard_1 = $$("main.editor.mode.copy");
        } else {
          sid_output = $$("main.editor.mode.copy");
        }
      } else {
        if (!standard_1) {
          standard_1 = $$("main.editor.mode.new");
        } else {
          sid_output = $$("main.editor.mode.new");
        }
      }
    }
    if (this.isPurged() && cls.includes("linked-object")) {
      purgedLabel = this.__createPurgedLabel();
      tmpl.append(purgedLabel, "standard_1");
    } else if (this.isDeleted() && cls.includes("linked-object")) {
      deletedLabel = this.__createDeletedLabel();
      if (standard_1) {
        container = CUI.dom.div("ez5-result-card-standard-with-deleted");
        CUI.dom.append(container, deletedLabel);
        CUI.dom.append(container, CUI.dom.text(" " + standard_1));
        tmpl.append(container, "standard_1");
      } else {
        tmpl.append(deletedLabel, "standard_1");
      }
    } else if (!this.isPurged()) {
      tmpl.append(standard_1, "standard_1");
    }
    if (standard_1 && (!cls.endsWith("linked-object-short") || !opts.path)) {
      new CUI.Tooltip({
        element: tmpl.get("standard_1"),
        text: standard_1
      });
    }
    if (opts.extra_button) {
      elem = CUI.dom.div("ez5-result-card-extra-button");
      elem.appendChild(opts.extra_button.DOM);
      this.__extra_button = opts.extra_button;
      CUI.dom.append(tmpl, elem);
    }
    if (opts.standard2 && standard["2"]) {
      standard_2 = ez5.loca.getBestDatabaseValue(standard["2"].text);
      tmpl.append(standard_2, "standard_2");
      if (standard_2) {
        new CUI.Tooltip({
          element: tmpl.get("standard_2"),
          text: standard_2
        });
      }
    }
    if (opts.system_fields) {
      pf = this.getMask().getPoolField();
      if (pf != null ? pf.isVisible(opts.mode, opts) : void 0) {
        top_level_data = CUI.util.copyObject(this.data);
        if (top_level_data._template) {
          top_level_data[this.objecttype()]._template = top_level_data._template[this.objecttype()];
        }
        tmpl.append(pf.renderDetailOutput(top_level_data[this.objecttype()], top_level_data), "pool");
      }
      objecttypeTextLocaKey = "result.object.card.objecttype." + (this.objecttype());
      if (ez5.loca.has(objecttypeTextLocaKey)) {
        objecttypeText = $$(objecttypeTextLocaKey, {
          objecttype: this.objecttypeLocalized()
        });
      } else {
        objecttypeText = this.objecttypeLocalized();
      }
      if (!this.isPurged()) {
        tmpl.append(CUI.dom.text(objecttypeText), "objecttype");
        tmpl.append(sid_output, "system_object_id");
      }
    }
    if (opts.tags) {
      els = this.renderTags("text", opts);
      if (els.length > 0) {
        tmpl.append(els, "tags");
        tmpl.addClass("ez5-has-tags");
      } else {
        tmpl.addClass("ez5-has-no-tags");
      }
    }
    if (opts.lassoable) {
      tmpl.addClass("ez5-lassoable");
    }
    if (opts.asset) {
      standard = this.getStandard(this.data, opts.hires);
      if (!this.getMask().hasStandardEASFields() && !opts.force_assets) {
        tmpl.addClass("ez5-mask-has-no-assets");
        if (!opts.hideNoAssetPlaceholder && !opts.for_print) {
          customIcon = this.getEmptyPlaceholderIcon();
          tmpl.append(EAS.getNoAssetInObjecttypePlaceholder(customIcon), "asset");
        }
      } else {
        tmpl.addClass("ez5-mask-has-assets");
        values = ((ref1 = standard.eas) != null ? ref1["1"] : void 0) || [];
        if (opts.asset_browser_instance instanceof AssetBrowser) {
          asset_browser_instance = opts.asset_browser_instance;
          assetCount = asset_browser_instance.getAssets().length;
        } else {
          eas_field = new EASField();
          assets = [];
          for (idx = n = 0, len3 = values.length; n < len3; idx = ++n) {
            value = values[idx];
            if (!CUI.util.isPlainObject(value)) {
              assets.push(new Asset(eas_field, {
                _error: {
                  code: "result.object.asset.faulty_data_from_server"
                }
              }));
              console.error("ResultObject.__render: standard.eas does not contain value", standard, this.getData(), this);
              continue;
            }
            assets.push(new Asset(eas_field, value, values, this.data));
            assetTypes[value["class"]] = true;
          }
          assetCount = assets.length;
        }
        if (opts.asset_browser) {
          if (asset_browser_instance) {
            assetElement = asset_browser_instance;
          } else {
            assetElement = new AssetBrowser({
              img_alt: this.__getAltText(standard),
              hires: opts.hires,
              assets: assets,
              show_hourglass: opts.show_hourglass,
              resultObject: this,
              for_print: opts.for_print,
              start_idx: opts.start_idx || 0,
              preferred_asset_size: opts.preferred_asset_size,
              custom_resize_events: opts.custom_resize_events,
              waitForResizeEvent: opts.waitForResizeEvent,
              fullscreen: opts.fullscreen
            });
          }
        } else {
          if (assetCount === 0) {
            if (opts.for_print) {
              tmpl.addClass("ez5-mask-has-no-assets");
            } else {
              customIcon = this.getEmptyPlaceholderIcon();
              assetElement = AssetBrowser.getNoAssetPlaceholder(customIcon);
            }
          } else {
            assetElement = assets[0].getImgElement(null, null, {
              for_print: opts.for_print,
              show_hourglass: opts.show_hourglass,
              alt: StandardField.getStandardText(this.data)
            });
          }
        }
        if (assetCount > 1) {
          versionsIndicator = CUI.dom.div("ez-asset-multiple-indicator", {
            ui: "result.object.multiple_indicator.icon"
          });
          CUI.dom.append(versionsIndicator, new CUI.Icon({
            icon: "svg-multiple"
          }));
          CUI.dom.append(assetElement, versionsIndicator);
        }
        tmpl.append(assetElement, "asset");
        if (opts.asset_browser && opts.hires) {
          tmpl.append(new LocaButton({
            "class": "ez5-result-object-detail-info-button",
            appearance: "transparent-border",
            ui: "result.object.detail_info.button",
            loca_key: "detail.info.button",
            onClick: (function(_this) {
              return function() {
                return _this.showModal();
              };
            })(this)
          }), "asset");
        }
      }
    }
    CUI.dom.setAttribute(tmpl.DOM, "ez5-number-of-assets", assetCount);
    CUI.dom.setAttribute(tmpl.DOM, "ez5-asset-types", Object.keys(assetTypes).join(" "));
    if (ez5.version("6") && ((ref2 = this.getData()) != null ? ref2._latest_version : void 0) === false) {
      labelNewerAvailable = new CUI.Label({
        icon: "fa-history",
        "class": "ez5-label-has-newer-version",
        tooltip: {
          text: $$("detail.history.linked-object.newer-available")
        }
      });
      CUI.dom.append(tmpl, labelNewerAvailable);
    }
    return tmpl.DOM;
  };

  ResultObject.prototype.getPathData = function(include_self) {
    if (include_self == null) {
      include_self = true;
    }
    if (this.data._paths) {
      return this.data._paths || [];
    }
    if (include_self) {
      return this.data._path;
    } else {
      return this.data._path.slice(0, this.data._path.length - 1);
    }
  };

  ResultObject.prototype.hasTags = function() {
    var ref;
    return ((ref = this.data._tags) != null ? ref.length : void 0) > 0;
  };

  ResultObject.prototype.getVirtualTags = function() {
    var pool;
    if (!ez5.version("6")) {
      return;
    }
    if (!this.pool()) {
      return;
    }
    pool = ez5.pools.findPoolById(this.pool().pool._id);
    if (!pool) {
      return;
    }
    return pool.getVirtualTags(this.data);
  };

  ResultObject.prototype.renderTags = function(style, opts) {
    var els, icon, j, l, len, len1, ref, systemTagsField, tag, vTag, virtualTags;
    if (opts == null) {
      opts = {};
    }
    CUI.util.assert(style === "icon" || style === "text", "ResultObject.renderTags", "style must be \"icon\" or \"text\"", {
      style: style
    });
    els = [];
    systemTagsField = this.mask.getFields(opts.mode || "all", opts).find((function(_this) {
      return function(f) {
        return f instanceof SystemTagsField;
      };
    })(this));
    if (systemTagsField) {
      els = els.concat(systemTagsField.getTags(this.data));
    }
    virtualTags = this.getVirtualTags();
    if (virtualTags) {
      for (j = 0, len = virtualTags.length; j < len; j++) {
        vTag = virtualTags[j];
        switch (style) {
          case "icon":
            icon = vTag.getIconElement();
            if (!icon) {
              continue;
            }
            els.push(icon);
            continue;
          case "text":
            els.push(vTag.getLabel(true, true).DOM);
        }
      }
    }
    if (!this.hasTags()) {
      return els;
    }
    if (opts.mode && !this.mask.getFields(opts.mode, opts).some((function(_this) {
      return function(f) {
        return f instanceof TagsField;
      };
    })(this))) {
      return els;
    }
    ref = ez5.tagForm.getTagsByData(this.data._tags);
    for (l = 0, len1 = ref.length; l < len1; l++) {
      tag = ref[l];
      if (!tag.isVisible(opts.tags_mode)) {
        continue;
      }
      switch (style) {
        case "icon":
          icon = tag.getIconElement();
          if (!icon) {
            continue;
          }
          els.push(icon);
          continue;
        case "text":
          els.push(tag.getLabel(true, true).DOM);
      }
    }
    return els;
  };

  ResultObject.prototype.dump = function() {
    console.info("--- " + (this.getGlobalObjectId()) + " ---");
    console.info(CUI.util.dump(this.data));
    return console.info("--- ---");
  };

  ResultObject.prototype.renderTitle = function() {
    var content, sid;
    content = [CUI.dom.text(this.objecttypeLocalized(), "objecttype")];
    if (sid = this.getSystemObjectId()) {
      content.push(CUI.dom.text("#" + sid, "sid"));
    } else if (this instanceof TemplateObject) {
      content.push(CUI.dom.addClass($empty$("main.editor.template"), "sid"));
    } else {
      content.push(CUI.dom.addClass($empty$("main.editor.new"), "sid"));
    }
    return new CUI.Label({
      "class": "result-object-title",
      content: content
    });
  };

  ResultObject.prototype.renderTextResult = function(opts) {
    var tmpl;
    if (opts == null) {
      opts = {};
    }
    tmpl = new CUI.Template({
      name: "result-object-text",
      map: {
        card: true,
        detail: true
      }
    });
    if (opts.tags === void 0) {
      opts.tags = true;
      opts.tags_mode = "search";
    }
    opts.standard2 = true;
    opts.system_fields = true;
    opts.asset = true;
    opts.asset_browser = true;
    opts.mode = "result-card-info-detail";
    tmpl.append(this.__render("text", opts), "card");
    tmpl.append(this.renderTextDetail(opts), "detail");
    return tmpl;
  };

  ResultObject.prototype.renderSystemObjectId = function() {
    return "#" + this.getSystemObjectId();
  };

  ResultObject.prototype.renderTextDetail = function(opts) {
    if (opts == null) {
      opts = {};
    }
    return this.mask.renderText(this.data, "text", null, opts);
  };

  ResultObject.prototype.renderPrint = function(opts) {
    var ab, asset, assets, dfr, fieldVisible, j, len, tmpl, visibleAssets;
    if (opts == null) {
      opts = {};
    }
    dfr = new CUI.Deferred();
    tmpl = new CUI.Template({
      "class": "ez5-print-object-mode-" + opts.printMode,
      name: "result-object-print",
      map: {
        card: true,
        detail: true,
        objecttype: true,
        id: true
      }
    });
    opts.for_print = true;
    opts.onDone = (function(_this) {
      return function() {
        var changeHistoryContainer;
        if (opts.addChangelog) {
          changeHistoryContainer = CUI.dom.div("ez5-print-change-history");
          CUI.dom.append(changeHistoryContainer, new CUI.Label({
            text: $$("changelog.column.name")
          }).DOM);
          CUI.dom.append(changeHistoryContainer, _this.renderHistoryForPrint().DOM);
          CUI.dom.append(tmpl.DOM, changeHistoryContainer);
        }
        dfr.resolve(tmpl.DOM);
      };
    })(this);
    if (opts.printMode === "detail") {
      tmpl.map.card.appendChild(this.renderCardPrint());
      assets = this.getAssetsForBrowser(["detail", "standard"]);
      if (CUI.util.isFunction(opts.isVisible)) {
        visibleAssets = [];
        for (j = 0, len = assets.length; j < len; j++) {
          asset = assets[j];
          fieldVisible = opts.isVisible(asset.field, "detail");
          if (fieldVisible || fieldVisible === void 0) {
            visibleAssets.push(asset);
          }
        }
      } else {
        visibleAssets = assets;
      }
      if (visibleAssets !== false && (visibleAssets != null ? visibleAssets.length : void 0) > 0) {
        ab = new AssetBrowser({
          hires: true,
          for_print: true,
          printLowRes: opts.printLowRes,
          assets: visibleAssets,
          start_idx: 0
        });
        CUI.dom.append(tmpl.map.detail, ab.DOM);
      }
      CUI.dom.append(tmpl.map.detail, this.renderDetail("detail", "detail-header", opts));
    } else if (opts.printMode === "standard") {
      CUI.dom.append(tmpl.map.detail, this.renderCardPrint(opts));
      dfr.resolve(tmpl.DOM);
    } else {
      CUI.dom.append(tmpl.map.detail, this.renderTextResult(opts));
    }
    return dfr.promise();
  };

  ResultObject.prototype.renderEditor = function(mode, header_mode, opts) {
    var div;
    if (opts == null) {
      opts = {};
    }
    CUI.util.assert(mode && header_mode && this.mask, "ResultObject.renderEditor", "mode, header_mode amd mask must be set", {
      ResultObject: this,
      Mask: this.mask,
      resultObject: this
    });
    div = this.mask.copy().renderEditor(this.data, mode, header_mode, opts);
    CUI.dom.addClass(div, "fields-renderer--root");
    return div;
  };

  ResultObject.prototype.renderDetail = function(mode, header_mode, opts) {
    var div, ref;
    if (opts == null) {
      opts = {};
    }
    CUI.util.assert(mode && header_mode && this.mask, "ResultObject.renderDetail", "mode, header_mode amd mask must be set", {
      ResultObject: this,
      Mask: this.mask,
      resultObject: this
    });
    CUI.util.assert(((ref = this.getFormat()) === "long" || ref === "full" || ref === "long_inheritance") || this.isMappedMetadataCreated() || this.isPurged(), "ResultObject.renderDetail", "format \"long\" or \"full\" required.", {
      data: this.getData()
    });
    if (this.isPurged()) {
      opts.is_purged = true;
    }
    div = this.mask.renderDetail(this.data, mode, header_mode, opts);
    CUI.dom.addClass(div, "fields-renderer--root");
    return div;
  };

  ResultObject.prototype.renderLastModifiedLabel = function() {
    if (!this.data._last_modified) {
      return;
    }
    return new LocaLabel({
      size: "mini",
      padded: true,
      centered: true,
      appearance: "muted",
      "class": "ez5-result-object-last-modified",
      loca_key: "result.object.detail.last_modified",
      loca_key_attrs: {
        last_modified: this.data._last_modified,
        version: this.getVersion()
      }
    });
  };

  ResultObject.prototype.renderDeletedHeader = function() {
    var __deletedObjectHeader, deletedLabel, deleted_date, loca_key_attrs, ref;
    if (!this.isDeleted() && !this.isPurged()) {
      return;
    }
    __deletedObjectHeader = CUI.dom.div("ez5-result-deleted-header");
    loca_key_attrs = null;
    if (this.isDeleted()) {
      deleted_date = (ref = this.getData()) != null ? ref._latest_version_deleted_at : void 0;
      loca_key_attrs = {
        deleted_date: ez5.format_date_and_time(deleted_date)
      };
    }
    deletedLabel = new LocaLabel({
      loca_key: "detail.sidebar.object." + (this.isDeleted() ? 'deleted' : 'purged'),
      "class": "ez5-deleted-object-label",
      loca_key_attrs: loca_key_attrs,
      multiline: true
    });
    CUI.dom.append(__deletedObjectHeader, deletedLabel.DOM);
    return __deletedObjectHeader;
  };

  ResultObject.prototype.__createDeletedLabel = function() {
    var deletedLabel;
    deletedLabel = new LocaLabel({
      loca_key: "result.object.deleted.label",
      "class": "ez5-deleted-object-label-inline italic"
    });
    return deletedLabel.DOM;
  };

  ResultObject.prototype.__createPurgedLabel = function() {
    var purgedLabel;
    purgedLabel = new LocaLabel({
      loca_key: "result.object.purged.label",
      "class": "ez5-purged-object-label-inline italic"
    });
    return purgedLabel.DOM;
  };

  ResultObject.prototype.getFormat = function() {
    return this.data._format;
  };

  ResultObject.prototype.getEASFields = function(mode) {
    return this.mask.getEASFields(mode);
  };

  ResultObject.prototype.isPluginSupported = function(plugin, mode) {
    return this.mask.isPluginSupported(plugin, mode);
  };

  ResultObject.prototype.getAssetsForBrowser = function(modes) {
    var _assets, appendStandardEAS, assets, filterAsset, filterAssetByFields, j, len, mode;
    CUI.util.assert(modes, "ResultObject.getAssetsForBrowser", "mode must be set", {
      ResultObject: this
    });
    filterAssetByFields = function(assets) {
      var asset, assetFieldMap, assetsFiltered, fieldName, j, len, ref;
      assetsFiltered = [];
      assetFieldMap = {};
      for (j = 0, len = assets.length; j < len; j++) {
        asset = assets[j];
        fieldName = asset.getField().name() + asset.getValue()._idx;
        if (((ref = assetFieldMap[asset.getValue()._id]) != null ? ref.length : void 0) > 0) {
          if (assetFieldMap[asset.getValue()._id].some((function(_this) {
            return function(v) {
              return v === fieldName;
            };
          })(this))) {
            continue;
          } else {
            assetsFiltered.push(asset);
            assetFieldMap[asset.getValue()._id].push(fieldName);
          }
        } else {
          assetsFiltered.push(asset);
          assetFieldMap[asset.getValue()._id] = [fieldName];
        }
      }
      return assetsFiltered;
    };
    appendStandardEAS = (function(_this) {
      return function(assets) {
        var eas, j, len, newAsset, standard, standard_assets, standard_eas;
        standard = _this.getStandard();
        if (!standard.eas) {
          return assets;
        }
        standard_eas = standard.eas["1"];
        if (!standard_eas || standard_eas.length === 0) {
          return assets;
        }
        standard_assets = [];
        for (j = 0, len = standard_eas.length; j < len; j++) {
          eas = standard_eas[j];
          if (assets.some(function(a) {
            return a.getValue()._id === eas._id;
          })) {
            continue;
          }
          newAsset = new Asset(new EASField(), eas, standard_eas, _this.data);
          standard_assets.push(newAsset);
        }
        assets = standard_assets.concat(assets);
        return assets;
      };
    })(this);
    filterAsset = function(assets) {
      var asset, assetsFiltered, idAssets, j, len, value;
      if (ez5.version("6")) {
        return fylrFilterAsset(assets);
      }
      idAssets = new Set();
      assetsFiltered = [];
      for (j = 0, len = assets.length; j < len; j++) {
        asset = assets[j];
        value = asset.getValue();
        if (idAssets.has(value._id)) {
          continue;
        }
        idAssets.add(value._id);
        assetsFiltered.push(asset);
      }
      return assetsFiltered;
    };
    if (CUI.util.isArray(modes)) {
      assets = [];
      for (j = 0, len = modes.length; j < len; j++) {
        mode = modes[j];
        _assets = this.mask.getAssetsForBrowser(this.data, mode);
        if (_assets) {
          assets = assets.concat(_assets);
        }
      }
      assets = filterAssetByFields(assets);
    } else {
      assets = filterAssetByFields(this.mask.getAssetsForBrowser(this.data, modes));
    }
    return appendStandardEAS(assets);
  };

  ResultObject.loadAssetVariantsFromLinkedObject = function(asset, linked_data, depth) {
    var dfr, ro;
    if (depth == null) {
      depth = 0;
    }
    dfr = new CUI.Deferred();
    if (depth >= 5) {
      return dfr.resolve([]);
    }
    ro = new ResultObject().setData(linked_data);
    ro.loadFromDbWithFormat("full").done((function(_this) {
      return function() {
        var assets, linked_asset;
        assets = ro.getAssetsForBrowser("detail");
        linked_asset = assets.find(function(a) {
          return a.getId() === asset.getId();
        });
        if (linked_asset.values && linked_asset.values._system_object_id) {
          return ResultObject.loadAssetVariantsFromLinkedObject(linked_asset, linked_asset.values, depth + 1).done(function(assets) {
            return dfr.resolve(assets);
          }).fail(function() {
            return dfr.resolve([]);
          });
        } else {
          return dfr.resolve(linked_asset.values || []);
        }
      };
    })(this)).fail((function(_this) {
      return function() {
        return dfr.resolve([]);
      };
    })(this));
    return dfr.promise();
  };

  ResultObject.prototype.getSaveData = function(opts) {
    var data;
    if (opts == null) {
      opts = {};
    }
    data = this.mask.getSaveData(this.data, opts);
    if (opts.copy) {
      data.__isCopy = opts.copy;
    }
    return data;
  };

  ResultObject.prototype.checkSaveData = function(opts) {
    return this.mask.checkSaveData(this.data, opts);
  };

  ResultObject.prototype.initSaveData = function(opts) {
    var exception;
    if (opts == null) {
      opts = {};
    }
    this.__initSaveData = null;
    try {
      opts.init_save_data = true;
      return this.__initSaveData = this.getSaveData(opts);
    } catch (error1) {
      exception = error1;
      if (!(exception instanceof InvalidSaveDataException)) {
        throw exception;
      }
    }
  };

  ResultObject.prototype.hasChangedSaveData = function() {
    var current_save_data, ex, opts;
    try {
      opts = {
        check_changed: true
      };
      current_save_data = this.getSaveData(opts);
    } catch (error1) {
      ex = error1;
      if (ex instanceof InvalidSaveDataException) {
        return -1;
      }
      throw ex;
    }
    return !CUI.util.isEqual(this.__initSaveData, current_save_data, true);
  };

  ResultObject.prototype.getCopyFromSaveData = function() {
    var dfr;
    dfr = new CUI.Deferred();
    ResultObject.loadFromGlobalObjectId(this.getGlobalObjectId()).done((function(_this) {
      return function(ro) {
        var save_data;
        save_data = ro.getSaveData({
          copy: true
        });
        ro.initData(_this.objecttype(), save_data);
        return dfr.resolve(ro);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  ResultObject.prototype.getStandardData = function(data) {
    var _html, _standard, _text, c, container, eas_value, eas_values, element, get_eas, idx, info, j, l, last, len, len1, len2, m, order, ref, ref1, ref2, ref3, sid, span, standard, value;
    standard = this.mask.renderStandard(data);
    _standard = {};
    get_eas = (function(_this) {
      return function(order) {
        var eas, ref;
        eas = (ref = _standard.eas) != null ? ref[order] : void 0;
        if (!eas) {
          if (!_standard.eas) {
            _standard.eas = {};
          }
          eas = _standard.eas[order] = [];
        }
        return eas;
      };
    })(this);
    for (idx = j = 0, len = standard.length; j < len; idx = ++j) {
      element = standard[idx];
      order = element.render_info.order;
      if (element.field instanceof EASColumn) {
        value = element.field.getImgValuePreferred(element.data);
        if (CUI.util.isEmpty(value)) {
          continue;
        }
        get_eas(order).push(value);
        continue;
      }
      if (element.field instanceof LinkedObject && element.eas) {
        eas_values = (ref = element.data[element.field.name()]) != null ? (ref1 = ref._standard) != null ? (ref2 = ref1.eas) != null ? ref2["1"] : void 0 : void 0 : void 0;
        if (eas_values && eas_values.length > 0) {
          for (l = 0, len1 = eas_values.length; l < len1; l++) {
            eas_value = eas_values[l];
            get_eas(order).push(eas_value);
            eas_value._incomplete_versions = true;
          }
        }
        continue;
      }
      if (CUI.util.isEmpty(element.value)) {
        continue;
      }
      if (!(container = _standard[order])) {
        container = _standard[order] = {
          __info: []
        };
      }
      container.__info.push({
        design: element.render_info.design,
        format: element.render_info.format,
        value: element.value
      });
    }
    if (!_standard["1"]) {
      sid = this.getSystemObjectId();
      if (sid) {
        sid = '#' + sid;
      } else {
        sid = '';
      }
      _standard["1"] = {
        __info: [
          {
            design: "normal",
            format: "comma",
            value: sid
          }
        ]
      };
    }
    for (order in _standard) {
      container = _standard[order];
      if (order === "eas") {
        continue;
      }
      _text = [];
      _html = CUI.dom.span("ez-output-" + order);
      ref3 = container.__info;
      for (idx = m = 0, len2 = ref3.length; m < len2; idx = ++m) {
        info = ref3[idx];
        last = idx === container.__info.length - 1;
        c = StandardField.getSeparatorsMap()[info.format] || [", "];
        if (c.length === 1) {
          _text.push(info.value);
          if (!last) {
            _text.push(c);
          }
        } else {
          _text.push(c[0]);
          _text.push(info.value);
          _text.push(c[1]);
        }
        span = CUI.dom.span("ez-design-" + info.design + " ez-format-" + info.format);
        span.textContent = info.value;
        CUI.dom.append(_html, span);
      }
      _standard[order] = {
        text: {},
        html: {}
      };
      _standard[order].text[ez5.loca.culture] = _text.join("").trim();
      _standard[order].html[ez5.loca.culture] = _html.outerHTML;
      delete _standard[order].__info;
    }
    return _standard;
  };

  ResultObject.prototype.renderHistoryForPrint = function() {
    var columns, j, len, ref, ref1, ref2, rows, user_name, version;
    if (this.changelog().length === 0) {
      return new CUI.EmptyLabel({
        text: $$("changelog.no_changelog_found"),
        padded: true
      });
    }
    columns = [
      {
        name: "version",
        text: "Version"
      }, {
        name: "time",
        text: $$("changelog.column.created")
      }, {
        name: "user",
        text: $$("changelog.column.popover.form.who")
      }, {
        name: "operation",
        text: $$("changelog.column.popover.form.operation")
      }, {
        name: "comment",
        text: $$("changelog.column.popover.form.comment")
      }
    ];
    rows = [];
    ref = this.changelog();
    for (j = 0, len = ref.length; j < len; j++) {
      version = ref[j];
      if (ez5.session.hasSystemRight("root", "frontend_features[changelog_with_user]") || this.hasRight("write")) {
        if (!CUI.util.isEmpty((ref1 = version.user) != null ? (ref2 = ref1.user) != null ? ref2._generated_displayname : void 0 : void 0)) {
          user_name = version.user.user._generated_displayname;
        }
      } else {
        user_name = "";
      }
      rows.push({
        version: version.version,
        time: ez5.format_date_and_time(version.time),
        user: user_name,
        operation: $$("changelog.operation." + version.operation),
        comment: version.comment
      });
    }
    return new CUI.Table({
      columns: columns,
      rows: rows,
      maximize_horizontal: true
    });
  };

  ResultObject.prototype.renderHistoryBrowser = function(closeButton, editor) {
    var __comment, __historyBrowserToolbar, __historyCloseToolbar, _historyBrowserRestoreToolbar, diffLegend, fn, get_prev_version, historyBrowserSelect, historyBrowserTitle, historyElements, j, l, label, layout, legendItems, len, len1, markDifferencesCheck, opts, ref, ref1, restore_button, show_version, status, version;
    this.history_browser_data.diff = false;
    __historyCloseToolbar = new CUI.PaneToolbar({
      "class": "history-close-toolbar"
    });
    __historyBrowserToolbar = new CUI.PaneToolbar({
      "class": "history-browser-toolbar"
    });
    if (editor != null) {
      _historyBrowserRestoreToolbar = new CUI.PaneToolbar({
        "class": "history-browser-restore-toolbar"
      });
    } else {
      _historyBrowserRestoreToolbar = null;
    }
    __comment = new CUI.VerticalLayout({
      "class": "history-comment",
      center: {
        content: "center"
      },
      maximize_horizontal: true
    });
    layout = new CUI.VerticalLayout({
      "class": "ez5-result-object-history-browser",
      top: {
        content: [__historyCloseToolbar, __historyBrowserToolbar, __comment]
      },
      center: {
        content: []
      },
      bottom: {
        content: _historyBrowserRestoreToolbar
      }
    });
    if (this.changelog().length === 0) {
      layout.replace(new CUI.EmptyLabel({
        padded: true,
        text: $$("changelog.no_changelog_found")
      }), "center");
      return layout;
    }
    opts = [];
    ref = this.changelog();
    fn = (function(_this) {
      return function(version) {
        var key, ref1, ref2, user_name;
        if (!CUI.util.isEmpty((ref1 = version.user) != null ? (ref2 = ref1.user) != null ? ref2._generated_displayname : void 0 : void 0) && (ez5.session.hasSystemRight("root", "frontend_features[changelog_with_user]") || _this.hasRight("write"))) {
          user_name = version.user.user._generated_displayname;
          key = "changelog.select.option";
        } else {
          key = "changelog.select.option.hidden_user";
        }
        return opts.push({
          text: $$(key, {
            version: version.version,
            time: version.time,
            user: user_name,
            operation: $$("changelog.operation." + version.operation)
          }),
          value: version
        });
      };
    })(this);
    for (j = 0, len = ref.length; j < len; j++) {
      version = ref[j];
      fn(version);
    }
    opts.reverse();
    get_prev_version = (function(_this) {
      return function(version) {
        var prevIdx;
        if (_this.changelog() && _this.changelog().length < 2) {
          return;
        }
        if (!version) {
          return _this.changelog()[_this.changelog().length - 2];
        }
        prevIdx = _this.changelog().findIndex(function(v) {
          return v.version === version;
        }) - 1;
        if (prevIdx < 0) {
          return;
        }
        return _this.changelog()[prevIdx];
      };
    })(this);
    show_version = (function(_this) {
      return function(version) {
        var ro, wb;
        if (!CUI.util.isEmpty(version.comment)) {
          __comment.replace([
            new CUI.Label({
              text: 'Comment',
              "class": 'history-comment-label',
              padded: true
            }), new CUI.MultilineLabel({
              text: version.comment,
              padded: true
            })
          ], "center");
        } else {
          __comment.replace(new CUI.EmptyLabel({
            padded: true,
            text: $$("result.object.history_browser.no_comment")
          }), "center");
        }
        if (version.current_version && !_this.history_browser_data.diff && !ez5.version("6")) {
          _this.__versionNumber = null;
        } else {
          _this.__versionNumber = version.version;
        }
        wb = new CUI.WaitBlock({
          element: layout.center()
        }).show();
        ro = _this.copy();
        return ro.loadFromDb(_this.__versionNumber).always(function() {
          return wb.destroy();
        }).fail(function() {
          return layout.replace(new CUI.EmptyLabel({
            centered: true,
            multiline: true,
            text: $$("result.object.history_browser.failed_loading.md")
          }), "center");
        }).done(function(data) {
          var historyData, prevVersion, prevVersionRo, renderHistory;
          historyData = data[0];
          renderHistory = function() {
            var isLastVersion, ref1;
            isLastVersion = historyData._current_version || historyData._latest_version;
            if (isLastVersion && (typeof restore_button !== "undefined" && restore_button !== null)) {
              restore_button.hide();
            } else if (typeof restore_button !== "undefined" && restore_button !== null) {
              restore_button.show();
            }
            if ((isLastVersion && !_this.__versionNumber) || (_this.__versionNumber && ((ref1 = historyData[historyData._objecttype]) != null ? ref1._version : void 0) === _this.__versionNumber)) {
              return layout.replace(ro.renderDetail("detail", "detail-header", {
                history: true
              }), "center");
            }
          };
          if (_this.history_browser_data.diff) {
            prevVersion = get_prev_version(_this.__versionNumber);
            if (!prevVersion) {
              renderHistory();
              return;
            }
            prevVersionRo = _this.copy();
            return prevVersionRo.loadFromDb(prevVersion.version).done(function() {
              ro.addVersionDifferences(prevVersionRo);
              return renderHistory();
            });
          } else {
            return renderHistory();
          }
        });
      };
    })(this);
    if (!this.history_browser_data.version) {
      this.history_browser_data.version = opts[0].value;
    }
    show_version(this.history_browser_data.version);
    historyBrowserSelect = new CUI.Select({
      options: opts,
      mark_changed: false,
      name: "version",
      "class": "history-browser-select",
      data: this.history_browser_data,
      maximize_horizontal: true,
      ui: "result.object.history_browser.select",
      onDataChanged: (function(_this) {
        return function() {
          return show_version(_this.history_browser_data.version);
        };
      })(this)
    }).start();
    diffLegend = new CUI.dom.div();
    CUI.dom.addClass(diffLegend, "history-legend");
    legendItems = [];
    ref1 = ["added", "modified", "deleted"];
    for (l = 0, len1 = ref1.length; l < len1; l++) {
      status = ref1[l];
      label = new CUI.Label({
        text: $$("result.object.history_browser.difference.status." + status),
        "class": "history-legend-label history-legend-label-" + status
      });
      legendItems.push(label);
    }
    CUI.dom.append(diffLegend, legendItems);
    markDifferencesCheck = new CUI.Checkbox({
      name: "diff",
      text: $$("result.object.history_browser.difference.checkbox"),
      "class": "history-mark-difference-checkbox",
      data: this.history_browser_data,
      onDataChanged: (function(_this) {
        return function(data, element) {
          show_version(_this.history_browser_data.version);
          if (data.diff) {
            return CUI.dom.append(CUI.dom.parent(element), diffLegend);
          } else {
            return CUI.dom.remove(diffLegend);
          }
        };
      })(this)
    }).start();
    historyElements = new CUI.VerticalList({
      maximize: true,
      content: [historyBrowserSelect, markDifferencesCheck]
    });
    historyBrowserTitle = new CUI.Label({
      text: $$("detail.sidebar.change-history.button|text")
    });
    __historyCloseToolbar.replace(historyBrowserTitle, "left");
    if (closeButton) {
      __historyCloseToolbar.replace(closeButton, "right");
    }
    __historyBrowserToolbar.replace(historyElements, "center");
    if ((editor != null) && ez5.version("6") && ez5.session.hasSystemRight("root", "frontend_features[changelog]")) {
      restore_button = new LocaButton({
        loca_key: "result.object.history_browser.restore.button",
        "class": "history-browser-restore-button",
        ui: "result.object.history_browser.restore.button",
        onClick: (function(_this) {
          return function() {
            if (_this.history_browser_data.version) {
              return CUI.confirm({
                text: $$("result.object.history_browser.restore.confirm"),
                button_text_ok: $$("result.object.history_browser.restore.confirm.ok"),
                button_text_cancel: $$("result.object.history_browser.restore.confirm.cancel"),
                markdown: true
              }).done(function() {
                editor.closeHistoryBrowser();
                return editor.restoreVersion(_this.history_browser_data.version.version);
              });
            } else {
              return CUI.dom.alert($$("result.object.history_browser.restore.error"));
            }
          };
        })(this)
      });
      _historyBrowserRestoreToolbar.replace(restore_button, "right");
    }
    return layout.DOM;
  };

  ResultObject.prototype.addVersionDifferences = function(roToCompare) {
    var addedTagIds, compareTagIds, compareTags, compareValue, currentTagIds, currentTags, dataForCompare, fieldName, ref, ref1, ref2, ref3, removedTagIds, value;
    dataForCompare = roToCompare.getData();
    this.data.versionDiff = {};
    ref = this.data[this.objecttype()];
    for (fieldName in ref) {
      value = ref[fieldName];
      compareValue = (ref1 = dataForCompare[this.objecttype()]) != null ? ref1[fieldName] : void 0;
      if (CUI.util.isBoolean(value) && CUI.util.isBoolean(compareValue)) {
        if (value !== compareValue) {
          this.data.versionDiff[fieldName] = "modified";
        }
      } else if (value && !compareValue) {
        this.data.versionDiff[fieldName] = "added";
      } else if (value != null ? value._system_object_id : void 0) {
        if (value._system_object_id !== compareValue._system_object_id) {
          this.data.versionDiff[fieldName] = "modified";
        }
      } else if (value && (((ref2 = value[0]) != null ? ref2.hash : void 0) != null)) {
        if (value.hash !== compareValue.hash) {
          this.data.versionDiff[fieldName] = "modified";
        }
      } else {
        if (value && !CUI.util.isEqual(value, compareValue)) {
          this.data.versionDiff[fieldName] = "modified";
        }
      }
    }
    ref3 = dataForCompare[this.objecttype()];
    for (fieldName in ref3) {
      value = ref3[fieldName];
      if (this.data[this.objecttype()][fieldName] || CUI.util.isBoolean(value)) {
        continue;
      }
      this.data[this.objecttype()][fieldName] = value;
      this.data.versionDiff[fieldName] = "deleted";
    }
    currentTags = this.data._tags || [];
    compareTags = dataForCompare._tags || [];
    currentTagIds = currentTags.map(function(t) {
      return t._id;
    });
    compareTagIds = compareTags.map(function(t) {
      return t._id;
    });
    addedTagIds = currentTagIds.filter(function(id) {
      return compareTagIds.indexOf(id) === -1;
    });
    removedTagIds = compareTagIds.filter(function(id) {
      return currentTagIds.indexOf(id) === -1;
    });
    if (addedTagIds.length > 0 || removedTagIds.length > 0) {
      if (addedTagIds.length > 0 && compareTags.length === 0) {
        this.data.versionDiff["_tags"] = "added";
      } else if (removedTagIds.length > 0 && currentTags.length === 0) {
        this.data.versionDiff["_tags"] = "deleted";
      } else {
        this.data.versionDiff["_tags"] = "modified";
      }
      return this.data.versionTagsDiff = {
        addedTagIds: addedTagIds,
        removedTagIds: removedTagIds
      };
    }
  };

  ResultObject.prototype.showModal = function(_opts) {
    var deletedHeader, mod, mod_opts, modalContent, opts;
    if (_opts == null) {
      _opts = {
        modal: {}
      };
    }
    opts = CUI.Element.readOpts(_opts, "ResultObject.showModal", {
      modal: {
        mandatory: true,
        check: "PlainObject"
      }
    });
    CUI.dom.exitFullscreen();
    mod_opts = CUI.util.copyObject(opts.modal, false);
    if (!mod_opts.hasOwnProperty('fill_space')) {
      mod_opts.fill_space = 'vertical';
    }
    modalContent = [this.renderCardDetail(), this.renderDetail("detail", "detail-header")];
    if (this.isDeleted()) {
      deletedHeader = this.renderDeletedHeader();
      modalContent.unshift(deletedHeader);
    }
    CUI.mergeMap(mod_opts, {
      "class": "ez5-result-object-details-modal",
      cancel: true,
      onHide: (function(_this) {
        return function() {
          return mod.destroy();
        };
      })(this),
      pane: {
        header_left: new LocaLabel({
          loca_key: "detail.sidebar.title"
        }),
        content: modalContent
      }
    });
    mod = new CUI.Modal(mod_opts);
    this.setCSSClasses(mod);
    mod.show();
    return mod;
  };

  ResultObject.prototype.showPopover = function(_opts) {
    var assetBrowser, assetBrowserBtn, assets, deletedHeader, headerButtons, infoControl, layout, mainContent, opts, pop, pop_opts, pullOutLayout, pulloutSwitch, ref, resultCardPinButton;
    opts = CUI.Element.readOpts(_opts, "ResultObject.showPopover", {
      detail: {
        check: DetailSidebar
      },
      popover: {
        mandatory: true,
        check: "PlainObject"
      }
    });
    pop_opts = CUI.util.copyObject(opts.popover, false);
    mainContent = [
      this.renderCardDetail({
        detail: opts.detail
      }), this.renderDetail("detail", "detail-header", {
        detail: opts.detail
      })
    ];
    assets = this.getAssetsForBrowser("detail");
    assetBrowserBtn = null;
    if (assets.length > 0) {
      pulloutSwitch = new CUI.Buttonbar({
        buttons: [
          assetBrowserBtn = new LocaButton({
            loca_key: "editor.pullout.asset_browser",
            hidden: false,
            radio_allow_null: true,
            group: "pull-out",
            radio: "editor-pull-out",
            onDeactivate: (function(_this) {
              return function(btn, flags, event) {
                return pullOutLayout.getFlexHandle("top").hide().close();
              };
            })(this),
            onActivate: (function(_this) {
              return function(btn, flags, event) {
                return pullOutLayout.getFlexHandle("top").show().open();
              };
            })(this)
          })
        ]
      });
      assetBrowser = new AssetBrowser({
        ui: "asset.browser.popover",
        assets: assets,
        hires: true,
        start_idx: 0
      });
      infoControl = new AssetBrowserInfoControl({
        assetBrowser: assetBrowser
      });
      pullOutLayout = new CUI.VerticalLayout({
        "class": "ez5-detail-popover-pane",
        center: {
          content: mainContent
        },
        top: {
          content: [assetBrowser, infoControl],
          flexHandle: {
            hidden: true,
            closed: true,
            state_name: "detail-popover-pullout"
          }
        }
      });
      layout = [pulloutSwitch, pullOutLayout];
    } else {
      layout = mainContent;
    }
    if (this.isDeleted() || this.isPurged()) {
      deletedHeader = this.renderDeletedHeader();
      layout.unshift(deletedHeader);
    }
    headerButtons = [];
    if (ez5.version("6") && !(this.isDeleted() || this.isPurged())) {
      headerButtons.push({
        icon: $$("tool.object.show.new_tab|icon"),
        tooltip: {
          text: $$("tool.object.show.new_tab|tooltip")
        },
        onClick: (function(_this) {
          return function() {
            return window.open(window.easydb_base_prefix + "/#/detail/" + (_this.getGlobalObjectId()), "_blank");
          };
        })(this)
      });
    }
    CUI.mergeMap(pop_opts, {
      "class": "ez5-result-object-details-popover",
      fill_screen_button: !this.isPurged(),
      header_buttons: headerButtons,
      onHide: (function(_this) {
        return function() {
          return pop.destroy();
        };
      })(this),
      placement: "w",
      pane: {
        header_left: new LocaLabel({
          loca_key: "detail.sidebar.title"
        }),
        maximize_horizontal: false,
        maximize_vertical: true,
        content: (function(_this) {
          return function() {
            return layout;
          };
        })(this)
      }
    });
    pop = new CUI.Popover(pop_opts);
    this.setCSSClasses(pop);
    pop.show();
    if (ez5.version("6") && ((ref = ez5.cssLoader.getActiveCSS()) != null ? ref.theme : void 0) === 'fylr') {
      resultCardPinButton = ResultObject.getResultCardPinButton(pullOutLayout);
      CUI.dom.append(mainContent[0], resultCardPinButton);
    }
    if (assetBrowserBtn != null) {
      assetBrowserBtn.setActive(true);
    }
    return pop;
  };

  ResultObject.prototype.setCSSClasses = function(element) {
    CUI.dom.setAttributeMap(element, {
      "ez5-objecttype": this.objecttype(),
      "ez5-mask": this.maskName()
    });
    return this;
  };

  ResultObject.prototype.getDetailShareUrl = function() {
    var id, ref, shareUrl;
    shareUrl = document.location.origin + window.easydb_base_prefix;
    if (window.easydb_server_url && window.easydb_server_url !== shareUrl) {
      shareUrl += "?server=" + encodeURIComponent(window.easydb_server_url);
    }
    if (this.getInstance()) {
      shareUrl += "#/detail/" + (this.getGlobalObjectId());
    } else {
      if ((ref = ez5.session.getBaseConfig().detail_deep_link) != null ? ref.use_system_object_id : void 0) {
        id = this.getSystemObjectId();
      } else {
        id = this.getUuid();
      }
      shareUrl += "#/detail/" + id;
    }
    return shareUrl;
  };

  ResultObject.prototype.getDeeplinkUrl = function(use_token) {
    var arr, dfr, objectUrlToReturn, objectsUrl;
    if (use_token == null) {
      use_token = false;
    }
    if (!this.getUuid()) {
      return CUI.rejectedPromise();
    }
    dfr = new CUI.Deferred();
    arr = ["", "uuid", this.getUuid()];
    objectsUrl = arr.join("/");
    objectUrlToReturn = "/api/v1/objects" + objectsUrl;
    if (use_token) {
      objectUrlToReturn = objectUrlToReturn + "?" + ez5.tokenParam + "=" + (encodeURIComponent(ez5.session.token));
    }
    ez5.api.objects({
      api: objectsUrl,
      remoteEasydb: this.getRemoteEasydb(),
      handle_error: (function(_this) {
        return function(xhr) {
          var ref, ref1;
          if ((ref = xhr != null ? (ref1 = xhr.responseJSON) != null ? ref1.code : void 0 : void 0) === "error.user.objects_not_allowed" || ref === "error.user.object_not_found" || ref === "ObjectInsufficientRights") {
            return true;
          }
        };
      })(this),
      add_token: false
    }).done((function(_this) {
      return function() {
        return dfr.resolve(objectUrlToReturn);
      };
    })(this)).fail((function(_this) {
      return function() {
        if (use_token) {
          return dfr.resolve(objectUrlToReturn);
        } else {
          return dfr.reject();
        }
      };
    })(this));
    return dfr.promise();
  };

  ResultObject.prototype.getOaiPmhUrl = function() {
    var arr, dfr, oai_pmh, object_url, parms;
    if (!this.getUuid()) {
      return CUI.rejectedPromise();
    }
    oai_pmh = this.getBaseConfig().oai_pmh;
    if (!oai_pmh) {
      return CUI.rejectedPromise();
    }
    dfr = new CUI.Deferred();
    arr = ["", "uuid", this.getUuid()];
    object_url = arr.join("/");
    parms = {
      verb: "GetRecord",
      identifier: "oai:" + oai_pmh.namespace_identifier + ":" + this.getUuid(),
      metadataPrefix: "easydb"
    };
    if (ez5.version("6")) {
      object_url = "/api/v1/oai?" + CUI.encodeUrlData(parms);
    } else {
      object_url = "/api/v1/plugin/base/oai/oai?" + CUI.encodeUrlData(parms);
    }
    ez5.server({
      url: object_url,
      remoteEasydb: this.getRemoteEasydb(),
      dataType: "text",
      handle_error: (function(_this) {
        return function(xhr) {
          return true;
        };
      })(this),
      add_token: false
    }).fail(dfr.reject).done((function(_this) {
      return function(data, status, xhr) {
        var error, parser, xml;
        if (!window.DOMParser) {
          dfr.resolve(object_url);
          return;
        }
        parser = new window.DOMParser();
        xml = parser.parseFromString(data, "text/xml");
        error = xml.querySelector("parsererror,OAI-PMH > error");
        if (error) {
          console.warn("OAI/PMH returned", error);
          return dfr.reject();
        } else {
          return dfr.resolve(object_url);
        }
      };
    })(this));
    return dfr.promise();
  };

  ResultObject.prototype.presentShareUrls = function(use_token) {
    var abs_url, add_type, deepLinkUrlPromise, getActionsButtonbar, getCustomiiifButtonBar, get_copy_button, get_copy_html_button, get_go_to_button, get_url_input, idx, j, len, link, present_dialog, ref, ref1, ref2, ref3, ref4, ref5, rows, spinner, types;
    if (use_token == null) {
      use_token = false;
    }
    types = ["detail"];
    if ((ref = this.getBaseConfig().deep_link_access) != null ? ref.enabled : void 0) {
      if (ez5.session.hasSystemRight("root", "frontend_features[deep_link_sharing]", "frontend_features[link_sharing][asset_deep_links]")) {
        deepLinkUrlPromise = this.getDeeplinkUrl(use_token);
        types.push("deeplink_xml_easydb");
      } else {
        deepLinkUrlPromise = CUI.rejectedPromise([]);
      }
      if (ez5.version("6")) {
        if (!((ref1 = this.getBaseConfig().deep_link_access) != null ? ref1.iiif_default_links : void 0)) {
          types.push("deeplink_iiif");
          types.push("deeplink_iiif_mirador");
        }
        if (((ref2 = this.getBaseConfig().deep_link_access) != null ? ref2.iiif_links : void 0) && ((ref3 = this.getBaseConfig().deep_link_access) != null ? ref3.iiif_links.length : void 0) > 0) {
          ref4 = this.getBaseConfig().deep_link_access.iiif_links;
          for (idx = j = 0, len = ref4.length; j < len; idx = ++j) {
            link = ref4[idx];
            types.push("deeplink_iiif_link_" + idx);
          }
        }
        if (ez5.session.isDebug()) {
          types.push("deeplink_html");
        }
      }
    }
    if ((ref5 = this.getBaseConfig().oai_pmh) != null ? ref5.enabled : void 0) {
      types.push("oai_pmh");
    }
    rows = [];
    idx = -1;
    spinner = CUI.spinner({
      text: $$("result.object.share.loading"),
      ui: "result.object.share.spinner"
    });
    abs_url = (function(_this) {
      return function(url, add_remote) {
        var aurl;
        if (add_remote == null) {
          add_remote = false;
        }
        if (add_remote && _this.getRemoteEasydb() && url.startsWith("/")) {
          aurl = _this.getRemoteEasydb().getServerUrl() + url;
        } else {
          aurl = ez5.getAbsoluteURL(url);
        }
        return aurl;
      };
    })(this);
    get_url_input = (function(_this) {
      return function(url, add_remote) {
        var aurl, input;
        if (add_remote == null) {
          add_remote = false;
        }
        aurl = abs_url(url, add_remote);
        input = new CUI.Input({
          name: "url",
          ui: "result.object.share.url.input",
          readonly: true,
          maximize_horizontal: true,
          data: {
            url: aurl
          }
        });
        input.start();
        return input;
      };
    })(this);
    getActionsButtonbar = (function(_this) {
      return function(url, add_remote) {
        var copyButton, goToButton;
        goToButton = get_go_to_button(url, add_remote);
        copyButton = get_copy_button(url, add_remote);
        return new CUI.Buttonbar({
          buttons: [copyButton, goToButton]
        });
      };
    })(this);
    getCustomiiifButtonBar = (function(_this) {
      return function(iiifLink, manifest_url) {
        var copyButton, goToButton, html_code, key, pattern, replacements, showHtmlButton, url, value;
        html_code = iiifLink.html_code;
        replacements = {
          "iiif_presentation_manifest.url": abs_url(manifest_url),
          "iiif_presentation_manifest.url:encoded": encodeURIComponent(abs_url(manifest_url)),
          "fylr:uuid": _this.getUuid()
        };
        for (key in replacements) {
          value = replacements[key];
          pattern = "%" + (key.replace(/\./g, '\\.')) + "%";
          html_code = html_code.replace(new RegExp(pattern, "g"), value);
        }
        try {
          url = new URL(html_code);
        } catch (error1) {}
        if (!CUI.util.isEmpty(url)) {
          goToButton = get_go_to_button(url, false, true);
          copyButton = get_copy_html_button(html_code);
          return new CUI.Buttonbar({
            buttons: [copyButton, goToButton]
          });
        } else {
          copyButton = get_copy_html_button(html_code);
          showHtmlButton = new CUI.Button({
            icon: $$("result.object.share.iiif_custom_link.show_html.button|icon"),
            group: "actions",
            tooltip: {
              text: $$("result.object.share.iiif_custom_link.show_html.button|tooltip")
            },
            onClick: function(ev) {
              var form, hint, inputData, popover, textarea;
              inputData = {
                html_code: html_code,
                manifest_url: manifest_url
              };
              hint = new CUI.Label({
                text: $$("result.object.share.iiif_custom_link.html_code|hint"),
                multiline: true,
                appearance: "secondary",
                padded: true,
                "class": "ez5-result-object-iiif-custom-link-show-html-hint",
                markdown: true
              });
              textarea = new CUI.Input({
                data: inputData,
                name: "html_code",
                readonly: true,
                maximize_horizontal: true,
                maximize_vertical: true,
                readonly_select_all: true,
                maximize_vertical: true,
                textarea: true,
                textarea_cols: 80,
                content_size: true
              });
              form = new CUI.Form({
                "class": "ez5-result-object-iiif-custom-link-show-html-form",
                fields: [textarea],
                data: inputData
              });
              popover = new CUI.Popover({
                element: showHtmlButton,
                "class": "ez5-result-object-iiif-custom-link-popover",
                placement: "e",
                placements: ["e", "w"],
                pane: {
                  header_left: new LocaLabel({
                    loca_key: "result.object.share.iiif_custom_link.show_html.popover.title",
                    loca_key_attrs: {
                      label: ez5.loca.getBestFrontendValue(iiifLink.label)
                    }
                  }),
                  content: [hint, form.start()]
                },
                onHide: function() {
                  return popover.destroy();
                },
                onShow: function() {
                  return CUI.setTimeout({
                    ms: 100,
                    call: function() {
                      return CUI.Events.trigger({
                        type: "viewport-resize"
                      });
                    }
                  });
                }
              });
              popover.show();
            }
          });
          return new CUI.Buttonbar({
            buttons: [copyButton, showHtmlButton]
          });
        }
      };
    })(this);
    get_copy_html_button = (function(_this) {
      return function(html_code) {
        var button;
        button = new CUI.Button({
          icon: $$("result.object.share.copy.button|icon"),
          ui: "result.object.share.copy.button",
          group: "actions",
          tooltip: {
            text: $$("result.object.share.copy.iif_link_html|tooltip")
          },
          onClick: function(ev) {
            var copiedTooltip;
            ez5.copyToClipboard(html_code);
            copiedTooltip = new CUI.Tooltip({
              element: button,
              text: $$("result.object.share.copy.iif_link_html.copied|tooltip")
            });
            copiedTooltip.show(ev);
            CUI.setTimeout({
              ms: 2000,
              call: (function(_this) {
                return function() {
                  return copiedTooltip.destroy();
                };
              })(this)
            });
          }
        });
        return button;
      };
    })(this);
    get_go_to_button = (function(_this) {
      return function(url, add_remote, absolute) {
        var aurl, button;
        if (add_remote == null) {
          add_remote = false;
        }
        if (absolute == null) {
          absolute = false;
        }
        if (!absolute) {
          aurl = abs_url(url, add_remote);
        } else {
          aurl = url;
        }
        button = new CUI.Button({
          icon: $$("result.object.share.button|icon"),
          ui: "result.object.share.button",
          group: "actions",
          tooltip: {
            text: $$("result.object.share.button|tooltip", {
              url: aurl
            })
          },
          onClick: function() {
            window.open(aurl, "_blank");
          }
        });
        return button;
      };
    })(this);
    get_copy_button = (function(_this) {
      return function(url, add_remote) {
        var aurl, button;
        if (add_remote == null) {
          add_remote = false;
        }
        aurl = abs_url(url, add_remote);
        button = new CUI.Button({
          icon: $$("result.object.share.copy.button|icon"),
          ui: "result.object.share.copy.button",
          group: "actions",
          tooltip: {
            text: $$("result.object.share.copy.button|tooltip", {
              url: aurl
            })
          },
          onClick: function(ev) {
            ez5.copyToClipboard(aurl);
            Asset.showCopyTooltip(aurl, button, ev);
          }
        });
        return button;
      };
    })(this);
    add_type = (function(_this) {
      return function() {
        var customIIIFLink, custom_link_idx, row, shareUrl, type;
        idx = idx + 1;
        if (idx === types.length) {
          present_dialog();
          return;
        }
        type = types[idx];
        row = {
          type: $$("result.object.share.type." + type)
        };
        if (ez5.version("6") && type.startsWith("deeplink_iiif_link_")) {
          custom_link_idx = parseInt(type.split("_").pop());
          customIIIFLink = _this.getBaseConfig().deep_link_access.iiif_links[custom_link_idx];
          if (CUI.util.isEmpty(customIIIFLink.html_code)) {
            add_type();
            return;
          }
          deepLinkUrlPromise.done(function(url) {
            row.type = ez5.loca.getBestFrontendValue(customIIIFLink.label) || $$("result.object.share.iiif_custom_link");
            row.go_to_button = getCustomiiifButtonBar(customIIIFLink, url + "/format/iiif/v3/manifest.json");
            rows.push(row);
            return add_type();
          }).fail(function() {
            return add_type();
          });
          return;
        }
        switch (type) {
          case "detail":
            shareUrl = _this.getDetailShareUrl();
            row.url = get_url_input(shareUrl);
            row.go_to_button = getActionsButtonbar(shareUrl);
            rows.push(row);
            return add_type();
          case "deeplink_xml_easydb":
            return deepLinkUrlPromise.done(function(url) {
              url += "/format/xml_easydb";
              row.url = get_url_input(url, true);
              row.go_to_button = getActionsButtonbar(url, true);
              rows.push(row);
              return add_type();
            }).fail(function() {
              return add_type();
            });
          case "deeplink_iiif":
          case "deeplink_iiif_mirador":
            return deepLinkUrlPromise.done(function(url) {
              url += "/format/iiif/v3/manifest.json";
              if (type === "deeplink_iiif_mirador") {
                url = "https://projectmirador.org/embed/?iiif-content=" + encodeURIComponent(abs_url(url, true));
              }
              row.url = get_url_input(url, true);
              row.go_to_button = getActionsButtonbar(url, true);
              rows.push(row);
              return add_type();
            }).fail(function() {
              return add_type();
            });
          case "deeplink_html":
            return deepLinkUrlPromise.done(function(url) {
              url += "/format/html";
              row.url = get_url_input(url, true);
              row.go_to_button = getActionsButtonbar(url, true);
              rows.push(row);
              return add_type();
            }).fail(function() {
              return add_type();
            });
          case "oai_pmh":
            return _this.getOaiPmhUrl().done(function(url) {
              row.url = get_url_input(url, true);
              row.go_to_button = getActionsButtonbar(url, true);
              rows.push(row);
              return add_type();
            }).fail(function() {
              return add_type();
            });
          default:
            throw "Unknown format";
        }
      };
    })(this);
    present_dialog = (function(_this) {
      return function() {
        var collector, l, len1, mod, publication, ref6, table;
        if (PublishColumn.isVisible("detail-header", _this.getMask())) {
          ref6 = PublishColumn.getPublications(_this.getData()._published);
          for (l = 0, len1 = ref6.length; l < len1; l++) {
            publication = ref6[l];
            collector = PublishColumn.getCollectorFromBaseConfig(publication.collector);
            if (!collector) {
              continue;
            }
            rows.push({
              type: collector.type || ez5.loca.getBestFrontendValue(collector.displayname) || collector.internalname,
              go_to_button: getActionsButtonbar(publication.url)
            });
          }
        }
        spinner.destroy();
        table = new CUI.Table({
          "class": "ez5-result-object-share-url-form cui-table--has-datafields",
          ui: "result.object.share.modal.content",
          columns: [
            {
              text: $$("result.object.share.column.type"),
              name: "type"
            }, {
              text: $$("result.object.share.column.go_to_button"),
              name: "go_to_button"
            }
          ],
          rows: rows
        });
        return mod = new CUI.Modal({
          "class": "ez5-result-object-share-url-modal",
          ui: "result.object.share.modal",
          cancel: true,
          pane: {
            header_left: new CUI.Label({
              text: $$("result.object.share.title")
            }),
            content: table,
            footer_right: {
              text: $$("base.ok"),
              primary: true,
              ui: "result.object.share.modal.ok.button",
              onClick: function() {
                return mod.destroy();
              }
            }
          }
        }).show();
      };
    })(this);
    add_type();
  };

  ResultObject.prototype.getEmptyPlaceholderIcon = function() {
    var icon, mask, objecttypeName, ref, ref1, ref2;
    if (!ez5.version("6")) {
      return null;
    }
    mask = this.getMask();
    objecttypeName = mask != null ? mask.table.name() : void 0;
    if (CUI.util.isEmpty(objecttypeName)) {
      return null;
    }
    icon = (ref = ez5.schema.CURRENT._objecttype_by_name[objecttypeName]) != null ? (ref1 = ref._objecttype) != null ? (ref2 = ref1.objecttype) != null ? ref2.empty_placeholder_icon : void 0 : void 0 : void 0;
    if (CUI.util.isEmpty(icon)) {
      return null;
    }
    return icon;
  };

  ResultObject.prototype.detailToolsEnabled = function() {
    return true;
  };

  ResultObject.prototype.getDetailTools = function(_opts) {
    var add_quick_view_tool, disabled, field, fn, j, l, len, len1, len2, len3, len4, len5, linkedSearchFields, m, match, n, o, objecttypeNames, opts, ot, q, ref, ref1, ref2, ref3, ref4, reverseFilter, reverseLinkedField, reverseLinkedFields, search, search_could_be_possible, tools;
    opts = CUI.Element.readOpts(_opts, "ResultObject.getDetailTools", {
      detail: {
        check: DetailSidebar
      },
      search: {
        check: Search
      },
      getElement: {
        check: Function
      }
    });
    search = opts.search;
    if (!search && opts.detail) {
      search = opts.detail.getMainSearch();
    }
    tools = [];
    linkedSearchFields = [];
    reverseLinkedFields = {};
    add_quick_view_tool = (function(_this) {
      return function() {
        if (opts.getElement) {
          return tools.push(new ToolboxTool({
            loca_key: "result.object.show_info",
            name: "result.object.show_info",
            run: function() {
              var collection;
              if ((ez5.version("6") && _this.isPurged()) || _this.isMappedMetadataCreated()) {
                collection = new CollectionObject(_this.getData());
              } else {
                collection = new CollectionObject({
                  _global_object_id: _this.getGlobalObjectId()
                });
              }
              return ResultObject.showCollectionObjectInPopover({
                collectionObject: collection,
                detail: opts.detail,
                element: opts.getElement()
              });
            }
          }));
        }
      };
    })(this);
    if (this.isPurged()) {
      add_quick_view_tool();
      return tools;
    }
    if (search) {
      search_could_be_possible = false;
      ref = search.getLinkedObjectFields("expert");
      for (j = 0, len = ref.length; j < len; j++) {
        field = ref[j];
        if (field.linkMask().table.name() === this.objecttype()) {
          search_could_be_possible = true;
          break;
        }
      }
      ref1 = search.getLinkedObjectFields("expert", true);
      for (l = 0, len1 = ref1.length; l < len1; l++) {
        field = ref1[l];
        if (field.linkMask().table.name() === this.objecttype()) {
          linkedSearchFields.push(field);
        }
      }
      if (search instanceof SearchMain) {
        objecttypeNames = search.getSearchObjecttypes(false).map(function(objecttype) {
          return objecttype.name();
        });
      }
      reverseFilter = (function(_this) {
        return function(f) {
          var objecttypeName;
          if (!(f instanceof ReverseLinkedTable)) {
            return;
          }
          objecttypeName = f.getMask().getTable().name();
          if (indexOf.call(objecttypeNames, objecttypeName) < 0) {
            return false;
          }
          return f.hasUserData(_this.data[_this.objecttype()], _this.getData());
        };
      })(this);
      ref2 = search.getFieldsByFilter(reverseFilter, "detail", true);
      for (m = 0, len2 = ref2.length; m < len2; m++) {
        field = ref2[m];
        reverseLinkedFields[field.name()] = field;
      }
    }
    reverseLinkedFields = Object.values(reverseLinkedFields);
    if (opts.detail) {
      tools.push(new ToolboxTool({
        loca_key: "result.object.show_in_sidebar",
        name: "result.object.show_in_sidebar",
        run: (function(_this) {
          return function() {
            return opts.detail.loadGlobalObjectId(_this.getGlobalObjectId());
          };
        })(this)
      }));
    }
    if (ez5.version("6") && !this.isDeleted() && !this.isMappedMetadataCreated()) {
      tools.push(new ToolboxTool({
        name: "object.show.new_tab",
        loca_key: "tool.object.show.new_tab",
        sort: "B:2",
        run: (function(_this) {
          return function() {
            return window.open(window.easydb_base_prefix + "/#/detail/" + (_this.getGlobalObjectId()), "_blank");
          };
        })(this)
      }));
    }
    if (ez5.version("6") && this.isDeleted() && TrashSearchManager.canSeeDeleted()) {
      tools.push(new ToolboxTool({
        name: "object.show.trash_tab",
        loca_key: "tool.object.show.trash_tab",
        sort: "B:2",
        run: (function(_this) {
          return function() {
            var globalObjectId, objecttypeName, systemId;
            globalObjectId = _this.getGlobalObjectId();
            systemId = globalObjectId.match(/(.*)@/)[1];
            objecttypeName = _this.getMask().getTable().name();
            return window.open(window.easydb_base_prefix + "#trash/" + (encodeURI(objecttypeName)) + "/" + systemId, "_blank");
          };
        })(this)
      }));
    }
    add_quick_view_tool();
    if ((linkedSearchFields.length > 0 || search_could_be_possible) && !this.isDeleted()) {
      tools.push(new ToolboxTool({
        loca_key: "result.object.show_in_search",
        name: "result.object.show_in_search",
        disabled: linkedSearchFields.length === 0,
        run: (function(_this) {
          return function() {
            return LinkedObject.showInSearch({
              search_fields: linkedSearchFields,
              search: search,
              result_object: _this
            });
          };
        })(this)
      }));
    }
    if (reverseLinkedFields.length > 0 && !this.isDeleted()) {
      fn = (function(_this) {
        return function(reverseLinkedField) {
          return tools.push(new ToolboxTool({
            loca_key: "result.object.show_reverse_in_search",
            loca_key_attrs: {
              objecttype: reverseLinkedField.table.nameLocalized(),
              field_name: reverseLinkedField.nameLocalized()
            },
            name: "result.object.show_reverse_in_search",
            run: function() {
              return ReverseLinkedTable.showInSearch({
                reverse_linked_field: reverseLinkedField,
                search: search,
                result_object: _this
              });
            }
          }));
        };
      })(this);
      for (n = 0, len3 = reverseLinkedFields.length; n < len3; n++) {
        reverseLinkedField = reverseLinkedFields[n];
        fn(reverseLinkedField);
      }
    }
    if (search && this.hasChildren() && (typeof search.getSearchHierarchyManager === "function" ? search.getSearchHierarchyManager() : void 0)) {
      match = false;
      ref3 = search.getSearchObjecttypes();
      for (o = 0, len4 = ref3.length; o < len4; o++) {
        ot = ref3[o];
        if (ot.name() === this.objecttype()) {
          match = true;
          break;
        }
      }
      if (match) {
        disabled = true;
        ref4 = search.getSearchObjecttypes(true);
        for (q = 0, len5 = ref4.length; q < len5; q++) {
          ot = ref4[q];
          if (ot.name() === this.objecttype()) {
            disabled = false;
            break;
          }
        }
        tools.push(new ToolboxTool({
          loca_key: "result.object.dive_in_search",
          disabled: disabled,
          name: "result.object.dive_in_search",
          run: (function(_this) {
            return function() {
              search.emptyRequest();
              search.getSearchHierarchyManager().addFilter(_this);
              DetailFullscreen.triggerClose();
              return search.execute();
            };
          })(this)
        }));
      }
    }
    if (search && this.hasParent() && !this.isDeleted()) {
      tools.push(new ToolboxTool({
        loca_key: "result.object.show_parents_in_search",
        disabled: false,
        name: "result.object.show_parent",
        run: (function(_this) {
          return function() {
            var len6, len7, len8, parentsIds, path, pathObject, pathObjects, paths, query, r, ref5, s, search_data, u;
            search.emptyRequest();
            parentsIds = [];
            pathObjects = [];
            if (_this.getData()._paths) {
              ref5 = _this.getData()._paths;
              for (r = 0, len6 = ref5.length; r < len6; r++) {
                paths = ref5[r];
                for (s = 0, len7 = paths.length; s < len7; s++) {
                  path = paths[s];
                  pathObjects.push(path);
                }
              }
            } else {
              pathObjects = _this.getData()._path || [];
            }
            for (u = 0, len8 = pathObjects.length; u < len8; u++) {
              pathObject = pathObjects[u];
              if (pathObject._system_object_id && pathObject._system_object_id !== _this.getData()._system_object_id) {
                parentsIds.push(pathObject._system_object_id);
              }
            }
            if (parentsIds.length > 0) {
              search_data = {
                _system_object_id: parentsIds.join(",")
              };
              query = new QueryElementField({
                data: search_data,
                field: new SystemObjectIdColumn(_this.mask)
              });
              return search.showInSearch(query);
            }
          };
        })(this)
      }));
    }
    return tools;
  };

  ResultObject.renderPath = function(path_els, content, opts, renderTooltip) {
    var idx, j, len, path_div, path_el, path_str, span;
    if (path_els == null) {
      path_els = [];
    }
    if (content == null) {
      content = false;
    }
    if (opts == null) {
      opts = {};
    }
    if (renderTooltip == null) {
      renderTooltip = true;
    }
    path_div = CUI.dom.element("div", {
      "class": "ez5-path"
    });
    if (opts.hierarchy_path_reverse) {
      CUI.dom.addClass(path_div, "ez5-path--reverse");
    }
    if (opts.hierarchy_path_reverse) {
      path_els = path_els.slice().reverse();
    }
    path_str = "";
    if (path_els && path_els.length > 0) {
      path_str = path_els.join(" > ");
    }
    for (idx = j = 0, len = path_els.length; j < len; idx = ++j) {
      path_el = path_els[idx];
      if (content) {
        CUI.dom.append(path_div, path_el);
        if (renderTooltip && !CUI.util.isEmpty(path_str)) {
          new CUI.Tooltip({
            on_hover: true,
            element: path_el,
            text: path_str
          });
        }
      } else {
        span = CUI.dom.span("ez5-path-element");
        span.textContent = path_el;
        CUI.dom.append(path_div, span);
        CUI.dom.setAttribute(span, "ui", "result.object.result.card.path.element:" + path_el);
        if (renderTooltip && !CUI.util.isEmpty(path_str)) {
          new CUI.Tooltip({
            on_hover: true,
            element: span,
            text: path_str
          });
        }
      }
    }
    return path_div;
  };

  ResultObject.showCollectionObjectInPopover = function(opts) {
    CUI.Element.readOpts(opts, "ResultObject.showCollectionObjectInPopover", {
      collectionObject: {
        check: function(v) {
          return v instanceof CollectionObject;
        }
      },
      detail: {
        check: DetailSidebar
      },
      element: {
        check: function(v) {
          return CUI.util.isElement(v) || CUI.util.isElement(v != null ? v.DOM : void 0);
        }
      }
    });
    return ResultObject.loadFromData(CUI.util.copyObject(opts.collectionObject.getObject(), true), "long").done((function(_this) {
      return function(ro) {
        return ro.showPopover({
          detail: opts.detail,
          popover: {
            element: opts.element
          }
        });
      };
    })(this));
  };

  ResultObject.loadFromDb = function(global_object_id) {
    var dfr;
    dfr = new CUI.Deferred();
    ResultObject.loadFromData({
      _global_object_id: global_object_id
    }).fail(dfr.reject).done((function(_this) {
      return function(ro) {
        return ro.loadFromDb().done(function() {
          return dfr.resolve(ro);
        }).fail(dfr.reject);
      };
    })(this));
    return dfr.promise();
  };

  ResultObject.loadFromData = function(data, _format, present_error, best_mask_filter, generate_rights, include_deleted) {
    var format, isPurgedObject, purgedData, ro;
    if (_format == null) {
      _format = "long";
    }
    if (present_error == null) {
      present_error = true;
    }
    if (best_mask_filter == null) {
      best_mask_filter = false;
    }
    if (generate_rights == null) {
      generate_rights = false;
    }
    if (include_deleted == null) {
      include_deleted = true;
    }
    isPurgedObject = ResultObject.dataFromPurgedObject(data);
    if (!isPurgedObject) {
      CUI.util.assert(data._global_object_id || data._format || data._mapped_metadata_created, "ResultObject.loadFromData", "Data needs to contain _global_object_id or _mapped_metadata_created", {
        data: data
      });
    }
    format = (function() {
      switch (_format) {
        case "text":
        case "long":
          return "long";
        case "short":
        case "standard":
          return "standard";
        case "long_inheritance":
          return "long_inheritance";
        default:
          return CUI.util.assert(false, "ResultObject.resultObjectFromData", "Unknown format " + _format + ".", {
            format: _format
          });
      }
    })();
    if (data._objecttype && _format !== 'short' && _format !== 'standard' && !data._path && data.__version !== 'TEMP' && ez5.schema.CURRENT._objecttype_by_name[data._objecttype].is_hierarchical) {
      data._format_incomplete = true;
    }
    if (isPurgedObject) {
      purgedData = CUI.util.copyObject(data, true);
      purgedData._format = "purged";
      if (!purgedData.hasOwnProperty(purgedData._objecttype)) {
        purgedData[purgedData._objecttype] = {};
      }
      ro = new ResultObject().setData(purgedData);
      return CUI.resolvedPromise(ro);
    }
    if (!data._global_object_id) {
      format = null;
    }
    if (format && (ResultObject.compareFormats(data._format, format) < 0 || data._format_incomplete)) {
      return this.loadFromGlobalObjectId(data._global_object_id, format, data._mask, best_mask_filter, generate_rights, include_deleted).fail(function(error) {
        if (present_error) {
          return error.presentError();
        }
      });
    } else {
      ro = new ResultObject().setData(data);
      return CUI.resolvedPromise(ro);
    }
  };

  ResultObject.prototype.loadFromCollectionObject = function(collection_object, format, mask_name, best_mask_filter, generate_rights, include_deleted) {
    var search_data;
    if (format == null) {
      format = "long";
    }
    if (mask_name == null) {
      mask_name = null;
    }
    if (best_mask_filter == null) {
      best_mask_filter = false;
    }
    if (generate_rights == null) {
      generate_rights = true;
    }
    if (include_deleted == null) {
      include_deleted = true;
    }
    CUI.util.assert(collection_object instanceof CollectionObject, "ResultObject.loadFromCollectionObject", "collection_object needs to be instance of CollectionObject", {
      collection_object: collection_object
    });
    if (ez5.version("6") && format === "long") {
      format = "long_inheritance";
    }
    search_data = {
      best_mask_filter: best_mask_filter,
      format: format,
      generate_rights: generate_rights,
      search: [collection_object.getSearchFilter()]
    };
    if (include_deleted && TrashSearchManager.canSeeDeleted()) {
      search_data.include_deleted = true;
    }
    return this.loadFromSearch(search_data, mask_name);
  };

  ResultObject.prototype.loadFromId = function(objecttype, id, format, mask_name, best_mask_filter, generate_rights, include_deleted) {
    var search_data;
    if (format == null) {
      format = "standard";
    }
    if (mask_name == null) {
      mask_name = null;
    }
    if (best_mask_filter == null) {
      best_mask_filter = false;
    }
    if (generate_rights == null) {
      generate_rights = true;
    }
    if (include_deleted == null) {
      include_deleted = true;
    }
    search_data = {
      best_mask_filter: best_mask_filter,
      generate_rights: generate_rights,
      format: format,
      objecttypes: [objecttype],
      search: [
        {
          type: "in",
          "in": [objecttype],
          fields: ["_objecttype"]
        }, {
          type: "in",
          "in": [id],
          fields: [objecttype + "._id"]
        }
      ]
    };
    if (include_deleted && TrashSearchManager.canSeeDeleted()) {
      search_data.include_deleted = true;
    }
    return this.loadFromSearch(search_data, mask_name);
  };

  ResultObject.prototype.loadFromUUID = function(uuid, format, mask_name, best_mask_filter, generate_rights, include_deleted) {
    var search_data;
    if (format == null) {
      format = "standard";
    }
    if (mask_name == null) {
      mask_name = null;
    }
    if (best_mask_filter == null) {
      best_mask_filter = false;
    }
    if (generate_rights == null) {
      generate_rights = true;
    }
    if (include_deleted == null) {
      include_deleted = true;
    }
    search_data = {
      best_mask_filter: best_mask_filter,
      generate_rights: generate_rights,
      format: format,
      search: [
        {
          type: "in",
          "in": [uuid],
          fields: ["_uuid"]
        }
      ]
    };
    if (include_deleted) {
      search_data.include_deleted = true;
    }
    return this.loadFromSearch(search_data, mask_name);
  };

  ResultObject.prototype.loadFromSystemObjectId = function(systemObjectId, format, mask_name, best_mask_filter, generate_rights, objecttype) {
    var search_data;
    if (format == null) {
      format = "standard";
    }
    if (mask_name == null) {
      mask_name = null;
    }
    if (best_mask_filter == null) {
      best_mask_filter = false;
    }
    if (generate_rights == null) {
      generate_rights = true;
    }
    if (objecttype == null) {
      objecttype = null;
    }
    search_data = {
      best_mask_filter: best_mask_filter,
      generate_rights: generate_rights,
      format: format,
      search: [
        {
          type: "in",
          "in": [systemObjectId],
          fields: ["_system_object_id"]
        }
      ]
    };
    if (objecttype) {
      search_data.objecttypes = [objecttype];
    }
    return this.loadFromSearch(search_data, mask_name);
  };

  ResultObject.loadFromGlobalObjectId = function(gid, format, mask, best_mask_filter, generate_rights, include_deleted) {
    if (mask == null) {
      mask = null;
    }
    if (best_mask_filter == null) {
      best_mask_filter = false;
    }
    if (generate_rights == null) {
      generate_rights = true;
    }
    if (include_deleted == null) {
      include_deleted = true;
    }
    return (new ResultObject()).loadFromCollectionObject(new CollectionObject({
      _global_object_id: gid
    }), format, mask, best_mask_filter, generate_rights, include_deleted);
  };

  ResultObject.loadFromId = function(objecttype, id, format, mask_name, best_mask_filter, generate_rights, include_deleted) {
    if (format == null) {
      format = "standard";
    }
    if (mask_name == null) {
      mask_name = null;
    }
    if (best_mask_filter == null) {
      best_mask_filter = false;
    }
    if (generate_rights == null) {
      generate_rights = true;
    }
    if (include_deleted == null) {
      include_deleted = false;
    }
    return (new ResultObject()).loadFromId(objecttype, id, format, mask_name, best_mask_filter, generate_rights, include_deleted);
  };

  ResultObject.loadFromUUID = function(uuid, format, mask_name, best_mask_filter, generate_rights, include_deleted) {
    if (format == null) {
      format = "standard";
    }
    if (mask_name == null) {
      mask_name = null;
    }
    if (best_mask_filter == null) {
      best_mask_filter = false;
    }
    if (generate_rights == null) {
      generate_rights = true;
    }
    if (include_deleted == null) {
      include_deleted = false;
    }
    return (new ResultObject()).loadFromUUID(uuid, format, mask_name, best_mask_filter, generate_rights, include_deleted);
  };

  ResultObject.__formats = ["", "short", "standard", "long", "long_inheritance", "full"];

  ResultObject.compareFormats = function(format1, format2) {
    if (format1 == null) {
      format1 = "";
    }
    if (format2 == null) {
      format2 = "";
    }
    return CUI.util.compareIndex(CUI.util.idxInArray(format1, this.__formats), CUI.util.idxInArray(format2, this.__formats));
  };

  ResultObject.prototype.copyAsTemplate = function() {
    window.adhoc_template = {
      name: $$("editor.template.adhoc_template.name"),
      data: this.getSaveData({
        copy: true,
        copy_for_template: true
      }),
      objecttype: this.objecttype()
    };
    return CUI.alert({
      text: $$("editor.template.adhoc_template.alert.text"),
      markdown: true
    });
  };

  ResultObject.prototype.setId = function(id) {
    var objectData;
    objectData = this.data[this.objecttype()];
    if (objectData) {
      return objectData._id = id;
    }
  };

  ResultObject.prototype.getId = function() {
    var ref;
    return (ref = this.data[this.objecttype()]) != null ? ref._id : void 0;
  };

  ResultObject.prototype.setVersion = function(version) {
    var objectData;
    objectData = this.data[this.objecttype()];
    if (objectData) {
      return objectData._version = version;
    }
  };

  ResultObject.prototype.getAssetsCount = function() {
    return this.__assetsCount || 0;
  };

  ResultObject.prototype.hasServerValidationError = function() {
    return !!this.__serverValidationError && this.__serverValidationError.errors.length > 0;
  };

  ResultObject.prototype.hasUnhandledServerValidationError = function() {
    var error, j, len, ref;
    if (this.__serverValidationError) {
      ref = this.__serverValidationError.errors;
      for (j = 0, len = ref.length; j < len; j++) {
        error = ref[j];
        if (!error.handled) {
          return true;
        }
      }
    }
    return false;
  };

  ResultObject.prototype.clearValidationErrors = function() {
    return delete this.__serverValidationError;
  };

  ResultObject.prototype.getServerValidationErrors = function() {
    var ref;
    return (ref = this.__serverValidationError) != null ? ref.errors : void 0;
  };

  ResultObject.prototype.addServerValidationError = function(error) {
    var field, parsedFieldPath, renderedField;
    if (!this.__serverValidationError) {
      this.__serverValidationError = {
        errors: []
      };
    }
    parsedFieldPath = ResultObject.parseServerValidationErrorFieldPath(error.field);
    if (!parsedFieldPath) {
      delete error.field;
      this.__serverValidationError.errors.push(error);
      return error;
    }
    error.parsedFieldPath = parsedFieldPath;
    renderedField = this.getRenderedFieldForServerValidationError(error);
    if (renderedField) {
      field = renderedField.getField();
      error.field = field;
      error.renderedField = renderedField;
      field.onServerValidationProblem(this.getDataFromDataPath(error.dataPath), error.message, error.parameters);
    } else {
      delete error.field;
    }
    if (parsedFieldPath.isRow) {
      error.row_index = parsedFieldPath.path[parsedFieldPath.path.length - 1].index;
    } else if (parsedFieldPath.nested && parsedFieldPath.path[parsedFieldPath.path.length - 1].nested) {
      error.row_index = -1;
    }
    this.__serverValidationError.errors.push(error);
    return error;
  };

  ResultObject.prototype.getRenderedFieldForServerValidationError = function(error) {
    var _insideNestedPopup, data, dataPath, f, j, l, len, len1, nestedName, nestedRenderedField, parsedFieldPath, path, ref, ref1, ref2, renderedField, reverseNestedName;
    if (!error.parsedFieldPath) {
      return;
    }
    data = this.data[this.objecttype()];
    parsedFieldPath = error.parsedFieldPath;
    if (parsedFieldPath.objecttype !== this.objecttype()) {
      if (!parsedFieldPath.nested) {
        return;
      }
      reverseNestedName = "_reverse_nested:" + parsedFieldPath.objecttype;
      dataPath = [];
      ref = parsedFieldPath.path;
      for (j = 0, len = ref.length; j < len; j++) {
        path = ref[j];
        if (path.nested) {
          reverseNestedName += ":" + path.name;
          if (!isNaN(path.index)) {
            dataPath.push({
              path: reverseNestedName,
              index: path.index
            });
            data = (ref1 = data[reverseNestedName]) != null ? ref1[path.index] : void 0;
          }
        } else {
          reverseNestedName = path.name;
        }
      }
      renderedField = data != null ? data[reverseNestedName + ":rendered"] : void 0;
    } else if (parsedFieldPath.nested) {
      nestedName = "_nested:" + this.objecttype();
      dataPath = [];
      _insideNestedPopup = false;
      ref2 = parsedFieldPath.path;
      for (l = 0, len1 = ref2.length; l < len1; l++) {
        path = ref2[l];
        if (path.nested) {
          nestedName += "__" + path.name;
          nestedRenderedField = data[nestedName + ":rendered"];
          if (nestedRenderedField) {
            f = nestedRenderedField.getField();
            if (f && f._isRenderedAsPopup()) {
              if (!_insideNestedPopup) {
                _insideNestedPopup = true;
              }
              path.nestedPopup = true;
              path.nestedField = f;
              path.nestedRenderedField = nestedRenderedField;
            }
          }
          if (!isNaN(path.index) && !!!path.markRow) {
            dataPath.push({
              path: nestedName,
              index: path.index
            });
            data = data[nestedName][path.index];
          }
        } else {
          nestedName = path.name;
        }
      }
      renderedField = data != null ? data[nestedName + ":rendered"] : void 0;
    } else {
      renderedField = data[parsedFieldPath.path[0].name + ":rendered"];
    }
    if (dataPath) {
      error.dataPath = dataPath;
    }
    if (_insideNestedPopup) {
      error.insideNestedPopup = true;
    }
    return renderedField;
  };

  ResultObject.prototype.updateServerValidationErrorsRenderedFields = function() {
    var callErrorInit, error, j, len, ref, renderedField;
    ref = this.getServerValidationErrors();
    for (j = 0, len = ref.length; j < len; j++) {
      error = ref[j];
      callErrorInit = false;
      if (!error.renderedField) {
        callErrorInit = true;
      }
      renderedField = this.getRenderedFieldForServerValidationError(error);
      if (renderedField) {
        error.renderedField = renderedField;
        if (callErrorInit) {
          error.field = renderedField.getField();
          error.field.onServerValidationProblem(this.getDataFromDataPath(error.dataPath), error.message, error.parameters);
        }
      }
    }
  };

  ResultObject.prototype.getDataFromDataPath = function(dataPath) {
    var data, j, len, path;
    data = this.data[this.objecttype()];
    if (!dataPath) {
      return data;
    }
    for (j = 0, len = dataPath.length; j < len; j++) {
      path = dataPath[j];
      data = data[path.path][path.index];
    }
    return data;
  };

  ResultObject.prototype.canBeShared = function() {
    var pool, rightCheck;
    if (this.isDeleted()) {
      return false;
    }
    rightCheck = ez5.session.hasSystemRight("root", "frontend_features[deep_link_sharing]", "frontend_features[link_sharing]") && this.getSession().hasSystemRight("root", "frontend_features[deep_link_sharing]", "frontend_features[link_sharing]");
    if (rightCheck && this.pool()) {
      pool = ez5.pools.findPoolById(this.pool().pool._id);
      if (pool) {
        return pool.allowSharing(this.data);
      }
    }
    return rightCheck;
  };

  ResultObject.parseServerValidationErrorFieldPath = function(path) {
    var isRow, j, len, match, objecttype, ref, regex, result, segment, segments;
    if (CUI.util.isEmpty(path) || !CUI.util.isString(path)) {
      return null;
    }
    segments = path.split('.');
    if (!segments.length || segments.length < 2) {
      return null;
    }
    objecttype = segments.shift();
    result = [];
    for (j = 0, len = segments.length; j < len; j++) {
      segment = segments[j];
      regex = /^([^.\[\]]+)(?:\[(\d*)\])?$/;
      match = segment.match(regex);
      if (!match) {
        return null;
      }
      if (match[2] !== void 0) {
        result.push({
          name: match[1],
          index: parseInt(match[2], 10),
          nested: true
        });
      } else {
        result.push({
          name: match[1],
          nested: false
        });
      }
    }
    if (result[result.length - 1].nested && !isNaN(result[result.length - 1].index)) {
      result[result.length - 1].markRow = true;
      isRow = true;
    }
    return {
      objecttype: objecttype,
      nested: !!((ref = result[0]) != null ? ref.nested : void 0),
      jqPath: path,
      path: result,
      isRow: !!isRow
    };
  };

  ResultObject.getResultCardPinButton = function(pane, prefName, onClick) {
    var button;
    if (prefName == null) {
      prefName = "resultCard.unpin";
    }
    if (onClick == null) {
      onClick = null;
    }
    if (!pane) {
      console.warn("ResultObject.getResultCardPinButton: No pane to pin given.");
      return;
    }
    button = new CUI.Button({
      icon: "fa-thumb-tack",
      "class": "cui-button-pin ez5-result-card-pin-button",
      tooltip: {
        text: (function(_this) {
          return function() {
            if (button.isActive()) {
              return $$("detail.sidebar.resultCard.unpin|tooltip");
            }
            return $$("detail.sidebar.resultCard.pin|tooltip");
          };
        })(this)
      },
      "switch": true,
      active: !ez5.session.getPref(prefName),
      onActivate: (function(_this) {
        return function() {
          CUI.dom.removeClass(pane, "is-fully-scrollable");
          ez5.session.savePref(prefName, false);
          if (onClick) {
            return onClick();
          }
        };
      })(this),
      onDeactivate: (function(_this) {
        return function() {
          CUI.dom.addClass(pane, "is-fully-scrollable");
          ez5.session.savePref(prefName, true);
          if (onClick) {
            return onClick();
          }
        };
      })(this)
    });
    return button;
  };

  return ResultObject;

})(CUI.Dummy);

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

  function ResultObjectDemo(opts) {
    var _id_parent, _opts, _ro, _sd, format, format_linked_object, i, j, k, mask, ref, sd, top_data, v, version;
    if (opts == null) {
      opts = {};
    }
    ResultObjectDemo.__super__.constructor.call(this);
    mask = opts.mask;
    version = opts.version || "CURRENT";
    format = opts.format;
    format_linked_object = opts.format_linked_object || "long";
    CUI.util.assert(mask instanceof Mask, "new ResultObjectDemo", "opts.mask needs to be instanceof Mask", {
      opts: opts
    });
    CUI.util.assert(format === "long" || format === "standard", "new ResultObjectDemo", "opts.format needs to be \"long\" or \"standard\".", {
      opts: opts
    });
    this.initData(mask.table.name(), {
      _mask: mask.name(),
      __version: version
    });
    _opts = opts.opts || {};
    _opts.demo_data = true;
    _opts.demo_version = version;
    _opts.demo_format_linked_object = format_linked_object;
    sd = this.getSaveData(_opts);
    sd._global_object_id = sd._system_object_id + "@" + version;
    sd._standard = this.getStandardData(sd);
    sd._generated_rights = {
      unlink: true,
      change_owner: true,
      "delete": true,
      write: true,
      acl: true
    };
    sd._format = opts.format;
    sd.__version = version;
    this.setData(sd);
    top_data = CUI.util.copyObject(sd, true);
    if (mask.table.isHierarchy() && !opts.demo_skip_path_create) {
      _id_parent = null;
      sd._path = [];
      for (i = j = 1; j <= 2; i = ++j) {
        _ro = new ResultObjectDemo({
          demo_skip_path_create: true,
          version: version,
          mask: mask,
          demo_format_linked_object: format_linked_object,
          format: "standard"
        });
        _sd = _ro.getData();
        _id_parent = _ro.id();
        delete _sd._owner;
        _sd[sd._objecttype]._id_parent = _id_parent;
        ref = _sd[sd._objecttype];
        for (k in ref) {
          v = ref[k];
          if (k.startsWith("_")) {
            continue;
          }
          delete _sd[sd._objecttype][k];
        }
        sd._path.push(_sd);
      }
      sd._path.push(top_data);
    }
    this;
  }

  return ResultObjectDemo;

})(ResultObject);
// Generated by CoffeeScript 1.12.7
var ParentRootResultObject,
  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;

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

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

  ParentRootResultObject.prototype.detailToolsEnabled = function() {
    return false;
  };

  ParentRootResultObject.prototype.getGlobalObjectId = function() {
    return "0";
  };

  ParentRootResultObject.prototype.renderTextDetail = function(opts) {
    if (opts == null) {
      opts = {};
    }
    return new CUI.Label({
      text: $$("base.path_column.root")
    });
  };

  ParentRootResultObject.prototype.__render = function(cls, opts) {
    var customIcon, hint, renderedPath, tmpl;
    if (opts == null) {
      opts = {};
    }
    tmpl = new CUI.Template({
      name: "result-card",
      map: {
        asset: true,
        tags: true,
        path: true,
        standard_1: true,
        standard_2: true,
        objecttype: true,
        pool: true,
        system_object_id: true
      }
    });
    if (cls === "standard") {
      tmpl.addClass("ez5-card--standard");
      tmpl.append($$("base.path_column.root"), "standard_1");
      if (opts.lassoable) {
        tmpl.addClass("ez5-lassoable");
      }
      tmpl.addClass("ez5-mask-has-no-assets");
      if (opts.asset) {
        customIcon = this.getEmptyPlaceholderIcon();
        tmpl.append(EAS.getNoAssetInObjecttypePlaceholder(customIcon), "asset");
      }
      CUI.dom.setAttribute(tmpl.DOM, "ez5-number-of-assets", 0);
      return tmpl.DOM;
    } else if (cls === "result-list") {
      tmpl.addClass("ez5-card--result-list");
      hint = CUI.dom.span("ez5-result-card-hint");
      hint.textContent = $$("base.path_column.root.hint");
      tmpl.append([$$("base.path_column.root"), hint], "standard_1");
      if (opts.lassoable) {
        tmpl.addClass("ez5-lassoable");
      }
    } else {
      renderedPath = ResultObject.renderPath([$$("base.path_column.root")], false, opts);
      tmpl.append(renderedPath, "path");
      tmpl.append($$("base.path_column.root.standard.hint"), "standard_1");
      tmpl.addClass("italic", "standard_1");
    }
    return tmpl.DOM;
  };

  ParentRootResultObject.loadFromData = function(data) {
    var ro;
    ro = new ParentRootResultObject().setData(data);
    return CUI.resolvedPromise(ro);
  };

  ParentRootResultObject.prototype.getStandard = function(data, force) {
    if (data == null) {
      data = this.data;
    }
    if (force == null) {
      force = false;
    }
    return ParentRootResultObject.__super__.getStandard.call(this, data, force);
  };

  ParentRootResultObject.prototype.loadFromSearch = function(search_data, mask_name) {
    if (mask_name == null) {
      mask_name = null;
    }
    return CUI.resolvedPromise();
  };

  ParentRootResultObject.getSaveDataFromMask = function(mask) {
    var sd;
    sd = {
      _system_object_id: 0,
      _objecttype: mask.table.name()
    };
    sd[mask.table.name()] = {
      _id: 0
    };
    sd._mask = mask.name();
    return sd;
  };

  ParentRootResultObject.renderTableOutput = function() {
    return new CUI.Label({
      text: $$("base.path_column.root")
    });
  };

  ParentRootResultObject.renderCardStandard = function() {
    var ro;
    ro = new ParentRootResultObject();
    return ro.renderCardStandard();
  };

  return ParentRootResultObject;

})(ResultObject);
// Generated by CoffeeScript 1.12.7
var ResultManager,
  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;

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

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

  ResultManager.prototype.initOpts = function() {
    ResultManager.__super__.initOpts.call(this);
    return this.addOpts({
      managers: {
        check: Array
      },
      pref: {
        check: String
      },
      default_view: {
        check: "Integer",
        "default": 0
      }
    });
  };

  ResultManager.prototype.readOpts = function() {
    var i, len, m, ref;
    ResultManager.__super__.readOpts.call(this);
    ref = this._managers;
    for (i = 0, len = ref.length; i < len; i++) {
      m = ref[i];
      CUI.util.assert(m instanceof ResultManagerResult, "new ResultManager", "opts.managers needs to be instance of ResultManagerResult", {
        opts: this.opts
      });
    }
    return this.managers = this._managers;
  };

  ResultManager.prototype.init = function() {
    var d, fn, i, idx, j, k, l, len, len1, len2, mgr, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, selectedViewExists, sm, switch_view, v;
    if (this._pref) {
      this.data = ez5.session.getPref(this._pref);
    }
    if (!this.data) {
      this.data = {
        view_select: ((ref = this.managers[this._default_view]) != null ? ref.getName() : void 0) || ((ref1 = this.managers[0]) != null ? ref1.getName() : void 0),
        view_data: {}
      };
    }
    ref2 = this.managers;
    for (i = 0, len = ref2.length; i < len; i++) {
      sm = ref2[i];
      mgr = sm.getName();
      if (!this.data.view_data[mgr]) {
        this.data.view_data[mgr] = {};
      }
      ref3 = sm.getViewDataDefault() || {};
      for (k in ref3) {
        v = ref3[k];
        if (this.data.view_data[mgr][k] === void 0) {
          this.data.view_data[mgr][k] = v;
        }
      }
    }
    if (CUI.util.isInteger(this.data.view_select)) {
      this.data.view_select = ((ref4 = this.managers[this._default_view]) != null ? ref4.getName() : void 0) || ((ref5 = this.managers[0]) != null ? ref5.getName() : void 0);
    }
    selectedViewExists = false;
    ref6 = this.managers;
    for (j = 0, len1 = ref6.length; j < len1; j++) {
      sm = ref6[j];
      if (sm.getName() === this.data.view_select) {
        selectedViewExists = true;
        break;
      }
    }
    if (!selectedViewExists) {
      this.data.view_select = ((ref7 = this.managers[this._default_view]) != null ? ref7.getName() : void 0) || ((ref8 = this.managers[0]) != null ? ref8.getName() : void 0);
    }
    this.viewBtns = [];
    switch_view = (function(_this) {
      return function() {
        return _this.setResultManagerInSearch().done(function() {
          return _this.saveViewData().done(function() {
            if (_this.getSearch().getSearchButton().isDisabled()) {
              return;
            }
            _this.disableViewBtns();
            return _this.getSearch().execute().always(function() {
              return _this.enableViewBtns();
            });
          });
        });
      };
    })(this);
    ref9 = this.managers;
    fn = (function(_this) {
      return function(sm) {
        var smName;
        smName = sm.getName().toLocaleLowerCase();
        return _this.viewBtns.push(new LocaButton({
          ui: "result.manager.view.button:" + smName,
          loca_key: "main.search.view." + smName,
          group: "view",
          radio: "view",
          attr: {
            value: sm.getName()
          },
          value: sm.getName(),
          active: sm.getName() === _this.data.view_select,
          onClick: function() {
            _this.data.view_select = sm.getName();
            return switch_view();
          }
        }));
      };
    })(this);
    for (idx = l = 0, len2 = ref9.length; l < len2; idx = ++l) {
      sm = ref9[idx];
      fn(sm);
      if (!(d = this.data.view_data[sm.getName()])) {
        d = this.data.view_data[sm.getName()] = {};
      }
      sm.setData(d);
    }
    this.settings_btn = new LocaButton({
      ui: "result.manager.view.options.button",
      "class": "ez5-result-manager-button-options",
      loca_key: "result.manager.button.options",
      group: "view",
      onClick: (function(_this) {
        return function() {
          var activeBtn, btn, len3, n, ref10, ref11;
          if (((ref10 = ez5.cssLoader.getActiveCSS()) != null ? ref10.theme : void 0) === 'fylr') {
            return _this.showPopover(_this.settings_btn.DOM);
          } else {
            activeBtn = null;
            ref11 = _this.viewBtns;
            for (n = 0, len3 = ref11.length; n < len3; n++) {
              btn = ref11[n];
              if (btn.getValue() === _this.data.view_select) {
                activeBtn = btn;
                break;
              }
            }
            return _this.showPopover((activeBtn != null ? activeBtn.DOM : void 0) || _this.settings_btn.DOM);
          }
        };
      })(this)
    });
    this.viewBtns.push(this.settings_btn);
    this.getSearch().getButtonToolbar().append(this.viewBtns, "left");
    return this.setResultManagerInSearch();
  };

  ResultManager.prototype.destroy = function() {
    var i, len, ref, sm;
    ref = this.managers;
    for (i = 0, len = ref.length; i < len; i++) {
      sm = ref[i];
      sm.destroy();
    }
    return ResultManager.__super__.destroy.call(this);
  };

  ResultManager.prototype.showPopover = function(element) {
    var pop;
    CUI.dom.addClass(this.settings_btn, CUI.defaults["class"].Button.defaults.active_css_class);
    pop = new CUI.Popover({
      element: element,
      backdrop: {
        policy: "click"
      },
      "class": "view-select-popover",
      pane: {
        header_left: new LocaLabel({
          loca_key: "main.search.view.result.title",
          loca_key_attrs: {
            view: $$("main.search.view." + this.current_result_manager.getName())
          }
        }),
        padded: true,
        content: (function(_this) {
          return function() {
            var f, fields, form, i, len;
            fields = _this.current_result_manager.getViewFields();
            for (i = 0, len = fields.length; i < len; i++) {
              f = fields[i];
              f.undo_and_changed_support = false;
            }
            form = new CUI.Form({
              fields: fields,
              undo_and_changed_support: false,
              onDataChanged: function(data, df) {
                pop.changed = true;
                return _this.current_result_manager.updateView(form);
              },
              data: _this.data.view_data[_this.current_result_manager.getName()]
            });
            form.start();
            _this.current_result_manager.initView(form);
            return form;
          };
        })(this)
      },
      onHide: (function(_this) {
        return function() {
          if (pop.changed) {
            _this.saveViewData(true);
          }
          return CUI.dom.removeClass(_this.settings_btn, CUI.defaults["class"].Button.defaults.active_css_class);
        };
      })(this)
    });
    return pop.show();
  };

  ResultManager.prototype.disableViewBtns = function() {
    var btn, i, len, ref;
    ref = this.viewBtns;
    for (i = 0, len = ref.length; i < len; i++) {
      btn = ref[i];
      btn.disable();
    }
    return this;
  };

  ResultManager.prototype.enableViewBtns = function() {
    var btn, i, len, ref;
    ref = this.viewBtns;
    for (i = 0, len = ref.length; i < len; i++) {
      btn = ref[i];
      btn.enable();
    }
    return this;
  };

  ResultManager.prototype.saveViewData = function(call_save_view_done) {
    if (call_save_view_done == null) {
      call_save_view_done = false;
    }
    if (this._pref) {
      ez5.session.savePref(this._pref, this.data, true);
      if (call_save_view_done) {
        this.current_result_manager.saveViewDone().always((function(_this) {
          return function() {
            return _this.enableViewBtns();
          };
        })(this));
      }
      return CUI.resolvedPromise();
    } else {
      return CUI.resolvedPromise();
    }
  };

  ResultManager.prototype.setResultManagerInSearch = function() {
    var i, len, ref, ret, selectedManager, sm;
    selectedManager = null;
    ref = this.managers;
    for (i = 0, len = ref.length; i < len; i++) {
      sm = ref[i];
      if (sm.getName() === this.data.view_select) {
        selectedManager = sm;
        break;
      }
    }
    if (this.current_result_manager === selectedManager) {
      return CUI.rejectedPromise();
    }
    if (this.current_result_manager) {
      this.getSearch().removeSearchManager(this.current_result_manager);
    }
    this.current_result_manager = selectedManager;
    ret = this.getSearch().insertAfterSearchManager(this, this.current_result_manager).init();
    if (CUI.util.isPromise(ret)) {
      return ret;
    } else {
      return CUI.resolvedPromise();
    }
  };

  ResultManager.prototype.getCurrentViewData = function() {
    return this.data.view_data[this.current_result_manager.getName()];
  };

  return ResultManager;

})(SearchManager);
// Generated by CoffeeScript 1.12.7
var ResultStandard,
  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;

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

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

  ResultStandard.prototype.getName = function() {
    return "result-standard";
  };

  ResultStandard.prototype.getRenderType = function() {
    return "standard";
  };

  ResultStandard.prototype.init = function() {
    ResultStandard.__super__.init.call(this);
    return this.cssSwitcher = new CSSSwitcher({
      element: this.__pane.DOM,
      variants: window[this.getElementClass()].CSSVariants,
      data: this.view_data
    });
  };

  ResultStandard.prototype.updateView = function(form) {
    this.checkOptionDependencies(form);
    this.cssSwitcher.setCSS();
    return ResultStandard.__super__.updateView.call(this, form);
  };

  ResultStandard.prototype.getViewDataDefault = function() {
    return {
      variant_texts: 1,
      variant_result: 2,
      variant_format: 0,
      variant_layout: 0,
      variant_standard_info: 1,
      variant_show_options: ["path", "standard_info", "info", "poolinfo", "tags", "system_object_id", "technical_info"]
    };
  };

  ResultStandard.prototype.initView = function(form) {
    return this.checkOptionDependencies(form);
  };

  ResultStandard.prototype.getFillViewMode = function() {
    var mode;
    if (this.__pane.hasClass("result-standard-info-underlay")) {
      mode = "underlay";
    } else if (this.__pane.hasClass("result-standard-info-sideways")) {
      mode = "sideways";
    } else if (this.__pane.hasClass("result-standard-info-overlay") || this.__pane.hasClass("result-standard-info-none")) {
      mode = "overlay";
    } else {
      console.error("ResultDynamic.__updateFillViewLayout", "Unable to set mode: underlay, sideways, overlay. Falling back to 'overlay'.");
      mode = "overlay";
    }
    if (this.__pane.hasClass("result-standard-format-fill")) {
      if (mode === "overlay") {
        mode = "fill";
      } else {
        console.error("ResultDynamic.__updateFillViewLayout", "Unable to set mode 'fill' if not in 'overlay' mode. Mode is:", mode);
      }
    }
    return mode;
  };

  ResultStandard.prototype.checkOptionDependencies = function(form) {
    var allOptions, cb, checkLayoutOption, checkShowOption, dependencies, field, format_field, format_layout, formats_def, i, idx, j, k, k_objecttype, k_path, k_pool, k_standard, k_system_id, k_tags, k_technical, l, layouts_def, len, len1, len2, len3, len4, len5, m, n, opt, option, ref, ref1, ref2, ref3, ref4, ref5, show_options, sizes_def, standardAndTags;
    k_standard = "standard_info";
    k_path = "path";
    k_objecttype = "info";
    k_pool = "poolinfo";
    k_system_id = "system_object_id";
    k_tags = "tags";
    k_technical = "technical_info";
    allOptions = [k_path, k_standard, k_objecttype, k_pool, k_system_id, k_tags, k_technical];
    standardAndTags = [k_standard, k_tags];
    sizes_def = ["mini", "midi", "large", "max"];
    formats_def = ["fill", "thumbnail", "cover"];
    layouts_def = ["overlay", "underlay", "sideways", "none"];
    dependencies = {
      mini: {
        fill: {
          none: []
        },
        thumbnail: {
          underlay: standardAndTags,
          none: [],
          sideways: standardAndTags
        },
        cover: {
          underlay: standardAndTags,
          sideways: standardAndTags
        }
      },
      midi: {
        fill: {
          overlay: standardAndTags,
          none: []
        },
        thumbnail: {
          overlay: standardAndTags,
          underlay: [k_path, k_standard, k_objecttype, k_pool, k_system_id, k_tags],
          sideways: [k_path, k_standard, k_objecttype, k_pool, k_system_id, k_tags],
          none: []
        },
        cover: {
          overlay: standardAndTags,
          underlay: [k_path, k_standard, k_objecttype, k_pool, k_system_id, k_tags],
          sideways: [k_path, k_standard, k_objecttype, k_pool, k_system_id, k_tags],
          none: []
        }
      },
      large: {
        fill: {
          overlay: allOptions,
          none: []
        },
        thumbnail: {
          overlay: allOptions,
          underlay: allOptions,
          sideways: allOptions,
          none: []
        },
        cover: {
          overlay: allOptions,
          underlay: allOptions,
          sideways: allOptions,
          none: []
        }
      },
      max: {
        fill: {
          overlay: allOptions,
          none: []
        },
        thumbnail: {
          overlay: allOptions,
          underlay: allOptions,
          sideways: allOptions,
          none: []
        },
        cover: {
          overlay: allOptions,
          underlay: allOptions,
          sideways: allOptions,
          none: []
        }
      }
    };
    checkShowOption = function(option, size, format, layout) {
      var ref, ref1, ref2;
      size = sizes_def[size];
      format = formats_def[format];
      layout = layouts_def[layout];
      return (ref = dependencies[size]) != null ? (ref1 = ref[format]) != null ? (ref2 = ref1[layout]) != null ? ref2.includes(option) : void 0 : void 0 : void 0;
    };
    checkLayoutOption = function(layout, size, format) {
      var ref, ref1;
      size = sizes_def[size];
      format = formats_def[format];
      layout = layouts_def[layout];
      return (ref = dependencies[size]) != null ? (ref1 = ref[format]) != null ? ref1[layout] : void 0 : void 0;
    };
    format_field = form.getFieldsByName("variant_format")[0];
    format_layout = form.getFieldsByName("variant_layout")[0];
    show_options = form.getFieldsByName("variant_show_options")[0];
    ref = [format_field, format_layout];
    for (i = 0, len = ref.length; i < len; i++) {
      field = ref[i];
      ref1 = field.getOptions();
      for (idx = j = 0, len1 = ref1.length; j < len1; idx = ++j) {
        opt = ref1[idx];
        field.enableOption(idx);
      }
    }
    ref2 = show_options.getOptions();
    for (k = 0, len2 = ref2.length; k < len2; k++) {
      opt = ref2[k];
      show_options.enableOption(opt.value);
    }
    ref3 = format_layout.getOptions();
    for (l = 0, len3 = ref3.length; l < len3; l++) {
      opt = ref3[l];
      if (!checkLayoutOption(opt.value, this.view_data.variant_result, this.view_data.variant_format)) {
        format_layout.disableOption(opt.value);
      }
    }
    if (format_layout.__getCheckboxByValue(this.view_data.variant_layout).isDisabled()) {
      ref4 = format_layout.getOptions();
      for (m = 0, len4 = ref4.length; m < len4; m++) {
        option = ref4[m];
        cb = format_layout.__getCheckboxByValue(option.value);
        if (!cb.isDisabled()) {
          format_layout.setValue(option.value);
          break;
        }
      }
    }
    ref5 = show_options.getOptions();
    for (n = 0, len5 = ref5.length; n < len5; n++) {
      opt = ref5[n];
      if (!checkShowOption(opt.value, this.view_data.variant_result, this.view_data.variant_format, this.view_data.variant_layout)) {
        show_options.disableOption(opt.value);
      }
    }
  };

  ResultStandard.prototype.getViewFields = function() {
    var fields;
    fields = this.cssSwitcher.getFields();
    fields.push.apply(fields, ResultStandard.__super__.getViewFields.call(this));
    return fields;
  };

  ResultStandard.prototype.getCSSSwitcher = function() {
    return this.cssSwitcher;
  };

  ResultStandard.CSSVariants = [
    {
      type: "choice",
      name: "result",
      label: "main.search.view.result",
      classes: [
        {
          label: "main.search.view.result.mini",
          "class": "result-standard-mini"
        }, {
          label: "main.search.view.result.midi",
          "class": "result-standard-midi"
        }, {
          label: "main.search.view.result.maxi",
          "class": "result-standard-maxi"
        }, {
          label: "main.search.view.result.huge",
          "class": "result-standard-huge"
        }
      ]
    }, {
      type: "choice",
      name: "format",
      label: "main.search.view.result.format",
      classes: [
        {
          label: "main.search.view.result.fill",
          "class": "result-standard-format-fill"
        }, {
          label: "main.search.view.result.thumbnail",
          "class": "result-standard-format-square"
        }, {
          label: "main.search.view.result.blow-up",
          "class": "eas-image-blow-up"
        }
      ]
    }, {
      type: "choice",
      name: "layout",
      label: "main.search.view.result.info.layout",
      classes: [
        {
          label: "main.search.view.result.info.layout.overlay",
          "class": "result-standard-info-overlay"
        }, {
          label: "main.search.view.result.info.layout.underlay",
          "class": "result-standard-info-underlay"
        }, {
          label: "main.search.view.result.info.layout.sideways",
          "class": "result-standard-info-sideways"
        }, {
          label: "main.search.view.result.info.layout.none",
          "class": "result-standard-info-overlay result-standard-info-none"
        }
      ]
    }, {
      type: "options",
      name: "show_options",
      label: "main.search.view.result.show-options",
      options: [
        {
          name: "path",
          label: "main.search.view.result.show_path",
          classes: [
            {
              "class": "hide-result-card-path"
            }, {
              "class": "show-result-card-path"
            }
          ]
        }, {
          name: "standard_info",
          label: "main.search.view.result.show_standard",
          classes: [
            {
              "class": "hide-result-card-standard"
            }, {
              "class": "show-result-card-standard"
            }
          ]
        }, {
          name: "info",
          label: "main.search.view.result.show_objecttypes",
          classes: [
            {
              "class": "hide-result-card-objecttype"
            }, {
              "class": "show-result-card-objecttype"
            }
          ]
        }, {
          name: "poolinfo",
          label: "main.search.view.result.show_poolpaths",
          classes: [
            {
              "class": "hide-result-card-pool"
            }, {
              "class": "show-result-card-pool"
            }
          ]
        }, {
          name: "tags",
          label: "main.search.view.result.show_tags",
          classes: [
            {
              "class": "hide-result-card-tags"
            }, {
              "class": "show-result-card-tags"
            }
          ]
        }, {
          name: "system_object_id",
          label: "main.search.view.result.show_system_object_id",
          classes: [
            {
              "class": "hide-result-card-system_object_id"
            }, {
              "class": "show-result-card-system_object_id"
            }
          ]
        }, {
          name: "technical_info",
          label: "main.search.view.result.show_technical_info",
          classes: [
            {
              "class": "hide-result-card-technical_info"
            }, {
              "class": "show-result-card-technical_info"
            }
          ]
        }
      ]
    }
  ];

  return ResultStandard;

})(ResultDynamic);
// Generated by CoffeeScript 1.12.7
var ResultDetail,
  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;

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

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

  ResultDetail.prototype.getName = function() {
    return "result-detail";
  };

  ResultDetail.prototype.getRenderType = function() {
    return "detail";
  };

  ResultDetail.prototype.getPageSizes = function() {
    return [2, 5, 10, 20, 30, 40, 50];
  };

  ResultDetail.prototype.init = function() {
    ResultDetail.__super__.init.call(this);
    return this.cssSwitcher = new CSSSwitcher({
      element: this.__pane.DOM,
      variants: window[this.getElementClass()].CSSVariants,
      data: this.view_data
    });
  };

  ResultDetail.prototype.updateView = function(form) {
    this.cssSwitcher.setCSS();
    return ResultDetail.__super__.updateView.call(this, form);
  };

  ResultDetail.prototype.getViewFields = function() {
    var fields;
    fields = this.cssSwitcher.getFields();
    fields.push.apply(fields, ResultDetail.__super__.getViewFields.call(this));
    return fields;
  };

  ResultDetail.prototype.getViewDataDefault = function() {
    return {
      variant_view: 0
    };
  };

  ResultDetail.prototype.__updateFillViewLayout = function() {};

  ResultDetail.CSSVariants = [
    {
      type: "choice",
      name: "view",
      label: "result.dynamic.detail.view",
      classes: [
        {
          label: "result.dynamic.detail.view.all",
          "class": "result-detail-view-all"
        }, {
          label: "result.dynamic.detail.view.only_image",
          "class": "result-detail-view-image"
        }, {
          label: "result.dynamic.detail.view.only_data",
          "class": "result-detail-view-data"
        }
      ]
    }
  ];

  return ResultDetail;

})(ResultDynamic);
// Generated by CoffeeScript 1.12.7
var ResultText,
  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;

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

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

  ResultText.prototype.getName = function() {
    return "result-text";
  };

  ResultText.prototype.__page_size = 10;

  ResultText.prototype.getPageSizes = function() {
    return [10, 25, 50, 100];
  };

  ResultText.prototype.getViewDataDefault = function() {
    return {
      variant_show_options: ["path", "standard_info", "info", "poolinfo", "tags", "system_object_id", "technical_info"]
    };
  };

  ResultText.prototype.getRenderType = function() {
    return "text";
  };

  ResultText.prototype.getFillViewMode = function() {
    return "dynamic";
  };

  ResultText.prototype.getViewFields = function() {
    var fields;
    fields = this.cssSwitcher.getFields();
    fields.push.apply(fields, ResultDynamic.prototype.getViewFields.call(this));
    return fields;
  };

  ResultText.prototype.checkOptionDependencies = function(form) {};

  ResultText.prototype.__updateFillViewLayout = function() {};

  ResultText.CSSVariants = [
    {
      type: "options",
      name: "show_options",
      label: "main.search.view.result.show-options",
      options: [
        {
          name: "path",
          label: "main.search.view.result.show_path",
          classes: [
            {
              "class": "hide-result-card-path"
            }, {
              "class": "show-result-card-path"
            }
          ]
        }, {
          name: "standard_info",
          label: "main.search.view.result.show_standard",
          classes: [
            {
              "class": "hide-result-card-standard"
            }, {
              "class": "show-result-card-standard"
            }
          ]
        }, {
          name: "info",
          label: "main.search.view.result.show_objecttypes",
          classes: [
            {
              "class": "hide-result-card-objecttype"
            }, {
              "class": "show-result-card-objecttype"
            }
          ]
        }, {
          name: "poolinfo",
          label: "main.search.view.result.show_poolpaths",
          classes: [
            {
              "class": "hide-result-card-pool"
            }, {
              "class": "show-result-card-pool"
            }
          ]
        }, {
          name: "tags",
          label: "main.search.view.result.show_tags",
          classes: [
            {
              "class": "hide-result-card-tags"
            }, {
              "class": "show-result-card-tags"
            }
          ]
        }, {
          name: "system_object_id",
          label: "main.search.view.result.show_system_object_id",
          classes: [
            {
              "class": "hide-result-card-system_object_id"
            }, {
              "class": "show-result-card-system_object_id"
            }
          ]
        }, {
          name: "technical_info",
          label: "main.search.view.result.show_technical_info",
          classes: [
            {
              "class": "hide-result-card-technical_info"
            }, {
              "class": "show-result-card-technical_info"
            }
          ]
        }
      ]
    }
  ];

  return ResultText;

})(ResultStandard);
// Generated by CoffeeScript 1.12.7
var ResultTable,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  ResultTable.prototype.__page_size = 10;

  ResultTable.prototype.__page_sizes = [10, 25, 50, 100];

  ResultTable.prototype.__nested_page_sizes = [5, 10, 20];

  ResultTable.prototype.initOpts = function() {
    ResultTable.__super__.initOpts.call(this);
    return this.addOpts({
      open_nodes: {
        "default": false,
        mandatory: true,
        check: Boolean
      },
      show_navigation: {
        "default": true,
        mandatory: true,
        check: Boolean
      }
    });
  };

  ResultTable.prototype.readOpts = function() {
    ResultTable.__super__.readOpts.call(this);
    return;
    if (this._selectable_opts && !this.opts.selectable_opts.onDraggableCreate) {
      this._selectable_opts.onDraggableCreate = (function(_this) {
        return function(ev) {
          if (ev.hasModifierKey()) {
            return false;
          }
          if (!CUI.dom.closest(ev.getTarget(), ".ez5-lassoable")) {
            return false;
          }
          return true;
        };
      })(this);
    }
  };

  ResultTable.prototype.getName = function() {
    return "result-table";
  };

  ResultTable.prototype.init = function() {
    var base, welcome_message;
    ResultTable.__super__.init.call(this);
    if (this._show_navigation) {
      this.__navi = new ResultNavigationToolbar({
        "class": "ez5-result-dynamic-navigation-toolbar",
        search: this.getSearch(),
        navigation_buttons_left: this._navigation_buttons_left,
        getPageSize: (function(_this) {
          return function() {
            return _this.getPageSize();
          };
        })(this)
      });
    }
    this.__pane = new CUI.Pane({
      "class": "ez5-result-table-pane",
      absolute: this._pane_absolute,
      bottom: {
        content: this.__navi
      }
    });
    welcome_message = typeof (base = this.getSearch()).getWelcomeMessagesDiv === "function" ? base.getWelcomeMessagesDiv(true) : void 0;
    CUI.dom.append(this.__pane.center(), welcome_message);
    this.__cssSwitcher = new CSSSwitcher({
      element: this.__pane.DOM,
      variants: this.getCSSVariants(),
      data: this.view_data
    });
    return CUI.dom.replace(this.getResultContainer(), this.__pane);
  };

  ResultTable.prototype.getCSSVariants = function() {
    var key;
    return [
      {
        type: "choice",
        name: "card_size",
        label: "result.table.view.card_size",
        classes: (function() {
          var i, len, ref, results;
          ref = ['mini', 'midi', 'maxi'];
          results = [];
          for (i = 0, len = ref.length; i < len; i++) {
            key = ref[i];
            results.push({
              label: "result.table.view.card_size." + key,
              "class": "result-table-card-" + key
            });
          }
          return results;
        })()
      }
    ];
  };

  ResultTable.prototype.setSearch = function(_search) {
    this._search = _search;
    ResultTable.__super__.setSearch.call(this, this._search);
    this.__poll_listener = EventPoller.listen({
      filter: {
        type: ["OBJECT_DELETE", "OBJECT_INDEX", "OBJECT_UNDELETE", "OBJECT_PURGE"]
      },
      instance: this,
      call: (function(_this) {
        return function(events) {
          var container, el, event, gid, i, j, len, len1, node, ref, resultTableNode, update_nodes;
          container = _this.getResultContainer();
          update_nodes = [];
          for (i = 0, len = events.length; i < len; i++) {
            event = events[i];
            gid = event.global_object_id;
            ref = CUI.dom.matchSelector(container, "[global-object-id=\"" + gid + "\"]");
            for (j = 0, len1 = ref.length; j < len1; j++) {
              el = ref[j];
              resultTableNode = CUI.dom.data(el, "listViewRow");
              if (event.type === "OBJECT_DELETE") {
                node = new ResultTableNodeDeleted();
                resultTableNode.prependSibling(node);
                resultTableNode.remove();
              } else if (event.type === "OBJECT_PURGE") {
                node = new ResultTableNodeDeleted({
                  policy: "purge"
                });
                resultTableNode.prependSibling(node);
                resultTableNode.remove();
              } else if (event.type === "OBJECT_UNDELETE") {
                node = new ResultTableNodeDeleted({
                  policy: "undelete"
                });
                resultTableNode.prependSibling(node);
                resultTableNode.remove();
              } else {
                update_nodes.push(resultTableNode);
              }
            }
          }
          if (update_nodes.length) {
            _this.__updateDataInNodes(update_nodes).done(function() {
              var l, len2, results;
              results = [];
              for (l = 0, len2 = update_nodes.length; l < len2; l++) {
                node = update_nodes[l];
                results.push(node.update());
              }
              return results;
            });
          }
        };
      })(this)
    });
    return this;
  };

  ResultTable.prototype.unsetSearch = function() {
    ResultTable.__super__.unsetSearch.call(this);
    if (this.__poll_listener) {
      CUI.Events.ignore(this.__poll_listener);
      this.__poll_listener = null;
    }
    return this;
  };

  ResultTable.prototype.getNavigation = function() {
    return this.__navi;
  };

  ResultTable.prototype.getPageSize = function() {
    return this.view_data.page_size;
  };

  ResultTable.prototype.getExcludeFields = function() {
    var ref;
    if ((ref = this.__exclude_fields) != null ? ref.length : void 0) {
      return this.__exclude_fields;
    } else {
      return void 0;
    }
  };

  ResultTable.prototype.addToRequest = function(request) {
    var i, len, mask, mask_name, ref, visible_fields;
    request.limit = this.getPageSize();
    request.format = this.getObjectFormatNeededInternal();
    request.generate_rights = false;
    if (request.format === "long") {
      this.__exclude_fields = [];
      visible_fields = {};
      ref = this.getSearch().getSearchBasics().getMaskNames();
      for (i = 0, len = ref.length; i < len; i++) {
        mask_name = ref[i];
        mask = ez5.mask.CURRENT._mask_instance_by_name[mask_name];
        mask.invokeOnFields("all", true, (function(_this) {
          return function(field, data, depth) {
            var fn;
            if (field instanceof MaskSplitter) {
              return;
            }
            switch (field.name()) {
              case "_version":
              case "_id":
              case "_pool":
              case "_id_parent":
              case "_mask":
              case "_standard":
              case "_path":
              case "_global_object_id":
              case "_system_object_id":
              case "_tags":
              case "_collections":
              case "_objecttype":
                return;
            }
            fn = field.fullName();
            if (field.isVisible("table")) {
              visible_fields[fn] = true;
              CUI.util.removeFromArray(fn, _this.__exclude_fields);
              return;
            }
            if (!visible_fields[fn]) {
              CUI.util.pushOntoArray(fn, _this.__exclude_fields);
              return false;
            }
          };
        })(this));
      }
    } else {
      this.__exclude_fields = null;
    }
    request.exclude_fields = this.getExcludeFields();
    if (!request.aggregations) {
      request.aggregations = {};
    }
    request.aggregations._result_table_masks = {
      type: "term",
      limit: 100000,
      field: "_mask"
    };
    if (request.execute && !this.__waitBlock) {
      if (request.page_request && this.__tree) {
        this.__waitBlock = new CUI.WaitBlock({
          element: this.__tree.getBottom()
        }).show();
      } else {
        this.__waitBlock = new CUI.WaitBlock({
          element: this.getResultContainer()
        }).show();
      }
    }
    return this;
  };

  ResultTable.prototype.getAdditionalViewFields = function() {
    return [
      {
        type: CUI.Options,
        sortable: true,
        name: "show_options",
        form: {
          label: $$("result.table.view.show-options")
        },
        options: [
          {
            value: "standard",
            text: $$("result.table.view.show-options.standard")
          }, {
            value: "tags",
            text: $$("result.table.view.show-options.tags")
          }, {
            value: 'system_object_id',
            text: $$("result.table.view.show-options.system_object_id")
          }, {
            value: 'pool',
            text: $$("result.table.view.show-options.pool")
          }, {
            value: 'objecttype',
            text: $$("result.table.view.show-options.objecttype")
          }
        ]
      }, {
        type: CUI.Checkbox,
        text: $$("result.table.view.show_hierarchy"),
        name: "show_hierarchy"
      }
    ];
  };

  ResultTable.prototype.filterTopLevel = function(request) {
    if (this.view_data.show_hierarchy) {
      return false;
    } else {
      return true;
    }
  };

  ResultTable.prototype.getViewFields = function() {
    var fields, o;
    fields = this.__cssSwitcher.getFields();
    fields.push.apply(fields, this.getAdditionalViewFields());
    fields.push({
      type: CUI.Select,
      form: {
        label: $$("result.table.select.page_size")
      },
      name: "page_size",
      options: (function() {
        var i, len, ref, results;
        ref = this.__page_sizes;
        results = [];
        for (i = 0, len = ref.length; i < len; i++) {
          o = ref[i];
          results.push({
            text: o + "",
            value: o
          });
        }
        return results;
      }).call(this)
    });
    fields.push({
      type: CUI.Select,
      form: {
        label: $$("result.table.select.nested_field.page_size")
      },
      name: "nested_page_size",
      options: (function() {
        var i, len, ref, results;
        ref = this.__nested_page_sizes;
        results = [];
        for (i = 0, len = ref.length; i < len; i++) {
          o = ref[i];
          results.push({
            text: "" + o,
            value: o
          });
        }
        return results;
      }).call(this)
    });
    return fields;
  };

  ResultTable.prototype.getViewData = function() {
    return this.view_data;
  };

  ResultTable.prototype.saveViewDone = function() {
    var current, page;
    if (!this.__tree) {
      return CUI.resolvedPromise();
    }
    current = this.__navi.getCurrent();
    if (this.view_data.page_size !== current.pageSize || this.view_data.show_hierarchy !== this.__show_hierarchy || this.view_data.nested_page_size !== this.__current_view_data.nested_page_size) {
      if (!this.__navi) {
        return this.getSearch().execute();
      } else {
        page = Math.floor((current.offset || 0) / this.view_data.page_size);
        return this.__navi.loadPage(page);
      }
    } else if (!CUI.util.isEqual(this.__current_view_data.show_options, this.view_data.show_options)) {
      return this.getSearch().execute();
    } else {
      return CUI.resolvedPromise();
    }
  };

  ResultTable.prototype.updateView = function(form) {
    this.__cssSwitcher.setCSS();
    return ResultTable.__super__.updateView.call(this, form);
  };

  ResultTable.prototype.initView = function() {
    var k, ref, v;
    this.__current_view_data = CUI.util.copyObject(this.view_data, true);
    ref = this.view_data;
    for (k in ref) {
      v = ref[k];
      if (k !== 'nested_page_size' && k !== 'page_size' && k !== 'show_options' && k !== 'show_hierarchy' && k !== 'variant_card_size') {
        console.debug("deleting key:", k);
        delete this.view_data[k];
      }
    }
    return this;
  };

  ResultTable.prototype.setData = function(view_data) {
    var i, k, len, ref, ref1, ref2;
    this.view_data = view_data;
    ref = ["page_size"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      if (CUI.util.isUndef(this.view_data[k])) {
        this.view_data[k] = this["__" + k];
      }
    }
    if (ref1 = this.view_data.page_size, indexOf.call(this.__page_sizes, ref1) < 0) {
      this.view_data.page_size = this.__page_size;
    }
    if (ref2 = this.view_data.nested_page_size, indexOf.call(this.__nested_page_sizes, ref2) < 0) {
      this.view_data.nested_page_size = this.__nested_page_sizes[0];
    }
    if (!this.view_data.show_options) {
      this.view_data.show_options = [];
    }
    this.__current_view_data = CUI.util.copyObject(this.view_data, true);
    return this;
  };

  ResultTable.prototype.getNodesFromData = function(data) {
    if (this.__show_hierarchy) {
      return this.getNodesFromDataTree(data);
    } else {
      return this.getNodesFromDataFlat(data);
    }
  };

  ResultTable.prototype.getNodesFromDataTree = function(data) {
    var gid, hasChildrenInSearch, i, idx, j, l, len, len1, len2, node, nodes, obj, object, objectPerGlobalObjectId, ref, ref1, searchNodeInChildren, stoppedOpenNodesGids;
    objectPerGlobalObjectId = {};
    stoppedOpenNodesGids = [];
    hasChildrenInSearch = (function(_this) {
      return function(objectData) {
        var child, i, len, ref;
        if (!objectData.children || objectData.children.length === 0) {
          return false;
        }
        ref = objectData.children;
        for (i = 0, len = ref.length; i < len; i++) {
          child = ref[i];
          if (objectPerGlobalObjectId[child._object._global_object_id]) {
            return true;
          }
          if (child.children && child.children.length > 0) {
            return hasChildrenInSearch(child);
          }
        }
        return false;
      };
    })(this);
    ref = data.objects;
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      obj = ref[idx];
      obj.__offset = data.offset + idx;
    }
    ref1 = data.objects;
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      object = ref1[j];
      objectPerGlobalObjectId[object._global_object_id] = object;
    }
    nodes = ez5.buildObjectTree({
      objects: data.objects,
      objectKey: (function(_this) {
        return function(obj) {
          return obj._objecttype;
        };
      })(this),
      doOpen: this._open_nodes,
      newInstanceFunc: (function(_this) {
        return function(obj) {
          var cls, node, stopOpen;
          cls = "";
          stopOpen = false;
          if (objectPerGlobalObjectId[obj._global_object_id]) {
            stopOpen = true;
          }
          node = new ResultTableNode({
            resultTable: _this,
            object: obj,
            "class": cls,
            open: _this._open_nodes && !stopOpen,
            offset: obj.__offset,
            path: "" + obj.__offset,
            cols: _this.__info.cols,
            field_per_column: _this.__info.field_per_column
          });
          if (stopOpen && _this._open_nodes && obj._has_children) {
            stoppedOpenNodesGids.push(obj._global_object_id);
          }
          return node;
        };
      })(this)
    });
    if (stoppedOpenNodesGids.length > 0) {
      searchNodeInChildren = (function(_this) {
        return function(children, gid) {
          var child, l, len2, nodeFound;
          if (!children || children.length === 0) {
            return;
          }
          for (l = 0, len2 = children.length; l < len2; l++) {
            child = children[l];
            if (child._object._global_object_id === gid) {
              return child;
            }
            if (child.children && child.children.length > 0) {
              nodeFound = searchNodeInChildren(child.children, gid);
              if (nodeFound) {
                return nodeFound;
              }
            }
          }
        };
      })(this);
      for (l = 0, len2 = stoppedOpenNodesGids.length; l < len2; l++) {
        gid = stoppedOpenNodesGids[l];
        node = searchNodeInChildren(nodes, gid);
        if (node && hasChildrenInSearch(node)) {
          node.do_open = true;
        }
      }
    }
    return nodes;
  };

  ResultTable.prototype.getNodesFromDataFlat = function(data) {
    var i, idx, len, node, nodes, obj, offset, ref;
    nodes = [];
    ref = data.objects;
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      obj = ref[idx];
      offset = data.offset + idx;
      node = new ResultTableNode({
        resultTable: this,
        object: obj,
        open: this._open_nodes && obj._has_children,
        path: data.__path + "." + offset,
        offset: data.offset + idx,
        cols: this.__info.cols,
        field_per_column: this.__info.field_per_column
      });
      nodes.push(node);
    }
    return nodes;
  };

  ResultTable.prototype.getNodesFromDataFlatNoHierarchy = function(data) {
    var i, idx, len, node, nodes, obj, offset, ref;
    nodes = [];
    ref = data.objects;
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      obj = ref[idx];
      offset = data.offset + idx;
      node = new ResultTableNode({
        force_no_children: true,
        resultTable: this,
        object: obj,
        open: false,
        path: "" + offset,
        offset: data.offset + idx,
        cols: this.__info.cols,
        field_per_column: this.__info.field_per_column
      });
      nodes.push(node);
    }
    return nodes;
  };

  ResultTable.prototype.destroy = function() {
    var ref;
    if (this.__navi) {
      this.__navi.destroy();
      this.__navi = null;
    }
    if (this.__tree) {
      this.__tree.destroy();
      this.__tree = null;
    }
    if (this.__waitBlock) {
      this.__waitBlock.destroy();
      this.__waitBlock = null;
    }
    if (this.__poll_listener) {
      CUI.Events.ignore(this.__poll_listener);
      this.__poll_listener = null;
    }
    if ((ref = this.__cssSwitcher) != null) {
      ref.destroy();
    }
    delete this.__cssSwitcher;
    CUI.Events.ignore({
      instance: this
    });
    return ResultTable.__super__.destroy.call(this);
  };

  ResultTable.prototype.renderResultObject = function(result_object, group) {
    var div, i, len, options, ref, ref1, ref2, value;
    options = {};
    ref = this.view_data.show_options;
    for (i = 0, len = ref.length; i < len; i++) {
      value = ref[i];
      options[value] = true;
    }
    switch (group) {
      case "standard":
        return result_object.renderCardResultTable({
          tags: options.tags
        });
      case "tags":
        div = CUI.dom.div("tags-field");
        return CUI.dom.append(div, result_object.renderTags("text"));
      case "system_object_id":
        return result_object.renderSystemObjectId();
      case "pool":
        return ez5.loca.getBestFrontendValue((ref1 = result_object.pool()) != null ? (ref2 = ref1.pool) != null ? ref2.name : void 0 : void 0);
      case "objecttype":
        return result_object.objecttype();
    }
  };

  ResultTable.prototype.getObjectFormatNeededInternal = function() {
    var format, search_format;
    format = this.getObjectFormatNeeded();
    search_format = this.getSearch().getRequestFormat();
    if (ResultObject.compareFormats(format, search_format) < 0) {
      return search_format;
    }
    return format;
  };

  ResultTable.prototype.getObjectFormatNeeded = function() {
    return "long";
  };

  ResultTable.prototype.failResult = function() {
    if (this.__waitBlock) {
      this.__waitBlock.destroy();
      this.__waitBlock = null;
    }
  };

  ResultTable.prototype.showResult = function(request, data) {
    var all_nodes, dfr, hasActiveFilter, i, j, len, len1, n, nodes, object, ref, ref1, show_result, txt;
    if ((ref = this.__navi) != null) {
      ref.update(data);
    }
    this.__show_hierarchy = this.view_data.show_hierarchy;
    if (this.__tree) {
      this.__tree.root.removeFromDOM(false);
    }
    if (!request.page_request) {
      txt = "ResultTable.showResult[colsAndHeaders]";
      this.__info = this.__getColsAndHeaders(data);
      if (this.__tree) {
        this.__tree.destroy();
      }
      this.__tree = null;
    }
    if (data.count === 0) {
      if (this.__waitBlock) {
        this.__waitBlock.destroy();
        this.__waitBlock = null;
      }
      this.__pane.replace(this.getSearch().getEmptyResultDiv(request), "center");
      return;
    }
    dfr = new CUI.Deferred();
    if (!this.getSearch()) {
      return dfr.reject().promise();
    }
    hasActiveFilter = this.hasSearchInput() || this.hasPoolFilter();
    if (hasActiveFilter) {
      this.__searchObjectsByGlobalObjectId = {};
      ref1 = data.objects;
      for (i = 0, len = ref1.length; i < len; i++) {
        object = ref1[i];
        this.__searchObjectsByGlobalObjectId[object._global_object_id] = object;
      }
    } else {
      delete this.__searchObjectsByGlobalObjectId;
    }
    show_result = (function(_this) {
      return function() {
        var _header, cols, columnWidthPreferenceKey, columnsWidth, fixedCols, idxColumn, j, l, len1, node, ref2, treeOpts, width;
        if (!_this.getSearch()) {
          return dfr.reject().promise();
        }
        if (!_this.__tree) {
          cols = _this.__info.cols.slice(0);
          fixedCols = 0;
          if (cols.length === 1) {
            cols[0] = "maximize";
          }
          columnWidthPreferenceKey = _this.getSearch().getSearchObjecttypes().map(function(objecttype) {
            return objecttype.name();
          }).join("-");
          treeOpts = CUI.util.copyObject(_this._tree_opts, true) || {};
          CUI.util.mergeMap(treeOpts, {
            focusable: true,
            maximize: true,
            absolute: false,
            no_hierarchy: _this.__info.no_hierarchy,
            fixedRows: _this.__info.headers.length,
            fixedCols: fixedCols,
            cols: cols,
            colClasses: _this.__info.colClasses,
            children: nodes,
            selectableRows: true,
            onColumnResize: function(column, width) {
              var columnsWidth, idxColumn;
              idxColumn = column.getColumnIdx();
              columnsWidth = ez5.session.getPref(columnWidthPreferenceKey);
              if (!columnsWidth) {
                columnsWidth = {};
              }
              columnsWidth[idxColumn] = width;
              return ez5.session.savePref(columnWidthPreferenceKey, columnsWidth);
            },
            onSelect: function(ev, info) {
              var ref2;
              if (ev != null) {
                ev.preventDefault();
              }
              if (!info.node) {
                return;
              }
              CUI.Events.trigger({
                type: "click",
                node: (ref2 = info.node.getDOMNodes()) != null ? ref2[0] : void 0
              });
            }
          });
          treeOpts["class"] = treeOpts["class"] ? treeOpts["class"] + " ez5-result-table" : "ez5-result-table";
          _this.__tree = new CUI.ListViewTree(treeOpts);
          _this.__pane.replace(_this.__tree.render(), "center");
          columnsWidth = ez5.session.getPref(columnWidthPreferenceKey);
          if (columnsWidth && cols.length > 1) {
            for (idxColumn in columnsWidth) {
              width = columnsWidth[idxColumn];
              _this.__tree.setColWidth(idxColumn, width);
            }
          }
          _this.__tree.root.open().done(dfr.resolve).fail(dfr.reject);
          ref2 = _this.__info.headers;
          for (j = ref2.length - 1; j >= 0; j += -1) {
            _header = ref2[j];
            _this.__tree.prependRow(_header);
          }
        } else {
          for (l = 0, len1 = nodes.length; l < len1; l++) {
            node = nodes[l];
            node.setFather(_this.__tree.root);
          }
          _this.__tree.root.children = nodes;
          _this.__tree.root.open().done(dfr.resolve).fail(dfr.reject);
        }
        if (_this.__waitBlock) {
          _this.__waitBlock.destroy();
          _this.__waitBlock = null;
        }
        return dfr.done(function() {
          _this.initSelectable(".result-table-node:not(.ez5-deleted)", _this.__tree.getScrollingContainer());
          return _this.initSelectableCollection();
        });
      };
    })(this);
    nodes = this.getNodesFromData(data);
    all_nodes = [];
    for (j = 0, len1 = nodes.length; j < len1; j++) {
      n = nodes[j];
      all_nodes.push.apply(all_nodes, n.find((function(_this) {
        return function(n) {
          var top_level_data;
          if (!(n instanceof ResultTableNode)) {
            return;
          }
          top_level_data = n.getTopLevelData();
          if (_this.getExcludeFields()) {
            top_level_data._format_incomplete = true;
          }
          return ResultObject.compareFormats(top_level_data._format, _this.getObjectFormatNeededInternal()) < 0;
        };
      })(this)));
    }
    if (all_nodes.length > 0) {
      this.__updateDataInNodes(all_nodes).done(show_result).fail(dfr.reject);
    } else {
      show_result();
    }
    return dfr.promise();
  };

  ResultTable.prototype.__updateDataInNodes = function(nodes) {
    var gid, global_object_ids, i, len, n, nodes_by_global_object_id, req_data;
    nodes_by_global_object_id = {};
    global_object_ids = [];
    for (i = 0, len = nodes.length; i < len; i++) {
      n = nodes[i];
      gid = n.getTopLevelData()._global_object_id;
      nodes_by_global_object_id[gid] = n;
      global_object_ids.push(gid);
    }
    req_data = {
      offset: 0,
      limit: global_object_ids.length,
      format: this.getObjectFormatNeededInternal(),
      exclude_fields: this.getExcludeFields(),
      search: [
        {
          type: "in",
          bool: "must",
          fields: ["_global_object_id"],
          "in": global_object_ids
        }
      ]
    };
    return ez5.api.search({
      data: {
        debug: "ResultTable.__updateDataInNodes"
      },
      json_data: req_data
    }).done((function(_this) {
      return function(data) {
        var j, len1, obj, ref;
        ref = data.objects;
        for (j = 0, len1 = ref.length; j < len1; j++) {
          obj = ref[j];
          if (_this.getExcludeFields()) {
            obj._format_incomplete = true;
          }
          nodes_by_global_object_id[obj._global_object_id].setData(obj);
        }
      };
    })(this));
  };

  ResultTable.prototype.getMode = function() {
    return "table";
  };

  ResultTable.prototype.__getColsAndHeaders = function(data, standard_only) {
    var _col, _header, addOptionsColumn, add_extra_header_colspan, add_field, all_colspan, c_common, c_unique, c_unique_per_mask, cf, cfs, colClasses, cols, commonFieldsByLocaName, extra_header_colspan, extra_header_colspan_for_ot, extra_headers, field_per_column, fn, has_show_options, header, header2_columns, headers, hierarchy, i, j, l, len, len1, len2, len3, len4, len5, len6, len7, m, mask, ot, ot_idx, otm, p, q, r, ref, ref1, ref2, ref3, ref4, ref5, s, term, top_header, top_header2, top_header2_use, uf, value;
    if (standard_only == null) {
      standard_only = false;
    }
    hierarchy = false;
    top_header = new CUI.ListViewHeaderRow();
    top_header2 = new CUI.ListViewHeaderRow();
    top_header2_use = false;
    extra_headers = [];
    header = new CUI.ListViewHeaderRow();
    cols = [];
    colClasses = [];
    all_colspan = 0;
    field_per_column = [];
    headers = [];
    has_show_options = this.view_data.show_options.length > 0;
    addOptionsColumn = (function(_this) {
      return function(optionsKey) {
        header.addColumn(new CUI.ListViewHeaderColumn({
          label: {
            text: $$("result.table.column." + optionsKey)
          }
        }));
        field_per_column.push({
          group: optionsKey
        });
        cols.push("auto");
        colClasses.push("ez5-result-table-" + optionsKey);
        return all_colspan++;
      };
    })(this);
    if (has_show_options && !standard_only) {
      ref = this.view_data.show_options;
      for (i = 0, len = ref.length; i < len; i++) {
        value = ref[i];
        addOptionsColumn(value);
      }
    }
    if (standard_only) {
      otm = null;
      addOptionsColumn("standard");
    } else {
      otm = new ObjecttypeManager();
    }
    if (data.aggregations._result_table_masks) {
      ref1 = data.aggregations._result_table_masks.terms;
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        term = ref1[j];
        mask = Mask.getMaskByMaskName(term.term);
        if (otm != null) {
          otm.addMask(mask);
        }
        if (mask.isHierarchy() || mask.isPolyhierarchy()) {
          hierarchy = true;
        }
      }
    }
    if (standard_only) {
      return {
        cols: cols,
        colClasses: colClasses,
        no_hierarchy: !hierarchy,
        headers: headers,
        field_per_column: field_per_column
      };
    }
    otm.initCommonFields(this.getMode(), false);
    commonFieldsByLocaName = otm.getCommonFieldsByLocaName(function(ot, field) {
      return !(field instanceof NestedTable);
    });
    for (fn in commonFieldsByLocaName) {
      cfs = commonFieldsByLocaName[fn];
      header.addColumn(new CUI.ListViewHeaderColumn({
        label: {
          text: fn
        }
      }));
      field_per_column[cols.length] = {
        group: "COMMONS",
        fields: cfs
      };
      cols.push("auto");
      colClasses.push(cfs[0].getClass());
      all_colspan++;
    }
    if (all_colspan > 0) {
      headers.push(top_header);
      top_header.addColumn(new CUI.ListViewColumn({
        text: $$("result.table.header.all_objecttypes"),
        colspan: all_colspan
      }));
      top_header2.addColumn(new CUI.ListViewColumnEmpty({
        colspan: all_colspan
      }));
    }
    extra_header_colspan = [all_colspan];
    extra_header_colspan_for_ot = 0;
    add_extra_header_colspan = (function(_this) {
      return function() {
        var extra_header, l, len2;
        if (extra_header_colspan_for_ot > 0) {
          for (l = 0, len2 = extra_headers.length; l < len2; l++) {
            extra_header = extra_headers[l];
            extra_header.addColumn(new CUI.ListViewColumnEmpty({
              colspan: extra_header_colspan_for_ot
            }));
          }
        }
        return extra_header_colspan_for_ot = 0;
      };
    })(this);
    ref2 = otm.objecttypes;
    for (ot_idx = l = 0, len2 = ref2.length; l < len2; ot_idx = ++l) {
      ot = ref2[ot_idx];
      add_field = (function(_this) {
        return function(field) {
          header.addColumn(new CUI.ListViewHeaderColumn({
            label: {
              text: field.nameLocalized()
            }
          }));
          extra_header_colspan_for_ot++;
          field_per_column[cols.length] = {
            field: field
          };
          cols.push("auto");
          colClasses.push(field.getClass());
          return 1;
        };
      })(this);
      c_common = 0;
      c_unique = 0;
      ref3 = ot.commonFields;
      for (m = 0, len3 = ref3.length; m < len3; m++) {
        cf = ref3[m];
        if (commonFieldsByLocaName[cf.nameLocalized()]) {
          continue;
        }
        c_common += add_field(cf);
      }
      header2_columns = [];
      if (c_common > 0) {
        header2_columns.push(new CUI.ListViewColumn({
          text: $$("result.table.common_fields"),
          colspan: c_common
        }));
      }
      add_extra_header_colspan();
      ref4 = ot.masks;
      for (p = 0, len4 = ref4.length; p < len4; p++) {
        mask = ref4[p];
        if (mask.uniqueFields.length > 0) {
          c_unique_per_mask = 0;
          ref5 = mask.uniqueFields;
          for (q = 0, len5 = ref5.length; q < len5; q++) {
            uf = ref5[q];
            c_unique_per_mask += add_field(uf);
          }
          if (c_unique_per_mask > 0) {
            header2_columns.push(new CUI.ListViewColumn({
              text: mask.nameLocalized(),
              colspan: c_unique_per_mask
            }));
            c_unique += c_unique_per_mask;
          }
        }
      }
      if (c_common + c_unique === 0) {
        continue;
      }
      extra_header_colspan[ot_idx + 1] = c_common + c_unique;
      add_extra_header_colspan();
      top_header.addColumn(new CUI.ListViewColumn({
        text: ot.nameLocalized(),
        colspan: c_common + c_unique
      }));
      if (header2_columns.length > 1) {
        for (r = 0, len6 = header2_columns.length; r < len6; r++) {
          _col = header2_columns[r];
          top_header2.addColumn(_col);
          top_header2_use = true;
        }
      } else {
        top_header2.addColumn(new CUI.ListViewColumnEmpty({
          colspan: c_common + c_unique
        }));
      }
    }
    if (top_header2_use) {
      headers.push(top_header2);
    }
    for (s = 0, len7 = extra_headers.length; s < len7; s++) {
      _header = extra_headers[s];
      headers.push(_header);
    }
    headers.push(header);
    if (cols.length === 0) {
      addOptionsColumn("standard");
    }
    return {
      cols: cols,
      colClasses: colClasses,
      headers: headers,
      has_show_options: has_show_options,
      no_hierarchy: !hierarchy,
      field_per_column: field_per_column
    };
  };

  return ResultTable;

})(ResultManagerResult);
// 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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  ResultTableV2.prototype.__defaultPageSize = 10;

  ResultTableV2.prototype.__pageSizes = [1, 10, 25, 50, 100];

  ResultTableV2.prototype.getName = function() {
    return "result-table-v2";
  };

  ResultTableV2.prototype.initOpts = function() {
    ResultTableV2.__super__.initOpts.call(this);
    return this.addOpts({
      filter_tree: {
        "default": false,
        check: Boolean
      }
    });
  };

  ResultTableV2.prototype.init = function() {
    var base, welcome_message;
    ResultTableV2.__super__.init.call(this);
    this.__navigation = new ResultNavigationToolbar({
      ui: "result.dynamic_navigation_toolbar",
      "class": "ez5-result-dynamic-navigation-toolbar",
      search: this.getSearch(),
      navigation_buttons_left: this._navigation_buttons_left,
      getPageSize: (function(_this) {
        return function() {
          return _this.getPageSize();
        };
      })(this)
    });
    this.__pane = new CUI.Pane({
      "class": "ez5-result-table-pane-v2",
      absolute: this._pane_absolute,
      bottom: {
        content: this.__navigation
      }
    });
    this.__cssSwitcher = new CSSSwitcher({
      element: this.__pane.DOM,
      variants: this.getCSSVariants(),
      data: this.__viewData
    });
    welcome_message = typeof (base = this.getSearch()).getWelcomeMessagesDiv === "function" ? base.getWelcomeMessagesDiv(true) : void 0;
    CUI.dom.append(this.__pane.center(), welcome_message);
    CUI.dom.replace(this.getResultContainer(), this.__pane);
  };

  ResultTableV2.prototype.saveViewDone = function() {
    var current, page;
    if (!this.__listViewTree) {
      return CUI.resolvedPromise();
    }
    current = this.__navigation.getCurrent();
    if (!CUI.util.isEqual(this.__currentViewData.show_options, this.__viewData.show_options)) {
      this.__reloadTable();
    } else if (this.__viewData.page_size !== current.pageSize) {
      page = Math.floor((current.offset || 0) / this.getPageSize());
      this.__navigation.loadPage(page);
    }
    return CUI.resolvedPromise();
  };

  ResultTableV2.prototype.updateView = function(form) {
    this.__cssSwitcher.setCSS();
    return ResultTableV2.__super__.updateView.call(this, form);
  };

  ResultTableV2.prototype.initView = function() {
    this.__currentViewData = CUI.util.copyObject(this.__viewData, true);
    return this;
  };

  ResultTableV2.prototype.getViewDataDefault = function() {
    return {
      variant_result: 0
    };
  };

  ResultTableV2.prototype.getCSSVariants = function() {
    return [
      {
        type: "choice",
        name: "result",
        label: "main.search.view.result",
        classes: [
          {
            label: "main.search.view.result.mini",
            "class": "result-standard-mini"
          }, {
            label: "main.search.view.result.midi",
            "class": "result-standard-midi"
          }, {
            label: "main.search.view.result.maxi",
            "class": "result-standard-maxi"
          }, {
            label: "main.search.view.result.huge",
            "class": "result-standard-huge"
          }
        ]
      }, {
        type: "switch",
        name: "show_copy_columns",
        label: "result.table.view.show_copy_columns",
        classes: [
          {
            "class": "ez5-result-table-hide-copy-columns"
          }, {
            "class": "ez5-result-table-show-copy-columns"
          }
        ]
      }, {
        type: "switch",
        name: "opacity_copy_columns",
        label: "result.table.view.opacity_copy_columns",
        classes: [
          {
            "class": ""
          }, {
            "class": "ez5-result-table-opacity-copy-columns"
          }
        ]
      }
    ];
  };

  ResultTableV2.prototype.setSearch = function(_search) {
    this._search = _search;
    ResultTableV2.__super__.setSearch.call(this, this._search);
    this.__poll_listener = EventPoller.listen({
      filter: {
        type: ["OBJECT_DELETE", "OBJECT_INDEX"]
      },
      instance: this,
      call: (function(_this) {
        return function(events) {
          var container, deletedRow, element, event, globalObjectId, globalObjectIds, j, k, len, len1, ref, resultTableRow, rowsToUpdate;
          container = _this.getResultContainer();
          globalObjectIds = {};
          rowsToUpdate = [];
          for (j = 0, len = events.length; j < len; j++) {
            event = events[j];
            globalObjectId = event.global_object_id;
            if (!globalObjectId || globalObjectIds[globalObjectId]) {
              continue;
            }
            globalObjectIds[globalObjectId] = true;
            ref = CUI.dom.matchSelector(container, "[global-object-id='" + globalObjectId + "']");
            for (k = 0, len1 = ref.length; k < len1; k++) {
              element = ref[k];
              resultTableRow = CUI.dom.data(element, "listViewRow");
              if (event.type === "OBJECT_DELETE") {
                deletedRow = new ez5.ResultTableNodeDeletedV2();
                _this.__listViewTree.replaceRow(resultTableRow.getRowIdx(), deletedRow);
              } else {
                rowsToUpdate.push(resultTableRow);
              }
            }
          }
          if (rowsToUpdate.length > 0) {
            _this.__updateRowsData(rowsToUpdate);
          }
        };
      })(this)
    });
    return this;
  };

  ResultTableV2.prototype.unsetSearch = function() {
    ResultTableV2.__super__.unsetSearch.call(this);
    if (this.__poll_listener) {
      CUI.Events.ignore(this.__poll_listener);
      this.__poll_listener = null;
    }
    return this;
  };

  ResultTableV2.prototype.__updateRowsData = function(rows) {
    var globalObjectId, globalObjectIds, j, len, row, rowsByGlobalObjectId;
    rowsByGlobalObjectId = {};
    for (j = 0, len = rows.length; j < len; j++) {
      row = rows[j];
      globalObjectId = row.getGlobalObjectId();
      if (!rowsByGlobalObjectId[globalObjectId]) {
        rowsByGlobalObjectId[globalObjectId] = [];
      }
      rowsByGlobalObjectId[globalObjectId].push(row);
    }
    globalObjectIds = Object.keys(rowsByGlobalObjectId);
    ez5.api.search({
      json_data: {
        offset: 0,
        limit: globalObjectIds.length,
        format: this.getSearchFormat(),
        search: [
          {
            type: "in",
            bool: "must",
            fields: ["_global_object_id"],
            "in": globalObjectIds
          }
        ]
      }
    }).done((function(_this) {
      return function(data) {
        var k, len1, ref, topLevelData;
        ref = data.objects;
        for (k = 0, len1 = ref.length; k < len1; k++) {
          topLevelData = ref[k];
          rows = rowsByGlobalObjectId[topLevelData._global_object_id];
          _this.__updateObject(topLevelData, rows);
        }
      };
    })(this));
  };

  ResultTableV2.prototype.__updateObject = function(topLevelData, rows) {
    var firstRow, firstRowIndex, globalObjectId, index, isOpen, j, k, len, previousNode, previousRow, ref, ref1, ref2, ref3, ref4, resultTableNode, row, updatedRows;
    firstRowIndex = rows[0].getRowIdx();
    firstRow = (ref = this.__listViewTree.getRow(firstRowIndex)) != null ? ref[0] : void 0;
    if (!firstRow) {
      return;
    }
    updatedRows = this.__getRowsForObject(topLevelData);
    for (j = 0, len = updatedRows.length; j < len; j++) {
      row = updatedRows[j];
      globalObjectId = row.shift();
      resultTableNode = new ez5.ResultTableNodeV2({
        object: topLevelData,
        resultTable: this,
        row: row,
        open: false
      });
      previousRow = (ref1 = this.__listViewTree.getRow(firstRowIndex)) != null ? ref1[0] : void 0;
      if (previousRow) {
        previousNode = CUI.dom.data(previousRow, "listViewRow");
        isOpen = previousNode.isOpen();
        if ((ref2 = previousNode.father) != null ? ref2.isLoading() : void 0) {
          firstRowIndex++;
          continue;
        }
        previousNode.prependSibling(resultTableNode).done((function(_this) {
          return function() {
            var ref3, savedChildren;
            if (isOpen && ((ref3 = previousNode.children) != null ? ref3.length : void 0) > 0) {
              savedChildren = previousNode.children;
            }
            return previousNode.remove(false, false).always(function() {
              if (savedChildren && savedChildren.length > 0) {
                resultTableNode.children = savedChildren;
                return resultTableNode.open();
              }
            });
          };
        })(this));
        if (previousNode.getGlobalObjectId() !== globalObjectId) {
          resultTableNode.appendSibling(previousNode);
        }
      } else {
        this.__listViewTree.addNode(resultTableNode);
      }
      firstRowIndex++;
    }
    if (rows.length > updatedRows.length) {
      for (index = k = ref3 = updatedRows.length, ref4 = rows.length; k < ref4; index = k += 1) {
        this.__listViewTree.removeRow(rows[index].getRowIdx());
      }
    }
  };

  ResultTableV2.prototype.getViewFields = function() {
    var fields, o;
    fields = this.__cssSwitcher.getFields();
    fields.push({
      type: CUI.Options,
      sortable: true,
      name: "show_options",
      form: {
        label: $$("result.table.view.show-options")
      },
      options: [
        {
          value: "_standard",
          text: $$("result.table.view.show-options.standard")
        }, {
          value: "_tags",
          text: $$("result.table.view.show-options.tags")
        }, {
          value: '_system_object_id',
          text: $$("result.table.view.show-options.system_object_id")
        }, {
          value: '_pool',
          text: $$("result.table.view.show-options.pool")
        }, {
          value: '_objecttype',
          text: $$("result.table.view.show-options.objecttype")
        }
      ],
      onRender: (function(_this) {
        return function(el) {
          if (el.getForm()) {
            return CUI.Events.trigger({
              node: el.getForm(),
              type: "content-resize"
            });
          }
        };
      })(this)
    });
    fields.push({
      type: CUI.Select,
      form: {
        label: $$("result.table.select.page_size")
      },
      name: "page_size",
      options: (function() {
        var j, len, ref, results;
        ref = this.__pageSizes;
        results = [];
        for (j = 0, len = ref.length; j < len; j++) {
          o = ref[j];
          results.push({
            text: o + "",
            value: o
          });
        }
        return results;
      }).call(this)
    });
    return fields;
  };

  ResultTableV2.prototype.filterTopLevel = function() {
    return true;
  };

  ResultTableV2.prototype.allowExpandHierarchy = function(request) {
    return false;
  };

  ResultTableV2.prototype.setData = function(__viewData) {
    var ref;
    this.__viewData = __viewData;
    if (!this.__viewData.page_size) {
      this.__viewData.page_size = this.__defaultPageSize;
    }
    if (ref = this.__viewData.page_size, indexOf.call(this.__pageSizes, ref) < 0) {
      this.__viewData.page_size = this.__defaultPageSize;
    }
    if (!this.__viewData.show_options) {
      this.__viewData.show_options = [];
    }
    return this;
  };

  ResultTableV2.prototype.addToRequest = function(request) {
    request.limit = this.getPageSize();
    request.format = this.getSearchFormat();
    request.exclude_fields = this.getExcludeFields();
    request.generate_rights = ez5.version("6");
    if (request.offset % request.limit !== 0) {
      request.offset = Math.floor(request.offset / request.limit) * request.limit;
    }
    if (!request.aggregations) {
      request.aggregations = {};
    }
    request.aggregations._result_table_masks = {
      type: "term",
      limit: 100000,
      field: "_mask"
    };
    if (request.execute && !this.__waitBlock) {
      this.__waitBlock = new CUI.WaitBlock({
        element: this.getResultContainer()
      }).show();
    }
    return this;
  };

  ResultTableV2.prototype.getSearchFormat = function() {
    return "long";
  };

  ResultTableV2.prototype.__reloadTable = function() {
    delete this.__fieldMap;
    delete this.__subnestedFieldMap;
    delete this.__header;
    this.getSearch().execute();
  };

  ResultTableV2.prototype.failResult = function() {
    if (this.__waitBlock) {
      this.__waitBlock.destroy();
      this.__waitBlock = null;
    }
  };

  ResultTableV2.prototype.showResult = function(request, data) {
    var _column, cols, column, columnWidthPreferenceKey, deferred, displayName, headerRow, j, label, len, mask, name, noFieldsAvailable, objecttypeManager, objecttypes, ref, ref1, ref2, term;
    if (this.__waitBlock) {
      this.__waitBlock.destroy();
      this.__waitBlock = null;
    }
    if ((ref = this.__navigation) != null) {
      ref.update(data);
    }
    if (data.count === 0) {
      this.__pane.replace(this.getSearch().getEmptyResultDiv(request), "center");
      return CUI.resolvedPromise();
    }
    objecttypeManager = new ObjecttypeManager();
    if (data.aggregations._result_table_masks) {
      ref1 = data.aggregations._result_table_masks.terms;
      for (j = 0, len = ref1.length; j < len; j++) {
        term = ref1[j];
        mask = Mask.getMaskByMaskName(term.term);
        objecttypeManager.addMask(mask);
      }
    }
    objecttypeManager.initCommonFields("all");
    objecttypes = objecttypeManager.getObjecttypes().map(function(objecttype) {
      return objecttype.name();
    });
    this.__topLevelKeys = this.__viewData.show_options;
    this.__fieldMap = this.__getFieldMap(objecttypeManager);
    this.__header = this.__getHeader(objecttypeManager);
    if (CUI.util.isEmptyObject(this.__header)) {
      noFieldsAvailable = new CUI.Label({
        text: $$("result.table.view.no-fields-available"),
        "class": "cui-empty-label search-empty-result",
        centered: true,
        multiline: true
      });
      this.__pane.replace(noFieldsAvailable, "center");
      return CUI.resolvedPromise();
    }
    headerRow = new CUI.ListViewHeaderRow({
      selectable: false
    });
    cols = [];
    ref2 = this.__header;
    for (name in ref2) {
      column = ref2[name];
      cols[column.index - 1] = "auto";
      displayName = column.display_name;
      if (indexOf.call(this.__topLevelKeys, name) >= 0) {
        displayName = $$("result.table.view.show-options." + (name.substring(1)));
      }
      label = new CUI.Label({
        text: displayName
      });
      _column = new CUI.ListViewHeaderColumn({
        label: label
      });
      new CUI.Tooltip({
        element: label,
        text: name
      });
      headerRow.addColumn(_column);
    }
    columnWidthPreferenceKey = objecttypes.join("-");
    this.__listViewTree = new CUI.ListViewTree({
      colResize: true,
      rowMove: false,
      fixedRows: 1,
      cols: cols,
      focusable: true,
      onColumnResize: (function(_this) {
        return function(column, width) {
          var columnsWidth, idxColumn;
          idxColumn = column.getColumnIdx();
          columnsWidth = ez5.session.getPref(columnWidthPreferenceKey);
          if (!columnsWidth) {
            columnsWidth = {};
          }
          columnsWidth[idxColumn] = width;
          return ez5.session.savePref(columnWidthPreferenceKey, columnsWidth);
        };
      })(this)
    });
    this.__listViewTree.render();
    this.__listViewTree.prependRow(headerRow);
    deferred = new CUI.Deferred();
    deferred.done((function(_this) {
      return function() {
        var columnsWidth, hasActiveFilter, hasPoolFilter, hasSearchInput, i, idxColumn, k, l, len1, n, nodes, object, ref3, ref4, ref5, width;
        if (_this.isDestroyed()) {
          return;
        }
        hasSearchInput = _this.hasSearchInput(null, [(ref3 = _this.getSearch()) != null ? typeof ref3.getSearchTypeSelector === "function" ? ref3.getSearchTypeSelector() : void 0 : void 0]);
        hasPoolFilter = _this.hasPoolFilter();
        hasActiveFilter = hasSearchInput || hasPoolFilter;
        if (hasActiveFilter) {
          _this.__searchObjectsByGlobalObjectId = {};
          ref4 = data.objects;
          for (k = 0, len1 = ref4.length; k < len1; k++) {
            object = ref4[k];
            _this.__searchObjectsByGlobalObjectId[object._global_object_id] = object;
          }
        } else {
          delete _this.__searchObjectsByGlobalObjectId;
        }
        nodes = _this.getNodesFromData(data, false, hasSearchInput);
        if (_this.__notFoundObjectsCount > 0) {
          for (i = l = 0, ref5 = _this.__notFoundObjectsCount; 0 <= ref5 ? l < ref5 : l > ref5; i = 0 <= ref5 ? ++l : --l) {
            n = new ResultTableNodeNotAllowed();
            n.father = _this.__listViewTree.root;
            nodes.push(n);
          }
        }
        _this.__listViewTree.root.children = nodes;
        _this.__listViewTree.root.open();
        _this.__pane.replace(_this.__listViewTree, "center");
        columnsWidth = ez5.session.getPref(columnWidthPreferenceKey);
        if (columnsWidth) {
          for (idxColumn in columnsWidth) {
            width = columnsWidth[idxColumn];
            _this.__listViewTree.setColWidth(idxColumn, width);
          }
        }
        if (nodes.length === 1) {
          nodes[0].open();
        }
        _this.initSelectable(".result-table-node-v2:not(.ez5-deleted)", _this.__listViewTree.getScrollingContainer());
        _this.initSelectableCollection();
      };
    })(this));
    this.__notFoundObjectsCount = data.objects.length;
    data.objects = data.objects.filter(function(object) {
      return (object != null) && (object._global_object_id != null);
    });
    this.__notFoundObjectsCount -= data.objects.length;
    console.warn("ResultTableV2: Not found objects count: " + this.__notFoundObjectsCount);
    this.__updateDataForStandardObjects(data).done(deferred.resolve).fail(deferred.reject);
    return deferred.promise();
  };

  ResultTableV2.prototype.__updateDataForStandardObjects = function(data) {
    var _object, _path, availableDataByGlobalObjectId, globalObjectId, globalObjectIds, j, k, l, len, len1, len2, len3, m, object, objectsByGlobalObjectId, path, ref, ref1, ref2, ref3;
    objectsByGlobalObjectId = {};
    availableDataByGlobalObjectId = {};
    ref = data.objects;
    for (j = 0, len = ref.length; j < len; j++) {
      object = ref[j];
      availableDataByGlobalObjectId[object._global_object_id] = object;
    }
    ref1 = data.objects;
    for (k = 0, len1 = ref1.length; k < len1; k++) {
      object = ref1[k];
      path = object._path;
      if (!path && CUI.util.isArray(object._paths)) {
        path = [];
        ref2 = object._paths;
        for (l = 0, len2 = ref2.length; l < len2; l++) {
          _path = ref2[l];
          path = path.concat(_path);
        }
      }
      ref3 = path || [];
      for (m = 0, len3 = ref3.length; m < len3; m++) {
        object = ref3[m];
        if (object._format === this.getSearchFormat()) {
          continue;
        }
        globalObjectId = object._global_object_id;
        if (availableDataByGlobalObjectId[globalObjectId]) {
          _object = availableDataByGlobalObjectId[globalObjectId];
          object[object._objecttype] = _object[_object._objecttype];
          continue;
        }
        if (!objectsByGlobalObjectId[globalObjectId]) {
          objectsByGlobalObjectId[globalObjectId] = [];
        }
        objectsByGlobalObjectId[globalObjectId].push(object);
      }
    }
    globalObjectIds = Object.keys(objectsByGlobalObjectId);
    if (globalObjectIds.length === 0) {
      return CUI.resolvedPromise();
    }
    return ez5.api.search({
      json_data: {
        offset: 0,
        limit: globalObjectIds.length,
        format: this.getSearchFormat(),
        exclude_fields: this.getExcludeFields(),
        search: [
          {
            type: "in",
            bool: "must",
            fields: ["_global_object_id"],
            "in": globalObjectIds
          }
        ]
      }
    }).done((function(_this) {
      return function(data) {
        var len4, len5, p, q, ref4, ref5;
        ref4 = data.objects;
        for (p = 0, len4 = ref4.length; p < len4; p++) {
          object = ref4[p];
          ref5 = objectsByGlobalObjectId[object._global_object_id];
          for (q = 0, len5 = ref5.length; q < len5; q++) {
            _object = ref5[q];
            _object[_object._objecttype] = object[_object._objecttype];
          }
        }
      };
    })(this));
  };

  ResultTableV2.prototype.getExcludeFields = function() {
    var error, excludeSet, field, j, k, len, len1, manager, maskNames, name, objectTypeNames, ref, ref1, result, search, visibleSet;
    try {
      search = this.getSearch();
      objectTypeNames = new Set(search.getSearchObjecttypes().map(function(ot) {
        return ot.name();
      }));
      maskNames = new Set(search.getAvailableMaskNames() || []);
      manager = new ObjecttypeManager();
      manager.addObjecttypes(function(table, mask) {
        return objectTypeNames.has(table.name()) && maskNames.has(mask.name());
      });
      excludeSet = new Set();
      visibleSet = new Set();
      ref = manager.getAllFieldsFromAllMasks("all");
      for (j = 0, len = ref.length; j < len; j++) {
        field = ref[j];
        name = field.fullName();
        if (field.isSystemField() || field.isTopLevelField()) {
          continue;
        }
        if (field.isVisible("table")) {
          visibleSet.add(name);
        } else {
          excludeSet.add(name);
        }
      }
      ref1 = visibleSet.values().toArray();
      for (k = 0, len1 = ref1.length; k < len1; k++) {
        name = ref1[k];
        excludeSet["delete"](name);
      }
      result = Array.from(excludeSet);
      if (ez5.session.isDebug()) {
        console.log("Excluded fields for Table View Search Request:", result);
      }
      if (result.length) {
        return result;
      } else {
        return void 0;
      }
    } catch (error1) {
      error = error1;
      console.log("Unable to determine exclude fields");
      return void 0;
    }
  };

  ResultTableV2.prototype.__initExcludeFields = function() {
    this.__excludeFields = [];
  };

  ResultTableV2.prototype.__getFieldMap = function(objecttypeManager) {
    var _objecttype, addSubnesteds, fatherField, field, fieldKey, fieldMap, j, k, len, len1, ref, ref1, ref2, tableName;
    fieldMap = {};
    this.__subnestedFieldMap = {};
    addSubnesteds = (function(_this) {
      return function(f) {
        if (f instanceof NestedTable) {
          _this.__subnestedFieldMap[f.name()] = true;
        }
        if (f.insideNested()) {
          addSubnesteds(f.getFatherField());
        }
      };
    })(this);
    ref = objecttypeManager.getObjecttypes();
    for (j = 0, len = ref.length; j < len; j++) {
      _objecttype = ref[j];
      ref1 = _objecttype.getAllFields("all");
      for (k = 0, len1 = ref1.length; k < len1; k++) {
        field = ref1[k];
        if (field instanceof NestedTable) {
          continue;
        }
        if (!this.__isFieldVisible(field)) {
          continue;
        }
        if (ref2 = field.name(), indexOf.call(this.__topLevelKeys, ref2) >= 0) {
          fieldMap[field.table.name() + "-" + field.name()] = field;
          continue;
        }
        if (field.insideNested()) {
          fatherField = field.getFatherField();
          tableName = fatherField.name();
          addSubnesteds(fatherField);
        } else {
          tableName = field.table.name();
        }
        fieldKey = tableName + "-" + (field.name());
        if (fieldMap[fieldKey]) {
          continue;
        }
        fieldMap[fieldKey] = field;
      }
    }
    return fieldMap;
  };

  ResultTableV2.prototype.__isFieldVisible = function(field) {
    if (!field.isVisible("table")) {
      return false;
    }
    if (field.insideNested()) {
      return this.__isFieldVisible(field.getFatherField());
    }
    return true;
  };

  ResultTableV2.prototype.__getHeader = function(objecttypeManager) {
    var field, header, index, j, key, len, ref, ref1, ref2, schema, value;
    header = {};
    index = 1;
    ref = this.__topLevelKeys;
    for (j = 0, len = ref.length; j < len; j++) {
      key = ref[j];
      header[key] = {
        index: index
      };
      index++;
    }
    ref1 = objecttypeManager.getCommonFieldsByLocaName(null, false);
    for (key in ref1) {
      value = ref1[key];
      field = value[0];
      if (!this.__isFieldVisible(field)) {
        continue;
      }
      schema = field.FieldSchema;
      if ((schema != null ? (ref2 = schema._column) != null ? ref2.kind : void 0 : void 0) !== "column") {
        continue;
      }
      header[key] = {
        index: index,
        display_name: field.nameLocalized()
      };
      index++;
    }
    return header;
  };

  ResultTableV2.prototype.__getField = function(tableName, fieldName) {
    return this.__fieldMap[tableName + "-" + fieldName];
  };

  ResultTableV2.prototype.__getFieldValue = function(tableName, fieldName, data) {
    var field, fieldElement, opts, top_level_data;
    top_level_data = data;
    if (data._objecttype && data[data._objecttype]) {
      data = data[data._objecttype];
    }
    field = this.__getField(tableName, fieldName);
    if (!field) {
      return;
    }
    opts = {
      hide_empty_label: true,
      hierarchy_path_reverse: true
    };
    fieldElement = field.renderForTable(data, top_level_data, opts);
    if (!fieldElement) {
      return;
    }
    if (field instanceof LinkedObject || field instanceof LocaTextColumn) {
      return fieldElement.DOM || fieldElement;
    }
    return fieldElement;
  };

  ResultTableV2.prototype.__getRowsForObject = function(topLevelData) {
    var addRows, copyRow, data, initRow, j, key, len, objecttype, ref, rowIndex, rows, table;
    copyRow = function(rowToCopy) {
      var _row, col, index, j, len;
      _row = [];
      for (index = j = 0, len = rowToCopy.length; j < len; index = ++j) {
        col = rowToCopy[index];
        if (!col) {
          continue;
        }
        col = CUI.util.copyObject(col, true);
        if (index > 0) {
          CUI.dom.addClass(col, "ez5-result-table-copy-column");
        }
        _row[index] = col;
      }
      return _row;
    };
    addRows = (function(_this) {
      return function(data, tableName, topLevelData) {
        var field, fieldName, headerField, initRow, j, k, len, maxNestedFieldCount, nameLocalized, nestedIndex, nestedValues, ref, ref1, ref2, results, row, tag, tag_div, tagsHeaderField, value, virtual_tags;
        row = rows[rowIndex];
        nestedValues = {};
        maxNestedFieldCount = 0;
        tagsHeaderField = _this.__header["_tags"];
        if (tagsHeaderField && ez5.version("6") && topLevelData && !_this.__getField(tableName, "_tags") && data._pool) {
          virtual_tags = ((ref = ez5.pools.findPoolById(data._pool.pool._id)) != null ? ref.getVirtualTags(topLevelData) : void 0) || [];
          if (virtual_tags.length > 0) {
            tag_div = CUI.dom.div("tags-field");
            for (j = 0, len = virtual_tags.length; j < len; j++) {
              tag = virtual_tags[j];
              CUI.dom.append(tag_div, tag.getLabel(true, true).DOM);
            }
            row[tagsHeaderField.index] = tag_div;
          }
        }
        for (fieldName in data) {
          value = data[fieldName];
          if (fieldName.indexOf("_nested") >= 0) {
            if (value.length === 0) {
              continue;
            }
            if (!Object.keys(_this.__fieldMap).some(function(key) {
              return key.startsWith(fieldName + "-");
            })) {
              if (!((ref1 = Object.keys(_this.__subnestedFieldMap)) != null ? ref1.some(function(key) {
                return key === fieldName;
              }) : void 0)) {
                continue;
              }
            }
            nestedValues[fieldName] = value;
            if (value.length > maxNestedFieldCount) {
              maxNestedFieldCount = value.length;
            }
            continue;
          }
          field = _this.__getField(tableName, fieldName);
          nameLocalized = field != null ? field.fullNameLocalized() : void 0;
          if (!nameLocalized) {
            continue;
          }
          headerField = _this.__header[nameLocalized];
          if (!headerField) {
            continue;
          }
          row[headerField.index] = _this.__getFieldValue(tableName, fieldName, data);
        }
        initRow = copyRow(row);
        if (maxNestedFieldCount > 0) {
          results = [];
          for (nestedIndex = k = 0, ref2 = maxNestedFieldCount; k < ref2; nestedIndex = k += 1) {
            results.push((function(nestedIndex) {
              var nestedData, nestedTableName, nestedValue;
              if (nestedIndex > 0) {
                rowIndex++;
                rows[rowIndex] = copyRow(initRow);
              }
              for (nestedTableName in nestedValues) {
                nestedValue = nestedValues[nestedTableName];
                nestedData = nestedValue[nestedIndex];
                if (!nestedData) {
                  continue;
                }
                addRows(nestedData, nestedTableName);
              }
            })(nestedIndex));
          }
          return results;
        }
      };
    })(this);
    rows = [];
    initRow = [topLevelData._global_object_id];
    rowIndex = 0;
    objecttype = topLevelData._objecttype;
    ref = this.__topLevelKeys;
    for (j = 0, len = ref.length; j < len; j++) {
      key = ref[j];
      table = ez5.schema.CURRENT._table_by_name[objecttype];
      if (key === "_tags" && !table.has_tags) {
        continue;
      }
      if (key === "_pool" && !table.pool_link) {
        continue;
      }
      initRow[this.__header[key].index] = this.__getFieldValue(objecttype, key, topLevelData);
    }
    data = topLevelData[objecttype];
    rows[rowIndex] = initRow;
    addRows(data, objecttype, topLevelData);
    return rows;
  };

  ResultTableV2.prototype.getNodesFromData = function(data, isChild, openNode) {
    var _, cls, collectRowsForObject, filter_objects, globalObjectId, hasActiveFilter, hasChildrenInSearch, j, k, l, lastGlobalObjectId, len, len1, len2, markResultRow, nodes, object, objectData, objectPerGlobalObjectId, objs, ref, resultTableNodeV2, row, rows, secondaryRow, stopOpening, top_level_node;
    if (isChild == null) {
      isChild = false;
    }
    if (openNode == null) {
      openNode = false;
    }
    markResultRow = false;
    stopOpening = false;
    if (this.isDestroyed()) {
      return [];
    }
    rows = [];
    objectPerGlobalObjectId = {};
    hasChildrenInSearch = (function(_this) {
      return function(objectData) {
        var child, j, len, ref;
        ref = objectData.children || [];
        for (j = 0, len = ref.length; j < len; j++) {
          child = ref[j];
          if (_this.__searchObjectsByGlobalObjectId[child._global_object_id]) {
            return true;
          }
          if (child._has_children) {
            return hasChildrenInSearch(child);
          }
        }
        return false;
      };
    })(this);
    collectRowsForObject = (function(_this) {
      return function(objectData) {
        var globalObjectId;
        globalObjectId = objectData._global_object_id;
        if (openNode && _this.__searchObjectsByGlobalObjectId[globalObjectId]) {
          markResultRow = true;
          stopOpening = true;
        }
        if (objectPerGlobalObjectId[globalObjectId]) {
          return;
        }
        rows = rows.concat(_this.__getRowsForObject(objectData));
        objectPerGlobalObjectId[objectData._global_object_id] = objectData;
      };
    })(this);
    if (isChild) {
      ref = data.objects;
      for (j = 0, len = ref.length; j < len; j++) {
        object = ref[j];
        collectRowsForObject(object);
      }
    } else {
      objs = ez5.buildObjectTree({
        objects: data.objects,
        objectKey: function(object) {
          return object._objecttype;
        },
        newInstanceFunc: (function(_this) {
          return function(object) {
            return object;
          };
        })(this)
      });
      if (this._filter_tree) {
        filter_objects = function(objects) {
          var child, filtered, filteredChildren, k, key, l, len1, len2, newObj, obj, value;
          filtered = [];
          for (k = 0, len1 = objects.length; k < len1; k++) {
            obj = objects[k];
            filteredChildren = obj.children != null ? filter_objects(obj.children) : [];
            if (obj.hasOwnProperty('_build_from_path')) {
              for (l = 0, len2 = filteredChildren.length; l < len2; l++) {
                child = filteredChildren[l];
                filtered.push(child);
              }
            } else {
              newObj = {};
              for (key in obj) {
                value = obj[key];
                newObj[key] = value;
              }
              if (obj.children != null) {
                newObj.children = filteredChildren;
              }
              filtered.push(newObj);
            }
          }
          return filtered;
        };
        objs = filter_objects(objs);
      }
      for (k = 0, len1 = objs.length; k < len1; k++) {
        object = objs[k];
        collectRowsForObject(object);
      }
    }
    lastGlobalObjectId = null;
    nodes = [];
    for (l = 0, len2 = rows.length; l < len2; l++) {
      row = rows[l];
      globalObjectId = row.shift();
      objectData = objectPerGlobalObjectId[globalObjectId];
      if (lastGlobalObjectId !== globalObjectId) {
        lastGlobalObjectId = globalObjectId;
        secondaryRow = false;
      } else {
        secondaryRow = true;
      }
      cls = secondaryRow ? "cui-lv-tr-outer--secondary" : "";
      hasActiveFilter = this.hasSearchInput() || this.hasPoolFilter();
      if (stopOpening && (objectData != null ? objectData.children : void 0) && hasActiveFilter) {
        if (hasChildrenInSearch(objectData)) {
          stopOpening = false;
        }
      } else if (!stopOpening && hasActiveFilter) {
        if (!hasChildrenInSearch(objectData)) {
          stopOpening = true;
        }
      }
      resultTableNodeV2 = new ez5.ResultTableNodeV2({
        object: objectData,
        resultTable: this,
        row: row,
        "class": cls,
        open: !secondaryRow && (openNode && !stopOpening),
        secondary: secondaryRow
      });
      if (objectData.children) {
        resultTableNodeV2.children = this.getNodesFromData({
          objects: objectData.children
        }, true, openNode && !stopOpening);
      }
      nodes.push(resultTableNodeV2);
    }
    for (_ in objectPerGlobalObjectId) {
      object = objectPerGlobalObjectId[_];
      delete object.children;
    }
    if (this._allowTopLevelPlaceholder && !isChild) {
      top_level_node = new ez5.ResultTableNodeV2({
        resultTable: this,
        row: [ParentRootResultObject.renderTableOutput()],
        object: {
          _global_object_id: "0",
          _system_object_id: 0
        },
        "class": cls,
        secondary: false
      });
      if (nodes.length > 0) {
        nodes.unshift(top_level_node);
      }
    }
    return nodes;
  };

  ResultTableV2.prototype.getNavigation = function() {
    return this.__navigation;
  };

  ResultTableV2.prototype.getPageSize = function() {
    return this.__viewData.page_size;
  };

  ResultTableV2.prototype.destroy = function() {
    var ref, ref1;
    delete this.__topLevelKeys;
    delete this.__fieldMap;
    delete this.__header;
    delete this.__subnestedFieldMap;
    if ((ref = this.__navigation) != null) {
      ref.destroy();
    }
    delete this.__navigation;
    if ((ref1 = this.__cssSwitcher) != null) {
      ref1.destroy();
    }
    delete this.__cssSwitcher;
    if (this.__poll_listener) {
      CUI.Events.ignore(this.__poll_listener);
      this.__poll_listener = null;
    }
    return ResultTableV2.__super__.destroy.call(this);
  };

  return ResultTableV2;

})(ResultManagerResult);
// 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.ResultTableNodeV2 = (function(superClass) {
  extend(ResultTableNodeV2, superClass);

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

  ResultTableNodeV2.prototype.initOpts = function() {
    ResultTableNodeV2.__super__.initOpts.call(this);
    return this.addOpts({
      object: {
        mandatory: true,
        check: "PlainObject"
      },
      row: {
        check: Array
      },
      resultTable: {
        check: ez5.ResultTableV2
      },
      secondary: {
        check: Boolean,
        "default": false
      }
    });
  };

  ResultTableNodeV2.prototype.readOpts = function() {
    var ref, ref1, ref2;
    ResultTableNodeV2.__super__.readOpts.call(this);
    this.__class += " ez5-lassoable";
    if (this._resultTable && ((ref = this._resultTable) != null ? (ref1 = ref.__searchObjectsByGlobalObjectId) != null ? ref1[this._object._global_object_id] : void 0 : void 0)) {
      this.__class += " cui-lv-tr-outer--search-result";
    } else if (this._resultTable && this._resultTable.__searchObjectsByGlobalObjectId && !((ref2 = this._resultTable.__searchObjectsByGlobalObjectId) != null ? ref2[this._object._global_object_id] : void 0)) {
      this.__class += " cui-lv-tr-outer--complementary-search-result";
    }
    this.setData(this._object);
    return this;
  };

  ResultTableNodeV2.prototype.render = function() {
    ResultTableNodeV2.__super__.render.call(this);
    if (this.__handleDiv && ez5.loca.has("result.table.open_handle|tooltip")) {
      this.__handleTooltip = new CUI.Tooltip({
        element: this.__handleDiv,
        text: $$("result.table.open_handle|tooltip"),
        on_click: false,
        on_hover: true,
        placement: "n"
      });
    }
    return this;
  };

  ResultTableNodeV2.prototype.renderContent = function() {
    var column, i, index, isCopiedColumn, len, ref;
    isCopiedColumn = false;
    ref = this._row;
    for (index = i = 0, len = ref.length; i < len; index = ++i) {
      column = ref[index];
      if (CUI.dom.hasClass(column, "ez5-result-table-copy-column")) {
        isCopiedColumn = true;
      }
      if (index === 0) {
        continue;
      }
      if (column) {
        column = new CUI.ListViewColumn({
          element: column
        });
      } else {
        column = new CUI.ListViewColumnEmpty();
      }
      this.addColumn(column);
    }
    if (isCopiedColumn) {
      this.__class += " ez5-result-table-copy-row";
    }
    return this._row[0];
  };

  ResultTableNodeV2.prototype.setData = function(data) {
    this.__object = data;
    this.__objecttype = this.__object._objecttype;
    this.__collectionObject = new CollectionObject(this.__object);
  };

  ResultTableNodeV2.prototype.getData = function() {
    return this.__object[this.__objecttype];
  };

  ResultTableNodeV2.prototype.getTopLevelData = function() {
    return this.__object;
  };

  ResultTableNodeV2.prototype.getGlobalObjectId = function() {
    return this.getTopLevelData()._global_object_id;
  };

  ResultTableNodeV2.prototype.addedToListView = function() {
    var nodes, rowDom;
    ResultTableNodeV2.__super__.addedToListView.call(this);
    rowDom = this.getDOMNodes()[0];
    CUI.dom.setAttribute(rowDom, "global-object-id", this.__object._global_object_id);
    CUI.dom.data(rowDom, "object", this.__object);
    if (this._resultTable.getCollectionSelection().objectIdx(this.__collectionObject) > -1) {
      CUI.dom.addClass(rowDom, "cui-selected");
    }
    nodes = this.__getSameObjectDOMNodes(true);
    if (nodes.length > 1 && nodes[0] !== this && nodes[0].isOpen()) {
      this.hide();
    }
  };

  ResultTableNodeV2.prototype.getChildren = function() {
    return this.loadChildren();
  };

  ResultTableNodeV2.prototype.open = function() {
    var i, len, node, ref;
    if (this._secondary) {
      return CUI.resolvedPromise();
    }
    ref = this.__getSameObjectDOMNodes();
    for (i = 0, len = ref.length; i < len; i++) {
      node = ref[i];
      node.hide();
    }
    return ResultTableNodeV2.__super__.open.call(this);
  };

  ResultTableNodeV2.prototype.close = function() {
    var i, len, node, ref;
    ref = this.__getSameObjectDOMNodes();
    for (i = 0, len = ref.length; i < len; i++) {
      node = ref[i];
      node.show();
    }
    return ResultTableNodeV2.__super__.close.call(this).done((function(_this) {
      return function() {
        if (!_this._resultTable._filter_tree) {
          return _this.children = null;
        }
      };
    })(this));
  };

  ResultTableNodeV2.prototype.__getSameObjectDOMNodes = function(includeSelf) {
    if (includeSelf == null) {
      includeSelf = false;
    }
    return this.father.children.filter((function(_this) {
      return function(node) {
        if (node instanceof ResultTableLoadMoreNode || node instanceof ResultTableNodeNotAllowed) {
          return false;
        }
        return (includeSelf || _this !== node) && node.getGlobalObjectId() === _this.getGlobalObjectId();
      };
    })(this));
  };

  ResultTableNodeV2.prototype.hide = function() {
    var ref;
    return CUI.dom.hideElement((ref = this.getDOMNodes()) != null ? ref[0] : void 0);
  };

  ResultTableNodeV2.prototype.show = function() {
    var ref;
    return CUI.dom.showElement((ref = this.getDOMNodes()) != null ? ref[0] : void 0);
  };

  ResultTableNodeV2.prototype.loadChildren = function(offset) {
    var cb, dfr, i, len, ref, req, searchField, sm;
    if (offset == null) {
      offset = 0;
    }
    if (this._resultTable.isDestroyed() || this._resultTable._filter_tree) {
      return CUI.resolvedPromise([]);
    }
    if (ez5.schema.CURRENT._objecttype_by_name[this.__objecttype].polyhierarchical) {
      searchField = this.__objecttype + "._parents." + this.__objecttype + "._id";
    } else {
      searchField = this.__objecttype + "._id_parent";
    }
    req = new Request({
      objecttypes: [this.__objecttype],
      offset: offset,
      generate_rights: false,
      limit: this._resultTable.getPageSize(),
      format: this._resultTable.getSearchFormat(),
      search: [
        {
          type: "in",
          bool: "must",
          fields: [searchField],
          "in": [this.getData()._id]
        }
      ]
    });
    ref = this._resultTable.getSearch().getSearchManagers();
    for (i = 0, len = ref.length; i < len; i++) {
      sm = ref[i];
      if (sm instanceof SortManager) {
        sm.addToRequest(req);
      }
    }
    cb = this._resultTable.getSearch().getOpt("onAddToRequest");
    if (cb) {
      cb(req);
    }
    dfr = new CUI.Deferred();
    ez5.api.search({
      data: {
        debug: "ResultTableNodeV2.loadChildren"
      },
      json_data: req.copy().cleanRequestForSearch()
    }).done((function(_this) {
      return function(data) {
        var children, ref1, ref2;
        if (_this._resultTable.isDestroyed()) {
          return dfr.resolve([]);
        }
        if ((data != null ? (ref1 = data.objects) != null ? ref1.length : void 0 : void 0) === 0 && ((ref2 = _this.__object) != null ? ref2._has_children : void 0)) {
          children = [new ResultTableNodeNotAllowed()];
          dfr.resolve(children);
          return;
        }
        children = _this._resultTable.getNodesFromData(data, true);
        if (data.offset + data.limit < data.count) {
          children.push(new ResultTableLoadMoreNode({
            offset: data.offset,
            limit: data.limit,
            count: data.count
          }));
        }
        return dfr.resolve(children);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  ResultTableNodeV2.prototype.isLeaf = function() {
    if (this._resultTable._filter_tree && (!this.children || this.children.length === 0)) {
      return true;
    }
    return !this.__object._has_children;
  };

  ResultTableNodeV2.prototype.isSelectable = function() {
    return true;
  };

  return ResultTableNodeV2;

})(CUI.ListViewTreeNode);
// 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.ResultTableNodeDeletedV2 = (function(superClass) {
  extend(ResultTableNodeDeletedV2, superClass);

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

  ResultTableNodeDeletedV2.prototype.readOpts = function() {
    var column, label;
    ResultTableNodeDeletedV2.__super__.readOpts.call(this);
    this.__class = "deleted ez5-deleted";
    label = new LocaLabel({
      "class": "ez5-object-deleted",
      loca_key: "ez5.object.deleted"
    });
    column = new CUI.ListViewColumn({
      element: label
    });
    this.addColumn(column);
    return this;
  };

  return ResultTableNodeDeletedV2;

})(CUI.ListViewRow);
// Generated by CoffeeScript 1.12.7
var ResultTableNode,
  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;

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

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

  ResultTableNode.prototype.initOpts = function() {
    ResultTableNode.__super__.initOpts.call(this);
    return this.addOpts({
      field_per_column: {
        mandatory: true,
        check: Array
      },
      object: {
        mandatory: true,
        check: "PlainObject"
      },
      resultTable: {
        mandatory: true,
        check: ResultTable
      },
      cols: {
        mandatory: true,
        check: Array
      },
      offset: {
        check: "Integer"
      },
      path: {
        check: String
      },
      force_no_children: {
        check: Boolean,
        "default": false
      }
    });
  };

  ResultTableNode.prototype.readOpts = function() {
    var ref, ref1, ref2;
    ResultTableNode.__super__.readOpts.call(this);
    this.__field_per_column = this.opts.field_per_column;
    this.__resultObject = new ResultObject();
    this.__offset = this._offset;
    this.__class = this.__class + "ez5-lassoable";
    if (this._resultTable && ((ref = this._resultTable) != null ? (ref1 = ref.__searchObjectsByGlobalObjectId) != null ? ref1[this._object._global_object_id] : void 0 : void 0)) {
      this.__class += " cui-lv-tr-outer--search-result";
    } else if (this._resultTable && this._resultTable.__searchObjectsByGlobalObjectId && !((ref2 = this._resultTable.__searchObjectsByGlobalObjectId) != null ? ref2[this._object._global_object_id] : void 0)) {
      this.__class += " cui-lv-tr-outer--complementary-search-result";
    }
    return this.setData(this._object);
  };

  ResultTableNode.prototype.setData = function(__object) {
    this.__object = __object;
    if (this.__object.hasOwnProperty("__offset")) {
      this.__offset = this.__object.__offset;
    }
    this.__objecttype = this.__object._objecttype;
    if (this.__object._global_object_id === "0") {
      this.__resultObject = new ParentRootResultObject();
    } else {
      this.__resultObject.setData(this.__object);
    }
    return this.__collectionObject = new CollectionObject(this.__object);
  };

  ResultTableNode.prototype.getResultObject = function() {
    return this.__resultObject;
  };

  ResultTableNode.prototype.getData = function() {
    return this.__object[this.__objecttype];
  };

  ResultTableNode.prototype.getTopLevelData = function() {
    return this.__object;
  };

  ResultTableNode.prototype.close = function() {
    return ResultTableNode.__super__.close.call(this).done((function(_this) {
      return function() {
        return _this.children = null;
      };
    })(this));
  };

  ResultTableNode.prototype.replaceSelf = function() {
    var ret;
    ret = ResultTableNode.__super__.replaceSelf.call(this);
    return ret.done((function(_this) {
      return function() {
        return CUI.Events.trigger({
          type: "search",
          node: _this.getDOMNodes()[0]
        });
      };
    })(this));
  };

  ResultTableNode.prototype.renderContent = function() {
    var column, i, idx, ref;
    for (idx = i = 1, ref = this._cols.length; i < ref; idx = i += 1) {
      column = this.__getContentByIdx(idx);
      if (column) {
        this.addColumn(column);
      }
    }
    return this.__getContentByIdx(0);
  };

  ResultTableNode.prototype.addedToListView = function() {
    var i, len, node, nodes;
    nodes = this.getDOMNodes();
    for (i = 0, len = nodes.length; i < len; i++) {
      node = nodes[i];
      CUI.dom.setAttributeMap(node, {
        "global-object-id": this.__resultObject.getGlobalObjectId(),
        offset: this.__offset,
        path: this._path
      });
    }
    if (this._resultTable.getCollectionSelection().objectIdx(this.__collectionObject) > -1) {
      CUI.dom.addClass(nodes[0], "cui-selected");
    }
    this.__object.__offset = this.__offset;
    return CUI.dom.data(nodes[0], "object", this.__object);
  };

  ResultTableNode.prototype.isLeaf = function() {
    if (this._force_no_children) {
      return true;
    }
    if (this.__object._has_children) {
      return false;
    } else {
      return true;
    }
  };

  ResultTableNode.prototype.setSelectable = function(on_off) {
    var ref, row;
    ResultTableNode.__super__.setSelectable.call(this, on_off);
    row = (ref = this.getDOMNodes()) != null ? ref[0] : void 0;
    if (!row) {
      return;
    }
    if (on_off) {
      CUI.dom.addClass(row, this.__selectableClass);
    } else {
      CUI.dom.removeClass(row, this.__selectableClass);
    }
  };

  ResultTableNode.prototype.getChildren = function() {
    return this.loadChildren();
  };

  ResultTableNode.prototype.loadChildren = function(offset) {
    var cb, dfr, i, len, ref, req, searchField, sm;
    if (offset == null) {
      offset = 0;
    }
    if (ez5.schema.CURRENT._objecttype_by_name[this.__objecttype].polyhierarchical) {
      searchField = this.__objecttype + "._parents." + this.__objecttype + "._id";
    } else {
      searchField = this.__objecttype + "._id_parent";
    }
    req = new Request({
      objecttypes: [this.__objecttype],
      offset: offset,
      generate_rights: false,
      limit: this._resultTable.getPageSize(),
      exclude_fields: this._resultTable.getExcludeFields(),
      format: this._resultTable.getObjectFormatNeededInternal(),
      search: [
        {
          type: "in",
          bool: "must",
          fields: [searchField],
          "in": [this.__object[this.__objecttype]._id]
        }
      ]
    });
    ref = this._resultTable.getSearch().getSearchManagers();
    for (i = 0, len = ref.length; i < len; i++) {
      sm = ref[i];
      if (sm instanceof SortManager) {
        sm.addToRequest(req);
      }
    }
    cb = this._resultTable.getSearch().getOpt("onAddToRequest");
    if (cb) {
      cb(req);
    }
    dfr = new CUI.Deferred();
    ez5.api.search({
      data: {
        debug: "ResultTableNode.loadChildren"
      },
      json_data: req.copy().cleanRequestForSearch()
    }).done((function(_this) {
      return function(data) {
        var children, onRequestDoneCallback, ref1, ref2;
        onRequestDoneCallback = _this._resultTable.getSearch().getOpt("onRequestDone");
        if (typeof onRequestDoneCallback === "function") {
          onRequestDoneCallback(data);
        }
        if ((data != null ? (ref1 = data.objects) != null ? ref1.length : void 0 : void 0) === 0 && ((ref2 = _this.__object) != null ? ref2._has_children : void 0)) {
          children = [new ResultTableNodeNotAllowed()];
          dfr.resolve(children);
          return;
        }
        data.__path = _this._path;
        children = _this._resultTable.getNodesFromDataFlat(data);
        if (data.offset + data.limit < data.count) {
          children.push(new ResultTableLoadMoreNode({
            offset: data.offset,
            limit: data.limit,
            count: data.count
          }));
        }
        return dfr.resolve(children);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  ResultTableNode.prototype.__getContentByIdx = function(idx) {
    var cls, colspan, content, f, i, info, len, ref, renderField, txt;
    info = this.__field_per_column[idx];
    if (!info) {
      return void 0;
    }
    renderField = (function(_this) {
      return function(field) {
        var viewData;
        viewData = _this._resultTable.getViewData();
        return field.renderForTable(_this.__object[_this.__objecttype], _this.__object, {
          mode: "table",
          nested_page_size: viewData.nested_page_size
        });
      };
    })(this);
    txt = null;
    content = null;
    colspan = 1;
    switch (info.group) {
      case "standard":
      case "tags":
      case "system_object_id":
      case "pool":
      case "objecttype":
        content = this._resultTable.renderResultObject(this.__resultObject, info.group);
        cls = "ez5-result-table-standard-cell";
        break;
      case "COMMONS":
        ref = info.fields;
        for (i = 0, len = ref.length; i < len; i++) {
          f = ref[i];
          if (f.table.name() === this.__objecttype) {
            content = renderField(f);
            cls = f.getClass();
            break;
          }
        }
        break;
      default:
        cls = info.field.getClass();
        if (info.field.getMainMask().table.name() === this.__objecttype) {
          content = renderField(info.field);
        } else {
          txt = null;
        }
        colspan = info.colspan;
    }
    if (idx > 0) {
      if (content instanceof CUI.ListViewColumn) {
        content.addClass(cls);
        return content;
      } else if (content !== null) {
        return new CUI.ListViewColumn({
          colspan: colspan,
          element: content,
          "class": cls
        });
      } else if (txt === null) {
        return new CUI.ListViewColumnEmpty({
          colspan: colspan,
          "class": cls
        });
      } else {
        return new CUI.ListViewColumn({
          colspan: colspan,
          text: txt,
          "class": cls
        });
      }
    } else {
      if (content) {
        if (content instanceof CUI.ListViewColumn) {
          return content.render();
        } else {
          return content;
        }
      } else {
        return new CUI.Label({
          text: txt
        });
      }
    }
  };

  return ResultTableNode;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var ResultTableNodeDeleted,
  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;

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

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

  ResultTableNodeDeleted.prototype.initOpts = function() {
    ResultTableNodeDeleted.__super__.initOpts.call(this);
    return this.addOpts({
      policy: {
        check: String,
        "default": "delete"
      }
    });
  };

  ResultTableNodeDeleted.prototype.readOpts = function() {
    ResultTableNodeDeleted.__super__.readOpts.call(this);
    return this.__class = "deleted ez5-deleted";
  };

  ResultTableNodeDeleted.prototype.renderContent = function() {
    var loca_key;
    if (this._policy === "undelete") {
      loca_key = "ez5.object.undeleted";
    } else if (this._policy === "purge") {
      loca_key = "ez5.object.purged";
    } else {
      loca_key = "ez5.object.deleted";
    }
    return new LocaLabel({
      "class": "ez5-object-deleted",
      loca_key: loca_key
    });
  };

  return ResultTableNodeDeleted;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var ResultTableNodeNotAllowed,
  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;

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

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

  ResultTableNodeNotAllowed.prototype.readOpts = function() {
    ResultTableNodeNotAllowed.__super__.readOpts.call(this);
    return this.__class = "not-allowed ez5-not-allowed";
  };

  ResultTableNodeNotAllowed.prototype.renderContent = function() {
    return new LocaLabel({
      "class": "ez5-object-not-allowed",
      loca_key: "ez5.object.not_allowed"
    });
  };

  return ResultTableNodeNotAllowed;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var ResultTableLoadMoreNode,
  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;

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

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

  ResultTableLoadMoreNode.prototype.initOpts = function() {
    ResultTableLoadMoreNode.__super__.initOpts.call(this);
    return this.addOpts({
      offset: {
        mandatory: true,
        check: function(v) {
          return v >= 0;
        }
      },
      limit: {
        mandatory: true,
        check: function(v) {
          return v > 0;
        }
      },
      count: {
        mandatory: true,
        check: function(v) {
          return v >= 0;
        }
      }
    });
  };

  ResultTableLoadMoreNode.prototype.renderContent = function() {
    var btn;
    return btn = new LocaButton({
      left: true,
      loca_key: "result.table.load.more.node.button",
      loca_key_attrs: {
        more: Math.min(this._count - this._offset - this._limit, this._limit),
        offset: this._offset,
        limit: this._limit,
        count: this._count
      },
      onClick: (function(_this) {
        return function(ev) {
          var node;
          btn.startSpinner();
          node = _this.getFather();
          return node.loadChildren(_this._offset + _this._limit).done(function(children) {
            var c, i, len;
            btn.stopSpinner();
            _this.remove(false, false);
            for (i = 0, len = children.length; i < len; i++) {
              c = children[i];
              node.addChild(c);
            }
          });
        };
      })(this)
    });
  };

  return ResultTableLoadMoreNode;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var TemplateObject,
  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;

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

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

  TemplateObject.prototype.renderCardStandard = function() {
    var label, tmpl;
    label = new LocaLabel({
      loca_key: "main.editor.template",
      "class": "ez5-result-object-no-asset-browser",
      centered: true
    });
    tmpl = new CUI.Template({
      name: "result-card",
      "class": "ez5-card--standard",
      map: {
        asset: true,
        standard_1: true
      }
    });
    tmpl.append(label, "asset");
    tmpl.append($$("main.editor.template"), "standard_1");
    return tmpl.DOM;
  };

  return TemplateObject;

})(ResultObject);
// Generated by CoffeeScript 1.12.7
var EAS,
  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;

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

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

  EAS.prototype.readOpts = function() {
    EAS.__super__.readOpts.call(this);
    this.polling = false;
    this.__pollableIds = [];
    return EventPoller.listen({
      instance: this,
      filter: {
        type: "OBJECT_INDEX",
        basetype: "asset"
      },
      call: (function(_this) {
        return function(events) {
          var ev, i, len;
          for (i = 0, len = events.length; i < len; i++) {
            ev = events[i];
            CUI.util.pushOntoArray(ev.object_id, _this.__pollableIds);
          }
        };
      })(this)
    });
  };

  EAS.prototype.pollQueue = [];

  EAS.prototype.replaceImgElement = function(oldImgElement, newImgElement, updateEvent) {
    var asset;
    if (updateEvent == null) {
      updateEvent = true;
    }
    CUI.util.assert(CUI.util.isElement(oldImgElement), "EAS.replaceImgElement", "oldImgElement needs to be Element", {
      oldImgElement: oldImgElement
    });
    CUI.util.assert(CUI.util.isElement(newImgElement), "EAS.replaceImgElement", "newImgElement needs to be Element", {
      newImgElement: newImgElement
    });
    asset = CUI.dom.data(oldImgElement, "asset");
    CUI.util.assert(asset instanceof Asset, "EAS.replaceImgElement", "No Asset found in key 'asset' in data of img element", {
      element: oldImgElement,
      asset: asset
    });
    CUI.dom.data(newImgElement, "asset", asset);
    if (!CUI.dom.parent(oldImgElement)) {
      return;
    }
    CUI.dom.replaceWith(oldImgElement, newImgElement);
    if (updateEvent) {
      CUI.Events.trigger({
        node: newImgElement,
        type: "eas_update",
        info: {
          asset: asset
        }
      });
    }
    return newImgElement;
  };

  EAS.prototype.getFileUploadMeter = function(file) {
    var pm, pm_active, update;
    pm = new CUI.ProgressMeter({
      "class": "ez5-file-upload-progress"
    });
    CUI.dom.setAttribute(pm, "ui", "eas.progress_meter.file_upload_progress");
    pm_active = false;
    update = (function(_this) {
      return function() {
        switch (file.getStatus()) {
          case "CREATED":
          case "QUEUED":
            return pm.setState("waiting");
          case "COMPLETED":
          case "DONE":
            return pm.setState("spinning");
          case "STARTED":
          case "PROGRESS":
            return pm.setState(file.getPercent());
          default:
            return pm.setState("waiting");
        }
      };
    })(this);
    file.getPromise().progress(function() {
      if (pm.isDestroyed()) {
        return;
      }
      return update();
    }).always(function() {
      if (pm.isDestroyed()) {
        return;
      }
      return update();
    });
    CUI.dom.data(pm.DOM, "file-upload", file);
    return pm.DOM;
  };

  EAS.prototype.getPollingPlaceholder = function(eas_field, value, version, opts) {
    var div, pm, ref, seen_in_dom, shouldDequeue;
    if (version == null) {
      version = null;
    }
    if (opts == null) {
      opts = {};
    }
    pm = new CUI.ProgressMeter({
      state: "spinning2"
    });
    CUI.dom.setAttribute(pm, "ui", "eas.progress_meter.polling_placeholder");
    seen_in_dom = false;
    shouldDequeue = (function(_this) {
      return function() {
        if (CUI.dom.isInDOM(div)) {
          seen_in_dom = true;
          return false;
        }
        if (!seen_in_dom) {
          return false;
        }
        return !CUI.dom.isInDOM(div);
      };
    })(this);
    this.addToQueue({
      value: value,
      version: version,
      listenForVersionsChanges: opts.listenForVersionsChanges,
      obj_uuid: (ref = opts.obj_data) != null ? ref._uuid : void 0,
      dequeue: shouldDequeue,
      done: (function(_this) {
        return function(eas_obj) {
          var ref1, ref2, versions, vname;
          if (!CUI.dom.isInDOM(div) && seen_in_dom) {
            return;
          }
          if (opts.loadVersion) {
            version = opts.loadVersion;
          }
          if (opts.listenForVersionsChanges) {
            opts.listenForVersionsChanges = false;
            value.__waitForOriginal = false;
            versions = [];
            ref1 = eas_obj.versions;
            for (vname in ref1) {
              version = ref1[vname];
              if (version.status !== "done") {
                versions.push(vname);
              }
            }
            _this.addToQueue({
              value: value,
              version: versions,
              obj_uuid: (ref2 = opts.obj_data) != null ? ref2._uuid : void 0,
              dequeue: shouldDequeue,
              done: function(eas_obj) {
                var i, len, v;
                if (!CUI.dom.isInDOM(div) && seen_in_dom) {
                  return;
                }
                for (i = 0, len = versions.length; i < len; i++) {
                  v = versions[i];
                  if (eas_obj.versions[v].status === "done") {
                    version = v;
                    break;
                  }
                }
                return _this.replaceImgElement(div, eas_field.getImgElementForValue(value, version));
              }
            });
            return;
          }
          if (!version) {
            version = Asset.getStandardVersionName(value);
          }
          return _this.replaceImgElement(div, eas_field.getImgElementForValue(value, version));
        };
      })(this),
      processing: function(poll_count) {},
      failed: function(eas_obj) {
        if (value._error) {
          CUI.dom.empty(div);
          return CUI.dom.append(div, EAS.getErrorPlaceholder(value._error).DOM);
        } else {
          CUI.dom.empty(div);
          return CUI.dom.append(div, EAS.getFailedPlaceholder().DOM);
        }
      }
    });
    div = CUI.dom.div("ez5-polling-placeholder");
    CUI.dom.append(div, pm.DOM);
    return div;
  };

  EAS.getFailedPlaceholder = function() {
    return new LocaLabel({
      "class": "ez5-eas-column-version-failed",
      multiline: true,
      loca_key: "eas.failed.placeholder",
      centered: true
    });
  };

  EAS.getErrorPlaceholder = function(error) {
    return new CUI.Label({
      icon: "failed",
      "class": "ez5-eas-column-version-error",
      multiline: true,
      centered: true,
      text: $$(error.code, error.parameters)
    });
  };

  EAS.getNoRightPlaceholder = function() {
    return new LocaLabel({
      "class": "ez5-eas-column-version-no-right",
      multiline: true,
      loca_key: "eas.no_right.placeholder",
      centered: true
    });
  };

  EAS.getProcessingPlaceholder = function() {
    return new LocaLabel({
      "class": "ez5-eas-column-version-processing",
      multiline: true,
      loca_key: "eas.processing.placeholder",
      centered: true
    });
  };

  EAS.getNoUrlPlaceholder = function() {
    return new LocaLabel({
      multiline: true,
      loca_key: "eas.no_url.placeholder",
      centered: true
    });
  };

  EAS.getDeletedPlaceholder = function() {
    return new CUI.Label({
      "class": "ez5-eas-column-version-error",
      multiline: true,
      centered: true,
      icon: $$("eas.deleted.placeholder|icon"),
      text: $$("eas.deleted.placeholder|text")
    });
  };

  EAS.getNoAssetPlaceholder = function(icon) {
    var labelClass, ll;
    if (icon == null) {
      icon = null;
    }
    labelClass = ["ez5-eas-column-version-no-asset", icon ? "ez5-asset-placeholder-custom-icon" : void 0];
    ll = new LocaLabel({
      "class": labelClass.join(" "),
      multiline: true,
      loca_key: "eas.no_asset.placeholder",
      centered: true
    });
    if (icon) {
      ll.setIcon(icon);
    }
    return ll;
  };

  EAS.getNoAssetInObjecttypePlaceholder = function(icon) {
    var labelClass, ll;
    if (icon == null) {
      icon = null;
    }
    labelClass = ["objecttype-has-no-asset", icon ? labelClass += " ez5-asset-placeholder-custom-icon" : void 0];
    ll = new LocaLabel({
      "class": labelClass.join(" "),
      multiline: true,
      centered: true,
      loca_key: "eas.no_asset_in_objecttype.placeholder"
    });
    if (icon) {
      ll.setIcon(icon);
    }
    return ll;
  };

  EAS.getNoThumbPlaceholder = function(value) {
    var charCountClass, i, key, len, loca_key, ref, ref1;
    loca_key = "eas.no_thumb.placeholder";
    ref = ["class_extension", "extension", "class"];
    for (i = 0, len = ref.length; i < len; i++) {
      key = ref[i];
      if (ez5.loca.has("eas.no_thumb.placeholder." + value[key] + "|icon")) {
        loca_key = "eas.no_thumb.placeholder." + value[key];
        break;
      }
    }
    if (((ref1 = value.extension) != null ? ref1.length : void 0) > 4) {
      charCountClass = "ez5-label--extension-long";
    } else {
      charCountClass = "";
    }
    return new LocaLabel({
      "class": "ez5-eas-column-version-no-thumb ez5-label--extension " + charCountClass,
      multiline: true,
      loca_key: loca_key,
      centered: true,
      text: value.extension
    });
  };

  EAS.prototype.pollInterval = 2000;

  EAS.prototype.__pollId = 0;

  EAS.prototype.addToQueue = function(poll) {
    var eas_id, ref;
    eas_id = poll != null ? (ref = poll.value) != null ? ref._id : void 0 : void 0;
    CUI.util.assert(eas_id, "ez5.eas.addToQueue", "value._id needs to be set", {
      poll: poll
    });
    CUI.util.pushOntoArray(eas_id, this.__pollableIds);
    poll.poll_count = 0;
    poll.__poll_id = this.__pollId;
    this.__pollId = this.__pollId + 1;
    if (!this.polling) {
      this.pollQueue.push(poll);
      this.doPoll();
    } else {
      if (this.nextPolls == null) {
        this.nextPolls = [];
      }
      this.nextPolls.push(poll);
    }
    return poll.__poll_id;
  };

  EAS.prototype.removeFromQueue = function(poll_id) {
    return CUI.util.removeFromArray(null, this.pollQueue, (function(_this) {
      return function(v) {
        return v.__poll_id === poll_id;
      };
    })(this));
  };

  EAS.prototype.doPoll = function() {
    var eas_ids, obj_uuid, q;
    this.polling = true;
    if (this.pollQueue.length === 0) {
      this.polling = false;
      return;
    }
    eas_ids = arrayUnique((function() {
      var i, len, ref, results;
      ref = this.pollQueue;
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        q = ref[i];
        results.push(q.value._id);
      }
      return results;
    }).call(this));
    obj_uuid = arrayUnique(((function() {
      var i, len, ref, results;
      ref = this.pollQueue;
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        q = ref[i];
        results.push(q.obj_uuid);
      }
      return results;
    }).call(this)).filter(function(v) {
      return !!v;
    }));
    if (eas_ids.length === 0) {
      CUI.setTimeout((function(_this) {
        return function() {
          return _this.doPoll();
        };
      })(this), this.pollInterval);
      return;
    }
    return ez5.api.eas({
      data: {
        ids: JSON.stringify(eas_ids),
        format: ez5.version("6") ? "standard" : "short",
        obj_uuid: obj_uuid != null ? obj_uuid[obj_uuid.length - 1] : void 0
      },
      handle_error: (function(_this) {
        return function(xhr) {
          var error, i, idx, len, ref;
          ref = _this.pollQueue;
          for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
            q = ref[idx];
            if (xhr.responseJSON && false) {
              error = $$(xhr.responseJSON.code, xhr.responseJSON.parameters);
            } else {
              error = $$("eas.unknown_error");
            }
            if (typeof q.failed === "function") {
              q.failed(error);
            }
          }
          _this.pollQueue = [];
          _this.polling = false;
          return true;
        };
      })(this)
    }).done((function(_this) {
      return function(data) {
        var eas_obj, i, idx, k, len, ref, ref1, ref2, ref3, ref4, remove, status, v, version, vname;
        idx = 0;
        while (idx < _this.pollQueue.length) {
          status = null;
          q = _this.pollQueue[idx];
          eas_obj = data[q != null ? q.value._id : void 0];
          if (!eas_obj) {
            idx++;
            continue;
          }
          q.poll_count++;
          remove = false;
          if (eas_obj.error) {
            if (typeof q.failed === "function") {
              q.failed(eas_obj.error);
            }
            q.value._error = eas_obj.error;
            remove = true;
          } else if (typeof q.dequeue === "function" ? q.dequeue(eas_obj) : void 0) {
            remove = true;
          } else {
            if (eas_obj.status === "failed") {
              status = "failed";
            } else {
              if (CUI.util.isArray(q.version) && q.version.length > 0) {
                ref = q.version;
                for (i = 0, len = ref.length; i < len; i++) {
                  vname = ref[i];
                  version = (ref1 = eas_obj.versions) != null ? ref1[vname] : void 0;
                  if (version && !version._not_allowed) {
                    if (version.status === "done") {
                      status = "done";
                      break;
                    }
                  }
                }
              } else {
                if (q.version) {
                  vname = q.version;
                } else {
                  vname = Asset.getStandardVersionName(eas_obj);
                }
                version = (ref2 = eas_obj.versions) != null ? ref2[vname] : void 0;
                if (!version) {
                  status = eas_obj.status;
                } else if (version._not_allowed) {
                  status = "failed";
                } else {
                  status = version.status;
                }
                if (q.listenForVersionsChanges) {
                  ref3 = eas_obj != null ? eas_obj.versions : void 0;
                  for (vname in ref3) {
                    version = ref3[vname];
                    if (vname !== q.version && (q.value.versions[vname] && version.status !== q.value.versions[vname].status)) {
                      status = "done";
                      break;
                    }
                  }
                }
              }
            }
            for (k in eas_obj) {
              v = eas_obj[k];
              q.value[k] = v;
            }
            switch (status) {
              case "done":
                if (typeof q.done === "function") {
                  q.done(q.value);
                }
                remove = true;
                break;
              case "failed":
                if (typeof q.failed === "function") {
                  q.failed(eas_obj);
                }
                remove = true;
                break;
              default:
                if (typeof q.processing === "function") {
                  q.processing(q.poll_count);
                }
            }
          }
          if (remove) {
            _this.pollQueue.splice(idx, 1);
          } else {
            idx++;
          }
        }
        if (((ref4 = _this.nextPolls) != null ? ref4.length : void 0) > 0) {
          _this.pollQueue = _this.pollQueue.concat(_this.nextPolls);
          _this.nextPolls = [];
        }
        if (_this.pollQueue.length > 0) {
          return CUI.setTimeout(function() {
            return _this.doPoll();
          }, _this.pollInterval);
        } else {
          return _this.polling = false;
        }
      };
    })(this));
  };

  EAS.prototype.getUploadUrl = function(parms) {
    if (parms == null) {
      parms = {};
    }
    if (!ez5.version("6") && (parms.produce_versions != null)) {
      delete parms.produce_versions;
    }
    if (ez5.version("6.1")) {
      parms.access_token = ez5.session.token;
    } else {
      parms.token = ez5.session.token;
    }
    if (!parms.hasOwnProperty("check_for_duplicates")) {
      parms.check_for_duplicates = "1";
    }
    return ez5.api.getFullBase() + "/eas/put?" + CUI.encodeUrlData(parms);
  };

  EAS.getRotateMapFromTransform = function(transform) {
    var i, j, k, len, len1, r, ref, t, v;
    r = {
      x: 0,
      y: 0,
      z: 0
    };
    if (!(transform != null ? transform.length : void 0)) {
      return r;
    }
    for (i = 0, len = transform.length; i < len; i++) {
      t = transform[i];
      for (k in t) {
        v = t[k];
        switch (k) {
          case "rotate-x":
            r.x += v;
            break;
          case "rotate-y":
            r.y += v;
            break;
          case "rotate-z":
            r.z += v;
        }
      }
    }
    ref = ["x", "y", "z"];
    for (j = 0, len1 = ref.length; j < len1; j++) {
      k = ref[j];
      while (r[k] < 0) {
        r[k] += 360;
      }
      r[k] = r[k] % 360;
    }
    return r;
  };

  EAS.setTransformStyle = function(node, transform, do_scale) {
    var i, k, len, scale_node, t, ts, v, z;
    if (do_scale == null) {
      do_scale = true;
    }
    ts = [];
    z = 0;
    CUI.Events.ignore({
      node: node,
      type: "viewport-resize"
    });
    if (!(transform != null ? transform.length : void 0)) {
      CUI.dom.setStyle(node, {
        transform: "",
        "transform-origin": ""
      });
      if (do_scale) {
        node.firstElementChild.firstElementChild.removeAttribute("scale");
        node.firstElementChild.firstElementChild.removeAttribute("turned90");
      }
      return;
    }
    for (i = 0, len = transform.length; i < len; i++) {
      t = transform[i];
      for (k in t) {
        v = t[k];
        switch (k) {
          case "rotate-x":
            ts.push("rotateX(" + v + "deg)");
            break;
          case "rotate-y":
            ts.push("rotateY(" + v + "deg)");
            break;
          case "rotate-z":
            ts.push("rotateZ(" + v + "deg)");
            z += v;
            break;
          default:
            CUI.util.assert(false, "EAS.setTransformStyle", "Unknown transform " + k + ".", {
              transform: transform,
              node: node
            });
        }
      }
    }
    if (z % 180 !== 0 && do_scale) {
      if (do_scale) {
        node.firstElementChild.firstElementChild.setAttribute("turned90", "turned90");
      }
      scale_node = function() {
        var dest_height, dest_width, dim_viewport, pic, pic_div, ref, scale, scale_css, viewport;
        dim_viewport = CUI.dom.getDimensions(node.parentNode);
        viewport = {
          width: dim_viewport.contentBoxWidth,
          height: dim_viewport.contentBoxHeight
        };
        if (viewport.width === 0 || viewport.height === 0) {
          dim_viewport = CUI.dom.getDimensions(CUI.dom.closest(node, ".ez-asset"));
          if (!dim_viewport) {
            return;
          }
          viewport = {
            width: dim_viewport.contentBoxWidth,
            height: dim_viewport.contentBoxHeight
          };
        }
        viewport.aspect = viewport.width / viewport.height;
        if (viewport.aspect !== 1) {
          pic_div = node.firstElementChild;
          pic = {
            width: CUI.util.getFloat(CUI.dom.getAttribute(pic_div, "real-width")),
            height: CUI.util.getFloat(CUI.dom.getAttribute(pic_div, "real-height"))
          };
          pic.aspect = 1 / (pic.width / pic.height);
          CUI.util.assert(!isNaN(pic.aspect) && !isNaN(viewport.aspect), "EAS.setTransformStyle", "pic aspect or viewport aspect NaN, you need real-width and real-height attributes set at DIV", {
            node: node,
            transform: transform
          });
          if (viewport.aspect < pic.aspect) {
            scale = viewport.width / pic.height;
          } else {
            scale = viewport.height / pic.width;
          }
          ref = ez5.fitRectangle(pic.width, pic.height, viewport.width, viewport.height), dest_width = ref[0], dest_height = ref[1];
          scale = scale * (pic.width / dest_width);
          scale_css = " scale(" + scale + ")";
          node.firstElementChild.firstElementChild.setAttribute("scale", scale);
        } else {
          scale_css = " scale(1)";
          node.firstElementChild.firstElementChild.removeAttribute("scale");
        }
        return CUI.dom.setStyle(node, {
          transform: ts.join(" ") + scale_css,
          "transform-origin": "center center"
        });
      };
      CUI.dom.waitForDOMInsert({
        node: node
      }).done(function() {
        return scale_node();
      });
      CUI.Events.listen({
        node: node,
        type: "viewport-resize",
        call: function(ev) {
          return scale_node();
        }
      });
    } else {
      CUI.dom.setStyle(node, {
        transform: ts.join(" ") + " scale(1)",
        "transform-origin": "center center"
      });
      if (do_scale) {
        node.firstElementChild.firstElementChild.removeAttribute("scale");
        node.firstElementChild.firstElementChild.removeAttribute("turned90");
      }
    }
    return this;
  };

  EAS.presentUploadError = function(file) {
    var ref;
    if ((ref = file.getErrorXHR()) != null ? ref.responseJSON : void 0) {
      return ez5.error_handler(file.getErrorXHR());
    } else {
      return CUI.problem({
        text: $$("file.upload.upload_error", {
          name: file.getName()
        }),
        markdown: true
      });
    }
  };

  EAS.mapMetadata = function(_opts) {
    var data, dfr, easRequestData, eas_id, mappingErrors, new_data, opts, ot, tn;
    dfr = new CUI.Deferred();
    if (_opts.mapping === "none") {
      return dfr.resolve().promise();
    }
    opts = CUI.Element.readOpts(_opts, "EditorModalNew.mapMetadata", {
      data: {
        mandatory: true,
        check: "PlainObject"
      },
      eas_id: {
        mandatory: true,
        check: function(v) {
          return v > 0;
        }
      },
      pool_id: {
        check: function(v) {
          return v > 0;
        }
      },
      mask_name: {
        mandatory: true,
        check: String
      },
      objecttype: {
        mandatory: true,
        check: String
      },
      mapping: {
        check: function(v) {
          return v > 0 || v === 'standard';
        }
      },
      mapping_recipe_configs: {
        check: "PlainObject"
      },
      editor: {
        check: function(v) {
          return v instanceof Editor;
        }
      },
      poll: {
        check: Boolean
      }
    });
    tn = opts.objecttype;
    ot = ez5.schema.CURRENT._objecttype_by_name[tn];
    CUI.util.assert(ot, "EAS.mapMetadata", "opts.objecttype not found.", {
      objecttype: tn
    });
    if (opts.mapping === "standard" && !opts.pool_id) {
      CUI.util.assert(!ot.pool_link, "EAS.mapMetadata", "Mapping \"standard\" for objecttype " + tn + " requires opts.pool_id to be set.");
    }
    eas_id = opts.eas_id;
    new_data = opts.data;
    easRequestData = {
      ids: JSON.stringify([eas_id]),
      mask: opts.mask_name,
      mapping: opts.mapping,
      objecttype: opts.objecttype,
      pool_id: opts.pool_id,
      format: "short"
    };
    if (opts.mapping_recipe_configs && !CUI.util.isEmptyObject(opts.mapping_recipe_configs)) {
      easRequestData.mapping_recipe_configs = JSON.stringify(opts.mapping_recipe_configs);
    }
    if (ez5.version("6") || opts.poll) {
      mappingErrors = [];
      EAS.pollMetadataMapping(eas_id, data = {}, easRequestData, mappingErrors).fail(function(e) {
        var ref, ref1, ref2, ref3;
        if ((e != null ? (ref = e.response) != null ? ref.code : void 0 : void 0) || (e != null ? (ref1 = e.response) != null ? ref1.error : void 0 : void 0)) {
          mappingErrors.push({
            code: e != null ? (ref2 = e.response) != null ? ref2.code : void 0 : void 0,
            error: e != null ? (ref3 = e.response) != null ? ref3.error : void 0 : void 0,
            eas_id: eas_id
          });
        }
        return dfr.resolve({
          result: {
            mappingfail: true,
            mappingErrors: mappingErrors
          }
        });
      }).done(function(data) {
        var map_data;
        map_data = data._mapped_metadata;
        map_data = map_data != null ? map_data[tn] : void 0;
        EAS.mergeMetadata(map_data, new_data, opts);
        return dfr.resolve();
      });
      return dfr.promise();
    } else {
      ez5.api.eas({
        data: easRequestData,
        handle_error: function() {
          return true;
        }
      }).done(function(data) {
        var map_data;
        map_data = data[eas_id]._mapped_metadata;
        map_data = map_data != null ? map_data[tn] : void 0;
        EAS.mergeMetadata(map_data, new_data, opts);
        return dfr.resolve();
      }).fail(function(xhr) {
        return ez5.error_handler(xhr).done(function() {
          return dfr.resolve();
        });
      });
      return dfr.promise();
    }
  };

  EAS.pollMetadataMapping = function(eas_id, data, easRequestData, mappingErrors) {
    var addToPoll, dfr;
    if (mappingErrors == null) {
      mappingErrors = [];
    }
    addToPoll = (function(_this) {
      return function(dfr) {
        var pollData;
        if (EAS.__metadataPolls == null) {
          EAS.__metadataPolls = [];
        }
        if (EAS.__metadataPollsQueue == null) {
          EAS.__metadataPollsQueue = [];
        }
        pollData = {
          id: eas_id,
          deferred: dfr,
          requestData: easRequestData
        };
        if (EAS.__metadataPolls.length > _this.MAX_METADATA_POLL_BATCH) {
          EAS.__metadataPollsQueue.push(pollData);
        } else {
          EAS.__metadataPolls.push(pollData);
        }
        return _this.__metadataPoll();
      };
    })(this);
    dfr = new CUI.Deferred();
    addToPoll(dfr);
    return dfr.promise();
  };

  EAS.MAX_METADATA_POLL_BATCH = 100;

  EAS.__metadataPoll = function() {
    var easRequestData, eas_ids, findPollIdxByEASid, getMetadata, i, len, poll, ref, ref1, removeFromPoll;
    findPollIdxByEASid = function(id) {
      return EAS.__metadataPolls.findIndex((function(_this) {
        return function(el) {
          return ("" + el.id) === ("" + id);
        };
      })(this));
    };
    removeFromPoll = function(pollDataIdx) {
      return EAS.__metadataPolls.splice(pollDataIdx, 1);
    };
    getMetadata = function(id) {
      var pollData, pollDataIdx;
      pollDataIdx = findPollIdxByEASid(id);
      if (pollDataIdx === -1) {
        return;
      }
      pollData = EAS.__metadataPolls[pollDataIdx];
      removeFromPoll(pollDataIdx);
      return ez5.api.eas({
        data: pollData.requestData,
        handle_error: function() {
          return true;
        }
      }).done(function(data) {
        return pollData.deferred.resolve(data[id]);
      }).fail(pollData.deferred.reject);
    };
    if (EAS.__metadataPolling) {
      return;
    }
    if (EAS.__metadataPollsQueue.length >= 0 && (EAS.__metadataPolls.length < EAS.MAX_METADATA_POLL_BATCH)) {
      EAS.__metadataPolls = EAS.__metadataPolls.concat(EAS.__metadataPollsQueue.splice(0, EAS.MAX_METADATA_POLL_BATCH - EAS.__metadataPolls.length));
    }
    if (((ref = EAS.__metadataPolls) != null ? ref.length : void 0) === 0) {
      EAS.__metadataPolling = false;
      return;
    }
    EAS.__metadataPolling = true;
    eas_ids = [];
    ref1 = EAS.__metadataPolls;
    for (i = 0, len = ref1.length; i < len; i++) {
      poll = ref1[i];
      eas_ids.push(poll.id);
    }
    easRequestData = {
      ids: JSON.stringify(eas_ids),
      format: "short"
    };
    return ez5.api.eas({
      data: easRequestData,
      handle_error: function() {
        return true;
      }
    }).done(function(pollData) {
      var easData, id, pollDataIdx;
      for (id in pollData) {
        easData = pollData[id];
        if (!easData) {
          continue;
        }
        if (easData.status === "sync" || easData.status === "done") {
          getMetadata(id);
        } else if (easData.status === "failed") {
          pollDataIdx = findPollIdxByEASid(id);
          pollData = EAS.__metadataPolls[pollDataIdx];
          pollData.deferred.reject();
          removeFromPoll(pollDataIdx);
        }
      }
      return CUI.setTimeout({
        ms: 2000,
        call: (function(_this) {
          return function() {
            EAS.__metadataPolling = false;
            EAS.__metadataPoll();
          };
        })(this)
      });
    }).fail((function() {
      var j, len1, pollData, ref2;
      ref2 = EAS.__metadataPolls;
      for (j = 0, len1 = ref2.length; j < len1; j++) {
        pollData = ref2[j];
        console.log("Mapping for EAS: " + pollData.id + " failed, removing from poller...");
        pollData.deferred.reject();
      }
      EAS.__metadataPolls = [];
      return CUI.setTimeout({
        ms: 2000,
        call: (function(_this) {
          return function() {
            EAS.__metadataPolling = false;
            EAS.__metadataPoll();
          };
        })(this)
      });
    }));
  };

  EAS.mergeMetadata = function(mappedData, newData, metadataOpts) {
    var _v, e, fileField, fileFieldName, firstNewIdx, i, idx, index, item, j, k, k2, len, len1, newIdx, ref, ref1, ref2, v, v2;
    if (metadataOpts == null) {
      metadataOpts = null;
    }
    if (!mappedData) {
      return;
    }
    for (k in mappedData) {
      _v = mappedData[k];
      v = CUI.util.copyObject(_v, true);
      if (CUI.util.isArray(v)) {
        if (!CUI.util.isArray(newData[k])) {
          newData[k] = [];
        }
        index = 0;
        try {
          if (!CUI.util.isEmpty(metadataOpts) && ((ref = metadataOpts.editor) != null ? (ref1 = ref.editor_data) != null ? ref1.bulk_field : void 0 : void 0)) {
            fileField = metadataOpts.editor.editor_data.bulk_field;
            if (fileField instanceof EASColumn) {
              fileFieldName = fileField.name();
              index = newData[k].findIndex(function(el) {
                if (!CUI.util.isEmpty(el[fileFieldName]) && el[fileFieldName] instanceof Array) {
                  return el[fileFieldName].some(function(el2) {
                    return el2._id === metadataOpts.eas_id;
                  });
                }
              });
            }
          }
        } catch (error1) {
          e = error1;
          console.error("EAS | mergemetadata: Fail trying to find nested index from eas data", e);
        }
        if (index > 0) {
          firstNewIdx = index;
        } else {
          firstNewIdx = 0;
          ref2 = newData[k];
          for (newIdx = i = 0, len = ref2.length; i < len; newIdx = ++i) {
            item = ref2[newIdx];
            if (item._new) {
              firstNewIdx = newIdx;
              break;
            }
          }
        }
        for (idx = j = 0, len1 = v.length; j < len1; idx = ++j) {
          item = v[idx];
          item._mapped_metadata_created = true;
          if (!newData[k][idx]) {
            newData[k][idx] = {};
          }
          for (k2 in item) {
            v2 = item[k2];
            newData[k][idx + firstNewIdx][k2] = v2;
          }
        }
      } else {
        if (v != null ? v._objecttype : void 0) {
          newData[k] = v;
        } else {
          newData[k + ":mapped_metadata"] = v;
        }
      }
    }
  };

  EAS.replaceMappedMetadata = function(object) {
    var _key, key, value;
    for (_key in object) {
      value = object[_key];
      if (!_key.endsWith(":mapped_metadata")) {
        continue;
      }
      key = _key.split(":mapped_metadata")[0];
      object[key] = value;
      delete object[_key];
    }
  };

  EAS.cleanMappedMetadata = function(object) {
    CUI.util.removePropertyRecursively(object, "_mapped_metadata_created");
  };

  EAS.postToProduce = function(data) {
    var i, k, len, ref, tr, transform, v;
    if (ez5.version("6")) {
      if (data.transform instanceof Array) {
        transform = {};
        ref = data.transform.slice(0);
        for (i = 0, len = ref.length; i < len; i++) {
          tr = ref[i];
          for (k in tr) {
            v = tr[k];
            transform[k] = v;
          }
        }
        data.transform = transform;
      }
    }
    return ez5.api.eas({
      api: "/produce",
      type: "POST",
      json_data: data
    });
  };

  EAS.getSignatureFromUrl = function(url) {
    var baseUrl, newUrl, params, queryString, ref, signature, signatureParam;
    if (!url) {
      return [null, null];
    }
    if (url.includes('?')) {
      ref = url.split('?'), baseUrl = ref[0], queryString = ref[1];
    }
    if (!queryString) {
      return [url, null];
    }
    params = queryString.split('&').filter(function(param) {
      return !param.startsWith('x-fylr-signature=');
    });
    signatureParam = queryString.split('&').find(function(param) {
      return param.startsWith('x-fylr-signature=');
    });
    signature = signatureParam != null ? signatureParam.split('=')[1] : void 0;
    newUrl = baseUrl;
    if (params.length > 0) {
      newUrl += '?' + params.join('&');
    }
    return [newUrl, signature];
  };

  EAS.loadImageAsBlob = function(opts) {
    var currentUrl, headers, imagePromise, origin, ref, ref1, remoteEasydb, serverOpts, signature, url;
    ref = EAS.getSignatureFromUrl(opts.src), url = ref[0], signature = ref[1];
    if (!!signature) {
      headers = {
        "x-fylr-signature": signature
      };
    }
    remoteEasydb = null;
    if (opts.remoteInstance) {
      remoteEasydb = (ref1 = ez5.connector) != null ? ref1.getRemoteEasydbByInstance(opts.remoteInstance) : void 0;
    }
    if (Session.crossServer() && ez5.version("6")) {
      origin = new URL(document.location.href).host;
      currentUrl = new URL(url);
      currentUrl.searchParams.set("origin", origin);
      url = currentUrl.toString();
    }
    serverOpts = {
      url: url,
      type: "GET",
      dataType: "blob",
      remoteEasydb: remoteEasydb,
      add_token: !signature,
      headers: headers,
      withCredentials: !signature,
      handle_error: (function(_this) {
        return function() {
          return true;
        };
      })(this)
    };
    if (remoteEasydb && !(typeof remoteEasydb.isFylr === "function" ? remoteEasydb.isFylr() : void 0)) {
      delete serverOpts.withCredentials;
    }
    imagePromise = ez5.server(serverOpts);
    imagePromise.done((function(_this) {
      return function(data) {
        var objUrl;
        objUrl = URL.createObjectURL(data);
        if (opts.onLoad) {
          return opts.onLoad(objUrl);
        }
      };
    })(this)).fail((function(_this) {
      return function() {
        if (opts.onFail) {
          return opts.onFail();
        }
      };
    })(this));
  };

  EAS.unloadBlob = function(blobUrl) {
    return URL.revokeObjectURL(blobUrl);
  };

  return EAS;

})(CUI.Element);

CUI.defaults.FileUpload.name = "file";

CUI.ready(function() {
  ez5.eas = new EAS();
  CUI.Events.registerEvent({
    type: "eas_update",
    bubble: true
  });
  return CUI.Events.registerEvent({
    type: "asset-browser-show-asset",
    bubble: true
  });
});
// Generated by CoffeeScript 1.12.7
EAS.IntersectionObserver = (function() {
  function IntersectionObserver() {}

  IntersectionObserver.init = function() {
    if (window.headless_mode) {
      return;
    }
    this.observer = new window.IntersectionObserver((function(_this) {
      return function(entries) {
        return entries.forEach(function(entry) {
          var img;
          if (!entry.isIntersecting) {
            return;
          }
          img = entry.target;
          _this.loadImage(img);
        });
      };
    })(this));
  };

  IntersectionObserver.add = function(img) {
    if (!img) {
      return;
    }
    if (!CUI.dom.getAttribute(img, "data-observer-src")) {
      CUI.util.assert(false, "EAS.IntersectionObserver.add", "Image does not contain data-observer-src.", {
        img: img
      });
      return;
    }
    CUI.dom.addClass(img, "ez5-img-observer");
    this.observer.observe(img);
  };

  IntersectionObserver.loadImage = function(img) {
    var deferred, image, onDone, onImageLoadError, promise, src;
    if (!img) {
      return CUI.resolvedPromise();
    }
    src = CUI.dom.getAttribute(img, "data-observer-src");
    if (!src) {
      return CUI.resolvedPromise();
    }
    promise = CUI.dom.data(image, "observer-promise");
    if (promise) {
      return promise;
    }
    deferred = new CUI.Deferred();
    onDone = (function(_this) {
      return function() {
        CUI.dom.removeAttribute(img, "data-observer-src");
        CUI.dom.removeClass(img, "ez5-img-observer");
        _this.observer.unobserve(img);
        deferred.resolve();
      };
    })(this);
    if (ez5.version("6")) {
      onImageLoadError = (function(_this) {
        return function() {
          var assetElement;
          assetElement = CUI.dom.parents(img, ".ez5-asset-element")[0];
          if (assetElement) {
            CUI.dom.append(assetElement, EAS.getErrorPlaceholder({}));
            CUI.dom.addClass(assetElement, "ez5-asset-element-error");
          }
          CUI.dom.remove(img);
          return console.error("Error loading an image.", img, src);
        };
      })(this);
      EAS.loadImageAsBlob({
        src: src,
        remoteInstance: CUI.dom.getAttribute(img, "data-remote-instance"),
        onLoad: (function(_this) {
          return function(result) {
            CUI.dom.setAttribute(img, "src", result);
            img.addEventListener("load", function() {
              CUI.dom.remove(img.__placeholder);
              CUI.dom.addClass(img, "is-loaded");
              return EAS.unloadBlob(result);
            });
            img.addEventListener("error", function() {
              return onImageLoadError();
            });
            return onDone();
          };
        })(this),
        fail: (function(_this) {
          return function() {
            onImageLoadError();
            return onDone();
          };
        })(this)
      });
    } else {
      img.onload = (function(_this) {
        return function() {
          return CUI.dom.addClass(img, "is-loaded");
        };
      })(this);
      image = new Image();
      image.onload = (function(_this) {
        return function() {
          CUI.dom.setAttribute(img, "src", src);
          CUI.dom.remove(img.__placeholder);
          onDone();
        };
      })(this);
      image.onerror = (function(_this) {
        return function() {
          console.error("Error loading an image.", img, src);
          onDone();
        };
      })(this);
      image.src = src;
    }
    promise = deferred.promise();
    CUI.dom.data(image, "observer-promise", promise);
    return promise;
  };

  return IntersectionObserver;

})();

CUI.ready(function() {
  return EAS.IntersectionObserver.init();
});
// Generated by CoffeeScript 1.12.7
var AclRights,
  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;

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

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

  AclRights.prototype.load = function() {
    return ez5.api.right({
      data: ez5.session.fylrCacheParams()
    }).done((function(_this) {
      return function(__contexts) {
        _this.__contexts = __contexts;
      };
    })(this));
  };

  AclRights.prototype.getContexts = function() {
    return this.__contexts;
  };

  AclRights.prototype.getContext = function(context) {
    var server_context;
    server_context = AclRights.getServerContextByFrontendContext(context);
    context = this.__contexts[server_context];
    CUI.util.assert(context, "AclRights.getContext", "Could not find server context \"" + server_context + "\".", {
      context: context
    });
    return context;
  };

  AclRights.prototype.byContext = function(context) {
    var aclRights, right, rights;
    rights = this.getContext(context).rights;
    aclRights = (function() {
      var i, len, results;
      results = [];
      for (i = 0, len = rights.length; i < len; i++) {
        right = rights[i];
        results.push(AclRight.newInstance(right, context));
      }
      return results;
    })();
    CUI.util.assert(aclRights.length > 0, "AclRights.byContext", "no rights found for context: " + (CUI.util.getObjectClass(context)), {
      byContext: context,
      contexts: this.__contexts
    });
    return aclRights;
  };

  AclRights.prototype.byName = function(context, name) {
    var aclRights, i, len, ref;
    ref = this.byContext(context);
    for (i = 0, len = ref.length; i < len; i++) {
      aclRights = ref[i];
      if (alRight.getName() === name) {
        return aclRight;
      }
    }
    return CUI.util.assert(false, "AclRight.byName", "Unknown right " + name + " in context " + (CUI.util.getObjectClass(context)), {
      context: context,
      name: name
    });
  };

  AclRights.prototype.hasCapByFrontendContext = function(cap, context) {
    if (this.getContext(context).capabilities[cap]) {
      return true;
    } else {
      return false;
    }
  };

  AclRights.prototype.hasCapByServerContext = function(cap, context) {
    if (this.__contexts[context].capabilities[cap]) {
      return true;
    } else {
      return false;
    }
  };

  AclRights.contextMap = function() {
    return {
      "user": window.User,
      "group": window.Group,
      "pool": window.Pool,
      "object": window.AclField,
      "tag": window.Tag,
      "collection": window.CollectionStorable,
      "objecttype-without-pool": window.ObjecttypeWithoutPoolListViewItem,
      "system": "SystemAclRight"
    };
  };

  AclRights.getServerContextByFrontendContext = function(context, do_assert) {
    var frontend_context, ref, server_context;
    if (do_assert == null) {
      do_assert = true;
    }
    ref = this.contextMap();
    for (server_context in ref) {
      frontend_context = ref[server_context];
      if (CUI.util.isFunction(frontend_context)) {
        if (context instanceof frontend_context || context === frontend_context) {
          return server_context;
        }
      } else {
        if (context === frontend_context) {
          return server_context;
        }
      }
    }
    if (do_assert) {
      return CUI.util.assert(false, "AclRights.getServerContextByFrontendContext", "Unknown context " + (CUI.util.getObjectClass(context)), {
        context: context
      });
    } else {
      return null;
    }
  };

  AclRights.getFrontendContextByServerContext = function(server_context) {
    return this.contextMap()[server_context] || null;
  };

  AclRights.getDisplaynameByServerContext = function(server_context) {
    return $$("acl.rights.context." + server_context);
  };

  return AclRights;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var AclRightManager,
  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;

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

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

  AclRightManager.prototype.initOpts = function() {
    AclRightManager.__super__.initOpts.call(this);
    return this.addOpts({
      context: {
        mandatory: true
      },
      data: {
        mandatory: true,
        check: "PlainObject"
      },
      name: {
        mandatory: true,
        check: String
      },
      filter: {
        check: Function
      }
    });
  };

  AclRightManager.prototype.readOpts = function() {
    AclRightManager.__super__.readOpts.call(this);
    if (!this._data[this._name]) {
      this._data[this._name] = {};
    }
    return CUI.util.assert(CUI.util.isPlainObject(this.getData()), "new AclRightManager", "opts.data[opts.name] needs to be PlainObject", {
      opts: this.opts
    });
  };

  AclRightManager.prototype.getData = function() {
    return this._data[this._name];
  };

  AclRightManager.prototype.getField = function(_opts) {
    var opts;
    if (_opts == null) {
      _opts = {};
    }
    opts = CUI.Element.readOpts(_opts, "AclRightManager.getField", {
      onDataChanged: {
        check: Function
      }
    });
    return {
      type: CUI.FormModal,
      modal: {
        pane: {
          header_left: new CUI.Label({
            text: $$("acl.right.manager.modal.title")
          }),
          padded: true
        },
        "class": "ez5-acl-right-manager-popover",
        size: "xl",
        fill_space: "vertical",
        cancel: true,
        onCancel: function(ev, modal, has_changes) {
          if (has_changes) {
            return CUI.confirm({
              text: $$("acl.right.manager.modal.confirm_cancel")
            });
          }
        },
        onShow: (function(_this) {
          return function(modal) {
            var label, titleText, userType, who;
            who = _this._context.aclManager.getAclWhoManager().getWho(_this._data);
            titleText = $$("acl.right.manager.modal.title");
            if (who) {
              userType = "";
              if (who instanceof AclWhoUser) {
                userType = $$("acl.who.manager.who_placeholder_user");
              }
              if (who instanceof AclWhoGroup) {
                userType = $$("acl.who.manager.who_placeholder_group");
              }
              titleText = $$("acl.right.manager.modal.title.user", {
                name: who.getDisplayText(),
                type: userType
              });
            }
            label = new CUI.Label({
              text: titleText
            });
            return modal.replace(label, "header_left");
          };
        })(this),
        apply_button: {
          loca_key: "acl.right.manager.modal.button_apply",
          primary: true,
          onClick: (function(_this) {
            return function(ev, btn) {
              if (ev.hasModifierKey()) {
                console.debug("AclRightManager[data]:", _this.getData());
                return false;
              }
            };
          })(this)
        }
      },
      fields: (function(_this) {
        return function() {
          return _this.getFormFields();
        };
      })(this),
      "class": "ez5-right-manager-form",
      onDataChanged: (function(_this) {
        return function(data, df) {
          return typeof opts.onDataChanged === "function" ? opts.onDataChanged(data, df) : void 0;
        };
      })(this),
      name: this._name,
      data: this._data,
      button: {
        text: $$("acl.right.manager.button")
      },
      renderDisplayContent: (function(_this) {
        return function(df) {
          var aclRight, c, content, div, i, j, lb, len, len1, ref;
          content = [];
          ref = ez5.aclRights.byContext(_this._context);
          for (i = 0, len = ref.length; i < len; i++) {
            aclRight = ref[i];
            lb = aclRight.getDisplayLabel(_this.getData());
            if (lb) {
              content.push(lb);
            }
          }
          div = CUI.dom.div(CUI.__ng__ ? "ez5-tag-holder" : "ez5-acl-right-manager-rights");
          if (content.length) {
            for (j = 0, len1 = content.length; j < len1; j++) {
              c = content[j];
              CUI.dom.append(div, c.DOM);
            }
          } else {
            CUI.dom.append(div, new CUI.EmptyLabel({
              text: $$("acl.right.manager.no_rights_defined")
            }).DOM);
          }
          return div;
        };
      })(this)
    };
  };

  AclRightManager.prototype.getFormFields = function() {
    var _groupsByName, aclRight, field, fields, formFields, getGroupsForm, groupName, groups, groupsByName, i, isSystemContext, j, len, len1, ref, ref1, type;
    groupsByName = {
      system: {},
      plugin: {}
    };
    ref = ez5.aclRights.byContext(this._context);
    for (i = 0, len = ref.length; i < len; i++) {
      aclRight = ref[i];
      fields = aclRight.getFields();
      if (this._filter) {
        fields = fields.filter(this._filter);
      }
      if (fields.length === 0) {
        continue;
      }
      groupName = aclRight.group();
      isSystemContext = AclRights.getServerContextByFrontendContext(this._context) === "system";
      if (isSystemContext) {
        _groupsByName = aclRight.isSystem() ? groupsByName.system : groupsByName.plugin;
      } else {
        _groupsByName = groupsByName.system;
      }
      if (!_groupsByName[groupName]) {
        _groupsByName[groupName] = [];
      }
      for (j = 0, len1 = fields.length; j < len1; j++) {
        field = fields[j];
        _groupsByName[groupName].push(field);
      }
    }
    getGroupsForm = (function(_this) {
      return function(groups) {
        var blkTitle, blkTitleKey, group, groupFields;
        groupFields = [];
        for (groupName in groups) {
          group = groups[groupName];
          if (groupName === "zzz") {
            continue;
          }
          blkTitleKey = "acl.right.manager.group." + (AclRights.getServerContextByFrontendContext(_this._context)) + "." + groupName;
          if (ez5.session.isDebug()) {
            blkTitle = blkTitleKey;
          } else {
            blkTitle = $$(blkTitleKey);
          }
          groupFields.push({
            type: CUI.Form,
            render_as_block: true,
            form: {
              label: blkTitle
            },
            fields: group
          });
        }
        return groupFields;
      };
    })(this);
    fields = [];
    for (type in groupsByName) {
      groups = groupsByName[type];
      if (Object.keys(groups).length === 0) {
        continue;
      }
      formFields = getGroupsForm(groups);
      if (((ref1 = groups.zzz) != null ? ref1.length : void 0) > 0) {
        formFields = groups.zzz.concat(formFields);
      }
      fields.push({
        type: CUI.Form,
        render_as_block: true,
        form: {
          label: $$("acl.right.manager.header." + type)
        },
        fields: formFields
      });
    }
    return fields;
  };

  AclRightManager.prototype.getForm = function(_opts) {
    var opts;
    if (_opts == null) {
      _opts = {};
    }
    opts = CUI.Element.readOpts(_opts, "AclRightManager.getForm", {
      onDataChanged: {
        check: Function
      }
    });
    return new CUI.Form({
      "class": "ez5-right-manager-form",
      data: this.getData(),
      onDataChanged: (function(_this) {
        return function(data, df) {
          return typeof opts.onDataChanged === "function" ? opts.onDataChanged(data, df) : void 0;
        };
      })(this),
      appearance: "separators",
      fields: this.getFormFields()
    });
  };

  AclRightManager.prototype.getSaveData = function() {
    return CUI.util.copyObject(this.getData(), true);
  };

  return AclRightManager;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var AclRight,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function AclRight(opts1) {
    this.opts = opts1 != null ? opts1 : {};
    this.remove = bind(this.remove, this);
    this.equals = bind(this.equals, this);
    this.getDisplayName = bind(this.getDisplayName, this);
    this.setAclRightManager = bind(this.setAclRightManager, this);
    if (this.opts instanceof AclRight) {
      this.opts = this.opts.opts;
    }
    AclRight.__super__.constructor.call(this, this.opts);
  }

  AclRight.prototype.initOpts = function() {
    AclRight.__super__.initOpts.call(this);
    return this.addOpts({
      right: {
        check: "PlainObject"
      },
      context: {}
    });
  };

  AclRight.prototype.readOpts = function() {
    AclRight.__super__.readOpts.call(this);
    this.__right = this._right;
    this.__context = this._context;
    this.__serverContext = AclRights.getServerContextByFrontendContext(this.__context);
    this.state = {};
    return this.setActive(true);
  };

  AclRight.prototype.name = function() {
    return this.__right.name;
  };

  AclRight.prototype.group = function() {
    return this.__right.group || 'zzz';
  };

  AclRight.prototype.getLocaKey = function() {
    return "server.right." + this.__serverContext + "." + this.__right.name;
  };

  AclRight.prototype.getParameterLocaKey = function(parm) {
    return this.getLocaKey() + ".parm." + parm;
  };

  AclRight.prototype.nameLocalized = function() {
    if (ez5.session.isDebug()) {
      return this.__right.name;
    } else {
      return $$(this.getLocaKey());
    }
  };

  AclRight.prototype.getLabelForParameter = function(parm) {
    if (ez5.session.isDebug()) {
      return parm;
    } else {
      return $$(this.getParameterLocaKey(parm));
    }
  };

  AclRight.prototype.setAclRightManager = function(aclRightManager) {
    this.aclRightManager = aclRightManager;
  };

  AclRight.prototype.getDisplayName = function() {
    return this.__right.name;
  };

  AclRight.prototype.getField = function(context) {
    var c, cbKey, cbLbl, fields, i, j, len, len1, options, ref, ref1, regexp, rparm, txt;
    CUI.util.assert(!context, "AclRight.getField", "context is obsolete");
    fields = [];
    if (this.__right.has_grantable) {
      fields.push({
        name: "_grantable",
        type: CUI.Checkbox,
        undo_support: false,
        text: ez5.session.isDebug() ? "_grantable" : $$("acl.right.grantable")
      });
    }
    if (this.__right.parameters) {
      ref = this.__right.parameters;
      for (i = 0, len = ref.length; i < len; i++) {
        rparm = ref[i];
        switch (rparm.type) {
          case "int":
            fields.push({
              form: {
                label: this.getLabelForParameter(rparm.name)
              },
              type: CUI.NumberInput,
              name: rparm.name
            });
            break;
          case "text":
            if (!CUI.util.isEmpty(rparm.regex)) {
              regexp = rparm.regex;
            } else {
              regexp = null;
            }
            fields.push({
              form: {
                label: this.getLabelForParameter(rparm.name)
              },
              type: CUI.Input,
              regexp: regexp,
              placeholder: regexp,
              undo_and_changed_support: false,
              name: rparm.name
            });
            break;
          case "bool":
            cbKey = this.getParameterLocaKey("label." + rparm.name);
            if (ez5.session.isDebug()) {
              cbLbl = "loca_key:" + cbKey;
            } else if (ez5.loca.has(cbKey)) {
              cbLbl = $$(cbKey);
            } else {
              cbLbl = void 0;
            }
            fields.push({
              type: CUI.Checkbox,
              undo_and_changed_support: false,
              text: this.getLabelForParameter(rparm.name),
              form: {
                label: cbLbl
              },
              name: rparm.name
            });
            break;
          case "string-list":
          case "string-list-one":
          case "string-list-one-or-zero":
          case "eas-class-list":
            options = [];
            if (CUI.util.isEmpty(rparm.choices)) {
              continue;
            }
            ref1 = rparm.choices;
            for (j = 0, len1 = ref1.length; j < len1; j++) {
              c = ref1[j];
              if (rparm.localization === false) {
                txt = c;
              } else {
                if (ez5.session.isDebug()) {
                  txt = c;
                } else {
                  txt = $$(this.getParameterLocaKey(rparm.name) + ".option." + c);
                }
              }
              options.push({
                text: txt,
                value: c
              });
            }
            if (rparm.sort_choices) {
              options.sort(function(a, b) {
                return CUI.util.compareIndex(a.text.toLocaleLowerCase(), b.text.toLocaleLowerCase());
              });
            }
            (function(_this) {
              return (function(rparm) {
                var hintKey, hintLabel, k, len2, min_checked, opt, radio, radio_unchecked_value;
                switch (rparm.type) {
                  case "string-list-one-or-zero":
                    radio = true;
                    min_checked = 0;
                    for (k = 0, len2 = options.length; k < len2; k++) {
                      opt = options[k];
                      opt.value_unchecked = null;
                    }
                    radio_unchecked_value = null;
                    break;
                  case "string-list-one":
                    radio = true;
                    min_checked = 1;
                    break;
                  case "string-list":
                  case "eas-class-list":
                    radio = false;
                    min_checked = void 0;
                }
                hintLabel = void 0;
                hintKey = _this.getParameterLocaKey(rparm.name + "|hint");
                if (ez5.loca.has(hintKey)) {
                  hintLabel = $$(hintKey);
                }
                return fields.push({
                  type: CUI.Options,
                  horizontal: true,
                  form: {
                    label: _this.getLabelForParameter(rparm.name),
                    hint: hintLabel
                  },
                  horizontal: Math.ceil(options.length / 5),
                  undo_and_changed_support: false,
                  radio_unchecked_value: radio_unchecked_value,
                  maximize_horizontal: true,
                  data: function(data) {
                    if (!data.hasOwnProperty(rparm.name) && min_checked === 1) {
                      data[rparm.name] = rparm.choices[0];
                    }
                    return data;
                  },
                  name: rparm.name,
                  radio: radio,
                  min_checked: min_checked,
                  options: options
                });
              });
            })(this)(rparm);
            break;
          case "mask-select":
            fields.push(this.getFieldForMaskSelectParameter(rparm));
            break;
          case "objecttype-select":
            fields.push(this.getFieldForObjecttypeSelectParameter(rparm));
            break;
          case "eas-column-select":
            fields.push(this.getFieldForEasColumnsSelectParameter(rparm));
            break;
          case "pool-select":
            fields.push(this.getFieldForPoolSelectParameter(rparm));
            break;
          case "preview-versions":
            fields.push(this.getFieldForPreviewVersionsParameter(rparm));
            break;
          default:
            fields.push({
              type: CUI.DataFieldProxy,
              element: CUI.dom.textEmpty(rparm.name + (": type \"" + rparm.type + "\" unsupported."))
            });
        }
      }
    }
    return {
      type: CUI.Form,
      "class": "acl-right-parameter-form",
      fields: fields,
      undo_and_changed_support: false,
      data: this.data,
      name: this.name(),
      form: {
        checkbox: {
          text: this.nameLocalized()
        }
      }
    };
  };

  AclRight.prototype.getFields = function(context) {
    return [this.getField(context)];
  };

  AclRight.prototype.getFieldForMaskSelectParameter = function(rparm) {
    var f, fields, i, len;
    if (this.__context instanceof ObjecttypeListViewItem) {
      fields = Pool.prototype.standard_mask_fields({
        forObjecttype: this.__context.objecttype
      });
    } else if (this.__context === ObjecttypeListViewItem) {
      fields = Pool.prototype.standard_mask_fields({
        forObjecttype: true
      });
    } else if (this.__context instanceof Pool || this.__context === Pool) {
      fields = Pool.prototype.standard_mask_fields({
        forPoolAcl: true
      });
    } else if (this.__context === "SystemAclRight") {
      fields = Pool.prototype.standard_mask_fields({
        forObjecttype: true
      });
    } else {
      return {
        type: CUI.Output,
        text: rparm.name + ": type \"" + rparm.type + "\" unsupported context \"" + this.__context + "\"."
      };
    }
    for (i = 0, len = fields.length; i < len; i++) {
      f = fields[i];
      f.name = f.name.split("_")[1];
      f.data = function(data, df) {
        var parm_data;
        parm_data = df.getForm().getData();
        if (!parm_data[rparm.name]) {
          parm_data[rparm.name] = {};
        }
        return parm_data[rparm.name];
      };
    }
    return {
      type: CUI.Form,
      fields: fields
    };
  };

  AclRight.prototype.getFieldForObjecttypeSelectParameter = function(rparm) {
    var i, lbl, len, opts, ot, ref, txt;
    opts = [];
    ref = ez5.schema.CURRENT._objecttypes;
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      if (ot._instance) {
        continue;
      }
      if (this.__context instanceof Pool) {
        if (!ot.pool_link) {
          continue;
        }
      }
      if (this.__context instanceof Collection) {
        if (!ot.in_main_search) {
          continue;
        }
      }
      if (ez5.session.isDebug()) {
        txt = ot.name + " [" + ot.table_id + "]";
      } else {
        txt = ot._name_localized;
      }
      opts.push({
        text: txt,
        value: ot.table_id
      });
    }
    if (ez5.session.isDebug()) {
      lbl = rparm.name;
    } else {
      lbl = $$("acl.right.objecttypes.label");
    }
    return {
      type: CUI.Options,
      horizontal: true,
      columns: 2,
      "class": 'ez5-objecttype-picker-list',
      form: {
        label: lbl
      },
      name: rparm.name,
      options: opts
    };
  };

  AclRight.prototype.getFieldForPoolSelectParameter = function(rparm) {
    var pf, poolField;
    pf = new PoolFieldForEditor();
    poolField = pf.renderEditorInput(null, null, {
      editor: this,
      onDataChanged: (function(_this) {
        return function(data, df) {
          var opt_df, pool_id;
          opt_df = df.getOtherField(rparm.name);
          pool_id = data[pf.name()].pool._id;
          if (pool_id && data[rparm.name] && indexOf.call(data[rparm.name], pool_id) < 0) {
            data[rparm.name].push(pool_id);
            opt_df.reload();
          }
          return delete data[pf.name()];
        };
      })(this)
    });
    return {
      type: CUI.Form,
      fields: [
        poolField, {
          type: CUI.Options,
          placeholder: $$("acl.right.pools.placeholder"),
          name: rparm.name,
          onDataChanged: (function(_this) {
            return function(data, df, ev) {
              return df.reload();
            };
          })(this),
          options: function(df) {
            var data, i, len, pool_id, ref, ref1, results;
            data = df.getData();
            ref = data[rparm.name];
            results = [];
            for (i = 0, len = ref.length; i < len; i++) {
              pool_id = ref[i];
              results.push({
                text: ((ref1 = ez5.pools.findPoolById(pool_id)) != null ? ref1.getDisplayText() : void 0) || "<" + pool_id + ">",
                value: pool_id
              });
            }
            return results;
          }
        }
      ]
    };
  };

  AclRight.prototype.getFieldForEasColumnsSelectParameter = function(rparm) {
    var eas_fields, otm;
    otm = new ObjecttypeManager().addObjecttypes();
    eas_fields = otm.getEASFields('all', (function(_this) {
      return function(ot) {
        if (_this.__context instanceof ObjecttypeListViewItem && _this.__context.getObjecttype().id() !== ot.id()) {
          return false;
        } else {
          return true;
        }
      };
    })(this), false);
    return AclRight.getFieldColumnSelector({
      name: rparm.name,
      label: this.getLabelForParameter(rparm.name),
      fields: eas_fields
    });
  };

  AclRight.getFieldColumnSelector = function(_opts) {
    var f, fieldById, fieldKey, fieldsByObjecttype, fullNameFunc, get_col_opts, i, inkl_tn, len, nameFunc, objecttypes, opts, ot, ot_fields, ref, sort_by_name;
    if (_opts == null) {
      _opts = {};
    }
    opts = CUI.Element.readOpts(_opts, 'AclRight.getFieldColumnSelector', {
      name: {
        mandatory: true,
        check: String
      },
      label: {
        check: String
      },
      placeholder_loca: {
        check: String,
        "default": $$("acl.right.column_select.placeholder.all_columns")
      },
      fields: {
        mandatory: true,
        check: function(v) {
          var f, i, len;
          if (!CUI.util.isArray(v) && v.length > 0) {
            return false;
          }
          for (i = 0, len = v.length; i < len; i++) {
            f = v[i];
            if (!(f instanceof Field)) {
              return false;
            }
          }
          return true;
        }
      }
    });
    objecttypes = [];
    fieldById = {};
    fieldsByObjecttype = {};
    ref = opts.fields;
    for (i = 0, len = ref.length; i < len; i++) {
      f = ref[i];
      ot = new Objecttype(f.getMainMask().table);
      ot_fields = fieldsByObjecttype[ot.id()];
      if (!ot_fields) {
        fieldsByObjecttype[ot.id()] = ot_fields = [];
        objecttypes.push(ot);
      }
      ot_fields.push(f);
      fieldKey = f.getKeyInRights();
      if (!fieldById[fieldKey]) {
        fieldById[fieldKey] = [];
      }
      fieldById[fieldKey].push(f);
    }
    sort_by_name = function(func) {
      return function(a, b) {
        return a[func]().localeCompare(b[func]());
      };
    };
    if (ez5.session.isDebug()) {
      fullNameFunc = 'fullName';
      nameFunc = 'name';
    } else {
      fullNameFunc = 'fullNameLocalized';
      nameFunc = 'nameLocalized';
    }
    objecttypes.sort(sort_by_name(nameFunc));
    get_col_opts = (function(_this) {
      return function(data) {
        var col_opts, disable_all, disabled, fields, j, k, len1, len2, ref1;
        col_opts = [
          {
            text: $$("acl.right.select.choose"),
            disabled: true,
            value: null
          }, {
            text: $$("acl.right.select.add_all"),
            value: true
          }
        ];
        disable_all = true;
        for (j = 0, len1 = objecttypes.length; j < len1; j++) {
          ot = objecttypes[j];
          fields = fieldsByObjecttype[ot.id()];
          if (fields.length === 0) {
            continue;
          }
          if (objecttypes.length > 1) {
            col_opts.push({
              label: ot.nameLocalized()
            });
          }
          ref1 = fields.sort(sort_by_name(fullNameFunc));
          for (k = 0, len2 = ref1.length; k < len2; k++) {
            f = ref1[k];
            fieldKey = f.getKeyInRights();
            disabled = data && indexOf.call(data[opts.name], fieldKey) >= 0;
            if (!disabled) {
              disable_all = false;
            }
            col_opts.push({
              text: f[fullNameFunc](),
              value: f,
              disabled: disabled
            });
          }
        }
        col_opts[1].disabled = disable_all;
        return col_opts;
      };
    })(this);
    inkl_tn = objecttypes.length > 1;
    return {
      type: CUI.Form,
      form: {
        label: opts.label
      },
      fields: [
        {
          type: CUI.Select,
          check_changed: false,
          options: function(df) {
            var data, ref1;
            data = (ref1 = df.getOtherField(opts.name)) != null ? ref1.getData() : void 0;
            return get_col_opts(data);
          },
          onDataChanged: (function(_this) {
            return function(data, df) {
              var col_arr, col_id, col_opts, field, j, len1, ref1;
              col_opts = df.getOtherField(opts.name);
              col_arr = col_opts.getValue();
              if (data.col === true) {
                ref1 = opts.fields;
                for (j = 0, len1 = ref1.length; j < len1; j++) {
                  field = ref1[j];
                  fieldKey = field.getKeyInRights();
                  CUI.util.pushOntoArray(fieldKey, col_arr);
                }
              } else {
                col_id = data.col.getKeyInRights();
                CUI.util.pushOntoArray(col_id, col_arr);
              }
              col_arr.sort(function(a, b) {
                return fieldById[a][0][fullNameFunc]().localeCompare(fieldById[b][0][fullNameFunc]());
              });
              col_opts.reload();
              return df.setValue(null);
            };
          })(this),
          name: 'col',
          data: {}
        }, {
          type: CUI.Options,
          name: opts.name,
          placeholder: opts.placeholder_loca,
          onDataChanged: (function(_this) {
            return function(data, df, ev) {
              return df.reload();
            };
          })(this),
          onDataInit: (function(_this) {
            return function(df, data) {
              if (CUI.util.isArray(data[opts.name])) {
                CUI.util.removeFromArray(null, data[opts.name], function(col_id) {
                  return !fieldById[col_id];
                });
              }
            };
          })(this),
          options: function(df) {
            var col_id, content, data, items, j, len1, options, ref1;
            data = df.getData();
            options = [];
            ref1 = data[opts.name];
            for (j = 0, len1 = ref1.length; j < len1; j++) {
              col_id = ref1[j];
              content = CUI.dom.ul("ez5-acl-right-field-column-options");
              items = fieldById[col_id].map((function(_this) {
                return function(field) {
                  var li;
                  li = CUI.dom.li();
                  CUI.dom.append(li, field[fullNameFunc](inkl_tn, inkl_tn));
                  return li;
                };
              })(this));
              CUI.dom.append(content, items);
              options.push({
                content: content,
                value: col_id
              });
            }
            return options;
          }
        }
      ]
    };
  };

  AclRight.prototype.getFieldForPreviewVersionsParameter = function(rparm) {
    var cls, config, def, fields, i, j, lbl, len, len1, opts, ref, ref1, txt;
    config = ez5.session.getEASConfig();
    fields = [];
    ref = Asset.fileclasses();
    for (i = 0, len = ref.length; i < len; i++) {
      cls = ref[i];
      if (ez5.session.isDebug()) {
        txt = "original";
      } else {
        txt = $$("acl.right.version.original");
      }
      opts = [
        {
          text: txt,
          value: cls + ".original"
        }
      ];
      if (config[cls]) {
        ref1 = config[cls].versions;
        for (j = 0, len1 = ref1.length; j < len1; j++) {
          def = ref1[j];
          if (!def.rightsmanagement) {
            continue;
          }
          if (ez5.session.isDebug()) {
            txt = def.version;
          } else {
            if (def.displayname && !CUI.util.isEmpty(ez5.loca.getBestFrontendValue(def.displayname))) {
              txt = ez5.loca.getBestFrontendValue(def.displayname);
            } else {
              txt = def.size_print || def.version;
            }
          }
          opts.push({
            text: txt,
            value: cls + "." + def.version
          });
        }
      }
      if (ez5.session.isDebug()) {
        lbl = cls;
      } else {
        lbl = $$("server.eas.fileclass." + cls);
      }
      fields.push({
        type: CUI.Options,
        horizontal: true,
        form: {
          label: lbl
        },
        name: rparm.name,
        options: opts,
        horizontal: true
      });
    }
    return {
      type: CUI.Form,
      fields: fields
    };
  };

  AclRight.prototype.getDisplayLabel = function(data) {
    var d;
    d = data[this.name()];
    if (!d) {
      return null;
    }
    return new CUI.Label({
      "class": "ez5-acl-right-label ez5-tag",
      text: this.nameLocalized()
    });
  };

  AclRight.prototype.getName = function() {
    return this.__right.name;
  };

  AclRight.prototype.setActive = function(aclRights, on_off) {
    if (on_off == null) {
      on_off = null;
    }
    if (on_off === null) {
      on_off = this.isInList(aclRights);
    }
    this.state[this.getName()] = on_off;
    if (on_off) {
      if (!this.isInList(aclRights)) {
        aclRights.push(this);
      }
    } else {
      if (this.isInList(aclRights)) {
        CUI.util.removeFromArray(this, aclRights, "equals");
      }
    }
    return this;
  };

  AclRight.prototype.isInList = function(aclRights) {
    var aclRight, i, len;
    for (i = 0, len = aclRights.length; i < len; i++) {
      aclRight = aclRights[i];
      if (aclRight.equals(this)) {
        return true;
      }
    }
    return false;
  };

  AclRight.prototype.equals = function(aclRightComp) {
    if (!aclRightComp) {
      return false;
    }
    CUI.util.assert(aclRightComp instanceof AclRight, "AclRight.equals", "Unable to compare aclRight", {
      aclRight: this,
      aclRightComp: aclRightComp
    });
    return aclRightComp.opts.right.name === this.__right.name;
  };

  AclRight.prototype.remove = function() {
    return this.aclRightManager.removeAclRight(this);
  };

  AclRight.prototype.isSystem = function() {
    var ref;
    return (ref = this.__right.name) != null ? ref.startsWith("system.") : void 0;
  };

  AclRight.newInstance = function(right, context) {
    var func;
    CUI.util.assert(CUI.util.isPlainObject(right), "AclRight.newInstance", "right needs to be plain object");
    if (right.type && right.type !== "right") {
      func = "AclRight" + CUI.util.toCamel(right.type, true);
    } else {
      func = "AclRight";
    }
    CUI.util.assert(CUI.util.isFunction(window[func]), "AclRight.newInstance", "Received unknown type for right: " + right.type, {
      right: right
    });
    return new window[func]({
      right: right,
      context: context
    });
  };

  AclRight.getDisplayForGeneratedRights = function(server_context, rights) {
    var def, div, right, rkey;
    if (rights == null) {
      rights = {};
    }
    div = CUI.dom.element("DIV", {
      "class": "ez5-tag-holder"
    });
    for (right in rights) {
      def = rights[right];
      if (ez5.session.isDebug()) {
        rkey = right;
      } else {
        rkey = "server.right." + server_context + "." + right;
      }
      CUI.dom.append(div, new CUI.Label({
        "class": "ez5-acl-right-label ez5-tag",
        text: rkey
      }));
    }
    return div;
  };

  return AclRight;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var AclRightChoice,
  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;

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

  function AclRightChoice(opts) {
    var i, len, ref, right;
    this.opts = opts;
    AclRightChoice.__super__.constructor.call(this, this.opts);
    this.rights = [];
    ref = this.__right.rights;
    for (i = 0, len = ref.length; i < len; i++) {
      right = ref[i];
      this.rights.push(AclRight.newInstance(right, this.__context));
    }
    this;
  }

  AclRightChoice.prototype.getDisplayText = function(data) {
    var i, len, r, ref;
    ref = this.rights;
    for (i = 0, len = ref.length; i < len; i++) {
      r = ref[i];
      if (data[r.name()]) {
        return r.getDisplayText(data);
      }
    }
  };

  AclRightChoice.prototype.getDisplayLabel = function(data) {
    var i, len, r, ref;
    ref = this.rights;
    for (i = 0, len = ref.length; i < len; i++) {
      r = ref[i];
      if (data[r.name()]) {
        return r.getDisplayLabel(data);
      }
    }
    return null;
  };

  AclRightChoice.prototype.getFields = function(context) {
    var field, fields, i, len, r, ref;
    fields = [];
    ref = this.rights;
    for (i = 0, len = ref.length; i < len; i++) {
      r = ref[i];
      field = r.getField(context);
      field.form.checkbox.radio = this.name();
      field.form.checkbox.radio_allow_null = true;
      fields.push(field);
    }
    return fields;
  };

  return AclRightChoice;

})(AclRight);
// Generated by CoffeeScript 1.12.7
var AssetDetail,
  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;

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

  function AssetDetail(opts) {
    if (!opts) {
      return;
    }
    AssetDetail.__super__.constructor.call(this, opts);
    this.registeredPlugins = [];
    this.clsName = CUI.util.getObjectClass(this).toLowerCase();
  }

  AssetDetail.prototype.initOpts = function() {
    AssetDetail.__super__.initOpts.call(this);
    return this.addOpts({
      element: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isElement(v);
        }
      },
      editor_mode: {
        "default": false,
        mandatory: true,
        check: Boolean
      }
    });
  };

  AssetDetail.prototype.getButtonLocaKey = function(asset) {
    return this.clsName;
  };

  AssetDetail.prototype.isPlayer = function() {
    return false;
  };

  AssetDetail.prototype.getLabelLocaKey = function(asset) {
    return this.getButtonLocaKey(asset);
  };

  AssetDetail.prototype.isButtonSwitch = function() {
    return null;
  };

  AssetDetail.prototype.startOnMousewheel = function() {
    return false;
  };

  AssetDetail.prototype.preventOnMousewheelIfActive = function() {
    return true;
  };

  AssetDetail.prototype.startAutomatically = function() {
    return false;
  };

  AssetDetail.prototype.getAsset = function() {
    return this.asset;
  };

  AssetDetail.prototype.getLabel = function() {
    return this.__label;
  };

  AssetDetail.prototype.start = function(asset1, mouseWheelstart) {
    var buttonbar, closeBtn, fullscreenBtn, loca_key;
    this.asset = asset1;
    this.mouseWheelstart = mouseWheelstart != null ? mouseWheelstart : false;
    if (!CUI.dom.isInDOM(this._element)) {
      return;
    }
    CUI.dom.addClass(this._element, "asset-detail asset-detail-" + this.clsName);
    CUI.dom.addClass(this._element.parentElement, "has-asset-detail-tool has-asset-detail-" + this.clsName);
    loca_key = this.getLabelLocaKey(this.asset);
    if (loca_key) {
      if (CUI.util.isArray(loca_key)) {
        this.__label = new LocaLabel({
          loca_key: loca_key[0],
          loca_key_attrs: loca_key[1]
        });
      } else {
        this.__label = new LocaLabel({
          loca_key: loca_key
        });
      }
    } else {
      this.__label = null;
    }
    CUI.dom.exitFullscreen();
    this.createMarkup();
    fullscreenBtn = this.getFullscreenButton();
    closeBtn = new LocaButton({
      group: "a",
      loca_key: "asset.detail.button.close",
      ui: "asset.detail.fullscreen.close.button",
      icon: "close",
      appearance: "transparent-border",
      onClick: (function(_this) {
        return function() {
          _this.destroy();
          return CUI.Events.trigger({
            type: "viewport-resize"
          });
        };
      })(this)
    });
    buttonbar = new CUI.Buttonbar({
      buttons: [this.__label, fullscreenBtn, closeBtn],
      "class": "ez5-asset-detail-buttonbar"
    });
    CUI.dom.append(this.outerDiv, buttonbar.DOM);
    this.callbackPlugins("start");
    return this;
  };

  AssetDetail.prototype.getFullscreenButton = function() {
    if (!CUI.dom.fullscreenEnabled()) {
      return;
    }
    return new LocaButton({
      group: "a",
      "switch": true,
      loca_key: "asset.detail.button.fullscreen",
      ui: "asset.detail.fullscreen.button",
      activate_initial: false,
      appearance: "transparent-border",
      onActivate: (function(_this) {
        return function(btn) {
          CUI.dom.addClass(_this.outerDiv, "ez5-asset-detail-fullscreen");
          if (window.bowser.check({
            msie: "11"
          }, true)) {
            CUI.dom.append(document.body, _this.outerDiv);
          }
          CUI.dom.requestFullscreen(_this.outerDiv).progress(function() {
            _this.positionOuterDiv();
            return _this.resize();
          }).done(function() {
            return btn.deactivate({
              position_only: true
            });
          });
        };
      })(this),
      onDeactivate: (function(_this) {
        return function(btn, flags) {
          if (!flags.position_only) {
            return CUI.dom.exitFullscreen().done(function() {
              return _this.__resizeAfterDeactivate();
            });
          } else {
            return _this.__resizeAfterDeactivate();
          }
        };
      })(this)
    });
  };

  AssetDetail.prototype.__resizeAfterDeactivate = function() {
    if (!this.outerDiv) {
      return;
    }
    if (window.bowser.check({
      msie: "11"
    }, true)) {
      this.asset._tmpl.replace(this.outerDiv, "tool");
    }
    CUI.dom.removeClass(this.outerDiv, "ez5-asset-detail-fullscreen");
    this.positionOuterDiv();
    this.resize();
  };

  AssetDetail.prototype.destroy = function() {
    this.callbackPlugins("destroy");
    if (this._element) {
      CUI.dom.removeClass(this._element, "asset-detail asset-detail-" + this.clsName);
      if (this._element.parentElement) {
        CUI.dom.removeClass(this._element.parentElement, "has-asset-detail-tool has-asset-detail-" + this.clsName);
      }
    }
    if (this.outerDiv) {
      CUI.Events.ignore({
        instance: this
      });
      CUI.dom.remove(this.outerDiv);
      this.outerDiv = null;
    }
    AssetDetail.__super__.destroy.call(this);
  };

  AssetDetail.prototype.isActive = function() {
    return !!this.outerDiv;
  };

  AssetDetail.prototype.isDestroyed = function() {
    return this.outerDiv === null;
  };

  AssetDetail.prototype.plugins = function() {
    return [];
  };

  AssetDetail.prototype.getPlugins = function() {
    var i, j, k, len, len1, len2, p, plugins, ref, ref1;
    plugins = [];
    ref = this.plugins();
    for (i = 0, len = ref.length; i < len; i++) {
      p = ref[i];
      plugins.push(p);
    }
    ref1 = this.registeredPlugins;
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      p = ref1[j];
      plugins.push(p);
    }
    for (k = 0, len2 = plugins.length; k < len2; k++) {
      p = plugins[k];
      CUI.util.assert(p instanceof AssetDetailPlugin, "AssetDetail.registerPlugin", "Plugin needs to be an instance of AssetDetailPlugin", {
        plugin: p
      });
    }
    return plugins;
  };

  AssetDetail.prototype.registerPlugin = function(p) {
    if (p._asset_detail) {
      p.deregister();
    }
    p._asset_detail = this;
    this.registeredPlugins.push(p);
    p.register(this, this.registeredPlugins.length - 1);
    return this;
  };

  AssetDetail.prototype.deregisterPlugin = function(p) {
    var _p, i, idx, len, ref;
    ref = this.registeredPlugins;
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      _p = ref[idx];
      if (_p === p) {
        this.registeredPlugins.splice(idx, 1);
        return this;
      }
    }
    return this;
  };

  AssetDetail.prototype.scroll = function() {};

  AssetDetail.prototype.resize = function() {};

  AssetDetail.prototype.reload = function() {};

  AssetDetail.prototype.callbackPlugins = function(ev_type, info) {
    var i, len, p, ref;
    if (info == null) {
      info = {};
    }
    ref = this.getPlugins();
    for (i = 0, len = ref.length; i < len; i++) {
      p = ref[i];
      if (p[ev_type]) {
        p[ev_type](this, info);
      }
    }
    info.type = ev_type;
    info.tool = this;
    return CUI.Events.trigger({
      node: this._element,
      type: "asset-detail",
      info: info
    });
  };

  AssetDetail.prototype.getViewport = function() {
    return this.viewport;
  };

  AssetDetail.prototype.positionOuterDiv = function() {
    var dim, offset, rect;
    if (CUI.__ng__) {
      if (CUI.dom.hasClass(this.outerDiv, "ez5-asset-detail-fullscreen")) {
        this.viewport = {
          width: window.innerWidth,
          height: window.innerHeight
        };
      } else {
        rect = CUI.dom.getRect(this._element);
        this.viewport = {
          width: rect.width,
          height: rect.height
        };
      }
      return;
    }
    if (CUI.dom.hasClass(this.outerDiv, "ez5-asset-detail-fullscreen")) {
      dim = CUI.dom.getDimensions(document.body);
      this.viewport = {
        width: window.innerWidth,
        height: window.innerHeight
      };
      CUI.dom.setStylePx(this.outerDiv, {
        top: 0,
        left: 0,
        width: this.viewport.width,
        height: this.viewport.height
      });
    } else {
      rect = CUI.dom.getRect(this._element);
      this.viewport = {
        width: rect.width,
        height: rect.height
      };
      offset = {
        top: rect.top,
        left: rect.left
      };
      CUI.dom.setAbsolutePosition(this.outerDiv, offset);
      this.outerDiv.css({
        width: this.viewport.width,
        height: this.viewport.height
      });
    }
    return this;
  };

  AssetDetail.prototype.fadeIn = function(doneCallback) {
    this.outerDiv.fadeIn(350, (function(_this) {
      return function() {
        _this.callbackPlugins("fade-in");
        return typeof doneCallback === "function" ? doneCallback() : void 0;
      };
    })(this));
    return this;
  };

  AssetDetail.prototype.fadeOut = function(doneCallback) {
    this.outerDiv.fadeOut(350, (function(_this) {
      return function() {
        _this.callbackPlugins("fade-out");
        return typeof doneCallback === "function" ? doneCallback() : void 0;
      };
    })(this));
    return this;
  };

  AssetDetail.prototype.createMarkup = function() {
    var bb, btn_opts, buttons, el, i, idx, len, p, plug_btn, ref;
    this.outerDiv = CUI.dom.div("asset-detail-outer-div asset-detail-" + this.clsName, {
      ui: "asset.detail.outer.container"
    });
    this.asset._tmpl.replace(this.outerDiv, "tool");
    CUI.Events.listen({
      type: "viewport-resize",
      instance: this,
      node: this._element,
      call: (function(_this) {
        return function() {
          _this.positionOuterDiv();
          _this.resize();
        };
      })(this)
    });
    this.controls = CUI.dom.div("asset-detail-controls");
    CUI.dom.append(this.outerDiv, this.controls);
    buttons = [];
    ref = this.getPlugins();
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      p = ref[idx];
      if (p.render) {
        el = p.render();
        if (!el) {
          continue;
        }
        if (el.DOM) {
          CUI.dom.append(this.controls, el.DOM);
        } else {
          CUI.dom.append(this.controls, el);
        }
        CUI.dom.append(this.controls, CUI.dom.space());
      } else if (p.btn || p.button) {
        if (p.btn) {
          btn_opts = {
            "class": "asset-detail-plugin-" + p.btn,
            value: {
              plugin: idx
            }
          };
          if (p.icon) {
            btn_opts.icon = new CUI.Icon({
              icon: p.icon
            });
          } else if (p.label) {
            btn_opts.text = $$(p.label);
          } else {
            btn_opts.text = p.btn;
          }
        } else {
          btn_opts = CUI.util.copyObject(p.button);
          if (!btn_opts["class"]) {
            btn_opts["class"] = "";
          }
        }
        btn_opts["class"] += " asset-detail-plugin";
        if (this.opts.smallControls) {
          btn_opts["class"] += " btn-mini";
        }
        (function(p) {
          return btn_opts.onClick = function(ev, btn) {
            ev.stopPropagation();
            p.run(ev, btn);
          };
        })(p);
        btn_opts.group = "plugin";
        btn_opts.appearance = "transparent-border";
        plug_btn = new CUI.defaults["class"].Button(btn_opts);
        buttons.push(plug_btn);
      }
    }
    if (buttons.length > 0) {
      bb = new CUI.Buttonbar({
        buttons: buttons,
        "class": "ez5-asset-detail-plugin-buttons"
      });
      CUI.dom.append(this.controls, bb.DOM);
    }
    this.positionOuterDiv();
    return this;
  };

  AssetDetail.prototype.getOuterDiv = function() {
    return this.outerDiv;
  };

  return AssetDetail;

})(CUI.Plugin);

CUI.ready(function() {
  return CUI.Events.registerEvent({
    type: "asset-detail",
    bubble: true
  });
});
// Generated by CoffeeScript 1.12.7
var AssetDetailPlugin,
  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;

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

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

  AssetDetailPlugin.prototype.initOpts = function() {
    AssetDetailPlugin.__super__.initOpts.call(this);
    return this.addOpts(this.____opts);
  };

  AssetDetailPlugin.prototype.readOpts = function() {
    var i, key, len, ref, results;
    AssetDetailPlugin.__super__.readOpts.call(this);
    ref = Object.keys(this.____opts);
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      key = ref[i];
      results.push(this[key] = this["_" + key]);
    }
    return results;
  };

  AssetDetailPlugin.prototype.deregister = function() {
    CUI.util.assert(this.__assetDetail, (CUI.util.getObjectClass(this)) + ".deregister", "Plugin is not registered with any AssetDetail.", {
      plugin: this
    });
    this.__assetDetail.deregisterPlugin(this);
    this.__assetDetail = null;
    return this.__assetDetailIdx = null;
  };

  AssetDetailPlugin.prototype.register = function(assetDetail, idx) {
    CUI.util.assert(!this.__assetDetail && assetDetail instanceof AssetDetail, (CUI.util.getObjectClass(this)) + ".register", "Plugin cannot be registered for more than one AssetDetail. Also, assetDetail must be instanceof AssetDetail", {
      plugin: this,
      assetDetail: this.__assetDetail
    });
    this.__assetDetail = assetDetail;
    this.__assetDetailIdx = idx;
    return this;
  };

  AssetDetailPlugin.prototype.____opts = {
    btn: {
      check: String
    },
    button: {
      check: "PlainObject"
    },
    name: {
      check: String
    },
    run: {
      check: Function
    },
    icon: {
      check: String
    },
    label: {
      check: String
    },
    render: {
      check: Function
    },
    update: {
      check: Function
    },
    start: {
      check: Function
    },
    destroy: {
      check: Function
    }
  };

  return AssetDetailPlugin;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var Zoomer,
  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;

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

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

  Zoomer.prototype.readOpts = function() {
    Zoomer.__super__.readOpts.call(this);
    return this._debug = 0;
  };

  Zoomer.prototype.tileSize = 320;

  Zoomer.prototype.maxZoom = 8;

  Zoomer.prototype.getButtonLocaKey = function(asset) {
    if (this.getZoomerVersion(asset) && this.checkValidSizes(asset)) {
      return "zoomer.button.title";
    } else {
      return null;
    }
  };

  Zoomer.prototype.getLabelLocaKey = function() {
    return null;
  };

  Zoomer.prototype.getZoomerVersion = function(asset) {
    var ref, version;
    if ((ref = asset.value["class"]) !== "image" && ref !== "vector2d") {
      return;
    }
    version = Asset.getBestImageForViewport(asset, 1000000, 1000000, (function(_this) {
      return function(version) {
        var ref1, ref2, v, vname;
        if (ez5.version("6") && version.version === "original") {
          ref2 = (asset != null ? (ref1 = asset.value) != null ? ref1.versions : void 0 : void 0) || [];
          for (vname in ref2) {
            v = ref2[vname];
            if (vname === "original") {
              continue;
            }
            if (v.zoom_url && v.width === version.width && v.height === version.height) {
              return false;
            }
          }
          return true;
        }
        if (version.zoom_url) {
          return true;
        } else {
          return false;
        }
      };
    })(this));
    if (ez5.session.isDebug() && version) {
      console.debug("Zoomer selected version:", version.version);
    }
    return version;
  };

  Zoomer.prototype.checkValidSizes = function(asset) {
    if (!asset.getWidth() || !asset.getHeight()) {
      console.error("Zoomer.checkValidSizes", "width or height is 0", this.asset);
      return false;
    }
    return true;
  };

  Zoomer.prototype.start = function(asset1, mouseWheelstart) {
    var loc, version, zoomUrl;
    this.asset = asset1;
    this.mouseWheelstart = mouseWheelstart != null ? mouseWheelstart : false;
    this.__zoomerVersion = this.getZoomerVersion(this.asset);
    version = Asset.getStandardVersion(this.asset.value);
    this.__thumbnailUrl = Session.addToken(version.url);
    this.__width = this.asset.getWidth();
    this.__height = this.asset.getHeight();
    this.__zoomScale = this.__width / this.__zoomerVersion.width;
    zoomUrl = Session.addToken(this.__zoomerVersion.zoom_url);
    loc = CUI.parseLocation(zoomUrl);
    this.__url = loc.origin + loc.pathname;
    this.__url_search = loc.search + loc.hash;
    Zoomer.__super__.start.call(this, this.asset, this.mouseWheelstart);
    this.__firstTileLoaded = false;
    this.__waitBlock = new CUI.WaitBlock({
      element: this.outerDiv
    }).show();
    this.__zoomerLabel = new CUI.Label({
      text: "",
      "class": "ez5-asset-overlaying-label"
    });
    CUI.dom.append(this.controls, CUI.dom.space());
    CUI.dom.append(this.controls, this.__zoomerLabel);
    this.init();
    this.zoomIn();
    return this;
  };

  Zoomer.prototype.init = function() {
    this.zoom = null;
    this.innerDivTiles = {};
    this.innerDivPos = {};
    this.createMap();
    this.__setRotate();
    this.positionAndSizeZoomer();
    this.fitZoom();
    return this.callbackPlugins("init");
  };

  Zoomer.prototype.__setRotate = function() {
    var ref, ref1;
    this.__transform = this.asset.value.transform || [];
    this.rotate = EAS.getRotateMapFromTransform(this.__transform);
    this.width = this.__width;
    this.height = this.__height;
    if ((ref = this.rotate.z) === 90 || ref === 270) {
      ref1 = [this.height, this.width], this.width = ref1[0], this.height = ref1[1];
    }
    return this;
  };

  Zoomer.prototype.getZoom = function() {
    return this.zoom;
  };

  Zoomer.prototype.getMapZoom = function() {
    return this.map.zoom;
  };

  Zoomer.prototype.fitZoom = function() {
    return this.setZoomAndMove(this.fit.minimumZoom, this.fit.left, this.fit.top);
  };

  Zoomer.prototype.startOnMousewheel = function() {
    return true;
  };

  Zoomer.prototype.limitZoom = function(new_zoom) {
    if (new_zoom > 1) {
      if (new_zoom < this.maxZoom) {
        return Math.floor(new_zoom);
      } else {
        return this.maxZoom;
      }
    } else {
      return Math.max(this.fit.minimumZoom, new_zoom);
    }
  };

  Zoomer.prototype.deltaZoom = function(delta) {
    var set_zoom;
    if (delta > 0 && this.zoom < 1 && this.zoom + delta > 1) {
      set_zoom = 1;
    } else if (delta > 0 && this.zoom >= 1) {
      if (this.zoom < this.maxZoom) {
        set_zoom = Math.floor(this.zoom + 1);
      } else {
        set_zoom = this.zoom;
      }
    } else if (delta < 0 && this.zoom > 1 && this.zoom + delta < 1) {
      set_zoom = 1;
    } else if (delta < 0 && this.zoom > 1) {
      if (this.zoom <= this.maxZoom) {
        set_zoom = Math.floor(this.zoom - 1);
      } else {
        set_zoom = this.zoom;
      }
    } else {
      set_zoom = this.zoom + delta;
    }
    return set_zoom;
  };

  Zoomer.prototype.zoomIn = function() {
    return this.setZoomAndPosition(this.deltaZoom(0.05), this.getViewportMiddle());
  };

  Zoomer.prototype.zoomOut = function() {
    return this.setZoomAndPosition(this.deltaZoom(-0.05), this.getViewportMiddle());
  };

  Zoomer.prototype.plugins = function() {
    return [
      new AssetDetailPlugin({
        button: {
          ui: "zoomer.zoom_in.button",
          loca_key: "zoomer.button.zoom_in"
        },
        run: (function(_this) {
          return function() {
            return _this.zoomIn();
          };
        })(this)
      }), new AssetDetailPlugin({
        button: {
          ui: "zoomer.zoom_out.button",
          loca_key: "zoomer.button.zoom_out"
        },
        run: (function(_this) {
          return function() {
            return _this.zoomOut();
          };
        })(this)
      })
    ];
  };

  Zoomer.prototype.fitScreen = function() {
    var zoom;
    this.fitZoom();
    if (this.fit.left > 0) {
      zoom = this.viewport.width / this.width;
    } else if (this.fit.top > 0) {
      zoom = this.viewport.height / this.height;
    }
    if (zoom > 1) {
      zoom = Math.min(this.maxZoom, Math.ceil(zoom));
    }
    this.setZoomAndPosition(zoom, this.getViewportMiddle());
    return this;
  };

  Zoomer.prototype.createMarkup = function() {
    Zoomer.__super__.createMarkup.call(this);
    CUI.Events.listen({
      type: "dragover-scroll",
      node: this.outerDiv,
      call: (function(_this) {
        return function(ev) {
          return ev.stopPropagation();
        };
      })(this)
    });
    this.innerDiv = CUI.dom.div("zoomer-inner-div");
    CUI.dom.append(this.outerDiv, this.innerDiv);
    this.innerDivTransform = CUI.dom.div("zoomer-inner-div-transform");
    CUI.dom.append(this.innerDiv, this.innerDivTransform);
    if (this._debug < 2) {
      CUI.dom.setStyle(this.innerDivTransform, {
        backgroundImage: "url(" + this.__thumbnailUrl + ")"
      });
    }
    CUI.Events.listen({
      type: ["wheel", "dblclick", "gesturechange"],
      node: this.outerDiv,
      call: (function(_this) {
        return function(ev) {
          var button, new_zoom, pos, ref, ref1, zoom_delta;
          if (CUI.dom.closest(ev.getTarget(), ".zoomer-controls,.zoomer-map")) {
            return;
          }
          ev.stopPropagation();
          ev.preventDefault();
          if (ev.getType() === "gesturechange") {
            console.debug("event", ev.getType());
            new_zoom = _this.limitZoom(_this.zoom * ev.getNativeEvent().scale);
            console.debug("zoom", _this.zoom, "scale", ev.getNativeEvent().scale, "new zoom", new_zoom);
            pos = CUI.util.elementGetPosition(CUI.util.getCoordinatesFromEvent(ev), _this.innerDiv);
            _this.setZoomAndPosition(new_zoom, pos);
            return;
          }
          zoom_delta = null;
          switch (ev.getType()) {
            case "dblclick":
              button = (ref = CUI.dom.parents(ev.getTarget(), ".cui-button")) != null ? ref[0] : void 0;
              if (((ref1 = CUI.dom.data(button)) != null ? ref1.element : void 0) instanceof CUI.Button) {
                return;
              }
              zoom_delta = 0.15;
              if (ev.hasModifierKey()) {
                zoom_delta *= -1;
              }
              break;
            case "wheel":
              if (ev.wheelDeltaY()) {
                if (ev.wheelDeltaY() < 0) {
                  zoom_delta = 0.02;
                } else {
                  zoom_delta = -0.02;
                }
                if (ev.hasModifierKey()) {
                  zoom_delta = zoom_delta * 0.5;
                }
              }
          }
          if (zoom_delta !== null && (zoom_delta > 0 || _this.zoom !== _this.fit.minimumZoom)) {
            pos = CUI.util.elementGetPosition(CUI.util.getCoordinatesFromEvent(ev), _this.innerDiv);
            _this.setZoomAndPosition(_this.deltaZoom(zoom_delta), pos);
          }
        };
      })(this)
    });
    new CUI.Movable({
      element: this.innerDiv,
      selector: ".zoomer-tile",
      dragging: (function(_this) {
        return function() {
          _this.innerDivPos.top = CUI.dom.getCSSFloatValue(CUI.dom.getComputedStyle(_this.innerDiv).top);
          _this.innerDivPos.left = CUI.dom.getCSSFloatValue(CUI.dom.getComputedStyle(_this.innerDiv).left);
          return _this.updateZoomOrPosition();
        };
      })(this),
      dragend: (function(_this) {
        return function() {
          _this.updateZoomOrPosition();
          return _this.fillInnerDivWithTiles();
        };
      })(this),
      create: (function(_this) {
        return function(ev) {
          return !ev.hasModifierKey();
        };
      })(this),
      onPosition: (function(_this) {
        return function(x, y) {
          return _this.getInnerDivPosPosition(x, y);
        };
      })(this)
    });
    CUI.Events.listen({
      node: this.innerDiv,
      type: "dragover-scroll",
      call: (function(_this) {
        return function(ev, info) {
          var d, diff, oldInnerDivPos, position, scrollSpeed, t;
          if (CUI.globalDrag.isFlexHandleDrag || CUI.globalDrag.isMapCursor) {
            return;
          }
          scrollSpeed = ev.getCount() * 0.01 + 0.9;
          position = CUI.util.elementGetPosition(CUI.util.getCoordinatesFromEvent(ev.getOriginalEvent()), _this.outerDiv);
          diff = {
            x: 0,
            y: 0
          };
          t = 30;
          if ((d = position.left - t) < 0) {
            diff.x = -Math.max(-20, d) * scrollSpeed;
          }
          if ((d = position.top - t) < 0) {
            diff.y = -Math.max(-20, d) * scrollSpeed;
          }
          if ((d = _this.viewport.width - position.left) < t) {
            diff.x = -Math.max(-20, d) * scrollSpeed;
          }
          if ((d = _this.viewport.height - position.top) < t) {
            diff.y = -Math.max(-20, d) * scrollSpeed;
          }
          if (diff.x !== 0 || diff.y !== 0) {
            oldInnerDivPos = {
              left: _this.innerDivPos.left,
              top: _this.innerDivPos.top
            };
            _this.innerDivPos.left += diff.x;
            _this.innerDivPos.top += diff.y;
            _this.setInnerDiv();
            _this.updateZoomOrPosition();
            _this.fillInnerDivWithTiles();
            CUI.Events.trigger({
              type: "zoomer-scroll",
              node: _this.innerDiv,
              info: {
                x: _this.innerDivPos.left - oldInnerDivPos.left,
                y: _this.innerDivPos.top - oldInnerDivPos.top
              }
            });
          }
          return ev.stopPropagation();
        };
      })(this)
    });
    return new CUI.Lasso({
      element: this.outerDiv,
      filter: null,
      create: (function(_this) {
        return function(ev) {
          return ev.hasModifierKey();
        };
      })(this),
      selected: (function(_this) {
        return function(ev, info) {
          var cornerCoord, cornerPix, newZoom;
          cornerCoord = {
            left: (info.start.left - _this.innerDivPos.left) / _this.zoom,
            top: (info.start.top - _this.innerDivPos.top) / _this.zoom
          };
          newZoom = _this.viewport.width / (info.lasso_dim.width / _this.zoom);
          cornerPix = {
            left: -cornerCoord.left * newZoom,
            top: -cornerCoord.top * newZoom
          };
          if (newZoom >= 1) {
            newZoom = Math.min(_this.maxZoom, Math.floor(newZoom));
          }
          return _this.setZoomAndMove(newZoom, cornerPix.left, cornerPix.top);
        };
      })(this)
    });
  };

  Zoomer.prototype.getViewportMiddle = function() {
    return {
      left: -this.innerDivPos.left + this.viewport.width / 2,
      top: -this.innerDivPos.top + this.viewport.height / 2
    };
  };

  Zoomer.prototype.resize = function() {
    this.positionAndSizeZoomer();
    this.updateZoomOrPosition();
    this.fillInnerDivWithTiles();
    this.setZoomAndPosition(this.zoom, this.getViewportMiddle());
    return this;
  };

  Zoomer.prototype.getInnerDivPosPosition = function(x, y) {
    if (this.innerDivPos.width >= this.viewport.width) {
      if (x > 0) {
        x = 0;
      } else {
        x = Math.max(x, this.viewport.width - this.innerDivPos.width);
      }
    } else {
      x = (this.viewport.width - this.innerDivPos.width) / 2;
    }
    if (this.innerDivPos.height >= this.viewport.height) {
      if (y > 0) {
        y = 0;
      } else {
        y = Math.max(y, this.viewport.height - this.innerDivPos.height);
      }
    } else {
      y = (this.viewport.height - this.innerDivPos.height) / 2;
    }
    CUI.util.assert(!isNaN(x) && !isNaN(y), "Zoomer.getInnerDivPosition", "x or y is NaN", {
      viewport: this.viewport,
      innerDivPos: this.innerDivPos
    });
    return [x, y];
  };

  Zoomer.prototype.positionAndSizeZoomer = function() {
    var ref;
    if (this.viewport.width === 0 || this.viewport.height === 0) {
      return;
    }
    this.fit = {};
    ref = ez5.fitRectangle(this.width, this.height, this.viewport.width, this.viewport.height), this.fit.width = ref[0], this.fit.height = ref[1], this.fit.top = ref[2], this.fit.left = ref[3];
    this.fit.minimumZoom = Math.min(1, this.fit.width / this.width);
    return this.sizeMap();
  };

  Zoomer.prototype.createMap = function() {
    this.mapDiv = CUI.dom.div("zoomer-map");
    this.mapDivInner = CUI.dom.div("zoomer-map-inner");
    CUI.dom.append(this.mapDiv, this.mapDivInner);
    CUI.dom.setStyle(this.mapDivInner, {
      backgroundImage: "url(" + this.__thumbnailUrl + ")"
    });
    this.mapDivCursor = CUI.dom.div("zoomer-map-cursor");
    this.mapDivCursor.appendChild(CUI.dom.div("zoomer-map-cursor-inner"));
    this.mapDiv.appendChild(this.mapDivCursor);
    new CUI.Movable({
      element: this.mapDivCursor,
      dragstart: (function(_this) {
        return function(ev, gd) {
          return gd.isMapCursor = true;
        };
      })(this),
      dragend: (function(_this) {
        return function(ev, info) {
          var pos;
          pos = CUI.dom.getRelativePosition(_this.mapDivCursor);
          CUI.dom.addClass(_this.innerDiv, "zoomer-map-drag");
          _this.innerDivPos.top = pos.top / _this.map.zoom * -_this.zoom;
          _this.innerDivPos.left = pos.left / _this.map.zoom * -_this.zoom;
          _this.setInnerDiv();
          _this.fillInnerDivWithTiles();
          return CUI.setTimeout(function() {
            return CUI.dom.removeClass(_this.innerDiv, "zoomer-map-drag");
          }, 1000);
        };
      })(this),
      onPosition: (function(_this) {
        return function(x, y) {
          if (x < 0) {
            x = 0;
          }
          if (y < 0) {
            y = 0;
          }
          x = Math.min(x, _this.map.width - _this.mapCursor.width);
          y = Math.min(y, _this.map.height - _this.mapCursor.height);
          return [x, y];
        };
      })(this)
    });
    return CUI.dom.append(this.outerDiv, this.mapDiv);
  };

  Zoomer.prototype.sizeMap = function() {
    var ref;
    this.map = {
      size: 0.2
    };
    ref = ez5.fitRectangle(this.width, this.height, this.viewport.width * this.map.size, this.viewport.height * this.map.size), this.map.width = ref[0], this.map.height = ref[1];
    this.map.zoom = this.map.width / this.width;
    CUI.dom.setStyle(this.mapDiv, {
      width: this.map.width,
      height: this.map.height,
      right: 10,
      bottom: 10
    });
    this.__setInnerDivStyle(this.mapDivInner, this.map);
    return this;
  };

  Zoomer.prototype.positionMapCursor = function() {
    this.mapCursor = {
      top: -this.innerDivPos.top / this.zoom * this.map.zoom,
      left: -this.innerDivPos.left / this.zoom * this.map.zoom,
      width: this.viewport.width / this.zoom * this.map.zoom,
      height: this.viewport.height / this.zoom * this.map.zoom
    };
    return CUI.dom.setStyle(this.mapDivCursor, this.mapCursor);
  };

  Zoomer.prototype.getDiff = function(x, y, oldZoom, newZoom) {
    var _new, _old, coord;
    coord = (function(_this) {
      return function(x, y, zoom) {
        return {
          x: x / zoom,
          y: y / zoom
        };
      };
    })(this);
    _old = coord(x, y, oldZoom);
    _new = coord(x, y, newZoom);
    return {
      x: (_new.x - _old.x) * newZoom,
      y: (_new.y - _old.y) * newZoom
    };
  };

  Zoomer.prototype.destroy = function() {
    var ref;
    if ((ref = this.__waitBlock) != null) {
      ref.destroy();
    }
    this.__waitBlock = null;
    return Zoomer.__super__.destroy.call(this);
  };

  Zoomer.prototype.reload = function(asset) {
    this.destroy();
    this.start(asset);
    return this;
  };

  Zoomer.prototype.update = function(asset) {
    var zoom;
    zoom = this.zoom;
    delete this.zoom;
    this.reload(asset);
    this.setZoomAndPosition(zoom, this.getViewportMiddle());
    return this;
  };

  Zoomer.prototype.setZoomAndPosition = function(zoom, pos) {
    var diff;
    zoom = Math.max(zoom, this.fit.minimumZoom);
    diff = this.getDiff(pos.left, pos.top, this.zoom, zoom);
    return this.setZoomAndMove(zoom, this.innerDivPos.left + diff.x, this.innerDivPos.top + diff.y);
  };

  Zoomer.prototype.setZoomAndMove = function(zoom, left, top) {
    if (left == null) {
      left = null;
    }
    if (top == null) {
      top = null;
    }
    CUI.util.assert(!isNaN(zoom), "Zoomer.setZoom(zoom)", "zoom cannot be NaN", {
      zoom: zoom
    });
    if (zoom !== this.zoom) {
      this.zoom = Math.max(zoom, this.fit.minimumZoom);
      this.zoom_print = (Math.round(this.getZoom() * 100)) + "%";
      this.innerDivPos.width = this.width * this.zoom;
      this.innerDivPos.height = this.height * this.zoom;
    }
    if (top !== null) {
      this.innerDivPos.top = top;
    }
    if (left !== null) {
      this.innerDivPos.left = left;
    }
    this.setInnerDiv();
    this.updateZoomOrPosition();
    this.fillInnerDivWithTiles();
    return this;
  };

  Zoomer.prototype.setInnerDiv = function() {
    var k, ref, ref1, set, v;
    ref = this.getInnerDivPosPosition(this.innerDivPos.left, this.innerDivPos.top), this.innerDivPos.left = ref[0], this.innerDivPos.top = ref[1];
    set = {};
    ref1 = this.innerDivPos;
    for (k in ref1) {
      v = ref1[k];
      set[k] = v;
    }
    CUI.dom.setStyle(this.innerDiv, set);
    this.__setInnerDivStyle(this.innerDivTransform, set);
    return this;
  };

  Zoomer.prototype.__setInnerDivStyle = function(div, set) {
    var inner, ref, ref1, ref2;
    inner = {};
    if ((ref = this.rotate.z) === 90 || ref === 270) {
      ref1 = [set.height, set.width], inner.width = ref1[0], inner.height = ref1[1];
      inner.left = -(inner.width / 2) + (set.width / 2);
      inner.top = -(inner.height / 2) + (set.height / 2);
    } else {
      ref2 = [set.width, set.height], inner.width = ref2[0], inner.height = ref2[1];
      inner.left = 0;
      inner.top = 0;
    }
    CUI.dom.setStyle(div, inner);
    EAS.setTransformStyle(div, this.__transform, false);
    return this;
  };

  Zoomer.prototype.updateZoomOrPosition = function() {
    this.positionMapCursor();
    this.__zoomerLabel.setText($$("zoomer.label", {
      zoom: this.zoom_print
    }));
    return this.callbackPlugins("update");
  };

  Zoomer.prototype.fillInnerDivWithTiles = function(withThrottle) {
    var $t, $tile, canAppendNewTiles, cut_x, cut_y, div, first_tile_x, first_tile_y, i, j, l, last_tile_x, last_tile_y, left, len, m, parts, rect, ref, ref1, ref10, ref11, ref12, ref13, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, results, span, tile, tileId, tileImg, tileSize, tile_x, tile_y, top, total_height, total_width, url, vr, zoomerVisibleRectangles;
    if (withThrottle == null) {
      withThrottle = true;
    }
    rect = this.calcVisibleRectangle();
    if (this._debug >= 2) {
      zoomerVisibleRectangles = CUI.dom.matchSelector(this.innerDiv, ".zoomer-visible-rectangle");
      for (i = 0, len = zoomerVisibleRectangles.length; i < len; i++) {
        div = zoomerVisibleRectangles[i];
        CUI.dom.remove(div);
      }
      vr = CUI.dom.div("zoomer-visible-rectangle");
      CUI.dom.append(this.innerDiv, vr);
      CUI.dom.setStyle(vr, rect);
      span = "<span>" + (Math.round(rect.left)) + "/" + (Math.round(rect.top)) + "  " + (Math.round(rect.width)) + "x" + (Math.round(rect.height)) + " " + (Math.round(this.innerDivPos.width)) + "x" + (Math.round(this.innerDivPos.height)) + "</span>";
      CUI.dom.append(vr, span);
    }
    ref = this.innerDivTiles;
    for (tileId in ref) {
      tile = ref[tileId];
      tile.needed = false;
    }
    canAppendNewTiles = !withThrottle || !this.checkThrottle();
    if (rect) {
      total_width = this.innerDivPos.width;
      total_height = this.innerDivPos.height;
      if ((ref1 = this.rotate.z) === 90 || ref1 === 270) {
        ref2 = [rect.width, rect.height], rect.height = ref2[0], rect.width = ref2[1];
        ref3 = [total_height, total_width], total_width = ref3[0], total_height = ref3[1];
      }
      if ((ref4 = this.rotate.z) === 90 || ref4 === 270) {
        if ((ref5 = this.rotate.z) === 90) {
          top = rect.top;
          left = rect.left;
          rect.top = total_height - rect.height - left;
          rect.left = top;
        }
        if ((ref6 = this.rotate.z) === 270) {
          top = rect.top;
          left = rect.left;
          rect.top = rect.left;
          rect.left = total_width - rect.width - top;
        }
      }
      if ((ref7 = this.rotate.x) === 180) {
        rect.top = total_height - rect.height - rect.top;
      }
      if ((ref8 = this.rotate.y) === 180) {
        rect.left = total_width - rect.width - rect.left;
      }
      first_tile_x = Math.floor(rect.left / this.tileSize);
      first_tile_y = Math.floor(rect.top / this.tileSize);
      last_tile_x = Math.ceil((rect.left + rect.width) / this.tileSize);
      last_tile_y = Math.ceil((rect.top + rect.height) / this.tileSize);
      for (tile_y = j = ref9 = first_tile_y, ref10 = last_tile_y; ref9 <= ref10 ? j < ref10 : j > ref10; tile_y = ref9 <= ref10 ? ++j : --j) {
        for (tile_x = l = ref11 = first_tile_x, ref12 = last_tile_x; ref11 <= ref12 ? l < ref12 : l > ref12; tile_x = ref11 <= ref12 ? ++l : --l) {
          tileId = tile_x + "x" + tile_y + "@" + this.zoom;
          if (this.innerDivTiles[tileId]) {
            this.innerDivTiles[tileId].needed = true;
          } else if (canAppendNewTiles) {
            $tile = CUI.dom.div("zoomer-tile", {
              "data-tile-id": tileId
            });
            this.innerDivTiles[tileId] = {
              $tile: $tile,
              needed: true
            };
            m = {
              top: this.tileSize * tile_y,
              left: this.tileSize * tile_x
            };
            cut_x = total_width - m.left - this.tileSize;
            if (cut_x < 0) {
              m.width = Math.round(this.tileSize + cut_x);
            } else {
              m.width = this.tileSize;
            }
            cut_y = total_height - m.top - this.tileSize;
            if (cut_y < 0) {
              m.height = Math.round(this.tileSize + cut_y);
            } else {
              m.height = this.tileSize;
            }
            if (this.zoom > 1) {
              parts = ["zoom" + (Math.round(this.zoom * this.__zoomerVersion.width))];
              tileSize = Math.round(this.tileSize / this.__zoomScale);
            } else {
              parts = ["zoom" + (Math.round(total_width))];
              tileSize = this.tileSize;
            }
            if (tileSize !== 320) {
              parts.push("size" + tileSize);
            }
            if (this.zoom > 1) {
              parts.push("avoid_interpolation");
            }
            parts.push("part" + tile_x + "x" + tile_y + ".jpg");
            url = this.__url + "/" + parts.join("/") + this.__url_search;
            CUI.dom.setStyle($tile, m);
            if (this._debug) {
              $tile.innerHTML = tile_x + "/" + tile_y + "<br><br>" + m.width + "x" + m.height + "<br>" + m.left + "/" + m.top;
            } else {
              CUI.dom.setStyle($tile, {
                backgroundImage: "url(" + url + ")",
                backgroundSize: "cover"
              });
              if (!this.__firstTileLoaded) {
                tileImg = new Image();
                tileImg.onload = (function(_this) {
                  return function() {
                    var ref13;
                    if (!_this.__firstTileLoaded) {
                      _this.__firstTileLoaded = true;
                      return (ref13 = _this.__waitBlock) != null ? ref13.hide() : void 0;
                    }
                  };
                })(this);
                tileImg.src = url;
              }
            }
            CUI.dom.append(this.innerDivTransform, $tile);
          }
        }
      }
    }
    ref13 = this.innerDivTiles;
    results = [];
    for (tileId in ref13) {
      tile = ref13[tileId];
      if (!tile.needed) {
        $t = tile.$tile;
        delete this.innerDivTiles[tileId];
        results.push(CUI.dom.remove($t));
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  Zoomer.prototype.checkThrottle = function() {
    if (!this.__thottling) {
      this.__thottling = true;
      CUI.setTimeout((function(_this) {
        return function() {
          _this.__thottling = false;
          return _this.fillInnerDivWithTiles(false);
        };
      })(this), 250);
      return false;
    }
    return this.__thottling;
  };

  Zoomer.prototype.calcVisibleRectangle = function() {
    var availableHeight, availableWidth, r;
    r = {};
    if (this.innerDivPos.top > 0) {
      if (this.innerDivPos.top > this.viewport.height) {
        return null;
      }
      r.top = 0;
      availableHeight = this.viewport.height - this.innerDivPos.top;
    } else {
      r.top = -this.innerDivPos.top;
      availableHeight = this.viewport.height;
    }
    if (this.innerDivPos.left > 0) {
      if (this.innerDivPos.left > this.viewport.width) {
        return null;
      }
      r.left = 0;
      availableWidth = this.viewport.width - this.innerDivPos.left;
    } else {
      r.left = -this.innerDivPos.left;
      availableWidth = this.viewport.width;
    }
    r.height = Math.min(this.innerDivPos.height - r.top, availableHeight);
    r.width = Math.min(this.innerDivPos.width - r.left, availableWidth);
    return r;
  };

  return Zoomer;

})(AssetDetail);

CUI.ready(function() {
  return CUI.Events.registerEvent({
    type: "zoomer-scroll",
    bubble: true
  });
});
// Generated by CoffeeScript 1.12.7
var ZoomerV2,
  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;

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

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

  ZoomerV2.prototype.readOpts = function() {
    ZoomerV2.__super__.readOpts.call(this);
    return this._debug = 0;
  };

  ZoomerV2.prototype.tileSize = 320;

  ZoomerV2.prototype.maxZoom = 8;

  ZoomerV2.prototype.MAX_CACHE_TILES = 200;

  ZoomerV2.prototype.ZOOM_STEPS = [1.0, 1.25, 1.5, 1.75, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];

  ZoomerV2.prototype.SUB_ONE_ZOOM_SPEED = 3.0;

  ZoomerV2.prototype.getButtonLocaKey = function(asset) {
    if (this.getZoomerVersion(asset) && this.checkValidSizes(asset)) {
      return "zoomer.button.title";
    } else {
      return null;
    }
  };

  ZoomerV2.prototype.getLabelLocaKey = function() {
    return null;
  };

  ZoomerV2.prototype.getZoomerVersion = function(asset) {
    var ref, version;
    if ((ref = asset.value["class"]) !== "image" && ref !== "vector2d") {
      return;
    }
    version = Asset.getBestImageForViewport(asset, 1000000, 1000000, (function(_this) {
      return function(version) {
        var ref1, ref2, v, vname;
        if (ez5.version("6") && version.version === "original") {
          ref2 = (asset != null ? (ref1 = asset.value) != null ? ref1.versions : void 0 : void 0) || [];
          for (vname in ref2) {
            v = ref2[vname];
            if (vname === "original") {
              continue;
            }
            if (v.zoom_url && v.width === version.width && v.height === version.height) {
              return false;
            }
          }
          return true;
        }
        if (version.zoom_url) {
          return true;
        } else {
          return false;
        }
      };
    })(this));
    if (ez5.session.isDebug() && version) {
      console.debug("ZoomerV2 selected version:", version.version);
    }
    return version;
  };

  ZoomerV2.prototype.checkValidSizes = function(asset) {
    if (!asset.getWidth() || !asset.getHeight()) {
      console.error("ZoomerV2.checkValidSizes", "width or height is 0", this.asset);
      return false;
    }
    return true;
  };

  ZoomerV2.prototype.start = function(asset1, mouseWheelstart) {
    var loc, version, zoomUrl;
    this.asset = asset1;
    this.mouseWheelstart = mouseWheelstart != null ? mouseWheelstart : false;
    this.__zoomerVersion = this.getZoomerVersion(this.asset);
    version = Asset.getStandardVersion(this.asset.value);
    this.__thumbnailUrl = Session.addToken(version.url);
    this.__width = this.asset.getWidth();
    this.__height = this.asset.getHeight();
    this.__zoomScale = this.__width / this.__zoomerVersion.width;
    zoomUrl = Session.addToken(this.__zoomerVersion.zoom_url);
    loc = CUI.parseLocation(zoomUrl);
    this.__url = loc.origin + loc.pathname;
    this.__url_search = loc.search + loc.hash;
    ZoomerV2.__super__.start.call(this, this.asset, this.mouseWheelstart);
    this.__firstTileLoaded = false;
    this.__waitBlock = new CUI.WaitBlock({
      element: this.outerDiv
    }).show();
    this.__zoomerLabelButton = new CUI.Button({
      text: "",
      "class": "ez5-zoomer-level-button",
      appearance: "transparent-border",
      menu: {
        items: (function(_this) {
          return function() {
            return [
              {
                text: $$("zoomer.zoom.fit_to_screen"),
                onClick: function() {
                  return _this.fitZoom();
                }
              }, {
                text: "50%",
                onClick: function() {
                  return _this.setZoomAndPosition(0.5, _this.getViewportMiddle());
                }
              }, {
                text: "100%",
                onClick: function() {
                  return _this.setZoomAndPosition(1, _this.getViewportMiddle());
                }
              }
            ];
          };
        })(this)
      }
    });
    CUI.dom.append(this.controls, this.__zoomerLabelButton);
    this.__init();
    this.zoomIn();
    return this;
  };

  ZoomerV2.prototype.__init = function() {
    this.zoom = null;
    this.__tileCache = {};
    this.__tileCacheOrder = [];
    this.__pendingTiles = {};
    this.__renderPending = false;
    this.__bgImg = null;
    this.__bgImgLoaded = false;
    this.__bgImg = new Image();
    this.__bgImg.crossOrigin = "anonymous";
    this.__bgImg.onload = (function(_this) {
      return function() {
        _this.__bgImgLoaded = true;
        return _this.__scheduleRender();
      };
    })(this);
    this.__bgImg.src = this.__thumbnailUrl;
    this.__createMap();
    this.__setRotate();
    if (this.__canvas && this.viewport) {
      this.__canvas.width = this.viewport.width;
      this.__canvas.height = this.viewport.height;
    }
    this.__positionAndSizeZoomer();
    this.fitZoom();
    return this.callbackPlugins("init");
  };

  ZoomerV2.prototype.__setRotate = function() {
    var ref, ref1;
    this.__transform = this.asset.value.transform || [];
    this.rotate = EAS.getRotateMapFromTransform(this.__transform);
    this.width = this.__width;
    this.height = this.__height;
    if ((ref = this.rotate.z) === 90 || ref === 270) {
      ref1 = [this.height, this.width], this.width = ref1[0], this.height = ref1[1];
    }
    return this;
  };

  ZoomerV2.prototype.getZoom = function() {
    return this.zoom;
  };

  ZoomerV2.prototype.getPanX = function() {
    return this.__panX;
  };

  ZoomerV2.prototype.getPanY = function() {
    return this.__panY;
  };

  ZoomerV2.prototype.getMapZoom = function() {
    return this.map.zoom;
  };

  ZoomerV2.prototype.fitZoom = function() {
    return this.setZoomAndMove(this.fit.minimumZoom, this.fit.left, this.fit.top);
  };

  ZoomerV2.prototype.startOnMousewheel = function() {
    return true;
  };

  ZoomerV2.prototype.limitZoom = function(new_zoom) {
    var best, i, len, ref, step;
    new_zoom = Math.max(this.fit.minimumZoom, new_zoom);
    new_zoom = Math.min(new_zoom, this.maxZoom);
    if (new_zoom >= 1) {
      best = this.ZOOM_STEPS[0];
      ref = this.ZOOM_STEPS;
      for (i = 0, len = ref.length; i < len; i++) {
        step = ref[i];
        if (Math.abs(step - new_zoom) < Math.abs(best - new_zoom)) {
          best = step;
        }
      }
      new_zoom = best;
    }
    return new_zoom;
  };

  ZoomerV2.prototype.__nextZoomStep = function(currentZoom) {
    var i, len, ref, step;
    ref = this.ZOOM_STEPS;
    for (i = 0, len = ref.length; i < len; i++) {
      step = ref[i];
      if (step > currentZoom + 0.001) {
        return step;
      }
    }
    return this.maxZoom;
  };

  ZoomerV2.prototype.__prevZoomStep = function(currentZoom) {
    var i, len, prev, ref, step;
    prev = this.ZOOM_STEPS[0];
    ref = this.ZOOM_STEPS;
    for (i = 0, len = ref.length; i < len; i++) {
      step = ref[i];
      if (step >= currentZoom - 0.001) {
        break;
      }
      prev = step;
    }
    return prev;
  };

  ZoomerV2.prototype.deltaZoom = function(delta) {
    var set_zoom;
    if (this.zoom < 1) {
      delta = delta * this.SUB_ONE_ZOOM_SPEED;
    }
    if (delta > 0) {
      if (this.zoom < 1 && this.zoom + delta >= 1) {
        set_zoom = 1;
      } else if (this.zoom >= 1) {
        set_zoom = this.__nextZoomStep(this.zoom);
      } else {
        set_zoom = this.zoom + delta;
      }
    } else {
      if (this.zoom > 1 && this.zoom + delta <= 1) {
        set_zoom = 1;
      } else if (this.zoom > 1) {
        set_zoom = this.__prevZoomStep(this.zoom);
      } else {
        set_zoom = Math.max(this.zoom + delta, this.fit.minimumZoom);
      }
    }
    return set_zoom;
  };

  ZoomerV2.prototype.zoomIn = function() {
    return this.setZoomAndPosition(this.deltaZoom(0.05), this.getViewportMiddle());
  };

  ZoomerV2.prototype.createMarkup = function() {
    ZoomerV2.__super__.createMarkup.call(this);
    CUI.Events.listen({
      type: "dragover-scroll",
      node: this.outerDiv,
      call: (function(_this) {
        return function(ev) {
          return ev.stopPropagation();
        };
      })(this)
    });
    this.innerDiv = CUI.dom.div("zoomer-v2-inner-div");
    CUI.dom.append(this.outerDiv, this.innerDiv);
    this.__canvas = document.createElement("canvas");
    this.__canvas.className = "zoomer-v2-canvas";
    CUI.dom.append(this.innerDiv, this.__canvas);
    this.__panX = 0;
    this.__panY = 0;
    this.__targetPanX = 0;
    this.__targetPanY = 0;
    this.__targetZoom = null;
    this.__animating = false;
    this.__setupWheelAndDblClick();
    this.__setupDrag();
    return this.__setupLasso();
  };

  ZoomerV2.prototype.__setupWheelAndDblClick = function() {
    return CUI.Events.listen({
      type: ["wheel", "dblclick", "gesturechange"],
      node: this.outerDiv,
      call: (function(_this) {
        return function(ev) {
          var button, new_zoom, pos, ref, ref1, step, zoom_factor;
          if (CUI.dom.closest(ev.getTarget(), ".zoomer-controls,.zoomer-map")) {
            return;
          }
          ev.stopPropagation();
          ev.preventDefault();
          if (ev.getType() === "gesturechange") {
            new_zoom = _this.limitZoom(_this.zoom * ev.getNativeEvent().scale);
            pos = _this.__getEventPos(ev);
            _this.setZoomAndPosition(new_zoom, pos);
            return;
          }
          zoom_factor = null;
          switch (ev.getType()) {
            case "dblclick":
              button = (ref = CUI.dom.parents(ev.getTarget(), ".cui-button")) != null ? ref[0] : void 0;
              if (((ref1 = CUI.dom.data(button)) != null ? ref1.element : void 0) instanceof CUI.Button) {
                return;
              }
              zoom_factor = ev.hasModifierKey() ? 0.85 : 1.15;
              break;
            case "wheel":
              if (ev.wheelDeltaY()) {
                step = 0.03;
                if (ev.hasModifierKey()) {
                  step = 0.015;
                }
                if (_this.zoom < 1) {
                  step = step * _this.SUB_ONE_ZOOM_SPEED;
                }
                if (ev.wheelDeltaY() < 0) {
                  zoom_factor = 1 + step;
                } else {
                  zoom_factor = 1 - step;
                }
              }
          }
          if (zoom_factor !== null) {
            pos = _this.__getEventPos(ev);
            _this.__pendingWheelFactor = (_this.__pendingWheelFactor || 1) * zoom_factor;
            _this.__pendingWheelPos = pos;
            if (!_this.__wheelRafId) {
              _this.__wheelRafId = requestAnimationFrame(function() {
                var factor, newZoom, pendingPos, rawZoom;
                _this.__wheelRafId = null;
                factor = _this.__pendingWheelFactor;
                pendingPos = _this.__pendingWheelPos;
                _this.__pendingWheelFactor = 1;
                rawZoom = _this.zoom * factor;
                if (rawZoom >= 1 && _this.zoom >= 1) {
                  if (factor > 1) {
                    newZoom = _this.__nextZoomStep(_this.zoom);
                  } else {
                    newZoom = _this.__prevZoomStep(_this.zoom);
                  }
                } else {
                  newZoom = _this.limitZoom(rawZoom);
                }
                if (newZoom !== _this.zoom) {
                  return _this.setZoomAndPosition(newZoom, pendingPos);
                }
              });
            }
          }
        };
      })(this)
    });
  };

  ZoomerV2.prototype.__getEventPos = function(ev) {
    var clientX, clientY, nativeEv, rect;
    rect = this.__canvas.getBoundingClientRect();
    nativeEv = ev.getNativeEvent();
    clientX = nativeEv.clientX || 0;
    clientY = nativeEv.clientY || 0;
    return {
      left: clientX - rect.left - this.__panX,
      top: clientY - rect.top - this.__panY
    };
  };

  ZoomerV2.prototype.__setupDrag = function() {
    var mousedown, mousemove, mouseup;
    this.__isDragging = false;
    this.__dragStartX = 0;
    this.__dragStartY = 0;
    this.__dragStartPanX = 0;
    this.__dragStartPanY = 0;
    this.__velocityX = 0;
    this.__velocityY = 0;
    this.__lastDragTime = 0;
    this.__lastDragX = 0;
    this.__lastDragY = 0;
    mousedown = (function(_this) {
      return function(ev) {
        if (ev.button !== 0 || ev.shiftKey) {
          return;
        }
        if (CUI.dom.closest(ev.target, ".zoomer-controls,.zoomer-map,.cui-button,.cui-buttonbar")) {
          return;
        }
        ev.preventDefault();
        _this.__isDragging = true;
        _this.__dragStartX = ev.clientX;
        _this.__dragStartY = ev.clientY;
        _this.__dragStartPanX = _this.__panX;
        _this.__dragStartPanY = _this.__panY;
        _this.__velocityX = 0;
        _this.__velocityY = 0;
        _this.__lastDragTime = performance.now();
        _this.__lastDragX = ev.clientX;
        _this.__lastDragY = ev.clientY;
        return _this.__canvas.style.cursor = "grabbing";
      };
    })(this);
    mousemove = (function(_this) {
      return function(ev) {
        var dt, newX, newY, now, ref;
        if (!_this.__isDragging) {
          return;
        }
        newX = _this.__dragStartPanX + (ev.clientX - _this.__dragStartX);
        newY = _this.__dragStartPanY + (ev.clientY - _this.__dragStartY);
        now = performance.now();
        dt = now - _this.__lastDragTime;
        if (dt > 0) {
          _this.__velocityX = (ev.clientX - _this.__lastDragX) / dt;
          _this.__velocityY = (ev.clientY - _this.__lastDragY) / dt;
        }
        _this.__lastDragTime = now;
        _this.__lastDragX = ev.clientX;
        _this.__lastDragY = ev.clientY;
        ref = _this.__clampPan(newX, newY), _this.__panX = ref[0], _this.__panY = ref[1];
        _this.__scheduleRender();
        if (!_this.__dragLabelRafId) {
          return _this.__dragLabelRafId = requestAnimationFrame(function() {
            _this.__dragLabelRafId = null;
            return _this.__updateMapAndLabel();
          });
        }
      };
    })(this);
    mouseup = (function(_this) {
      return function(ev) {
        if (!_this.__isDragging) {
          return;
        }
        _this.__isDragging = false;
        _this.__canvas.style.cursor = "grab";
        _this.__updateMapAndLabel();
        _this.__loadVisibleTiles();
        return _this.__applyMomentum();
      };
    })(this);
    CUI.Events.listen({
      type: "mousedown",
      node: this.__canvas,
      call: (function(_this) {
        return function(ev) {
          return mousedown(ev.getNativeEvent());
        };
      })(this)
    });
    CUI.Events.listen({
      type: "mousemove",
      node: window,
      instance: this,
      call: (function(_this) {
        return function(ev) {
          return mousemove(ev.getNativeEvent());
        };
      })(this)
    });
    return CUI.Events.listen({
      type: "mouseup",
      node: window,
      instance: this,
      call: (function(_this) {
        return function(ev) {
          return mouseup(ev.getNativeEvent());
        };
      })(this)
    });
  };

  ZoomerV2.prototype.__applyMomentum = function() {
    var animate, friction, speed, vx, vy;
    vx = this.__velocityX;
    vy = this.__velocityY;
    speed = Math.sqrt(vx * vx + vy * vy);
    if (speed < 0.1) {
      return;
    }
    friction = 0.95;
    animate = (function(_this) {
      return function() {
        var newX, newY, ref;
        vx *= friction;
        vy *= friction;
        if (Math.abs(vx) < 0.01 && Math.abs(vy) < 0.01) {
          _this.__loadVisibleTiles();
          return;
        }
        newX = _this.__panX + vx * 16;
        newY = _this.__panY + vy * 16;
        ref = _this.__clampPan(newX, newY), _this.__panX = ref[0], _this.__panY = ref[1];
        _this.__scheduleRender();
        _this.__updateMapAndLabel();
        return _this.__momentumRafId = requestAnimationFrame(animate);
      };
    })(this);
    return this.__momentumRafId = requestAnimationFrame(animate);
  };

  ZoomerV2.prototype.__setupLasso = function() {
    return new CUI.Lasso({
      element: this.outerDiv,
      filter: null,
      create: (function(_this) {
        return function(ev) {
          return ev.hasModifierKey();
        };
      })(this),
      selected: (function(_this) {
        return function(ev, info) {
          var cornerCoord, cornerPix, newZoom;
          cornerCoord = {
            left: (info.start.left - _this.__panX) / _this.zoom,
            top: (info.start.top - _this.__panY) / _this.zoom
          };
          newZoom = _this.viewport.width / (info.lasso_dim.width / _this.zoom);
          cornerPix = {
            left: -cornerCoord.left * newZoom,
            top: -cornerCoord.top * newZoom
          };
          if (newZoom >= 1) {
            newZoom = _this.limitZoom(newZoom);
          }
          return _this.setZoomAndMove(newZoom, cornerPix.left, cornerPix.top);
        };
      })(this)
    });
  };

  ZoomerV2.prototype.getViewportMiddle = function() {
    return {
      left: -this.__panX + this.viewport.width / 2,
      top: -this.__panY + this.viewport.height / 2
    };
  };

  ZoomerV2.prototype.__clampPan = function(x, y) {
    var imgH, imgW;
    imgW = this.width * this.zoom;
    imgH = this.height * this.zoom;
    if (imgW >= this.viewport.width) {
      if (x > 0) {
        x = 0;
      }
      x = Math.max(x, this.viewport.width - imgW);
    } else {
      x = (this.viewport.width - imgW) / 2;
    }
    if (imgH >= this.viewport.height) {
      if (y > 0) {
        y = 0;
      }
      y = Math.max(y, this.viewport.height - imgH);
    } else {
      y = (this.viewport.height - imgH) / 2;
    }
    return [x, y];
  };

  ZoomerV2.prototype.getDiff = function(x, y, oldZoom, newZoom) {
    var _new, _old, coord;
    coord = (function(_this) {
      return function(x, y, zoom) {
        return {
          x: x / zoom,
          y: y / zoom
        };
      };
    })(this);
    _old = coord(x, y, oldZoom);
    _new = coord(x, y, newZoom);
    return {
      x: (_new.x - _old.x) * newZoom,
      y: (_new.y - _old.y) * newZoom
    };
  };

  ZoomerV2.prototype.setZoomAndPosition = function(zoom, pos) {
    var diff;
    zoom = Math.max(zoom, this.fit.minimumZoom);
    diff = this.getDiff(pos.left, pos.top, this.zoom, zoom);
    return this.setZoomAndMove(zoom, this.__panX + diff.x, this.__panY + diff.y);
  };

  ZoomerV2.prototype.setZoomAndMove = function(zoom, left, top) {
    var clampedZoom, ref;
    if (left == null) {
      left = null;
    }
    if (top == null) {
      top = null;
    }
    CUI.util.assert(!isNaN(zoom), "ZoomerV2.setZoomAndMove", "zoom cannot be NaN", {
      zoom: zoom
    });
    if (zoom !== this.zoom) {
      clampedZoom = Math.max(zoom, this.fit.minimumZoom);
      this.__cancelObsoleteTiles(clampedZoom);
      this.zoom = clampedZoom;
      this.zoom_print = (Math.round(this.getZoom() * 100)) + "%";
    }
    if (left !== null) {
      this.__panX = left;
    }
    if (top !== null) {
      this.__panY = top;
    }
    ref = this.__clampPan(this.__panX, this.__panY), this.__panX = ref[0], this.__panY = ref[1];
    this.__scheduleRender();
    this.__updateMapAndLabel();
    this.__loadVisibleTiles();
    return this;
  };

  ZoomerV2.prototype.__cancelObsoleteTiles = function(newZoom) {
    var img, key, newLevel, ref, tileZoom;
    newLevel = this.__getTileLevel(newZoom);
    ref = this.__pendingTiles;
    for (key in ref) {
      img = ref[key];
      tileZoom = parseFloat(key.split("_")[0]);
      if (tileZoom !== newLevel) {
        img.onload = null;
        img.onerror = null;
        img.src = "";
        delete this.__pendingTiles[key];
      }
    }
  };

  ZoomerV2.prototype.resize = function() {
    if (!this.__canvas) {
      return;
    }
    this.__canvas.width = this.viewport.width;
    this.__canvas.height = this.viewport.height;
    this.__positionAndSizeZoomer();
    this.setZoomAndPosition(this.zoom, this.getViewportMiddle());
    return this;
  };

  ZoomerV2.prototype.__positionAndSizeZoomer = function() {
    var ref;
    if (this.viewport.width === 0 || this.viewport.height === 0) {
      return;
    }
    this.fit = {};
    ref = ez5.fitRectangle(this.width, this.height, this.viewport.width, this.viewport.height), this.fit.width = ref[0], this.fit.height = ref[1], this.fit.top = ref[2], this.fit.left = ref[3];
    this.fit.minimumZoom = Math.min(1, this.fit.width / this.width);
    return this.__sizeMap();
  };

  ZoomerV2.prototype.__updateMapAndLabel = function() {
    this.__positionMapCursor();
    this.__zoomerLabelButton.setText($$("zoomer.label", {
      zoom: this.zoom_print
    }));
    return this.callbackPlugins("update");
  };

  ZoomerV2.prototype.zoomOut = function() {
    return this.setZoomAndPosition(this.deltaZoom(-0.05), this.getViewportMiddle());
  };

  ZoomerV2.prototype.plugins = function() {
    return [
      new AssetDetailPlugin({
        button: {
          ui: "zoomer.zoom_in.button",
          loca_key: "zoomer.button.zoom_in"
        },
        run: (function(_this) {
          return function() {
            return _this.zoomIn();
          };
        })(this)
      }), new AssetDetailPlugin({
        button: {
          ui: "zoomer.fit.button",
          loca_key: "zoomer.button.fit",
          icon: "resize_small"
        },
        run: (function(_this) {
          return function() {
            return _this.fitZoom();
          };
        })(this)
      }), new AssetDetailPlugin({
        button: {
          ui: "zoomer.zoom_out.button",
          loca_key: "zoomer.button.zoom_out"
        },
        run: (function(_this) {
          return function() {
            return _this.zoomOut();
          };
        })(this)
      })
    ];
  };

  ZoomerV2.prototype.fitScreen = function() {
    var zoom;
    this.fitZoom();
    if (this.fit.left > 0) {
      zoom = this.viewport.width / this.width;
    } else if (this.fit.top > 0) {
      zoom = this.viewport.height / this.height;
    }
    if (zoom > 1) {
      zoom = this.limitZoom(zoom);
    }
    this.setZoomAndPosition(zoom, this.getViewportMiddle());
    return this;
  };

  ZoomerV2.prototype.__scheduleRender = function() {
    if (this.__renderPending) {
      return;
    }
    this.__renderPending = true;
    return requestAnimationFrame((function(_this) {
      return function() {
        _this.__renderPending = false;
        return _this.__render();
      };
    })(this));
  };

  ZoomerV2.prototype.__render = function() {
    var ctx, cx, cy, drawH, drawW, dx, dy, h, imgH, imgW, ref, ref1, ref2, w;
    if (!this.__canvas) {
      return;
    }
    ctx = this.__canvas.getContext("2d");
    w = this.__canvas.width;
    h = this.__canvas.height;
    ctx.clearRect(0, 0, w, h);
    ctx.imageSmoothingEnabled = this.zoom <= 1;
    imgW = this.width * this.zoom;
    imgH = this.height * this.zoom;
    ctx.save();
    ctx.beginPath();
    ctx.rect(this.__panX, this.__panY, imgW, imgH);
    ctx.clip();
    if (this.rotate.z !== 0 || this.rotate.x !== 0 || this.rotate.y !== 0) {
      cx = this.__panX + imgW / 2;
      cy = this.__panY + imgH / 2;
      ctx.translate(cx, cy);
      if (this.rotate.z !== 0) {
        ctx.rotate(this.rotate.z * Math.PI / 180);
      }
      if (this.rotate.y === 180) {
        ctx.scale(-1, 1);
      }
      if (this.rotate.x === 180) {
        ctx.scale(1, -1);
      }
      ctx.translate(-cx, -cy);
      if ((ref = this.rotate.z) === 90 || ref === 270) {
        dx = (imgW - imgH) / 2;
        dy = (imgH - imgW) / 2;
        ctx.translate(dx, dy);
      }
    }
    if (this.__bgImgLoaded) {
      drawW = (ref1 = this.rotate.z) === 90 || ref1 === 270 ? imgH : imgW;
      drawH = (ref2 = this.rotate.z) === 90 || ref2 === 270 ? imgW : imgH;
      ctx.drawImage(this.__bgImg, this.__panX, this.__panY, drawW, drawH);
    }
    this.__drawCachedTiles(ctx, imgW, imgH);
    return ctx.restore();
  };

  ZoomerV2.prototype.TILE_LEVELS = [0.05, 0.1, 0.2, 0.25, 0.4, 0.5, 0.8, 1.0];

  ZoomerV2.prototype.__getTileLevel = function(zoom) {
    var effectiveZoom, i, len, level, ref;
    effectiveZoom = Math.min(zoom, 1);
    ref = this.TILE_LEVELS;
    for (i = 0, len = ref.length; i < len; i++) {
      level = ref[i];
      if (level >= effectiveZoom) {
        return level;
      }
    }
    return 1.0;
  };

  ZoomerV2.prototype.__drawCachedTiles = function(ctx, imgW, imgH) {
    var canvasB, canvasR, canvasX, canvasY, displayScale, e, entry, groups, i, j, key, len, len1, ref, results, tileZoom, tiles, x, y, zKey, zoomKeys;
    groups = {};
    ref = this.__tileCache;
    for (key in ref) {
      entry = ref[key];
      if (!entry.loaded) {
        continue;
      }
      zKey = String(entry.tileZoom);
      if (!groups[zKey]) {
        groups[zKey] = [];
      }
      groups[zKey].push(entry);
    }
    zoomKeys = [];
    for (zKey in groups) {
      zoomKeys.push(zKey);
    }
    zoomKeys.sort(function(a, b) {
      return parseFloat(a) - parseFloat(b);
    });
    results = [];
    for (i = 0, len = zoomKeys.length; i < len; i++) {
      zKey = zoomKeys[i];
      tiles = groups[zKey];
      tileZoom = parseFloat(zKey);
      displayScale = this.zoom / tileZoom;
      ctx.save();
      ctx.translate(this.__panX, this.__panY);
      ctx.scale(displayScale, displayScale);
      for (j = 0, len1 = tiles.length; j < len1; j++) {
        entry = tiles[j];
        x = entry.tx * this.tileSize;
        y = entry.ty * this.tileSize;
        canvasX = this.__panX + x * displayScale;
        canvasY = this.__panY + y * displayScale;
        canvasR = canvasX + this.tileSize * displayScale;
        canvasB = canvasY + this.tileSize * displayScale;
        if (canvasR < 0 || canvasX > this.viewport.width || canvasB < 0 || canvasY > this.viewport.height) {
          continue;
        }
        try {
          ctx.drawImage(entry.img, x, y);
        } catch (error) {
          e = error;
        }
      }
      results.push(ctx.restore());
    }
    return results;
  };

  ZoomerV2.prototype.__buildTileUrl = function(tile_x, tile_y, total_width) {
    var parts;
    parts = ["zoom" + (Math.round(total_width))];
    parts.push("part" + tile_x + "x" + tile_y + ".jpg");
    return this.__url + "/" + parts.join("/") + this.__url_search;
  };

  ZoomerV2.prototype.__loadVisibleTiles = function() {
    if (!(this.zoom && this.viewport)) {
      return;
    }
    if (this.__tileLoadTimeout) {
      CUI.clearTimeout(this.__tileLoadTimeout);
    }
    return this.__tileLoadTimeout = CUI.setTimeout((function(_this) {
      return function() {
        _this.__tileLoadTimeout = null;
        return _this.__doLoadVisibleTiles();
      };
    })(this), 100);
  };

  ZoomerV2.prototype.__doLoadVisibleTiles = function() {
    var cacheKey, firstTileX, firstTileY, i, j, k, lastTileX, lastTileY, maxTileX, maxTileY, preX1, preX2, preY1, preY2, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, results, tileLevel, totalH, totalW, tx, ty, uH, uW, visBottom, visLeft, visRight, visTop;
    if (!(this.zoom && this.viewport)) {
      return;
    }
    uW = (ref = this.rotate.z) === 90 || ref === 270 ? this.height : this.width;
    uH = (ref1 = this.rotate.z) === 90 || ref1 === 270 ? this.width : this.height;
    tileLevel = this.__getTileLevel(this.zoom);
    totalW = uW * tileLevel;
    totalH = uH * tileLevel;
    visLeft = (-this.__panX / this.zoom) * tileLevel;
    visTop = (-this.__panY / this.zoom) * tileLevel;
    visRight = visLeft + (this.viewport.width / this.zoom) * tileLevel;
    visBottom = visTop + (this.viewport.height / this.zoom) * tileLevel;
    visLeft = Math.max(0, visLeft);
    visTop = Math.max(0, visTop);
    visRight = Math.min(totalW, visRight);
    visBottom = Math.min(totalH, visBottom);
    if (visRight <= visLeft || visBottom <= visTop) {
      return;
    }
    firstTileX = Math.floor(visLeft / this.tileSize);
    firstTileY = Math.floor(visTop / this.tileSize);
    lastTileX = Math.ceil(visRight / this.tileSize);
    lastTileY = Math.ceil(visBottom / this.tileSize);
    for (ty = i = ref2 = firstTileY, ref3 = lastTileY; ref2 <= ref3 ? i < ref3 : i > ref3; ty = ref2 <= ref3 ? ++i : --i) {
      for (tx = j = ref4 = firstTileX, ref5 = lastTileX; ref4 <= ref5 ? j < ref5 : j > ref5; tx = ref4 <= ref5 ? ++j : --j) {
        cacheKey = tileLevel + "_" + tx + "_" + ty;
        if (((ref6 = this.__tileCache[cacheKey]) != null ? ref6.loaded : void 0) || this.__pendingTiles[cacheKey]) {
          continue;
        }
        if (this.__hasSufficientCoverage(tx, ty, tileLevel)) {
          continue;
        }
        this.__requestTile(tx, ty, tileLevel, totalW);
      }
    }
    maxTileX = Math.ceil(totalW / this.tileSize);
    maxTileY = Math.ceil(totalH / this.tileSize);
    preX1 = Math.max(0, firstTileX - 1);
    preY1 = Math.max(0, firstTileY - 1);
    preX2 = Math.min(maxTileX, lastTileX + 1);
    preY2 = Math.min(maxTileY, lastTileY + 1);
    results = [];
    for (ty = k = ref7 = preY1, ref8 = preY2; ref7 <= ref8 ? k < ref8 : k > ref8; ty = ref7 <= ref8 ? ++k : --k) {
      results.push((function() {
        var l, ref10, ref11, ref9, results1;
        results1 = [];
        for (tx = l = ref9 = preX1, ref10 = preX2; ref9 <= ref10 ? l < ref10 : l > ref10; tx = ref9 <= ref10 ? ++l : --l) {
          if (tx >= firstTileX && tx < lastTileX && ty >= firstTileY && ty < lastTileY) {
            continue;
          }
          cacheKey = tileLevel + "_" + tx + "_" + ty;
          if (((ref11 = this.__tileCache[cacheKey]) != null ? ref11.loaded : void 0) || this.__pendingTiles[cacheKey]) {
            continue;
          }
          if (this.__hasSufficientCoverage(tx, ty, tileLevel)) {
            continue;
          }
          results1.push(this.__requestTile(tx, ty, tileLevel, totalW));
        }
        return results1;
      }).call(this));
    }
    return results;
  };

  ZoomerV2.prototype.__hasSufficientCoverage = function(tx, ty, effectiveZoom) {
    var eB, eR, eX, eY, entry, key, ref, tileImgB, tileImgR, tileImgX, tileImgY;
    tileImgX = tx * this.tileSize / effectiveZoom;
    tileImgY = ty * this.tileSize / effectiveZoom;
    tileImgR = (tx + 1) * this.tileSize / effectiveZoom;
    tileImgB = (ty + 1) * this.tileSize / effectiveZoom;
    ref = this.__tileCache;
    for (key in ref) {
      entry = ref[key];
      if (!entry.loaded || entry.tileZoom < effectiveZoom) {
        continue;
      }
      eX = entry.tx * this.tileSize / entry.tileZoom;
      eY = entry.ty * this.tileSize / entry.tileZoom;
      eR = (entry.tx + 1) * this.tileSize / entry.tileZoom;
      eB = (entry.ty + 1) * this.tileSize / entry.tileZoom;
      if (eX <= tileImgX && eY <= tileImgY && eR >= tileImgR && eB >= tileImgB) {
        return true;
      }
    }
    return false;
  };

  ZoomerV2.prototype.__requestTile = function(tx, ty, zoom, totalWidth) {
    var cacheKey, img, url;
    cacheKey = zoom + "_" + tx + "_" + ty;
    if (this.__pendingTiles[cacheKey]) {
      return;
    }
    url = this.__buildTileUrl(tx, ty, totalWidth);
    img = new Image();
    img.crossOrigin = "anonymous";
    this.__pendingTiles[cacheKey] = img;
    img.onload = (function(_this) {
      return function() {
        var ref;
        delete _this.__pendingTiles[cacheKey];
        _this.__addToCache(cacheKey, img, tx, ty, zoom);
        if (!_this.__firstTileLoaded) {
          _this.__firstTileLoaded = true;
          if ((ref = _this.__waitBlock) != null) {
            ref.hide();
          }
        }
        return _this.__scheduleRender();
      };
    })(this);
    img.onerror = (function(_this) {
      return function() {
        return delete _this.__pendingTiles[cacheKey];
      };
    })(this);
    return img.src = url;
  };

  ZoomerV2.prototype.__addToCache = function(key, img, tx, ty, zoom) {
    var idx;
    if (this.__tileCache[key]) {
      idx = this.__tileCacheOrder.indexOf(key);
      if (idx >= 0) {
        this.__tileCacheOrder.splice(idx, 1);
      }
      this.__tileCacheOrder.push(key);
      this.__tileCache[key].img = img;
      this.__tileCache[key].loaded = true;
      return;
    }
    this.__tileCache[key] = {
      img: img,
      loaded: true,
      tx: tx,
      ty: ty,
      tileZoom: zoom
    };
    this.__tileCacheOrder.push(key);
    return this.__evictCache();
  };

  ZoomerV2.prototype.__evictCache = function() {
    var oldKey, results;
    results = [];
    while (this.__tileCacheOrder.length > this.MAX_CACHE_TILES) {
      oldKey = this.__tileCacheOrder.shift();
      results.push(delete this.__tileCache[oldKey]);
    }
    return results;
  };

  ZoomerV2.prototype.__createMap = function() {
    this.mapDiv = CUI.dom.div("zoomer-map zoomer-v2-map");
    this.mapDivInner = CUI.dom.div("zoomer-map-inner");
    CUI.dom.append(this.mapDiv, this.mapDivInner);
    CUI.dom.setStyle(this.mapDivInner, {
      backgroundImage: "url(" + this.__thumbnailUrl + ")"
    });
    this.mapDivCursor = CUI.dom.div("zoomer-map-cursor");
    this.mapDivCursor.appendChild(CUI.dom.div("zoomer-map-cursor-inner"));
    this.mapDiv.appendChild(this.mapDivCursor);
    CUI.Events.listen({
      type: "mousedown",
      node: this.mapDiv,
      call: (function(_this) {
        return function(ev) {
          var ch, clickX, clickY, cursorLeft, cursorTop, cw, mapRect, nativeEv, ref, ref1, ref2, syntheticEvent, target;
          target = ev.getNativeEvent().target;
          if (CUI.dom.closest(target, ".zoomer-map-cursor")) {
            return;
          }
          nativeEv = ev.getNativeEvent();
          mapRect = _this.mapDiv.getBoundingClientRect();
          clickX = nativeEv.clientX - mapRect.left;
          clickY = nativeEv.clientY - mapRect.top;
          cw = ((ref = _this.mapCursor) != null ? ref.width : void 0) || 0;
          ch = ((ref1 = _this.mapCursor) != null ? ref1.height : void 0) || 0;
          cursorLeft = Math.max(0, Math.min(clickX - cw / 2, _this.map.width - cw));
          cursorTop = Math.max(0, Math.min(clickY - ch / 2, _this.map.height - ch));
          CUI.dom.setStyle(_this.mapDivCursor, {
            left: cursorLeft,
            top: cursorTop
          });
          _this.__panX = cursorLeft / _this.map.zoom * -_this.zoom;
          _this.__panY = cursorTop / _this.map.zoom * -_this.zoom;
          ref2 = _this.__clampPan(_this.__panX, _this.__panY), _this.__panX = ref2[0], _this.__panY = ref2[1];
          _this.__scheduleRender();
          _this.__updateMapAndLabel();
          _this.__loadVisibleTiles();
          ev.stopPropagation();
          ev.preventDefault();
          syntheticEvent = new MouseEvent("mousedown", {
            bubbles: true,
            clientX: nativeEv.clientX,
            clientY: nativeEv.clientY,
            button: 0
          });
          return _this.mapDivCursor.dispatchEvent(syntheticEvent);
        };
      })(this)
    });
    new CUI.Movable({
      element: this.mapDivCursor,
      dragstart: (function(_this) {
        return function(ev, gd) {
          return gd.isMapCursor = true;
        };
      })(this),
      onPosition: (function(_this) {
        return function(x, y) {
          if (x < 0) {
            x = 0;
          }
          if (y < 0) {
            y = 0;
          }
          x = Math.min(x, _this.map.width - _this.mapCursor.width);
          y = Math.min(y, _this.map.height - _this.mapCursor.height);
          return [x, y];
        };
      })(this),
      onPositioned: (function(_this) {
        return function(pos) {
          var ref;
          _this.__panX = pos.x / _this.map.zoom * -_this.zoom;
          _this.__panY = pos.y / _this.map.zoom * -_this.zoom;
          ref = _this.__clampPan(_this.__panX, _this.__panY), _this.__panX = ref[0], _this.__panY = ref[1];
          _this.__scheduleRender();
          _this.__updateMapAndLabel();
          return _this.__loadVisibleTiles();
        };
      })(this)
    });
    return CUI.dom.append(this.outerDiv, this.mapDiv);
  };

  ZoomerV2.prototype.__sizeMap = function() {
    var ref;
    this.map = {
      size: 0.2
    };
    ref = ez5.fitRectangle(this.width, this.height, this.viewport.width * this.map.size, this.viewport.height * this.map.size), this.map.width = ref[0], this.map.height = ref[1];
    this.map.zoom = this.map.width / this.width;
    CUI.dom.setStyle(this.mapDiv, {
      width: this.map.width,
      height: this.map.height,
      right: 10,
      bottom: 10
    });
    this.__setMapInnerStyle(this.mapDivInner, this.map);
    return this;
  };

  ZoomerV2.prototype.__setMapInnerStyle = function(div, set) {
    var inner, ref, ref1, ref2;
    inner = {};
    if ((ref = this.rotate.z) === 90 || ref === 270) {
      ref1 = [set.height, set.width], inner.width = ref1[0], inner.height = ref1[1];
      inner.left = -(inner.width / 2) + (set.width / 2);
      inner.top = -(inner.height / 2) + (set.height / 2);
    } else {
      ref2 = [set.width, set.height], inner.width = ref2[0], inner.height = ref2[1];
      inner.left = 0;
      inner.top = 0;
    }
    CUI.dom.setStyle(div, inner);
    EAS.setTransformStyle(div, this.__transform, false);
    return this;
  };

  ZoomerV2.prototype.__positionMapCursor = function() {
    if (!(this.map && this.zoom)) {
      return;
    }
    this.mapCursor = {
      top: -this.__panY / this.zoom * this.map.zoom,
      left: -this.__panX / this.zoom * this.map.zoom,
      width: this.viewport.width / this.zoom * this.map.zoom,
      height: this.viewport.height / this.zoom * this.map.zoom
    };
    return CUI.dom.setStyle(this.mapDivCursor, this.mapCursor);
  };

  ZoomerV2.prototype.getInnerDivPos = function() {
    return {
      left: this.__panX,
      top: this.__panY,
      width: this.width * this.zoom,
      height: this.height * this.zoom
    };
  };

  ZoomerV2.prototype.destroy = function() {
    var img, key, ref, ref1;
    if (this.__wheelRafId) {
      cancelAnimationFrame(this.__wheelRafId);
    }
    this.__wheelRafId = null;
    if (this.__dragLabelRafId) {
      cancelAnimationFrame(this.__dragLabelRafId);
    }
    this.__dragLabelRafId = null;
    if (this.__momentumRafId) {
      cancelAnimationFrame(this.__momentumRafId);
    }
    this.__momentumRafId = null;
    if (this.__tileLoadTimeout) {
      CUI.clearTimeout(this.__tileLoadTimeout);
    }
    this.__tileLoadTimeout = null;
    ref = this.__pendingTiles;
    for (key in ref) {
      img = ref[key];
      img.src = "";
    }
    this.__pendingTiles = {};
    this.__tileCache = {};
    this.__tileCacheOrder = [];
    if ((ref1 = this.__waitBlock) != null) {
      ref1.destroy();
    }
    this.__waitBlock = null;
    this.__canvas = null;
    return ZoomerV2.__super__.destroy.call(this);
  };

  ZoomerV2.prototype.reload = function(asset) {
    this.destroy();
    this.start(asset);
    return this;
  };

  ZoomerV2.prototype.update = function(asset) {
    var zoom;
    zoom = this.zoom;
    delete this.zoom;
    this.reload(asset);
    this.setZoomAndPosition(zoom, this.getViewportMiddle());
    return this;
  };

  return ZoomerV2;

})(AssetDetail);
// Generated by CoffeeScript 1.12.7
var VideoPlayer,
  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;

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

  function VideoPlayer() {
    this.setThumbnail = bind(this.setThumbnail, this);
    this.toggleAdvancedTools = bind(this.toggleAdvancedTools, this);
    return VideoPlayer.__super__.constructor.apply(this, arguments);
  }

  VideoPlayer.prototype.cls = "video";

  VideoPlayer.UNSUPPORTED_CODECS = ["H.265"];

  VideoPlayer.prototype.getVersions = function(asset) {
    return Asset.getVideoVersions(asset.value);
  };

  VideoPlayer.prototype.initPlugins = function() {
    var advanceConfigurationTool, data, i, j, len, len1, opts, originalNotSupported, ref, ref1, txt, unsupportedCodec, version, videoCodec;
    opts = [];
    data = {
      version: null
    };
    originalNotSupported = false;
    ref = VideoPlayer.UNSUPPORTED_CODECS;
    for (i = 0, len = ref.length; i < len; i++) {
      unsupportedCodec = ref[i];
      videoCodec = this.asset.value.technical_metadata.video_codec;
      if (!videoCodec) {
        continue;
      }
      if (videoCodec.indexOf(unsupportedCodec) === -1) {
        continue;
      }
      originalNotSupported = true;
      break;
    }
    ref1 = this.getVersions(this.asset);
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      version = ref1[j];
      if (version.version === "original") {
        if (originalNotSupported) {
          continue;
        }
        txt = $$("asset_detail.player.video.original_version", {
          height: version.height
        });
      } else {
        txt = version.version;
      }
      opts.push({
        text: txt,
        value: version
      });
    }
    opts.sort(function(a, b) {
      if (a.value.height > b.value.height || a.value.version === "original") {
        return -1;
      } else if (a.value.height < b.value.height) {
        return 1;
      } else {
        return 0;
      }
    });
    data.version = opts[0].value;
    this.__plugins = [
      new AssetDetailPlugin({
        start: (function(_this) {
          return function() {
            return _this.initPlayer(data.version);
          };
        })(this),
        render: (function(_this) {
          return function() {
            if (opts.length === 1) {
              return;
            }
            return new CUI.Select({
              data: data,
              mark_changed: false,
              name: "version",
              options: opts,
              onDataChanged: function() {
                return _this.initPlayer(data.version);
              }
            }).start().DOM;
          };
        })(this)
      })
    ];
    advanceConfigurationTool = new AssetDetailPlugin({
      render: (function(_this) {
        return function() {
          _this.__advanceConfigButton = new LocaButton({
            appearance: "flat",
            icon_right: false,
            icon: "fa-cog",
            hidden: true,
            menu: {
              items: function() {
                return [
                  new LocaButton({
                    loca_key: "asset.versions.tool.set_thumbnail",
                    onClick: function() {
                      return _this.setThumbnail();
                    }
                  }), new LocaButton({
                    loca_key: "asset.versions.tool.go_to_thumbnail",
                    tooltip_disabled: $$("asset.versions.tool.go_to_thumbnail|tooltip"),
                    disabled: !_this.hasCustomThumbnail(),
                    onClick: function() {
                      return _this.goToThumbnail();
                    }
                  }), new LocaButton({
                    loca_key: "asset.versions.tool.clear_thumbnail",
                    tooltip_disabled: $$("asset.versions.tool.clear_thumbnail|tooltip"),
                    disabled: !_this.hasCustomThumbnail(),
                    onClick: function() {
                      return _this.setThumbnail(true);
                    }
                  })
                ];
              }
            }
          }, ez5.api.eas({
            api: "/" + _this.asset.value._id,
            data: {
              "permission_check_only": 1
            },
            type: "POST"
          }).done(function() {
            return _this.__hasEASPermission = true;
          }));
          return _this.__advanceConfigButton.DOM;
        };
      })(this)
    });
    if (this._editor_mode && ez5.version("6.8")) {
      this.__thumbnailTools = [
        new AssetDetailPlugin({
          render: (function(_this) {
            return function() {
              _this.__previousFrameButton = new CUI.Button({
                icon: "fa-step-backward",
                hidden: true,
                tooltip: {
                  text: $$("asset_detail.player.video.previous_frame|tooltip")
                },
                onClick: function() {
                  return _this.previousFrame();
                }
              });
              return _this.__previousFrameButton.DOM;
            };
          })(this)
        }), new AssetDetailPlugin({
          render: (function(_this) {
            return function() {
              _this.__nextFrameButton = new CUI.Button({
                icon: "fa-step-forward",
                hidden: true,
                tooltip: {
                  text: $$("asset_detail.player.video.next_frame|tooltip")
                },
                onClick: function() {
                  return _this.nextFrame();
                }
              });
              return _this.__nextFrameButton.DOM;
            };
          })(this)
        }), advanceConfigurationTool
      ];
      return this.__plugins = this.__thumbnailTools.concat(this.__plugins);
    }
  };

  VideoPlayer.prototype.getFullscreenButton = function() {};

  VideoPlayer.prototype.initPlayer = function(version) {
    var add_subtitles, i, len, node, ref, ref1, ref2, source;
    source = CUI.dom.source("", {
      src: Session.addToken(version.download_url || version.url)
    });
    this.__mediaElement = CUI.dom.$element(this.cls, "", {
      controls: true,
      autoplay: true,
      controlsList: 'nodownload',
      crossorigin: "anonymous"
    });
    CUI.dom.setStyle(this.__mediaElement, {
      width: "100%",
      height: "100%"
    });
    CUI.dom.append(this.__mediaElement, source);
    if (version["class"] = "video") {
      add_subtitles = (function(_this) {
        return function(variants) {
          var i, len, ref, ref1, results, track, trackName, value;
          ref = variants || [];
          results = [];
          for (i = 0, len = ref.length; i < len; i++) {
            value = ref[i];
            if (value.extension !== 'vtt') {
              continue;
            }
            trackName = ((ref1 = value.original_filename.match(EditorModalNew.MATCH_SUBTITLES_REGEXP)) != null ? ref1[2] : void 0) || value.original_filename_basename;
            track = CUI.dom.element("track", {
              label: trackName,
              kind: "subtitles",
              src: Session.addToken(value.versions.original.url)
            });
            results.push(CUI.dom.append(_this.__mediaElement, track));
          }
          return results;
        };
      })(this);
      if (!this.asset.values || !CUI.util.isArray(this.asset.values)) {
        if ((ref = this.asset) != null ? (ref1 = ref.values) != null ? ref1._system_object_id : void 0 : void 0) {
          ResultObject.loadAssetVariantsFromLinkedObject(this.asset, this.asset.values).done((function(_this) {
            return function(variants) {
              return add_subtitles(variants);
            };
          })(this));
        }
      } else {
        add_subtitles(this.asset.values);
      }
    }
    ref2 = CUI.dom.matchSelector(this.outerDiv, this.cls);
    for (i = 0, len = ref2.length; i < len; i++) {
      node = ref2[i];
      CUI.dom.remove(node);
    }
    CUI.dom.prepend(this.outerDiv, this.__mediaElement);
    this.__mediaElement.addEventListener("pause", (function(_this) {
      return function() {
        _this.toggleAdvancedTools(true);
        return CUI.Events.trigger({
          node: _this.__mediaElement,
          type: "asset-detail-player-play-pause",
          info: {
            asset: _this.asset,
            player: _this,
            state: "pause"
          }
        });
      };
    })(this));
    return this.__mediaElement.addEventListener("play", (function(_this) {
      return function() {
        _this.toggleAdvancedTools(false);
        return CUI.Events.trigger({
          node: _this.__mediaElement,
          type: "asset-detail-player-play-pause",
          info: {
            asset: _this.asset,
            player: _this,
            state: "play"
          }
        });
      };
    })(this));
  };

  VideoPlayer.prototype.getButtonLocaKey = function(asset) {
    if (asset.value["class"] !== this.cls) {
      return;
    }
    if (this.getVersions(asset).length === 0) {
      return;
    }
    return "asset_detail.player." + this.cls;
  };

  VideoPlayer.prototype.startOnMousewheel = function() {
    return false;
  };

  VideoPlayer.prototype.start = function(asset1, mouseWheelstart) {
    this.asset = asset1;
    this.mouseWheelstart = mouseWheelstart;
    this.initPlugins();
    VideoPlayer.__super__.start.call(this, this.asset, this.mouseWheelstart);
    this.play();
  };

  VideoPlayer.prototype.pause = function() {
    var ref;
    return (ref = this.__mediaElement) != null ? ref.pause() : void 0;
  };

  VideoPlayer.prototype.play = function() {
    var ref, ref1;
    return (ref = this.__mediaElement) != null ? (ref1 = ref.play()) != null ? ref1["catch"]((function(_this) {
      return function(err) {
        if (err.name === 'AbortError') {
          return console.log('Playback was aborted — media element may have been removed.');
        } else {
          return console.error('Error during playback:', err);
        }
      };
    })(this)) : void 0 : void 0;
  };

  VideoPlayer.prototype.getCurrentTime = function() {
    var ref;
    return (ref = this.__mediaElement) != null ? ref.currentTime : void 0;
  };

  VideoPlayer.prototype.setCurrentTime = function(currentTime) {
    var ref;
    return (ref = this.__mediaElement) != null ? ref.currentTime = currentTime || 0.0 : void 0;
  };

  VideoPlayer.prototype.isPaused = function() {
    var ref;
    return (ref = this.__mediaElement) != null ? ref.paused : void 0;
  };

  VideoPlayer.prototype.isInDOM = function() {
    return CUI.dom.isInDOM(this.__mediaElement);
  };

  VideoPlayer.prototype.isPlayer = function() {
    return true;
  };

  VideoPlayer.prototype.createMarkup = function() {
    VideoPlayer.__super__.createMarkup.call(this);
  };

  VideoPlayer.prototype.plugins = function() {
    return this.__plugins || [];
  };

  VideoPlayer.prototype.nextFrame = function() {
    var ref;
    this.pause();
    return (ref = this.__mediaElement) != null ? ref.currentTime += 1.0 / 25.0 : void 0;
  };

  VideoPlayer.prototype.previousFrame = function() {
    var ref;
    this.pause();
    return (ref = this.__mediaElement) != null ? ref.currentTime -= 1.0 / 25.0 : void 0;
  };

  VideoPlayer.prototype.hasCustomThumbnail = function() {
    var ref, ref1, ref2;
    return !!((ref = this.asset.value.custom_produce_config) != null ? (ref1 = ref.overwrites) != null ? (ref2 = ref1[0]) != null ? ref2["custom"]["video-thumb-select"] : void 0 : void 0 : void 0);
  };

  VideoPlayer.prototype.toggleAdvancedTools = function(show) {
    if (!ez5.version("6") || !this._editor_mode) {
      return;
    }
    if (show && this.__hasEASPermission) {
      this.__advanceConfigButton.show();
    } else {
      this.__advanceConfigButton.hide();
    }
    if (show) {
      this.__previousFrameButton.show();
      return this.__nextFrameButton.show();
    } else {
      this.__previousFrameButton.hide();
      return this.__nextFrameButton.hide();
    }
  };

  VideoPlayer.prototype.goToThumbnail = function() {
    var ref, time;
    this.pause();
    try {
      time = this.asset.value.custom_produce_config.overwrites[0]["custom"]["video-thumb-select"];
      if (time) {
        return (ref = this.__mediaElement) != null ? ref.currentTime = time : void 0;
      }
    } catch (error) {}
  };

  VideoPlayer.prototype.setThumbnail = function(clear) {
    var currentVideoTime, mode, thumbDialog, videoElem;
    if (clear == null) {
      clear = false;
    }
    mode = clear ? "clear" : "set";
    if (!clear) {
      videoElem = this.__mediaElement;
    }
    currentVideoTime = videoElem != null ? videoElem.currentTime : void 0;
    thumbDialog = new CUI.ConfirmationDialog({
      icon: $$("download.manager.modal.icon"),
      title: $$("asset.versions.video." + mode + "_thumbnail.title"),
      "class": "ez5-download-manager-confirmation-dialog ez5-video-thumbnail-dialog",
      content: [
        new CUI.Label({
          text: $$("asset.versions.video." + mode + "_thumbnail.text", {
            currentVideoTime: currentVideoTime
          })
        })
      ],
      buttons: [
        new CUI.Button({
          text: $$("base.cancel"),
          onClick: (function(_this) {
            return function(ev) {
              return thumbDialog.destroy();
            };
          })(this)
        }), new CUI.Button({
          text: $$("asset.versions.video." + mode + "_thumbnail.confirm"),
          primary: true,
          onClick: (function(_this) {
            return function(ev) {
              var data;
              if (clear) {
                data = {
                  "custom_produce_config": {
                    "overwrites": []
                  }
                };
              } else {
                data = {
                  "custom_produce_config": {
                    "overwrites": [
                      {
                        "match": {
                          "version_class": "image"
                        },
                        "custom": {
                          "video-thumb-select": "" + currentVideoTime
                        }
                      }
                    ]
                  }
                };
              }
              return ez5.api.eas({
                api: "/" + _this.asset.value._id,
                json_data: data,
                type: "POST"
              }).done(function(newAssetData) {
                var assetData, domElem, imgElem, ref, ref1, ref2;
                _this.asset.value.status = newAssetData.status;
                _this.asset.value.versions = newAssetData.versions;
                assetData = _this.asset.data;
                domElem = (ref = assetData[assetData._objecttype]) != null ? (ref1 = ref[_this.asset.field.name() + ":rendered"]) != null ? ref1.__element : void 0 : void 0;
                if (domElem) {
                  imgElem = (ref2 = CUI.dom.matchSelector(domElem, "img")) != null ? ref2[0] : void 0;
                  if (imgElem) {
                    CUI.Events.trigger({
                      type: "eas_update",
                      node: imgElem,
                      info: {
                        thumbnailUpdate: true
                      }
                    });
                  }
                }
                return thumbDialog.destroy();
              });
            };
          })(this)
        })
      ],
      cancel: true
    });
    return thumbDialog.show();
  };

  return VideoPlayer;

})(AssetDetail);

CUI.ready((function(_this) {
  return function() {
    return CUI.Events.registerEvent({
      type: "asset-detail-player-play-pause",
      bubble: true
    });
  };
})(this));
// Generated by CoffeeScript 1.12.7
var WebDVDPlayer,
  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;

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

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

  WebDVDPlayer.prototype.start = function(asset, mouseWheelStart, btn) {
    var dfr, promise, url;
    btn.startSpinner();
    btn.disable();
    dfr = new CUI.Deferred();
    dfr.fail((function(_this) {
      return function() {
        return CUI.problem({
          text: $$("web.dvd.player.not_found")
        });
      };
    })(this));
    if (ez5.version("6")) {
      url = asset.value.versions.original.url.replace(/^(.*?)(\?|$)/, "$1/?");
      promise = new CUI.XHR({
        url: url,
        method: "GET"
      }).start();
    } else {
      promise = ez5.api.eas({
        type: "GET",
        data: {
          ids: JSON.stringify([asset.value._id]),
          format: "long"
        }
      });
    }
    promise.fail(dfr.reject);
    promise.always((function(_this) {
      return function() {
        return btn.stopSpinner();
      };
    })(this));
    promise.done((function(_this) {
      return function(data) {
        btn.enable();
        if (ez5.version("6")) {
          _this.__eas = asset.value;
          _this.__eas.files = data;
        } else {
          _this.__eas = data[asset.value._id];
        }
        if (_this.__eas.error || !_this.__eas.files) {
          dfr.reject();
          return;
        }
        _this.__htmlFiles = _this.getTopLevelHtmlFiles();
        _this.__data = {
          idx: 0,
          screen: "1024x768"
        };
        AssetDetail.prototype.start.call(_this, asset);
        return dfr.resolve();
      };
    })(this));
    return dfr.promise();
  };

  WebDVDPlayer.prototype.getButtonLocaKey = function(asset) {
    if (!this.getWebDVDVersion(asset.value)) {
      return;
    }
    if (ez5.version("6")) {
      return "web.dvd.player.play.button.title";
    }
    return "web.dvd.player.button.title";
  };

  WebDVDPlayer.prototype.getLabelLocaKey = function() {
    return "web.dvd.player.button.title";
  };

  WebDVDPlayer.prototype.startOnMousewheel = function() {
    return true;
  };

  WebDVDPlayer.prototype.getWebDVDVersion = function(value) {
    var i, len, version, vname, vnames;
    if (value["class"] !== "archive" && !ez5.version("6")) {
      return;
    }
    if (ez5.version("6")) {
      if (value.extension !== "webdvd.zip" || !value.versions["original"]) {
        return;
      }
      return value.versions["original"];
    }
    vnames = Asset.getVersionNamesForClass(value["class"], false);
    if (!(vnames != null ? vnames.length : void 0) > 0) {
      return;
    }
    for (i = 0, len = vnames.length; i < len; i++) {
      vname = vnames[i];
      version = value.versions[vname];
      if (!version || version._not_allowed) {
        continue;
      }
      if (version["class"] === "directory" && version.status === "done" && version.webdvd_url) {
        return version;
      }
    }
  };

  WebDVDPlayer.prototype.isPlayer = function() {
    return true;
  };

  WebDVDPlayer.prototype.plugins = function() {
    var html_file, i, idx, len, opts, opts2, plugins, ref, ref1;
    if (ez5.version("6")) {
      plugins = [];
    } else {
      plugins = [
        new AssetDetailPlugin({
          button: {
            loca_key: "web.dvd.player.button.fullscreen"
          },
          run: (function(_this) {
            return function() {
              return window.open(_this.getStartUrl(), "_blank", ez5.session.getClientDefault("webdvd_player_open_window_parameter") || "");
            };
          })(this)
        })
      ];
    }
    if (!((ref = this.__htmlFiles) != null ? ref.length : void 0)) {
      return plugins;
    }
    opts = [];
    ref1 = this.__htmlFiles;
    for (idx = i = 0, len = ref1.length; i < len; idx = ++i) {
      html_file = ref1[idx];
      opts.push({
        value: idx,
        text: html_file.path
      });
    }
    if (this.__htmlFiles.length > 1) {
      plugins.push(new AssetDetailPlugin({
        render: (function(_this) {
          return function() {
            return new CUI.Select({
              data: _this.__data,
              tooltip: {
                text: $$("web.dvd.player.button.start_file.tooltip")
              },
              name: "idx",
              onDataChanged: function() {
                return _this.showStartUrl();
              },
              options: opts
            }).start();
          };
        })(this)
      }));
    }
    opts2 = [
      {
        value: "1024x768",
        text: "1024x768"
      }, {
        value: "800x600",
        text: "800x600"
      }
    ];
    if (!ez5.version("6")) {
      plugins.push(new AssetDetailPlugin({
        render: (function(_this) {
          return function() {
            return new CUI.Select({
              data: _this.__data,
              name: "screen",
              tooltip: {
                text: $$("web.dvd.player.button.screen.tooltip")
              },
              onDataChanged: function() {
                return _this.showStartUrl();
              },
              options: opts2
            }).start();
          };
        })(this)
      }));
    }
    return plugins;
  };

  WebDVDPlayer.prototype.createMarkup = function() {
    WebDVDPlayer.__super__.createMarkup.call(this);
    this.showStartUrl();
    return this;
  };

  WebDVDPlayer.prototype.getTopLevelHtmlFiles = function() {
    var file, files, html_files, i, j, len, len1, min_depth;
    files = this.__eas.files;
    min_depth = null;
    for (i = 0, len = files.length; i < len; i++) {
      file = files[i];
      file.depth = file.path.split("/").length - 1;
      if ((min_depth === null || file.depth < min_depth) && file.path.endsWith(".html")) {
        min_depth = file.depth;
      }
    }
    html_files = [];
    if (min_depth !== null) {
      for (j = 0, len1 = files.length; j < len1; j++) {
        file = files[j];
        if (file.depth === min_depth && file.path.endsWith(".html")) {
          html_files.push(file);
        }
      }
    }
    console.debug("top level html files found", html_files);
    return html_files;
  };

  WebDVDPlayer.prototype.getStartUrl = function(append) {
    var p, version;
    if (append == null) {
      append = "";
    }
    console.debug("getStartUrl for webdvd", this.__eas);
    version = this.getWebDVDVersion(this.__eas);
    if (ez5.version("6")) {
      p = version.url.replace(/^(.*?)(\?|$)/, "$1" + this.__htmlFiles[this.__data.idx].path + "?");
    } else {
      p = ez5.getAbsoluteURL(version.webdvd_url) + "/" + this.__htmlFiles[this.__data.idx].path;
    }
    if (p.match(/\?/)) {
      return p = p + "&" + append;
    } else {
      return p = p + "?" + append;
    }
  };

  WebDVDPlayer.prototype.showStartUrl = function() {
    if (this.__iframe) {
      this.__iframe.remove();
    }
    this.__iframe = CUI.dom.$element("iframe", "ez5-webdvd-player", {
      name: "webdvd-player",
      src: this.getStartUrl()
    });
    if (ez5.version("6")) {
      this.__iframe.onload = (function(_this) {
        return function() {
          var doc;
          doc = _this.__iframe.contentDocument || _this.__iframe.contentWindow.document;
          doc.querySelectorAll('a').forEach(function(link) {
            return link.href = Session.addToken(link.href);
          });
          return doc.querySelectorAll('video[src], video source[src]').forEach(function(element) {
            var src, video;
            src = element.src || element.getAttribute('src');
            if (src) {
              video = element.tagName === 'VIDEO' ? element : element.parentElement;
              video.src = Session.addToken(src);
              return video.load();
            }
          });
        };
      })(this);
    }
    CUI.dom.append(this.getOuterDiv(), this.__iframe);
    this.resize();
    return this;
  };

  WebDVDPlayer.prototype.resize = function() {
    var dim, h, margin_left, margin_top, ref, screen, transform, w, zoom;
    screen = this.__data.screen.split("x");
    dim = this.getViewport();
    if (dim.width === 0 || dim.height === 0) {
      return;
    }
    ref = ez5.fitRectangle(screen[0], screen[1], dim.width, dim.height), w = ref[0], h = ref[1], margin_top = ref[2], margin_left = ref[3];
    zoom = w / screen[0];
    transform = "scale(" + zoom + ") translateX(" + (margin_left / zoom) + "px) translateY(" + (margin_top / zoom) + "px)";
    CUI.dom.setStyle(this.__iframe, {
      width: screen[0],
      height: screen[1],
      transform: transform,
      transformOrigin: "0 0"
    });
    return this;
  };

  WebDVDPlayer.prototype.destroy = function() {
    this.__iframe = null;
    return WebDVDPlayer.__super__.destroy.call(this);
  };

  return WebDVDPlayer;

})(AssetDetail);
// Generated by CoffeeScript 1.12.7
var AudioPlayer,
  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;

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

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

  AudioPlayer.prototype.cls = "audio";

  AudioPlayer.prototype.getFullscreenButton = function() {};

  AudioPlayer.prototype.initPlayer = function() {
    AudioPlayer.__super__.initPlayer.apply(this, arguments);
    return CUI.dom.setStyle(this.__mediaElement, {
      height: ""
    });
  };

  AudioPlayer.prototype.getVersions = function(asset) {
    return Asset.getAudioVersions(asset.value);
  };

  return AudioPlayer;

})(VideoPlayer);
// Generated by CoffeeScript 1.12.7
var GifPlayer,
  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;

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

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

  GifPlayer.prototype.getButtonLocaKey = function(asset) {
    var ref, ref1;
    if (asset.value["class"] !== "image") {
      return;
    }
    if ((ref = asset.value.extension) !== "gif" && ref !== "GIF" && ref !== "webp" && ref !== "WEBP") {
      return;
    }
    if (((ref1 = asset.value.versions.original) != null ? ref1.status : void 0) !== "done") {
      return;
    }
    return "gifplayer.button.title";
  };

  GifPlayer.prototype.getLabelLocaKey = function(asset) {
    return "gifplayer.label.title";
  };

  GifPlayer.prototype.start = function(asset, mouseWheelstart) {
    var img;
    GifPlayer.__super__.start.call(this, asset, mouseWheelstart);
    img = asset.getImgElement(null, "original");
    if (img) {
      CUI.dom.append(this.__container, img);
    } else {
      this.close();
    }
  };

  GifPlayer.prototype.createMarkup = function() {
    GifPlayer.__super__.createMarkup.call(this);
    this.__container = CUI.dom.div("gif-player-container");
    CUI.dom.append(this.outerDiv, this.__container);
  };

  GifPlayer.prototype.close = function() {
    this.destroy();
    return CUI.Events.trigger({
      type: "viewport-resize"
    });
  };

  return GifPlayer;

})(AssetDetail);
// Generated by CoffeeScript 1.12.7
var MetadataBrowser,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  MetadataBrowser.prototype.start = function(asset, mousewheelStart, btn) {
    btn.disable();
    btn.startSpinner();
    return this.load(asset.value._id).always((function(_this) {
      return function() {
        btn.enable();
        return btn.stopSpinner();
      };
    })(this)).done((function(_this) {
      return function(data) {
        return AssetDetail.prototype.start.call(_this, asset);
      };
    })(this));
  };

  MetadataBrowser.prototype.load = function(eas_id) {
    var dfr;
    dfr = new CUI.Deferred();
    ez5.api.eas({
      type: "GET",
      data: {
        ids: JSON.stringify([eas_id]),
        format: "long"
      }
    }).done((function(_this) {
      return function(data) {
        _this.__eas = data[eas_id];
        if (_this.__eas.error) {
          return dfr.reject();
        } else {
          return dfr.resolve();
        }
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  MetadataBrowser.prototype.getButtonLocaKey = function(asset) {
    if (!asset.value.class_extension) {
      return;
    }
    if (!ez5.session.hasSystemRight("root", "frontend_features[asset_browser_metadata_tool]")) {
      return;
    }
    return "metadata.browser.title";
  };

  MetadataBrowser.prototype.getLabelLocaKey = function() {
    return "metadata.browser.title";
  };

  MetadataBrowser.prototype.createMarkup = function() {
    var lay;
    MetadataBrowser.__super__.createMarkup.call(this);
    lay = new CUI.SimplePane({
      "class": "ez5-metadata-browser",
      header_left: new CUI.Label({
        text: this.asset.value.compiled
      })
    });
    this.appendMarkup(lay.center());
    CUI.dom.append(this.outerDiv, lay.DOM);
    return lay;
  };

  MetadataBrowser.prototype.appendMarkup = function(markup_div) {
    var append_group, dpi, featured_groups, i, j, k, len, len1, len2, lsort, name_of_group, print_sizes, ref, ref1, results, shc, size_h, size_w, tm, tryToLocalize;
    tryToLocalize = function(key) {
      var loca_key;
      loca_key = "detail.asset_browser.info.advanced." + key;
      if (ez5.loca.has(loca_key)) {
        return $$(loca_key);
      }
      return key;
    };
    lsort = (function(_this) {
      return function(a, b) {
        return a.localeCompare(b);
      };
    })(this);
    shc = new CUI.StickyHeaderControl({
      element: markup_div
    });
    append_group = (function(_this) {
      return function(name_of_group) {
        var i, info, len, ref, sh, table;
        if (!_this.__eas.metadata.groups[name_of_group]) {
          return;
        }
        sh = new CUI.StickyHeader({
          control: shc,
          "class": "group-header",
          text: tryToLocalize(name_of_group)
        });
        markup_div.appendChild(sh.DOM);
        table = new CUI.Table({
          "class": "ez5-metadata-browser-group",
          flex: true,
          key_value: true
        });
        _this.__eas.metadata.groups[name_of_group].sort(function(a, b) {
          return a.name.localeCompare(b.name);
        });
        ref = _this.__eas.metadata.groups[name_of_group];
        for (i = 0, len = ref.length; i < len; i++) {
          info = ref[i];
          if (CUI.util.isEmpty(info.print)) {
            continue;
          }
          table.addRow({
            key: tryToLocalize(info.name),
            value: new CUI.MultilineLabel({
              text: info.print,
              manage_overflow: true
            })
          });
        }
        return markup_div.appendChild(table.DOM);
      };
    })(this);
    tm = this.__eas.technical_metadata;
    if (this.__eas.metadata.groups["EAS::PrintSizes"]) {
      print_sizes = this.__eas.metadata.groups["EAS::PrintSizes"];
      ref = [72, 150, 300, 600];
      for (i = 0, len = ref.length; i < len; i++) {
        dpi = ref[i];
        size_w = Math.round((tm.width / dpi) * 254) / 100;
        size_h = Math.round((tm.height / dpi) * 254) / 100;
        print_sizes.push({
          group: "EAS::PrintSizes",
          name: "print_size@" + dpi + "DPI",
          print: size_w + "cm x " + size_h + "cm"
        });
      }
      featured_groups = ["EAS::PrintSizes", "EAS::TypeInfo"];
    } else {
      featured_groups = ["EAS::TypeInfo"];
    }
    featured_groups.sort(lsort);
    this.__eas.metadata.groupnames.sort(lsort);
    for (j = 0, len1 = featured_groups.length; j < len1; j++) {
      name_of_group = featured_groups[j];
      append_group(name_of_group);
    }
    ref1 = this.__eas.metadata.groupnames;
    results = [];
    for (k = 0, len2 = ref1.length; k < len2; k++) {
      name_of_group = ref1[k];
      if (indexOf.call(featured_groups, name_of_group) >= 0) {
        continue;
      }
      results.push(append_group(name_of_group));
    }
    return results;
  };

  return MetadataBrowser;

})(AssetDetail);
// Generated by CoffeeScript 1.12.7
var DetailInfo,
  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;

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

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

  DetailInfo.prototype.initOpts = function() {
    DetailInfo.__super__.initOpts.call(this);
    return this.addOpts({
      resultObject: {
        mandatory: true,
        check: ResultObject
      }
    });
  };

  DetailInfo.prototype.start = function(asset, mousewheelStart, btn) {
    console.debug("DetailInfo.start", asset, mousewheelStart, btn);
    btn.setIcon("spinner");
    return ResultObject.loadFromData(this._resultObject.getData()).always((function(_this) {
      return function() {
        return btn.setIcon();
      };
    })(this)).done((function(_this) {
      return function(result_object) {
        return result_object.showModal();
      };
    })(this));
  };

  DetailInfo.prototype.getButtonLocaKey = function(asset) {
    return "detail.info.button";
  };

  DetailInfo.prototype.getLabelLocaKey = function() {
    return "detail.info.button";
  };

  DetailInfo.prototype.getFullscreenButton = function() {};

  return DetailInfo;

})(AssetDetail);
// Generated by CoffeeScript 1.12.7
var FullscreenDetailInfo,
  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;

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

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

  FullscreenDetailInfo.prototype.initOpts = function() {
    FullscreenDetailInfo.__super__.initOpts.call(this);
    this.removeOpt("resultObject");
    this.removeOpt("element");
    return this.addOpts({
      layout: {
        mandatory: true,
        check: CUI.HorizontalLayout
      },
      side: {
        mandatory: true,
        check: String
      },
      search: {
        check: Search
      },
      getGlobalObjectId: {
        mandatory: true,
        check: Function
      },
      collection: {
        check: CollectionWithDetail,
        mandatory: false
      }
    });
  };

  FullscreenDetailInfo.prototype.isButtonSwitch = function() {
    return true;
  };

  FullscreenDetailInfo.prototype.readOpts = function() {
    var flexHandlePane;
    FullscreenDetailInfo.__super__.readOpts.call(this);
    this.__sidebar = new Sidebar({
      mainLayout: this._layout,
      getSearch: (function(_this) {
        return function() {
          return _this._search;
        };
      })(this),
      detailSidebarClass: ez5.FullscreenDetailSidebar,
      collection: this._collection
    });
    flexHandlePane = this._layout.getFlexHandle(this._side).getPane();
    CUI.Events.listen({
      node: flexHandlePane,
      type: "flex-open",
      call: (function(_this) {
        return function() {
          var button;
          button = _this.__button || _this._btn;
          if (button != null) {
            button.activate();
          }
        };
      })(this)
    });
    CUI.Events.listen({
      node: flexHandlePane,
      type: "flex-close",
      call: (function(_this) {
        return function() {
          var button;
          button = _this.__button || _this._btn;
          if (button != null) {
            button.deactivate();
          }
        };
      })(this)
    });
    return this;
  };

  FullscreenDetailInfo.prototype.start = function() {
    return this.toggle();
  };

  FullscreenDetailInfo.prototype.preventOnMousewheelIfActive = function() {
    return false;
  };

  FullscreenDetailInfo.prototype.toggle = function() {
    var flexHandle;
    flexHandle = this._layout.getFlexHandle(this._side);
    if (flexHandle.isOpen() && !document.fullscreenElement) {
      flexHandle.close();
      return;
    }
    CUI.dom.exitFullscreen();
    this.loadObject();
  };

  FullscreenDetailInfo.prototype.updateObject = function() {
    var flexHandle;
    flexHandle = this._layout.getFlexHandle(this._side);
    if (flexHandle.isOpen()) {
      this.loadObject();
    }
  };

  FullscreenDetailInfo.prototype.loadObject = function() {
    var flexHandle;
    flexHandle = this._layout.getFlexHandle(this._side);
    flexHandle.open();
    flexHandle.show();
    this.__sidebar.loadDetail({
      global_object_id: this._getGlobalObjectId()
    });
  };

  FullscreenDetailInfo.prototype.updateAssetBrowserIdx = function(asset_browser_idx) {
    this.__sidebar.updateAssetBrowserIdx(asset_browser_idx);
  };

  FullscreenDetailInfo.prototype.setToggleButton = function(button) {
    return this.__button = button;
  };

  return FullscreenDetailInfo;

})(DetailInfo);
// Generated by CoffeeScript 1.12.7
var PagedViewer,
  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;

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

  function PagedViewer(opts) {
    this.opts = opts != null ? opts : {};
    this.setLastPage = bind(this.setLastPage, this);
    PagedViewer.__super__.constructor.call(this, this.opts);
    this.minimumZoom = 0.05;
    this.zoom = null;
  }

  PagedViewer.prototype.startOnMousewheel = function() {
    return true;
  };

  PagedViewer.prototype.createMarkup = function() {
    var scroll;
    PagedViewer.__super__.createMarkup.call(this);
    this.outerDiv2 = CUI.dom.div("paged-viewer-outer-div-2");
    CUI.dom.append(this.outerDiv, this.outerDiv2);
    CUI.Events.listen({
      type: "click",
      node: this.outerDiv2,
      call: (function(_this) {
        return function(ev) {
          var $page;
          $page = CUI.dom.closest(ev.getTarget(), ".paged-viewer-page");
          if (!$page) {
            return;
          }
          ev.stopPropagation();
          ev.preventDefault();
          _this.setLastPage($page);
          _this.fitZoom("fit");
        };
      })(this)
    });
    new CUI.Dragscroll({
      element: this.outerDiv2
    });
    scroll = (function(_this) {
      return function() {
        return _this.scroll();
      };
    })(this);
    CUI.Events.listen({
      type: "scroll",
      node: this.outerDiv2,
      call: (function(_this) {
        return function() {
          CUI.scheduleCallback({
            ms: 200,
            call: scroll
          });
        };
      })(this)
    });
    this.innerDiv = CUI.dom.div("paged-viewer-inner-div");
    CUI.dom.append(this.outerDiv2, this.innerDiv);
    this.initPages();
    this.fillPages();
    this.setFitDim();
    this.setZoom(0.1);
    return this;
  };

  PagedViewer.prototype.getButtonLocaKey = function(asset) {
    var cls, locaKey;
    locaKey = "paged.viewer.title";
    if (ez5.version("6") && !this.__getPagedVersion(asset.value)) {
      return;
    }
    if (!asset.value.class_extension) {
      return;
    }
    cls = asset.value.class_extension.split(".");
    if (cls[0] !== "office") {
      return;
    }
    if (!ez5.version("6") && !asset.value.pages_allowed) {
      return;
    }
    return locaKey;
  };

  PagedViewer.prototype.__getPagedVersion = function(value) {
    var name, ref, version;
    if (ez5.version("6")) {
      ref = value.versions;
      for (name in ref) {
        version = ref[name];
        if (version.extension === "pages.zip" && Asset.checkVersionShowAllowed(version)) {
          return version;
        }
      }
    }
  };

  PagedViewer.prototype.getLabelLocaKey = function() {
    return [
      "paged.viewer.label", {
        extension: this.extension
      }
    ];
  };

  PagedViewer.prototype.start = function(asset, mouseWheelstart, btn) {
    var finish_load, pagedVersion, url;
    this.mouseWheelstart = mouseWheelstart != null ? mouseWheelstart : false;
    this.extension = asset.value.class_extension.split(".")[1].toUpperCase();
    this.__pagedViewerDestroyed = false;
    btn.setIcon("spinner");
    btn.disable();
    finish_load = (function(_this) {
      return function() {
        btn.setIcon();
        btn.enable();
        AssetDetail.prototype.start.call(_this, asset, _this.mouseWheelstart, btn);
        return _this.fitScreen();
      };
    })(this);
    if (ez5.version("6")) {
      pagedVersion = this.__getPagedVersion(asset.value);
      url = pagedVersion.url.replace(/^(.*?)(\?|$)/, "$1/info.json?");
      this.__pages_base_url = pagedVersion.url;
      return new CUI.XHR({
        url: Session.addToken(url),
        method: "GET"
      }).start().done((function(_this) {
        return function(data) {
          var normalizeData, normalized_data;
          normalizeData = function(data) {
            var key, normalized, value;
            if (Array.isArray(data)) {
              return data.map(function(item) {
                return normalizeData(item);
              });
            }
            if (CUI.util.isPlainObject(data)) {
              normalized = {};
              for (key in data) {
                value = data[key];
                normalized[key.toLowerCase()] = normalizeData(value);
              }
              return normalized;
            }
            return data;
          };
          if (_this.__pagedViewerDestroyed) {
            return;
          }
          normalized_data = normalizeData(data);
          _this.__pagesData = normalized_data;
          _this.__easData = asset.value;
          _this.__easData.pages = normalized_data.pages;
          return finish_load();
        };
      })(this));
    } else {
      this.__easId = asset.value._id;
      return ez5.api.eas({
        type: "GET",
        data: {
          ids: JSON.stringify([this.__easId]),
          format: "short"
        }
      }).done((function(_this) {
        return function(data) {
          if (_this.__pagedViewerDestroyed) {
            return;
          }
          _this.__easData = data;
          return finish_load();
        };
      })(this));
    }
  };

  PagedViewer.prototype.destroy = function() {
    this.lastPage = null;
    this.__pagedViewerDestroyed = true;
    return PagedViewer.__super__.destroy.call(this);
  };

  PagedViewer.prototype.resize = function() {
    return this.setFitDim();
  };

  PagedViewer.prototype.initPages = function() {
    var c, i, idx, j, k, l, last, len, len1, len2, len3, m, name, p, ref, ref1, ref2, ref3, ref4, version;
    this.maxPageDim = {
      width: null,
      height: null
    };
    last = {
      width: null,
      height: null
    };
    if (this.__easData.pages) {
      this.asset_data = this.__easData;
    } else {
      this.asset_data = this.__easData[this.__easId];
      this.asset_data.pages = [];
      ref = this.asset_data.children || [this.__easId];
      for (i = 0, len = ref.length; i < len; i++) {
        c = ref[i];
        this.asset_data.pages.push(this.__easData[c]);
      }
    }
    ref1 = this.asset_data.pages;
    for (idx = j = 0, len1 = ref1.length; j < len1; idx = ++j) {
      p = ref1[idx];
      p.current_version = null;
      p.idx = idx;
      if (ez5.version("6")) {
        if (p.technical_metadata == null) {
          p.technical_metadata = {};
        }
        ref2 = ["width", "height"];
        for (l = 0, len2 = ref2.length; l < len2; l++) {
          k = ref2[l];
          if (p.versions[p.versions.length - 1].technical_metadata) {
            p.technical_metadata[k] = p.versions[p.versions.length - 1].technical_metadata[k];
          } else if (p.versions[p.versions.length - 1].technicalmetadata) {
            p.technical_metadata[k] = p.versions[p.versions.length - 1].technicalmetadata[k];
          }
        }
      } else {
        ref3 = ["width", "height"];
        for (m = 0, len3 = ref3.length; m < len3; m++) {
          k = ref3[m];
          if (!p.technical_metadata[k]) {
            p.technical_metadata[k] = last[k] || 1000;
          } else {
            last[k] = p.technical_metadata[k];
          }
        }
      }
      p.versions_sorted_by_size = [];
      ref4 = p.versions;
      for (name in ref4) {
        version = ref4[name];
        if (!ez5.version("6") && (version._not_allowed || version.status !== "done")) {
          continue;
        }
        version.name = name;
        if (ez5.version("6")) {
          version.url = this.__pages_base_url.replace(/^(.*?)(\?|$)/, "$1" + version.path + "?");
        }
        p.versions_sorted_by_size.push(version);
      }
      p.versions_sorted_by_size.sort((function(_this) {
        return function(a, b) {
          if (a.width < b.width || a.height < b.height) {
            return -1;
          } else if (a.width > b.width || a.height > b.height) {
            return 1;
          } else {
            return 0;
          }
        };
      })(this));
      this.maxPageDim.width = Math.max(this.maxPageDim.width, p.technical_metadata.width);
      this.maxPageDim.height = Math.max(this.maxPageDim.height, p.technical_metadata.height);
    }
  };

  PagedViewer.prototype.fillPages = function() {
    var divPageNumber, i, idx, len, p, ref;
    ref = this.asset_data.pages;
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      p = ref[idx];
      p.$page = CUI.dom.div("paged-viewer-page");
      divPageNumber = CUI.dom.div("page-number");
      divPageNumber.textContent = idx + 1;
      CUI.dom.append(p.$page, divPageNumber);
      CUI.dom.data(p.$page, "page", p);
      CUI.Events.listen({
        node: p.$page,
        type: "click",
        call: (function(_this) {
          return function(ev) {
            var page;
            if (!ev.shiftKey()) {
              return;
            }
            page = ev.getTarget();
            ev.preventDefault();
            ev.stopImmediatePropagation();
            return p = CUI.dom.data(page);
          };
        })(this)
      });
      CUI.dom.append(this.innerDiv, p.$page);
    }
    return this;
  };

  PagedViewer.prototype.setFitDim = function() {
    var ref;
    this.fit = {};
    return ref = ez5.fitRectangle(this.maxPageDim.width, this.maxPageDim.height, this.viewport.width || 1000, this.viewport.height || 1000), this.fit.width = ref[0], this.fit.height = ref[1], this.fit.top = ref[2], this.fit.left = ref[3], ref;
  };

  PagedViewer.prototype.setZoom = function(zoom) {
    var i, idx, len, p, ref;
    if (zoom < this.minimumZoom) {
      zoom = this.minimumZoom;
    }
    if (this.zoom !== zoom) {
      this.zoom = zoom;
      ref = this.asset_data.pages;
      for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
        p = ref[idx];
        p.size = {
          marginBoxWidth: Math.round(p.technical_metadata.width * this.zoom),
          marginBoxHeight: Math.round(p.technical_metadata.height * this.zoom)
        };
        CUI.dom.setDimensions(p.$page, p.size);
      }
      if (this.viewport.width / (this.maxPageDim.width * this.zoom) >= 3) {
        CUI.dom.addClass(this.outerDiv, "paged-viewer-thumbnails");
      } else {
        CUI.dom.removeClass(this.outerDiv, "paged-viewer-thumbnails");
      }
      return this.setVisible();
    }
  };

  PagedViewer.prototype.setVisible = function() {
    var i, idx, j, len, len1, p, page_dim, pos, ref, ref1, ref2, ref3, thumbnail_version_name, v, visible;
    visible = {
      top: this.outerDiv2.scrollTop,
      bottom: this.outerDiv2.scrollTop + this.outerDiv2.clientHeight,
      height: this.outerDiv2.clientHeight
    };
    ref = this.asset_data.pages;
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      p = ref[idx];
      page_dim = CUI.dom.getDimensions(p.$page);
      pos = {
        top: page_dim.offsetTop - visible.top,
        height: page_dim.borderBoxHeight
      };
      if (pos.top + pos.height < 0 || pos.top > visible.height) {
        CUI.dom.removeClass(p.$page, "visible");
        if (p.current_version) {
          CUI.dom.removeChildren(p.$page, "img");
          p.current_version = null;
        }
      } else {
        CUI.dom.addClass(p.$page, "visible");
        thumbnail_version_name = (ref1 = p.versions_sorted_by_size[0]) != null ? ref1.name : void 0;
        if (!thumbnail_version_name) {
          continue;
        }
        if (!p.current_version) {
          CUI.dom.setStyle(p.$page, {
            backgroundImage: "url(" + (Session.addToken(p.versions[thumbnail_version_name].url)) + ")"
          });
        }
        ref2 = p.versions_sorted_by_size;
        for (j = 0, len1 = ref2.length; j < len1; j++) {
          v = ref2[j];
          if (v.width >= p.size.width && v.height >= p.size.height) {
            break;
          }
        }
        if (((ref3 = p.current_version) != null ? ref3.name : void 0) !== v.name) {
          p.current_version = v;
          (function(_this) {
            return (function(p, v) {
              var new_img;
              new_img = new Image();
              new_img.style.width = "100%";
              new_img.style.height = "100%";
              new_img.src = Session.addToken(v.url);
              CUI.Events.listen({
                node: new_img,
                type: ["error"],
                call: function(ev) {
                  return console.error("img could not be loaded", new_img.src, {
                    version: v,
                    page: p
                  });
                }
              });
              return CUI.Events.listen({
                node: new_img,
                type: ["load"],
                call: function(ev) {
                  CUI.dom.removeChildren(p.$page, "img");
                  return p.$page.appendChild(new_img);
                }
              });
            });
          })(this)(p, v);
        }
      }
    }
  };

  PagedViewer.prototype.lastPageScrollIntoView = function() {
    var ref;
    if ((ref = this.lastPage) != null) {
      ref.scrollIntoView();
    }
    return CUI.Events.trigger({
      node: this.outerDiv2,
      type: "scroll"
    });
  };

  PagedViewer.prototype.scroll = function() {
    return this.setVisible();
  };

  PagedViewer.prototype.setLastPage = function(page) {
    if (this.lastPage) {
      CUI.dom.removeClass(this.lastPage, "last-page");
    }
    this.lastPage = page;
    return CUI.dom.addClass(this.lastPage, "last-page");
  };

  PagedViewer.prototype.plugins = function() {
    return [
      new AssetDetailPlugin({
        btn: "plus",
        icon: "zoom_in",
        run: (function(_this) {
          return function() {
            return _this.setZoom(_this.zoom + 0.05);
          };
        })(this)
      }), new AssetDetailPlugin({
        btn: "minus",
        icon: "zoom_out",
        run: (function(_this) {
          return function() {
            return _this.setZoom(_this.zoom - 0.05);
          };
        })(this)
      }), new AssetDetailPlugin({
        btn: "fit",
        icon: "resize_small",
        run: (function(_this) {
          return function() {
            return _this.fitZoom("fit");
          };
        })(this)
      }), new AssetDetailPlugin({
        btn: "fit-screen",
        icon: "resize_full",
        run: (function(_this) {
          return function() {
            return _this.fitZoom("fit-screen");
          };
        })(this)
      }), new AssetDetailPlugin({
        btn: "zoom_thumbs",
        label: "asset_detail.zoom_overview",
        run: (function(_this) {
          return function() {
            _this.setZoom(150 / _this.maxPageDim.width);
            return _this.lastPageScrollIntoView();
          };
        })(this)
      })
    ];
  };

  PagedViewer.prototype.fitScreen = function() {
    return this.fitZoom("fit");
  };

  PagedViewer.prototype.fitZoom = function(mode) {
    var extraSpace, zoom;
    extraSpace = (function(_this) {
      return function(dir) {
        var dim, dir1, dir2, i, k, len, ref, space;
        switch (dir) {
          case "width":
            dir = "Width";
            dir1 = "left";
            dir2 = "right";
            break;
          case "height":
            dir = "Height";
            dir1 = "top";
            dir2 = "bottom";
        }
        dim = CUI.dom.getDimensions(_this.outerDiv2);
        space = dim["innerBox" + dir] - dim["client" + dir];
        if (_this.lastPage) {
          ref = ["margin-" + dir1, "margin-" + dir2, "border-" + dir1 + "-width", "border-" + dir2 + "-width", "padding-" + dir1, "padding-" + dir2];
          for (i = 0, len = ref.length; i < len; i++) {
            k = ref[i];
            space += CUI.dom.getCSSFloatValue(CUI.dom.getComputedStyle(_this.lastPage)[k]);
          }
        }
        return space;
      };
    })(this);
    if ((this.fit.left > 0 && mode === "fit-screen") || (this.fit.top > 0 && mode === "fit")) {
      zoom = (this.viewport.width - extraSpace("width")) / this.maxPageDim.width;
    } else {
      zoom = (this.viewport.height - extraSpace("height")) / this.maxPageDim.height;
    }
    this.setZoom(zoom);
    return this.lastPageScrollIntoView();
  };

  return PagedViewer;

})(AssetDetail);
// Generated by CoffeeScript 1.12.7
var Asset,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

Asset = (function() {
  function Asset(field, value2, values1, data1) {
    var i, len, ref, v;
    this.field = field;
    this.value = value2;
    this.values = values1 != null ? values1 : null;
    this.data = data1 != null ? data1 : null;
    this.OLD_addVersionsFromDeepLink = bind(this.OLD_addVersionsFromDeepLink, this);
    this.__addDeepLinkToVersions = bind(this.__addDeepLinkToVersions, this);
    this.__checkIIIFToVersions = bind(this.__checkIIIFToVersions, this);
    this.__buildDeepLinkUrl = bind(this.__buildDeepLinkUrl, this);
    this.__allowVersionChange = true;
    CUI.util.assert(this.field instanceof EASColumn && (this.value === null || CUI.util.isPlainObject(this.value)) && (this.data === null || CUI.util.isPlainObject(this.data)), "new Asset()", "field, value need to be of type EASColumn and PlainObject (or null), respectivly", {
      field: this.field,
      value: this.value,
      data: this.data
    });
    if (this.value) {
      this.checkTechnicalMetadata(this.value);
    }
    if (CUI.util.isArray(this.values)) {
      if (ez5.version("6.8") && !ez5.session.hasSystemRight("root", "frontend_features[asset_variants]") && this.values.length > 1) {
        this.values = [this.values[0]];
      }
      ref = this.values;
      for (i = 0, len = ref.length; i < len; i++) {
        v = ref[i];
        this.checkTechnicalMetadata(v);
      }
    }
    this.__activeIdx = 0;
    return;
  }

  Asset.prototype.getSiblingsFromData = function() {
    var asset, i, len, ref, ro;
    if (!CUI.util.isPlainObject(this.data)) {
      console.error("Unable to getSiblingsFromData, no data set.");
      return [];
    }
    ro = new ResultObject();
    ro.setData(this.data);
    ref = ro.getAssetsForBrowser("detail");
    for (i = 0, len = ref.length; i < len; i++) {
      asset = ref[i];
      if (asset.getId() === this.getId()) {
        if (CUI.util.isArray(asset.values)) {
          return asset.values;
        } else {
          return [asset.getValue()];
        }
      }
    }
    console.error("Unable to getSiblingsFromData, asset not found in data.");
    return [];
  };

  Asset.prototype.isDeleted = function() {
    var ref;
    if (!ez5.version("6")) {
      return false;
    }
    return ((ref = this.value) != null ? ref.status : void 0) === "deleted";
  };

  Asset.prototype.checkTechnicalMetadata = function(value) {
    var height, i, len, ref, version, versionName, width;
    if (!value.technical_metadata) {
      value.technical_metadata = {};
    }
    if (!value.technical_metadata.width || !value.technical_metadata.height) {
      width = 0;
      height = 0;
      if (value.versions) {
        ref = ["original", "huge", "full", "preview", "small"];
        for (i = 0, len = ref.length; i < len; i++) {
          versionName = ref[i];
          version = value.versions[versionName];
          if (!version) {
            continue;
          }
          if (!version.width || !version.height) {
            continue;
          }
          width = version.width;
          height = version.height;
          break;
        }
      }
      value.technical_metadata.width = width;
      value.technical_metadata.height = height;
    }
  };

  Asset.prototype.getEASConfig = function() {
    var ref, session;
    if ((ref = this.data) != null ? ref._instance : void 0) {
      session = ez5.connector.getRemoteEasydbByInstance(this.data._instance);
      if (session) {
        return session.getSession().getEASConfig();
      } else {
        return ez5.session.getEASConfig();
      }
    } else {
      return ez5.session.getEASConfig();
    }
  };

  Asset.prototype.getImgElement = function(onUpdate, version, opts) {
    var node, ref, value, versionName, versionValue;
    if (onUpdate == null) {
      onUpdate = null;
    }
    if (version == null) {
      version = null;
    }
    if (opts == null) {
      opts = {};
    }
    value = this.value;
    if (version === null && (value != null ? value._id : void 0)) {
      version = Asset.getStandardVersionName(value, this.getEASConfig());
    }
    if (!version && (value != null ? value.versions : void 0)) {
      ref = value.versions;
      for (versionName in ref) {
        versionValue = ref[versionName];
        if (!Asset.checkVersionShowAllowed(versionValue)) {
          continue;
        }
        if (versionValue.status !== "done" || versionValue["class"] !== "image") {
          continue;
        }
        version = versionName;
        break;
      }
    }
    if (ez5.version("6") && this.data) {
      opts.obj_data = this.data;
    }
    node = this.field.getImgElementForValue(value, version, onUpdate, opts);
    CUI.dom.addClass(node, "asset-instance");
    CUI.dom.data(node, "asset", this);
    return node;
  };

  Asset.prototype.getTechnicalInfo = function(keys, values, onAfterRenderFunc) {
    var add_value, i, j, key, len, len1, locKey, parseValue, ref, ref1, table, tryToLocalize, val;
    if (keys == null) {
      keys = [];
    }
    if (values == null) {
      values = [];
    }
    tryToLocalize = function(key) {
      var loca_key;
      loca_key = "detail.asset_browser.info.general." + key;
      if (ez5.loca.has(loca_key)) {
        return $$(loca_key);
      }
      return key;
    };
    parseValue = (function(_this) {
      return function(value) {
        if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(value)) {
          return ez5.format_date_and_time(value, true);
        }
        return value;
      };
    })(this);
    table = new CUI.Table({
      "class": "ez5-metadata-browser-group",
      flex: true,
      key_value: true
    });
    ref = ["class_extension", "filesize", "original_filename", "date_created", "date_uploaded", "name", "_id", "eas_parent_id"];
    for (i = 0, len = ref.length; i < len; i++) {
      key = ref[i];
      if (CUI.util.isEmpty(this.value[key])) {
        continue;
      }
      locKey = tryToLocalize(key);
      if (!CUI.util.isEmpty(locKey)) {
        if (key === "_id" && ez5.session.hasSystemRight("root") && ez5.version("6")) {
          val = new CUI.ButtonHref({
            appearance: "link",
            target: "_blank",
            text: "" + this.value[key],
            href: ((ref1 = window.easydb_server_url) != null ? ref1 : "") + "/inspect/files/?filter=id:" + this.value[key] + "&parents=1&children=1"
          });
        } else {
          val = parseValue(this.value[key]);
        }
        table.addRow({
          key: tryToLocalize(locKey),
          value: val
        });
      }
    }
    if (this.value.technical_metadata) {
      add_value = (function(_this) {
        return function(key, value) {
          var idx, j, key1, len1, results, results1, value1;
          if (CUI.util.isPlainObject(value)) {
            results = [];
            for (key1 in value) {
              value1 = value[key1];
              results.push(add_value(key + "." + key1, value1));
            }
            return results;
          } else if (CUI.util.isArray(value)) {
            results1 = [];
            for (idx = j = 0, len1 = value.length; j < len1; idx = ++j) {
              value1 = value[idx];
              results1.push(add_value(key + ".#" + (idx + 1), value1));
            }
            return results1;
          } else {
            locKey = tryToLocalize(key);
            if (!CUI.util.isEmpty(locKey)) {
              return table.addRow({
                key: tryToLocalize(locKey),
                value: parseValue("" + value)
              });
            }
          }
        };
      })(this);
      for (key in this.value.technical_metadata) {
        keys.push(key);
      }
      keys.sort((function(_this) {
        return function(a, b) {
          return a.localeCompare(b);
        };
      })(this));
      for (j = 0, len1 = keys.length; j < len1; j++) {
        key = keys[j];
        add_value(key, this.value.technical_metadata[key]);
      }
    }
    if (typeof onAfterRenderFunc === "function") {
      onAfterRenderFunc();
    }
    return table;
  };

  Asset.prototype.getInfoTabs = function(opts) {
    var assetBrowser, assetBrowserInfoControl, include_flyout, tabs;
    if (opts == null) {
      opts = {};
    }
    if (CUI.util.isUndef(opts.include_flyout)) {
      opts.include_flyout = false;
    }
    assetBrowser = opts.assetBrowser;
    assetBrowserInfoControl = opts.assetBrowserInfoControl;
    include_flyout = opts.include_flyout;
    tabs = new CUI.Tabs({
      appearance: "mini",
      active_idx: this.__activeIdx,
      onActivate: (function(_this) {
        return function(tabs, tab) {
          return _this.__activeIdx = tabs.__tabs.indexOf(tab);
        };
      })(this),
      header_right: (function(_this) {
        return function() {
          var tools;
          if (!include_flyout) {
            return;
          }
          tools = _this.getCurrentTools();
          return Toolbox.getFlyoutButtonbar(tools);
        };
      })(this),
      tabs: [
        {
          text: $$("asset.info.tab.general"),
          ui: "asset.info.tab.general",
          content: (function(_this) {
            return function() {
              return _this.getTechnicalInfo([], []);
            };
          })(this)
        }, ez5.session.hasSystemRight("root", "frontend_features[asset_browser_metadata_tool]") ? {
          text: $$("asset.info.tab.extended"),
          ui: "asset.info.tab.advanced",
          load_on_show: true,
          "class": 'ez5-asset-metadata-browser',
          content: (function(_this) {
            return function(tab) {
              var browser, spinner;
              spinner = new CUI.WaitBlock({
                element: tab
              }).show();
              browser = new MetadataBrowser({
                element: CUI.dom.div()
              });
              browser.load(_this.getId()).always(function() {
                return spinner.destroy();
              }).done(function() {
                return browser.appendMarkup(tab.DOM);
              }).fail(function() {
                return tab.append(new CUI.EmptyLabel({
                  centered: true,
                  text: $$("metadata.browser.eas_not_found")
                }));
              });
              return spinner.DOM;
            };
          })(this)
        } : void 0, this.getVersionsTab(assetBrowser, assetBrowserInfoControl)
      ]
    });
    return tabs;
  };

  Asset.prototype.getVersionsTab = function(assetBrowser, assetBrowserInfoControl, tabKey) {
    var _value, _version, addHighlight, changeVersion, cols, column, div, enableTab, header, highlightIcon, i, j, key, len, len1, listView, ref, ref1, ref2, renderVersionsListView, tab, toggleTab, values, versionName, versions;
    if (tabKey == null) {
      tabKey = "asset.info.tab.versions";
    }
    values = CUI.util.isArray(this.values) ? this.values : [this.getValue()];
    if (!values) {
      return;
    }
    if (!this.__selectedVersionValue) {
      this.__selectedVersionValue = this.getValue();
    }
    listView = null;
    highlightIcon = new CUI.Icon({
      icon: $$("asset.info.tab.versions.list.version.highlight-icon"),
      "class": "ez5-asset-browser-info-control-tab-version-highlight-icon"
    });
    changeVersion = (function(_this) {
      return function() {
        var assetValue, node, ref, versionName;
        node = listView.getSelectedNode();
        if (node) {
          versionName = node.getVersion();
          assetValue = node.getValue();
          if (Asset.checkVersionShowAllowed((ref = assetValue.versions) != null ? ref[versionName] : void 0) === false) {
            return false;
          }
          _this.__selectedVersion = versionName;
          _this.__selectedVersionValue = assetValue;
          _this.setValue(_this.__selectedVersionValue);
        }
        if (assetBrowser) {
          CUI.Events.trigger({
            type: "asset-browser-change-version",
            node: assetBrowser,
            info: {
              asset: _this,
              version: _this.__selectedVersion
            }
          });
        }
        return true;
      };
    })(this);
    addHighlight = (function(_this) {
      return function() {
        var addIcon, childNode, i, j, len, len1, node, nodes, ref;
        if (!listView) {
          return;
        }
        nodes = listView.root.children;
        addIcon = function(_node) {
          var element, firstColumn;
          firstColumn = _node.getColumns()[0];
          if (!firstColumn) {
            return;
          }
          element = firstColumn.getElement();
          CUI.dom.prepend(element, highlightIcon);
          CUI.dom.showElement(highlightIcon);
          CUI.dom.addClass(element, "ez5-asset-browser-info-control-tab-version-highlight-column");
        };
        for (i = 0, len = nodes.length; i < len; i++) {
          node = nodes[i];
          if (!node.children) {
            continue;
          }
          ref = node.children;
          for (j = 0, len1 = ref.length; j < len1; j++) {
            childNode = ref[j];
            if (childNode.getValue()._id !== _this.__selectedVersionValue._id) {
              continue;
            }
            if (childNode.getVersion() !== _this.__selectedVersion) {
              continue;
            }
            addIcon(childNode);
            break;
          }
        }
      };
    })(this);
    cols = [];
    header = new CUI.ListViewHeaderRow({
      selectable: false
    });
    ref = ["filename", "version", "info", "status", "download", "share", "watermark"];
    for (i = 0, len = ref.length; i < len; i++) {
      key = ref[i];
      cols.push("auto");
      column = new CUI.ListViewHeaderColumn({
        label: {
          text: $$("asset.info.tab.versions.list." + key)
        }
      });
      header.addColumn(column);
    }
    cols[2] = "maximize";
    div = CUI.dom.div();
    enableTab = false;
    toggleTab = (function(_this) {
      return function() {
        if (!tab.getButton()) {
          return;
        }
        if (enableTab) {
          tab.enable();
        } else {
          tab.disable();
        }
      };
    })(this);
    tab = new CUI.Tab({
      text: $$(tabKey),
      ui: "asset.info.tab.versions",
      "class": 'ez5-asset-browser-info-control-tab-version',
      load_on_show: true,
      onInitButton: toggleTab,
      content: div
    });
    renderVersionsListView = (function(_this) {
      return function() {
        var j, len1, node, nodes, value, versionsWithParents;
        enableTab = true;
        toggleTab();
        versionsWithParents = values.filter(function(value) {
          return !CUI.util.isEmpty(value.eas_parent_id);
        });
        nodes = [];
        for (j = 0, len1 = values.length; j < len1; j++) {
          value = values[j];
          if (value.eas_parent_id) {
            continue;
          }
          node = new ez5.AssetTreeNode({
            ui: "asset.tree.node:" + value.original_filename,
            value: value,
            versions_with_parent: versionsWithParents,
            open: true,
            asset: _this
          });
          nodes.push(node);
        }
        if (nodes.length === 0) {
          value = values[0];
          node = new ez5.AssetTreeNode({
            ui: "asset.tree.node:" + value.original_filename,
            value: value,
            versions_with_parent: [],
            open: true,
            asset: _this
          });
          nodes.push(node);
        }
        listView = new CUI.ListViewTree({
          root: new CUI.ListViewTreeNode({
            children: nodes
          }),
          "class": 'cui-lv--has-datafields',
          onSelect: function() {
            var versionChanged;
            if (_this.__allowVersionChange === false) {
              return;
            }
            versionChanged = changeVersion();
            if (!versionChanged) {
              return;
            }
            addHighlight();
            if (assetBrowserInfoControl) {
              return assetBrowserInfoControl.getInfoButton().deactivate();
            }
          },
          selectableRows: true,
          maximize: true,
          rowMove: false,
          fixedRows: 1,
          cols: cols
        });
        listView.appendRow(header);
        listView.render();
        listView.root.open().done(function() {
          CUI.dom.append(div, listView);
          if (_this.__selectedVersion) {
            return addHighlight();
          } else {
            return changeVersion();
          }
        });
      };
    })(this);
    if ((ref1 = this.data) != null ? ref1._uuid : void 0) {
      versions = {};
      for (j = 0, len1 = values.length; j < len1; j++) {
        _value = values[j];
        if (!_value.versions) {
          return;
        }
        ref2 = _value.versions;
        for (versionName in ref2) {
          _version = ref2[versionName];
          _version._id = _value._id;
          _version.version = versionName;
          versions[versionName + "." + _value._id] = _version;
        }
      }
      this.__addDeepLinkToVersions(versions, this.data._uuid).always((function(_this) {
        return function() {
          return renderVersionsListView();
        };
      })(this));
    } else {
      renderVersionsListView();
    }
    CUI.Events.listen({
      type: "asset-browser-info-change-version",
      node: tab,
      call: (function(_this) {
        return function(_, info) {
          if (_this !== info.asset) {
            return;
          }
          _this.__selectedVersion = info.version.version;
          addHighlight();
        };
      })(this)
    });
    return tab;
  };

  Asset.getVideoVersions = function(asset) {
    var i, include_sync_versions, len, ref, ref1, ref2, version, versions;
    versions = [];
    include_sync_versions = ez5.version("6");
    ref = Asset.getDoneVersions(asset, false, false, include_sync_versions);
    for (i = 0, len = ref.length; i < len; i++) {
      version = ref[i];
      if ((ref1 = version["class"]) !== "video") {
        continue;
      }
      if ((ref2 = version.extension) !== "mp4") {
        continue;
      }
      if (version.version === "original" && !(CUI.util.isTrue(ez5.session.getClientDefault("video_player_use_original")) || ez5.version("6"))) {
        continue;
      }
      if (!Asset.checkVersionShowAllowed(version)) {
        continue;
      }
      versions.push(version);
    }
    return versions;
  };

  Asset.getAudioVersions = function(asset) {
    var i, len, ref, ref1, ref2, version, versions;
    versions = [];
    ref = Asset.getDoneVersions(asset);
    for (i = 0, len = ref.length; i < len; i++) {
      version = ref[i];
      if ((ref1 = version["class"]) !== "audio" && ref1 !== "video") {
        continue;
      }
      if ((ref2 = version.extension) !== "mp4" && ref2 !== "mp3" && ref2 !== "m4a" && ref2 !== "aac" && ref2 !== "ogg" && ref2 !== "oga" && ref2 !== "flac" && ref2 !== "opus") {
        continue;
      }
      if (version.version === "original" && !(CUI.util.isTrue(ez5.session.getClientDefault("audio_player_use_original")) || ez5.version("6"))) {
        continue;
      }
      if (!Asset.checkVersionShowAllowed(version)) {
        continue;
      }
      versions.push(version);
    }
    return versions;
  };

  Asset.prototype.getButtonDownloadOriginal = function(loca_key, force) {
    var original, original_download_url, ref, ref1;
    if (loca_key == null) {
      loca_key = "asset.download_original";
    }
    if (force == null) {
      force = false;
    }
    if (!ez5.session.hasSystemRight("root", "frontend_features[download]")) {
      return null;
    }
    original = (ref = this.value) != null ? (ref1 = ref.versions) != null ? ref1.original : void 0 : void 0;
    if (!original) {
      return;
    }
    if (!(original != null ? original._download_allowed : void 0) && !force) {
      return;
    }
    if (ez5.version("6.1")) {
      original_download_url = Session.addToken(original.url.split('?')[0]) + "&disposition=attachment";
    } else {
      original_download_url = original.download_url;
    }
    if (!original_download_url) {
      return;
    }
    return new LocaButton({
      ui: "asset.download_original.button",
      loca_key: loca_key,
      "class": "cui-button-download",
      onClick: (function(_this) {
        return function(ev, btn) {
          return DownloadManager.showAdminMessagesFromAssetAndDownloadUrl(_this, original_download_url);
        };
      })(this)
    });
  };

  Asset.prototype.getImgElementByIdx = function(idx, version) {
    var node;
    if (version == null) {
      version = null;
    }
    if (version === null && this.value) {
      version = Asset.getStandardVersionName(this.value);
    }
    node = this.field.getImgElementForValue(this.values[idx], version);
    CUI.dom.addClass(node, "asset-instance");
    return CUI.dom.data(node, "asset", this);
  };

  Asset.prototype.getField = function() {
    return this.field;
  };

  Asset.prototype.getValue = function(value) {
    return this.value;
  };

  Asset.prototype.getId = function() {
    return this.value._id;
  };

  Asset.prototype.setValue = function(value) {
    return this.value = value;
  };

  Asset.prototype.getWidth = function() {
    return this.value.technical_metadata.width;
  };

  Asset.prototype.getHeight = function() {
    return this.value.technical_metadata.height;
  };

  Asset.prototype.getStatus = function() {
    var original, ref, ref1, ref2;
    original = (ref = this.value) != null ? (ref1 = ref.versions) != null ? ref1.original : void 0 : void 0;
    if (!original) {
      if ((ref2 = this.value) != null ? ref2.technical_metadata : void 0) {
        return "done";
      } else {
        return "original_not_found";
      }
    } else {
      return original.status;
    }
  };

  Asset.prototype.getDownloadTools = function() {
    var cls, fn, i, label, len, tools, v, version, versions;
    cls = this.value["class"];
    versions = Asset.getExportVersionNamesForClass(cls);
    tools = [];
    fn = (function(_this) {
      return function(version) {
        return tools.push(new ToolboxTool({
          name: "asset.download." + cls + "." + v,
          loca_key: "tool.asset.download." + cls + "." + v,
          loca_key_attrs: [label],
          run: function() {
            var url;
            url = _this.getURL(version);
            url = url.replace("-inline", "");
            return document.location.href = url;
          }
        }));
      };
    })(this);
    for (i = 0, len = versions.length; i < len; i++) {
      v = versions[i];
      version = this.value.versions[v];
      if (!version) {
        continue;
      }
      label = Asset.getLabelForVersion(version);
      fn(version);
    }
    return tools;
  };

  Asset.prototype.getCurrentTools = function() {
    var download_btn, shareBtn, tools, versions_button;
    tools = [];
    shareBtn = this.getToolShareUrl();
    if (shareBtn) {
      tools.push(shareBtn);
    }
    download_btn = this.getButtonDownloadOriginal();
    if (download_btn) {
      tools.push(new ToolboxToolButton({
        favorite: this.getButtonDownloadOriginal("asset.download.original.favorite"),
        button: download_btn
      }));
    }
    versions_button = this.getAssetVersionsButton();
    if (versions_button) {
      tools.push(new ToolboxToolButton({
        button: versions_button
      }));
    }
    return tools;
  };

  Asset.prototype.getAssetVersionsButton = function() {
    if (!this.values) {
      return;
    }
    if (ez5.version("6.8")) {
      if (!ez5.session.hasSystemRight("root", "frontend_features[asset_variants]")) {
        return;
      }
    }
    return new LocaButton({
      ui: "asset.manage_versions.button",
      loca_key: "eas.column.button.manage_versions",
      onClick: (function(_this) {
        return function() {
          var data;
          data = {};
          data[_this.field.name()] = _this.values;
          return new AssetVersions({
            field: _this.field,
            mode: "detail",
            data: data,
            object_data: _this.data
          });
        };
      })(this)
    });
  };

  Asset.prototype.getToolShareUrl = function() {
    var isObjectDeleted, isObjectLatestVersion, ref, ref1;
    isObjectDeleted = ((ref = this.data) != null ? ref._latest_version_deleted_at : void 0) != null;
    isObjectLatestVersion = (ref1 = this.data) != null ? ref1._latest_version : void 0;
    if (!ez5.session.hasSystemRight("root", "frontend_features[deep_link_sharing]", "frontend_features[link_sharing][asset_deep_links]")) {
      return null;
    }
    if (!isObjectDeleted && isObjectLatestVersion) {
      return new ToolboxTool({
        group: "asset",
        name: "asset.share",
        loca_key: "asset.share_url_button",
        run: (function(_this) {
          return function() {
            return _this.showShareUrl2();
          };
        })(this)
      });
    }
  };

  Asset.prototype.getButtonShareUrl = function() {
    if (!ez5.session.hasSystemRight("root", "frontend_features[deep_link_sharing]", "frontend_features[link_sharing][asset_deep_links]")) {
      return null;
    }
    return new LocaButton({
      ui: "asset.share_url.button",
      loca_key: "asset.share_url_button",
      onClick: (function(_this) {
        return function() {
          return _this.showShareUrl2();
        };
      })(this)
    });
  };

  Asset.prototype.__buildDeepLinkUrl = function(versionValue, uuid) {
    var id, instance, ref, remoteEasydb, serverUrl, uri;
    id = "" + versionValue._id;
    serverUrl = null;
    if (id.indexOf("@") >= 0 && ez5.connector) {
      ref = id.split("@"), id = ref[0], instance = ref[1];
      remoteEasydb = ez5.connector.getRemoteEasydbByInstance(instance);
      serverUrl = remoteEasydb.getServerUrl();
    }
    uri = "/api/v1/objects/uuid/" + uuid + "/file/id/" + id + "/file_version/name/" + versionValue.version;
    return ez5.getAbsoluteURL(uri, serverUrl);
  };

  Asset.prototype.__checkIIIFToVersions = function(versions) {
    var fn, requests, version, versionValue;
    if (!ez5.version("6")) {
      return CUI.resolvedPromise();
    }
    requests = [];
    fn = (function(_this) {
      return function(version, versionValue) {
        var deferred, iiifURL, xhr;
        iiifURL = versionValue.iiif_url;
        if (!iiifURL) {
          return;
        }
        delete versions[version].iiif_url;
        deferred = new CUI.Deferred();
        requests.push(deferred.promise());
        xhr = new CUI.XHR({
          url: iiifURL + "/info.json",
          method: "HEAD"
        }).start();
        return xhr.done(function() {
          versions[version].iiif_url = iiifURL;
          return deferred.resolve();
        }).fail(deferred.resolve);
      };
    })(this);
    for (version in versions) {
      versionValue = versions[version];
      fn(version, versionValue);
    }
    return CUI.when(requests);
  };

  Asset.prototype.__addDeepLinkToVersions = function(versions, uuid) {
    var fn, requests, versionName, versionValue;
    if (!uuid) {
      return CUI.resolvedPromise();
    }
    requests = [];
    fn = (function(_this) {
      return function(versionName, versionValue) {
        var deepLinkUrl, deferred, xhr;
        if (ez5.version("6")) {
          deepLinkUrl = versionValue.deep_link_url;
        } else {
          deepLinkUrl = _this.__buildDeepLinkUrl(versionValue, uuid);
        }
        if (!deepLinkUrl) {
          return;
        }
        delete versions[versionName].deep_link_url;
        if (!ez5.session.getBaseConfig().deep_link_access.enabled) {
          return;
        }
        deferred = new CUI.Deferred();
        requests.push(deferred.promise());
        xhr = new CUI.XHR({
          url: deepLinkUrl,
          method: "HEAD"
        }).start();
        return xhr.done(function() {
          versions[versionName].deep_link_url = deepLinkUrl;
          return deferred.resolve();
        }).fail(deferred.resolve);
      };
    })(this);
    for (versionName in versions) {
      versionValue = versions[versionName];
      fn(versionName, versionValue);
    }
    return CUI.when(requests);
  };

  Asset.prototype.OLD_addVersionsFromDeepLink = function(versions, mask) {
    var arr, object_url, remoteEasydb;
    if (mask == null) {
      mask = null;
    }
    arr = ["", "uuid", this.data._uuid];
    if (mask) {
      arr.push("mask");
      arr.push(mask);
    }
    object_url = arr.join("/");
    remoteEasydb = null;
    if (this.data._instance) {
      remoteEasydb = ez5.connector.getRemoteEasydbByInstance(this.data._instance);
    }
    return ez5.api.objects({
      api: object_url,
      remoteEasydb: remoteEasydb,
      handle_error: (function(_this) {
        return function(xhr) {
          if (xhr.status === 400) {
            return true;
          }
        };
      })(this),
      add_token: false
    }).done((function(_this) {
      return function(data) {
        var asset, downloadVersions, i, index, j, l, len, len1, len2, ref, ro, value, values, version, versionName;
        if (!data) {
          console.error("No data received from call, not showing deep link url");
          return;
        }
        if (remoteEasydb) {
          Connector.addInstanceToObject(data, remoteEasydb);
        }
        ro = new ResultObject();
        ro.setData(data);
        ref = ro.getAssetsForBrowser("all");
        for (i = 0, len = ref.length; i < len; i++) {
          asset = ref[i];
          if (asset.getId() !== _this.getId()) {
            continue;
          }
          values = CUI.util.isArray(asset.values) ? asset.values : [asset.getValue()];
          for (j = 0, len1 = values.length; j < len1; j++) {
            value = values[j];
            downloadVersions = Asset.getDownloadVersions(value);
            for (index = l = 0, len2 = downloadVersions.length; l < len2; index = ++l) {
              version = downloadVersions[index];
              if (value === asset.getValue()) {
                versionName = version.version;
              } else {
                versionName = version.version + ("." + value._id);
              }
              if (versions[versionName]) {
                CUI.util.mergeMap(versions[versionName], version);
                continue;
              }
              versions[versionName] = version;
            }
          }
        }
      };
    })(this));
  };

  Asset.prototype.showShareUrl2 = function() {
    var add_versions_local, deepLinkPromise, iiifPromise, ref, ref1, show_modal_dialog, versions;
    versions = {};
    add_versions_local = (function(_this) {
      return function() {
        var i, len, ref, value, version;
        value = _this.getValue();
        ref = Asset.getDownloadVersions(value);
        for (i = 0, len = ref.length; i < len; i++) {
          version = ref[i];
          if (!versions[version.version]) {
            version._id = value._id;
            versions[version.version] = version;
          } else {
            CUI.util.mergeMap(versions[version.version], version);
          }
        }
      };
    })(this);
    show_modal_dialog = (function(_this) {
      return function() {
        var absurl, button, buttonBar, col, cols, columns, content, hint, hintLabel, i, j, len, len1, mod, ref, ref1, row, rows, table, version, vname, vnames;
        vnames = Asset.getVersionNamesForClass(_this.getValue()["class"]);
        rows = [];
        for (i = 0, len = vnames.length; i < len; i++) {
          vname = vnames[i];
          version = versions[vname];
          if (!version) {
            continue;
          }
          if (version["class"] === "directory") {
            continue;
          }
          row = {
            version: vname,
            filename: _this.getValue().original_filename_basename,
            print: Asset.getPrintSizeForVersion(version["class"], vname),
            width: version.width || "",
            height: version.height || "",
            format: version.extension,
            filesize: ez5.format_filesize(version.filesize)
          };
          if (ez5.version("6") && !version.download_url && version._download_allowed) {
            version.download_url = version.url;
            version.download_url += "&disposition=attachment";
          }
          if (version.deep_link_url) {
            absurl = ez5.getAbsoluteURL(version.deep_link_url);
            buttonBar = Asset.getShareButtonbar(absurl);
            row.url = buttonBar;
          } else {
            row.url = new CUI.EmptyLabel({
              text: $$("asset.share.url_not_available")
            });
          }
          if (version.download_url) {
            button = new CUI.Button({
              icon: $$("asset.share.versions.download|icon"),
              href: Session.addToken(version.download_url),
              download: true,
              ui: "asset.share.download.button",
              tooltip: {
                text: $$("asset.share.column.download|tooltip")
              },
              onClick: function(ev, btn) {
                ev.preventDefault();
                return DownloadManager.showAdminMessagesFromAssetAndDownloadUrl(_this, btn.opts.href);
              }
            });
            row.go_to_button = button;
          }

          /*
          				if ez5.version("6") and version.iiif_url
          					iiifUrl = version.iiif_url + "/info.json"
          					buttonBar = Asset.getShareButtonbar(iiifUrl, "asset.share.iiif")
          					row.iiif = buttonBar
           */
          rows.push(row);
        }
        cols = [];
        columns = ["print", "url", "go_to_button", "format", "filesize", "width", "height"];

        /*
        			if ez5.version("6")
        				columns.splice(3, 0, "iiif")
         */
        for (j = 0, len1 = columns.length; j < len1; j++) {
          col = columns[j];
          if (col === "url" && !((ref = _this.data) != null ? ref._uuid : void 0)) {
            continue;
          }
          cols.push({
            name: col,
            text: $$("asset.share.column." + col)
          });
        }
        table = new CUI.Table({
          "class": "ez5-asset-share-url-form",
          columns: cols,
          rows: rows
        });
        hint = CUI.dom.div('cui-form-hint ez5-asset-share-hint');
        hintLabel = new CUI.Label({
          multiline: true,
          markdown: true,
          ui: "asset.share.modal.hint",
          text: $$("asset.share.hint")
        });
        CUI.dom.append(hint, hintLabel);
        content = table;
        if (((ref1 = _this.values) != null ? ref1.length : void 0) > 1) {
          content = new CUI.Tabs({
            ui: "asset.share.modal.content",
            tabs: [
              {
                text: $$("asset.share.tab.preferred_version"),
                content: table
              }, _this.getVersionsTab(null, null, "asset.share.tab.all_versions")
            ],
            maximize_horizontal: true,
            maximize_vertical: true
          });
        }
        return mod = new CUI.Modal({
          "class": "ez5-asset-share-url-modal",
          cancel: true,
          ui: "asset.share.modal",
          pane: {
            header_left: new CUI.Label({
              text: $$("asset.share_url_modal.title")
            }),
            content: [content, hint],
            footer_right: {
              text: $$("base.done"),
              ui: "asset.share.modal.ok.button",
              primary: true,
              onClick: function() {
                return mod.destroy();
              }
            }
          }
        }).show();
      };
    })(this);
    add_versions_local();
    if ((ref = this.data) != null ? ref._uuid : void 0) {
      deepLinkPromise = this.__addDeepLinkToVersions(versions, (ref1 = this.data) != null ? ref1._uuid : void 0);
      iiifPromise = this.__checkIIIFToVersions(versions);
      CUI.when([deepLinkPromise, iiifPromise]).done((function(_this) {
        return function() {
          return show_modal_dialog();
        };
      })(this));
    } else {
      this.__checkIIIFToVersions(versions).done((function(_this) {
        return function() {
          return show_modal_dialog();
        };
      })(this));
    }
  };

  Asset.prototype.showDownloadModal = function() {
    var add_versions_local, show_modal_dialog, versions;
    versions = {};
    add_versions_local = (function(_this) {
      return function() {
        var i, len, ref, value, version;
        value = _this.getValue();
        ref = Asset.getDownloadVersions(value);
        for (i = 0, len = ref.length; i < len; i++) {
          version = ref[i];
          if (!versions[version.version]) {
            version._id = value._id;
            versions[version.version] = version;
          } else {
            CUI.util.mergeMap(versions[version.version], version);
          }
        }
      };
    })(this);
    show_modal_dialog = (function(_this) {
      return function() {
        var button, col, cols, columns, content, i, j, len, len1, mod, row, rows, table, version, vname, vnames;
        vnames = Asset.getVersionNamesForClass(_this.getValue()["class"]);
        rows = [];
        for (i = 0, len = vnames.length; i < len; i++) {
          vname = vnames[i];
          version = versions[vname];
          if (!version) {
            continue;
          }
          if (version["class"] === "directory") {
            continue;
          }
          row = {
            version: vname,
            filename: _this.getValue().original_filename_basename,
            print: Asset.getPrintSizeForVersion(version["class"], vname),
            width: version.width || "",
            height: version.height || "",
            format: version.extension,
            filesize: ez5.format_filesize(version.filesize)
          };
          if (ez5.version("6") && !version.download_url && version._download_allowed) {
            version.download_url = version.url;
            version.download_url += "&disposition=attachment";
          }
          if (version.download_url) {
            button = new CUI.ButtonHref({
              icon: $$("asset.share.versions.download|icon"),
              href: Session.addToken(version.download_url),
              download: true,
              ui: "asset.share.download.button",
              tooltip: {
                text: $$("asset.share.column.download|tooltip")
              }
            });
            row.go_to_button = button;
          }
          rows.push(row);
        }
        cols = [];
        columns = ["print", "go_to_button", "format", "filesize", "width", "height"];
        for (j = 0, len1 = columns.length; j < len1; j++) {
          col = columns[j];
          cols.push({
            name: col,
            text: $$("asset.share.column." + col)
          });
        }
        table = new CUI.Table({
          "class": "ez5-asset-share-url-form",
          columns: cols,
          rows: rows
        });
        content = table;

        /*
        			if @values?.length > 1
        				content = new CUI.Tabs
        					ui: "asset.download.modal.content"
        					tabs: [
        						text: $$("asset.share.tab.preferred_version")
        						content: table
        					,
        						@getVersionsTab(null, null, "asset.share.tab.all_versions")
        					]
        					maximize_horizontal: true
        					maximize_vertical: true
        
        
         *
         */
        return mod = new CUI.Modal({
          "class": "ez5-asset-versions-download-modal",
          cancel: true,
          ui: "asset.share.modal",
          pane: {
            header_left: new CUI.Label({
              text: $$("asset.download.versions")
            }),
            content: content,
            footer_right: {
              text: $$("base.done"),
              ui: "asset.share.modal.ok.button",
              primary: true,
              onClick: function() {
                return mod.destroy();
              }
            }
          }
        }).show();
      };
    })(this);
    add_versions_local();
    show_modal_dialog();
  };

  Asset.prototype.renderDetailOutput = function(opts) {
    var _opts, hl, img_el;
    if (opts == null) {
      opts = {};
    }
    _opts = {
      resize_placeholder: opts.resize_placeholder,
      alt: opts.alt
    };
    if (opts.for_print) {
      _opts.for_print = true;
    }
    img_el = this.getImgElement(null, null, _opts);
    hl = new CUI.HorizontalLayout({
      maximize_horizontal: true,
      maximize_vertical: true,
      ui: opts.ui ? opts.ui : void 0,
      "class": "ez5-eas-column-detail-output " + (opts["class"] || ""),
      left: {
        content: img_el
      },
      center: {
        content: this.getSummary()
      },
      right: opts.right
    });
    return hl;
  };

  Asset.prototype.getSummary = function() {
    return Asset.getSummary(this.getValue());
  };

  Asset.prototype.showShareUrl = function() {
    return ez5.api.eas({
      type: "GET",
      data: {
        ids: JSON.stringify([this.value._id]),
        format: "short"
      }
    }).done((function(_this) {
      return function(_data) {
        var data, form, i, len, mod, rows, value, version, versions, vname;
        value = _data[_this.value._id];
        versions = Asset.getVersionNamesForClass(value["class"]);
        rows = [];
        console.debug("showShareUrl", value, versions);
        for (i = 0, len = versions.length; i < len; i++) {
          vname = versions[i];
          version = value.versions[vname];
          if (!version || version._not_allowed) {
            continue;
          }
          rows.push({
            version: vname,
            print: Asset.getPrintSizeForVersion(value["class"], vname),
            width: version.width,
            height: version.height,
            format: version.extension,
            filesize: version.filesize,
            url: ez5.getAbsoluteURL(version.url),
            status: version.status
          });
        }
        data = {
          urls: rows
        };
        form = new CUI.Form({
          "class": "ez5-asset-share-url-form",
          ui: "asset.share.modal.form",
          fields: [
            {
              type: CUI.DataTable,
              data: data,
              new_rows: "none",
              maximize: false,
              name: "urls",
              fields: [
                {
                  type: CUI.Output,
                  name: "print",
                  ui: "asset.share.modal.form.print.output"
                }, {
                  type: CUI.Input,
                  "class": "cui-input-break-all",
                  content_size: true,
                  textarea: true,
                  readonly: true,
                  name: "url",
                  ui: "asset.share.modal.form.url.input"
                }, {
                  type: CUI.Output,
                  name: "format",
                  ui: "asset.share.modal.form.format.output"
                }, {
                  type: CUI.Output,
                  name: "filesize",
                  getValue: function(v) {
                    return ez5.format_filesize(v);
                  },
                  ui: "asset.share.modal.form.filesize.output"
                }, {
                  type: CUI.Output,
                  name: "width",
                  ui: "asset.share.modal.form.width.output"
                }, {
                  type: CUI.Output,
                  name: "height",
                  ui: "asset.share.modal.form.height.output"
                }, {
                  type: CUI.Output,
                  name: "status",
                  ui: "asset.share.modal.form.status.output"
                }
              ]
            }
          ]
        }).start();
        console.debug(CUI.util.dump(rows));
        return mod = new CUI.Modal({
          "class": "ez5-asset-share-url-modal",
          cancel: true,
          ui: "asset.share.modal",
          pane: {
            content: form,
            header_left: new CUI.Label({
              text: $$("asset.share_url_modal.title")
            }),
            footer_right: {
              text: $$("base.done"),
              onClick: function() {
                return mod.destroy();
              }
            }
          }
        }).show();
      };
    })(this));
  };

  Asset.prototype.canProduceNewVersion = function() {
    return Asset.canProduceNewVersion(this.getValue());
  };

  Asset.canProduceNewVersion = function(value) {
    var i, len, recipe, recipeClass, recipeExtensions, recipes, ref, ref1, ref2, ref3;
    if (!ez5.version("6")) {
      return true;
    }
    recipes = ((ref = ez5.session.data.config.eas._produce) != null ? ref.recipes : void 0) || [];
    if (recipes.length === 0) {
      return false;
    }
    for (i = 0, len = recipes.length; i < len; i++) {
      recipe = recipes[i];
      recipeClass = recipe.Class || recipe["class"];
      recipeExtensions = recipe.Extensions || recipe.extensions;
      if (recipeClass === "_produce" && (recipeExtensions != null ? recipeExtensions.length : void 0) > 0) {
        if (ref1 = value != null ? (ref2 = value.versions) != null ? (ref3 = ref2.original) != null ? ref3.extension : void 0 : void 0 : void 0, indexOf.call(recipeExtensions, ref1) >= 0) {
          return true;
        }
      }
    }
    return false;
  };

  Asset.getDoneVersions = function(value, for_download, ignore_rights, include_sync) {
    var ref, version, versions, vname;
    if (for_download == null) {
      for_download = false;
    }
    if (ignore_rights == null) {
      ignore_rights = false;
    }
    if (include_sync == null) {
      include_sync = false;
    }
    versions = [];
    if (!(value != null ? value.versions : void 0)) {
      return versions;
    }
    ref = value.versions;
    for (vname in ref) {
      version = ref[vname];
      if (!ignore_rights && version._not_allowed) {
        continue;
      }
      if (version.status !== "done" && !(include_sync && version.status === "sync")) {
        continue;
      }
      if (for_download && !version._download_allowed && !ignore_rights) {
        continue;
      }
      version.version = vname;
      versions.push(version);
    }
    return versions;
  };

  Asset.getDownloadVersions = function(value, ignore_rights) {
    if (ignore_rights == null) {
      ignore_rights = false;
    }
    return this.getDoneVersions(value, true, ignore_rights);
  };

  Asset.getLabelForVersion = function(version) {
    switch (version["class"]) {
      case "image":
        return "[" + version.extension + ", " + version.width + "x" + version.height + ", " + (ez5.format_filesize(version.filesize)) + "]";
      default:
        return "[" + version.extension + ", " + (ez5.format_filesize(version.filesize)) + "]";
    }
  };

  Asset.getConfigForVersion = function(cls, version, eas_config) {
    var def, i, info, len, ref;
    if (eas_config == null) {
      eas_config = ez5.session.getEASConfig();
    }
    if (version === "original") {
      return null;
    }
    info = eas_config != null ? eas_config[cls] : void 0;
    if (!(info != null ? info.versions : void 0)) {
      return null;
    }
    ref = info.versions;
    for (i = 0, len = ref.length; i < len; i++) {
      def = ref[i];
      if (def.version === version) {
        return def;
      }
    }
    return null;
  };

  Asset.getPrintSizeForVersion = function(cls, version, include_cls_name, eas_config) {
    var def;
    if (include_cls_name == null) {
      include_cls_name = false;
    }
    if (eas_config == null) {
      eas_config = ez5.session.getEASConfig();
    }
    if (version === "original") {
      return $$("asset.original");
    }
    def = this.getConfigForVersion(cls, version, eas_config);
    if (def === null) {
      console.warn("getPrintSizeForVersion: Version not found: ", cls, version);
      return version;
    }
    if (include_cls_name) {
      if (ez5.version("6") && def.displayname) {
        return $$("server.eas.fileclass." + cls) + " " + ez5.loca.getBestFrontendValue(def.displayname);
      } else {
        return $$("server.eas.fileclass." + cls) + " " + def.size_print;
      }
    } else {
      if (ez5.version("6") && def.displayname) {
        return ez5.loca.getBestFrontendValue(def.displayname);
      } else {
        return def.size_print;
      }
    }
    return null;
  };

  Asset.fileclasses = function(include_unknown) {
    var classes, cls, def, eas_config;
    if (include_unknown == null) {
      include_unknown = false;
    }
    eas_config = ez5.session.getEASConfig();
    CUI.util.assert(eas_config, "Asset.fileclasses", "ez5.session.getEASConfig: no config found.");
    classes = [];
    for (cls in eas_config) {
      def = eas_config[cls];
      if (cls.startsWith("_")) {
        continue;
      }
      classes.push(cls);
    }
    classes.sort((function(_this) {
      return function(a, b) {
        var a_txt, b_txt;
        a_txt = $$("server.eas.fileclass." + a);
        b_txt = $$("server.eas.fileclass." + b);
        return CUI.util.compareIndex(a_txt, b_txt);
      };
    })(this));
    if (include_unknown) {
      classes.push("unknown");
    }
    return classes;
  };

  Asset.getExportVersionGroups = function(eas_config) {
    var cls, def, groups, i, info, len, ref;
    if (eas_config == null) {
      eas_config = ez5.session.getEASConfig();
    }
    groups = {};
    for (cls in eas_config) {
      info = eas_config[cls];
      ref = info.versions;
      for (i = 0, len = ref.length; i < len; i++) {
        def = ref[i];
        if ((def["export"] || ez5.version("6")) && def.group) {
          def.__cls = cls;
          def.__full_version = cls + "." + def.version;
          if (!groups[def.group]) {
            groups[def.group] = [];
          }
          groups[def.group].push(def);
        }
      }
    }
    return groups;
  };

  Asset.getExportVersionNamesForClass = function(cls, include_original, eas_config) {
    if (include_original == null) {
      include_original = true;
    }
    if (eas_config == null) {
      eas_config = ez5.session.getEASConfig();
    }
    return this.getVersionNamesForClass(cls, include_original, (function(def) {
      return !!def["export"] || ez5.version("6");
    }), eas_config);
  };

  Asset.getVersionNamesForClass = function(cls, include_original, filter, eas_config) {
    var def, i, info, len, names, versions;
    if (include_original == null) {
      include_original = true;
    }
    if (filter == null) {
      filter = (function() {
        return true;
      });
    }
    if (eas_config == null) {
      eas_config = ez5.session.getEASConfig();
    }
    names = [];
    if (include_original) {
      names.push("original");
    }
    info = eas_config != null ? eas_config[cls] : void 0;
    if (!info) {
      return names;
    }
    if (info.versions) {
      versions = info.versions.slice(0);
      versions.sort(function(a, b) {
        var size_a, size_b;
        size_a = a.size_limit || 1000000;
        return size_b = b.size_limit || 1000000;
      });
      for (i = 0, len = versions.length; i < len; i++) {
        def = versions[i];
        if (!filter(def)) {
          continue;
        }
        names.push(def.version);
      }
    }
    return names;
  };

  Asset.getStandardVersion = function(value, eas_config) {
    var i, len, ref, v, version;
    if (eas_config == null) {
      eas_config = ez5.session.getEASConfig();
    }
    if (CUI.util.isArray(value)) {
      for (i = 0, len = value.length; i < len; i++) {
        v = value[i];
        if (v.preferred) {
          return Asset.getStandardVersion(v, eas_config);
        }
      }
      return null;
    } else {
      version = (ref = value.versions) != null ? ref[this.getStandardVersionName(value, eas_config)] : void 0;
      if (!version || version._not_allowed) {
        return null;
      } else {
        return version;
      }
    }
  };

  Asset.getStandardVersionName = function(value, eas_config) {
    var getVersionName, id, standardNoWatermarkVersionNames, standardVersionNames, versionName;
    if (eas_config == null) {
      eas_config = ez5.session.getEASConfig();
    }
    id = value != null ? value._id : void 0;
    if (CUI.util.isString(id)) {
      id = id.substring(0, id.indexOf("@"));
    }
    CUI.util.assert(id > 0, "Asset.getStandardVersionName", "value needs to be a valid asset value containing at least ._id", {
      value: value
    });
    standardVersionNames = this.getVersionNamesForClass(value["class"], false, (function(def) {
      return !!def.standard;
    }), eas_config);
    if (standardVersionNames === null || standardVersionNames.length === 0) {
      return null;
    }
    getVersionName = function(versionNames) {
      var i, len, ref, version, vname, vname_not_done;
      for (i = 0, len = versionNames.length; i < len; i++) {
        vname = versionNames[i];
        version = (ref = value.versions) != null ? ref[vname] : void 0;
        if (!version || version._not_allowed) {
          continue;
        }
        if (version.status === "done") {
          return vname;
        }
        vname_not_done = vname;
      }
      return vname_not_done;
    };
    standardNoWatermarkVersionNames = this.getVersionNamesForClass(value["class"], false, (function(def) {
      return !!def.standard && !def.watermark;
    }), eas_config);
    versionName = getVersionName(standardNoWatermarkVersionNames);
    if (versionName) {
      return versionName;
    }
    return getVersionName(standardVersionNames);
  };

  Asset.getImageValidExtensionsForBrowser = function() {
    return ["jpg", "png", "gif", "bmp", "jpeg", "svg", "webp"];
  };

  Asset.checkVersionShowAllowed = function(version) {
    if (!ez5.version("6") || !version) {
      return true;
    }
    if (!version.hasOwnProperty("_show_allowed")) {
      return true;
    }
    return version._show_allowed;
  };

  Asset.getBestImageForViewport = function(asset, viewport_w, viewport_h, filter_callback) {
    var all_versions, bestVersionTooSmall, best_version, best_watermark_version, def, i, idx, j, len, len1, max_filesize, orientation, ref, ref1, ref2, sort_by_size, v, vname, watermarkSelected, watermarkVersions;
    sort_by_size = function(a, b) {
      if (viewport_w > viewport_h) {
        return CUI.util.compareIndex(a.width, b.width);
      }
      return CUI.util.compareIndex(a.height, b.height);
    };
    all_versions = [];
    max_filesize = CUI.util.getInt(ez5.session.getClientDefault("asset_browser_max_preview_filesize"));
    if (asset.value._error || !asset.value.versions) {
      return;
    }
    if ((asset.value["class"] === "vector2d" || asset.value.class_extension === "image.svg") && asset.value.versions.original && asset.value.versions.original.status === "done" && Asset.checkVersionShowAllowed(asset.value.versions.original)) {
      asset.value.versions.original.version = "original";
      if (!filter_callback || filter_callback(asset.value.versions.original)) {
        return asset.value.versions.original;
      }
    }
    if (!filter_callback) {
      filter_callback = (function(_this) {
        return function() {
          if (v.ratio === -1) {
            return false;
          }
          if (vname === "original") {
            if (CUI.util.isNull(max_filesize) || max_filesize === -1) {
              return false;
            }
            if (asset.value.technical_metadata.server_auto_rotated_90 || asset.value.technical_metadata.orientation > 1) {
              return false;
            }
          }
          if (max_filesize > 0 && v.filesize > max_filesize) {
            console.info("Cannot deliver version \"" + vname + "\", filesize exceeds maximum filesize:", max_filesize, "version:", v);
            return false;
          }
        };
      })(this);
    }
    watermarkVersions = [];
    ref = asset.value.versions;
    for (vname in ref) {
      v = ref[vname];
      def = this.getConfigForVersion(v["class"], vname);
      if ((def != null ? def.watermark : void 0) && v["class"] === "image" && (ref1 = v.extension, indexOf.call(Asset.getImageValidExtensionsForBrowser(), ref1) >= 0)) {
        v.version = vname;
        watermarkVersions.push(v);
        continue;
      }
      if (v["class"] !== "image" || v.status !== "done" || (ref2 = v.extension, indexOf.call(Asset.getImageValidExtensionsForBrowser(), ref2) < 0)) {
        continue;
      }
      if (v._not_allowed) {
        continue;
      }
      if (filter_callback(v) === false) {
        continue;
      }
      if (Asset.checkVersionShowAllowed(v) === false) {
        continue;
      }
      v.version = vname;
      all_versions.push(v);
    }
    if (!all_versions.length) {
      if (watermarkVersions.length > 0) {
        watermarkSelected = true;
        all_versions = watermarkVersions;
      } else {
        return;
      }
    }
    all_versions.sort(sort_by_size);
    for (idx = i = 0, len = all_versions.length; i < len; idx = ++i) {
      v = all_versions[idx];
      best_version = v;
      if (v.width > viewport_w || v.height > viewport_h) {
        break;
      }
      orientation = best_version.width > best_version.height ? "landscape" : "portrait";
    }
    bestVersionTooSmall = (orientation === "landscape" && best_version.width < viewport_w) || (orientation === "portrait" && best_version.height < viewport_h);
    if (bestVersionTooSmall && watermarkVersions.length > 0 && !watermarkSelected) {
      watermarkVersions.sort(sort_by_size);
      for (idx = j = 0, len1 = watermarkVersions.length; j < len1; idx = ++j) {
        v = watermarkVersions[idx];
        best_watermark_version = v;
        if (v.width > viewport_w || v.height > viewport_h) {
          break;
        }
      }
      if (best_watermark_version.width > best_version.width || best_watermark_version.height > best_version.height) {
        best_version = best_watermark_version;
      }
    }
    return best_version;
  };

  Asset.showCopyTooltip = function(url, element, ev, ms) {
    var tooltip;
    if (ms == null) {
      ms = 2000;
    }
    tooltip = new CUI.Tooltip({
      element: element,
      text: $$("asset.share.link.copied.tooltip", {
        url: url
      })
    });
    tooltip.show(ev);
    CUI.setTimeout({
      ms: ms,
      call: (function(_this) {
        return function() {
          return tooltip.destroy();
        };
      })(this)
    });
  };

  Asset.getSummary = function(value) {
    var asset_info, glyphes, i, index, j, key, len, len1, localizedGlyphesLabel, localizedPageLabel, original_filename, pages, part, ref, ref1, ref2, ref3, summary, summary_items, v;
    if (!value) {
      return;
    }
    summary = CUI.dom.element("DIV", {
      "class": "ez5-asset-summary"
    });
    original_filename = ez5.basename(value.original_filename);
    if (!CUI.util.isEmpty(original_filename)) {
      CUI.dom.append(summary, new CUI.Label({
        "class": "ez5-asset-summary-filename",
        text: original_filename.trim(),
        ui: "asset.summary.item:original_filename"
      }));
    }
    summary_items = CUI.dom.element("DIV", {
      "class": "ez5-asset-summary-items"
    });
    if (value.name) {
      CUI.dom.append(summary_items, new CUI.Label({
        "class": "ez5-asset-summary-item",
        text: value.name,
        ui: "asset.summary.item:version_name"
      }));
    }
    if (value != null ? value.compiled : void 0) {
      if (ez5.version("6.12")) {
        if ((ref = value.compiled_props) != null ? ref["pages"] : void 0) {
          pages = parseInt(value.compiled_props["pages"].replace(" p.", ""));
          localizedPageLabel = $$("asset.browser.info.pages", {
            pages: pages
          });
          value.compiled = value.compiled.replace(/(\d+ p.)/, localizedPageLabel);
        }
        if ((ref1 = value.compiled_props) != null ? ref1["num_glyphes"] : void 0) {
          glyphes = parseInt(value.compiled_props["num_glyphes"].replace(" gly.", ""));
          localizedGlyphesLabel = $$("asset.browser.info.num_glyphes", {
            glyphes: glyphes
          });
          value.compiled = value.compiled.replace(/(\d+ gly.)/, localizedGlyphesLabel);
        }
      }
      asset_info = value.compiled;
    } else if ((value != null ? value.status : void 0) === "deleted") {
      asset_info = "";
      if (value != null ? value.date_deleted : void 0) {
        asset_info += $$("asset.browser.info.deleted_at", {
          deleted_date: ez5.format_date_and_time(value.date_deleted)
        });
      }
      if (value != null ? value.filesize : void 0) {
        if (!CUI.util.isEmpty(asset_info)) {
          asset_info += ", ";
        }
        asset_info += "" + (ez5.format_filesize(value.filesize));
      }
    } else {
      asset_info = "";
    }
    ref2 = asset_info.split(",");
    for (index = i = 0, len = ref2.length; i < len; index = ++i) {
      part = ref2[index];
      if (CUI.util.isEmpty(part.trim())) {
        continue;
      }
      CUI.dom.append(summary_items, new CUI.Label({
        "class": "ez5-asset-summary-item",
        text: part.trim(),
        ui: "asset.summary.item:part_" + index
      }));
    }
    if (value.technical_metadata) {
      ref3 = ["dpi", "colorprofile", "camera_scanner"];
      for (j = 0, len1 = ref3.length; j < len1; j++) {
        key = ref3[j];
        v = value.technical_metadata[key];
        if (CUI.util.isEmpty(v)) {
          continue;
        }
        CUI.dom.append(summary_items, new CUI.Label({
          "class": "ez5-asset-summary-item",
          text: $$("asset.summary." + key, {
            value: v,
            ui: "asset.summary.item:technical_metadata:" + key
          })
        }));
      }
    }
    CUI.dom.append(summary, summary_items);
    return summary;
  };

  Asset.getShareButtonbar = function(url, locaKeySuffix) {
    var copyButton, goToButton;
    if (locaKeySuffix == null) {
      locaKeySuffix = "asset.share.versions";
    }
    copyButton = new LocaButton({
      loca_key: locaKeySuffix + ".copy.button",
      loca_key_attrs: {
        url: decodeURIComponent(url)
      },
      group: "share",
      ui: "asset.share.copy.button",
      onClick: function(ev) {
        ez5.copyToClipboard(url);
        Asset.showCopyTooltip(url, copyButton, ev);
      }
    });
    goToButton = new LocaButton({
      loca_key: locaKeySuffix + ".goto.button",
      loca_key_attrs: {
        url: decodeURIComponent(url)
      },
      group: "share",
      ui: "asset.share.goto.button",
      onClick: (function(_this) {
        return function() {
          var k, session, v;
          session = CUI.getSessionStorage();
          CUI.clearSessionStorage();
          window.open(url, "_blank");
          for (k in session) {
            v = session[k];
            CUI.setSessionStorage(k, v);
          }
        };
      })(this)
    });
    return new CUI.Buttonbar({
      buttons: [copyButton, goToButton]
    });
  };

  return 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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  AssetVersionTreeNode.prototype.initOpts = function() {
    AssetVersionTreeNode.__super__.initOpts.call(this);
    this.addOpts({
      value: {
        check: "PlainObject",
        mandatory: true
      },
      version_value: {
        check: "PlainObject"
      },
      asset: {
        check: (function(_this) {
          return function(v) {
            return v instanceof Asset;
          };
        })(this)
      }
    });
    return this;
  };

  AssetVersionTreeNode.prototype.readOpts = function() {
    AssetVersionTreeNode.__super__.readOpts.call(this);
    this.__value = this._value;
    this.__versionValue = this._version_value;
  };

  AssetVersionTreeNode.prototype.getVersion = function() {
    var ref;
    return (ref = this.__versionValue) != null ? ref.version : void 0;
  };

  AssetVersionTreeNode.prototype.getVersionFilesize = function() {
    var ref;
    return ((ref = this.__versionValue) != null ? ref.filesize : void 0) || 0;
  };

  AssetVersionTreeNode.prototype.getValue = function() {
    return this.__value;
  };

  AssetVersionTreeNode.prototype.renderContent = function() {
    var absoluteURL, button, copyButton, def, descriptionKey, downloadUrl, goToButton, i, infoText, input, k, len, ref, ref1, shareButtonBar, version, watermark;
    version = this.__versionValue.version;
    if (!ez5.session.isDebug()) {
      version = Asset.getPrintSizeForVersion(this.__versionValue["class"], version, true) || version;
    }
    this.addColumn(new CUI.ListViewColumn({
      text: version
    }));
    if (!this.__versionValue.width && !this.__versionValue.height) {
      descriptionKey = "asset.info.tab.versions.list.info.value.no-width-height";
    } else {
      descriptionKey = "asset.info.tab.versions.list.info.value";
    }
    ref = ["class", "extension"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      if (this.__versionValue[k] === "unknown") {
        this.__versionValue[k] = null;
      }
    }
    if (!this.__versionValue["class"] && !this.__versionValue.extension) {
      infoText = $$("asset.versions.label.filesize.placeholder");
    } else {
      infoText = $$(descriptionKey, {
        extension: this.__versionValue.extension || "",
        "class": this.__versionValue["class"] || "",
        width: this.__versionValue.width || "",
        height: this.__versionValue.height || "",
        filesize: this.__versionValue.filesize ? ez5.format_filesize(this.__versionValue.filesize) : ""
      });
      infoText = infoText.replace(/,\s*,/g, ",").replace(/,\s*$/, "").trim();
    }
    this.addColumn(new CUI.ListViewColumn({
      text: infoText
    }));
    this.addColumn(new CUI.ListViewColumn({
      text: $$("eas.column.status." + this.__versionValue.status)
    }));
    downloadUrl = this.__getDownloadURL(this.__versionValue);
    if (downloadUrl && (ref1 = this.__versionValue, indexOf.call(Asset.getDownloadVersions(this.__value), ref1) >= 0)) {
      button = new LocaButton({
        loca_key: "asset.info.tab.versions.list.download.button",
        onClick: (function(_this) {
          return function() {
            return DownloadManager.showAdminMessagesFromAssetAndDownloadUrl(_this._asset, downloadUrl);
          };
        })(this)
      });
      this.addColumn(new CUI.ListViewColumn({
        element: button
      }));
    } else {
      this.addColumn(new CUI.ListViewColumnEmpty());
    }
    if (this.__versionValue.deep_link_url && ez5.session.hasSystemRight("root", "frontend_features[deep_link_sharing]", "frontend_features[link_sharing][asset_deep_links]")) {
      absoluteURL = ez5.getAbsoluteURL(this.__versionValue.deep_link_url);
      input = new CUI.Input({
        name: "url",
        readonly: true,
        data: {
          url: absoluteURL
        }
      });
      input.start();
      copyButton = new LocaButton({
        loca_key: "asset.info.tab.versions.list.share-copy.button",
        loca_key_attrs: {
          url: absoluteURL
        },
        group: "share",
        onClick: function(ev) {
          ez5.copyToClipboard(absoluteURL);
          Asset.showCopyTooltip(absoluteURL, copyButton, ev);
        }
      });
      goToButton = new LocaButton({
        loca_key: "asset.info.tab.versions.list.share-goto.button",
        loca_key_attrs: {
          url: absoluteURL
        },
        group: "share",
        onClick: (function(_this) {
          return function() {
            window.open(absoluteURL, "_blank");
          };
        })(this)
      });
      shareButtonBar = new CUI.Buttonbar({
        buttons: [copyButton, goToButton]
      });
      this.addColumn(new CUI.ListViewColumn({
        element: shareButtonBar
      }));
    } else {
      this.addColumn(new CUI.ListViewColumnEmpty());
    }
    def = Asset.getConfigForVersion(this.__versionValue["class"], this.__versionValue.version);
    if ((def != null ? def.watermark : void 0) === true) {
      watermark = new CUI.Icon({
        "class": "fa fa-check"
      });
      this.addColumn(new CUI.ListViewColumn({
        element: watermark
      }));
    } else {
      this.addColumn(new CUI.ListViewColumnEmpty());
    }
  };

  AssetVersionTreeNode.prototype.getChildren = null;

  AssetVersionTreeNode.prototype.isSelectable = function() {
    var ref, ref1, ref2, ref3, ref4;
    if ((ref = (ref1 = this.__versionValue) != null ? ref1["class"] : void 0) !== "image" && ref !== "vector2d") {
      return false;
    }
    if (((ref2 = this.__versionValue) != null ? ref2["class"] : void 0) === "image") {
      if (ref3 = (ref4 = this.__versionValue) != null ? ref4.extension : void 0, indexOf.call(Asset.getImageValidExtensionsForBrowser(), ref3) < 0) {
        return false;
      }
    }
    return AssetVersionTreeNode.__super__.isSelectable.call(this);
  };

  AssetVersionTreeNode.prototype.__getDownloadURL = function(versionValue) {
    if (ez5.version("6.1")) {
      if (versionValue.url && versionValue._download_allowed) {
        return Session.addToken(versionValue.url) + "&disposition=attachment";
      }
      return null;
    } else {
      return versionValue.download_url;
    }
  };

  return AssetVersionTreeNode;

})(CUI.ListViewTreeNode);
// 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.AssetTreeNode = (function(superClass) {
  extend(AssetTreeNode, superClass);

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

  AssetTreeNode.prototype.initOpts = function() {
    AssetTreeNode.__super__.initOpts.call(this);
    this.addOpts({
      versions_with_parent: {
        check: Array
      }
    });
    return this;
  };

  AssetTreeNode.prototype.readOpts = function() {
    var _, child, ref, ref1, value, version;
    AssetTreeNode.__super__.readOpts.call(this);
    this.__children = [];
    this.__versions = [];
    ref = this.__value.versions;
    for (version in ref) {
      value = ref[version];
      if (value._not_allowed) {
        continue;
      }
      value.version = version;
      this.__versions.push(value);
    }
    ref1 = this._versions_with_parent;
    for (_ in ref1) {
      value = ref1[_];
      if (value.eas_parent_id !== this.__value._id) {
        continue;
      }
      child = new ez5.AssetTreeNode({
        ui: "asset.tree.node:" + value.original_filename,
        value: value,
        asset: this._asset,
        versions_with_parent: this._versions_with_parent
      });
      this.__children.push(child);
      return;
    }
  };

  AssetTreeNode.prototype.getChildren = function() {
    var children;
    children = this.__versions.map((function(_this) {
      return function(version) {
        return new ez5.AssetVersionTreeNode({
          ui: "asset.tree.node:" + _this.__value.original_filename + ":" + (version != null ? version.version : void 0),
          value: _this.__value,
          version_value: version,
          asset: _this._asset
        });
      };
    })(this));
    children.sort((function(_this) {
      return function(a, b) {
        if (a.getVersion() === "original") {
          return -1;
        }
        if (b.getVersion() === "original") {
          return 1;
        }
        return b.getVersionFilesize() - a.getVersionFilesize();
      };
    })(this));
    if (this.__children.length > 0) {
      children = children.concat(this.__children);
    }
    return children;
  };

  AssetTreeNode.prototype.renderContent = function() {
    this.addColumn(new CUI.ListViewColumn({
      text: this.__value.name || ""
    }));
    this.addColumn(new CUI.ListViewColumn({
      text: this.__value.compiled || ""
    }));
    return new CUI.Label({
      text: this.__value.original_filename
    });
  };

  AssetTreeNode.prototype.isSelectable = function() {
    return CUI.ListViewTreeNode.prototype.isSelectable.call(this);
  };

  return AssetTreeNode;

})(ez5.AssetVersionTreeNode);
// Generated by CoffeeScript 1.12.7
var AssetPlain,
  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;

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

  function AssetPlain(opts) {
    var _opts;
    if (opts == null) {
      opts = {};
    }
    _opts = CUI.util.copyObject(opts, true);
    CUI.util.assert(!_opts.hasOwnProperty("default"), "new AssetPlain", "opts.default is not supported for AssetPlain.");
    delete _opts.value;
    AssetPlain.__super__.constructor.call(this, new EASField(_opts), opts.value);
  }

  AssetPlain.prototype.getImgElement = function(onUpdate, version, opts) {
    var img_el;
    if (onUpdate == null) {
      onUpdate = null;
    }
    if (version == null) {
      version = null;
    }
    if (opts == null) {
      opts = {};
    }
    img_el = AssetPlain.__super__.getImgElement.call(this, onUpdate, version, opts);
    img_el.setAttribute("data-ez5-asset-class", this.value["class"]);
    img_el.setAttribute("data-ez5-asset-extension", this.value.extension);
    return img_el;
  };

  return AssetPlain;

})(Asset);
// Generated by CoffeeScript 1.12.7
var AssetBrowser,
  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;

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

  function AssetBrowser(opts) {
    var a, asset, customIcon, el, fn, i, idx, index, isMultiple, j, k, l, len, len1, len2, len3, plugin, ref, ref1, ref2, ref3, ref4, ref5, tool;
    this.opts = opts != null ? opts : {};
    AssetBrowser.__super__.constructor.call(this, this.opts);
    this.current_idx = null;
    this.__activeTools = [];
    this.__autoVersionSwitchEnabled = true;
    this.__startIdx = this._start_idx;
    if (!this.__startIdx) {
      this.__startIdx = 0;
      ref = this._assets;
      for (index = i = 0, len = ref.length; i < len; index = ++i) {
        asset = ref[index];
        if (((ref1 = Asset.getStandardVersion(asset.value, asset.getEASConfig())) != null ? ref1.status : void 0) === "done") {
          this.__startIdx = index;
          break;
        }
      }
    }
    if (this._hires) {
      this.browser = new CUI.Template({
        name: "asset-browser-hires",
        map: {
          assets: true
        }
      });
    } else {
      isMultiple = this._assets.length > 1;
      this.browser = new CUI.Template({
        name: "asset-browser",
        map: {
          assets: true,
          multiple: true,
          multiple_indicator: true,
          multiple_navigation: true
        }
      });
    }
    if (this._hires) {
      this.browser.addClass("ez5-asset-browser-hires");
    }
    CUI.dom.setClassOnMousemove({
      element: this.browser.DOM,
      ms: 3000,
      "class": "ez5-asset-browser--show-controls"
    });
    this.registerTemplate(this.browser);
    CUI.dom.setAttribute(this.browser.DOM, "ez5-asset-browser-number-of-assets", this._assets.length);
    this.__pollIds = [];
    switch (this._assets.length) {
      case 0:
        customIcon = (ref2 = this.getResultObject()) != null ? ref2.getEmptyPlaceholderIcon() : void 0;
        if (this.__noAssetInObjecttype()) {
          CUI.dom.addClass(this.browser.DOM, "ez5-asset-browser--no-asset");
          this.browser.append(AssetBrowser.getNoAssetInObjecttypePlaceholder(customIcon), "assets");
        } else {
          CUI.dom.addClass(this.browser.DOM, "ez5-asset-browser--no-asset");
          this.browser.append(AssetBrowser.getNoAssetPlaceholder(customIcon), "assets");
        }
        return;
      case 1:
        CUI.dom.addClass(this.browser.DOM, "ez5-asset-browser--one-asset");
        break;
      default:
        CUI.dom.addClass(this.browser.DOM, "ez5-asset-browser--multiple-assets");
    }
    if (this._hires) {
      this.__videoPlayer = new VideoPlayer({
        element: this.browser.map.assets,
        editor_mode: this._editor_mode
      });
      this.tools = [
        new AudioPlayer({
          element: this.browser.map.assets
        }), this.__videoPlayer, ez5.version("6") ? new ZoomerV2({
          element: this.browser.map.assets
        }) : new Zoomer({
          element: this.browser.map.assets
        }), new ez5.defaults["class"].WebDVDPlayer({
          element: this.browser.map.assets
        }), new PagedViewer({
          element: this.browser.map.assets
        }), new GifPlayer({
          element: this.browser.map.assets
        })
      ];
      ref3 = AssetBrowser.plugins.newPlugins({
        element: this.browser.map.assets
      });
      for (j = 0, len1 = ref3.length; j < len1; j++) {
        plugin = ref3[j];
        this.tools.push(plugin);
      }
      if (this._resultObject) {
        this.tools.push(new DetailInfo({
          element: this.browser.map.assets,
          resultObject: this._resultObject
        }));
      }
      if (!CUI.util.isUndef(this._enable_tools)) {
        CUI.util.removeFromArray(null, this.tools, (function(_this) {
          return function(t) {
            var dt, k, len2, ref4;
            ref4 = _this._enable_tools;
            for (k = 0, len2 = ref4.length; k < len2; k++) {
              dt = ref4[k];
              if (t instanceof dt) {
                return false;
              }
            }
            return true;
          };
        })(this));
      }
    } else {
      this.tools = [];
    }
    this.activeTool = null;
    ref4 = this._assets;
    for (idx = k = 0, len2 = ref4.length; k < len2; idx = ++k) {
      a = ref4[idx];
      CUI.util.assert(a instanceof Asset, "new AssetBrowser", "opts.assets[" + idx + "] is not instance of Asset.", {
        opts: this.opts
      });
      this.browser.append(el = this.getAssetContainer(a, idx), "assets");
      if (idx === 0) {
        this.firstAsset = el;
      }
    }
    this.setIdx(this.__startIdx);
    if (isMultiple) {
      this.browser.append(new CUI.Icon({
        icon: "svg-multiple",
        ui: "asset.browser.multiple_indicator.icon"
      }), "multiple_indicator");
      this.appendNaviButtons();
    } else {
      CUI.dom.remove(this.browser.map.multiple);
    }
    if (this.tools.length && !this._for_print) {
      ref5 = this.tools;
      fn = (function(_this) {
        return function(tool) {
          return tool.registerPlugin(new AssetDetailPlugin({
            destroy: function() {
              return _this.activeTool = null;
            },
            start: function() {
              return _this.activeTool = tool;
            }
          }));
        };
      })(this);
      for (l = 0, len3 = ref5.length; l < len3; l++) {
        tool = ref5[l];
        fn(tool);
      }
      if (!this._disableWheelForTools) {
        CUI.Events.listen({
          node: this.browser,
          type: ["wheel", "gesturestart"],
          selector: ".ez-asset",
          call: (function(_this) {
            return function(ev) {
              if (ev.getType() === "gesturestart") {
                _this.startFirstTool(ev);
              } else if (ev.wheelDeltaY() < 0) {
                _this.startFirstTool(ev);
              }
            };
          })(this)
        });
      }
      CUI.Events.listen({
        node: this.browser,
        type: "click",
        selector: ".ez-asset-class-icon",
        call: (function(_this) {
          return function(ev) {
            _this.startFirstTool(ev);
          };
        })(this)
      });
    }
    if (this._hires && !this._for_print) {
      CUI.dom.waitForDOMInsert({
        node: this.browser
      }).done((function(_this) {
        return function() {
          var ref6;
          _this.sizeAssets();
          CUI.Events.listen({
            type: "viewport-resize",
            node: _this.browser,
            call: function() {
              return _this.sizeAssets(true);
            }
          });
          CUI.Events.listen({
            type: "asset-browser-info-control-close",
            node: _this.browser,
            call: function(ev, info) {
              var currentAsset;
              currentAsset = _this.getCurrentAsset();
              if (currentAsset && !currentAsset.__selectedVersion) {
                return CUI.scheduleCallback({
                  ms: 250,
                  call: function() {
                    return _this.sizeAssets(true);
                  }
                });
              }
            }
          });
          if ((ref6 = _this._onInit) != null) {
            ref6.call(_this, _this);
          }
          return CUI.dom.waitForDOMRemove({
            node: _this.browser
          }).done(function() {
            if (!_this.isDestroyed()) {
              return _this.destroy();
            }
          });
        };
      })(this));
    }
    if (this._for_print) {
      return;
    }
    if (this._custom_resize_events && this._custom_resize_events.length > 0) {
      CUI.Events.listen({
        type: this._custom_resize_events,
        node: this.browser,
        call: (function(_this) {
          return function() {
            if (_this._waitForResizeEvent) {
              _this._waitForResizeEvent = false;
            }
            return _this.sizeAssets(true);
          };
        })(this)
      });
    }
    CUI.Events.listen({
      type: "eas_update",
      node: this.browser,
      call: (function(_this) {
        return function(ev, info) {
          if (_this._hires) {
            _this.sizeAssets();
          }
          if (_this.getActiveTool() && info.asset === _this.getCurrentAsset()) {
            _this.getActiveTool().update(info.asset);
          }
        };
      })(this)
    });
    CUI.Events.listen({
      type: "show-asset",
      node: this.browser,
      call: (function(_this) {
        return function(ev, info) {
          var len4, len5, m, n, ref6, ref7;
          if (info == null) {
            info = {};
          }
          if (info.asset) {
            ref6 = _this._assets;
            for (idx = m = 0, len4 = ref6.length; m < len4; idx = ++m) {
              a = ref6[idx];
              if (a === info.asset) {
                _this.setIdx(idx);
                return;
              }
            }
          } else if (info.value) {
            ref7 = _this._assets;
            for (idx = n = 0, len5 = ref7.length; n < len5; idx = ++n) {
              a = ref7[idx];
              if (a.value._id === info.value._id) {
                _this.setIdx(idx);
                return;
              }
            }
          }
          console.warn("AssetBrowser[easydbui-show-asset]: Asset not found", ev, info);
        };
      })(this)
    });
    CUI.Events.listen({
      type: "asset-browser-change-version",
      node: this.browser,
      call: (function(_this) {
        return function(ev, info) {
          if (info == null) {
            info = {};
          }
          if (!info.asset) {
            return;
          }
          _this.updateImgElement(info.asset, info.version);
          if (!info.version) {
            _this.sizeAssets();
          }
        };
      })(this)
    });
    CUI.Events.listen({
      type: ["toolbox", "toolbox-sink"],
      node: this.browser,
      call: (function(_this) {
        return function(ev, info) {
          var detail_tools, len4, m, oinfo, ref6;
          if (info.__asset_browser_done) {
            return;
          }
          return;
          info.__asset_browser_done = true;
          oinfo = HashObjectInfo.getFromEvent(ev);
          console.debug("ev: ", CUI.dom.getAttribute(_this.browser.DOM, "asset-browser-idx"), ev.getPhase(), ev.getTarget(), ev.getCurrentTarget(), ev, info, oinfo);
          if (oinfo.asset_browser_idx >= 0) {
            asset = _this._assets[oinfo.asset_browser_idx];
          } else if (ev.getType() === "toolbox-sink" && _this.current_idx !== null) {
            asset = _this._assets[_this.current_idx];
          } else {
            return;
          }
          CUI.util.assert(asset instanceof Asset, "AssetBrowser[toolbox]", "Asset not found", {
            oinfo: oinfo
          });
          detail_tools = [];
          ref6 = _this.getAvailableTools(asset);
          for (m = 0, len4 = ref6.length; m < len4; m++) {
            tool = ref6[m];
            detail_tools.push(new ToolboxTool({
              group: "asset",
              name: CUI.util.getObjectClass(tool.tool),
              run: tool.run,
              loca_key: tool.btn_loca_key
            }));
          }
          if (detail_tools.length > 0) {
            info.tools.push(new ToolboxTool({
              group: "asset",
              disabled: detail_tools.length === 0,
              name: "asset.tools",
              tools: detail_tools
            }));
          }
        };
      })(this)
    });
    return;
  }

  AssetBrowser.prototype.startFirstTool = function(ev) {
    var asset, i, len, ref, ref1, t;
    if (((ref = this.activeTool) != null ? ref.preventOnMousewheelIfActive : void 0) != null) {
      if (this.activeTool.preventOnMousewheelIfActive() && this.activeTool) {
        return;
      }
    } else {
      if (this.activeTool) {
        return;
      }
    }
    if (ez5.version("6")) {
      if ((ev != null ? ev.getType() : void 0) === "wheel" && !this._fullscreen) {
        return;
      }
    }
    asset = this._assets[this.current_idx];
    ref1 = this.getAvailableTools(asset);
    for (i = 0, len = ref1.length; i < len; i++) {
      t = ref1[i];
      if (ev && t.tool.startOnMousewheel()) {
        t.run(ev, true, t.tool._btn);
        ev.stopImmediatePropagation();
        ev.preventDefault();
        break;
      } else if (t.tool.startAutomatically()) {
        t.run(null, true, t.tool._btn);
      }
    }
  };

  AssetBrowser.prototype.initOpts = function() {
    AssetBrowser.__super__.initOpts.call(this);
    return this.addOpts({
      assets: {
        check: function(v) {
          var a, i, len;
          if (!CUI.util.isArray(v)) {
            return false;
          }
          for (i = 0, len = v.length; i < len; i++) {
            a = v[i];
            if (!v instanceof Asset) {
              return false;
            }
          }
          return true;
        }
      },
      img_alt: {
        "default": null,
        check: String
      },
      start_idx: {
        "default": 0,
        check: function(v) {
          if (v >= 0) {
            return true;
          } else {
            return false;
          }
        }
      },
      hires: {
        "default": false,
        check: Boolean
      },
      for_print: {
        "default": false,
        check: Boolean
      },
      printLowRes: {
        "default": false,
        check: Boolean
      },
      disableWheelForTools: {
        "default": false,
        check: Boolean
      },
      noEasOnObjecttype: {
        "default": false,
        check: Boolean
      },
      onInit: {
        check: Function
      },
      show_hourglass: {
        check: Boolean
      },
      enable_tools: {
        mandatory: false,
        check: function(v) {
          var func, i, len;
          if (!CUI.util.isArray(v)) {
            return false;
          }
          for (i = 0, len = v.length; i < len; i++) {
            func = v[i];
            if (!CUI.util.isFunction(func)) {
              return false;
            }
          }
          return true;
        }
      },
      resultObject: {
        mandatory: false,
        check: ResultObject
      },
      custom_resize_events: {
        mandatory: false,
        check: Array
      },
      preferred_asset_size: {
        mandatory: false
      },
      waitForResizeEvent: {
        mandatory: false,
        check: Boolean
      },
      editor_mode: {
        "default": false,
        check: Boolean,
        mandatory: false
      },
      fullscreen: {
        "default": false,
        check: Boolean,
        mandatory: false
      }
    });
  };

  AssetBrowser.prototype.readOpts = function() {
    var asset, i, len, ref;
    AssetBrowser.__super__.readOpts.call(this);
    ref = this._assets;
    for (i = 0, len = ref.length; i < len; i++) {
      asset = ref[i];
      if (!asset.value.technical_metadata) {
        asset.value.technical_metadata = {};
      }
    }
  };

  AssetBrowser.getNoAssetPlaceholder = function(icon) {
    var div, tmpl;
    if (icon == null) {
      icon = null;
    }
    tmpl = new CUI.Template({
      name: "ng-asset",
      map: {
        element: true
      }
    });
    div = CUI.dom.div("ez5-asset-element ez5-eas-column asset-instance");
    CUI.dom.append(div, EAS.getNoAssetPlaceholder(icon));
    tmpl.append(div, "element");
    return tmpl;
  };

  AssetBrowser.getNoAssetInObjecttypePlaceholder = function(icon) {
    var div, tmpl;
    if (icon == null) {
      icon = null;
    }
    tmpl = new CUI.Template({
      name: "ng-asset",
      map: {
        element: true
      }
    });
    div = CUI.dom.div("ez5-asset-element ez5-eas-column asset-instance");
    CUI.dom.append(div, EAS.getNoAssetInObjecttypePlaceholder(icon));
    tmpl.append(div, "element");
    return tmpl;
  };

  AssetBrowser.prototype.getAssetContainer = function(asset, idx) {
    var $img_el, ref, tmpl;
    if (this._hires) {
      tmpl = new CUI.Template({
        name: "ng-asset-hires",
        map: {
          status: true,
          tools: true,
          element: true,
          preview_version: true,
          extension: true,
          filesize: true,
          info: true,
          tool: true
        }
      });
    } else {
      tmpl = new CUI.Template({
        name: "ng-asset",
        map: {
          element: true,
          extension: true,
          filesize: true,
          info: true
        }
      });
    }
    if (asset._tmpl) {
      asset._tmpl.destroy();
    }
    asset._tmpl = tmpl;
    CUI.dom.setAttribute(tmpl.DOM, "asset-browser-idx", idx);
    CUI.dom.setAttribute(tmpl.DOM, "ui", "asset.browser.asset:" + idx);
    this.updateImgElement(asset);
    if (this._hires) {
      $img_el = (ref = CUI.dom.matchSelector(tmpl.DOM, ".eas-image")) != null ? ref[0] : void 0;
      if (this.__blurhash = $img_el != null ? $img_el.children[1] : void 0) {
        CUI.dom.setStyle(this.__blurhash, {
          visibility: "hidden"
        });
      }
    }
    asset.getElement = function() {
      return this._tmpl.DOM;
    };
    return tmpl.DOM;
  };

  AssetBrowser.prototype.updateImgElement = function(asset, version) {
    var _el, best_version, el, i, len, preferred_asset_size, ref, show_hourglass;
    if (this._for_print) {
      if (this._printLowRes) {
        best_version = Asset.getBestImageForViewport(asset, 500, 500);
      } else {
        best_version = Asset.getBestImageForViewport(asset, 100000, 100000);
      }
      if (!best_version) {
        el = new CUI.Label({
          text: $$("asset.browser.img_not_found")
        });
      } else {
        el = asset.getImgElement(null, best_version.version, {
          for_print: true
        });
      }
    } else {
      if (this._show_hourglass !== void 0) {
        show_hourglass = this._show_hourglass;
      } else {
        show_hourglass = !this._hires;
      }
      if (!this._hires) {
        preferred_asset_size = this._preferred_asset_size || 500;
        if (best_version = Asset.getBestImageForViewport(asset, preferred_asset_size, preferred_asset_size)) {
          version = best_version.version;
        }
      }
      el = asset.getImgElement(null, version, {
        show_hourglass: show_hourglass,
        force_no_observer: this._waitForResizeEvent
      });
      if (this._img_alt) {
        ref = CUI.dom.matchSelector(el, "img");
        for (i = 0, len = ref.length; i < len; i++) {
          _el = ref[i];
          _el.alt = this._img_alt;
        }
      }
    }
    asset._tmpl.replace(el, "element");
    return this.updateAssetInfo(asset);
  };

  AssetBrowser.prototype.updateAssetInfo = function(asset) {
    var $img_el, asset_extension_css_class, extension, fileSize, glyphes, i, info, info_props, len, more_info, pages, ref, ref1, ref2, ref3, ref4, ref5, ref6, sec, tmpl, v, version;
    tmpl = asset._tmpl;
    v = asset.value;
    asset_extension_css_class = "asset-class-" + v["class"] + " asset-extension-" + v.extension;
    tmpl.addClass(asset_extension_css_class);
    if (this._hires) {
      $img_el = CUI.dom.matchSelector(tmpl.DOM, ".eas-image")[0];
      version = $img_el ? CUI.dom.getAttribute($img_el, "version") : void 0;
      tmpl.replace(CUI.dom.text(version), "preview_version");
    }
    fileSize = ez5.version("6.12") ? (ref = v.compiled_props) != null ? ref.byte_size : void 0 : ez5.format_filesize(v.filesize);
    tmpl.replace(CUI.dom.text(fileSize), "filesize");
    extension = ez5.version("6.12") ? (ref1 = v.compiled_props) != null ? ref1.extension : void 0 : v.extension;
    tmpl.replace(CUI.dom.text(extension), "extension");
    if (ez5.version("6.12")) {
      more_info = [];
      switch (v["class"]) {
        case "office":
          info_props = ["dimensions", "pages", "num_glyphes"];
          break;
        case "image":
          info_props = ["dimensions"];
          break;
        case "video":
          info_props = ["dimensions", "duration"];
          break;
        case "audio":
          info_props = ["duration"];
          break;
        default:
          info_props = ["dimensions", "duration", "pages", "num_glyphes"];
      }
      for (i = 0, len = info_props.length; i < len; i++) {
        info = info_props[i];
        if (info === "pages" && !CUI.util.isUndef((ref2 = v.compiled_props) != null ? ref2[info] : void 0)) {
          pages = parseInt(v.compiled_props[info].replace(" p.", ""));
          if (pages > 1) {
            CUI.dom.addClass(tmpl.DOM, "ez5-asset-browser--multiple-pages");
          } else {
            CUI.dom.addClass(tmpl.DOM, "ez5-asset-browser--one-page");
          }
          CUI.dom.setAttribute(tmpl.DOM, "ez5-assert-browser-pages", pages);
          more_info.push($$("asset.browser.info.pages", {
            pages: pages
          }));
          continue;
        }
        if (info === "num_glyphes" && !CUI.util.isUndef((ref3 = v.compiled_props) != null ? ref3[info] : void 0)) {
          glyphes = parseInt(v.compiled_props[info].replace(" gly.", ""));
          more_info.push($$("asset.browser.info.num_glyphes", {
            glyphes: glyphes
          }));
          continue;
        }
        if (!CUI.util.isUndef((ref4 = v.compiled_props) != null ? ref4[info] : void 0)) {
          more_info.push(v.compiled_props[info]);
        }
      }
      if (more_info.length > 0) {
        more_info = more_info.map((function(_this) {
          return function(info) {
            return CUI.dom.text(info);
          };
        })(this));
        tmpl.replace(more_info, "info");
      }
    } else if (!CUI.util.isEmptyObject(v.technical_metadata)) {
      switch (v["class"]) {
        case "image":
          if (((ref5 = v.technical_metadata) != null ? ref5.width : void 0) && ((ref6 = v.technical_metadata) != null ? ref6.height : void 0)) {
            more_info = v.technical_metadata.width + " x " + v.technical_metadata.height;
          }
          break;
        case "video":
        case "audio":
          if (!CUI.util.isUndef(sec = v.technical_metadata.duration)) {
            more_info = ez5.format_seconds(sec);
          }
          break;
        case "office":
          if (!CUI.util.isUndef(pages = v.technical_metadata.pages)) {
            more_info = $$("asset.browser.info.pages", {
              pages: pages
            });
            if (pages > 1) {
              CUI.dom.addClass(tmpl.DOM, "ez5-asset-browser--multiple-pages");
            } else {
              CUI.dom.addClass(tmpl.DOM, "ez5-asset-browser--one-page");
            }
            CUI.dom.setAttribute(tmpl.DOM, "ez5-assert-browser-pages", pages);
          }
      }
      if (more_info) {
        tmpl.replace(CUI.dom.text(more_info), "info");
      }
    }
    return this;
  };

  AssetBrowser.prototype.getActiveTool = function() {
    return this.activeTool;
  };

  AssetBrowser.prototype.getAssets = function() {
    return this._assets;
  };

  AssetBrowser.prototype.getCurrentAsset = function() {
    return this._assets[this.current_idx];
  };

  AssetBrowser.prototype.getCurrentIdx = function() {
    return this.current_idx;
  };

  AssetBrowser.prototype.appendNaviButtons = function() {
    var buttonBar;
    this.navigationPreviousButton = new LocaButton({
      loca_key: "asset.browser.button.previous",
      ui: "asset.browser.navigation.previous.button",
      appearance: "flat",
      disabled: this.__startIdx === 0,
      onClick: (function(_this) {
        return function() {
          return _this.setIdx(_this.current_idx - 1);
        };
      })(this)
    });
    this.navigationNextButton = new LocaButton({
      loca_key: "asset.browser.button.next",
      ui: "asset.browser.navigation.next.button",
      appearance: "flat",
      disabled: this.__startIdx === this._assets.length,
      onClick: (function(_this) {
        return function() {
          return _this.setIdx(_this.current_idx + 1);
        };
      })(this)
    });
    this.navigationCounter = new LocaLabel({
      ui: "asset.browser.navigation.label",
      text: (this.current_idx + 1) + "/" + this._assets.length,
      size: "mini"
    });
    this.navigationCounter.setTextMaxChars((this._assets.length + "/" + this._assets.length).length);
    buttonBar = new CUI.Buttonbar({
      buttons: [this.navigationPreviousButton, this.navigationCounter, this.navigationNextButton]
    });
    this.browser.append(buttonBar, "multiple_navigation");
    CUI.Events.listen({
      node: this.browser.map.multiple_navigation,
      type: ["dblclick"],
      call: (function(_this) {
        return function(ev) {
          ev.stopPropagation();
        };
      })(this)
    });
  };

  AssetBrowser.prototype.setNaviState = function() {
    CUI.dom.setAttribute(this.browser.DOM, "asset-browser-current-idx", this.current_idx);
    if (!this.navigationPreviousButton) {
      return;
    }
    if (this.current_idx === 0) {
      this.navigationPreviousButton.disable();
    } else {
      this.navigationPreviousButton.enable();
    }
    this.navigationCounter.setText((this.current_idx + 1) + "/" + this._assets.length);
    if (this.current_idx === this._assets.length - 1) {
      this.navigationNextButton.disable();
    } else {
      this.navigationNextButton.enable();
    }
    return this;
  };

  AssetBrowser.prototype.getAvailableTools = function(asset) {
    var btn_loca_key, fn, i, len, ref, tool, tools_av;
    CUI.util.assert(asset instanceof Asset, "AssetBrowser.getAvailableTools", "asset must be instance of Asset", {
      asset: asset
    });
    tools_av = [];
    ref = this.tools;
    fn = (function(_this) {
      return function(tool, btn_loca_key) {
        return tools_av.push({
          tool: tool,
          run: function(ev, mousewheelStart) {
            var ref1;
            if (mousewheelStart == null) {
              mousewheelStart = false;
            }
            if ((ref1 = _this.activeTool) != null) {
              ref1.destroy();
            }
            _this.activeTool = tool;
            return tool.start(asset, mousewheelStart, tool._btn);
          },
          btn_loca_key: btn_loca_key
        });
      };
    })(this);
    for (i = 0, len = ref.length; i < len; i++) {
      tool = ref[i];
      btn_loca_key = tool.getButtonLocaKey(asset);
      CUI.util.assert(CUI.util.isString(btn_loca_key) || CUI.util.isNull(btn_loca_key), "AssetBrowser.updateTools", (CUI.util.getObjectClass(tool)) + ".getButtonLocaKey must return null or String.", {
        ret: btn_loca_key
      });
      if (!btn_loca_key) {
        continue;
      }
      fn(tool, btn_loca_key);
    }
    return tools_av;
  };

  AssetBrowser.prototype.getActiveTools = function() {
    return this.__activeTools;
  };

  AssetBrowser.prototype.updateTools = function(asset) {
    var buttons, fn, has_wheelstart, i, len, playerButton, ref, tool;
    buttons = [];
    playerButton = null;
    has_wheelstart = false;
    this.__activeTools = [];
    ref = this.getAvailableTools(asset);
    fn = (function(_this) {
      return function(tool) {
        var base, ref1;
        tool.tool._btn = new LocaButton({
          loca_key: tool.btn_loca_key,
          ui: "asset.browser.tool:" + tool.btn_loca_key,
          group: "btn_tools",
          "class": "cui-button-tool-" + ((ref1 = tool.tool) != null ? ref1.clsName : void 0),
          appearance: "transparent-border",
          left: true,
          "switch": typeof (base = tool.tool).isButtonSwitch === "function" ? base.isButtonSwitch() : void 0,
          onClick: function(ev) {
            return tool.run(ev);
          }
        });
        if (tool.tool.isPlayer()) {
          playerButton = tool.tool._btn;
          playerButton.addClass("cui-button-tool-play");
        } else {
          buttons.push(tool.tool._btn);
        }
        return _this.__activeTools.push(tool);
      };
    })(this);
    for (i = 0, len = ref.length; i < len; i++) {
      tool = ref[i];
      if (tool.tool.startOnMousewheel()) {
        has_wheelstart = true;
      }
      fn(tool);
    }
    if (CUI.util.isEmpty(buttons) && !CUI.util.isEmpty(playerButton)) {
      asset._tmpl.replace(playerButton, "tools");
    }
    if (!CUI.util.isEmpty(buttons)) {
      asset._tmpl.replace(new CUI.Buttonbar({
        buttons: buttons,
        "class": "ez5-asset-browser-tools"
      }), "tools");
      if (!CUI.util.isEmpty(playerButton)) {
        asset._tmpl.append(playerButton, "tools");
      }
    }
    if (has_wheelstart) {
      asset._tmpl.addClass("ez5-asset-browser-has-wheelstart");
    } else {
      asset._tmpl.removeClass("ez5-asset-browser-has-wheelstart");
    }
  };

  AssetBrowser.prototype.setIdx = function(idx) {
    var i, img, index, len, nas, ref, ref1, ref2;
    CUI.util.assert(CUI.util.isInteger(idx) && idx >= 0 && this._assets[idx] instanceof Asset, "AssetBrowser.setIdx", "Cannot set idx to " + idx + ", opts.assets contains " + this._assets.length + " elements.", {
      assets: this._assets,
      idx: idx
    });
    if ((ref = this._assets[this.current_idx]) != null) {
      ref._tmpl.removeClass("cui-selected");
    }
    if (this.current_idx === idx) {
      return;
    }
    if ((ref1 = this.activeTool) != null) {
      ref1.destroy();
    }
    this.current_idx = idx;
    if (this._hires && !this._for_print) {
      this.sizeAssets();
    }
    CUI.Events.trigger({
      node: this.browser,
      type: "asset-browser-idx-changed",
      info: {
        current_idx: idx,
        asset: this._assets[idx]
      }
    });
    if (CUI.dom.closest(this.DOM, ".asset-browser-disable-scroll")) {
      CUI.dom.setStyleOne(this.firstAsset, "marginLeft", "");
    } else {
      CUI.dom.setStyleOne(this.firstAsset, "marginLeft", "-" + (idx * 100) + "%");
    }
    this.setNaviState();
    if (this.tools.length && !this._for_print) {
      CUI.dom.waitForDOMInsert({
        node: this.browser
      }).done((function(_this) {
        return function() {
          return _this.startFirstTool();
        };
      })(this));
    }
    if (!this._fullscreen) {
      ref2 = [-2, -1, 1, 2];
      for (i = 0, len = ref2.length; i < len; i++) {
        index = ref2[i];
        nas = this._assets[this.current_idx + index];
        if (!nas) {
          continue;
        }
        img = CUI.dom.matchSelector(nas.getElement(), "img")[0];
        EAS.IntersectionObserver.loadImage(img);
      }
    }
    return this;
  };

  AssetBrowser.prototype.getCurrentAssetEement = function() {
    var ref;
    return (ref = this.getCurrentAsset()) != null ? ref._tmpl.DOM : void 0;
  };

  AssetBrowser.prototype.sizeAssets = function(resizeEvent) {
    var asset, fn, fullSize, h, i, len, poll_versions, rect, ref, ref1, ref2, v, vname, w;
    if (resizeEvent == null) {
      resizeEvent = false;
    }
    rect = CUI.dom.getRect(this.firstAsset);
    if (rect.width === 0 || rect.height === 0) {
      return;
    }
    w = rect.width;
    h = rect.height;
    fullSize = CUI.dom.isFullscreen() && CUI.dom.closest(this.DOM, CUI.dom.fullscreenElement());
    if (this._hires && fullSize) {
      w = 100000;
      h = 100000;
    }
    ref = this._assets;
    fn = (function(_this) {
      return function(asset) {
        asset._poll_version = poll_versions;
        return _this.__pollIds.push(ez5.eas.addToQueue({
          value: asset.value,
          version: poll_versions,
          done: function(eas_obj) {
            asset._poll_version = null;
            return _this.sizeAssets(resizeEvent);
          },
          error: function() {
            asset._poll_version = null;
            return _this.sizeAssets(resizeEvent);
          }
        }));
      };
    })(this);
    for (i = 0, len = ref.length; i < len; i++) {
      asset = ref[i];
      if (asset !== this.getCurrentAsset()) {
        continue;
      }
      if (!resizeEvent) {
        this.updateAssetInfo(asset);
        this.updateTools(asset);
      }
      if (!asset.value.versions && !asset.value._incomplete_versions) {
        continue;
      }
      if (asset.value._incomplete_versions) {
        if (asset._polling) {
          continue;
        }
        (function(_this) {
          return (function(asset) {
            asset._polling = true;
            return _this.__pollIds.push(ez5.eas.addToQueue({
              value: asset.value,
              done: function(eas_obj) {
                asset._polling = null;
                asset.value._incomplete_versions = null;
                return _this.sizeAssets(resizeEvent);
              },
              failed: function() {
                asset._polling = null;
                asset.value._incomplete_versions = null;
                return _this.sizeAssets(resizeEvent);
              }
            }));
          });
        })(this)(asset);
        continue;
      }
      if (asset.value.versions && Object.values(asset.value.versions).some((function(_this) {
        return function(version) {
          return version.status === "done";
        };
      })(this))) {
        this.__size_image(asset, w, h);
      } else {
        console.debug("No version with status 'done' found for asset", asset);
      }
      poll_versions = null;
      ref1 = asset.value.versions;
      for (vname in ref1) {
        v = ref1[vname];
        if ((ref2 = v.status) === "processing" || ref2 === "pending") {
          if (poll_versions == null) {
            poll_versions = [];
          }
          poll_versions.push(vname);
        }
      }
      if (!poll_versions || asset._poll_version) {
        continue;
      }
      fn(asset);
    }
    return this;
  };

  AssetBrowser.prototype.__size_image = function(asset, viewport_width, viewport_height) {
    var $img_el, asset_element, best_version, betterVersionUrl, currentVersion, hasBetterVersion, img_el, img_h, img_w, newImage, onLoaded, transform_element, versionName;
    asset_element = asset._tmpl.DOM;
    img_w = asset.getWidth();
    img_h = asset.getHeight();
    transform_element = CUI.dom.matchSelector(asset_element, ".ez5-asset-element-transform")[0];
    if (transform_element) {
      EAS.setTransformStyle(transform_element, asset.value.transform);
    }
    best_version = Asset.getBestImageForViewport(asset, viewport_width, viewport_height);
    if (!best_version) {
      return;
    }
    $img_el = CUI.dom.matchSelector(asset_element, ".eas-image")[0];
    if (!$img_el) {
      asset.__selectedVersion = best_version.version;
      return;
    }
    this.allowDragImage($img_el);
    CUI.dom.setAttributeMap(asset_element, {
      "viewport-width": viewport_width,
      "viewport-height": viewport_height
    });
    CUI.dom.setClass(asset_element, "ez5-asset-browser-viewport-fit-height", viewport_width / viewport_height > img_w / img_h);
    if (viewport_width < img_w && viewport_height < img_h) {
      CUI.dom.addClass(asset_element, "ez5-asset-browser-image-smaller-than-viewport");
      CUI.dom.removeClass(asset_element, "ez5-asset-browser-viewport-smaller-than-image");
    } else {
      CUI.dom.addClass(asset_element, "ez5-asset-browser-viewport-smaller-than-image");
      CUI.dom.removeClass(asset_element, "ez5-asset-browser-image-smaller-than-viewport");
    }
    onLoaded = (function(_this) {
      return function() {
        if (asset._tmpl.has("preview_version")) {
          asset._tmpl.replace(CUI.dom.text(currentVersion.version + (" [VP " + viewport_width + "x" + viewport_height + "]")), "preview_version");
        }
        CUI.dom.setAttributeMap($img_el, {
          "real-width": currentVersion.width,
          "real-height": currentVersion.height,
          "version": currentVersion.version
        });
        if (asset === _this._assets[_this.current_idx]) {
          CUI.Events.trigger({
            type: "asset-browser-info-change-version",
            info: {
              asset: asset,
              version: currentVersion
            }
          });
        }
        return asset.__selectedVersion = currentVersion.version;
      };
    })(this);
    versionName = CUI.dom.getAttribute($img_el, "version");
    currentVersion = asset.value.versions[versionName];
    hasBetterVersion = (currentVersion != null ? currentVersion.version : void 0) !== best_version.version;
    img_el = $img_el.firstChild;
    if (hasBetterVersion && this.__autoVersionSwitchEnabled) {
      if (this.__blurhash) {
        CUI.dom.setStyle(this.__blurhash, {
          visibility: ""
        });
      }
      currentVersion = best_version;
      betterVersionUrl = currentVersion.url;
      if (ez5.version("6")) {
        if (betterVersionUrl !== CUI.dom.getAttribute(img_el, "data-original-src")) {
          CUI.dom.setAttribute(img_el, "data-original-src", betterVersionUrl);
          EAS.loadImageAsBlob({
            src: betterVersionUrl,
            remoteInstance: CUI.dom.getAttribute(img_el, "data-remote-instance"),
            onLoad: (function(_this) {
              return function(result) {
                var alt, newImage, originalSrc;
                newImage = new Image();
                if (img_el) {
                  newImage.src = result;
                  alt = CUI.dom.getAttribute(img_el, "alt");
                  originalSrc = CUI.dom.getAttribute(img_el, "data-original-src");
                  CUI.dom.setAttribute(newImage, "alt", alt);
                  CUI.dom.setAttribute(newImage, "data-original-src", originalSrc);
                  CUI.dom.addClass(newImage, "is-loaded");
                  newImage.addEventListener("load", function() {
                    CUI.dom.replace($img_el, newImage);
                    img_el = newImage;
                    return EAS.unloadBlob(result);
                  });
                }
                return onLoaded();
              };
            })(this)
          });
        }
      } else {
        newImage = new Image();
        newImage.src = betterVersionUrl;
        newImage.onload = (function(_this) {
          return function() {
            var alt;
            if (img_el) {
              alt = CUI.dom.getAttribute(img_el, "alt");
              CUI.dom.setAttribute(newImage, "alt", alt);
              CUI.dom.addClass(newImage, "is-loaded");
              CUI.dom.replace($img_el, newImage);
              img_el = newImage;
            } else {
              CUI.dom.setStyleOne($img_el, "backgroundImage", "url(" + betterVersionUrl + ")");
            }
            onLoaded();
          };
        })(this);
      }
    } else {
      EAS.IntersectionObserver.loadImage(img_el).done((function(_this) {
        return function() {
          onLoaded();
        };
      })(this));
    }
  };

  AssetBrowser.prototype.allowDragImage = function(img_el) {
    var target_element;
    if (!ez5.version("6") || !ez5.session.hasSystemRight("root", "frontend_features[download]")) {
      return;
    }
    target_element = CUI.dom.closest(img_el, ".ez-asset");
    if (!target_element) {
      return;
    }
    return CUI.dom.addClass(target_element, "asset-download-allowed");
  };

  AssetBrowser.prototype.getVideoPlayer = function() {
    return this.__videoPlayer;
  };

  AssetBrowser.prototype.getResultObject = function() {
    return this._resultObject;
  };

  AssetBrowser.prototype.setAutoVersionSwitch = function(enabled) {
    var asset, i, len, ref;
    this.__autoVersionSwitchEnabled = enabled;
    ref = this._assets || [];
    for (i = 0, len = ref.length; i < len; i++) {
      asset = ref[i];
      asset.__allowVersionChange = enabled;
    }
    return this;
  };

  AssetBrowser.prototype.isAutoVersionSwitchEnabled = function() {
    return this.__autoVersionSwitchEnabled;
  };

  AssetBrowser.prototype.__noAssetInObjecttype = function() {
    var ref;
    if (this._noEasOnObjecttype) {
      return true;
    }
    if (this.getResultObject() && !((ref = this.getResultObject().mask) != null ? ref.hasStandardEASFields() : void 0)) {
      return true;
    }
    return false;
  };

  AssetBrowser.prototype.destroy = function() {
    var i, j, len, len1, poll_id, ref, ref1, t;
    if (this.isDestroyed()) {
      return;
    }
    this.__activeTools = null;
    this.setAutoVersionSwitch(true);
    if (this.tools) {
      ref = this.tools;
      for (i = 0, len = ref.length; i < len; i++) {
        t = ref[i];
        t.destroy();
      }
    }
    delete this.__videoPlayer;
    ref1 = this.__pollIds;
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      poll_id = ref1[j];
      ez5.eas.removeFromQueue(poll_id);
    }
    this.__pollIds = [];
    this.tools = null;
    AssetBrowser.__super__.destroy.call(this);
    return this;
  };

  return AssetBrowser;

})(CUI.DOMElement);

ez5.session_ready(function() {
  return AssetBrowser.plugins = new CUI.PluginRegistry({
    "class": AssetDetail
  });
});

CUI.Events.registerEvent({
  type: ["asset-browser-show-asset", "asset-browser-idx-changed", "asset-browser-change-version"],
  bubble: true
});

CUI.Events.registerEvent({
  type: ["show-asset"],
  sink: true
});
// Generated by CoffeeScript 1.12.7
var AssetBrowserInfoControl,
  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;

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

  function AssetBrowserInfoControl(opts) {
    this.opts = opts != null ? opts : {};
    AssetBrowserInfoControl.__super__.constructor.call(this, this.opts);
    this.__tmpl = new CUI.Template({
      name: "asset-browser-info-control",
      map: {
        button: true,
        navigation: true,
        tabs: true,
        label: true,
        position_label: true
      }
    });
    CUI.Events.listen({
      node: this._assetBrowser,
      instance: this,
      type: ["asset-browser-idx-changed", "eas_update"],
      call: (function(_this) {
        return function(ev) {
          _this.updateNavigation();
          if (_this.__info_is_on) {
            _this.renderTabs();
          }
        };
      })(this)
    });
    this.registerTemplate(this.__tmpl, false);
    this.updateNavigation();
    if (this._show_info_button) {
      this.__info_button = new LocaButton({
        ui: "asset.browser.info.control.button",
        loca_key: "asset.browser.info.control.info_button",
        "switch": true,
        activate_initial: false,
        size: "mini",
        disabled: this._assetBrowser.getAssets().length === 0,
        onActivate: (function(_this) {
          return function() {
            _this.setInfoMode(true);
            return typeof _this._onUpdate === "function" ? _this._onUpdate(_this) : void 0;
          };
        })(this),
        onDeactivate: (function(_this) {
          return function(_, flags) {
            _this.setInfoMode(false);
            if (typeof _this._onUpdate === "function") {
              _this._onUpdate(_this);
            }
            if (flags.initial_activate) {
              return;
            }
          };
        })(this)
      });
      this.__download_button = this.__getDownloadOriginalButton();
      this.append(this.__info_button, "button");
      if (this.__download_button) {
        this.append(this.__download_button, "button");
      }
    }
    this.setInfoMode(false);
  }

  AssetBrowserInfoControl.prototype.initOpts = function() {
    AssetBrowserInfoControl.__super__.initOpts.call(this);
    return this.addOpts({
      assetBrowser: {
        mandatory: true,
        check: AssetBrowser
      },
      onUpdate: {
        check: Function
      },
      show_info_button: {
        mandatory: true,
        "default": true,
        check: Boolean
      },
      contentContainer: {
        check: function(v) {
          return CUI.dom.isNode(v);
        }
      }
    });
  };

  AssetBrowserInfoControl.prototype.setInfoMode = function(__info_is_on) {
    this.__info_is_on = __info_is_on;
    if (this.__info_is_on) {
      this.renderTabs();
    } else {
      if (this._assetBrowser) {
        CUI.Events.trigger({
          type: "asset-browser-info-control-close",
          node: this._assetBrowser
        });
      }
      this.destroyTabs();
    }
    return CUI.dom.setClass(this.DOM, "ez5-asset-browser-info-control--info-mode", this.__info_is_on);
  };

  AssetBrowserInfoControl.prototype.getInfoState = function() {
    return this.__info_is_on;
  };

  AssetBrowserInfoControl.prototype.renderTabs = function() {
    var asset;
    asset = this._assetBrowser.getCurrentAsset();
    this.__infoTabs = asset.getInfoTabs({
      assetBrowser: this._assetBrowser,
      assetBrowserInfoControl: this
    });
    if (this._contentContainer) {
      CUI.dom.replace(this._contentContainer, this.__infoTabs);
    } else {
      this.replace(this.__infoTabs, "tabs");
    }
  };

  AssetBrowserInfoControl.prototype.destroyTabs = function() {
    var ref;
    if ((ref = this.__infoTabs) != null) {
      ref.destroy();
    }
    if (this._contentContainer) {
      CUI.dom.empty(this._contentContainer);
    }
  };

  AssetBrowserInfoControl.prototype.updateNavigation = function() {
    var asset, assets, bb, counter, idx, len, nextBtn, pos, prevBtn;
    assets = this._assetBrowser.getAssets();
    len = assets.length;
    if (len <= 1) {
      return;
    }
    asset = this._assetBrowser.getCurrentAsset();
    idx = this._assetBrowser.getCurrentIdx();
    prevBtn = new LocaButton({
      icon: "left",
      ui: "asset.browser.info.control.left.button",
      loca_key: "asset.browser.info.control.button.left",
      group: "navi",
      size: "mini",
      disabled: idx === 0,
      onClick: (function(_this) {
        return function() {
          return _this._assetBrowser.setIdx(idx - 1);
        };
      })(this)
    });
    if (asset.value._idx >= 0 && !asset.value._hideIdx) {
      pos = (asset.value._idx + 1) + "/" + asset.value._len;
    } else {
      pos = "";
    }
    this.__tmpl.map.label.textContent = this.getAssetLabelText();
    this.__tmpl.map.position_label.textContent = pos;
    nextBtn = new LocaButton({
      icon: "right",
      ui: "asset.browser.info.control.right.button",
      loca_key: "asset.browser.info.control.button.right",
      group: "navi",
      size: "mini",
      disabled: idx === assets.length - 1,
      onClick: (function(_this) {
        return function() {
          return _this._assetBrowser.setIdx(idx + 1);
        };
      })(this)
    });
    counter = new LocaLabel({
      ui: "asset.browser.info.control.count",
      text: (idx + 1) + "/" + len,
      group: "navi",
      size: "mini"
    });
    counter.setTextMaxChars((len + "/" + len).length);
    bb = new CUI.Buttonbar({
      buttons: [prevBtn, counter, nextBtn]
    });
    return this.replace(bb, "navigation");
  };

  AssetBrowserInfoControl.prototype.getInfoButton = function() {
    return this.__info_button;
  };

  AssetBrowserInfoControl.prototype.__getDownloadOriginalButton = function() {
    if (!ez5.session.hasSystemRight("root", "frontend_features[download]")) {
      return null;
    }
    return new CUI.Button({
      ui: "asset.browser.download.control.button",
      icon: $$("asset.download_original|icon"),
      size: "mini",
      tooltip: {
        text: $$("asset.download.versions|tooltip")
      },
      onClick: (function(_this) {
        return function() {
          return _this.__startDownloadCurrentAsset();
        };
      })(this)
    });
  };

  AssetBrowserInfoControl.prototype.__startDownloadCurrentAsset = function() {
    var currentAsset, downloadManager, getAssetsFilter, resultObject;
    currentAsset = this._assetBrowser.getCurrentAsset();
    getAssetsFilter = (function(_this) {
      return function() {
        var asset, assetsFilter, i, len1, ref;
        assetsFilter = {};
        ref = _this._assetBrowser.getAssets();
        for (i = 0, len1 = ref.length; i < len1; i++) {
          asset = ref[i];
          assetsFilter[asset.getId()] = asset.getId() === currentAsset.getId();
        }
        return assetsFilter;
      };
    })(this);
    if (!currentAsset.data._global_object_id) {
      console.warn("We cannot start download manager without an object with a global_object_id");
      return;
    }
    resultObject = new ResultObject();
    resultObject.setData(currentAsset.data);
    downloadManager = new DownloadManager({
      result_object: resultObject,
      assetsFilter: getAssetsFilter()
    });
    downloadManager.startExport();
  };

  AssetBrowserInfoControl.prototype.getAssetLabelText = function() {
    var assetField;
    assetField = this._assetBrowser.getCurrentAsset().getField();
    if (!(assetField instanceof EASField)) {
      return assetField.fullNameLocalized();
    }
    return assetField.name();
  };

  return AssetBrowserInfoControl;

})(CUI.DOMElement);

CUI.Events.registerEvent({
  type: "asset-browser-info-change-version",
  sink: true
});

CUI.Events.registerEvent({
  type: "asset-browser-info-control-close",
  sink: true
});
// 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.PDFViewerAssetDetail = (function(superClass) {
  extend(PDFViewerAssetDetail, superClass);

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

  PDFViewerAssetDetail.prototype.getButtonLocaKey = function(asset) {
    if (!ez5.session.hasSystemRight("root", "frontend_features[download]")) {
      return;
    }
    if (!this.getPDFVersion(asset)) {
      return;
    }
    return "pdf-viewer.asset-detail";
  };

  PDFViewerAssetDetail.prototype.getPDFVersion = function(asset) {
    var name, ref, ref1, version;
    if (asset.value.class_extension === "office.pdf") {
      if (((ref = asset.value.versions.original) != null ? ref.status : void 0) === "done" && Asset.checkVersionShowAllowed(asset.value.versions.original)) {
        return asset.value.versions.original.url;
      }
    }
    if (!asset.value.versions) {
      return null;
    }
    ref1 = asset.value.versions;
    for (name in ref1) {
      version = ref1[name];
      if (version.extension === "pdf" && version.status === "done" && Asset.checkVersionShowAllowed(version)) {
        return version.url;
      }
    }
    return null;
  };

  PDFViewerAssetDetail.prototype.createMarkup = function() {
    var lbl, objectElement, versionUrl;
    PDFViewerAssetDetail.__super__.createMarkup.call(this);
    versionUrl = this.getPDFVersion(this.asset);
    if (!versionUrl) {
      return;
    }
    objectElement = CUI.dom.element("OBJECT", {
      "class": "ez5-pdf-viewer-asset-detail"
    });
    objectElement.data = Session.addToken(versionUrl);
    objectElement.type = "application/pdf";
    CUI.dom.append(this.outerDiv, objectElement);
    lbl = new CUI.Label({
      "class": "ez5-pdf-viewer-asset-detail-filename",
      text: this.asset.value.original_filename
    });
    return CUI.dom.append(this.outerDiv, lbl);
  };

  return PDFViewerAssetDetail;

})(AssetDetail);

ez5.session_ready(function() {
  return AssetBrowser.plugins.registerPlugin(ez5.PDFViewerAssetDetail);
});
// Generated by CoffeeScript 1.12.7
var ScheduleEditorNode,
  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;

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

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

  return ScheduleEditorNode;

})(ListViewEditTreeNode);
// Generated by CoffeeScript 1.12.7
var ScheduleEditor,
  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;

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

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

  ScheduleEditor.prototype.initOpts = function() {
    ScheduleEditor.__super__.initOpts.call(this);
    return this.addOpts({
      button_type: {
        mandatory: true,
        check: ["apply", "save"]
      },
      has_schedules: {
        check: Boolean
      },
      loadSchedules: {
        check: Function
      },
      show_minutes: {
        check: Boolean
      },
      onButtonClick: {
        check: Function
      }
    });
  };

  ScheduleEditor.prototype.loadSchedules = function() {
    var dfr, load_schedules, ret;
    dfr = new CUI.Deferred();
    load_schedules = (function(_this) {
      return function(schedules) {
        var j, len, s;
        _this.__schedules = [];
        for (j = 0, len = schedules.length; j < len; j++) {
          s = schedules[j];
          if (!s.timezone) {
            s.timezone = CUI.Timezone.getTimezone();
          }
          _this.__schedules.push(new ScheduleEditorNode({
            data: s
          }));
        }
        _this.__startData = JSON.stringify(_this.getSaveData());
        return dfr.resolve();
      };
    })(this);
    if (this._schedules) {
      load_schedules(this._schedules);
    } else {
      ret = this._loadSchedules();
      if (CUI.util.isArray(ret)) {
        load_schedules(ret);
      } else {
        CUI.util.assert(CUI.util.isPromise(ret), "ScheduleEditor.loadSchedules", "Function needs to return Array or Promise", {
          "return": ret
        });
        ret.done(function(schedules) {
          return load_schedules(schedules);
        }).fail(dfr.reject);
      }
    }
    dfr.done((function(_this) {
      return function() {
        return _this.setButtonState();
      };
    })(this));
    return dfr.promise();
  };

  ScheduleEditor.prototype.setButtonState = function() {
    if (this.__schedules.length > 0) {
      return this.openButton.activate();
    } else {
      return this.openButton.deactivate();
    }
  };

  ScheduleEditor.prototype.getButton = function(opts) {
    if (opts == null) {
      opts = {};
    }
    CUI.util.mergeMap(opts, {
      ui: "schedule-editor-button",
      loca_key: "schedule.editor.button",
      secondary: true,
      onClick: (function(_this) {
        return function() {
          return _this.openPopover();
        };
      })(this)
    });
    this.openButton = new LocaButton(opts);
    if (this._has_schedules === true) {
      this.openButton.activate();
    } else if (this._has_schedules === false) {

    } else {
      this.loadSchedules();
    }
    return this.openButton;
  };

  ScheduleEditor.prototype.checkChanged = function() {
    var hasEmptySchedules, saveData;
    if (this.tree.getSelectedNode()) {
      this.minusButton.enable();
    } else {
      this.minusButton.disable();
    }
    saveData = this.getSaveData();
    hasEmptySchedules = saveData.some((function(_this) {
      return function(schedule) {
        return CUI.util.isEmpty(schedule.days_of_month) && CUI.util.isEmpty(schedule.weekdays) && CUI.util.isEmpty(schedule.hours);
      };
    })(this));
    if (hasEmptySchedules) {
      this.saveButton.disable();
      return;
    }
    if (this.__startData !== JSON.stringify(saveData)) {
      return this.saveButton.enable();
    } else {
      return this.saveButton.disable();
    }
  };

  ScheduleEditor.prototype.openPopover = function() {
    this.saveButton = new LocaButton({
      ui: "schedule-editor-" + this._button_type + "-button",
      loca_key: "schedule.editor.button." + this._button_type,
      primary: true,
      onClick: (function(_this) {
        return function(ev) {
          var ret, saved, sd;
          sd = _this.getSaveData();
          if (ev.hasModifierKey()) {
            console.debug("schedule save", CUI.util.dump(sd));
            return;
          }
          saved = function() {
            _this.loadSchedules();
            return _this.modal.destroy();
          };
          ret = typeof _this._onButtonClick === "function" ? _this._onButtonClick(ev, sd) : void 0;
          if (CUI.util.isPromise(ret)) {
            ret.done(saved);
          } else {
            saved();
          }
        };
      })(this)
    });
    this.tree = new ListViewEditTree({
      maximize: true,
      "class": 'cui-lv--has-datafields',
      no_hierarchy: true,
      fields: [
        {
          th_label: "schedule.editor.col.schedule",
          type: CUI.Form,
          undo_support: false,
          fields: ScheduleEditor.getFields({
            show_minutes: this._show_minutes
          })
        }
      ],
      cols: ["maximize"],
      selectableRows: true,
      rowMove: false,
      footer_left: [
        {
          loca_key: "schedule.editor.plus_button",
          group: "plus-minus",
          "class": "btn-mini",
          onClick: (function(_this) {
            return function() {
              var data, node;
              data = {
                timezone: CUI.Timezone.getTimezone()
              };
              node = new ScheduleEditorNode({
                data: data
              });
              return _this.tree.addNode(node);
            };
          })(this)
        }, this.minusButton = new LocaButton({
          loca_key: "schedule.editor.minus_button",
          disabled: true,
          group: "plus-minus",
          "class": "btn-mini",
          onClick: (function(_this) {
            return function() {
              var ref;
              return (ref = _this.tree.getSelectedNode()) != null ? ref.remove() : void 0;
            };
          })(this)
        })
      ]
    });
    CUI.Events.listen({
      node: this.tree,
      type: ["row_added", "row_removed", "row_deselected", "row_selected", "data-changed"],
      call: (function(_this) {
        return function(ev, info) {
          return _this.checkChanged();
        };
      })(this)
    });
    this.modal = new CUI.Modal({
      "class": "ez5-schedule-editor-modal",
      cancel: true,
      onHide: (function(_this) {
        return function() {
          _this.tree.destroy();
          return _this.tree = null;
        };
      })(this),
      onCancel: (function(_this) {
        return function() {
          if (_this.saveButton.isDisabled()) {

          } else {
            return CUI.confirm({
              text: $$("schedule.editor.confirm.discard")
            });
          }
        };
      })(this),
      pane: {
        header_left: new CUI.Label({
          text: $$("schedule.editor.title")
        }),
        footer_right: (function(_this) {
          return function() {
            return new CUI.Buttonbar({
              buttons: [_this.saveButton]
            });
          };
        })(this),
        content: (function(_this) {
          return function() {
            var t;
            t = _this.tree.render();
            _this.loadSchedules().done(function() {
              _this.tree.load_data(_this.__schedules);
              return _this.checkChanged();
            });
            return t;
          };
        })(this)
      }
    });
    return this.modal.show();
  };

  ScheduleEditor.prototype.getSaveData = function() {
    var j, k, l, len, len1, ref, ref1, s, sch, sd, sdata;
    sd = [];
    ref = this.__schedules;
    for (j = 0, len = ref.length; j < len; j++) {
      s = ref[j];
      sdata = s.getData();
      sch = {};
      ref1 = ["days_of_month", "hours", "weekdays", "minutes", "timezone"];
      for (l = 0, len1 = ref1.length; l < len1; l++) {
        k = ref1[l];
        if (!this._show_minutes && k === "minutes") {
          continue;
        }
        sch[k] = sdata[k] || [];
      }
      sd.push(sch);
    }
    return sd;
  };

  ScheduleEditor.getFields = function(_opts) {
    var day, days_opts, fields, get_preset_by_data, get_preset_data, hour, hours_opts, j, l, len, len1, m, n, opts, preset_names, preset_opt, preset_opts, ref, set_field_visibility, timezones, update_constrained_fields, update_fields, update_fields_reset, wd, weekdays_opts;
    if (_opts == null) {
      _opts = {};
    }
    opts = CUI.Element.readOpts(_opts, "ScheduleEditor.getFields", {
      show_minutes: {
        check: Boolean
      }
    });
    preset_names = ['none', 'custom', 'weekly', 'daily', 'hourly'];
    if (opts.show_minutes) {
      preset_names.push.apply(preset_names, ['30_minutes', '15_minutes', '10_minutes', '5_minutes', '1_minute']);
    }
    get_preset_by_data = (function(_this) {
      return function(sdata) {
        var cdata, data, j, k, len, preset_name, v;
        for (j = 0, len = preset_names.length; j < len; j++) {
          preset_name = preset_names[j];
          if (preset_name === "custom") {
            continue;
          }
          cdata = {};
          data = get_preset_data(preset_name);
          for (k in data) {
            v = data[k];
            cdata[k] = sdata[k] || [];
          }
          if (JSON.stringify(data) === JSON.stringify(cdata)) {
            return preset_name;
          }
        }
        return 'custom';
      };
    })(this);
    get_preset_data = (function(_this) {
      return function(preset_name) {
        var data, days_of_month, i;
        data = {};
        switch (preset_name) {
          case 'none':
            data.days_of_month = [];
            data.weekdays = [];
            data.hours = [];
            data.minutes = [];
            break;
          case 'weekly':
            days_of_month = [];
            data.weekdays = ['sunday'];
            data.hours = [];
            data.minutes = [];
            break;
          case 'daily':
            data.days_of_month = [];
            data.weekdays = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
            data.hours = [];
            data.minutes = [];
            break;
          case 'hourly':
            data.days_of_month = [];
            data.weekdays = [];
            data.hours = (function() {
              var j, results;
              results = [];
              for (i = j = 0; j <= 23; i = ++j) {
                results.push(i);
              }
              return results;
            })();
            data.minutes = [];
            break;
          case '1_minute':
            data.days_of_month = [];
            data.weekdays = [];
            data.hours = (function() {
              var j, results;
              results = [];
              for (i = j = 0; j <= 23; i = ++j) {
                results.push(i);
              }
              return results;
            })();
            data.minutes = (function() {
              var j, results;
              results = [];
              for (i = j = 0; j <= 59; i = ++j) {
                results.push(i);
              }
              return results;
            })();
            break;
          case '5_minutes':
            data.days_of_month = [];
            data.weekdays = [];
            data.hours = (function() {
              var j, results;
              results = [];
              for (i = j = 0; j <= 23; i = ++j) {
                results.push(i);
              }
              return results;
            })();
            data.minutes = (function() {
              var j, results;
              results = [];
              for (i = j = 0; j <= 59; i = j += 5) {
                results.push(i);
              }
              return results;
            })();
            break;
          case '10_minutes':
            data.days_of_month = [];
            data.weekdays = [];
            data.hours = (function() {
              var j, results;
              results = [];
              for (i = j = 0; j <= 23; i = ++j) {
                results.push(i);
              }
              return results;
            })();
            data.minutes = (function() {
              var j, results;
              results = [];
              for (i = j = 0; j <= 59; i = j += 10) {
                results.push(i);
              }
              return results;
            })();
            break;
          case '15_minutes':
            data.days_of_month = [];
            data.weekdays = [];
            data.hours = (function() {
              var j, results;
              results = [];
              for (i = j = 0; j <= 23; i = ++j) {
                results.push(i);
              }
              return results;
            })();
            data.minutes = (function() {
              var j, results;
              results = [];
              for (i = j = 0; j <= 59; i = j += 15) {
                results.push(i);
              }
              return results;
            })();
            break;
          case '30_minutes':
            data.days_of_month = [];
            data.weekdays = [];
            data.hours = (function() {
              var j, results;
              results = [];
              for (i = j = 0; j <= 23; i = ++j) {
                results.push(i);
              }
              return results;
            })();
            data.minutes = (function() {
              var j, results;
              results = [];
              for (i = j = 0; j <= 59; i = j += 30) {
                results.push(i);
              }
              return results;
            })();
        }
        if (!opts.show_minutes) {
          delete data.minutes;
        }
        return data;
      };
    })(this);
    preset_opts = [];
    for (j = 0, len = preset_names.length; j < len; j++) {
      preset_opt = preset_names[j];
      preset_opts.push({
        text: $$("schedule.editor.form.preset." + preset_opt),
        value: preset_opt
      });
    }
    update_fields_reset = (function(_this) {
      return function(data, df) {
        var fo, k, ref, v;
        if (data._preset !== "custom") {
          ref = get_preset_data(data._preset);
          for (k in ref) {
            v = ref[k];
            data[k] = v;
          }
        } else if (opts.show_minutes) {
          data.minutes = [];
        }
        fo = df.getForm();
        fo.reload();
        set_field_visibility(data, fo);
        return update_constrained_fields(data, fo);
      };
    })(this);
    set_field_visibility = (function(_this) {
      return function(data, fo) {
        var key, l, len1, ref;
        ref = ["days_of_month", "weekdays", "hours", "timezone"];
        for (l = 0, len1 = ref.length; l < len1; l++) {
          key = ref[l];
          if (data._preset.match(/minute/)) {
            fo.getFieldsByName(key)[0].hide(true);
          } else {
            fo.getFieldsByName(key)[0].show(true);
          }
        }
      };
    })(this);
    update_constrained_fields = (function(_this) {
      return function(data, fo) {
        var ref, ref1;
        if (!ez5.version("6")) {
          return;
        }
        if (((ref = data["days_of_month"]) != null ? ref.length : void 0) > 0) {
          fo.getFieldsByName("weekdays")[0].hide(true);
          if (data["weekdays"]) {
            delete data["weekdays"];
          }
          return;
        } else if (!data._preset.match(/minute/)) {
          fo.getFieldsByName("weekdays")[0].show(true);
        }
        if (((ref1 = data["weekdays"]) != null ? ref1.length : void 0) > 0) {
          return fo.getFieldsByName("days_of_month")[0].hide(true);
        } else if (!data._preset.match(/minute/)) {
          return fo.getFieldsByName("days_of_month")[0].show(true);
        }
      };
    })(this);
    update_fields = (function(_this) {
      return function(data, df) {
        var preset;
        preset = get_preset_by_data(data);
        if (preset === "custom" && opts.show_minutes) {
          data.minutes = [];
        }
        df.getForm().getFieldsByName("_preset")[0].setValue(get_preset_by_data(data));
        return update_constrained_fields(data, df.getForm());
      };
    })(this);
    days_opts = [];
    weekdays_opts = [];
    hours_opts = [];
    for (day = l = 0; l <= 30; day = ++l) {
      days_opts.push({
        text: (day + 1) + "",
        value: day + 1
      });
    }
    ref = ez5.weekdays;
    for (m = 0, len1 = ref.length; m < len1; m++) {
      wd = ref[m];
      weekdays_opts.push({
        text: $$("base.weekday." + wd),
        value: wd
      });
    }
    for (hour = n = 0; n <= 23; hour = ++n) {
      hours_opts.push({
        text: hour + "",
        value: hour
      });
    }
    timezones = ScheduleEditor.getTimezones();
    fields = [
      {
        form: {
          label: $$("schedule.editor.form.preset")
        },
        name: "_preset",
        undo_support: false,
        onDataInit: (function(_this) {
          return function(df, data) {
            if (!data._preset) {
              data._preset = get_preset_by_data(data);
              set_field_visibility(data, df.getForm());
              return update_constrained_fields(data, df.getForm());
            }
          };
        })(this),
        onDataChanged: update_fields_reset,
        type: CUI.Select,
        options: preset_opts
      }, {
        form: {
          label: $$("schedule.editor.form.days")
        },
        type: CUI.Options,
        onDataChanged: update_fields,
        undo_support: false,
        name: "days_of_month",
        horizontal: 10,
        options: days_opts
      }, {
        form: {
          label: $$("schedule.editor.form.weekdays")
        },
        type: CUI.Options,
        onDataChanged: update_fields,
        undo_support: false,
        horizontal: true,
        name: "weekdays",
        options: weekdays_opts
      }, {
        form: {
          label: $$("schedule.editor.form.hours")
        },
        onDataChanged: update_fields,
        name: "hours",
        undo_support: false,
        type: CUI.Options,
        horizontal: 10,
        options: hours_opts
      }, {
        form: {
          label: $$("schedule.editor.form.timezone")
        },
        onDataChanged: update_fields,
        name: "timezone",
        undo_support: false,
        type: CUI.Select,
        onDataInit: function(_, data) {
          var len2, o, timezone;
          if (!data.timezone) {
            return;
          }
          for (o = 0, len2 = timezones.length; o < len2; o++) {
            timezone = timezones[o];
            if (timezone.value === data.timezone) {
              return;
            }
          }
          timezones.unshift({
            text: data.timezone,
            value: data.timezone
          });
        },
        options: function() {
          return timezones;
        }
      }
    ];
    return fields;
  };

  ScheduleEditor.getTimezones = function() {
    var j, len, options, ref, timezone;
    options = [
      {
        text: $$("schedule.editor.form.timezone.default-option"),
        value: "Etc/UTC"
      }
    ];
    ref = CUI.Timezone.timezones;
    for (j = 0, len = ref.length; j < len; j++) {
      timezone = ref[j];
      options.push({
        text: timezone.displayName,
        value: timezone.name
      });
    }
    return options;
  };

  ScheduleEditor.isEmpty = function(data) {
    var j, k, l, len, len1, len2, m, props, s;
    if (CUI.util.isEmpty(data)) {
      return true;
    }
    props = ["days_of_month", "weekdays", "hours"];
    if (CUI.util.isArray(data)) {
      for (j = 0, len = data.length; j < len; j++) {
        s = data[j];
        for (l = 0, len1 = props.length; l < len1; l++) {
          k = props[l];
          if (!CUI.util.isEmpty(s[k])) {
            return false;
          }
        }
      }
    } else {
      for (m = 0, len2 = props.length; m < len2; m++) {
        k = props[m];
        if (!CUI.util.isEmpty(data[k])) {
          return false;
        }
      }
    }
    return true;
  };

  ScheduleEditor.getSchedulerFormButton = function(opts) {
    var button, getField, hasData, proxyField, showSchedulerModal, updateButtonStatus;
    button = null;
    hasData = function(field) {
      var data;
      data = field.getData()[opts.name];
      return !ScheduleEditor.isEmpty(data);
    };
    getField = (function(_this) {
      return function() {
        if (opts.multiple) {
          return [
            {
              type: CUI.DataTable,
              no_header: true,
              maximize: true,
              name: opts.name,
              fields: [
                {
                  type: CUI.Form,
                  fields: ScheduleEditor.getFields()
                }
              ]
            }
          ];
        } else {
          return ScheduleEditor.getFields();
        }
      };
    })(this);
    updateButtonStatus = (function(_this) {
      return function(df) {
        if (hasData(df)) {
          button.setActive(true);
          return button.setText(opts.editLabelText || $$("admin.user.schedule.edit"));
        } else {
          button.setActive(false);
          return button.setText(opts.labelText || $$("admin.user.schedule"));
        }
      };
    })(this);
    showSchedulerModal = (function(_this) {
      return function(name, df) {
        var popover;
        if (CUI.util.isEmpty(df.getData()[opts.name])) {
          df.getData()[opts.name] = [{}];
        }
        popover = new CUI.Popover({
          element: button,
          "class": opts.modal_class,
          pane: {
            title: "Schedules Editor",
            content: (new CUI.Form({
              fields: getField(),
              data: df.getData()
            })).start(),
            footer_right: []
          },
          onHide: function() {
            updateButtonStatus(df);
            return CUI.Events.trigger({
              node: df,
              type: "data-changed",
              info: {
                element: df
              }
            });
          }
        });
        return popover.show();
      };
    })(this);
    proxyField = {
      type: CUI.DataFieldProxy,
      form: opts.form,
      name: opts.name,
      element: function(df) {
        return button = new CUI.Button({
          icon: "fa-calendar",
          active: hasData(df),
          text: hasData(df) ? opts.editLabelText || $$("admin.user.schedule.edit") : opts.labelText || $$("admin.user.schedule"),
          onClick: (function(_this) {
            return function(ev, button) {
              return showSchedulerModal(name, df);
            };
          })(this)
        });
      }
    };
    return proxyField;
  };

  return ScheduleEditor;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var DecimalTokenizer, DoubleTokenizer, NumberTokenizer, Tokenizer,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function Tokenizer() {
    this.tokenize = bind(this.tokenize, this);
    this.retrieveTokens = bind(this.retrieveTokens, this);
    this.getTokens = bind(this.getTokens, this);
    return Tokenizer.__super__.constructor.apply(this, arguments);
  }

  Tokenizer.DASH = '-';

  Tokenizer.COMMA = ',';

  Tokenizer.EMPTY_CHARACTER = '';

  Tokenizer.SPACE = ' ';

  Tokenizer.QUOTES = '"';

  Tokenizer.SINGLE_QUOTE = "'";

  Tokenizer.GRAVE_ACCENT = '`';

  Tokenizer.prototype.readOpts = function() {
    this.tokenClass = Tokenizer.TextToken;
    this.phraseTokenClass = Tokenizer.PhraseToken;
    this.exactTokenClass = Tokenizer.ExactToken;
    this.rangeTokenClass = Tokenizer.RangeToken;
    this.comma = Tokenizer.COMMA;
    return this.space = Tokenizer.SPACE;
  };

  Tokenizer.prototype.getTokens = function(val) {
    var c, chars, end_token, i, idx, k, phrase_end_char, phrase_state, push_char, push_common_token, push_token, ref, reset_chars, start_idx, tokens;
    chars = [];
    tokens = [];
    phrase_state = 0;
    start_idx = 0;
    idx = null;
    reset_chars = (function(_this) {
      return function() {
        return chars = [];
      };
    })(this);
    push_char = (function(_this) {
      return function(c) {
        if (chars.length === 0) {
          start_idx = idx;
        }
        return chars.push(c);
      };
    })(this);
    push_token = (function(_this) {
      return function(token) {
        var ptoken;
        if (token === "") {
          return;
        }
        ptoken = {
          start: start_idx,
          end: start_idx + token.length,
          raw_token: token
        };
        if (token.startsWith(Tokenizer.GRAVE_ACCENT) && token.endsWith(Tokenizer.GRAVE_ACCENT)) {
          if (token.length === 2) {
            return;
          }
          ptoken.token = token.substr(1, token.length - 2);
          ptoken.exact = true;
        } else if (token.startsWith(Tokenizer.QUOTES) && token.endsWith(Tokenizer.QUOTES)) {
          if (token.length === 2) {
            return;
          }
          ptoken.token = token.substr(1, token.length - 2);
          ptoken.phrase = true;
        } else if (token === Tokenizer.DASH) {
          ptoken.range = true;
          ptoken.token = Tokenizer.EMPTY_CHARACTER;
        } else if (token === _this.comma) {
          ptoken.comma = true;
          ptoken.token = Tokenizer.EMPTY_CHARACTER;
        } else if (token === _this.space) {
          ptoken.space = true;
          ptoken.token = Tokenizer.EMPTY_CHARACTER;
        } else {
          ptoken.token = SearchUtil.removeSingleQuotes(token);
        }
        if (ptoken.token.length > SearchUtil.SEARCH_MAX_LENGTH) {
          ptoken.token = ptoken.token.substring(0, SearchUtil.SEARCH_MAX_LENGTH);
        }
        tokens.push(ptoken);
      };
    })(this);
    end_token = (function(_this) {
      return function(extra_token) {
        var token;
        token = chars.join(Tokenizer.EMPTY_CHARACTER).trim();
        push_token(token);
        if (extra_token) {
          start_idx = start_idx + token.length;
          push_token(extra_token);
        }
        reset_chars();
      };
    })(this);
    push_common_token = (function(_this) {
      return function(token) {
        if (phrase_state === 2) {
          end_token(_this.comma);
          phrase_state = 0;
        }
        push_char(token);
      };
    })(this);
    for (i = k = 0, ref = val.length - 1; 0 <= ref ? k <= ref : k >= ref; i = 0 <= ref ? ++k : --k) {
      idx = i;
      c = val.substr(i, 1);
      switch (c) {
        case this.comma:
          if (phrase_state === 1) {
            push_char(c);
          } else {
            if (phrase_state === 2) {
              phrase_state = 0;
            }
            end_token(c);
          }
          break;
        case Tokenizer.GRAVE_ACCENT:
          switch (phrase_state) {
            case 0:
              if (chars.length) {
                end_token(this.comma);
              }
              phrase_end_char = c;
              phrase_state = 1;
              push_char(c);
              break;
            case 1:
              phrase_state = 2;
              push_char(c);
              break;
            case 2:
              end_token(this.comma);
              phrase_state = 1;
              push_char(c);
          }
          break;
        case Tokenizer.QUOTES:
          switch (phrase_state) {
            case 0:
              if (chars.length) {
                end_token(this.comma);
              }
              phrase_end_char = c;
              phrase_state = 1;
              push_char(c);
              break;
            case 1:
              phrase_state = 2;
              push_char(c);
              break;
            case 2:
              end_token(this.comma);
              phrase_state = 1;
              push_char(c);
          }
          break;
        case Tokenizer.SPACE:
          switch (phrase_state) {
            case 0:
              end_token(Tokenizer.SPACE);
              break;
            default:
              push_common_token(c);
          }
          break;
        case Tokenizer.SINGLE_QUOTE:
          switch (phrase_state) {
            case 0:
              if (chars.length && chars[0].trim()) {
                end_token(this.comma);
              }
              push_char(c);
              phrase_state = 1;
              break;
            case 1:
              push_char(c);
              phrase_state = 2;
              break;
            case 2:
              push_char(c);
              phrase_state = 1;
              end_token(this.comma);
          }
          break;
        case Tokenizer.DASH:
          if (val[i + 1] === Tokenizer.SPACE && val[i - 1] === Tokenizer.SPACE) {
            if (phrase_state === 1) {
              push_char(c);
            } else {
              if (phrase_state === 2) {
                phrase_state = 0;
              }
              end_token(c);
            }
          } else {
            push_common_token(c);
          }
          break;
        default:
          push_common_token(c);
      }
    }
    if (phrase_state === 1) {
      if (phrase_end_char) {
        push_char(phrase_end_char);
      }
      phrase_state = 2;
    }
    end_token();
    return tokens;
  };

  Tokenizer.prototype.retrieveTokens = function(tokens) {
    var __findRangeIndex, _idx, end, fromParts, fromValue, i, idx, j, rangeIdx, ret_tokens, start, t, toEnd, toIdx, toParts, toValue, token;
    ret_tokens = [];
    _idx = 0;
    __findRangeIndex = function(from) {
      var i;
      i = from;
      while (i < tokens.length) {
        if (tokens[i].range) {
          return i;
        }
        if (tokens[i].comma) {
          return -1;
        }
        i++;
      }
      return -1;
    };
    while (_idx < tokens.length) {
      idx = _idx;
      token = tokens[idx];
      start = token.start;
      end = token.end;
      if (token.exact) {
        ret_tokens.push(new this.exactTokenClass(token.token, start, end));
        _idx++;
        continue;
      }
      if (token.phrase) {
        ret_tokens.push(new this.phraseTokenClass(token.token, start, end));
        _idx++;
        continue;
      }
      if (token.space || token.comma || token.range) {
        _idx++;
        continue;
      }
      rangeIdx = __findRangeIndex(idx + 1);
      if (rangeIdx >= 0) {
        fromParts = [];
        i = idx;
        while (i < rangeIdx) {
          t = tokens[i];
          if (t.space) {
            fromParts.push(Tokenizer.SPACE);
          } else if (t.token && t.token.length) {
            fromParts.push(t.token);
          }
          i++;
        }
        fromValue = fromParts.join(Tokenizer.EMPTY_CHARACTER).trim();
        toIdx = rangeIdx + 1;
        while (toIdx < tokens.length && tokens[toIdx].space) {
          toIdx++;
        }
        toParts = [];
        toEnd = start;
        j = toIdx;
        while (j < tokens.length) {
          t = tokens[j];
          if (t.range || t.comma) {
            break;
          }
          if (t.space) {
            toParts.push(Tokenizer.SPACE);
          } else if (t.token && t.token.length) {
            toParts.push(t.token);
            toEnd = t.end;
          }
          j++;
        }
        toValue = toParts.join(Tokenizer.EMPTY_CHARACTER).trim();
        if (fromValue.length && toValue.length) {
          ret_tokens.push(new this.rangeTokenClass(fromValue, toValue, start, toEnd));
          _idx = j;
          continue;
        }
      }
      if (token.token && token.token.length) {
        ret_tokens.push(new this.tokenClass(token.token, token.raw_token, start, end));
      }
      _idx++;
    }
    return ret_tokens;
  };

  Tokenizer.prototype.tokenize = function(val) {
    return this.retrieveTokens(this.getTokens(val));
  };

  Tokenizer.test = function(val) {
    var Tokens, k, len, tokenizer, tokens, values;
    tokenizer = new Tokenizer({
      debug: true
    });
    if (arguments.length > 0) {
      values = [];
      if (indexOf.call(arguments, val) >= 0) {
        values.push(val);
      }
    } else {
      values = ['12-23', '"123,23","31290-312', '12-', '"open phrase'];
    }
    for (k = 0, len = values.length; k < len; k++) {
      val = values[k];
      console.debug('tokenize:', val);
      tokens = tokenizer.getTokens(val);
      console.debug('tokens:', CUI.util.dump(tokens));
      Tokens = tokenizer.retrieveTokens(tokens);
      console.debug('Tokens:', Tokens);
    }
  };

  return Tokenizer;

})(CUI.Element);

Tokenizer.RangeToken = (function() {
  function RangeToken(from1, to, start1, end1) {
    this.from = from1;
    this.to = to;
    this.start = start1;
    this.end = end1;
  }

  RangeToken.prototype.getFilter = function(field) {
    var filter;
    filter = {
      type: "range",
      field: field.getSearchField()
    };
    if (!CUI.util.isEmpty(this.from)) {
      filter.from = this.from;
    }
    if (!CUI.util.isEmpty(this.to)) {
      filter.to = this.to;
    }
    return filter;
  };

  return RangeToken;

})();

Tokenizer.TextToken = (function() {
  function TextToken(text, raw_token, start1, end1) {
    this.text = text;
    this.raw_token = raw_token;
    this.start = start1;
    this.end = end1;
  }

  TextToken.prototype.__getMode = function() {
    if (SearchUtil.isWrappedWithSingleQuotes(this.raw_token)) {
      return "token";
    }
    if (SearchUtil.isWildcard(this.text)) {
      return "wildcard";
    }
    return "fulltext";
  };

  TextToken.prototype.getFilter = function(field) {
    var filter;
    filter = {
      type: "match",
      string: this.text,
      fields: [field.getSearchField()],
      mode: this.__getMode()
    };
    return filter;
  };

  return TextToken;

})();

Tokenizer.PhraseToken = (function() {
  function PhraseToken(phrase1, start1, end1) {
    this.phrase = phrase1;
    this.start = start1;
    this.end = end1;
  }

  PhraseToken.prototype.getFilter = function(field) {
    var filter;
    return filter = {
      type: "match",
      string: this.phrase,
      phrase: true,
      fields: [field.getSearchField()]
    };
  };

  return PhraseToken;

})();

Tokenizer.ExactToken = (function() {
  function ExactToken(text, start1, end1) {
    this.text = text;
    this.start = start1;
    this.end = end1;
  }

  ExactToken.prototype.getFilter = function(field) {
    var filter;
    return filter = {
      type: "text",
      query: "exact",
      string: this.text,
      fields: [field.getSearchField()]
    };
  };

  return ExactToken;

})();

Tokenizer.StringToken = (function() {
  function StringToken(value, start1, end1) {
    this.value = value;
    this.start = start1;
    this.end = end1;
  }

  StringToken.prototype.getFilter = function(field) {
    var filter;
    return filter = {
      type: "in",
      "in": [this.value],
      fields: [field.getSearchField()]
    };
  };

  return StringToken;

})();

Tokenizer.NumberToken = (function(superClass) {
  extend(NumberToken, superClass);

  function NumberToken(number, start1, end1) {
    this.start = start1;
    this.end = end1;
    this.value = parseInt(number.trim());
    if (isNaN(this.value)) {
      this.value = null;
    }
  }

  NumberToken.prototype.getFilter = function(field) {
    if (this.value === null) {
      return null;
    } else {
      return NumberToken.__super__.getFilter.call(this, field);
    }
  };

  return NumberToken;

})(Tokenizer.StringToken);

Tokenizer.DecimalToken = (function(superClass) {
  extend(DecimalToken, superClass);

  function DecimalToken(number, start1, end1) {
    this.start = start1;
    this.end = end1;
    this.value = Tokenizer.DecimalToken.formatNumber(number);
  }

  DecimalToken.formatNumber = function(number) {
    number = number.trim();
    number = number.replace(",", ".");
    number = parseFloat(number);
    if (isNaN(number)) {
      return null;
    }
    return number.toFixed(2) * 100;
  };

  return DecimalToken;

})(Tokenizer.NumberToken);

Tokenizer.DoubleToken = (function(superClass) {
  extend(DoubleToken, superClass);

  function DoubleToken(number, start1, end1) {
    this.start = start1;
    this.end = end1;
    this.value = Tokenizer.DoubleToken.formatNumber(number);
  }

  DoubleToken.formatNumber = function(number) {
    number = number.trim();
    number = CUI.NumberInput.parse(number, -1);
    if (isNaN(number)) {
      return null;
    }
    return number;
  };

  return DoubleToken;

})(Tokenizer.NumberToken);

Tokenizer.NumberPhraseToken = (function(superClass) {
  extend(NumberPhraseToken, superClass);

  function NumberPhraseToken(phrase, start1, end1) {
    this.start = start1;
    this.end = end1;
    NumberPhraseToken.__super__.constructor.call(this, phrase, this.start, this.end);
  }

  return NumberPhraseToken;

})(Tokenizer.NumberToken);

Tokenizer.NumberRangeToken = (function(superClass) {
  extend(NumberRangeToken, superClass);

  function NumberRangeToken(from1, to, start1, end1) {
    this.from = from1;
    this.to = to;
    this.start = start1;
    this.end = end1;
    this.from = Tokenizer.DecimalToken.formatNumber(this.from);
    this.to = Tokenizer.DecimalToken.formatNumber(this.to);
    return;
  }

  return NumberRangeToken;

})(Tokenizer.RangeToken);

Tokenizer.DoubleRangeToken = (function(superClass) {
  extend(DoubleRangeToken, superClass);

  function DoubleRangeToken(from1, to, start1, end1) {
    this.from = from1;
    this.to = to;
    this.start = start1;
    this.end = end1;
    this.from = Tokenizer.DoubleToken.formatNumber(this.from);
    this.to = Tokenizer.DoubleToken.formatNumber(this.to);
    return;
  }

  return DoubleRangeToken;

})(Tokenizer.RangeToken);

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

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

  NumberTokenizer.prototype.readOpts = function() {
    NumberTokenizer.__super__.readOpts.call(this);
    this.tokenClass = Tokenizer.NumberToken;
    return this.phraseTokenClass = Tokenizer.NumberPhraseToken;
  };

  return NumberTokenizer;

})(Tokenizer);

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

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

  DecimalTokenizer.SEMICOLON = ";";

  DecimalTokenizer.prototype.readOpts = function() {
    DecimalTokenizer.__super__.readOpts.call(this);
    this.tokenClass = Tokenizer.DecimalToken;
    this.rangeTokenClass = Tokenizer.NumberRangeToken;
    return this.comma = DecimalTokenizer.SEMICOLON;
  };

  return DecimalTokenizer;

})(NumberTokenizer);

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

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

  DoubleTokenizer.SEMICOLON = ";";

  DoubleTokenizer.prototype.readOpts = function() {
    DoubleTokenizer.__super__.readOpts.call(this);
    this.tokenClass = Tokenizer.DoubleToken;
    this.rangeTokenClass = Tokenizer.DoubleRangeToken;
    return this.comma = DecimalTokenizer.SEMICOLON;
  };

  return DoubleTokenizer;

})(NumberTokenizer);
// 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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  ScriptRunner.prototype.initOpts = function() {
    ScriptRunner.__super__.initOpts.call(this);
    return this.addOpts({
      count: {
        mandatory: true,
        check: (function(_this) {
          return function(v) {
            return CUI.util.isPosInt(v);
          };
        })(this)
      },
      getChunk: {
        mandatory: true,
        check: Function
      },
      caller: {
        check: function(v) {
          return v instanceof CUI.Element;
        }
      }
    });
  };

  ScriptRunner.prototype.readOpts = function() {
    var plugins;
    ScriptRunner.__super__.readOpts.call(this);
    plugins = ez5.ScriptRunner.plugins.newPlugins({
      scriptRunner: this
    });
    return this.__plugins = plugins.filter((function(_this) {
      return function(plugin) {
        return plugin.isAvailable();
      };
    })(this));
  };

  ScriptRunner.prototype.getActivePlugin = function() {
    var i, len, p, ref;
    if (this.__data.plugin) {
      ref = this.__plugins;
      for (i = 0, len = ref.length; i < len; i++) {
        p = ref[i];
        if (this.__data.plugin === p.name()) {
          return p;
        }
      }
    }
    return this.__plugins[0];
  };

  ScriptRunner.prototype.getFields = function() {
    var _f, _fields, content, desc, fields, i, j, len, len1, loadingLabel, maskSelectField, p, plugin, plugin_opts, ref;
    plugin = this.getActivePlugin();
    _fields = plugin.getFields(this.__data);
    plugin_opts = [];
    ref = this.__plugins;
    for (i = 0, len = ref.length; i < len; i++) {
      p = ref[i];
      plugin_opts.push({
        value: p.name(),
        text: p.nameLocalized()
      });
    }
    content = CUI.dom.div();
    loadingLabel = new LocaLabel({
      loca_key: "script.runner.form.mask.loading"
    });
    CUI.dom.append(content, loadingLabel);
    maskSelectField = new CUI.DataFieldProxy({
      form: {
        label: $$("script.runner.form.mask.label")
      },
      element: content
    });
    MaskFieldSelector.getFormSelect(this._caller, {
      data: this.__data
    }).done(function(maskSelectForm) {
      maskSelectForm.start();
      return CUI.dom.replace(content, maskSelectForm);
    }).fail(function() {
      var label;
      label = new LocaLabel({
        loca_key: "script.runner.form.mask.error-loading"
      });
      return CUI.dom.replace(content, label);
    });
    fields = [
      maskSelectField, {
        form: {
          label: $$("script.runner.form.limit")
        },
        type: CUI.Select,
        maximize_horizontal: true,
        options: [
          {
            value: this._count,
            text: $$("script.runner.form.limit.none", {
              count: this._count
            })
          }, {
            value: 1
          }, {
            value: 10
          }, {
            value: 100
          }
        ],
        name: "limit"
      }, {
        form: {
          label: $$("script.runner.form.filename")
        },
        type: CUI.Input,
        maximize_horizontal: true,
        name: "filename"
      }, {
        form: {
          label: $$("script.runner.form.plugin")
        },
        type: CUI.Select,
        name: "plugin",
        onDataChanged: (function(_this) {
          return function(data, df) {
            return df.getForm().reload();
          };
        })(this),
        maximize_horizontal: true,
        options: plugin_opts
      }
    ];
    desc = plugin.description();
    if (!CUI.util.isEmpty(desc)) {
      fields.push({
        type: CUI.Output,
        text: desc,
        markdown: true,
        maximize_horizontal: true
      });
    }
    for (j = 0, len1 = _fields.length; j < len1; j++) {
      _f = _fields[j];
      fields.push(_f);
    }
    return fields;
  };

  ScriptRunner.prototype.show = function() {
    var btns, form, mod;
    this.__data = CUI.getLocalStorage("script_runner.data");
    if (!this.__data) {
      this.__data = {};
    }
    if (!this.__data.plugin) {
      this.__data.plugin = this.__plugins[0].name();
    }
    this.__data.limit = this._count;
    if (!this.__data.chunk_size) {
      this.__data.chunk_size = 100;
    }
    form = new CUI.Form({
      data: this.__data,
      maximize: true,
      fields: (function(_this) {
        return function() {
          return _this.getFields(form);
        };
      })(this)
    });
    form.start();
    btns = [
      new LocaButton({
        loca_key: "script.runner.start",
        primary: true,
        onClick: (function(_this) {
          return function() {
            return _this.run();
          };
        })(this)
      })
    ];
    mod = new CUI.Modal({
      cancel: true,
      onCancel: (function(_this) {
        return function() {
          return delete _this.__data;
        };
      })(this),
      "class": "script-runner",
      fill_space: "vertical",
      pane: {
        padded: true,
        title: $$("script.runner.modal.title"),
        content: form,
        footer_right: [btns]
      }
    });
    return mod.show();
  };

  ScriptRunner.prototype.download = function(data, delim) {
    if (delim == null) {
      delim = "\n\r";
    }
    return this.__download_data.push(data + delim);
  };

  ScriptRunner.prototype.getFilename = function() {
    var ext, filename;
    ext = this.getActivePlugin().getFilenameExtension();
    filename = this.__data.filename || "EasydbScriptRunner";
    if (ext && ez5.extension(filename) !== ext) {
      filename = filename + "." + ext;
    }
    return filename;
  };

  ScriptRunner.prototype.run = function() {
    var abort, all_gids, chunk_size, items, lbl, master_dfr, plugin, status;
    CUI.setLocalStorage("script_runner.data", this.__data);
    items = [];
    items.length = this.__data.limit;
    chunk_size = this.__data.chunk_size;
    this.__download_data = [];
    lbl = new LocaLabel({
      loca_key: "script.runner.progress.getting_chunk",
      loca_key_attrs: {
        count: "..."
      }
    });
    status = new CUI.Alert({
      button_text_ok: $$("base.abort"),
      content: lbl
    });
    abort = false;
    plugin = this.getActivePlugin();
    status.open().done((function(_this) {
      return function() {
        return abort = true;
      };
    })(this));
    all_gids = [];
    master_dfr = new CUI.Deferred();
    CUI.chunkWork.call(this, {
      chunk_size: this.__data.chunk_size,
      items: items,
      call: (function(_this) {
        return function(items, offset, limit) {
          var promise, upper_limit;
          if (abort) {
            return CUI.rejectedPromise();
          }
          upper_limit = Math.min(offset + chunk_size, limit);
          lbl.setText($$("script.runner.progress.prepare_chunk|text", {
            chunk: (offset + 1) + "-" + upper_limit + "/" + limit
          }));
          promise = _this._getChunk(offset, upper_limit - offset).done(function(cos) {
            var co, i, len;
            for (i = 0, len = cos.length; i < len; i++) {
              co = cos[i];
              all_gids.push(co.getGlobalObjectId());
            }
          });
          return promise;
        };
      })(this)
    }).fail(master_dfr.reject).done((function(_this) {
      return function() {
        return CUI.chunkWork.call(_this, {
          chunk_size: _this.__data.chunk_size,
          items: all_gids,
          call: function(gids, offset, limit) {
            var best_mask_filter, dfr, key, masks, objecttypes, ref, search, upper_limit, value;
            if (abort) {
              return CUI.rejectedPromise();
            }
            upper_limit = Math.min(offset + chunk_size, limit);
            lbl.setText($$("script.runner.progress.getting_chunk|text", {
              chunk: (offset + 1) + "-" + upper_limit + "/" + limit
            }));
            dfr = new CUI.Deferred();
            best_mask_filter = true;
            if (!CUI.util.isEmpty(_this.__data.mask)) {
              masks = {};
              objecttypes = _this._caller.getLastData().objecttypes || [];
              ref = _this.__data.mask;
              for (key in ref) {
                value = ref[key];
                if (indexOf.call(objecttypes, key) >= 0) {
                  masks[key] = value;
                }
              }
              best_mask_filter = false;
              search = [
                {
                  type: "in",
                  fields: ["_global_object_id"],
                  "in": gids
                }
              ];
              if (!best_mask_filter) {
                search.push(MaskFieldSelector.getSearchFilter(masks));
              }
            }
            ez5.api.search({
              data: {
                debug: "ScriptRunnerChunk-" + offset
              },
              json_data: {
                type: "object",
                format: "long",
                offset: 0,
                limit: _this.__data.chunk_size,
                best_mask_filter: best_mask_filter,
                search: search
              }
            }).fail(dfr.reject).done(function(data) {
              data.objects.sort(function(a, b) {
                var idx_a, idx_b;
                idx_a = gids.indexOf(a._global_object_id);
                idx_b = gids.indexOf(b._global_object_id);
                return CUI.util.compareIndex(idx_a, idx_b);
              });
              return CUI.decide(plugin.run(data, offset, _this.__data.chunk_size, limit)).done(dfr.resolve).fail(dfr.reject);
            });
            return dfr.promise();
          }
        }).fail(master_dfr.reject).done(master_dfr.resolve);
      };
    })(this));
    master_dfr.always((function(_this) {
      return function() {
        return status.destroy();
      };
    })(this)).done((function(_this) {
      return function() {
        if (_this.__download_data.length > 0) {
          CUI.FileReader.save(_this.getFilename(), _this.__download_data.join(""));
        }
        delete _this.__download_data;
        return CUI.alert({
          text: $$("script.runner.alert.run_done")
        });
      };
    })(this)).fail((function(_this) {
      return function() {
        delete _this.__download_data;
        return CUI.problem({
          text: $$("script.runner.problem.run_failed")
        });
      };
    })(this));
    return master_dfr.promise();
  };

  ScriptRunner.prototype.getCaller = function() {
    return this._caller;
  };

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

  return ScriptRunner;

})(CUI.Element);

ez5.session_ready(function() {
  return ez5.ScriptRunner.plugins = new CUI.PluginRegistry({
    "class": ez5.ScriptRunner.Plugin
  });
});
// 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.ScriptRunner.Plugin = (function(superClass) {
  extend(Plugin, superClass);

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

  Plugin.prototype.initOpts = function() {
    Plugin.__super__.initOpts.call(this);
    return this.addOpts({
      scriptRunner: {
        mandatory: true,
        check: ez5.ScriptRunner
      }
    });
  };

  Plugin.prototype.name = function() {
    return this.getElementClass();
  };

  Plugin.prototype.locaKeyPrefix = function() {
    return "script.runner." + CUI.util.toDash(this.name()).replace(/-/g, ".");
  };

  Plugin.prototype.nameLocalized = function() {
    return $$(this.locaKeyPrefix() + ".plugin.name");
  };

  Plugin.prototype.description = function() {
    return $$(this.locaKeyPrefix() + ".plugin.description");
  };

  Plugin.prototype.getFields = function(data) {
    return [];
  };

  Plugin.prototype.getFilenameExtension = function() {
    return "txt";
  };

  Plugin.prototype.initRun = function(data, offset, limit, configData) {};

  Plugin.prototype.run = function(obj, offset) {};

  Plugin.prototype.getConfigData = function() {
    return this._scriptRunner.__data;
  };

  Plugin.prototype.download = function(data, delim) {
    if (delim == null) {
      delim = "\n";
    }
    return this._scriptRunner.download(data, delim);
  };

  Plugin.prototype.isAvailable = function() {
    return true;
  };

  return Plugin;

})(CUI.Plugin);
// 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.ScriptRunner.AssetMetadata = (function(superClass) {
  extend(AssetMetadata, superClass);

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

  AssetMetadata.prototype.getFields = function(data) {
    return [
      {
        form: {
          label: $$(this.locaKeyPrefix() + ".form.metadata")
        },
        type: CUI.DataTable,
        name: "metadata",
        fields: [
          {
            type: CUI.Input,
            name: "group",
            form: {
              label: $$(this.locaKeyPrefix() + ".form.table.group")
            }
          }, {
            type: CUI.Input,
            name: "name",
            form: {
              label: $$(this.locaKeyPrefix() + ".form.table.name")
            }
          }
        ]
      }, {
        form: {
          label: $$(this.locaKeyPrefix() + ".form.show_empty_rows")
        },
        type: CUI.Checkbox,
        name: "show_empty_rows"
      }
    ];
  };

  AssetMetadata.prototype.getFilenameExtension = function() {
    return "csv";
  };

  AssetMetadata.prototype.run = function(data, offset, chunk_size, limit) {
    var a, add_data, assets, c, config, dfr, eas_ids, filter, find_asset_by_id, get_regexp, i, j, k, len, len1, len2, obj, promises, ref, ref1, ref2, ro;
    if (offset === 0) {
      this.__rows = [];
      this.__columnNames = [];
    }
    assets = [];
    ref = data.objects;
    for (i = 0, len = ref.length; i < len; i++) {
      obj = ref[i];
      ro = (new ResultObject()).setData(obj);
      ref1 = ro.getAssetsForBrowser("detail");
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        a = ref1[j];
        assets.push(a);
      }
    }
    if (assets.length === 0) {
      dfr = new CUI.Deferred();
      CUI.alert({
        text: $$(this.locaKeyPrefix() + ".error.no_assets")
      }).done(dfr.reject);
      return dfr.promise();
    }
    config = this.getConfigData();
    get_regexp = function(s) {
      var regexp;
      if (s.trim() === "") {
        s = "*";
      }
      regexp = "^" + CUI.util.escapeRegExp(s.trim()).replace(/\\\*/g, ".*") + "$";
      return new RegExp(regexp);
    };
    filter = [];
    ref2 = config.metadata;
    for (k = 0, len2 = ref2.length; k < len2; k++) {
      c = ref2[k];
      if (CUI.util.isEmpty(c.group) && CUI.util.isEmpty(c.name)) {
        continue;
      }
      filter.push({
        group: get_regexp(c.group),
        name: get_regexp(c.name)
      });
    }
    if (filter.length === 0) {
      filter.push({
        group: get_regexp("*"),
        name: get_regexp("*")
      });
    }
    promises = [];
    eas_ids = (function() {
      var l, len3, results;
      results = [];
      for (l = 0, len3 = assets.length; l < len3; l++) {
        a = assets[l];
        results.push(a.getId());
      }
      return results;
    })();
    find_asset_by_id = (function(_this) {
      return function(eas_id) {
        var l, len3;
        for (l = 0, len3 = assets.length; l < len3; l++) {
          a = assets[l];
          if (a.getId() === eas_id) {
            return a;
          }
        }
        return null;
      };
    })(this);
    add_data = (function(_this) {
      return function(data) {
        var asset, col, eas_id, f, group, has_data, info, l, len3, len4, len5, m, n, ref3, ref4, row, v, values;
        for (l = 0, len3 = eas_ids.length; l < len3; l++) {
          eas_id = eas_ids[l];
          info = data[eas_id];
          if (!(info != null ? (ref3 = info.metadata) != null ? ref3.groups : void 0 : void 0)) {
            return;
          }
          asset = find_asset_by_id(eas_id);
          if (asset) {
            row = {
              _system_object_id: a.data._system_object_id,
              _objecttype: a.data._objecttype,
              _id: a.data[a.data._objecttype]._id,
              _eas_id: eas_id
            };
          } else {
            row = {};
          }
          console.debug(eas_id, info);
          has_data = false;
          ref4 = info.metadata.groups;
          for (group in ref4) {
            values = ref4[group];
            for (m = 0, len4 = filter.length; m < len4; m++) {
              f = filter[m];
              if (!f.group.exec(group)) {
                continue;
              }
              for (n = 0, len5 = values.length; n < len5; n++) {
                v = values[n];
                if (!f.name.exec(v.name)) {
                  continue;
                }
                col = group + "-" + v.name + "#print";
                CUI.util.pushOntoArray(col, _this.__columnNames);
                row[col] = v.print;
                has_data = true;
              }
            }
          }
          if (has_data || config.show_empty_rows) {
            _this.__rows.push(row);
          }
        }
      };
    })(this);
    return ez5.api.eas({
      data: {
        format: "long",
        ids: JSON.stringify(eas_ids)
      }
    }).done((function(_this) {
      return function(data) {
        var col, csv_row, l, len3, len4, len5, m, n, ref3, ref4, ref5, row;
        add_data(data);
        if (offset + chunk_size < limit) {
          return;
        }
        _this.__columnNames.sort(function(a, b) {
          return a.localeCompare(b);
        });
        _this.__columnNames.splice(0, 0, "_system_object_id", "_objecttype", "_id", "_eas_id");
        csv_row = [];
        ref3 = _this.__columnNames;
        for (l = 0, len3 = ref3.length; l < len3; l++) {
          col = ref3[l];
          csv_row.push(_this.escapeCsv(col));
        }
        _this.download(csv_row.join(","));
        ref4 = _this.__rows;
        for (m = 0, len4 = ref4.length; m < len4; m++) {
          row = ref4[m];
          csv_row = [];
          ref5 = _this.__columnNames;
          for (n = 0, len5 = ref5.length; n < len5; n++) {
            col = ref5[n];
            if (CUI.util.isEmpty(row[col])) {
              csv_row.push("");
            } else {
              csv_row.push(row[col]);
            }
          }
          _this.download(csv_row.join(","));
        }
        console.debug("rows:", _this.__rows, _this.__columnNames);
        delete _this.__rows;
        return delete _this.__columNames;
      };
    })(this));
  };

  AssetMetadata.prototype.escapeCsv = function(s) {
    s = '"' + s + '"';
    return s.replace(/"/g, '""');
  };

  return AssetMetadata;

})(ez5.ScriptRunner.Plugin);

ez5.session_ready(function() {
  return ez5.ScriptRunner.plugins.registerPlugin(ez5.ScriptRunner.AssetMetadata);
});
// 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.ScriptRunner.CustomCode = (function(superClass) {
  extend(CustomCode, superClass);

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

  CustomCode.prototype.getFields = function(data) {
    return [
      {
        form: {
          label: $$(this.locaKeyPrefix() + ".form.script"),
          hint: $$(this.locaKeyPrefix() + ".form.script|hint")
        },
        type: CUI.Input,
        placeholder: "function(obj, offset) {\n// your script\n}",
        textarea: true,
        name: "script",
        appearance: "code",
        maximize: true
      }
    ];
  };

  CustomCode.prototype.run = function(data, offset, chunk_size, limit) {
    var dfr, download, e, i, idx, len, obj, ref, ret, str;
    download = (function(_this) {
      return function(data, delim) {
        if (delim == null) {
          delim = "\n";
        }
        return _this.download(data, delim);
      };
    })(this);
    str = "(function(obj, offset) {\n\n//script\n" + this.getConfigData().script + "\n})(obj, offset+idx)";
    try {
      ref = data.objects;
      for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
        obj = ref[idx];
        ret = eval(str);
        if (ret === false) {
          return CUI.rejectedPromise();
        }
      }
    } catch (error) {
      e = error;
      dfr = new CUI.Deferred();
      CUI.problem({
        text: str + "\n\n" + e
      }).done(dfr.reject);
      return dfr.promise();
    }
    return CUI.resolvedPromise();
  };

  return CustomCode;

})(ez5.ScriptRunner.Plugin);

ez5.session_ready(function() {
  return ez5.ScriptRunner.plugins.registerPlugin(ez5.ScriptRunner.CustomCode);
});
// 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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

ez5.ScriptRunner.FieldsMigrator = (function(superClass) {
  extend(FieldsMigrator, superClass);

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

  FieldsMigrator.prototype.getFields = function() {
    var casterField, casterFields, casterOptsForm, casterPlugin, casterSelectOptions, casters, descriptionField, i, initCasterField, initCasterOptsForm, len, objecttypes, ref, setCurrentMask;
    casters = [];
    casterSelectOptions = [];
    casterFields = [];
    objecttypes = this._scriptRunner.getCaller().getLastData().objecttypes || [];
    ref = ez5.ScriptRunner.FieldsMigrator.casterPlugins.newPlugins();
    for (i = 0, len = ref.length; i < len; i++) {
      casterPlugin = ref[i];
      casters = casters.concat(casterPlugin.getCasters());
    }
    casterField = new CUI.Select({
      form: {
        label: $$("script.runner.fields.migrator.plugin.form.caster.label")
      },
      name: "caster",
      options: function() {
        return casterSelectOptions;
      },
      onDataInit: (function(_this) {
        return function(_, data) {
          return initCasterOptsForm(data);
        };
      })(this),
      onDataChanged: (function(_this) {
        return function(data) {
          initCasterOptsForm(data);
          return casterOptsForm.reload();
        };
      })(this)
    });
    casterOptsForm = new CUI.Form({
      form: {
        label: $$("script.runner.fields.migrator.plugin.form.caster_opts.label")
      },
      name: "caster_opts",
      fields: function() {
        return casterFields;
      }
    });
    descriptionField = new CUI.Output({
      text: null
    });
    initCasterField = (function(_this) {
      return function(data) {
        var castersForField, fieldFrom, fieldTo;
        fieldFrom = _this.__getFieldById(data.idFieldFrom);
        fieldTo = _this.__getFieldById(data.idFieldTo);
        castersForField = casters.filter(function(caster) {
          return caster.canCast(fieldFrom, fieldTo);
        });
        data.caster = null;
        if (castersForField.length > 0) {
          casterSelectOptions = castersForField.map(function(caster) {
            return {
              text: caster.name,
              value: caster
            };
          });
          return data.caster = castersForField[0];
        } else {
          casterSelectOptions = [
            {
              text: $$("script.runner.fields.migrator.plugin.form.caster.option.no-casters-available"),
              value: null
            }
          ];
        }
      };
    })(this);
    initCasterOptsForm = (function(_this) {
      return function(data) {
        var caster, description, key;
        caster = data.caster;
        for (key in data.caster_opts) {
          delete data.caster_opts[key];
        }
        if (caster) {
          if (caster.opt_fields.length > 0) {
            casterFields = caster.opt_fields;
          } else {
            casterFields = [
              {
                type: CUI.Output,
                text: $$("script.runner.fields.migrator.plugin.form.caster_opts.no-options-available")
              }
            ];
          }
          description = caster.description || $$("script.runner.fields.migrator.plugin.form.description.no-description-available");
          descriptionField.setText(description);
          return;
        }
        descriptionField.setText(null);
        casterFields = [
          {
            type: CUI.Output,
            text: $$("script.runner.fields.migrator.plugin.form.caster_opts.no-caster-selected")
          }
        ];
      };
    })(this);
    setCurrentMask = (function(_this) {
      return function(data) {
        var maskName, objecttype;
        data = _this.__getData();
        if (!(data != null ? data.mask : void 0)) {
          return;
        }
        objecttype = ez5.schema.CURRENT._table_by_id[data.idObjectType];
        if (data.idObjectType && objecttype) {
          maskName = data.mask[objecttype.name];
          _this.__currentMask = Mask.getMaskByMaskName(maskName, data.idObjectType);
        }
      };
    })(this);
    return [
      {
        type: ez5.ObjecttypeSelector,
        form: {
          label: $$("script.runner.fields.migrator.plugin.form.object-type.label")
        },
        name: "idObjectType",
        show_name: true,
        filter: function(objecttype) {
          var ref1;
          return ref1 = objecttype.name(), indexOf.call(objecttypes, ref1) >= 0;
        },
        onDataInit: (function(_this) {
          return function(_, data) {
            return setCurrentMask(data);
          };
        })(this),
        onDataChanged: setCurrentMask
      }, {
        type: ez5.FieldSelector,
        form: {
          label: $$("script.runner.fields.migrator.plugin.form.field-from.label")
        },
        name: "idFieldFrom",
        objecttype_data_key: "idObjectType",
        show_name: true,
        onDataChanged: (function(_this) {
          return function(data, field) {
            field.getForm().getFieldsByName("idFieldTo")[0].reload();
            initCasterField(data);
            initCasterOptsForm(data);
            casterOptsForm.reload();
            return casterField.reload();
          };
        })(this),
        filter: function(field) {
          return !field.isSystemField() && !field.isTopLevelField() && !field.insideNested() && !(field instanceof NestedTable);
        }
      }, {
        type: ez5.FieldSelector,
        form: {
          label: $$("script.runner.fields.migrator.plugin.form.field-to.label")
        },
        name: "idFieldTo",
        objecttype_data_key: "idObjectType",
        show_name: true,
        filter: (function(_this) {
          return function(fieldTo, data) {
            var canCast, fieldFrom, ref1;
            if (fieldTo.isSystemField() || fieldTo.isTopLevelField() || ((ref1 = fieldTo.getFatherField()) != null ? ref1.insideNested() : void 0) || fieldTo.id() === data.idFieldFrom) {
              return false;
            }
            fieldFrom = _this.__getFieldById(data.idFieldFrom);
            canCast = casters.some(function(caster) {
              return caster.canCast(fieldFrom, fieldTo);
            });
            return canCast;
          };
        })(this),
        onDataInit: (function(_this) {
          return function(_, data) {
            return initCasterField(data);
          };
        })(this),
        onDataChanged: (function(_this) {
          return function(data) {
            initCasterField(data);
            initCasterOptsForm(data);
            casterOptsForm.reload();
            return casterField.reload();
          };
        })(this)
      }, casterField, descriptionField, casterOptsForm
    ];
  };

  FieldsMigrator.prototype.run = function(data, offset) {
    var deferred;
    if (offset === 0) {
      deferred = new CUI.Deferred();
      CUI.confirm({
        markdown: true,
        text: $$("script.runner.fields.migrator.plugin.confirm.text")
      }).fail((function(_this) {
        return function() {
          CUI.alert({
            text: $$("script.runner.fields.migrator.plugin.confirm.cancel")
          });
          return deferred.reject();
        };
      })(this)).done((function(_this) {
        return function() {
          var caster, checkFormResponse, errorKey, formData, objecttypeName, ref;
          formData = _this.__getData();
          objecttypeName = (ref = ez5.schema.CURRENT._table_by_id[formData.idObjectType]) != null ? ref.name : void 0;
          if (!objecttypeName) {
            errorKey = "empty-objecttype";
          } else if (!formData.idFieldFrom) {
            errorKey = "empty-field-from";
          } else if (!formData.idFieldTo) {
            errorKey = "empty-field-to";
          } else if (formData.idFieldFrom === formData.idFieldTo) {
            errorKey = "field-to-from-equals";
          }
          if (errorKey) {
            CUI.alert({
              text: $$("script.runner.fields.migrator.plugin.error." + errorKey)
            });
            return deferred.reject();
          }
          caster = formData.caster;
          checkFormResponse = caster.checkForm(formData.caster_opts);
          if (!CUI.util.isTrue(checkFormResponse)) {
            CUI.alert({
              text: $$("script.runner.fields.migrator.plugin.caster.form.invalid-text", {
                message: checkFormResponse
              })
            });
            return deferred.reject();
          }
          return _this.__run(data).done(deferred.resolve).fail(deferred.reject);
        };
      })(this));
      return deferred.promise();
    } else {
      return this.__run(data);
    }
  };

  FieldsMigrator.prototype.__run = function(data) {
    var caster, chunkWork, fieldFrom, fieldTo, formData, getRootDataForField, objects, objecttypeName, ref;
    formData = this.__getData();
    objecttypeName = (ref = ez5.schema.CURRENT._table_by_id[formData.idObjectType]) != null ? ref.name : void 0;
    objects = data.objects.filter(function(object) {
      return !CUI.util.isEmpty(object[objecttypeName]);
    });
    fieldFrom = this.__getFieldById(formData.idFieldFrom);
    fieldTo = this.__getFieldById(formData.idFieldTo);
    caster = formData.caster;
    getRootDataForField = (function(_this) {
      return function(field, value) {
        var _data, nestedField;
        if (field.insideNested()) {
          _data = {};
          nestedField = field.getFatherField();
          _data[nestedField.name()] = [value];
          return getRootDataForField(nestedField, _data);
        } else {
          if (field instanceof NestedTable) {
            value[field.name() + ":group_mode"] = "append";
          }
          return value;
        }
      };
    })(this);
    chunkWork = CUI.chunkWork.call(this, {
      items: objects,
      chunk_size: 1,
      call: (function(_this) {
        return function(items) {
          var deferred, object, objectData, value;
          object = items[0];
          objectData = object[objecttypeName];
          value = objectData[fieldFrom.name()];
          if (CUI.util.isNull(value)) {
            return CUI.resolvedPromise();
          }
          deferred = new CUI.Deferred();
          caster.doCast(value, formData.caster_opts).done(function(castedValue) {
            var dataToSave, json_data;
            if (CUI.util.isNull(castedValue)) {
              return deferred.resolve();
            }
            dataToSave = {};
            dataToSave[fieldTo.name()] = castedValue;
            dataToSave = getRootDataForField(fieldTo, dataToSave);
            dataToSave["_id"] = [objectData._id];
            json_data = {
              _mask: _this.__currentMask.name(),
              _objecttype: objecttypeName
            };
            json_data[objecttypeName] = dataToSave;
            return ez5.api.db({
              api: "/" + objecttypeName,
              json_data: [json_data]
            }).done(deferred.resolve).fail(deferred.reject);
          });
          return deferred.promise();
        };
      })(this)
    });
    return chunkWork;
  };

  FieldsMigrator.prototype.__getFieldById = function(idField) {
    var fieldFound;
    fieldFound = null;
    if (!this.__currentMask || !idField || isNaN(idField)) {
      return fieldFound;
    }
    idField = parseInt(idField);
    this.__currentMask.invokeOnFields("all", true, (function(_this) {
      return function(field) {
        if (field instanceof MaskSplitter) {
          return;
        }
        if (field.id() === idField) {
          fieldFound = field;
          return false;
        }
      };
    })(this));
    return fieldFound;
  };

  FieldsMigrator.prototype.__getData = function() {
    return this._scriptRunner.getData();
  };

  FieldsMigrator.prototype.isAvailable = function() {
    return this._scriptRunner.getCaller() instanceof Search;
  };

  return FieldsMigrator;

})(ez5.ScriptRunner.Plugin);

ez5.session_ready(function() {
  ez5.ScriptRunner.plugins.registerPlugin(ez5.ScriptRunner.FieldsMigrator);
  return ez5.ScriptRunner.FieldsMigrator.casterPlugins = new CUI.PluginRegistry({
    "class": ez5.CasterPlugin
  });
});
// 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.CasterPlugin = (function(superClass) {
  extend(CasterPlugin, superClass);

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

  CasterPlugin.prototype.getCasters = function() {
    var casters;
    casters = this.__initCasters();
    return casters.map((function(_this) {
      return function(caster) {
        return _this.__buildCaster(caster);
      };
    })(this));
  };

  CasterPlugin.prototype.__buildCaster = function(casterOpts) {
    var caster, doCast;
    if (casterOpts == null) {
      casterOpts = {};
    }
    caster = CUI.Element.readOpts(casterOpts, "ez5.CasterPlugin.__buildCaster", {
      name: {
        check: String,
        mandatory: true
      },
      description: {
        check: String
      },
      canCast: {
        check: Function,
        mandatory: true
      },
      doCast: {
        check: Function,
        mandatory: true
      },
      checkForm: {
        check: Function,
        "default": function() {
          return true;
        }
      },
      opt_fields: {
        check: Array,
        "default": []
      }
    });
    doCast = caster.doCast;
    caster.doCast = (function(_this) {
      return function(value, opts) {
        if (opts == null) {
          opts = {};
        }
        value = doCast(value, opts);
        if (CUI.util.isPromise(value)) {
          return value;
        }
        return CUI.resolvedPromise(value);
      };
    })(this);
    return caster;
  };

  CasterPlugin.prototype.__canCast = function(fromInstance, toInstance, fromClass, toClass) {
    return (fromInstance != null ? fromInstance.constructor : void 0) === fromClass && (toInstance != null ? toInstance.constructor : void 0) === toClass;
  };

  CasterPlugin.prototype.__initCasters = function() {
    return CUI.util.assert(false, CUI.util.getObjectClass(this) + ".__initCasters needs to be implemented.");
  };

  return CasterPlugin;

})(CUI.Plugin);
// 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.CasterDataColumn = (function(superClass) {
  extend(CasterDataColumn, superClass);

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

  CasterDataColumn.prototype.__initCasters = function() {
    return [
      {
        name: $$("caster.plugin.data-column.name"),
        description: $$("caster.plugin.data-column.description"),
        canCast: (function(_this) {
          return function(from, to) {
            return from instanceof DataColumn && (from != null ? from.constructor : void 0) === (to != null ? to.constructor : void 0);
          };
        })(this),
        doCast: function(value) {
          return value;
        }
      }
    ];
  };

  return CasterDataColumn;

})(ez5.CasterPlugin);

ez5.session_ready(function() {
  return ez5.ScriptRunner.FieldsMigrator.casterPlugins.registerPlugin(ez5.CasterDataColumn);
});
// 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.CasterDateColumn = (function(superClass) {
  extend(CasterDateColumn, superClass);

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

  CasterDateColumn.prototype.__initCasters = function() {
    return [
      {
        name: $$("caster.plugin.date-column.date-to-text.name"),
        description: $$("caster.plugin.date-column.date-to-text.description"),
        canCast: (function(_this) {
          return function(from, to) {
            return _this.__canCast(from, to, DateColumn, TextColumn);
          };
        })(this),
        doCast: (function(_this) {
          return function(value) {
            return _this.__dateToText(value);
          };
        })(this)
      }, {
        name: $$("caster.plugin.date-column.text-to-date.name"),
        description: $$("caster.plugin.date-column.text-to-date.description"),
        canCast: (function(_this) {
          return function(from, to) {
            return _this.__canCast(from, to, TextColumn, DateColumn);
          };
        })(this),
        doCast: (function(_this) {
          return function(value) {
            return _this.__textToDate(value);
          };
        })(this)
      }
    ];
  };

  CasterDateColumn.prototype.__textToDate = function(value) {
    var formatValue;
    formatValue = CUI.DateTime.format(value, "store");
    if (CUI.util.isNull(formatValue)) {
      return null;
    }
    return {
      value: formatValue
    };
  };

  CasterDateColumn.prototype.__dateToText = function(value) {
    return CUI.DateTime.display(value.value);
  };

  return CasterDateColumn;

})(ez5.CasterPlugin);

ez5.session_ready(function() {
  return ez5.ScriptRunner.FieldsMigrator.casterPlugins.registerPlugin(ez5.CasterDateColumn);
});
// 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.CasterDateRangeColumn = (function(superClass) {
  extend(CasterDateRangeColumn, superClass);

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

  CasterDateRangeColumn.prototype.__initCasters = function() {
    var optAnyFields, optBothFields, sameOptions;
    sameOptions = [
      {
        text: $$("caster.plugin.date-range.options.select.options.from.label"),
        value: "from"
      }, {
        text: $$("caster.plugin.date-range.options.select.options.to.label"),
        value: "to"
      }
    ];
    optAnyFields = [
      {
        type: CUI.Select,
        name: "value",
        form: {
          label: $$("caster.plugin.date-range.options.select.label")
        },
        options: [
          {
            text: $$("caster.plugin.date-range.options.select.options.any.label"),
            value: "any"
          }
        ].concat(sameOptions)
      }
    ];
    optBothFields = [
      {
        type: CUI.Select,
        name: "value",
        form: {
          label: "Value"
        },
        options: [
          {
            text: $$("caster.plugin.date-range.options.select.options.both.label"),
            value: "both"
          }
        ].concat(sameOptions)
      }
    ];
    return [
      {
        name: $$("caster.plugin.date-range.date-range-to-text.name"),
        description: $$("caster.plugin.date-range.date-range-to-text.description"),
        canCast: (function(_this) {
          return function(from, to) {
            return _this.__canCast(from, to, DateRangeColumn, TextColumn);
          };
        })(this),
        doCast: (function(_this) {
          return function(value) {
            return _this.__dateRangeToText(value);
          };
        })(this)
      }, {
        name: $$("caster.plugin.date-range.text-to-date-range.name"),
        description: $$("caster.plugin.date-range.text-to-date-range.description"),
        canCast: (function(_this) {
          return function(from, to) {
            return _this.__canCast(from, to, TextColumn, DateRangeColumn);
          };
        })(this),
        doCast: (function(_this) {
          return function(value) {
            return _this.__textToDateRange(value);
          };
        })(this)
      }, {
        name: $$("caster.plugin.date-range.date-to-date-range.name"),
        description: $$("caster.plugin.date-range.date-to-date-range.description"),
        canCast: (function(_this) {
          return function(from, to) {
            return _this.__canCast(from, to, DateColumn, DateRangeColumn);
          };
        })(this),
        doCast: (function(_this) {
          return function(value, opts) {
            return _this.__dateToDateRange(value, opts);
          };
        })(this),
        checkForm: (function(_this) {
          return function(opts) {
            return _this.__checkForm(opts);
          };
        })(this),
        opt_fields: optBothFields
      }, {
        name: $$("caster.plugin.date-range.date-range-to-date.name"),
        description: $$("caster.plugin.date-range.date-range-to-date.description"),
        canCast: (function(_this) {
          return function(from, to) {
            return _this.__canCast(from, to, DateRangeColumn, DateColumn);
          };
        })(this),
        doCast: (function(_this) {
          return function(value, opts) {
            return _this.__dateRangeToDate(value, opts);
          };
        })(this),
        checkForm: (function(_this) {
          return function(opts) {
            return _this.__checkForm(opts);
          };
        })(this),
        opt_fields: optAnyFields
      }
    ];
  };

  CasterDateRangeColumn.prototype.__checkForm = function(opts) {
    var ref;
    if (opts == null) {
      opts = {};
    }
    if (!opts.value || ((ref = !opts.value) === "from" || ref === "to" || ref === "any" || ref === "both")) {
      return $$("caster.plugin.check-form.missing-configuration-message");
    }
    return true;
  };

  CasterDateRangeColumn.prototype.__dateRangeToText = function(value) {
    var from, to;
    from = CUI.DateTime.display(value.from);
    to = CUI.DateTime.display(value.to);
    if (from && to) {
      return from + " - " + to;
    } else if (from) {
      return from;
    } else {
      return to;
    }
  };

  CasterDateRangeColumn.prototype.__textToDateRange = function(value) {
    var formatValue, from, to;
    formatValue = CUI.DateTime.format(value, "store");
    if (!CUI.util.isNull(formatValue)) {
      return {
        from: formatValue,
        to: formatValue
      };
    }
    value = value.split(" - ");
    from = CUI.DateTime.format(value[0], "store");
    to = CUI.DateTime.format(value[1], "store");
    if (from && to) {
      return {
        from: from,
        to: to
      };
    } else if (from) {
      return {
        from: from
      };
    } else if (to) {
      return {
        to: to
      };
    } else {
      return null;
    }
  };

  CasterDateRangeColumn.prototype.__dateRangeToDate = function(value, opts) {
    var check, dateRangeValue;
    check = this.__checkForm(opts);
    if (!CUI.util.isTrue(check)) {
      return check;
    }
    switch (opts.value) {
      case "to":
        dateRangeValue = value.to;
        break;
      case "from":
        dateRangeValue = value.from;
        break;
      default:
        dateRangeValue = value.to || value.from;
    }
    if (CUI.util.isNull(dateRangeValue)) {
      return null;
    }
    return {
      value: dateRangeValue
    };
  };

  CasterDateRangeColumn.prototype.__dateToDateRange = function(value, opts) {
    var check, dateValue;
    check = this.__checkForm(opts);
    if (!CUI.util.isTrue(check)) {
      return check;
    }
    dateValue = value.value;
    if (CUI.util.isNull(dateValue)) {
      return null;
    }
    switch (opts.value) {
      case "to":
        return {
          to: dateValue
        };
      case "from":
        return {
          from: dateValue
        };
      default:
        return {
          from: dateValue,
          to: dateValue
        };
    }
  };

  return CasterDateRangeColumn;

})(ez5.CasterPlugin);

ez5.session_ready(function() {
  return ez5.ScriptRunner.FieldsMigrator.casterPlugins.registerPlugin(ez5.CasterDateRangeColumn);
});
// 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.CasterLinkedObject = (function(superClass) {
  extend(CasterLinkedObject, superClass);

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

  CasterLinkedObject.prototype.__initCasters = function() {
    return [
      {
        name: $$("caster.plugin.linked-object.linked-to-linked.name"),
        description: $$("caster.plugin.linked-object.linked-to-linked.description"),
        canCast: (function(_this) {
          return function(from, to) {
            return _this.__isLinkedAndSameObjecttype(from, to);
          };
        })(this),
        doCast: function(value) {
          return value;
        }
      }
    ];
  };

  CasterLinkedObject.prototype.__isLinkedAndSameObjecttype = function(from, to) {
    var fromObjecttype, toObjecttype;
    if (from instanceof LinkedObject && to instanceof LinkedObject) {
      toObjecttype = to.linkMask().table.name();
      fromObjecttype = from.linkMask().table.name();
      if (toObjecttype === fromObjecttype) {
        return true;
      }
    }
    return false;
  };

  return CasterLinkedObject;

})(ez5.CasterPlugin);

ez5.session_ready(function() {
  return ez5.ScriptRunner.FieldsMigrator.casterPlugins.registerPlugin(ez5.CasterLinkedObject);
});
// Generated by CoffeeScript 1.12.7
var BaseConfig, TypeExtensionCustomSettingsConfig,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  BaseConfig.prototype.initOpts = function() {
    BaseConfig.__super__.initOpts.call(this);
    return this.addOpts({
      name: {
        mandatory: true,
        check: String
      },
      group: {
        check: String
      },
      parameters: {
        check: "PlainObject"
      }
    });
  };

  BaseConfig.prototype.readOpts = function() {
    BaseConfig.__super__.readOpts.call(this);
    if (this._parameters) {
      this.paramCount = Object.keys(this._parameters).length;
    } else {
      this.paramCount = 0;
    }
    this.__l10n_prefix = "server";
    return this.__class = "base";
  };

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

  BaseConfig.prototype.locaKey = function(type, parent_def) {
    var key, parentKeys;
    key = this.__l10n_prefix + ".config." + type + "." + this.__class + "." + this.name();
    parentKeys = [];
    while (parent_def) {
      parentKeys.push(parent_def._parameter_name);
      parent_def = parent_def._parent_def;
    }
    if (parentKeys.length === 0) {
      return key;
    } else {
      return key + "." + parentKeys.reverse().join(".");
    }
  };

  BaseConfig.prototype.nameLocalized = function() {
    return $$(this.locaKey("name"));
  };

  BaseConfig.prototype.getHint = function() {
    var hint;
    if (ez5.loca.has(this.locaKey("name") + "|hint")) {
      hint = $$(this.locaKey("name") + "|hint");
    } else {
      hint = "";
    }
    if (hint) {
      return hint;
    }
    return null;
  };

  BaseConfig.prototype.getClassForParameter = function(def) {
    var cls;
    cls = (this.__class + "-" + (this.name()) + "-" + def.type + "-" + def._parameter_name).replace(/[\._]/g, "-");
    return cls;
  };

  BaseConfig.prototype.getFieldDefFromParm = function(pname, def, parent_def) {
    return BaseConfig.getFieldDefinitionFromParameter.apply(this, [pname, def, parent_def, this.locaKey]);
  };

  BaseConfig.getFieldDefinitionFromParameter = function(pname, def, parent_def, locaKeyFn) {
    var _def, _fields, c, d, data, eas_field, fasProduceConfigBaseConfig, field, i, j, k, l, len, len1, len2, len3, len4, len5, licenseConfigBaseConfig, lkey, loca_key, m, n, opt, options, opts, pName, panel_label, params, placeholder, plugin, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, regexp, rp, sel_opts, set_label, t, tag, tagGroup, tf, tt;
    if (!pname) {
      console.warn("BaseConfig.getFieldDefinitionFromParameter: Skipping field definition without 'name'.", def);
      return null;
    }
    def._parameter_name = pname;
    def._parent_def = parent_def;
    set_label = (function(_this) {
      return function(field) {
        var label;
        if (!CUI.util.isPlainObject(field)) {
          return field;
        }
        if (!field.form) {
          field.form = {};
        }
        if (def.label) {
          label = _this.__l10n_prefix + (".config.label." + _this.__class + "." + def.label);
        } else {
          label = locaKeyFn.apply(_this, ["parameter", parent_def]) + "." + pname + ".label";
        }
        field.form.label = $$(label);
        if (ez5.loca.has(label + "|hint")) {
          field.form.hint = $$(label + "|hint");
        }
        if (ez5.loca.has(label + "|hint_icon")) {
          field.form.hint_icon = $$(label + "|hint_icon");
        }
        return field;
      };
    })(this);
    if (!CUI.util.isEmpty(def["default"])) {
      if (def.type === "text-l10n" || def.type === "text-l10n-multiline") {
        placeholder = def["default"];
      } else {
        placeholder = def["default"] + "";
      }
    } else if (def.placeholder) {
      placeholder = $$(locaKeyFn.apply(this, ["parameter", parent_def]) + "." + pname + ".placeholder");
      if (placeholder === "-") {
        placeholder = "";
      }
      if (def.type === "text-l10n" || def.type === "text-l10n-multiline") {
        placeholder = void 0;
      }
    } else {
      placeholder = void 0;
    }
    switch (def.type) {
      case "user":
        field = {
          type: UserGroupSelector,
          undo_and_changed_support: false,
          aclWhoManager: new AclWhoManager({
            who_filter: ["user"]
          }),
          name: pname
        };
        break;
      case "license":
        licenseConfigBaseConfig = new LicenseConfigBaseConfig({
          baseConfig: this,
          pname: pname
        });
        field = licenseConfigBaseConfig.getField();
        break;
      case "json":
        if (def.plugin_type === "produce_config") {
          fasProduceConfigBaseConfig = new FASProduceConfigBaseConfig({
            baseConfig: this
          });
          field = fasProduceConfigBaseConfig.getField(pname);
        } else if (def.plugin_type === "csv_config") {
          field = CSVImporterConfigurator.getConfigButton(pname);
        } else if (def.plugin_type === "search") {
          field = SearchPopover.getBaseConfigButton(pname);
        } else if (def.plugin_type === "set-unset-tags") {
          tf = new TagSetUnset({
            ui: "base-config-manager-" + pname + "-tag-filter",
            tagForm: ez5.tagForm,
            name: pname
          });
          field = tf.getField();
        } else if (def.plugin_type !== "") {
          field = {
            type: CUI.CodeInput,
            maximize_horizontal: true,
            name: pname,
            mode: "json"
          };
        }
        break;
      case "bool":
        field = {
          type: CUI.Checkbox,
          multiline: true,
          text: $$(locaKeyFn.apply(this, ["parameter", ez5.version("6") ? parent_def : void 0]) + ("." + pname + ".checkbox")),
          name: pname
        };
        break;
      case 'secret':
        field = {
          type: CUI.Input,
          name: pname,
          ui: "base-config-manager-" + pname + "-input",
          onDataInit: function(field, data) {
            if (CUI.util.isEmpty(data[pname])) {
              field._placeholder = "";
            } else {
              field._placeholder = data[pname];
            }
            return data[pname] = "";
          }
        };
        break;
      case 'text':
      case 'string':
        if (!CUI.util.isEmpty(def.regex)) {
          regexp = def.regex;
          if (placeholder === void 0) {
            placeholder = regexp;
          }
        } else {
          regexp = null;
        }
        switch (def.plugin_type) {
          case 'date':
            field = {
              type: CUI.DateTime,
              display_type: 'long',
              name: pname,
              input_types: ['date'],
              ui: "base-config-manager-" + pname + "-datetime"
            };
            break;
          case 'tag-select':
            options = [
              {
                text: $$(locaKeyFn.apply(this, ["parameter"]) + ("." + pname + ".placeholder")),
                value: null
              }
            ];
            ref = ez5.tagForm.tagGroups;
            for (i = 0, len = ref.length; i < len; i++) {
              tagGroup = ref[i];
              options.push({
                label: tagGroup.getDisplayName()
              });
              ref1 = tagGroup.getTags();
              for (j = 0, len1 = ref1.length; j < len1; j++) {
                tag = ref1[j];
                options.push({
                  text: tag.getDisplayName(),
                  value: parseInt(tag.getId())
                });
              }
            }
            field = {
              type: CUI.Select,
              name: pname,
              options: options
            };
            break;
          default:
            if (!def.plugin_type) {
              field = {
                type: CUI.Input,
                name: pname,
                regexp: regexp,
                placeholder: placeholder,
                ui: "base-config-manager-" + pname + "-input"
              };
            }
            if (def.name === "fa-icon") {
              field.type = CUI.IconInput;
            }
            if ((ref2 = def.name) === "tag_color" || ref2 === "brand_color" || ref2 === "background_color") {
              field.type = CUI.ColorInput;
            }
        }
        break;
      case 'int':
      case 'uint64':
        switch (def.plugin_type) {
          case 'profile_mapping_select':
            opts = ez5.metadata.getMappingOpts([
              {
                text: $$('base.config.profile_mapping_select.none'),
                value: null
              }
            ], null, def.profile);
            field = {
              type: CUI.Select,
              options: opts,
              name: pname
            };
            break;
          case 'group_easydb_select':
            field = (function(_this) {
              return function() {
                var aclWhoManager, ugs, userGroupData;
                userGroupData = {};
                aclWhoManager = new AclWhoManager({
                  who_filter: ['group'],
                  filter_groups: ['easydb'],
                  filter_groups_bool: 'must',
                  onUpdate: function(data) {
                    if (!data["_" + pname]) {
                      data[pname] = void 0;
                    } else {
                      data[pname] = parseInt(data["_" + pname].group._id);
                    }
                    CUI.Events.trigger({
                      type: "editor-changed",
                      node: _this.field
                    });
                  }
                });
                field = set_label({});
                ugs = new UserGroupSelector({
                  name: "_" + pname,
                  form: field.form,
                  aclWhoManager: aclWhoManager,
                  maximize_horizontal: true,
                  data: function(data) {
                    if (CUI.util.isInteger(data[pname])) {
                      data["_" + pname] = {
                        _basetype: 'group',
                        group: {
                          _id: data[pname]
                        }
                      };
                    }
                    return data;
                  }
                });
                return ugs;
              };
            })(this);
            break;
          case 'right_preset_collection':
            sel_opts = [
              {
                text: $$('base.config.plugin_type.right_preset_collection.option.none'),
                value: null
              }
            ];
            ref3 = RightPresetManager.getByServerContext('collection');
            for (k = 0, len2 = ref3.length; k < len2; k++) {
              rp = ref3[k];
              sel_opts.push({
                value: rp.getId(),
                text: rp.getDisplayname()
              });
            }
            field = {
              type: CUI.Select,
              options: sel_opts,
              name: pname,
              ui: "base-config-manager-" + pname + "-select"
            };
            break;
          default:
            if (!def.plugin_type) {
              field = {
                type: CUI.NumberInput,
                name: pname,
                placeholder: placeholder,
                min: def.min,
                max: def.max,
                ui: "base-config-manager-" + pname + "-number-input"
              };
            }
        }
        break;
      case 'email':
        field = {
          type: CUI.EmailInput,
          name: pname,
          placeholder: placeholder,
          ui: "base-config-manager-" + pname + "-email-input"
        };
        break;
      case 'text-multiline':
        if (def.plugin_type === "json") {
          field = {
            type: CUI.CodeInput,
            maximize_horizontal: true,
            name: pname,
            mode: "json"
          };
        } else {
          field = {
            type: CUI.Input,
            textarea: true,
            maximize_horizontal: true,
            name: pname,
            placeholder: placeholder,
            ui: "base-config-manager-" + pname + "-multiline"
          };
        }
        break;
      case 'text-l10n':
        field = {
          type: CUI.MultiInput,
          control: ez5.loca.getLanguageControlAdmin(),
          name: pname,
          user_selectable: ez5.session.getPref("languages_user_selection"),
          ui: "base-config-manager-" + pname + "-multiinput"
        };
        if (placeholder) {
          if (placeholder && CUI.util.isPlainObject(placeholder)) {
            field.placeholder = placeholder;
          }
        }
        break;
      case 'text-l10n-multiline':
        field = {
          type: CUI.MultiInput,
          textarea: true,
          control: ez5.loca.getLanguageControlAdmin(),
          name: pname,
          user_selectable: ez5.session.getPref("languages_user_selection"),
          ui: "base-config-manager-" + pname + "-multiline-multiinput"
        };
        if (placeholder) {
          field.placeholder = placeholder;
        }
        break;
      case 'string-list':
      case 'string-list-sort':
        options = [];
        ref4 = def.choices;
        for (l = 0, len3 = ref4.length; l < len3; l++) {
          c = ref4[l];
          d = false;
          if (this.__class === "system" && ((ref5 = this.name()) === "languages" || ref5 === "search.suggest.autocompletion")) {
            t = ez5.loca.getLanguageLabel(c);
            lkey = locaKeyFn.apply(this, ["choice"]) + ("." + c);
            if (ez5.loca.has(lkey + "|hint")) {
              tt = {
                text: $$(lkey + "|hint")
              };
            }
            if (pname === "database" && Datamodel.getLevel() !== "commit") {
              d = true;
            }
          } else if (def.label_choice) {
            lkey = locaKeyFn.apply(this, ["choice"]) + ("." + def.label_choice + "." + c);
            t = $$(lkey);
            if (ez5.loca.has(lkey + "|hint")) {
              tt = {
                text: $$(lkey + "|hint")
              };
            }
          } else {
            t = c;
          }
          options.push({
            text: t,
            value: c,
            tooltip: tt,
            disabled: d
          });
        }
        field = {
          type: CUI.Options,
          name: pname,
          min_checked: def.minimum || 0,
          options: options,
          ui: "base-config-manager-" + pname + "-options"
        };
        if (def.type === 'string-list-sort') {
          field.sortable = true;
        } else {
          field.horizontal = true;
        }
        break;
      case "location-select":
        field = {
          type: LocationSelector,
          default_value: this.data[pname],
          name: pname,
          ui: "base-config-manager-" + pname + "-select"
        };
        break;
      case "select":
        options = [];
        ref6 = def.options;
        for (m = 0, len4 = ref6.length; m < len4; m++) {
          c = ref6[m];
          if (def.options_loca_off) {
            opt = {};
            if (c === "---") {
              opt.divider = true;
            }
          } else {
            loca_key = (def.options_loca_key_prefix || locaKeyFn.apply(this, ["option"]) + ("." + pname)) + ("." + c);
            opt = LocaLabel.getStandardOpts(loca_key);
            if (CUI.isEmptyObject(opt)) {
              opt.text = $$(loca_key);
            }
          }
          opt.value = c;
          options.push(opt);
        }
        field = {
          type: CUI.Select,
          name: pname,
          data: function(data) {
            if (CUI.util.isEmpty(data[pname])) {
              data[pname] = def["default"];
            }
            return data;
          },
          options: options,
          ui: "base-config-manager-" + pname + "-select"
        };
        break;
      case "file":
        eas_field = new EASField({
          name: pname,
          "class": this.getClassForParameter(def)
        });
        field = {
          ui: "base-config-manager-" + pname + "-data-field-proxy",
          type: CUI.DataFieldProxy,
          name: pname,
          element: (function(_this) {
            return function(df) {
              return eas_field.renderEditorInput(df.getData(), def["default"]);
            };
          })(this)
        };
        break;
      case "form":
        params = [];
        ref7 = def.parameters || {};
        for (pName in ref7) {
          _def = ref7[pName];
          _def.name = pName;
          params.push(_def);
        }
        params.sort(this.paramsSort);
        _fields = (function() {
          var len5, n, results;
          results = [];
          for (n = 0, len5 = params.length; n < len5; n++) {
            _def = params[n];
            results.push(this.getFieldDefFromParm(_def.name, _def, def));
          }
          return results;
        }).call(this);
        _fields = _fields.filter(Boolean);
        if (def.plugin_type === "panel") {
          if (def.label) {
            panel_label = $$(this.__l10n_prefix + (".config.label." + this.__class + "." + def.label));
          } else {
            panel_label = $$(locaKeyFn.apply(this, ["parameter", parent_def]) + "." + pname + ".label");
          }
          field = {
            type: FormPanel,
            name: pname,
            panel_label: panel_label,
            closed: true,
            fields: _fields
          };
        } else {
          field = {
            type: CUI.Form,
            name: pname,
            fields: _fields
          };
        }
        break;
      case "table":
        _fields = (function() {
          var len5, n, ref8, results;
          ref8 = def.fields || [];
          results = [];
          for (n = 0, len5 = ref8.length; n < len5; n++) {
            _def = ref8[n];
            results.push(BaseConfig.getFieldDefinitionFromParameter.apply(this, [_def.name, _def, def, locaKeyFn]));
          }
          return results;
        }).call(this);
        _fields = _fields.filter(Boolean);
        field = {
          ui: "base-config-manager-" + pname + "-data-form",
          type: CUI.DataForm,
          has_add_button: _fields.length > 1,
          rowMove: true,
          name: pname,
          fields: _fields,
          maximize_horizontal: true
        };
        break;
      case "tag-select":
        data = {
          _tags: []
        };
        field = {
          ui: "base-config-manager-" + pname + "-data-field-proxy",
          type: CUI.DataFieldProxy,
          name: pname,
          onDataChanged: (function(_this) {
            return function(df_data) {
              var len5, n, ref8, results;
              df_data[pname].splice(0);
              ref8 = data._tags;
              results = [];
              for (n = 0, len5 = ref8.length; n < len5; n++) {
                tag = ref8[n];
                results.push(df_data[pname].push(tag._id));
              }
              return results;
            };
          })(this),
          element: (function(_this) {
            return function(df) {
              var len5, n, ref8, tag_id;
              data._tags.splice(0);
              if (!df.getData()[pname]) {
                df.getData()[pname] = [];
              }
              ref8 = df.getData()[pname];
              for (n = 0, len5 = ref8.length; n < len5; n++) {
                tag_id = ref8[n];
                data._tags.push({
                  _id: tag_id
                });
              }
              return (new TagsFieldForBaseConfig({
                name: "_tags"
              })).render(data);
            };
          })(this)
        };
        break;
      case "tagfilter-select":
        tf = new TagFilter({
          ui: "base-config-manager-" + pname + "-tag-filter",
          tagForm: ez5.tagForm,
          name: pname
        });
        field = tf.getField();
        break;
      default:
        console.error("BaseConfig.getForm: Unknown config type " + def.type, def, this.opts);
    }
    if (!field && def.plugin_type) {
      ref8 = BaseConfig.__plugins;
      for (n = 0, len5 = ref8.length; n < len5; n++) {
        plugin = ref8[n];
        field = plugin.getFieldDefFromParm(this, pname, def, parent_def);
        if (field) {
          break;
        }
      }
      if (!field) {
        console.error("Unknown BaseConfig Plugin-Type: " + def.plugin_type, def);
        field = {
          type: CUI.Output,
          placeholder: $$("base.config.unknown_plugin_type", {
            type: def.plugin_type
          })
        };
      }
    }
    return set_label(field);
  };

  BaseConfig.prototype.getField = function(data) {
    var field;
    this.initData(data);
    field = {
      type: CUI.Form,
      fields: this.getFields(),
      data: this.data
    };
    return this.field = CUI.DataField["new"](field);
  };

  BaseConfig.prototype.paramsSort = function(a, b) {
    var a_pos, b_pos;
    if (a.hasOwnProperty("position")) {
      a_pos = a.position;
    } else {
      a_pos = 99;
    }
    if (b.hasOwnProperty("position")) {
      b_pos = b.position;
    } else {
      b_pos = 99;
    }
    return CUI.util.compareIndex(a_pos, b_pos);
  };

  BaseConfig.prototype.getFields = function() {
    var _field, def, fields, i, len, params, pname, ref;
    fields = [];
    params = [];
    ref = this._parameters;
    for (pname in ref) {
      def = ref[pname];
      def.__name = pname;
      params.push(def);
    }
    params.sort(this.paramsSort);
    for (i = 0, len = params.length; i < len; i++) {
      def = params[i];
      pname = def.__name;
      CUI.util.assert(pname !== "name", "BaseConfig.getForm", "Parameter name of a config option cannot be \"name\" as it collides when saving.", {
        config: this.opts
      });
      _field = this.getFieldDefFromParm(pname, def);
      if (_field) {
        fields.push(_field);
      }
    }
    return fields;
  };

  BaseConfig.prototype.initData = function(data) {
    var _d, _p, def, get_json, pname, ref, ref1, ref2, ref3, ref4, ref5;
    this.data = data[this.name()] || {};
    get_json = (function(_this) {
      return function(data, key, def, level) {
        var ex, field, i, j, len, len1, ref, ref1, row;
        if (level == null) {
          level = 0;
        }
        if (!data.hasOwnProperty(key)) {
          return;
        }
        if (def.plugin_type === "produce_config") {
          data[key] = FASProduceConfigBaseConfig.initData(data[key], _this);
          return;
        }
        if (def.store_as_json) {
          try {
            data[key] = JSON.parse(data[key]);
            if (CUI.util.isEmpty(data[key])) {
              data[key] = {};
            }
          } catch (error) {
            ex = error;
            console.warn("BaseConfig, invalid json received in data", data, _this.name());
            data[key] = {};
          }
        }
        if (def.type === "tagfilter-select" && CUI.util.isString(data[key])) {
          data[key] = JSON.parse(data[key]);
        }
        if (def.type === "table") {
          ref = def.fields || [];
          for (i = 0, len = ref.length; i < len; i++) {
            field = ref[i];
            if (!CUI.util.isArray(data[key])) {
              continue;
            }
            ref1 = data[key];
            for (j = 0, len1 = ref1.length; j < len1; j++) {
              row = ref1[j];
              get_json(row, field.name, field, level + 1);
            }
          }
        }
      };
    })(this);
    ref = this._parameters;
    for (pname in ref) {
      def = ref[pname];
      if (ez5.version("6")) {
        if (def.type === "form") {
          ref1 = def.parameters;
          for (_p in ref1) {
            _d = ref1[_p];
            if (((ref2 = this.data[pname][_p + ":info"]) != null ? ref2.is_default : void 0) && ((ref3 = _d.type) === "text" || ref3 === "string" || ref3 === "int" || ref3 === "text-multiline")) {
              this.data[pname][_p] = null;
            }
          }
        } else if (((ref4 = this.data[pname + ":info"]) != null ? ref4.is_default : void 0) && ((ref5 = def.type) === "text" || ref5 === "text-multiline" || ref5 === "string" || ref5 === "int" || ref5 === "text-l10n-multiline" || ref5 === "text-l10n")) {
          delete this.data[pname];
          continue;
        }
      }
      get_json(this.data, pname, def);
    }
    return this.data;
  };

  BaseConfig.prototype.validateData = function(errors) {
    var def, pname, ref;
    if (errors == null) {
      errors = [];
    }
    ref = this._parameters;
    for (pname in ref) {
      def = ref[pname];
      if (def.plugin_type === "produce_config") {
        FASProduceConfigBaseConfig.validateData(this.data[pname], errors);
        return;
      }
    }
  };

  BaseConfig.prototype.getSaveData = function(save_data, forDownload) {
    var clean_info, def, pname, ref, ref1, ref2, saveData, saveData2, setNullInEmptyObjects, set_json;
    if (save_data == null) {
      save_data = {};
    }
    if (forDownload == null) {
      forDownload = false;
    }
    saveData2 = CUI.util.copyObject(this.data, true);
    clean_info = (function(_this) {
      return function(data, pname, def) {
        var _d, _def, _pname, i, j, len, len1, ref, ref1, ref2, table_field_def;
        if (data[pname + ":info"] != null) {
          delete data[pname + ":info"];
        }
        if (def.type === "form") {
          ref = def.parameters || {};
          for (_pname in ref) {
            _def = ref[_pname];
            clean_info(data[pname], _pname, _def);
          }
        } else if (def.type === "table") {
          ref1 = data[pname] || [];
          for (i = 0, len = ref1.length; i < len; i++) {
            _d = ref1[i];
            ref2 = def.fields || [];
            for (j = 0, len1 = ref2.length; j < len1; j++) {
              table_field_def = ref2[j];
              clean_info(_d, table_field_def.name, table_field_def);
            }
          }
        }
      };
    })(this);
    save_data[this.name()] = saveData = {};
    ref = this._parameters;
    for (pname in ref) {
      def = ref[pname];
      saveData[pname] = saveData2[pname];
      if (ez5.version("6") && ((ref1 = def.type) === "form" || ref1 === "table")) {
        clean_info(saveData, pname, def);
      }
      if (!ez5.version("6") && def["default"] && (def.type === "text" || def.type === "string") && CUI.util.isEmpty(saveData[pname])) {
        saveData[pname] = def["default"];
      }
      if (forDownload && saveData2[pname + ":info"]) {
        saveData[pname + ":info"] = saveData2[pname + ":info"];
      }
    }
    setNullInEmptyObjects = function(object, key) {
      var _object, i, len, ref2;
      if (CUI.util.isUndef(key)) {
        for (key in object) {
          setNullInEmptyObjects(object, key);
        }
        return;
      }
      if (CUI.util.isPlainObject(object[key])) {
        if (CUI.util.isEmptyObject(object[key])) {
          object[key] = null;
          return;
        }
        setNullInEmptyObjects(object[key]);
        return;
      }
      if (CUI.util.isArray(object[key])) {
        ref2 = object[key];
        for (i = 0, len = ref2.length; i < len; i++) {
          _object = ref2[i];
          setNullInEmptyObjects(_object);
        }
        return;
      }
    };
    setNullInEmptyObjects(saveData);
    set_json = (function(_this) {
      return function(data, key, def, level) {
        var field, i, j, len, len1, ref2, ref3, row;
        if (level == null) {
          level = 0;
        }
        if (!data.hasOwnProperty(key) || data[key] === null) {
          return;
        }
        if (def.plugin_type === "produce_config") {
          data[key] = FASProduceConfigBaseConfig.getSaveData(data[key], forDownload);
          return;
        }
        if (def.type === "license") {
          if (CUI.util.isString(data[key])) {
            data[key] = JSON.parse(data[key]);
          } else {
            data[key] = CUI.util.copyObject(data[key], true);
          }
        }
        if (def.type === "table") {
          ref2 = def.fields || [];
          for (i = 0, len = ref2.length; i < len; i++) {
            field = ref2[i];
            if (!CUI.util.isArray(data[key])) {
              continue;
            }
            ref3 = data[key];
            for (j = 0, len1 = ref3.length; j < len1; j++) {
              row = ref3[j];
              set_json(row, field.name, field, level + 1);
            }
          }
        }
        if (def.store_as_json) {
          data[key] = JSON.stringify(data[key]);
        }
      };
    })(this);
    ref2 = this._parameters;
    for (pname in ref2) {
      def = ref2[pname];
      set_json(saveData, pname, def);
    }
    return save_data;
  };

  BaseConfig.initialize = function(_opts) {
    var bc, config, content, field, group, i, idx, initializeData, j, k, l, len, len1, len2, len3, onDataChanged, opts, plugin_row, prefix, prefixGroup, ref, ref1, ref2, ref3, row, sort, text;
    opts = CUI.Element.readOpts(_opts, "new BaseConfig", {
      config: {
        mandatory: true,
        check: "Array"
      },
      group_order: {
        check: "Array",
        "default": []
      },
      BaseConfigClass: {
        mandatory: true,
        check: Function
      },
      data: {
        mandatory: true,
        check: "PlainObject"
      },
      l10n_prefix: {
        manatory: true,
        check: String
      },
      show_introduction: {
        check: Boolean,
        "default": true
      }
    });
    onDataChanged = (function(_this) {
      return function(data, dataField, event) {
        var i, len, plugin, ref;
        ref = BaseConfig.__plugins;
        for (i = 0, len = ref.length; i < len; i++) {
          plugin = ref[i];
          plugin.onDataChanged(data, dataField, event);
        }
      };
    })(this);
    initializeData = {
      baseConfigs: [],
      plugin_rows: []
    };
    ref = opts.config;
    for (i = 0, len = ref.length; i < len; i++) {
      config = ref[i];
      if (!config.name) {
        console.warn("BaseConfig.initialize: Skipping config entry without 'name'.", config);
        continue;
      }
      bc = new opts.BaseConfigClass(config);
      initializeData.baseConfigs.push(bc);
      group = bc.getGroup() || "other";
      plugin_row = null;
      ref1 = initializeData.plugin_rows;
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        row = ref1[j];
        if (row.name === group) {
          plugin_row = row;
          break;
        }
      }
      if (ez5.version("6")) {
        prefixGroup = group;
        if (!group.startsWith("plugin_") && config.plugin) {
          prefixGroup = "plugin_" + config.plugin;
        }
        prefix = opts.l10n_prefix + "." + bc.getBaseConfigType() + "." + prefixGroup + ".";
        sort = opts.group_order.indexOf(group);
      } else {
        prefix = opts.l10n_prefix + "." + bc.getBaseConfigType() + "." + group + ".";
        sort = void 0;
      }
      if (!plugin_row) {
        plugin_row = {
          __intro: prefix + "introduction",
          __fields: [],
          __baseConfigs: [],
          name: group,
          plugin: config.plugin,
          text: $$(prefix + "title"),
          sort: sort
        };
        initializeData.plugin_rows.push(plugin_row);
      }
      plugin_row.__fields.push(bc.getField(opts.data));
      plugin_row.__baseConfigs.push(bc);
    }
    ref2 = initializeData.plugin_rows;
    for (k = 0, len2 = ref2.length; k < len2; k++) {
      plugin_row = ref2[k];
      content = [];
      text = "";
      if (opts.show_introduction) {
        if (plugin_row.plugin) {
          text = plugin_row.plugin;
          content = [
            new CUI.Label({
              text: plugin_row.text,
              appearance: "secondary"
            }), new CUI.MultilineLabel({
              markdown: true,
              text: $$(plugin_row.__intro)
            })
          ];
        } else {
          text = plugin_row.text;
          content = [
            new CUI.MultilineLabel({
              markdown: true,
              text: $$(plugin_row.__intro)
            })
          ];
        }
        plugin_row.content = [
          new CUI.Block({
            text: text,
            padded: false,
            appearance: "wide",
            content: content
          })
        ];
      } else {
        plugin_row.content = [];
      }
      ref3 = plugin_row.__fields;
      for (idx = l = 0, len3 = ref3.length; l < len3; idx = ++l) {
        field = ref3[idx];
        CUI.Events.listen({
          type: "data-changed",
          node: field.DOM,
          call: (function(_this) {
            return function(ev, info) {
              return onDataChanged(info.element.getData(), info.element, ev);
            };
          })(this)
        });
        field.setBlockLevelOffset(1);
        plugin_row.content.push(new CUI.Block({
          level: 2,
          padded: false,
          description: plugin_row.__baseConfigs[idx].getHint(),
          appearance: "wide",
          text: plugin_row.__baseConfigs[idx].nameLocalized(),
          content: field.start()
        }));
      }
      delete plugin_row.__intro;
      delete plugin_row.__fields;
    }
    return initializeData;
  };

  BaseConfig.__plugins = [];

  BaseConfig.registerPlugin = function(plugin) {
    CUI.util.assert(plugin instanceof BaseConfigPlugin, "BaseConfig.registerPlugin", "Plugin needs to be instanceof BaseConfigPlugin.", {
      plugin: plugin
    });
    CUI.util.assert(indexOf.call(this.__plugins, plugin) < 0, "BaseConfig.registerPlugin", "Plugin can only be registered once.", {
      plugin: plugin
    });
    this.__plugins.push(plugin);
    return plugin;
  };

  return BaseConfig;

})(CUI.Element);

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

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

  TypeExtensionCustomSettingsConfig.prototype.getFieldsWithData = function(data) {
    var field, fields, i, len;
    fields = this.getFields();
    for (i = 0, len = fields.length; i < len; i++) {
      field = fields[i];
      field.data = data;
      field.ui = "type-extension-custom-settings-" + field.name;
    }
    return fields;
  };

  TypeExtensionCustomSettingsConfig.prototype.readOpts = function() {
    TypeExtensionCustomSettingsConfig.__super__.readOpts.call(this);
    return this.__l10n_prefix = "type.extension.custom.settings";
  };

  return TypeExtensionCustomSettingsConfig;

})(BaseConfig);
// Generated by CoffeeScript 1.12.7
var BaseConfigItem,
  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;

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

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

  BaseConfigItem.prototype.initOpts = function() {
    BaseConfigItem.__super__.initOpts.call(this);
    return this.addOpts({
      container: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isElement(v);
        }
      },
      row: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isPlainObject(v);
        }
      }
    });
  };

  BaseConfigItem.prototype.renderContent = function() {
    return this._row.text;
  };

  BaseConfigItem.prototype.check_deselect = function(ev, new_node) {
    if (new_node === this) {
      return CUI.rejectedPromise();
    } else {
      return CUI.resolvedPromise();
    }
  };

  BaseConfigItem.prototype.select = function(ev) {
    return BaseConfigItem.__super__.select.call(this, ev).done((function(_this) {
      return function() {
        return CUI.dom.replace(_this._container, new CUI.SimplePane({
          "class": "cui-pane--window",
          title: $$("base.config.manager.pane.center.title"),
          content: _this._row.content
        }));
      };
    })(this));
  };

  return BaseConfigItem;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var PluginBaseConfigItem,
  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;

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

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

  PluginBaseConfigItem.prototype.renderContent = function() {
    return new CUI.Label({
      text: this._row.name
    });
  };

  return PluginBaseConfigItem;

})(BaseConfigItem);
// Generated by CoffeeScript 1.12.7
var SystemBaseConfig,
  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;

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

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

  SystemBaseConfig.prototype.initOpts = function() {
    SystemBaseConfig.__super__.initOpts.call(this);
    return this.addOpts({
      unauthenticated_visible: {
        check: Boolean
      },
      require_system_right: {
        check: String
      },
      plugin: {
        check: String
      }
    });
  };

  SystemBaseConfig.prototype.readOpts = function() {
    SystemBaseConfig.__super__.readOpts.call(this);
    return this.__class = "system";
  };

  SystemBaseConfig.prototype.getBaseConfigType = function() {
    return this.__class;
  };

  SystemBaseConfig.prototype.getGroup = function() {
    return this._group;
  };

  return SystemBaseConfig;

})(BaseConfig);
// Generated by CoffeeScript 1.12.7
var PluginBaseConfig,
  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;

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

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

  PluginBaseConfig.prototype.getPluginName = function() {
    return this._plugin;
  };

  PluginBaseConfig.prototype.getGroup = function() {
    return this.getPluginName();
  };

  return PluginBaseConfig;

})(SystemBaseConfig);
// Generated by CoffeeScript 1.12.7
var BaseConfigPlugin,
  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;

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

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

  BaseConfigPlugin.prototype.getFieldDefFromParm = function(baseConfig, pname, def, parent_def) {};

  BaseConfigPlugin.prototype.onDataChanged = function(data, dataField, event) {};

  return BaseConfigPlugin;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var FASProduceConfigBaseConfig,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  FASProduceConfigBaseConfig.prototype.initOpts = function() {
    FASProduceConfigBaseConfig.__super__.initOpts.call(this);
    return this.addOpts({
      baseConfig: {
        check: BaseConfig,
        mandatory: true
      }
    });
  };

  FASProduceConfigBaseConfig.prototype.readOpts = function() {
    FASProduceConfigBaseConfig.__super__.readOpts.call(this);
    this.__prepareExtensionsByClass();
    return this;
  };

  FASProduceConfigBaseConfig.initData = function(data, baseConfig) {
    var _, classData, cls, i, len, ref, ref1, ref2, version;
    if (CUI.util.isEmpty(data) || !CUI.util.isPlainObject(data)) {
      data = {
        classes: {}
      };
    }
    FASProduceConfigBaseConfig.__normalizeUserData(data);
    for (cls in ez5.session.data.config.eas) {
      if (cls.startsWith("_") || cls === "unknown") {
        continue;
      }
      if (data.classes[cls]) {
        continue;
      }
      data.classes[cls] = {
        versions: []
      };
    }
    ref = data.classes;
    for (_ in ref) {
      classData = ref[_];
      ref1 = classData.versions;
      for (i = 0, len = ref1.length; i < len; i++) {
        version = ref1[i];
        if (!version.sourceversion) {
          version.sourceversion = "";
        }
        if (version.name === "original") {
          version._is_original = true;
          continue;
        }
      }
    }
    if ((ref2 = baseConfig.data["value:info"]) != null ? ref2.is_default : void 0) {
      data.use_default_settings = true;
    }
    return data;
  };

  FASProduceConfigBaseConfig.getSaveData = function(data, forDownload) {
    var saveData;
    if (data == null) {
      data = {};
    }
    if (data.use_default_settings && !forDownload) {
      return null;
    }
    saveData = data;
    return saveData;
  };

  FASProduceConfigBaseConfig.validateData = function(data, errors) {
    var classData, cls, customMetadataValue, custom_metadata_recipes, i, j, k, len, len1, len2, ref, ref1, ref2, ref3, ref4, ref5, ref6, version;
    if (errors == null) {
      errors = [];
    }
    custom_metadata_recipes = ((ref = ez5.session.data.config.eas._metadata) != null ? ref.recipes.map((function(_this) {
      return function(recipe) {
        return recipe.RecipeName || recipe.recipe_name;
      };
    })(this)) : void 0) || [];
    if (!CUI.util.isEmpty(data.custommetadata)) {
      ref1 = data.custommetadata;
      for (i = 0, len = ref1.length; i < len; i++) {
        customMetadataValue = ref1[i];
        if (ref2 = customMetadataValue.recipename, indexOf.call(custom_metadata_recipes, ref2) >= 0) {
          continue;
        } else {
          errors.push($$("fylr.produce.config.form.custom_metadata.recipe_not_found", {
            recipename: customMetadataValue.recipename
          }));
        }
      }
    }
    ref3 = data.classes;
    for (cls in ref3) {
      classData = ref3[cls];
      ref4 = classData.versions;
      for (j = 0, len1 = ref4.length; j < len1; j++) {
        version = ref4[j];
        if (CUI.util.isEmpty(version.custommetadata)) {
          continue;
        }
        ref5 = version.custommetadata;
        for (k = 0, len2 = ref5.length; k < len2; k++) {
          customMetadataValue = ref5[k];
          if (ref6 = customMetadataValue.recipename, indexOf.call(custom_metadata_recipes, ref6) >= 0) {
            continue;
          } else {
            errors.push($$("fylr.produce.config.form.rendition.custom_metadata.recipe_not_found", {
              recipename: customMetadataValue.recipename,
              rendition: version.name,
              "class": cls
            }));
          }
        }
      }
    }
  };

  FASProduceConfigBaseConfig.prototype.getField = function(fieldName) {
    var fields, form, setDisableStatus;
    setDisableStatus = function(data, field) {
      var i, len, ref;
      data = form.getData();
      ref = form.getFields();
      for (i = 0, len = ref.length; i < len; i++) {
        field = ref[i];
        if (field.getName() === "use_default_settings") {
          continue;
        }
        if (data.use_default_settings) {
          field.disable();
        } else {
          field.enable();
        }
      }
    };
    fields = [
      {
        type: CUI.Checkbox,
        name: "use_default_settings",
        text: $$("fylr.produce.config.form.use_default_settings")
      }, {
        type: CUI.Checkbox,
        name: "uploadallowunknown",
        text: $$("fylr.produce.config.form.uploadallowunknown")
      }, {
        type: CUI.Input,
        name: "uploadmaxfilesize",
        form: {
          label: $$("fylr.produce.config.form.uploadmaxfilesize")
        }
      }, this.__getCustomMetadataField(), this.__getRenditionsTable()
    ];
    form = new CUI.Form({
      name: fieldName,
      onDataChanged: setDisableStatus,
      onDataInit: function(field, data) {
        return setDisableStatus(data, field);
      },
      fields: fields
    });
    return form;
  };

  FASProduceConfigBaseConfig.prototype.__getRenditionsTable = function() {
    var field;
    field = {
      type: CUI.DataFieldProxy,
      name: "classes",
      maximize_horizontal: true,
      element: (function(_this) {
        return function(field) {
          var cls, data, panel, tab, tabs;
          data = field.getData();
          if (!data.classes) {
            data.classes = {};
          }
          tabs = [];
          for (cls in _this.__recipesByClass) {
            if (cls.startsWith("_")) {
              continue;
            }
            if (!data.classes[cls]) {
              data.classes[cls] = {};
            }
            tabs.push(_this.__getClassTab(cls, data.classes[cls]));
          }
          tab = new CUI.Tabs({
            tabs: tabs,
            maximize_horizontal: true,
            maximize_vertical: false
          });
          panel = new CUI.Panel({
            text: "Renditions",
            closed: true,
            content: tab,
            radio: "renditions",
            save_state: "baseconfig_fileworker_renditions"
          });
          return panel;
        };
      })(this)
    };
    return field;
  };

  FASProduceConfigBaseConfig.prototype.__getClassTab = function(cls, classData) {
    var tab;
    tab = new CUI.Tab({
      name: cls,
      text: $$("fylr.produce.config.form.class.title." + cls),
      content: (function(_this) {
        return function() {
          var editButton, form;
          editButton = new LocaButton({
            icon: "edit",
            group: "edit",
            disabled: true,
            onClick: function(ev, btn) {
              var field, i, len, ref, results;
              ref = form.getFieldsByName("versions")[0].listView.getSelectedRows()[0].getFields();
              results = [];
              for (i = 0, len = ref.length; i < len; i++) {
                field = ref[i];
                if (field instanceof CUI.FormModal) {
                  field.__openPopover();
                  break;
                } else {
                  results.push(void 0);
                }
              }
              return results;
            }
          });
          form = new CUI.Form({
            data: classData,
            fields: [
              {
                type: CUI.Options,
                name: "uploadenabledextensions",
                form: {
                  label: $$("fylr.produce.config.form.class.extensions")
                },
                maximize_horizontal: true,
                horizontal: true,
                onDataChanged: function() {
                  form.getFieldsByName("versions")[0].reload();
                },
                options: function() {
                  var extension, i, len, options, ref;
                  options = [];
                  ref = _this.__extensionsByClass[cls] || [];
                  for (i = 0, len = ref.length; i < len; i++) {
                    extension = ref[i];
                    options.push({
                      content: new CUI.Label({
                        "class": "ez5-tag",
                        text: extension.toUpperCase()
                      }),
                      value: extension
                    });
                  }
                  return options;
                }
              }, {
                type: CUI.Input,
                name: "uploadmaxfilesize",
                form: {
                  label: $$("fylr.produce.config.form.class.uploadmaxfilesize")
                },
                maximize_horizontal: true
              }, {
                type: CUI.DataTable,
                "class": "ez5-version-produce-table",
                name: "versions",
                rowMove: true,
                buttons: [editButton],
                append_buttons: true,
                maximize_horizontal: true,
                onBeforeRowRemove: function(data, ev) {
                  if (_this.__creatingNewRow) {
                    return true;
                  }
                  return CUI.confirm({
                    text: $$("fylr.produce.config.form.version.delete.confirm", {
                      name: data.name
                    }),
                    markdown: true
                  });
                },
                onRowSelect: function(ev, row) {
                  return editButton.enable();
                },
                onRowDeselect: function(ev, row) {
                  return editButton.disable();
                },
                onNewNodeAdd: function(new_node) {
                  var field, i, len, ref;
                  ref = new_node.getFields();
                  for (i = 0, len = ref.length; i < len; i++) {
                    field = ref[i];
                    if (field instanceof CUI.FormModal) {
                      field.__openPopover();
                      break;
                    }
                  }
                  return _this.__creatingNewRow = new_node;
                },
                fields: [
                  {
                    type: CUI.OutputContent,
                    name: "extensions",
                    form: {
                      label: $$("fylr.produce.config.form.version.extensions"),
                      column: "maximize"
                    },
                    maximize_horizontal: true,
                    getValue: function(extensions) {
                      var div, extension, i, len;
                      if (CUI.util.isArray(extensions) && extensions.length > 0) {
                        div = CUI.dom.element("DIV", {
                          "class": "ez5-tag-holder"
                        });
                        for (i = 0, len = extensions.length; i < len; i++) {
                          extension = extensions[i];
                          div.appendChild(new CUI.Label({
                            "class": "ez5-tag",
                            text: extension.toUpperCase()
                          }).DOM);
                        }
                        return div;
                      }
                      return null;
                    }
                  }, {
                    type: CUI.Output,
                    name: "displayname",
                    form: {
                      label: $$("fylr.produce.config.form.settings.displayname")
                    },
                    getValue: function(_, data) {
                      return ez5.loca.getBestFrontendValue(data.displayname);
                    }
                  }, {
                    type: CUI.Output,
                    name: "name",
                    form: {
                      label: $$("fylr.produce.config.form.version.name")
                    }
                  }, {
                    type: CUI.OutputContent,
                    form: {
                      label: "Output"
                    },
                    name: "recipename",
                    getValue: function(value, field) {
                      return new CUI.Label({
                        "class": "ez5-tag",
                        text: _this.__getOutputExtensionForRendition(field.getData()).toUpperCase()
                      });
                    }
                  }, {
                    type: CUI.OutputContent,
                    name: "standard",
                    form: {
                      rotate_90: true,
                      label: $$("fylr.produce.config.form.settings.standard")
                    },
                    getValue: function(value) {
                      return new CUI.Icon({
                        icon: value ? "fa-check" : "fa-minus"
                      });
                    }
                  }, {
                    type: CUI.OutputContent,
                    name: "rightsmanagement",
                    form: {
                      rotate_90: true,
                      label: $$("fylr.produce.config.form.settings.rightsmanagement")
                    },
                    getValue: function(value) {
                      return new CUI.Icon({
                        icon: value ? "fa-check" : "fa-minus"
                      });
                    }
                  }, {
                    type: CUI.OutputContent,
                    name: "watermark",
                    form: {
                      rotate_90: true,
                      label: $$("fylr.produce.config.form.settings.watermark")
                    },
                    getValue: function(value) {
                      return new CUI.Icon({
                        icon: value ? "fa-check" : "fa-minus"
                      });
                    }
                  }, {
                    type: CUI.FormModal,
                    modal: {
                      pane: {
                        header_left: new LocaLabel({
                          loca_key: "fylr.produce.config.form.version.configuration.label"
                        }),
                        padded: true
                      },
                      "class": "ez5-acl-right-manager-popover",
                      size: "xl",
                      cancel: true,
                      onCancel: function(ev, modal, has_changes) {
                        var confirmPromise;
                        if (_this.__creatingNewRow) {
                          confirmPromise = CUI.confirm({
                            text: $$("acl.right.manager.modal.confirm_cancel")
                          });
                          confirmPromise.done(function() {
                            _this.__creatingNewRow.remove();
                            delete _this.__creatingNewRow;
                            return classData.versions.pop();
                          });
                          return confirmPromise;
                        }
                        if (has_changes) {
                          return CUI.confirm({
                            text: $$("acl.right.manager.modal.confirm_cancel")
                          });
                        }
                      },
                      apply_button: {
                        loca_key: "acl.right.manager.modal.button_apply",
                        primary: true,
                        onClick: function(ev, btn, field) {
                          delete _this.__creatingNewRow;
                          return delete field.original_data;
                        }
                      }
                    },
                    fields: function() {
                      return _this.__getProduceVersionConfigFields(cls, classData);
                    },
                    button: {
                      icon: "edit"
                    },
                    hasChanges: function(field, data) {
                      if (!field.original_data) {
                        field.original_data = CUI.util.copyObject(field.getData(), true);
                        return false;
                      }
                      if (CUI.util.isEmpty(data.recipename)) {
                        return false;
                      }
                      return !CUI.util.isEqual(field.original_data, field.getData());
                    },
                    revertData: function(field) {
                      Object.assign(field.getForm().getData(), CUI.util.copyObject(field.original_data, true));
                      delete field.original_data;
                      field.removeFields();
                    },
                    onDataChanged: function(editedVersionData) {
                      var dataTableNode, newRightsManagement, versionName;
                      versionName = editedVersionData.name;
                      newRightsManagement = editedVersionData.rightsmanagement;
                      dataTableNode = this.getForm();
                      if (dataTableNode != null) {
                        dataTableNode.reload();
                      }
                      return setTimeout((function(_this) {
                        return function() {
                          var i, len, ref, ref1, ref2, versionData, versionsData;
                          versionsData = dataTableNode != null ? typeof dataTableNode.getDataTable === "function" ? (ref = dataTableNode.getDataTable()) != null ? ref.getData() : void 0 : void 0 : void 0;
                          if (versionsData && versionsData.versions.length > 0) {
                            ref1 = versionsData.versions;
                            for (i = 0, len = ref1.length; i < len; i++) {
                              versionData = ref1[i];
                              if (versionData.name === versionName) {
                                versionData.rightsmanagement = newRightsManagement;
                              }
                            }
                          }
                          if (dataTableNode != null) {
                            if ((ref2 = dataTableNode.getDataTable()) != null) {
                              ref2.reload();
                            }
                          }
                        };
                      })(this), 0);
                    }
                  }
                ]
              }
            ]
          });
          return form;
        };
      })(this)
    });
    return tab;
  };

  FASProduceConfigBaseConfig.prototype.__getProduceVersionConfigFields = function(cls, classData) {
    var checkNameInput, checkRecipeField, checkSourceField, customMetadataField, emptyField, fields, getSourceVersionOptions, showHideOriginalFields;
    if (CUI.util.isEmpty(this.__recipesByClass[cls])) {
      emptyField = {
        type: CUI.Output,
        text: $$("fylr.produce.config.form.version.no-recipes-found")
      };
      return [emptyField];
    }
    showHideOriginalFields = (function(_this) {
      return function(data, field, init) {
        var nameField, sourceVersionField;
        if (init == null) {
          init = false;
        }
        nameField = field.getForm().getFieldsByName("name")[0];
        sourceVersionField = field.getForm().getFieldsByName("sourceversion")[0];
        if (data._is_original) {
          data.__oldName = data.name;
          data.name = "original";
          nameField.disable();
          sourceVersionField.hide(true);
        } else {
          if (data.__oldName) {
            data.name = data.__oldName;
          }
          if (data.name === "original") {
            data.name = "";
          }
          nameField.enable();
          sourceVersionField.show(true);
        }
        if (!init) {
          nameField.reload();
        }
        checkSourceField(data, field, init);
      };
    })(this);
    getSourceVersionOptions = (function(_this) {
      return function(field) {
        var combinedOutputs, configuredExtensions, extensionsString, groupedVersions, i, j, len, len1, name1, options, outputFormats, recipe, ref, ref1, singleOutputFormat, textValue, tooltipParts, tooltipValue, v, version, versionData, versionName, versionOutputFormat, versionsByName;
        versionData = field.getData();
        options = [
          {
            text: $$("fylr.produce.config.form.version.sourceversion.original"),
            value: ""
          }
        ];
        recipe = _this.__allRecipes.find(function(r) {
          return r.RecipeName === versionData.recipename;
        });
        versionsByName = {};
        ref = classData.versions || [];
        for (i = 0, len = ref.length; i < len; i++) {
          version = ref[i];
          if (version.name === versionData.name) {
            continue;
          }
          if (CUI.util.isEmpty(versionData.name) && CUI.util.isEmpty(version.name)) {
            continue;
          }
          if (version._is_original) {
            continue;
          }
          versionOutputFormat = _this.__getOutputExtensionForRendition(version);
          if (recipe && !((ref1 = recipe.Extensions) != null ? ref1.includes(versionOutputFormat) : void 0)) {
            continue;
          }
          if (versionsByName[name1 = version.name] == null) {
            versionsByName[name1] = [];
          }
          versionsByName[version.name].push(version);
        }
        for (versionName in versionsByName) {
          groupedVersions = versionsByName[versionName];
          outputFormats = [];
          tooltipParts = [];
          for (j = 0, len1 = groupedVersions.length; j < len1; j++) {
            v = groupedVersions[j];
            configuredExtensions = v.extensions || [];
            if (configuredExtensions.length === 0) {
              extensionsString = "[ALL]";
            } else {
              extensionsString = "[" + configuredExtensions.join(", ").toUpperCase() + "]";
            }
            singleOutputFormat = _this.__getOutputExtensionForRendition(v).toUpperCase();
            if (!outputFormats.includes(singleOutputFormat)) {
              outputFormats.push(singleOutputFormat);
            }
            tooltipParts.push("Input: " + extensionsString + "\nOutput: [" + singleOutputFormat + "]");
          }
          combinedOutputs = "[" + outputFormats.join(", ") + "]";
          textValue = versionName + " | Output: " + combinedOutputs;
          tooltipValue = tooltipParts.join("\n---\n");
          options.push({
            text: textValue,
            value: versionName,
            tooltip: {
              text: tooltipValue
            }
          });
        }
        return options;
      };
    })(this);
    checkNameInput = function(data, field) {
      var originalCheckbox;
      if (data.name !== "original") {
        return;
      }
      originalCheckbox = field.getForm().getFieldsByName("_is_original")[0];
      data._is_original = true;
      originalCheckbox.reload();
      showHideOriginalFields(data, field);
    };
    checkSourceField = (function(_this) {
      return function(data, field, init) {
        var recipeName, recipes, ref;
        if (init == null) {
          init = false;
        }
        if (!init) {
          recipeName = data.recipename;
          recipes = _this.__getRecipes(cls, classData, data);
          if (!(recipes != null ? recipes.some(function(recipe) {
            return recipe.RecipeName === recipeName;
          }) : void 0)) {
            data.recipename = "";
          }
          field.getForm().getFieldsByName("recipename")[0].reload();
          field.getForm().getFieldsByName("extensions")[0].reload();
          field.getForm().getFieldsByName("_params")[0].reload();
          if ((ref = field.getForm().getFieldByIdx(7)) != null) {
            ref.reload();
          }
        }
      };
    })(this);
    checkRecipeField = (function(_this) {
      return function(data, field, init) {
        var newOptions, ref;
        if (init) {
          return;
        }
        if (!data.recipename) {
          return;
        }
        newOptions = getSourceVersionOptions(field);
        if (data.sourceversion && !newOptions.some(function(option) {
          return option.value === data.sourceversion;
        })) {
          data.sourceversion = "";
        }
        field.getForm().getFieldsByName("sourceversion")[0].reload();
        field.getForm().getFieldsByName("extensions")[0].reload();
        field.getForm().getFieldsByName("_params")[0].reload();
        if ((ref = field.getForm().getFieldByIdx(7)) != null) {
          ref.reload();
        }
      };
    })(this);
    fields = [
      {
        type: CUI.Checkbox,
        form: {
          label: ""
        },
        name: "_is_original",
        text: $$("fylr.produce.config.form.version.is_original"),
        onDataInit: function(field, data) {
          return showHideOriginalFields(data, field, true);
        },
        onDataChanged: function(data, field) {
          return showHideOriginalFields(data, field);
        }
      }, {
        type: CUI.Input,
        name: "name",
        form: {
          label: $$("fylr.produce.config.form.version.name")
        },
        maximize_horizontal: true,
        onDataChanged: checkNameInput
      }, {
        type: CUI.Select,
        name: "sourceversion",
        form: {
          label: $$("fylr.produce.config.form.version.sourceversion")
        },
        maximize_horizontal: true,
        onDataInit: (function(_this) {
          return function(field, data) {
            return checkSourceField(data, field, true);
          };
        })(this),
        onDataChanged: (function(_this) {
          return function(data, field) {
            return checkSourceField(data, field, false);
          };
        })(this),
        options: (function(_this) {
          return function(field) {
            return getSourceVersionOptions(field);
          };
        })(this)
      }, this.__getRecipesField(cls, classData, {
        onDataInit: (function(_this) {
          return function(field, data) {
            return checkRecipeField(data, field, true);
          };
        })(this),
        onDataChanged: (function(_this) {
          return function(data, field) {
            return checkRecipeField(data, field, false);
          };
        })(this)
      }), {
        type: CUI.Options,
        name: "extensions",
        form: {
          label: $$("fylr.produce.config.form.version.extensions")
        },
        maximize_horizontal: true,
        options: (function(_this) {
          return function(field) {
            var data, extension, extensions, extensions_set, i, j, k, len, len1, len2, options, recipe, recipeName, ref, version, versions;
            data = field.getData();
            extensions = [];
            options = [];
            if (CUI.util.isEmpty(data.sourceversion)) {
              recipeName = data.recipename;
              recipe = _this.__allRecipes.find(function(recipe) {
                return recipe.RecipeName === recipeName;
              });
              if (!recipe) {
                return options;
              }
              extensions = recipe.Extensions;
            } else {
              versions = classData.versions.filter(function(v) {
                return v.name === data.sourceversion;
              });
              if (versions.length === 0) {
                return options;
              }
              extensions_set = new Set();
              for (i = 0, len = versions.length; i < len; i++) {
                version = versions[i];
                recipeName = version.recipename;
                recipe = _this.__allRecipes.find(function(recipe) {
                  return recipe.RecipeName === recipeName;
                });
                if (!recipe) {
                  continue;
                }
                ref = recipe.Extensions || [];
                for (j = 0, len1 = ref.length; j < len1; j++) {
                  extension = ref[j];
                  extensions_set.add(extension);
                }
              }
              extensions = Array.from(extensions_set);
            }
            for (k = 0, len2 = extensions.length; k < len2; k++) {
              extension = extensions[k];
              options.push({
                content: new CUI.Label({
                  "class": "ez5-tag",
                  text: extension.toUpperCase()
                }),
                value: extension
              });
            }
            return options;
          };
        })(this)
      }, this.__getRecipeParamsField(cls, classData), this.__getSettingsField()
    ];
    if (customMetadataField = this.__getCustomMetadataField(true, cls, classData)) {
      fields.push(customMetadataField);
    }
    return fields;
  };

  FASProduceConfigBaseConfig.prototype.__getRecipesField = function(cls, classData, opts) {
    var field, getHint;
    if (opts == null) {
      opts = {};
    }
    getHint = (function(_this) {
      return function(data) {
        var recipe;
        if (data.recipename) {
          recipe = _this.__allRecipes.find(function(recipe) {
            return recipe.RecipeName === data.recipename;
          });
        }
        return (recipe != null ? recipe.Description : void 0) || "";
      };
    })(this);
    field = {
      type: CUI.Select,
      form: {
        label: $$("fylr.produce.config.form.recipe.name")
      },
      name: "recipename",
      maximize_horizontal: true,
      options: (function(_this) {
        return function(field) {
          var _recipes, compatibleExtensionFound, cookbookName, i, index, j, k, len, len1, len2, name, options, recipe, recipeInput, recipeOutput, recipes, recipesByCookbook, ref, ref1, ref2, ref3, sourceVersion, sourceVersionOutputFormat, sv, tooltip, versionData;
          if (opts.metadata && opts.isForVersion) {
            versionData = opts.metadataProxy.getData();
          } else {
            versionData = field.getData();
          }
          options = [
            {
              text: $$("fylr.produce.config.form.recipe.options.select"),
              value: ""
            }
          ];
          recipesByCookbook = {};
          _recipes = _this.__getRecipes(cls, classData, versionData);
          ref = _recipes || [];
          for (i = 0, len = ref.length; i < len; i++) {
            recipe = ref[i];
            if (versionData.sourceversion) {
              sourceVersion = classData.versions.filter(function(v) {
                return v.name === versionData.sourceversion;
              });
              if (!sourceVersion || sourceVersion.length === 0) {
                continue;
              }
              compatibleExtensionFound = false;
              for (j = 0, len1 = sourceVersion.length; j < len1; j++) {
                sv = sourceVersion[j];
                sourceVersionOutputFormat = _this.__getOutputExtensionForRendition(sv);
                if ((ref1 = recipe.Extensions) != null ? ref1.includes(sourceVersionOutputFormat) : void 0) {
                  compatibleExtensionFound = true;
                  break;
                }
              }
              if (!compatibleExtensionFound) {
                continue;
              }
            }
            cookbookName = (ref2 = recipe.RecipeName.split(":")) != null ? ref2[0] : void 0;
            if (!cookbookName) {
              continue;
            }
            if (!recipesByCookbook[cookbookName]) {
              recipesByCookbook[cookbookName] = [];
            }
            recipesByCookbook[cookbookName].push(recipe);
          }
          index = 0;
          for (cookbookName in recipesByCookbook) {
            recipes = recipesByCookbook[cookbookName];
            if (index > 0) {
              options.push({
                divider: true
              });
            }
            index++;
            options.push({
              label: cookbookName
            });
            ref3 = recipes || [];
            for (k = 0, len2 = ref3.length; k < len2; k++) {
              recipe = ref3[k];
              name = ez5.loca.getBestFrontendValue(recipe.Displayname) || recipe.Name;
              recipeOutput = _this.__getOutputsForRecipe(recipe);
              recipeInput = recipe.Extensions || [];
              if (recipeInput.length > 0) {
                tooltip = "Input: [" + recipeInput.join(", ").toUpperCase() + "]";
              }
              if (recipeOutput.length > 0) {
                tooltip += " \n Output: [" + recipeOutput.join(", ").toUpperCase() + "]";
              }
              options.push({
                text: name,
                value: recipe.RecipeName,
                tooltip: {
                  text: tooltip
                }
              });
            }
          }
          return options;
        };
      })(this),
      onDataInit: (function(_this) {
        return function(field, data) {
          field.opts.form.hint = getHint(data);
          if (opts.onDataInit) {
            return opts.onDataInit(field, data);
          }
        };
      })(this),
      onDataChanged: (function(_this) {
        return function(data, field) {
          var form, recipeParamsField, ref;
          data.params = {};
          form = field.getForm();
          if ((ref = form.getFieldsByName("extensions")[0]) != null) {
            ref.reload();
          }
          recipeParamsField = form.getFieldsByName("_params")[0];
          if (data.recipename) {
            recipeParamsField.show(true);
          }
          recipeParamsField.reload();
          field.getForm().updateHint("recipename", getHint(data));
          if (opts.onDataChanged) {
            opts.onDataChanged(data, field);
          }
        };
      })(this)
    };
    return field;
  };

  FASProduceConfigBaseConfig.prototype.__getRecipeParamsField = function(cls, classData, hideIfEmpty) {
    var field;
    if (hideIfEmpty == null) {
      hideIfEmpty = false;
    }
    field = {
      type: CUI.DataFieldProxy,
      form: {
        label: ""
      },
      name: "_params",
      element: (function(_this) {
        return function(field) {
          var _recipes, fields, i, len, panelOpts, paramName, paramValue, recipe, recipeFound, recipeName, ref, versionData;
          panelOpts = {
            text: $$("fylr.produce.config.form.version.recipe.panel.configuration"),
            closed: true,
            radio: "recipe_params"
          };
          versionData = field.getData();
          recipeName = versionData.recipename;
          if (!recipeName) {
            field.hide(true);
            panelOpts.content = new CUI.Label({
              text: $$("fylr.produce.config.form.version.recipe.no-recipe-selected"),
              appearance: "secondary"
            });
            return new CUI.Panel(panelOpts);
          }
          _recipes = _this.__getRecipes(cls, classData, versionData);
          for (i = 0, len = _recipes.length; i < len; i++) {
            recipe = _recipes[i];
            if (recipe.RecipeName !== recipeName) {
              continue;
            }
            recipeFound = recipe;
            break;
          }
          if (hideIfEmpty && (!recipeFound || CUI.util.isEmpty(recipeFound.Params))) {
            field.hide(true);
            panelOpts.content = new CUI.Label({
              text: $$("fylr.produce.config.form.version.recipe.recipe-no-params"),
              appearance: "secondary"
            });
            return new CUI.Panel(panelOpts);
          }
          if (!recipeFound) {
            panelOpts.content = new CUI.Label({
              text: $$("fylr.produce.config.form.version.recipe.recipe-not-found", {
                recipeName: recipeName
              }),
              appearance: "secondary"
            });
            return new CUI.Panel(panelOpts);
          }
          if (CUI.util.isEmpty(recipeFound.Params)) {
            panelOpts.content = new CUI.Label({
              text: $$("fylr.produce.config.form.version.recipe.recipe-no-params"),
              appearance: "secondary"
            });
            return new CUI.Panel(panelOpts);
          }
          if (!versionData.params) {
            versionData.params = {};
          }
          fields = [];
          ref = recipeFound.Params;
          for (paramName in ref) {
            paramValue = ref[paramName];
            field = _this.__getParamField(paramName, paramValue);
            fields.push(field);
          }
          panelOpts.content = new CUI.Form({
            fields: fields,
            name: "params",
            data: versionData
          });
          return new CUI.Panel(panelOpts);
        };
      })(this)
    };
    return field;
  };

  FASProduceConfigBaseConfig.prototype.__getParamField = function(paramName, paramValue) {
    var emptyValueFound, field, i, len, option, ref;
    field = this._baseConfig.getFieldDefFromParm(paramName, paramValue);
    field.form.label = field.name;
    switch (paramValue.type) {
      case "bool":
        field.form.label = null;
        field.text = paramName;
        break;
      case "int":
        if (paramValue.defaultint) {
          field.placeholder = "" + paramValue.defaultint;
        }
        break;
      case "text":
        if (paramValue.multiline) {
          field.textarea = true;
        }
        if (paramValue.defaultstring) {
          field.placeholder = paramValue.defaultstring;
        }
    }
    field.form.hint = paramValue.description;
    if (field.options) {
      emptyValueFound = false;
      ref = field.options;
      for (i = 0, len = ref.length; i < len; i++) {
        option = ref[i];
        if (option.value === "") {
          if (!emptyValueFound) {
            emptyValueFound = true;
          } else {
            option.divider = true;
          }
        }
        if (ez5.loca.has(option.text)) {
          option.text = $$(option.text);
        } else if (ez5.loca.has("fylr.produce.config.form.version.recipe.params." + paramName + "." + option.value)) {
          option.text = $$("fylr.produce.config.form.version.recipe.params." + paramName + "." + option.value);
        } else {
          option.text = option.value;
        }
      }
    }
    return field;
  };

  FASProduceConfigBaseConfig.prototype.__getSettingsField = function() {
    var field;
    field = {
      type: CUI.Form,
      form: {
        label: $$("fylr.produce.config.form.settings.title")
      },
      fields: [
        {
          type: CUI.Checkbox,
          name: "standard",
          text: $$("fylr.produce.config.form.settings.standard"),
          form: {
            hint: $$("fylr.produce.config.form.settings.resync.hint")
          }
        }, {
          type: CUI.Checkbox,
          name: "rightsmanagement",
          text: $$("fylr.produce.config.form.settings.rightsmanagement"),
          form: {
            hint: $$("fylr.produce.config.form.settings.rightsmanagement.hint")
          }
        }, {
          type: CUI.Checkbox,
          name: "watermark",
          text: $$("fylr.produce.config.form.settings.watermark")
        }, {
          type: CUI.MultiInput,
          name: "displayname",
          control: ez5.loca.getLanguageControlAdmin(),
          user_selectable: ez5.session.getPref("languages_user_selection"),
          form: {
            label: $$("fylr.produce.config.form.settings.displayname")
          }
        }, {
          type: CUI.Select,
          name: "group",
          form: {
            label: $$("fylr.produce.config.form.settings.group")
          },
          options: [
            {
              text: "",
              value: ""
            }, {
              text: $$("fylr.produce.config.form.settings.group.preview"),
              value: "preview"
            }, {
              text: $$("fylr.produce.config.form.settings.group.huge"),
              value: "huge"
            }, {
              text: $$("fylr.produce.config.form.settings.group.thumbnail"),
              value: "thumbnail"
            }
          ]
        }
      ]
    };
    return field;
  };

  FASProduceConfigBaseConfig.prototype.__getCustomMetadataField = function(isForVersion, vcls, classData) {
    var field, recipes;
    if (isForVersion == null) {
      isForVersion = false;
    }
    if (vcls == null) {
      vcls = "";
    }
    recipes = this.__getRecipes("metadata", classData);
    if (recipes.length === 0) {
      return;
    }
    if (isForVersion) {
      vcls = "metadata:" + vcls;
    } else {
      vcls = "metadata";
    }
    field = {
      type: CUI.DataFieldProxy,
      form: {
        label: ""
      },
      element: (function(_this) {
        return function(field) {
          var customMetadataFields, data, panel, panelContent, recipesSelectorOpts, warning_label;
          data = field.getData();
          recipesSelectorOpts = {
            metadata: true,
            isForVersion: isForVersion,
            metadataProxy: field
          };
          customMetadataFields = [_this.__getRecipesField(vcls, classData, recipesSelectorOpts), _this.__getRecipeParamsField("metadata", null, true)];
          customMetadataFields.push({
            type: CUI.Options,
            name: "extensions",
            form: {
              label: $$("fylr.produce.config.form.custom_metadata.extensions")
            },
            maximize_horizontal: true,
            options: function(field) {
              var extension, i, len, options, recipe, recipeName, ref;
              data = field.getData();
              recipeName = data.recipename;
              recipe = _this.__metadata.recipes.find(function(recipe) {
                return recipe.RecipeName === recipeName;
              });
              options = [];
              if (!recipe) {
                return options;
              }
              ref = recipe.Extensions || [];
              for (i = 0, len = ref.length; i < len; i++) {
                extension = ref[i];
                options.push({
                  content: new CUI.Label({
                    "class": "ez5-tag",
                    text: extension.toUpperCase()
                  }),
                  value: extension
                });
              }
              return options;
            }
          });
          if (!isForVersion) {
            customMetadataFields.push({
              type: CUI.Checkbox,
              form: {
                label: ""
              },
              name: "include_versions",
              text: $$("fylr.produce.config.form.custom_metadata.include_versions")
            });
            customMetadataFields.push({
              type: CUI.Checkbox,
              form: {
                label: ""
              },
              name: "metadata_request_only",
              text: $$("fylr.produce.config.form.custom_metadata.metadata_request_only")
            });
          }
          warning_label = new CUI.Label({
            text: $$("fylr.produce.config.form.custom_metadata.no_recipes")
          });
          panelContent = new CUI.Form({
            data: data,
            fields: [
              {
                type: CUI.DataForm,
                rowMove: true,
                has_add_button: true,
                maximize_horizontal: true,
                name: "custommetadata",
                fields: customMetadataFields,
                no_default_empty_row: isForVersion,
                enableAddButton: function(field, rows) {
                  var outputFormat;
                  if (!isForVersion) {
                    warning_label.hide();
                    return true;
                  }
                  outputFormat = _this.__getOutputExtensionForRendition(field.getData());
                  recipes = _this.__getMetadataRecipesForInput(outputFormat);
                  if (recipes.length === 0) {
                    warning_label.show();
                    return false;
                  } else {
                    warning_label.hide();
                    return true;
                  }
                }
              }
            ]
          });
          panel = new CUI.Panel({
            text: $$("fylr.produce.config.form.custom_metadata.title"),
            closed: true,
            content: [warning_label, panelContent],
            radio: "custom_metadata",
            save_state: "baseconfig_fileworker_custom_metadata" + (isForVersion ? "_version" : "")
          });
          return panel;
        };
      })(this)
    };
    return field;
  };

  FASProduceConfigBaseConfig.__normalizeRecipe = function(recipe) {
    var exec, i, len, normalizeExec, ref;
    if (recipe.RecipeName == null) {
      recipe.RecipeName = recipe.recipe_name || recipe.recipename;
    }
    if (recipe.Extensions == null) {
      recipe.Extensions = recipe.extensions;
    }
    if (recipe.Params == null) {
      recipe.Params = recipe.params;
    }
    if (recipe.ProduceClass == null) {
      recipe.ProduceClass = recipe.produceclass || recipe.produce_class;
    }
    if (recipe.Displayname == null) {
      recipe.Displayname = recipe.displayname;
    }
    if (recipe.Name == null) {
      recipe.Name = recipe.name;
    }
    if (recipe.Description == null) {
      recipe.Description = recipe.description;
    }
    if (!recipe.Execs) {
      recipe.Execs = recipe.execs || recipe.Execs;
    }
    if (!recipe.Exec) {
      recipe.Exec = recipe.exec || recipe.Exec;
    }
    normalizeExec = function(exec) {
      if (exec) {
        return exec.Extension != null ? exec.Extension : exec.Extension = exec.extension;
      }
    };
    if (CUI.util.isArray(recipe.Execs)) {
      ref = recipe.Execs;
      for (i = 0, len = ref.length; i < len; i++) {
        exec = ref[i];
        normalizeExec(exec);
      }
    }
    if (recipe.Exec) {
      normalizeExec(recipe.Exec);
    }
    return recipe;
  };

  FASProduceConfigBaseConfig.__normalizeUserData = function(data) {
    var _, classData, i, len, normalizeCustomMetadata, normalizeVersionData, ref, ref1, version;
    if (!data) {
      return;
    }
    normalizeVersionData = function(version) {
      if (version.recipe_name && !version.recipename) {
        version.recipename = version.recipe_name;
        return delete version.recipe_name;
      }
    };
    normalizeCustomMetadata = function(custommetadata) {
      var entry, i, len, results;
      if (!CUI.util.isArray(custommetadata)) {
        return;
      }
      results = [];
      for (i = 0, len = custommetadata.length; i < len; i++) {
        entry = custommetadata[i];
        if (entry.recipe_name && !entry.recipename) {
          entry.recipename = entry.recipe_name;
          results.push(delete entry.recipe_name);
        } else {
          results.push(void 0);
        }
      }
      return results;
    };
    normalizeCustomMetadata(data.custommetadata);
    ref = data.classes || {};
    for (_ in ref) {
      classData = ref[_];
      ref1 = classData.versions || [];
      for (i = 0, len = ref1.length; i < len; i++) {
        version = ref1[i];
        normalizeVersionData(version);
        normalizeCustomMetadata(version.custommetadata);
      }
    }
  };

  FASProduceConfigBaseConfig.prototype.__prepareExtensionsByClass = function() {
    var cls, extension, extensions, i, j, k, len, len1, len2, recipe, ref, ref1, ref2, ref3, value;
    if (!ez5.session.data.config.eas) {
      console.error("ProduceConfigBaseConfig :: ez5.session.data.config.eas does not have extensions.");
      return;
    }
    this.__extensionsByClass = {};
    this.__recipesByClass = {};
    this.__metadata = {};
    this.__allRecipes = [];
    ref = ez5.session.data.config.eas;
    for (cls in ref) {
      value = ref[cls];
      if (cls.startsWith("_")) {
        if (cls === "_metadata") {
          this.__metadata = value;
          if (this.__metadata.recipes) {
            ref1 = this.__metadata.recipes;
            for (i = 0, len = ref1.length; i < len; i++) {
              recipe = ref1[i];
              FASProduceConfigBaseConfig.__normalizeRecipe(recipe);
            }
          }
        }
        continue;
      }
      if (cls === "unknown") {
        continue;
      }
      extensions = new Set();
      if (!value.recipes) {
        continue;
      }
      this.__recipesByClass[cls] = [];
      ref2 = value.recipes;
      for (j = 0, len1 = ref2.length; j < len1; j++) {
        recipe = ref2[j];
        FASProduceConfigBaseConfig.__normalizeRecipe(recipe);
        this.__recipesByClass[cls].push(recipe);
        this.__allRecipes.push(recipe);
        ref3 = recipe.Extensions || [];
        for (k = 0, len2 = ref3.length; k < len2; k++) {
          extension = ref3[k];
          extensions.add(extension);
        }
      }
      this.__extensionsByClass[cls] = Array.from(extensions);
    }
  };

  FASProduceConfigBaseConfig.prototype.__getRecipes = function(cls, classData, versionData) {
    var clses, foundVersion, m_recipes, outputExtension, sourceVersionRecipe;
    if (cls === "metadata") {
      return this.__metadata.recipes;
    }
    if (cls.startsWith("metadata:")) {
      clses = cls.split(":");
      m_recipes = this.__metadata.recipes;
      outputExtension = this.__getOutputExtensionForRendition(versionData);
      return this.__getMetadataRecipesForInput(outputExtension);
    }
    if (versionData._is_original) {
      return this.__allRecipes;
    }
    if (versionData.sourceversion) {
      foundVersion = classData.versions.find(function(version) {
        return version.name === versionData.sourceversion;
      });
      sourceVersionRecipe = this.__allRecipes.find(function(recipe) {
        return recipe.RecipeName === (foundVersion != null ? foundVersion.recipename : void 0);
      });
      if (!sourceVersionRecipe) {
        return [];
      }
      cls = sourceVersionRecipe.ProduceClass;
    }
    return this.__recipesByClass[cls];
  };

  FASProduceConfigBaseConfig.prototype.__getMetadataRecipesForInput = function(format) {
    var all_metadata_recipes;
    all_metadata_recipes = this.__metadata.recipes;
    return all_metadata_recipes.filter(function(recipe) {
      if (!recipe.Extensions || recipe.Extensions.length === 0) {
        return true;
      }
      return recipe.Extensions.includes(format);
    });
  };

  FASProduceConfigBaseConfig.prototype.__getOutputExtensionForRendition = function(rendition_data) {
    var exec, extension, key, recipe, recipeName, ref;
    recipeName = rendition_data.recipename;
    recipe = this.__allRecipes.find((function(_this) {
      return function(recipe) {
        return recipe.RecipeName === recipeName;
      };
    })(this));
    if (!recipe) {
      return "UNKNOWN";
    }
    if (CUI.util.isArray(recipe.Execs) && recipe.Execs.length > 0) {
      exec = recipe.Execs[0];
    } else {
      exec = recipe.Exec;
    }
    extension = exec.Extension;
    if (extension.startsWith("%") && extension.endsWith("%")) {
      key = extension.slice(1, -1);
      extension = ((ref = rendition_data.params) != null ? ref[key] : void 0) || "UNKNOWN";
    }
    return extension || "UNKNOWN";
  };

  FASProduceConfigBaseConfig.prototype.__getOutputsForRecipe = function(recipe) {
    var exec, key, output, ref, ref1;
    if (CUI.util.isArray(recipe.Execs) && recipe.Execs.length > 0) {
      exec = recipe.Execs[0];
    } else {
      exec = recipe.Exec;
    }
    output = exec.Extension;
    if (!output) {
      return [];
    }
    if (output.startsWith("%") && output.endsWith("%")) {
      key = output.slice(1, -1);
      output = ((ref = recipe.Params[key]) != null ? ref.options : void 0) || ((ref1 = recipe.Params[key]) != null ? ref1.Options : void 0) || "UNKNOWN";
    }
    if (CUI.util.isArray(output)) {
      return output;
    } else {
      return [output];
    }
  };

  return FASProduceConfigBaseConfig;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var LicenseConfigBaseConfig,
  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;

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

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

  LicenseConfigBaseConfig.prototype.initOpts = function() {
    LicenseConfigBaseConfig.__super__.initOpts.call(this);
    return this.addOpts({
      baseConfig: {
        check: BaseConfig,
        mandatory: true
      },
      pname: {
        check: String,
        mandatory: true
      }
    });
  };

  LicenseConfigBaseConfig.prototype.getField = function() {
    return {
      type: CUI.DataFieldProxy,
      call_others: false,
      name: this._pname,
      "class": "base-config-license-config",
      element: (function(_this) {
        return function(dataField) {
          var label, labelText, ref, ref1, removeLicenseBtn, uploadBlock, uploadLicenseBtn, validation_tab, verticalList;
          _this.__field = dataField;
          _this.__data = dataField.getData();
          uploadLicenseBtn = new CUI.FileUploadButton({
            fileUpload: _this.__getUploadFileReader(),
            accept: ".json,.txt,.text,text/plain,/text/json",
            icon: "upload",
            text: $$("fylr.license.config.upload_button|text"),
            multiple: false
          });
          _this.__licenseInfo = null;
          if (_this.isEmpty()) {
            _this.__data[_this._pname] = null;
          } else {
            removeLicenseBtn = new CUI.Button({
              icon: "trash",
              text: $$("fylr.license.config.remove_button|text"),
              onClick: function() {
                return CUI.confirm({
                  title: $$("fylr.license.config.remove.title"),
                  icon: new CUI.Icon({
                    icon: $$("admin.easydb.object.remove.icon")
                  }),
                  text: $$("fylr.license.config.remove.text"),
                  button_text_ok: $$("base.delete"),
                  button_icon_ok: new CUI.Icon({
                    icon: $$("base.delete|icon")
                  }),
                  button_text_cancel: $$("base.cancel"),
                  button_danger: "ok"
                }).done(function(choice, btn, ev) {
                  return _this.__removeLicense();
                });
              }
            });
            _this.__licenseInfo = new CUI.Form({
              data: _this.__data,
              name: _this._pname,
              fields: _this.__getLicenseInfoFields(),
              "class": "base-config-license-info"
            });
          }
          labelText = _this.isEmpty() ? $$("fylr.license.config.no_license_text") : $$("fylr.license.config.license_text");
          label = new CUI.Label({
            text: labelText,
            "class": "cui-label-description"
          });
          uploadBlock = new CUI.VerticalList({
            content: [label, uploadLicenseBtn, removeLicenseBtn],
            "class": "base-config-license-upload"
          });
          verticalList = new CUI.VerticalList({
            content: [uploadBlock, (ref = _this.__licenseInfo) != null ? ref.start() : void 0]
          });
          validation_tab = null;
          if (((ref1 = _this.__data[_this._pname + ":info"]) != null ? ref1.validation : void 0) && !_this.isEmpty()) {
            validation_tab = {
              text: "Validation",
              content: _this.__getValidationTabContent()
            };
          }
          return new CUI.Tabs({
            tabs: [
              {
                text: "License",
                content: verticalList
              }, validation_tab, ez5.session.isDebug() ? {
                text: "JSON Data",
                content: new CUI.CodeInput({
                  maximize_horizontal: true,
                  name: _this._pname,
                  data: _this.__data,
                  mode: "json"
                }).start()
              } : void 0
            ]
          });
          return verticalList;
        };
      })(this)
    };
  };

  LicenseConfigBaseConfig.prototype.__getValidationTabContent = function() {
    var i, k, len, li, nProblems, problem, problemList, problems, rows, table, v, validationData;
    validationData = this.__data[this._pname + ":info"].validation;
    if (!validationData) {
      return null;
    }
    rows = [];
    for (k in validationData) {
      v = validationData[k];
      if (k === "problems") {
        problems = v;
        nProblems = (problems != null ? problems.length : void 0) || 0;
        if (nProblems > 0) {
          problemList = CUI.dom.element("UL");
          for (i = 0, len = problems.length; i < len; i++) {
            problem = problems[i];
            li = CUI.dom.element("LI");
            CUI.dom.append(li, problem);
            CUI.dom.append(problemList, li);
          }
        }
        v = nProblems;
      }
      if (CUI.util.isBoolean(v)) {
        v = new CUI.Icon({
          icon: v ? "fa-check" : "fa-minus"
        });
      }
      rows.push({
        key: ez5.loca.has("fylr.license.config.info.validation." + k) ? $$("fylr.license.config.info.validation." + k) : k,
        value: v
      });
    }
    if (!CUI.util.isEmpty(problemList)) {
      rows.push({
        key: ez5.loca.has("fylr.license.config.info.validation.problems-list") ? $$("fylr.license.config.info.validation.problems") : "Problem List",
        value: problemList
      });
    }
    return table = new CUI.Table({
      key_value: true,
      rows: rows
    });
  };

  LicenseConfigBaseConfig.prototype.__getUploadFileReader = function() {
    return new CUI.FileReader({
      onDone: (function(_this) {
        return function(fileReader) {
          var e;
          try {
            _this.__data[_this._pname] = JSON.parse(fileReader.getResult());
            console.log("Loaded license data from file", _this.__data[_this._pname]);
            _this.__field.reload();
          } catch (error) {
            e = error;
            CUI.problem({
              text: $$("fylr.license.config.error")
            });
            console.log({
              text: "There was a problem reading the license file"
            }, e);
            _this.__removeLicense();
            return;
          }
          return CUI.Events.trigger({
            node: _this.__field,
            type: "data-changed",
            info: {
              element: _this.__field
            }
          });
        };
      })(this)
    });
  };

  LicenseConfigBaseConfig.prototype.__removeLicense = function() {
    this.__data[this._pname] = null;
    this.__field.reload();
    return CUI.Events.trigger({
      node: this.__field,
      type: "data-changed",
      info: {
        element: this.__field
      }
    });
  };

  LicenseConfigBaseConfig.prototype.isEmpty = function() {
    return CUI.util.isEmpty(this.__data[this._pname]) || this.__data[this._pname] === "{}" || this.__data[this._pname] === "null";
  };

  LicenseConfigBaseConfig.prototype.__getLicenseInfoFields = function() {
    var fields, i, j, key, keys, len, len1, ref, subkey;
    fields = [];
    keys = ["key", "issuer", "holder", "type", "edition", "valid", "paid_to", "notes", "domains", "signature", "capabilities", "plugins", "contact_emails"];
    for (i = 0, len = keys.length; i < len; i++) {
      key = keys[i];
      if (CUI.util.isEmpty(this.__data[this._pname][key])) {
        continue;
      }
      switch (key) {
        case "capabilities":
          fields.push(new CUI.DataFieldProxy({
            form: {
              label: $$("fylr.license.config.info." + key)
            },
            data: this.__data[this._pname][key],
            element: (function(_this) {
              return function(datafield) {
                var data, feature, features, value;
                data = datafield.getData();
                features = [];
                for (feature in data) {
                  value = data[feature];
                  features.push(new CUI.Label({
                    multiline: true,
                    text: ($$("fylr.license.config.info.capabilities." + feature)) + " : **" + value + "**",
                    markdown: true
                  }));
                }
                return new CUI.VerticalList({
                  content: features
                });
              };
            })(this)
          }));
          break;
        case "contact_emails":
          fields.push(new CUI.DataFieldProxy({
            form: {
              label: $$("fylr.license.config.info." + key)
            },
            name: "contact_emails",
            data: this.__data[this._pname],
            element: (function(_this) {
              return function(datafield) {
                var data, email, emailElements, j, len1;
                data = datafield.getData()["contact_emails"];
                emailElements = [];
                for (j = 0, len1 = data.length; j < len1; j++) {
                  email = data[j];
                  emailElements.push(new CUI.Label({
                    multiline: true,
                    text: "[" + email + "](mailto:" + email + ")",
                    markdown: true
                  }));
                }
                return new CUI.VerticalList({
                  content: emailElements
                });
              };
            })(this)
          }));
          break;
        case "created_at":
          fields.push(new CUI.Output({
            name: key,
            form: {
              label: $$("fylr.license.config.info." + key)
            },
            getValue: (function(_this) {
              return function(v) {
                return CUI.DateTime.toMoment(v).utc().format("YYYY-MM-DD HH:mm:ss") + ' UTC';
              };
            })(this)
          }));
          break;
        case "valid":
          ref = ['from', 'to'];
          for (j = 0, len1 = ref.length; j < len1; j++) {
            subkey = ref[j];
            if (!CUI.util.isEmpty(this.__data[this._pname][key][subkey])) {
              fields.push(new CUI.Output({
                data: this.__data[this._pname][key],
                name: subkey,
                form: {
                  label: $$("fylr.license.config.info.valid." + subkey)
                },
                getValue: (function(_this) {
                  return function(v) {
                    return CUI.DateTime.toMoment(v).utc().format("YYYY-MM-DD HH:mm:ss") + ' UTC';
                  };
                })(this)
              }));
            }
          }
          break;
        case "paid_to":
          fields.push(new CUI.Output({
            name: key,
            form: {
              label: $$("fylr.license.config.info.paid_to")
            },
            getValue: (function(_this) {
              return function(v) {
                return CUI.DateTime.toMoment(v).utc().format("YYYY-MM-DD HH:mm:ss") + ' UTC';
              };
            })(this)
          }));
          break;
        case "plugins":
          fields.push(new CUI.Output({
            name: key,
            multiline: true,
            form: {
              label: $$("fylr.license.config.info." + key)
            },
            getValue: (function(_this) {
              return function(v) {
                if (CUI.util.isEmpty(v)) {
                  return "";
                }
                return Object.keys(v).map(function(k) {
                  return k;
                }).join("\n");
              };
            })(this)
          }));
          break;
        default:
          fields.push(new CUI.Output({
            name: key,
            multiline: true,
            form: {
              label: $$("fylr.license.config.info." + key)
            },
            getValue: (function(_this) {
              return function(v) {
                if (Array.isArray(v)) {
                  return v.join(",");
                } else {
                  return v;
                }
              };
            })(this)
          }));
      }
    }
    return fields;
  };

  return LicenseConfigBaseConfig;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var CustomDataType,
  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;

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

  function CustomDataType(mask, fieldSchema) {
    if (mask == null) {
      mask = null;
    }
    if (fieldSchema == null) {
      fieldSchema = null;
    }
    if (arguments.length === 0) {
      return;
    }
    CustomDataType.__super__.constructor.call(this, mask, fieldSchema);
  }


  /*
  	Create the output for datamodel info
  
  	@param [Object] custom_settings
  	@return [Array<String>] Localized Strings with information shown as tags.
  
  	Receives the map of custom settings, needs to return
  	an Array of localized Strings with information shown as tags.
   */

  CustomDataType.prototype.getCustomDataOptionsInDatamodelInfo = function(custom_settings) {
    return CUI.util.assert(false, CUI.util.getObjectClass(this) + ".getCustomDataOptionsInDatamodelInfo needs to be implemented.");
  };


  /*
  	Get the Function for the new parameter to create another instance of this class.
  
  	@return [Function]
   */


  /*
  	Whether or not to render field as group
  
  	@param [Object] data
  	@param [Object] top_level_data
  	@param [Object] opts
  
  	@return [Boolean] True if value should be shown as group, False if otherwise.
   */

  CustomDataType.prototype.renderStandard = function(standard, data) {
    var _standard, bestDatabaseValue, invalidSaveDataException, outputStandard, ref, saveData, value;
    if (!this.supportsStandard()) {
      return;
    }
    if (this.isEmpty(data)) {
      return;
    }
    outputStandard = this.getOutputStandard();
    if (!outputStandard) {
      return;
    }
    try {
      this.getSaveData(data, saveData = {});
    } catch (error) {
      invalidSaveDataException = error;
      return;
    }
    _standard = (ref = saveData[this.name()]) != null ? ref._standard : void 0;
    if (CUI.util.isEmpty(_standard)) {
      return;
    }
    value = _standard.text;
    if (!CUI.util.isEmpty(_standard.l10ntext)) {
      if (bestDatabaseValue = ez5.loca.getBestDatabaseValue(_standard.l10ntext)) {
        value = bestDatabaseValue;
      }
    }
    if (!value) {
      return;
    }
    standard.push({
      field: this,
      value: value,
      render_info: this.getOutputStandard()
    });
  };

  CustomDataType.prototype.hasMappingChildFields = function() {
    return true;
  };

  CustomDataType.prototype.getMappingChildFields = function(_, fieldsFormNode) {
    var fieldName, fieldValue, fields, isValidTypeForStandard, mapping, profileType, ref, ref1, ref2;
    fields = [];
    isValidTypeForStandard = true;
    if (fieldsFormNode instanceof XMLFormWrapperTreeNode) {
      profileType = fieldsFormNode.getProfileType();
      isValidTypeForStandard = !profileType.xml_import && (profileType.dc_export || profileType.exiftool_export || profileType.exiftool_import || profileType.xml_export);
    }
    if (this.supportsStandard() && isValidTypeForStandard) {
      fields.push(new CustomDataTypeStandardField({
        customDataType: this
      }));
    }
    mapping = (ref = ez5.session.getDefaults().server) != null ? (ref1 = ref.custom_data_types) != null ? (ref2 = ref1[this.getCustomDataTypeName()]) != null ? ref2.mapping : void 0 : void 0 : void 0;
    if (mapping) {
      for (fieldName in mapping) {
        fieldValue = mapping[fieldName];
        fields.push(new CustomDataTypeMappingField({
          customDataType: this,
          field: {
            name: fieldName,
            type: fieldValue.type
          }
        }));
      }
    }
    return fields;
  };

  CustomDataType.prototype.isSourceForMapping = function() {
    return true;
  };

  CustomDataType.prototype.getMappingTargetName = function() {
    return this.name();
  };

  CustomDataType.prototype.getMappingSourceFullNameLocalized = function(useTableName) {
    var mappingSourceFullNameLocalized;
    mappingSourceFullNameLocalized = CustomDataType.__super__.getMappingSourceFullNameLocalized.call(this, useTableName);
    return mappingSourceFullNameLocalized + " [" + $$("custom.data.type.mapping_source_name") + "]";
  };

  CustomDataType.prototype.renderFieldAsGroup = function(data, top_level_data, opts) {
    return true;
  };

  CustomDataType.prototype.getClassFunction = function() {
    if (window.headless_mode) {
      return this.constructor;
    }
    return window[CUI.util.getObjectClass(this)];
  };

  CustomDataType.prototype.getCustomDataTypeName = function() {
    return CUI.util.assert(false, CUI.util.getObjectClass(this) + ".getCustomDataTypeName needs to be implemented.");
  };

  CustomDataType.prototype.getCustomDataTypeNameLocalized = function() {
    return $$(this.getL10NPrefix() + ".name");
  };

  CustomDataType.prototype.getCustomSchemaSettingNameLocalized = function(name) {
    return $$(this.getL10NPrefix() + ".setting.schema." + name);
  };

  CustomDataType.prototype.getCustomMaskSettingNameLocalized = function(name) {
    return $$(this.getL10NPrefix() + ".setting.mask." + name);
  };

  CustomDataType.prototype.getL10NPrefix = function() {
    return CUI.util.toDash(CUI.util.getObjectClass(this)).replace(/-/g, ".");
  };

  CustomDataType.prototype.getCustomSchemaSettings = function() {
    return this.ColumnSchema.custom_settings || {};
  };

  CustomDataType.prototype.getCustomMaskSettings = function() {
    return this.FieldSchema.custom_settings || {};
  };

  CustomDataType.prototype.isVisible = function(mode, opts) {
    if (opts == null) {
      opts = {};
    }
    if (!CustomDataType.__super__.isVisible.call(this, mode, opts) || mode === 'fulltext') {
      return false;
    }
    if (opts.for_print) {
      return this.supportsPrinting();
    }
    return true;
  };

  CustomDataType.prototype.getXMLFormWrapperSaveData = function(wrapperField) {
    return {
      type: "custom",
      custom_type: this.getCustomDataTypeName()
    };
  };

  CustomDataType.prototype.getXMLFormWrapperType = function() {
    return "custom";
  };

  CustomDataType.prototype.supportsStandard = function() {
    return false;
  };

  CustomDataType.prototype.supportsGeoStandard = function() {
    return false;
  };

  CustomDataType.prototype.supportsPrinting = function() {
    return false;
  };


  /*
  	Render the summary output below the options button.
  
  	@return [Element] DIV with content.
   */

  CustomDataType.prototype.renderCustomDataOptionsInDatamodel = function(custom_settings) {
    var div, i, info, len, txt;
    info = this.getCustomDataOptionsInDatamodelInfo(custom_settings);
    if (!(info != null ? info.length : void 0)) {
      return;
    }
    div = CUI.dom.element("DIV", {
      "class": "ez5-tag-holder"
    });
    for (i = 0, len = info.length; i < len; i++) {
      txt = info[i];
      div.appendChild(new CUI.Label({
        "class": "ez5-tag",
        text: txt
      }).DOM);
    }
    return div;
  };


  /*
  	Check if data has user data.
  
  	@return [Boolean] True if data has user ented data.
   */

  CustomDataType.prototype.hasUserData = function(data, top_level_data, opts) {
    return !this.isEmpty(data, top_level_data, opts);
  };

  CustomDataType.__customDataTypes = {};

  CustomDataType.get = function(customDataTypeName) {
    var dt;
    dt = this.__customDataTypes[customDataTypeName];
    if (!dt) {
      return new CustomDataTypeUnknown();
    } else {
      return dt;
    }
  };

  CustomDataType.getTypes = function() {
    var key, ref, results, value;
    ref = this.__customDataTypes;
    results = [];
    for (key in ref) {
      value = ref[key];
      results.push(value);
    }
    return results;
  };

  CustomDataType.register = function(customDataType) {
    var custom_name, dt;
    CUI.util.assert(CUI.util.isFunction(customDataType) && new customDataType() instanceof CustomDataType, "ez5.register_custom_data_type", "customDataType needs to be instance of CustomDataType.", {
      customDataType: customDataType
    });
    dt = new customDataType();
    custom_name = dt.getCustomDataTypeName() || "";
    CUI.util.assert(custom_name.match("^custom:[a-z][0-9a-z_\.\-]*[0-9a-z]$"), "ez5.register_custom_data_type", "customDataType \"" + custom_name + "\" name is no good.", {
      customDataTypeName: custom_name
    });
    CUI.util.assert(!this.__customDataTypes[custom_name], "ez5.register_custom_data_type", "customDataType \"" + custom_name + "\" already registered.", {
      customDataTypes: this.__customDataTypes
    });
    this.__customDataTypes[custom_name] = dt;
  };

  CustomDataType.prototype.hasRenderForSort = function() {
    return false;
  };

  CustomDataType.prototype.getSortFields = function(filter) {
    var field;
    if (!filter._extra) {
      console.warn(CUI.util.getObjectClass(this) + ".sortExtraOpts needs to be implemented in order to sort it. Skipping...");
      return;
    }
    field = {
      field: this.fullName() + ("." + filter._extra),
      group_field: this.fullName() + ("." + filter._extra),
      order: filter._order
    };
    return field;
  };

  CustomDataType.prototype.getCSVDestinationFields = function(csvImporter) {
    var opts;
    opts = {
      csvImporter: csvImporter,
      field: this
    };
    return [new CustomDataTypeColumnCSVImporterDestinationField(opts)];
  };

  CustomDataType.prototype.getHasValueFilter = function(data, key) {
    if (key == null) {
      key = this.name();
    }
    return null;
  };

  CustomDataType.prototype.showInDetail = function() {
    return true;
  };

  return CustomDataType;

})(DataColumn);
// Generated by CoffeeScript 1.12.7
var CustomDataTypeMappingField,
  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;

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

  function CustomDataTypeMappingField(_opts) {
    CUI.Element.readOpts.call(this, _opts, "new CustomDataTypeMappingField", {
      customDataType: {
        mandatory: true,
        check: CustomDataType
      },
      field: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isPlainObject(v) && CUI.util.isString(v.type) && CUI.util.isString(v.name);
        }
      }
    }, true);
  }

  CustomDataTypeMappingField.prototype.getMappingTargetName = function() {
    return this._field.name;
  };

  CustomDataTypeMappingField.prototype.getMappingSourceFullNameLocalized = function(useTableName) {
    var mappingSourceFullNameLocalized;
    mappingSourceFullNameLocalized = CustomDataTypeMappingField.__super__.getMappingSourceFullNameLocalized.call(this, useTableName);
    return mappingSourceFullNameLocalized + (" [" + this._field.name + "]");
  };

  CustomDataTypeMappingField.prototype.name = function() {
    return this._field.name;
  };

  CustomDataTypeMappingField.prototype.nameLocalized = function() {
    return this._field.name;
  };

  CustomDataTypeMappingField.prototype.isVisible = function(mode, opts) {
    if (opts == null) {
      opts = {};
    }
    return this._customDataType.isVisible(mode, opts);
  };

  CustomDataTypeMappingField.prototype.fullName = function() {
    return this._customDataType.fullName();
  };

  CustomDataTypeMappingField.prototype.fullNameLocalized = function() {
    return this._customDataType.fullNameLocalized();
  };

  CustomDataTypeMappingField.prototype.getXMLFormWrapperType = function() {
    return this._customDataType.getXMLFormWrapperType();
  };

  CustomDataTypeMappingField.prototype.getXMLFormWrapperSaveData = function(wrapperField) {
    return this._customDataType.getXMLFormWrapperSaveData(wrapperField);
  };

  return CustomDataTypeMappingField;

})(Field);
// Generated by CoffeeScript 1.12.7
var CustomDataTypeStandardField,
  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;

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

  function CustomDataTypeStandardField(_opts) {
    CUI.Element.readOpts.call(this, _opts, "new CustomDataTypeMappingField", {
      customDataType: {
        mandatory: true,
        check: CustomDataType
      }
    }, true);
  }

  CustomDataTypeStandardField.prototype.initOpts = function() {
    CustomDataTypeStandardField.__super__.initOpts.call(this);
    return this.removeOpt("field");
  };

  CustomDataTypeStandardField.prototype.getMappingTargetName = function() {
    return "_standard";
  };

  CustomDataTypeStandardField.prototype.getMappingSourceFullNameLocalized = function(useTableName) {
    var mappingSourceFullNameLocalized;
    mappingSourceFullNameLocalized = this.fullNameLocalized(useTableName);
    return mappingSourceFullNameLocalized + " [" + $$("custom.data.type.standard.field.mapping_source_name") + "]";
  };

  CustomDataTypeStandardField.prototype.name = function() {
    return "_standard";
  };

  CustomDataTypeStandardField.prototype.nameLocalized = function() {
    return $$("custom.data.type.standard.field.field_name");
  };

  CustomDataTypeStandardField.prototype.isSourceForMapping = function(required_type) {
    if (required_type["import"]) {
      return false;
    }
    return true;
  };

  CustomDataTypeStandardField.prototype.isValidMappingField = function() {
    return true;
  };

  return CustomDataTypeStandardField;

})(CustomDataTypeMappingField);
// Generated by CoffeeScript 1.12.7
var CustomDataTypeUnknown,
  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;

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

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

  CustomDataTypeUnknown.prototype.renderCustomDataOptionsInDatamodel = function(custom_settings) {
    return (new CUI.EmptyLabel({
      text: $$("custom.data.type.unknown.options")
    })).DOM;
  };

  CustomDataTypeUnknown.prototype.getCustomDataTypeName = function() {
    return "custom.data.type.unknown";
  };

  CustomDataTypeUnknown.prototype.getCustomDataTypeNameLocalized = function() {
    return $$("custom.data.type.unknown.name", {
      name: this._name
    });
  };

  CustomDataTypeUnknown.prototype.getCustomSchemaSettings = function() {
    return [];
  };

  CustomDataTypeUnknown.prototype.getCustomMaskSettings = function() {
    return [];
  };

  CustomDataTypeUnknown.prototype.getSaveData = function(data, save_data, opts) {
    var e, fieldData, jsonData;
    fieldData = data[this.name()];
    jsonData = data[this.name() + ":json"];
    if (jsonData != null ? jsonData.json : void 0) {
      try {
        return save_data[this.name()] = JSON.parse(jsonData.json);
      } catch (error) {
        e = error;
      }
    }
    return save_data[this.name()] = fieldData;
  };

  CustomDataTypeUnknown.prototype.renderDetailOutput = function(data, top_level_data, opts) {
    var e, fieldData;
    fieldData = data[this.name()];
    try {
      return new CUI.VerticalList({
        content: [
          this.__getNotFoundLabel(), new CUI.ObjectDumper({
            object: fieldData
          })
        ]
      });
    } catch (error) {
      e = error;
      return CustomDataTypeUnknown.__super__.renderDetailOutput.call(this, data, top_level_data, opts);
    }
  };

  CustomDataTypeUnknown.prototype.renderEditorInput = function(data) {
    var fieldData, form, jsonData;
    fieldData = data[this.name()];
    jsonData = {};
    jsonData.json = JSON.stringify(fieldData, null, 2);
    data[this.name() + ":json"] = jsonData;
    form = new CUI.Form({
      data: jsonData,
      maximize_horizontal: true,
      fields: [
        {
          type: CUI.CodeInput,
          mode: "json",
          name: "json",
          checkInput: (function(_this) {
            return function(value) {
              var e;
              try {
                JSON.parse(value);
                return true;
              } catch (error) {
                e = error;
                return false;
              }
            };
          })(this)
        }
      ],
      onDataChanged: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            node: form,
            type: "editor-changed"
          });
        };
      })(this)
    });
    form.start();
    return new CUI.VerticalList({
      content: [this.__getNotFoundLabel(), form]
    });
  };

  CustomDataTypeUnknown.prototype.__getNotFoundLabel = function() {
    return new LocaLabel({
      markdown: true,
      loca_key: "custom.data.type.unknown.label-not-found.md",
      loca_key_attrs: {
        type: this.ColumnSchema.type
      },
      "class": "ez5-custom-data-type-unknown"
    });
  };

  CustomDataTypeUnknown.prototype.renderFieldAsGroup = function() {
    return false;
  };

  return CustomDataTypeUnknown;

})(CustomDataType);
// Generated by CoffeeScript 1.12.7
var CustomDataTypeConfig, CustomDataTypeConfigMask, CustomDataTypeConfigSchema, CustomDataTypeDatamodelSupport,
  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;

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

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

  CustomDataTypeDatamodelSupport.prototype.datamodelSetRowState = function(_opts) {
    var opts;
    opts = CUI.Element.readOpts(_opts, this.__cls + ".datamodelSetRowState", {
      row: {
        check: ListViewEditTreeNode
      },
      field_numbers: {
        check: "PlainObject"
      },
      hide: {
        check: Array
      },
      disable: {
        check: Array
      }
    });
    return opts.hide.push("reverse_edit", "bidirectional", "bidirectional_reverse");
  };

  CustomDataTypeDatamodelSupport.prototype.maskSetRowState = function(_opts) {
    var config, custom_field, opts;
    opts = CUI.Element.readOpts(_opts, this.__cls + ".maskSetRowState", {
      row: {
        check: ListViewEditTreeMaskRowNode
      },
      field_numbers: {
        check: "PlainObject"
      },
      hide: {
        check: Array
      },
      disable: {
        check: Array
      }
    });
    config = this.getCustomTypeConfig(opts.row.column_type).mask;
    custom_field = CustomDataType.get(opts.row.column_type);
    if (custom_field.supportsStandard()) {
      CUI.util.removeFromArray(opts.field_numbers.standard, opts.hide);
    }
    if (ez5.version("6.10")) {
      if (custom_field.supportsGeoStandard()) {
        CUI.util.removeFromArray(opts.field_numbers.standard_geo, opts.hide);
      }
    }
  };

  CustomDataTypeDatamodelSupport.prototype.getCustomSchemaOptions = function(data) {
    return this.__getCustomDatamodelOptions(data, data.type, "schema");
  };

  CustomDataTypeDatamodelSupport.prototype.getCustomMaskOptions = function(data) {
    return this.__getCustomDatamodelOptions(data, data.field._column.type, "mask");
  };

  CustomDataTypeDatamodelSupport.prototype.getCustomMaskOptionTags = function(data) {
    var config, config_item, custom_data_type, custom_name, custom_settings, def, dt, i, len, param, ref, setting, setting_value, tags;
    custom_data_type = data.field._column.type;
    dt = CustomDataType.get(custom_data_type);
    custom_name = custom_data_type.match("^custom:(.*)$")[1];
    config = this.getCustomTypeConfig(custom_data_type).mask;
    custom_settings = data.custom_settings;
    tags = [];
    for (i = 0, len = config.length; i < len; i++) {
      config_item = config[i];
      setting = custom_settings[config_item.name];
      ref = config_item.parameters;
      for (param in ref) {
        def = ref[param];
        if (CUI.util.isEmpty(setting != null ? setting[param] : void 0)) {
          setting_value = def["default"];
          if (setting_value === void 0) {
            if (def.type === 'select') {
              setting_value = def.options[0];
            }
          }
        } else {
          setting_value = setting[param];
        }
        if (setting_value === false || setting_value === void 0) {
          continue;
        }
        if (def.type === "select") {
          tags.push($$(dt.getL10NPrefix() + ".config.option.mask." + config_item.name + "." + param + "." + setting_value));
        } else {
          tags.push($$(dt.getL10NPrefix() + ".config.parameter.mask." + config_item.name + "." + param + ".label"));
        }
      }
    }
    return tags;
  };

  CustomDataTypeDatamodelSupport.prototype.getCustomTypeConfig = function(custom_data_type) {
    var config;
    config = ez5.session.getCustomDataTypes()[custom_data_type] || {};
    if (!config.mask) {
      config.mask = [];
    }
    if (!config.schema) {
      config.schema = [];
    }
    return config;
  };

  CustomDataTypeDatamodelSupport.prototype.__getCustomDatamodelOptions = function(data, custom_data_type, type) {
    var bc, config, config_item, custom_name, custom_settings, dt, field, fields, i, j, len, len1, ref;
    dt = CustomDataType.get(custom_data_type);
    custom_name = custom_data_type.match("^custom:(.*)$")[1];
    config = this.getCustomTypeConfig(custom_data_type)[type];
    custom_settings = data.custom_settings;
    fields = [];
    for (i = 0, len = config.length; i < len; i++) {
      config_item = config[i];
      config_item.CustomDataType = dt;
      switch (type) {
        case "schema":
          bc = new CustomDataTypeConfigSchema(config_item);
          break;
        case "mask":
          bc = new CustomDataTypeConfigMask(config_item);
      }
      if (!custom_settings[bc.name()]) {
        custom_settings[bc.name()] = {};
      }
      ref = bc.getFields();
      for (j = 0, len1 = ref.length; j < len1; j++) {
        field = ref[j];
        field.data = bc.initData(custom_settings);
        fields.push(field);
      }
    }
    return fields;
  };

  CustomDataTypeDatamodelSupport.prototype.getCustom = function(data) {};

  CustomDataTypeDatamodelSupport.prototype.renderDisplayForCustomSchemaOptions = function(data) {
    var dt;
    dt = CustomDataType.get(data.type);
    return dt.renderCustomDataOptionsInDatamodel(data.custom_settings);
  };

  return CustomDataTypeDatamodelSupport;

})(CUI.Element);

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

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

  CustomDataTypeConfig.prototype.initOpts = function() {
    CustomDataTypeConfig.__super__.initOpts.call(this);
    return this.addOpts({
      CustomDataType: {
        check: CustomDataType
      }
    });
  };

  CustomDataTypeConfig.prototype.readOpts = function() {
    CustomDataTypeConfig.__super__.readOpts.call(this);
    return this.__l10n_prefix = this._CustomDataType.getL10NPrefix();
  };

  return CustomDataTypeConfig;

})(BaseConfig);

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

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

  CustomDataTypeConfigSchema.prototype.readOpts = function() {
    CustomDataTypeConfigSchema.__super__.readOpts.call(this);
    return this.__class = "schema";
  };

  CustomDataTypeConfigSchema.prototype.nameLocalized = function() {
    return this._CustomDataType.getCustomSchemaSettingNameLocalized(this._name);
  };

  return CustomDataTypeConfigSchema;

})(CustomDataTypeConfig);

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

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

  CustomDataTypeConfigMask.prototype.readOpts = function() {
    CustomDataTypeConfigMask.__super__.readOpts.call(this);
    return this.__class = "mask";
  };

  CustomDataTypeConfigMask.prototype.nameLocalized = function() {
    return this._CustomDataType.getCustomMaskSettingNameLocalized(this._name);
  };

  return CustomDataTypeConfigMask;

})(CustomDataTypeConfig);
// Generated by CoffeeScript 1.12.7
var CSVImporter,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  CSVImporter.prototype.start = function() {
    this.__setingsUploadedText = new CUI.Label({
      text: ""
    });
    this.resetFile();
    return this.showModal();
  };

  CSVImporter.prototype.resetFile = function() {
    this.__form_data = {
      header_row: 0,
      dest_field_row: 0,
      csv_header_rows: 0,
      csv_rows_count: 0,
      table_preview_chunk_size: 100,
      mapping: {},
      match_existing: null,
      control_fields_warning_shown: null,
      csv_field_names: [],
      preview_offset: 0,
      record_preview: 0,
      csv_filename: null,
      action_chunk_size: this.getActionChunkSizes()[0],
      show_localized_names: false
    };
    this.cf_idx = {};
    this.__csv_data = null;
    this.__csv_text = null;
    this.dest_fields = [];
    return this.resetData();
  };

  CSVImporter.prototype.__initControlFieldIndeces = function() {
    var cf, i, len, ref;
    this.cf_idx = {};
    ref = this.control_fields;
    for (i = 0, len = ref.length; i < len; i++) {
      cf = ref[i];
      this.cf_idx[cf.getName()] = cf.getColIdx();
    }
    return this;
  };

  CSVImporter.prototype.resetData = function() {
    this.__setingsUploadedText.setText("");
    this.__stats = null;
    this.__readyRows = null;
    return this.__statusFilters = {
      ready: true,
      invalid: true,
      processing: true,
      done: true,
      failed: true,
      warning: true,
      insert: true,
      update: true,
      "delete": true
    };
  };

  CSVImporter.prototype.getTitleLocaKey = function() {
    return "csv.importer.title";
  };

  CSVImporter.prototype.getDestinationFields = function() {
    return [];
  };

  CSVImporter.prototype.getControlFields = function() {
    var f, fields, i, len, ref;
    fields = [];
    ref = [
      {
        name: "row_idx"
      }, {
        name: "operation",
        format: "json"
      }, {
        name: "status"
      }, {
        name: "timestamp"
      }, {
        name: "status_text"
      }, {
        name: "warning_text"
      }, {
        name: "id"
      }, {
        name: "version"
      }
    ];
    for (i = 0, len = ref.length; i < len; i++) {
      f = ref[i];
      fields.push(new CSVImporterControlField(f));
    }
    return fields;
  };

  CSVImporter.prototype.action = function() {
    return CUI.util.assert(false, this.__cls + ".action needs implementation.");
  };

  CSVImporter.prototype.__action = function(ev, op) {
    var chunk_size, dfr, rows, start_action;
    chunk_size = this.__form_data.action_chunk_size;
    rows = this.getReadyRows(op);
    start_action = (function(_this) {
      return function() {
        var i, len, promise, row, toaster;
        for (i = 0, len = rows.length; i < len; i++) {
          row = rows[i];
          row[_this.cf_idx.status] = "processing";
        }
        _this.updateStatsTable();
        promise = CUI.chunkWork.call(_this, {
          items: rows,
          chunk_size: chunk_size,
          call: function(items) {
            return _this.action(ev, op, items);
          }
        });
        toaster = CUI.toaster({
          text_icon: "spinner",
          text: $$("csv.importer.action.start"),
          show_ms: 0
        });
        promise.progress(function(info) {
          return toaster.setText($$("csv.importer.action.progress", {
            progress: info.progress
          }));
        });
        promise.always(function() {
          var j, len1;
          for (j = 0, len1 = rows.length; j < len1; j++) {
            row = rows[j];
            row[_this.cf_idx.timestamp] = CUI.util.moment().format("YYYY-MM-DD HH:mm:ss");
            if (row[_this.cf_idx.status] === "processing") {
              row[_this.cf_idx.status] = "ready";
            }
          }
          _this.updateModal();
          return toaster.destroy();
        });
        promise.fail(dfr.reject);
        return promise.done(dfr.resolve);
      };
    })(this);
    dfr = new CUI.Deferred();
    if (rows.length === 0) {
      CUI.problem({
        text: $$("csv.importer.no_ready_rows_found_to_import"),
        markdown: true
      }).done((function(_this) {
        return function() {
          return dfr.reject();
        };
      })(this));
    } else if (ev.hasModifierKey()) {
      start_action();
    } else {
      this.__getActionConfirmation(op, rows).done((function(_this) {
        return function() {
          return start_action();
        };
      })(this)).fail(dfr.reject);
    }
    return dfr.promise();
  };

  CSVImporter.prototype.__getActionConfirmation = function(op, rows) {
    return CUI.confirm({
      text: $$("csv.importer.action.confirm." + op, {
        count: rows.length
      })
    });
  };

  CSVImporter.prototype.__prepareData = function() {
    var promise, rows, toaster;
    toaster = CUI.toaster({
      text_icon: "spinner",
      text: $$("csv.importer.preparing_data.start"),
      show_ms: 0
    });
    rows = this.getRows();
    this.__beforePrepareData(rows);
    promise = this.prepareData(rows);
    promise.progress((function(_this) {
      return function(info) {
        return toaster.setText($$("csv.importer.preparing_data.progress", {
          progress: info.progress
        }));
      };
    })(this));
    promise.always((function(_this) {
      return function() {
        return toaster.destroy();
      };
    })(this));
    promise.fail((function(_this) {
      return function() {
        return _this.resetReadyRows();
      };
    })(this));
    promise.done((function(_this) {
      return function() {
        return _this.collectReadyRows();
      };
    })(this));
    return promise;
  };

  CSVImporter.prototype.__beforePrepareData = function(rows) {
    this.callOnMappedDestFields((function(_this) {
      return function(dest_field, configs) {
        return dest_field.beforePrepareData(configs, rows);
      };
    })(this));
  };

  CSVImporter.prototype.prepareData = function(rows) {
    return CUI.chunkWork.call(this, {
      items: rows,
      chunk_size: this.__form_data.action_chunk_size,
      call: (function(_this) {
        return function(items, offset) {
          return _this.prepareDataChunk(items, offset);
        };
      })(this)
    });
  };

  CSVImporter.prototype.prepareDestinationFieldsDataChunk = function(rows, offset) {
    return this.callOnMappedDestFields((function(_this) {
      return function(dest_field, configs) {
        return dest_field.prepareDataChunk(configs, rows, offset);
      };
    })(this));
  };

  CSVImporter.prototype.prepareDataChunk = function(rows, offset) {
    var dfr;
    dfr = new CUI.Deferred();
    this.prepareDestinationFieldsDataChunk(rows, offset).done((function(_this) {
      return function() {
        return _this.preparePrimaryKeyDataChunk(rows, offset).done(function() {
          return _this.prepareExistingDataChunk(rows, offset).done(dfr.resolve).fail(dfr.reject);
        }).fail(dfr.reject);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  CSVImporter.prototype.__updateStats = function() {
    var i, len, message, ref, ref1, row, row_i, status;
    this.__stats = {
      rows: (ref = this.getRows()) != null ? ref.length : void 0,
      ready: 0,
      invalid: 0,
      processing: 0,
      done: 0,
      failed: 0,
      warning: 0
    };
    ref1 = this.getRows() || [];
    for (row_i = i = 0, len = ref1.length; i < len; row_i = ++i) {
      row = ref1[row_i];
      message = row[this.cf_idx.warning_text];
      if (message) {
        this.__stats.warning++;
      }
      status = row[this.cf_idx.status];
      if (CUI.util.isEmpty(status)) {
        continue;
      }
      if (this.__stats[status] === void 0) {
        this.__stats[status] = 0;
      }
      this.__stats[status]++;
    }
    return this.__stats;
  };

  CSVImporter.prototype.resetReadyRows = function() {
    var i, len, ref, row;
    this.__readyRows = null;
    if (this.cf_idx.status) {
      ref = this.getRows();
      for (i = 0, len = ref.length; i < len; i++) {
        row = ref[i];
        row[this.cf_idx.status] = "";
        row[this.cf_idx.operation] = "";
        row[this.cf_idx.status_text] = "";
        row[this.cf_idx.warning_text] = "";
      }
    }
    return this;
  };

  CSVImporter.prototype.collectReadyRows = function() {
    var ex, i, j, k, len, len1, ops, ref, ref1, row, row_i, status;
    this.__readyRows = {
      insert: [],
      update: [],
      "delete": []
    };
    ref = this.getRows();
    for (row_i = i = 0, len = ref.length; i < len; row_i = ++i) {
      row = ref[row_i];
      status = row[this.cf_idx.status];
      if (status !== "ready") {
        continue;
      }
      try {
        ops = JSON.parse(row[this.cf_idx.operation]);
      } catch (error1) {
        ex = error1;
        continue;
      }
      ref1 = ["insert", "update", "delete"];
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        k = ref1[j];
        if (indexOf.call(ops, k) >= 0) {
          this.__readyRows[k].push(row_i);
        }
      }
    }
  };

  CSVImporter.prototype.getRow = function(row_i) {
    return this.__rows[row_i + this.__form_data.csv_header_rows];
  };

  CSVImporter.prototype.getRows = function() {
    var ref;
    return (ref = this.__rows) != null ? ref.slice(this.__form_data.csv_header_rows) : void 0;
  };

  CSVImporter.prototype.getControlRecord = function(row) {
    var cf, i, len, record, ref;
    record = {};
    ref = this.control_fields;
    for (i = 0, len = ref.length; i < len; i++) {
      cf = ref[i];
      record[cf.name] = row[cf.getColIdx()];
    }
    return record;
  };

  CSVImporter.prototype.getSourceRecord = function(row) {
    var csv_field_idx, csv_field_name, i, len, record, ref;
    record = {};
    ref = this.__form_data.csv_field_names;
    for (csv_field_idx = i = 0, len = ref.length; i < len; csv_field_idx = ++i) {
      csv_field_name = ref[csv_field_idx];
      record[csv_field_name] = row[csv_field_idx];
    }
    return record;
  };

  CSVImporter.prototype.getRecord = function(row, opts) {
    var configs, dest_field, i, len, record, ref;
    if (opts == null) {
      opts = {};
    }
    record = {};
    ref = this.dest_fields;
    for (i = 0, len = ref.length; i < len; i++) {
      dest_field = ref[i];
      configs = this.getMappingConfigsForDestinationField(dest_field);
      if (configs.length > 0) {
        dest_field.setRecordValue(record, configs, row, opts);
      }
    }
    return record;
  };

  CSVImporter.prototype.getMappedDestinationFields = function() {
    var configs, dest_field, i, len, mapped_dest_fields, ref;
    mapped_dest_fields = [];
    ref = this.dest_fields;
    for (i = 0, len = ref.length; i < len; i++) {
      dest_field = ref[i];
      configs = this.getMappingConfigsForDestinationField(dest_field);
      if (configs.length > 0) {
        mapped_dest_fields.push(dest_field);
      }
    }
    return mapped_dest_fields;
  };

  CSVImporter.prototype.getDestinationFieldRow = function() {
    return this.__rows[this.__form_data.dest_field_row - 1];
  };

  CSVImporter.prototype.getHeaderRow = function() {
    var ref;
    return (ref = this.__rows) != null ? ref[this.__form_data.header_row - 1] : void 0;
  };

  CSVImporter.prototype.getMappingConfigsForDestinationField = function(destinationField) {
    var col, configs, csv_field_idx, i, indices, len, nestedDepth, row;
    configs = [];
    row = this.getHeaderRow();
    if (row) {
      for (csv_field_idx = i = 0, len = row.length; i < len; csv_field_idx = ++i) {
        col = row[csv_field_idx];
        if (this.__form_data.mapping[csv_field_idx] !== destinationField.getName()) {
          continue;
        }
        nestedDepth = destinationField.getNestedDepth();
        if (nestedDepth > 0) {
          indices = row[csv_field_idx].match(/\[(\d)\]/g);
          if (indices) {
            indices = indices.map((function(_this) {
              return function(val) {
                return val.split('')[1];
              };
            })(this));
          }
        }
        configs.push({
          csv_field_idx: csv_field_idx,
          config: this.__form_data.mapping["custom_" + csv_field_idx],
          indices: indices,
          nestedDepth: nestedDepth
        });
      }
    }
    return configs;
  };

  CSVImporter.prototype.initMapping = function() {
    var cf, cf_indices, config, csv_field_idx, dest_field, i, j, len, len1, name, ref, row;
    row = this.getDestinationFieldRow();
    if (row) {
      this.__form_data.mapping = {};
      cf_indices = (function() {
        var i, len, ref, results;
        ref = this.control_fields;
        results = [];
        for (i = 0, len = ref.length; i < len; i++) {
          cf = ref[i];
          results.push(cf.getColIdx());
        }
        return results;
      }).call(this);
      for (csv_field_idx = i = 0, len = row.length; i < len; csv_field_idx = ++i) {
        name = row[csv_field_idx];
        if (indexOf.call(cf_indices, csv_field_idx) >= 0) {
          continue;
        }
        ref = this.dest_fields;
        for (j = 0, len1 = ref.length; j < len1; j++) {
          dest_field = ref[j];
          if (!dest_field.matchesColumnName(name)) {
            continue;
          }
          config = dest_field.getDefaultConfigFromColumnName(name);
          this.__form_data.mapping[csv_field_idx] = dest_field.getName();
          this.__form_data.mapping["custom_" + csv_field_idx] = config;
        }
      }
    }
    this.__form_data.init_mapping_done = true;
    return this;
  };

  CSVImporter.prototype.getMappingForm = function() {
    var csv_field_idx, csv_field_name, fn, get_cfield, get_dest_options, i, len, mapping_fields, mapping_form, ref;
    if (!this.__csv_data) {
      return new CUI.EmptyLabel({
        text: $$("csv.importer.no_file.placeholder"),
        centered: true
      });
    }
    if (!this.dest_fields.length) {
      return new CUI.EmptyLabel({
        text: $$("csv.importer.no_destination_fields.placeholder"),
        centered: true
      });
    }
    mapping_fields = [];
    get_dest_options = (function(_this) {
      return function() {
        var dest_field, i, len, opts, ref;
        opts = [];
        ref = _this.dest_fields;
        for (i = 0, len = ref.length; i < len; i++) {
          dest_field = ref[i];
          opts.push({
            value: dest_field.getName(),
            text: _this.__form_data.show_localized_names ? dest_field.getLabel() : dest_field.getName(),
            tooltip: {
              text: _this.__form_data.show_localized_names ? dest_field.getName() : dest_field.getLabel()
            }
          });
          opts.sort(function(optionOne, optionTwo) {
            return optionOne.text.localeCompare(optionTwo.text);
          });
        }
        opts.unshift({
          divider: true
        });
        opts.unshift({
          text: $$("csv.importer.mapping.dest_col_name.unmapped"),
          value: null
        });
        return opts;
      };
    })(this);
    get_cfield = (function(_this) {
      return function(col_idx) {
        var cf, i, len, ref;
        ref = _this.control_fields;
        for (i = 0, len = ref.length; i < len; i++) {
          cf = ref[i];
          if (cf.getColIdx() === col_idx) {
            return cf;
          }
        }
        return null;
      };
    })(this);
    ref = this.__form_data.csv_field_names;
    fn = (function(_this) {
      return function(csv_field_idx) {
        var custom_form;
        custom_form = new CUI.Form({
          name: "custom_" + csv_field_idx,
          undo_and_changed_support: false,
          render_as_block: false,
          fields: function() {
            var dest_field;
            dest_field = _this.getDestinationFieldByName(_this.__form_data.mapping[csv_field_idx]);
            if (!dest_field) {
              return [];
            }
            return dest_field.getCustomFields();
          }
        });
        mapping_fields.push({
          type: CUI.Select,
          undo_and_changed_support: false,
          form: {
            label: csv_field_name
          },
          name: "" + csv_field_idx,
          onDataChanged: function(data, df) {
            return custom_form.reload();
          },
          options: get_dest_options
        });
        return mapping_fields.push(custom_form);
      };
    })(this);
    for (csv_field_idx = i = 0, len = ref.length; i < len; csv_field_idx = ++i) {
      csv_field_name = ref[csv_field_idx];
      if (get_cfield(csv_field_idx)) {
        continue;
      }
      fn(csv_field_idx);
      if (this.__form_data.mapping[csv_field_idx] === void 0) {
        this.__form_data.mapping[csv_field_idx] = null;
      }
    }
    mapping_form = new CUI.Form({
      data: this.__form_data.mapping,
      undo_and_changed_support: false,
      maximize_horizontal: true,
      onDataChanged: (function(_this) {
        return function() {
          _this.resetReadyRows();
          _this.updateRecordPreview();
          _this.updateUploadForm();
          _this.updateStatsTable();
          return _this.updateButtons();
        };
      })(this),
      "class": "ez5-csv-importer-mapping",
      fields: mapping_fields
    });
    return mapping_form.start();
  };

  CSVImporter.prototype.getPrepareDataSearchOpts = function() {
    return {};
  };

  CSVImporter.prototype.getMatchExistingValue = function(obj, match_existing) {
    var ex, get_eval_split;
    get_eval_split = (function(_this) {
      return function(key) {
        var idx, part, parts;
        parts = key.split(".");
        idx = 0;
        while (idx < parts.length) {
          part = parts[idx];
          if (part.endsWith("[]") || part.endsWith("[<n>]")) {
            parts[idx] = part.substr(0, part.length - 2);
            parts.splice(idx + 1, 0, '0');
          }
          idx = idx + 1;
        }
        return 'obj["' + parts.join('"]["') + '"]';
      };
    })(this);
    try {
      return eval(get_eval_split(this.getDestinationFieldByName(match_existing).getRecordKeyPath()));
    } catch (error1) {
      ex = error1;
      return null;
    }
  };

  CSVImporter.prototype.getMatchExistingValueFromSearchResponse = function(obj, match_existing) {
    return this.getMatchExistingValue(obj, match_existing);
  };

  CSVImporter.prototype.getDestinationFieldByName = function(name) {
    var dest_field, i, len, parts, ref;
    if (CUI.util.isEmpty(name)) {
      return null;
    }
    parts = name.split("#");
    ref = this.dest_fields;
    for (i = 0, len = ref.length; i < len; i++) {
      dest_field = ref[i];
      if (dest_field.getName() === parts[0]) {
        return dest_field;
      }
      null;
    }
  };

  CSVImporter.prototype.setRowInvalid = function(row, err_loca_key, err_loca_key_attrs) {
    var text;
    text = err_loca_key ? $$(err_loca_key, err_loca_key_attrs) : void 0;
    return this.setRowInvalidWithText(row, text);
  };

  CSVImporter.prototype.setRowInvalidWithText = function(row, statusText) {
    row[this.cf_idx.operation] = null;
    row[this.cf_idx.status] = "invalid";
    if (!CUI.util.isEmpty(statusText)) {
      row[this.cf_idx.status_text] = statusText;
    }
    return this;
  };

  CSVImporter.prototype.supportsDelete = function() {
    return false;
  };

  CSVImporter.prototype.setRowUpdate = function(row, obj) {
    if (this.supportsDelete()) {
      row[this.cf_idx.operation] = JSON.stringify(["update", "delete"]);
    } else {
      row[this.cf_idx.operation] = JSON.stringify(["update"]);
    }
    row[this.cf_idx.status] = "ready";
    row[this.cf_idx.version] = obj._version;
    row[this.cf_idx.id] = obj._id;
    return this;
  };

  CSVImporter.prototype.setRowInsert = function(row) {
    row[this.cf_idx.operation] = JSON.stringify(["insert"]);
    row[this.cf_idx.id] = null;
    row[this.cf_idx.version] = 1;
    row[this.cf_idx.status] = "ready";
    return this;
  };

  CSVImporter.prototype.prepareExistingDataChunk = function(rows) {
    var unique_dest_field;
    unique_dest_field = this.getDestinationFieldByName(this.__form_data.match_existing);
    if (!unique_dest_field) {
      return CUI.resolvedPromise();
    }
    return this.prepareMatchExistingDataChunk(rows);
  };

  CSVImporter.prototype.prepareMatchExistingDataChunk = function(rows) {
    var dfr, found_unique_values, i, len, ot_name, record, row, search, search_next_chunk, search_opts, unique_dest_field, unique_value, unique_values;
    unique_values = {};
    ot_name = this.getObjecttype();
    unique_dest_field = this.getDestinationFieldByName(this.__form_data.match_existing);
    for (i = 0, len = rows.length; i < len; i++) {
      row = rows[i];
      if (row[this.cf_idx.status] === "invalid") {
        continue;
      }
      record = this.getRecord(row);
      unique_value = unique_dest_field.getMatchExistingValue(record, this.__form_data.match_existing);
      if (CUI.util.isEmpty(unique_value)) {
        this.setRowInsert(row);
        continue;
      }
      if (unique_values[unique_value]) {
        this.setRowInvalid(row, "csv.importer.unique_key_duplicate");
        continue;
      }
      unique_values[unique_value] = row;
    }
    if (!Object.keys(unique_values).length) {
      return CUI.resolvedPromise();
    }
    found_unique_values = {};
    search_opts = this.getPrepareDataSearchOpts();
    search_opts.limit = 1000;
    search = unique_dest_field.getMatchExistingSearch(Object.keys(unique_values), this.__form_data.match_existing);
    if (search_opts.search) {
      search_opts.search = search_opts.search.concat(search);
    } else {
      search_opts.search = search;
    }
    search_opts.offset = 0;
    search_next_chunk = (function(_this) {
      return function() {
        return ez5.api.search({
          data: {
            debug: "CSVImporter.prepareMatchExistingDataChunk.offset" + search_opts.offset
          },
          json_data: search_opts
        }).fail(dfr.reject).done(function(data) {
          var j, len1, obj, ref;
          _this.__globalObjectIds = new Set();
          ref = data.objects;
          for (j = 0, len1 = ref.length; j < len1; j++) {
            obj = ref[j];
            if (obj._global_object_id) {
              if (_this.__globalObjectIds.has(obj._global_object_id)) {
                continue;
              }
              _this.__globalObjectIds.add(obj._global_object_id);
            }
            unique_value = unique_dest_field.getMatchExistingValueFromSearchResponse(obj, _this.__form_data.match_existing);
            row = unique_values[unique_value];
            if (!row) {
              console.error("CSVImporter[prepareMatchExistingDataChunk]: No row matched for object:", obj, "Unique Value:", unique_value, "Unique Values:", unique_values);
              continue;
            }
            if (found_unique_values[unique_value]) {
              found_unique_values[unique_value]++;
              _this.setRowInvalid(row, "csv.importer.error.duplicate_rows_found");
              continue;
            }
            if (row[_this.cf_idx.status] !== "ready") {
              _this.setRowUpdate(row, obj[ot_name]);
            }
            found_unique_values[unique_value] = 1;
          }
          if (data.count > data.offset + data.objects.length) {
            search_opts.offset = search_opts.offset + search_opts.limit;
            search_next_chunk();
          } else {
            dfr.resolve();
          }
        });
      };
    })(this);
    dfr = new CUI.Deferred();
    search_next_chunk();
    dfr.fail((function(_this) {
      return function() {
        var j, len1;
        for (j = 0, len1 = rows.length; j < len1; j++) {
          row = rows[j];
          _this.setRowInvalid(row);
        }
      };
    })(this));
    dfr.done((function(_this) {
      return function() {
        for (unique_value in unique_values) {
          row = unique_values[unique_value];
          if (!found_unique_values[unique_value]) {
            _this.setRowInsert(row);
          }
        }
      };
    })(this));
    return dfr.promise();
  };

  CSVImporter.prototype.preparePrimaryKeyDataChunk = function(rows) {
    var easydb_id, easydb_ids, i, len, ot_name, record, row, search_opts, unique_dest_field;
    ot_name = this.getObjecttype();
    unique_dest_field = this.getDestinationFieldByName(this.__form_data.match_existing);
    easydb_ids = {};
    for (i = 0, len = rows.length; i < len; i++) {
      row = rows[i];
      if (row[this.cf_idx.status] === "invalid") {
        continue;
      }
      record = this.getRecord(row);
      if (CUI.util.isEmptyObject(record)) {
        this.setRowInvalid(row, "csv.importer.empty_record");
        continue;
      }
      easydb_id = row[this.cf_idx.id];
      if (easydb_id) {
        if (easydb_ids[easydb_id]) {
          this.setRowInvalid(row, "csv.importer.easydb_id_duplicate");
          continue;
        }
        easydb_ids[easydb_id] = row;
        continue;
      }
      if (!unique_dest_field) {
        this.setRowInsert(row);
        continue;
      }
    }
    if (!Object.keys(easydb_ids).length) {
      return CUI.resolvedPromise();
    }
    search_opts = this.getPrepareDataSearchOpts();
    search_opts.limit = rows.length;
    search_opts.search = [
      {
        type: "in",
        "in": (function() {
          var j, len1, ref, results;
          ref = Object.keys(easydb_ids);
          results = [];
          for (j = 0, len1 = ref.length; j < len1; j++) {
            easydb_id = ref[j];
            results.push(parseInt(easydb_id));
          }
          return results;
        })(),
        fields: [ot_name + "._id"]
      }
    ];
    return ez5.api.search({
      json_data: search_opts
    }).done((function(_this) {
      return function(data) {
        var j, len1, obj, ref, results;
        ref = data.objects;
        for (j = 0, len1 = ref.length; j < len1; j++) {
          obj = ref[j];
          row = easydb_ids[obj[ot_name]._id];
          if (!row) {
            continue;
          }
          _this.setRowUpdate(row, obj[ot_name]);
          delete easydb_ids[obj[ot_name]._id];
        }
        results = [];
        for (easydb_id in easydb_ids) {
          row = easydb_ids[easydb_id];
          results.push(_this.setRowInvalid(row, "csv.importer.easydb_id_not_found"));
        }
        return results;
      };
    })(this)).fail((function(_this) {
      return function() {
        var j, len1, results;
        results = [];
        for (j = 0, len1 = rows.length; j < len1; j++) {
          row = rows[j];
          results.push(_this.setRowInvalid(row));
        }
        return results;
      };
    })(this));
  };

  CSVImporter.prototype.getRecordPreview = function(json) {
    var getContent, getJsonContent, getPreviewContent, getPreviewRow, navi_record_preview, vl_record_preview;
    if (json == null) {
      json = false;
    }
    if (!this.__csv_data) {
      return new CUI.EmptyLabel({
        text: $$("csv.importer.no_file.placeholder"),
        centered: true
      });
    }
    getPreviewRow = (function(_this) {
      return function() {
        var row;
        row = _this.getRow(_this.__form_data.record_preview);
        if (!row) {
          _this.__form_data.record_preview = 0;
          row = _this.getRow(_this.__form_data.record_preview);
        }
        return row;
      };
    })(this);
    if (!getPreviewRow()) {
      return new CUI.EmptyLabel({
        text: $$("csv.importer.error.csv_has_no_rows"),
        centered: true
      });
    }
    getPreviewContent = (function(_this) {
      return function() {
        var content;
        if (json) {
          content = getJsonContent();
        } else {
          content = getContent();
        }
        navi_record_preview.update({
          count: _this.__form_data.csv_rows_count,
          offset: _this.__form_data.record_preview,
          limit: 1
        });
        return content;
      };
    })(this);
    getContent = (function(_this) {
      return function() {
        var data, parent, ref, resultObject, row;
        row = getPreviewRow();
        data = _this.getRecord(row, {
          for_preview: true,
          for_preview_detail: true
        });
        if (CUI.util.isEmpty(data)) {
          return new CUI.EmptyLabel({
            text: $$("csv.importer.error.missing-configuration"),
            centered: true
          });
        }
        data._objecttype = _this.__form_data.objecttype;
        data._format = "full";
        parent = (ref = data[data._objecttype]) != null ? ref._id_parent : void 0;
        if (CUI.util.isPlainObject(parent)) {
          data._path = [parent, data];
        }
        resultObject = new ResultObject();
        resultObject.setData(data);
        resultObject.setMask(_this.__form_data.mask);
        return resultObject.renderDetail("detail", "detail-header", {
          inline_mode: "standard"
        });
      };
    })(this);
    getJsonContent = (function(_this) {
      return function() {
        var blk1, blk2, row;
        row = getPreviewRow();
        blk1 = new CUI.Block({
          text: $$("csv.importer.block.source_record_preview"),
          content: new CUI.ObjectDumper({
            object: _this.getSourceRecord(row),
            do_open: true
          }),
          padded: true
        });
        blk2 = new CUI.Block({
          text: $$("csv.importer.block.record_preview"),
          content: new CUI.ObjectDumper({
            object: _this.getRecord(row, {
              for_preview: true
            }),
            do_open: false
          }),
          padded: true
        });
        return new CUI.HorizontalLayout({
          maximize: true,
          left: {
            content: blk1,
            flexHandle: {
              closable: false,
              hidden: false,
              state_name: "csv-importer-record-preview"
            }
          },
          center: {
            content: blk2
          }
        });
      };
    })(this);
    navi_record_preview = new NavigationToolbar({
      onLoadPage: (function(_this) {
        return function(page) {
          _this.__form_data.record_preview = page;
          return vl_record_preview.replace(getPreviewContent(), "center");
        };
      })(this)
    });
    return vl_record_preview = new CUI.VerticalLayout({
      center: {
        content: getPreviewContent
      },
      bottom: {
        content: navi_record_preview
      }
    });
  };

  CSVImporter.prototype.getMatchExistingField = function() {
    var dest_field, dest_field_name, dest_field_set, field, i, k, len, ref, ref1, selectOptions, set_dest_fields;
    if (!this.dest_fields.length) {
      return;
    }
    field = {
      form: {
        label: $$("csv.importer.output_form.match_existing"),
        hint: $$("csv.importer.output_form.match_existing|hint")
      }
    };
    selectOptions = [];
    set_dest_fields = [];
    ref = this.__form_data.mapping;
    for (k in ref) {
      dest_field_name = ref[k];
      if (k.startsWith("custom_")) {
        continue;
      }
      dest_field = this.getDestinationFieldByName(dest_field_name);
      if (dest_field) {
        set_dest_fields.push(dest_field);
      }
    }
    if (this.__form_data.match_existing) {
      dest_field_set = this.getDestinationFieldByName(this.__form_data.match_existing);
      if (indexOf.call(set_dest_fields, dest_field_set) < 0) {
        this.__form_data.match_existing = null;
      }
    }
    ref1 = this.dest_fields;
    for (i = 0, len = ref1.length; i < len; i++) {
      dest_field = ref1[i];
      dest_field.addToMatchExisting(selectOptions, set_dest_fields);
    }
    if (selectOptions.length === 0) {
      field.type = CUI.Output;
      field.placeholder = $$("csv.importer.output_form.match_existing.no_unique_field");
    } else {
      selectOptions.sort(function(optionOne, optionTwo) {
        return optionOne.text.localeCompare(optionTwo.text);
      });
      selectOptions.unshift({
        text: $$("csv.importer.output_form.match_existing.insert_only"),
        value: null
      });
      field.type = CUI.Select;
      field.options = selectOptions;
      field.name = "match_existing";
    }
    return field;
  };

  CSVImporter.prototype.getOutputSettingFields = function() {
    var chunk_sizes, cs, fields;
    fields = [];
    chunk_sizes = this.getActionChunkSizes();
    fields.push({
      type: CUI.Select,
      form: {
        label: $$("csv.importer.output_form.action_chunk_size")
      },
      options: (function() {
        var i, len, results;
        results = [];
        for (i = 0, len = chunk_sizes.length; i < len; i++) {
          cs = chunk_sizes[i];
          results.push({
            value: cs,
            text: $$("csv.importer.output_form.action_chunk_size.opt", {
              size: cs
            })
          });
        }
        return results;
      })(),
      name: "action_chunk_size"
    });
    fields.push({
      type: CUI.Checkbox,
      form: {
        label: $$("csv.importer.output_form.show_localized_names.label")
      },
      name: "show_localized_names",
      onDataChanged: (function(_this) {
        return function() {
          return _this.updateUploadForm();
        };
      })(this)
    });
    return fields;
  };

  CSVImporter.prototype.getActionChunkSizes = function() {
    return [100, 10, 1];
  };

  CSVImporter.prototype.getReadyRows = function(op) {
    var i, len, ref, row_i, rows;
    rows = [];
    ref = this.__readyRows[op];
    for (i = 0, len = ref.length; i < len; i++) {
      row_i = ref[i];
      rows.push(this.getRow(row_i));
    }
    return rows;
  };

  CSVImporter.prototype.__control_prefix = "easydb|";

  CSVImporter.prototype.__loadCSVData = function() {
    this.__csv_data = new CUI.CSVData();
    ez5.splash.show("csv.importer.loading");
    return this.__csv_data.parse({
      text: this.__csv_text
    }).done((function(_this) {
      return function() {
        _this.__rows = _this.__csv_data.getRows();
        CUI.util.removeFromArray(null, _this.__rows, function(row) {
          return row.join("").trim() === "";
        });
        return _this.reloadFormData();
      };
    })(this)).always((function(_this) {
      return function() {
        return ez5.splash.hide();
      };
    })(this));
  };

  CSVImporter.prototype.reloadFormData = function() {
    var cf, col_idx, col_name, controlIndex, controlName, controlNames, header_row, i, idx, index, j, l, len, len1, len2, len3, len4, len5, m, map, n, o, p, ref, ref1, ref2, ref3, ref4, ref5, row, txt;
    if (!this.__csv_data) {
      return this.updateModal();
    }
    this.dest_fields = this.getDestinationFields();
    this.dest_fields.sort(function(a, b) {
      return a.getLabel().localeCompare(b.getLabel());
    });
    this.control_fields = this.getControlFields();
    if (this.__form_data.header_row >= 2 || this.__form_data.dest_field_row >= 2) {
      this.__form_data.csv_header_rows = 2;
    } else if (this.__form_data.header_row >= 1 || this.__form_data.dest_field_row >= 1) {
      this.__form_data.csv_header_rows = 1;
    } else {
      this.__form_data.csv_header_rows = 0;
    }
    this.__form_data.csv_rows_count = Math.max(0, this.__rows.length - this.__form_data.csv_header_rows);
    if (this.__form_data.header_row > 0) {
      header_row = this.__form_data.header_row - 1;
      map = {};
      ref = this.control_fields;
      for (i = 0, len = ref.length; i < len; i++) {
        cf = ref[i];
        ref1 = this.__rows[header_row];
        for (col_idx = j = 0, len1 = ref1.length; j < len1; col_idx = ++j) {
          col_name = ref1[col_idx];
          if (col_name !== this.__control_prefix + cf.getName()) {
            continue;
          }
          map[cf.getName()] = cf;
          cf.setColIdx(col_idx);
        }
      }
      controlNames = [];
      ref2 = this.control_fields;
      for (l = 0, len2 = ref2.length; l < len2; l++) {
        cf = ref2[l];
        controlNames.push(cf.getName());
        if (map[cf.getName()]) {
          continue;
        }
        this.__rows[header_row].push(this.__control_prefix + cf.getName());
        map[cf.getName()] = cf;
        cf.setColIdx(this.__rows[header_row].length - 1);
      }
      this.__initControlFieldIndeces();
      this.__csv_data.giveAllRowsSameNumberOfColumns();
      ref3 = this.__rows;
      for (index = m = 0, len3 = ref3.length; m < len3; index = ++m) {
        row = ref3[index];
        if (index === header_row) {
          continue;
        }
        for (n = 0, len4 = controlNames.length; n < len4; n++) {
          controlName = controlNames[n];
          controlIndex = this.cf_idx[controlName];
          row[controlIndex] = "";
        }
      }
      ref4 = this.getRows();
      for (idx = o = 0, len5 = ref4.length; o < len5; idx = ++o) {
        row = ref4[idx];
        row[this.cf_idx.row_idx] = idx;
      }
    }
    if (this.__form_data.dest_field_row && !this.__form_data.init_mapping_done) {
      this.initMapping();
    }
    this.__form_data.csv_field_names = [];
    for (col_idx = p = 0, ref5 = this.__csv_data.getMaxColumnCount(); 0 <= ref5 ? p < ref5 : p > ref5; col_idx = 0 <= ref5 ? ++p : --p) {
      txt = null;
      if (this.__form_data.header_row) {
        txt = this.__rows[this.__form_data.header_row - 1][col_idx];
      }
      if (CUI.util.isEmpty(txt)) {
        txt = "Column " + (col_idx + 1);
      }
      this.__form_data.csv_field_names.push(txt);
    }
    this.resetReadyRows();
    this.updateModal();
  };

  CSVImporter.prototype.getUploadForm = function() {
    var csv_btn, csv_upload, dest_field_row_opts, fields, fr, header_row_opts, i, k, len, ref, ret, update_form;
    fr = new CUI.FileReader({
      onDone: (function(_this) {
        return function(frf) {
          _this.__form_data.csv_filename = frf.getFile().name;
          _this.loadSettings().always(function() {
            _this.__csv_text = frf.getResult();
            return _this.__loadCSVData();
          });
        };
      })(this)
    });
    if (!this.__csv_data) {
      csv_btn = new CUI.FileUploadButton({
        fileUpload: fr,
        text: $$("csv.importer.button.upload"),
        icon: "upload",
        accept: ".csv,.txt,.text,text/plain,/text/csv",
        multiple: false
      });
      csv_upload = {
        form: {
          label: $$("csv.importer.form.file")
        },
        type: CUI.DataFieldProxy,
        element: csv_btn.DOM
      };
    } else {
      csv_upload = {
        form: {
          label: $$("csv.importer.form.file")
        },
        type: CUI.Output,
        multiline: false,
        name: "csv_filename",
        onDataChanged: (function(_this) {
          return function() {
            return _this.resetFile();
          };
        })(this),
        allow_delete: true
      };
    }
    header_row_opts = [];
    dest_field_row_opts = [];
    ref = [0, 1, 2];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      header_row_opts.push({
        text: $$("csv.importer.form.header_row.option." + k),
        value: k
      });
      dest_field_row_opts.push({
        text: $$("csv.importer.form.dest_field_row.option." + k),
        value: k
      });
    }
    fields = [
      csv_upload, {
        form: {
          label: $$("csv.importer.form.header_row")
        },
        type: CUI.Select,
        disabled: this.__form_data.header_row > 0,
        name: "header_row",
        options: header_row_opts
      }, {
        form: {
          label: $$("csv.importer.form.dest_field_row")
        },
        type: CUI.Select,
        onDataChanged: (function(_this) {
          return function() {
            return _this.__form_data.init_mapping_done = false;
          };
        })(this),
        name: "dest_field_row",
        options: dest_field_row_opts
      }
    ];
    this.__upload_form_vl = new CUI.VerticalLayout({
      center: {
        "class": "ez5-csv-importer-upload"
      }
    });
    update_form = (function(_this) {
      return function() {
        var form;
        form = new CUI.Form({
          padded: true,
          maximize_horizontal: true,
          undo_and_changed_support: false,
          data: _this.__form_data,
          onDataChanged: function() {
            return _this.reloadFormData();
          },
          fields: fields
        });
        _this.__upload_form_vl.replace(form.start(), "center");
        return _this.updateStatsTable();
      };
    })(this);
    ret = this.getOutputSettingFields();
    if (CUI.util.isPromise(ret)) {
      ret.done((function(_this) {
        return function(_fields) {
          fields.push.apply(fields, _fields);
          return update_form();
        };
      })(this));
      ret.fail(update_form);
    } else {
      fields.push.apply(fields, ret);
      update_form();
    }
    return this.__upload_form_vl;
  };

  CSVImporter.prototype.getStatsForm = function() {
    this.__stats_form_vl = new CUI.VerticalLayout({
      center: {
        "class": "ez5-csv-importer-stats"
      }
    });
    this.updateStatsTable();
    return this.__stats_form_vl;
  };

  CSVImporter.prototype.updateStatsTable = function() {
    var add_row, k, ref, ref1, ref2, rows, table, v;
    if (!this.__csv_data) {
      if ((ref = this.__stats_form_vl) != null) {
        ref.replace(new CUI.EmptyLabel({
          text: $$("csv.importer.no_file.placeholder"),
          centered: true
        }), "center");
      }
      return;
    }
    this.__updateStats();
    rows = [];
    add_row = (function(_this) {
      return function(key, value) {
        var btn, row, tt;
        tt = ez5.loca.str_default("csv.importer.info.tooltip." + key);
        if (tt) {
          btn = new CUI.Button({
            icon: "info",
            appearance: "flat",
            onClick: function() {
              return new ez5.HintPopover({
                element: btn,
                text: tt
              }).show();
            }
          });
        }
        row = {
          info: btn,
          name: $$("csv.importer.info.key." + key),
          value: value
        };
        if (!CUI.util.isUndef(_this.__statusFilters[key])) {
          row.statusFilterCheckbox = new CUI.Checkbox({
            name: key,
            data: _this.__statusFilters,
            group: "statusFilters",
            onDataChanged: function() {
              return _this.__table_preview_tab.setContent(_this.getTablePreview());
            }
          }).start();
        }
        return rows.push(row);
      };
    })(this);
    ref1 = this.__stats;
    for (k in ref1) {
      v = ref1[k];
      add_row(k, v);
    }
    if (this.__readyRows) {
      ref2 = this.__readyRows;
      for (k in ref2) {
        v = ref2[k];
        add_row(k, v.length);
      }
    }
    table = new CUI.Table({
      columns: [
        {
          name: "info",
          text: " "
        }, {
          name: "name",
          text: $$("csv.importer.info-table.header.status")
        }, {
          name: "value",
          text: $$("csv.importer.info-table.header.quantity")
        }, {
          name: "statusFilterCheckbox",
          text: $$("csv.importer.info-table.header.show")
        }
      ],
      header: true,
      rows: rows
    });
    return this.__stats_form_vl.replace(table, "center");
  };

  CSVImporter.prototype.updateModal = function() {
    this.updateUploadForm();
    this.__table_preview_tab.setContent(this.getTablePreview());
    this.__mapping_tab.setContent(this.getMappingForm());
    this.updateRecordPreview();
    this.updateStatsTable();
    return this.updateButtons();
  };

  CSVImporter.prototype.updateUploadForm = function() {
    return this.__upload_tab.setContent(this.getUploadForm());
  };

  CSVImporter.prototype.getReadyForPrepare = function() {
    if (!this.__csv_data) {
      return CUI.rejectedPromise("csv.importer.required.fields.file");
    }
    if (this.__form_data.header_row === 0) {
      return CUI.rejectedPromise("csv.importer.required.fields.fieldname");
    }
    if (!(this.__form_data.header_row > 0 && this.dest_fields.length > 0)) {
      return CUI.rejectedPromise();
    }
    return this.callOnMappedDestFields((function(_this) {
      return function(dest_field, configs) {
        return dest_field.getReadyForPrepare(configs);
      };
    })(this));
  };

  CSVImporter.prototype.callOnMappedDestFields = function(func) {
    var dfr, idx, next_dest_field;
    dfr = new CUI.Deferred();
    idx = -1;
    next_dest_field = (function(_this) {
      return function() {
        var configs, dest_field, ret;
        while (true) {
          idx = idx + 1;
          if (idx === _this.dest_fields.length) {
            dfr.resolve();
            return;
          }
          dest_field = _this.dest_fields[idx];
          configs = _this.getMappingConfigsForDestinationField(dest_field);
          if (configs.length > 0) {
            break;
          }
        }
        ret = func.call(_this, dest_field, configs);
        if (CUI.util.isPromise(ret)) {
          ret.done(next_dest_field);
          return ret.fail(dfr.reject);
        } else {
          return next_dest_field();
        }
      };
    })(this);
    next_dest_field();
    return dfr.promise();
  };

  CSVImporter.prototype.readyForImport = function() {
    return !!this.__readyRows;
  };

  CSVImporter.prototype.updateButtons = function() {
    var action_done, action_fail, buttons, buttons_done, buttons_left, deletes, disabled, fileUploadReader, inserts, last_ev, tooltip, update_view, updates;
    last_ev = null;
    action_done = (function(_this) {
      return function() {
        var confirmMessage;
        if (last_ev.hasModifierKey()) {
          update_view();
          return;
        }
        if (_this.__stats.failed > 0) {
          confirmMessage = $$("csv.importer.action_done_with_errors.message");
        } else {
          confirmMessage = $$("csv.importer.action_done.message");
        }
        return CUI.confirm({
          text: confirmMessage,
          button_text_ok: $$("csv.importer.action_done.button.save_csv"),
          button_text_cancel: $$("csv.importer.action_done.button.done"),
          button_primary: "ok"
        }).always(function() {
          return update_view();
        }).done(function() {
          return _this.saveCSV();
        });
      };
    })(this);
    action_fail = (function(_this) {
      return function(message) {
        if (CUI.util.isString(message)) {
          CUI.alert({
            text: message
          });
        }
        return update_view();
      };
    })(this);
    update_view = (function(_this) {
      return function() {
        _this.collectReadyRows();
        _this.updateStatsTable();
        return _this.updateButtons();
      };
    })(this);
    buttons_done = (function(_this) {
      return function() {
        return _this.__modal.replace(buttons, "footer_right");
      };
    })(this);
    if (this.readyForImport()) {
      updates = this.__readyRows.update.length;
      inserts = this.__readyRows.insert.length;
      deletes = this.__readyRows["delete"].length;
      buttons = [
        deletes > 0 ? {
          loca_key: "csv.importer.button.delete",
          onClick: (function(_this) {
            return function(ev, btn) {
              last_ev = ev;
              return _this.__action(ev, "delete").done(action_done).fail(action_fail);
            };
          })(this)
        } : void 0, inserts > 0 ? {
          loca_key: "csv.importer.button.insert",
          onClick: (function(_this) {
            return function(ev, btn) {
              last_ev = ev;
              return _this.__action(ev, "insert").done(action_done).fail(action_fail);
            };
          })(this)
        } : void 0, updates > 0 ? {
          loca_key: "csv.importer.button.update",
          onClick: (function(_this) {
            return function(ev, btn) {
              last_ev = ev;
              return _this.__action(ev, "update").done(action_done).fail(action_fail);
            };
          })(this)
        } : void 0, updates > 0 && inserts > 0 ? {
          loca_key: "csv.importer.button.sync",
          onClick: (function(_this) {
            return function(ev, btn) {
              last_ev = ev;
              return _this.__action(ev, "insert").done(function() {
                return _this.__action(ev, "update").done(action_done).fail(action_fail);
              }).fail(action_fail);
            };
          })(this)
        } : void 0
      ];
      buttons_done();
    } else {
      disabled = true;
      tooltip = null;
      buttons = [];
      this.getReadyForPrepare().done((function(_this) {
        return function() {
          return disabled = false;
        };
      })(this)).fail((function(_this) {
        return function(errorLocaKeyOrLabel, loca_key_attrs) {
          var errorLabel;
          if (loca_key_attrs == null) {
            loca_key_attrs = {};
          }
          if (errorLocaKeyOrLabel) {
            if (errorLocaKeyOrLabel instanceof CUI.Label) {
              errorLabel = errorLocaKeyOrLabel;
            } else {
              errorLabel = new LocaLabel({
                "class": "ez5-csv-importer-prepare-data-error",
                icon: "warning",
                loca_key: errorLocaKeyOrLabel,
                loca_key_attrs: loca_key_attrs
              });
            }
            buttons = [errorLabel];
          }
        };
      })(this)).always((function(_this) {
        return function() {
          buttons.push.apply(buttons, [
            {
              loca_key: "csv.importer.button.prepare",
              disabled: disabled,
              onClick: function(ev, btn) {
                return _this.saveSettings().done(function() {
                  return _this.__prepareData().fail(function(err_loca_key) {
                    if (CUI.util.isString(err_loca_key)) {
                      return CUI.problem({
                        text: $$(err_loca_key)
                      });
                    }
                  }).done(function() {
                    var count, i, key, len, ref;
                    count = 0;
                    ref = ["update", "insert", "delete"];
                    for (i = 0, len = ref.length; i < len; i++) {
                      key = ref[i];
                      count += _this.__readyRows[key].length;
                    }
                    if (count === 0) {
                      return CUI.problem({
                        text: $$("csv.importer.error.no_action_rows_found")
                      });
                    }
                  }).always(function() {
                    var alertText;
                    _this.updateModal();
                    if (_this.__stats.warning > 0) {
                      alertText = $$("csv.importer.warning_text.message.alert");
                    }
                    if (_this.__stats.invalid > 0) {
                      alertText = $$("csv.importer.invalid_text.message.alert");
                    }
                    if (alertText) {
                      CUI.confirm({
                        text: alertText,
                        button_text_ok: $$("cui.confirmation.choice.ok"),
                        button_text_cancel: $$("csv.importer.action_done.button.save_csv"),
                        button_primary: "ok"
                      }).fail(function() {
                        return _this.saveCSV();
                      });
                    }
                  });
                });
              }
            }
          ]);
          return buttons_done();
        };
      })(this));
    }
    fileUploadReader = new CUI.FileReader({
      onDone: (function(_this) {
        return function(frf) {
          var error, result, settings;
          try {
            result = JSON.parse(frf.getResult());
            settings = result.settings;
          } catch (error1) {
            error = true;
          }
          if (error || CUI.util.isEmpty(settings)) {
            CUI.problem({
              text: $$("csv.importer.button.upload_settings.wrong-format-message")
            });
            return;
          }
          if (error = _this.isImportSettingsValid(result)) {
            CUI.problem({
              text: error
            });
            return;
          }
          _this.__setingsUploadedText.setText(frf.getFile().name);
          _this.loadSettings(settings, true).done(function() {
            var invalidMappingRemoved, warnings;
            warnings = _this.getImportSettingsWarnings(result) || [];
            if (CUI.util.isString(warnings)) {
              warnings = [warnings];
            }
            invalidMappingRemoved = _this.__removeInvalidMapping();
            if (invalidMappingRemoved) {
              warnings.push($$("csv.importer.button.upload_settings.warning-message"));
            }
            _this.reloadFormData();
            if (warnings.length > 0) {
              return CUI.problem({
                text: $$("csv.importer.button.upload_settings.done-warning-message", {
                  warnings: warnings
                }),
                markdown: true
              });
            } else {
              return CUI.alert({
                text: $$("csv.importer.button.upload_settings.done-message")
              });
            }
          });
        };
      })(this)
    });
    buttons_left = [
      {
        loca_key: "csv.importer.button.reload",
        disabled: !this.__csv_data,
        onClick: (function(_this) {
          return function() {
            _this.resetData();
            _this.__loadCSVData();
            return _this.initMapping();
          };
        })(this)
      }, {
        loca_key: "csv.importer.button.csv_save",
        disabled: !this.__csv_data,
        onClick: (function(_this) {
          return function() {
            return _this.saveCSV();
          };
        })(this)
      }, {
        icon: CUI.Icon.icon_map.settings,
        menu: {
          items: [
            {
              loca_key: "csv.importer.button.download_settings",
              disabled: !this.__csv_data,
              onClick: (function(_this) {
                return function() {
                  var jsonSettings;
                  jsonSettings = {
                    __EASYDB_CSV_IMPORTER_SETTINGS: true,
                    version: 2,
                    settings: _this.getFormSaveData(true)
                  };
                  _this.addDownloadExtraSettings(jsonSettings);
                  return CUI.FileReader.save(ez5.session.getEasydbName() + "-" + _this.__form_data.csv_filename + "-csv_importer_settings.json", JSON.stringify(jsonSettings, null, "    "));
                };
              })(this)
            }, new CUI.FileUploadButton({
              disabled: !this.__csv_data,
              fileUpload: fileUploadReader,
              text: $$("csv.importer.button.upload_settings|text"),
              icon: $$("csv.importer.button.upload_settings|icon"),
              accept: ".json,application/json",
              multiple: false
            })
          ]
        }
      }
    ];
    this.__modal.replace(buttons_left, "footer_left");
    this.__modal.append(this.__setingsUploadedText, "footer_left");
  };

  CSVImporter.prototype.saveCSV = function() {
    var csv_text, protocollCsvName;
    csv_text = this.__csv_data.toText();
    protocollCsvName = this.__form_data.csv_filename.replace(/(\.[^.]+)?$/, "_protocoll$1");
    return CUI.FileReader.save(protocollCsvName, csv_text + "\n" + JSON.stringify(this.getFormSaveData()) + "\n");
  };

  CSVImporter.prototype.getSettingsKeyName = function() {
    return "easydb-" + ez5.session.getInstanceGlobalName() + "-" + CUI.util.toDash(this.getElementClass());
  };

  CSVImporter.prototype.__getLocalStore = function() {
    var localStore, schema, sk;
    sk = this.getSettingsKeyName();
    schema = JSON.stringify(ez5.session.getSchemaInfo());
    localStore = CUI.getLocalStorage(sk) || {};
    if (localStore.schema !== schema) {
      localStore = {
        schema: schema,
        data_per_filename: {}
      };
    }
    return localStore;
  };

  CSVImporter.prototype.__setLocalStore = function(localStore) {
    var sk;
    sk = this.getSettingsKeyName();
    return CUI.setLocalStorage(sk, localStore);
  };

  CSVImporter.prototype.saveSettings = function() {
    var localStore;
    localStore = this.__getLocalStore();
    localStore.data_per_filename[this.__form_data.csv_filename] = this.getFormSaveData();
    this.__setLocalStore(localStore);
    return CUI.resolvedPromise();
  };

  CSVImporter.prototype.loadSettings = function(settings, fromFile) {
    var headerRow, index, isCustom, k, key, keySplitted, localStore, mapping, newMapping, v, value;
    if (fromFile == null) {
      fromFile = false;
    }
    if (!settings) {
      localStore = this.__getLocalStore();
      settings = localStore.data_per_filename[this.__form_data.csv_filename];
      if (!settings) {
        CUI.rejectedPromise();
      }
    }
    for (k in settings) {
      v = settings[k];
      this.__form_data[k] = v;
    }
    mapping = this.__form_data.mapping;
    if (mapping && fromFile) {
      newMapping = {};
      headerRow = this.getHeaderRow();
      if (headerRow) {
        for (key in mapping) {
          value = mapping[key];
          keySplitted = typeof key.split === "function" ? key.split("custom_") : void 0;
          isCustom = !!keySplitted[1];
          key = keySplitted[1] || key;
          index = headerRow.indexOf(key);
          if (isCustom) {
            newMapping["custom_" + index] = value;
          } else {
            newMapping["" + index] = value;
          }
        }
      } else {
        index = 0;
        for (key in mapping) {
          value = mapping[key];
          if (typeof key.startsWith === "function" ? key.startsWith("custom_") : void 0) {
            newMapping["custom_" + index] = value;
          } else {
            newMapping["" + index] = value;
          }
          index++;
        }
      }
      this.__form_data.mapping = newMapping;
    }
    this.__form_data.init_mapping_done = true;
    return CUI.resolvedPromise();
  };

  CSVImporter.prototype.getFormSaveData = function(forDownload) {
    var columnIndex, columnText, headerRow, i, index, indexSplitted, isCustom, key, len, mapping, mappingData, ref, saveData, value;
    if (forDownload == null) {
      forDownload = false;
    }
    saveData = {};
    ref = ["control_fields_warning_shown", "match_existing", "dest_field_row", "header_row", "action_chunk_size"];
    for (i = 0, len = ref.length; i < len; i++) {
      key = ref[i];
      saveData[key] = this.__form_data[key];
    }
    mappingData = this.__form_data.mapping;
    headerRow = this.getHeaderRow();
    if (headerRow && forDownload) {
      mapping = {};
      for (index in mappingData) {
        value = mappingData[index];
        indexSplitted = typeof index.split === "function" ? index.split("custom_") : void 0;
        isCustom = !!indexSplitted[1];
        columnIndex = indexSplitted[1] || index;
        columnIndex = parseInt(columnIndex);
        columnText = headerRow[columnIndex];
        if (!columnText) {
          continue;
        }
        if (isCustom) {
          mapping["custom_" + columnText] = value;
        } else {
          mapping[columnText] = value;
        }
      }
      saveData.mapping = mapping;
    } else {
      saveData.mapping = mappingData;
    }
    return saveData;
  };

  CSVImporter.prototype.resetInitMapping = function() {
    return this.__form_data.init_mapping_done = false;
  };

  CSVImporter.prototype.updateRecordPreview = function() {
    return this.__json_record_preview_tab.setContent(this.getRecordPreview(true));
  };

  CSVImporter.prototype.getTablePreview = function() {
    var get_table, navi_table_preview, vl_table_preview;
    if (!this.__csv_data) {
      return new CUI.EmptyLabel({
        text: $$("csv.importer.no_file.placeholder"),
        centered: true
      });
    }
    get_table = (function(_this) {
      return function() {
        var col_idx, columns, field_name, i, len, operationColumnIndex, operationFieldName, ref, rows, statusColumnIndex, statusFieldName, warningFieldName;
        columns = [];
        statusFieldName = _this.__control_prefix + "status";
        operationFieldName = _this.__control_prefix + "operation";
        warningFieldName = _this.__control_prefix + "warning_text";
        ref = _this.__form_data.csv_field_names;
        for (col_idx = i = 0, len = ref.length; i < len; col_idx = ++i) {
          field_name = ref[col_idx];
          if (field_name === statusFieldName) {
            statusColumnIndex = col_idx;
          }
          if (field_name === operationFieldName) {
            operationColumnIndex = col_idx;
          }
          columns.push({
            name: "" + col_idx,
            text: field_name
          });
        }
        rows = _this.__rows.filter(function(row) {
          var j, len1, op, operation, operationFilterValue, status, warningFilterValue;
          status = row[statusColumnIndex];
          if (!status) {
            return true;
          }
          operationFilterValue = false;
          try {
            operation = eval(row[operationColumnIndex]);
            if (operation && operation.length > 0) {
              for (j = 0, len1 = operation.length; j < len1; j++) {
                op = operation[j];
                operationFilterValue = _this.__statusFilters[op];
                if (operationFilterValue) {
                  break;
                }
              }
            }
          } catch (error1) {}
          warningFilterValue = false;
          if (!CUI.util.isEmpty(row[warningFieldName])) {
            warningFilterValue = _this.__statusFilters["warning"];
          }
          return _this.__statusFilters[status] || operationFilterValue || warningFilterValue;
        });
        navi_table_preview.update({
          count: rows.length,
          limit: _this.__form_data.table_preview_chunk_size,
          offset: _this.__form_data.preview_offset
        });
        rows = rows.slice(_this.__form_data.preview_offset, _this.__form_data.preview_offset + _this.__form_data.table_preview_chunk_size);
        return new CUI.Table({
          columns: columns,
          rows: rows,
          header: true
        });
      };
    })(this);
    navi_table_preview = new NavigationToolbar({
      onLoadPage: (function(_this) {
        return function(page) {
          _this.__form_data.preview_offset = page * _this.__form_data.table_preview_chunk_size;
          return vl_table_preview.replace(get_table(), "center");
        };
      })(this)
    });
    return vl_table_preview = new CUI.VerticalLayout({
      center: {
        content: get_table
      },
      bottom: {
        content: navi_table_preview
      }
    });
  };

  CSVImporter.prototype.showModal = function() {
    var dfr, extraPreviewTabs, form_tabs, hl, previewTabs, preview_tabs;
    dfr = new CUI.Deferred();
    this.__upload_tab = new CUI.Tab({
      name: "upload_tab",
      text: $$("csv.importer.tab.upload"),
      content: (function(_this) {
        return function() {
          return _this.getUploadForm();
        };
      })(this)
    });
    this.__mapping_tab = new CUI.Tab({
      padded: true,
      name: "mapping_tab",
      text: $$("csv.importer.tab.mapping"),
      content: (function(_this) {
        return function() {
          return _this.getMappingForm();
        };
      })(this)
    });
    this.__stats_tab = new CUI.Tab({
      name: "stats_tab",
      text: $$("csv.importer.tab.stats"),
      content: (function(_this) {
        return function() {
          return _this.getStatsForm();
        };
      })(this)
    });
    form_tabs = new CUI.Tabs({
      tabs: [this.__upload_tab, this.__mapping_tab, this.__stats_tab]
    });
    this.__table_preview_tab = new CUI.Tab({
      name: "table_preview",
      text: $$("csv.importer.tab.table_preview"),
      content: (function(_this) {
        return function() {
          return _this.getTablePreview();
        };
      })(this)
    });
    this.__json_record_preview_tab = new CUI.Tab({
      name: "json_preview",
      text: $$("csv.importer.tab.json_record_preview"),
      content: (function(_this) {
        return function() {
          return _this.getRecordPreview(true);
        };
      })(this)
    });
    extraPreviewTabs = this.getExtraPreviewTabs();
    previewTabs = [this.__table_preview_tab].concat(extraPreviewTabs);
    previewTabs.push(this.__json_record_preview_tab);
    preview_tabs = new CUI.Tabs({
      tabs: previewTabs
    });
    hl = new CUI.HorizontalLayout({
      left: {
        "class": "ez5-csv-importer-left",
        content: form_tabs,
        flexHandle: {
          closable: false,
          state_name: "csv-importer-left"
        }
      },
      center: {
        "class": "ez5-csv-importer-center",
        content: preview_tabs
      }
    });
    this.__modal = new CUI.Modal({
      cancel: true,
      fill_space: "both",
      onHide: (function(_this) {
        return function() {
          return dfr.resolve();
        };
      })(this),
      "class": "ez5-csv-importer-modal",
      pane: {
        header_left: new LocaLabel({
          loca_key: this.getTitleLocaKey()
        }),
        force_footer: true,
        content: hl
      }
    });
    this.updateButtons();
    this.__modal.show();
    return dfr.promise();
  };

  CSVImporter.prototype.getExtraPreviewTabs = function() {
    return [];
  };

  CSVImporter.prototype.getFormData = function() {
    return this.__form_data;
  };

  CSVImporter.prototype.__removeInvalidMapping = function() {
    var headerRow, i, index, invalidMappingRemoved, len, value;
    headerRow = this.getHeaderRow();
    if (!headerRow || !this.__form_data.mapping) {
      return;
    }
    for (index = i = 0, len = headerRow.length; i < len; index = ++i) {
      value = headerRow[index];
      if (!value.startsWith(this.__control_prefix)) {
        continue;
      }
      delete this.__form_data.mapping[index];
      delete this.__form_data.mapping["custom_" + index];
    }
    invalidMappingRemoved = false;
    for (index in this.__form_data.mapping) {
      if (index.startsWith("custom_")) {
        continue;
      }
      if (headerRow[index] && !headerRow[index].startsWith(this.__control_prefix)) {
        continue;
      }
      invalidMappingRemoved = true;
      delete this.__form_data.mapping[index];
      delete this.__form_data.mapping["custom_" + index];
    }
    return invalidMappingRemoved;
  };

  CSVImporter.prototype.__addRecordsToReport = function(records, op) {};

  CSVImporter.prototype.addDownloadExtraSettings = function(jsonSettings) {};

  CSVImporter.prototype.isImportSettingsValid = function(jsonSettings) {
    return false;
  };

  CSVImporter.prototype.getImportSettingsWarnings = function(jsonSettings) {
    return [];
  };

  return CSVImporter;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var CSVImporterMenuApp,
  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;

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

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

  CSVImporterMenuApp.click = function() {
    var importer;
    ez5.rootMenu.closeMenu();
    if (ez5.session.isReadOnly()) {
      CUI.alert({
        text: $$("base.error.user.read_only_mode")
      });
      return;
    }
    importer = new ObjecttypeCSVImporter();
    return importer.start();
  };

  CSVImporterMenuApp.label = function() {
    return "main.list.extra.upload_csv|text";
  };

  CSVImporterMenuApp.is_allowed = function() {
    return ez5.session.hasSystemRight("root", "frontend_features[csv_importer]");
  };

  CSVImporterMenuApp.group = function() {
    return "za_importer";
  };

  CSVImporterMenuApp.submenu = function() {
    return "plugins";
  };

  CSVImporterMenuApp.isStartApp = function() {
    return false;
  };

  return CSVImporterMenuApp;

})(RootMenuApp);

ez5.session_ready(function() {
  return ez5.rootMenu.registerApp(CSVImporterMenuApp);
});
// Generated by CoffeeScript 1.12.7
var CSVImporterField,
  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;

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

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

  CSVImporterField.prototype.initOpts = function() {
    CSVImporterField.__super__.initOpts.call(this);
    return this.addOpts({
      name: {
        check: String,
        mandatory: true
      },
      format: {
        mandatory: true,
        "default": "string",
        check: String
      }
    });
  };

  CSVImporterField.prototype.getName = function() {
    return this._name;
  };

  CSVImporterField.prototype.getFormat = function() {
    return this._format;
  };

  return CSVImporterField;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var CSVImporterControlField,
  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;

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

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

  CSVImporterControlField.prototype.setColIdx = function(__col_idx) {
    this.__col_idx = __col_idx;
  };

  CSVImporterControlField.prototype.getColIdx = function() {
    return this.__col_idx;
  };

  return CSVImporterControlField;

})(CSVImporterField);
// Generated by CoffeeScript 1.12.7
var CSVImporterDestinationField,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function CSVImporterDestinationField(opts1) {
    var _idx, arr_idx, idx, j, key, key_name, len, m, part, ref;
    this.opts = opts1 != null ? opts1 : {};
    this.csvData = new CUI.CSVData();
    CSVImporterDestinationField.__super__.constructor.call(this, this.opts);
    key = this.getRecordKeyPath();
    this.__key_parts = [];
    this.__key_part_idx_is_array = [];
    ref = key.split(".");
    for (idx = j = 0, len = ref.length; j < len; idx = ++j) {
      part = ref[idx];
      m = part.match(/(.*?)(?:|\[([0-9]*)\])$/);
      key_name = m[1];
      arr_idx = m[2];
      if (arr_idx === void 0) {
        this.__key_parts.push({
          key: key_name,
          type: "map"
        });
        continue;
      }
      this.__key_parts.push({
        key: key_name,
        type: "array"
      });
      if (arr_idx === "") {
        this.__key_part_idx_is_array.push(this.__key_parts.length);
        _idx = null;
      } else {
        _idx = parseInt(arr_idx);
      }
      this.__key_parts.push({
        key: _idx,
        type: "map"
      });
    }
    this.__nested_depth = this.__key_part_idx_is_array.length;
    return;
  }

  CSVImporterDestinationField.prototype.initOpts = function() {
    CSVImporterDestinationField.__super__.initOpts.call(this);
    return this.addOpts({
      csvImporter: {
        mandatory: true,
        check: CSVImporter
      },
      use_for_match_existing: {
        mandatory: true,
        "default": false,
        check: Boolean
      },
      label: {
        check: String
      }
    });
  };

  CSVImporterDestinationField.prototype.addToMatchExisting = function(select_opts, set_dest_fields) {
    var disabled, text, tooltipText;
    if (!this.useForMatchExisting()) {
      return;
    }
    if (indexOf.call(set_dest_fields, this) < 0) {
      disabled = true;
    } else {
      disabled = false;
    }
    text = this._csvImporter.getFormData().show_localized_names ? this.getLabel() : this.getName();
    tooltipText = this._csvImporter.getFormData().show_localized_names ? this.getName() : this.getLabel();
    select_opts.push({
      text: text,
      disabled: disabled,
      value: this.getName(),
      tooltip: {
        text: tooltipText
      }
    });
  };

  CSVImporterDestinationField.prototype.getNestedDepth = function() {
    return this.__nested_depth;
  };

  CSVImporterDestinationField.prototype.getColumnNames = function() {
    return [this.getName()];
  };

  CSVImporterDestinationField.prototype.getLabel = function() {
    return this._label || this.getName();
  };

  CSVImporterDestinationField.prototype.getRecordKeyPath = function() {
    return this.getName();
  };

  CSVImporterDestinationField.prototype.getRecordKeyPathForSearch = function() {
    return this.getRecordKeyPath();
  };

  CSVImporterDestinationField.prototype.beforePrepareData = function(config, rows) {};

  CSVImporterDestinationField.prototype.prepareDataChunk = function(configs, rows) {};

  CSVImporterDestinationField.prototype.getReadyForPrepare = function(configs) {};

  CSVImporterDestinationField.prototype.action = function(ev, op, rows) {};

  CSVImporterDestinationField.prototype.matchesColumnName = function(name) {
    var check_name, j, len, n, ref;
    if (CUI.util.isEmpty(name)) {
      return false;
    }
    check_name = name.split("#")[0];
    if (this.getNestedDepth() > 0) {
      check_name = check_name.replace(/\[\d]/g, "[]");
    }
    ref = this.getColumnNames();
    for (j = 0, len = ref.length; j < len; j++) {
      n = ref[j];
      n = n.replace(/\[<n>]/g, "[]");
      if (n === check_name) {
        return true;
      }
    }
    return false;
  };

  CSVImporterDestinationField.prototype.getDefaultConfigFromColumnName = function(name) {
    var cf, config, idx, j, len, parts, ref;
    if (!this.matchesColumnName(name)) {
      return null;
    }
    if (CUI.util.isEmpty(name)) {
      return null;
    }
    parts = name.split("#");
    config = {};
    ref = this.getCustomFields();
    for (idx = j = 0, len = ref.length; j < len; idx = ++j) {
      cf = ref[idx];
      config[cf.name] = this.getValueForCustom(cf.name, parts[idx + 1]);
    }
    return config;
  };

  CSVImporterDestinationField.prototype.setRecordValue = function(record, configs, row, opts) {
    var defaultIndices, index, indexValueInArray, indices, j, k, key_parts, l, len, len1, len2, ref, set_value, sourceValue, sourceValueIndex, useSpecifiedIndices, value, valueInArray;
    if (opts == null) {
      opts = {};
    }
    sourceValue = this.getRecordValue(configs, row, opts);
    key_parts = CUI.util.copyObject(this.__key_parts, true);
    if (sourceValue === void 0) {
      return;
    }
    set_value = (function(_this) {
      return function(record, value, indices, set_empty_array) {
        var data, i, idx, index, j, k, l, len, len1, part, ref;
        if (set_empty_array == null) {
          set_empty_array = false;
        }
        if (_this.getNestedDepth() > 0 && !set_empty_array) {
          CUI.util.assert(_this.getNestedDepth() === indices.length, "CSVImporterDestinationField.eval", "indices length must match nested depth.");
          for (idx = j = 0, len = indices.length; j < len; idx = ++j) {
            index = indices[idx];
            key_parts[_this.__key_part_idx_is_array[idx]].key = index;
          }
        }
        data = record;
        for (idx = k = 0, len1 = key_parts.length; k < len1; idx = ++k) {
          part = key_parts[idx];
          if (key_parts.length - 2 === idx && set_empty_array) {
            return;
          }
          if (key_parts.length - 1 === idx) {
            data[part.key] = value;
            return;
          }
          if (!data[part.key]) {
            if (part.type === "map") {
              if (CUI.util.isArray(data) && CUI.util.isNumber(part.key)) {
                if (data.length < part.key) {
                  for (i = l = 0, ref = part.key; 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) {
                    if (data[i]) {
                      continue;
                    }
                    data[i] = {};
                  }
                }
              }
              data = data[part.key] = {};
            } else {
              data = data[part.key] = [];
            }
          } else {
            data = data[part.key];
          }
        }
      };
    })(this);
    if (this.getNestedDepth() > 0) {
      if (!CUI.util.isArray(sourceValue)) {
        console.error("CSVImporterDestinationField.setRecordValue", "getRecordValue needs to return an Array: " + this.getRecordKeyPath(), {
          key: key_parts,
          nested_depth: this.getNestedDepth()
        });
        return;
      }
      if (sourceValue.length === 0) {
        set_value(record, void 0, void 0, true);
        return;
      }
      if (this.getNestedDepth() === 1) {
        for (index = j = 0, len = sourceValue.length; j < len; index = ++j) {
          value = sourceValue[index];
          set_value(record, value, [index]);
        }
      } else {
        defaultIndices = (function() {
          var k, ref, results;
          results = [];
          for (k = 0, ref = this.getNestedDepth() - 2; 0 <= ref ? k <= ref : k >= ref; 0 <= ref ? k++ : k--) {
            results.push(0);
          }
          return results;
        }).call(this);
        useSpecifiedIndices = false;
        for (sourceValueIndex = k = 0, len1 = sourceValue.length; k < len1; sourceValueIndex = ++k) {
          value = sourceValue[sourceValueIndex];
          indices = (ref = configs[sourceValueIndex]) != null ? ref.indices : void 0;
          if (CUI.util.isArray(indices) && indices.length === this.getNestedDepth() - 1) {
            indices = indices.map((function(_this) {
              return function(idx) {
                return parseInt(idx);
              };
            })(this));
          } else if (CUI.util.isArray(indices) && indices.length === this.getNestedDepth() && !CUI.util.isArray(value)) {
            useSpecifiedIndices = true;
            indices = indices.map((function(_this) {
              return function(idx) {
                return parseInt(idx);
              };
            })(this));
          } else {
            indices = defaultIndices;
          }
          if (CUI.util.isArray(value)) {
            for (indexValueInArray = l = 0, len2 = value.length; l < len2; indexValueInArray = ++l) {
              valueInArray = value[indexValueInArray];
              set_value(record, valueInArray, indices.concat(indexValueInArray));
            }
          } else {
            if (!useSpecifiedIndices) {
              indices = indices.concat(sourceValueIndex);
            }
            set_value(record, value, indices);
          }
        }
      }
    } else {
      set_value(record, sourceValue);
    }
  };

  CSVImporterDestinationField.prototype.getRecordValue = function(configs, row, opts) {
    var __row, _row, _value, _values, config, hasSpecificIndex, info, j, k, l, len, len1, len2, len3, nestedDepth, o, ref, ref1, ref2, ret_values, value, values, valuesFormatted;
    if (opts == null) {
      opts = {};
    }
    nestedDepth = this.getNestedDepth();
    values = [];
    for (j = 0, len = configs.length; j < len; j++) {
      config = configs[j];
      value = row[config.csv_field_idx];
      if (CUI.util.isUndef(value)) {
        continue;
      }
      hasSpecificIndex = false;
      if (nestedDepth > 0 && ((ref = config.indices) != null ? ref.length : void 0) >= nestedDepth) {
        if (config.indices[nestedDepth - 1]) {
          hasSpecificIndex = true;
        }
      }
      if (nestedDepth > 0 && !hasSpecificIndex) {
        info = this.csvData.parse({
          quotechar: '"',
          delimiter: "",
          text: value,
          defer: false
        });
        _values = [];
        ref1 = info.rows;
        for (k = 0, len1 = ref1.length; k < len1; k++) {
          _row = ref1[k];
          __row = (ref2 = _row[0]) != null ? ref2.trim() : void 0;
          _values.push(__row);
        }
        if (nestedDepth === 1) {
          values = values.concat(_values);
        } else {
          values.push(_values);
        }
      } else {
        values.push(value);
      }
    }
    if (values.length === 0) {
      if (nestedDepth > 0) {
        return [];
      }
      return void 0;
    }
    if (nestedDepth > 0) {
      ret_values = [];
      for (l = 0, len2 = values.length; l < len2; l++) {
        value = values[l];
        if (CUI.util.isArray(value)) {
          valuesFormatted = [];
          for (o = 0, len3 = value.length; o < len3; o++) {
            _value = value[o];
            valuesFormatted.push(this.formatValues([_value], row));
          }
          ret_values.push(valuesFormatted);
        } else {
          ret_values.push(this.formatValues([value], row, opts));
        }
      }
      while (ret_values.length > 0 && CUI.util.isEmpty(ret_values[ret_values.length - 1])) {
        ret_values.pop();
      }
      return ret_values;
    } else {
      return this.formatValues(values, row, opts);
    }
  };

  CSVImporterDestinationField.prototype.formatValues = function(values, row) {
    var data, e, j, k, len, len1, message, number, result, s, v, value;
    switch (this.getFormat()) {
      case "string":
        s = values.join(", ").trim();
        return s;
      case "json":
        data = [];
        for (j = 0, len = values.length; j < len; j++) {
          v = values[j];
          if (CUI.util.isEmpty(v)) {
            continue;
          }
          try {
            data.push(JSON.parse(v));
          } catch (error) {
            e = error;
            row[this._csvImporter.cf_idx.warning_text] = e.message;
            return {
              __error: e.message
            };
          }
        }
        if (data.length === 0) {
          return void 0;
        } else if (data.length === 1) {
          return data[0];
        } else {
          return data;
        }
        break;
      case "boolean":
        v = values.join("");
        if (CUI.util.isEmpty(v)) {
          return void 0;
        } else {
          if (CUI.util.isTrue(v)) {
            return true;
          }
          if (CUI.util.isFalse(v)) {
            return false;
          }
          message = $$("csv.importer.boolean.value-not-boolean.warning_text");
          row[this._csvImporter.cf_idx.warning_text] = message;
          return false;
        }
        break;
      case "number":
        v = values.join("");
        number = parseFloat(v);
        if (isNaN(number)) {
          return void 0;
        } else {
          return number;
        }
        break;
      case "datetime":
        value = CUI.DateTime.format(values[0], "store", "date_time_seconds", true);
        if (value) {
          return value;
        } else {
          return void 0;
        }
        break;
      case "array":
        result = [];
        for (k = 0, len1 = values.length; k < len1; k++) {
          v = values[k];
          result = result.concat(v.split(","));
        }
        return result;
    }
  };

  CSVImporterDestinationField.prototype.getCustomFields = function() {
    return [];
  };

  CSVImporterDestinationField.prototype.getValueForCustom = function(key, value) {
    return value;
  };

  CSVImporterDestinationField.prototype.useForMatchExisting = function() {
    return this._use_for_match_existing;
  };

  CSVImporterDestinationField.prototype.getMatchExistingValue = function(obj, match_existing) {
    return this._csvImporter.getMatchExistingValue(obj, match_existing);
  };

  CSVImporterDestinationField.prototype.getMatchExistingValueFromSearchResponse = function(obj, match_existing) {
    return this._csvImporter.getMatchExistingValueFromSearchResponse(obj, match_existing);
  };

  CSVImporterDestinationField.prototype.fillPrepareDataSearchOpts = function(search_opts) {};

  CSVImporterDestinationField.prototype.getMatchExistingSearch = function(values) {
    var v;
    switch (this.getFormat()) {
      case "number":
        return [
          {
            type: "in",
            "in": (function() {
              var j, len, results;
              results = [];
              for (j = 0, len = values.length; j < len; j++) {
                v = values[j];
                results.push(parseInt(v));
              }
              return results;
            })(),
            fields: [this.getRecordKeyPathForSearch()]
          }
        ];
      default:
        return [
          {
            type: "in",
            "in": values,
            fields: [this.getRecordKeyPathForSearch()]
          }
        ];
    }
  };

  CSVImporterDestinationField.prototype.afterPreparePathData = function(configs, rows) {};

  CSVImporterDestinationField.prototype.hasPrepareError = function(configs) {
    return false;
  };

  return CSVImporterDestinationField;

})(CSVImporterField);
// Generated by CoffeeScript 1.12.7
var ObjecttypeCSVImporter,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  ObjecttypeCSVImporter.prototype.readOpts = function() {
    var dbinfo, objecttypes_dfr;
    ObjecttypeCSVImporter.__super__.readOpts.call(this);
    objecttypes_dfr = new CUI.Deferred();
    this.__objecttypes_promise = objecttypes_dfr.promise();
    objecttypes_dfr.done((function(_this) {
      return function() {
        return _this.__updateMasks();
      };
    })(this));
    dbinfo = new DbInfo();
    dbinfo.load().done((function(_this) {
      return function() {
        var i, len, objecttype, objecttypes, table_id;
        objecttypes = [];
        for (table_id in dbinfo.getAvailableObjecttypes()) {
          objecttypes.push(new Objecttype(ez5.schema.CURRENT._table_by_id[table_id]));
        }
        objecttypes.sort(function(a, b) {
          return a.nameLocalized().localeCompare(b.nameLocalized());
        });
        _this.__objecttype_opts = [
          {
            text: $$("objecttype.csv.importer.form.objecttype.select"),
            value: null
          }
        ];
        for (i = 0, len = objecttypes.length; i < len; i++) {
          objecttype = objecttypes[i];
          _this.__objecttype_opts.push({
            text: objecttype.nameLocalized(),
            value: objecttype.name()
          });
        }
        return objecttypes_dfr.resolve();
      };
    })(this)).fail(objecttypes_dfr.reject);
    return this;
  };

  ObjecttypeCSVImporter.prototype.resetFile = function() {
    ObjecttypeCSVImporter.__super__.resetFile.call(this);
    this.__form_data.append_nested = false;
    this.__form_data.append_reverse_nested = false;
    return this.__form_data.create_linked_objects = true;
  };

  ObjecttypeCSVImporter.prototype.__updateMasks = function() {
    var idPool, masks_dfr, ref, ref1, table;
    masks_dfr = new CUI.Deferred();
    this.__masks_promise = masks_dfr.promise();
    this.__mask_opts = [
      {
        text: $$("objecttype.csv.importer.form.mask.select"),
        value: null
      }
    ];
    if (!((ref = this.__form_data) != null ? ref.objecttype : void 0)) {
      masks_dfr.resolve();
      return this.__masks_promise;
    }
    table = new Table("CURRENT", ez5.schema.CURRENT._table_by_name[this.__form_data.objecttype]);
    this.__mask_dbinfo = new DbInfo();
    idPool = (ref1 = this.__form_data._pool) != null ? ref1.pool._id : void 0;
    if (idPool && !ez5.pools.findPoolById(idPool)) {
      this.__form_data._pool = null;
      idPool = null;
    }
    this.__mask_dbinfo.load({
      table: table,
      pool_id: idPool
    }).done((function(_this) {
      return function() {
        var i, len, mask, masks;
        masks = _this.__mask_dbinfo.availableMasks(false);
        masks.sort(function(a, b) {
          return a.nameSort().localeCompare(b.nameSort());
        });
        for (i = 0, len = masks.length; i < len; i++) {
          mask = masks[i];
          _this.__mask_opts.push({
            text: mask.nameLocalized(),
            value: mask.name()
          });
        }
        return masks_dfr.resolve();
      };
    })(this)).fail(masks_dfr.reject);
    return this.__masks_promise;
  };

  ObjecttypeCSVImporter.prototype.getMask = function() {
    var table;
    if (!this.__form_data.objecttype || !this.__form_data.mask) {
      return null;
    }
    table = new Table("CURRENT", ez5.schema.CURRENT._table_by_name[this.__form_data.objecttype]);
    return Mask.getMaskByMaskName(this.__form_data.mask, table.id(), 'CURRENT', false);
  };

  ObjecttypeCSVImporter.prototype.getDestinationFields = function() {
    var dest_field, dest_fields, field, i, j, len, len1, ref, ref1;
    dest_fields = [];
    if (!this.__form_data.mask) {
      return dest_fields;
    }
    ref = this.getMask().getFields("csv-import");
    for (i = 0, len = ref.length; i < len; i++) {
      field = ref[i];
      if (!(field instanceof Field)) {
        continue;
      }
      ref1 = field.getCSVDestinationFields(this);
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        dest_field = ref1[j];
        CUI.util.assert(dest_field instanceof ObjecttypeCSVImporterDestinationField, "ObjecttypeCSVImporter.getDestinationFields", "field need to be instanceof ObjecttypeCSVImporterDestinationField");
        dest_fields.push(dest_field);
      }
    }
    return dest_fields;
  };

  ObjecttypeCSVImporter.prototype.loadSettings = function(settings, fromFile) {
    var dfr, ret;
    dfr = new CUI.Deferred();
    ret = ObjecttypeCSVImporter.__super__.loadSettings.call(this, settings, fromFile);
    ret.done((function(_this) {
      return function() {
        _this.__validateLoadedSettings();
        return _this.__objecttypes_promise.done(function() {
          return _this.__updateMasks().done(dfr.resolve).fail(dfr.reject);
        }).fail(dfr.reject);
      };
    })(this));
    return dfr.promise();
  };

  ObjecttypeCSVImporter.prototype.__validateLoadedSettings = function() {
    var idTable, ref;
    if (!this.__form_data.objecttype) {
      return;
    }
    idTable = (ref = ez5.schema.CURRENT._table_by_name[this.__form_data.objecttype]) != null ? ref.table_id : void 0;
    if (!idTable) {
      CUI.alert({
        text: $$("objecttype.csv.importer.form.objecttype.not-found", {
          objecttype: this.__form_data.objecttype
        })
      });
      delete this.__form_data.objecttype;
      delete this.__form_data.mask;
    } else if (this.__form_data.mask) {
      try {
        Mask.getMaskByMaskName(this.__form_data.mask, idTable, 'CURRENT', false);
      } catch (error) {
        CUI.alert({
          text: $$("objecttype.csv.importer.form.mask.not-found", {
            mask: this.__form_data.mask
          })
        });
        delete this.__form_data.mask;
      }
    }
  };

  ObjecttypeCSVImporter.prototype.getObjecttype = function() {
    return this.__form_data.objecttype;
  };

  ObjecttypeCSVImporter.prototype.getReadyForPrepare = function() {
    var dfr, ret;
    this.linked_objects_by_mask = {};
    dfr = new CUI.Deferred();
    ret = ObjecttypeCSVImporter.__super__.getReadyForPrepare.call(this);
    ret.fail((function(_this) {
      return function(key, params) {
        var hasPools;
        if (key) {
          return dfr.reject(key, params);
        }
        if (!_this.__form_data.objecttype) {
          return dfr.reject("objecttype.csv.importer.required.fields.objecttype");
        }
        hasPools = ez5.schema.CURRENT._table_by_name[_this.__form_data.objecttype].pool_link;
        if (hasPools && !_this.__form_data._pool) {
          return dfr.reject("objecttype.csv.importer.required.fields.pool");
        }
        if (!_this.__form_data.mask) {
          return dfr.reject("objecttype.csv.importer.required.fields.mask");
        }
        return dfr.reject();
      };
    })(this));
    ret.done((function(_this) {
      return function() {
        var configs, destinationField, errorMessage, fetchPoolPromise, hasPoolLinkedObjects, i, len, mask, ref;
        mask = _this.getMask();
        if (mask.requireComment() === "always" && !_this.__form_data.comment.trim().length > 0) {
          dfr.reject("objecttype.csv.importer.error.comment_required");
          return;
        }
        hasPoolLinkedObjects = _this.dest_fields.some(function(destinationField) {
          var field, linkedTableName;
          field = destinationField.getField();
          if (!(field instanceof LinkedObject)) {
            return false;
          }
          linkedTableName = field.linkMask().getTable().name();
          return ez5.schema.CURRENT._table_by_name[linkedTableName].pool_link;
        });
        if (hasPoolLinkedObjects && !_this.__form_data._pool_linked_objects) {
          dfr.reject("objecttype.csv.importer.required.fields.pool_linked_object");
          return;
        }
        ref = _this.dest_fields;
        for (i = 0, len = ref.length; i < len; i++) {
          destinationField = ref[i];
          configs = _this.getMappingConfigsForDestinationField(destinationField);
          errorMessage = destinationField.hasPrepareError(configs);
          if (errorMessage) {
            dfr.reject(errorMessage);
            return;
          }
        }
        if (_this.__form_data._pool) {
          fetchPoolPromise = ez5.api.pool({
            api: "/" + _this.__form_data._pool.pool._id
          });
        } else {
          fetchPoolPromise = CUI.resolvedPromise();
        }
        return fetchPoolPromise.done(function(pool) {
          var check_dest_fields, col, config, csv_field_idx, dest_field, idx, j, k, l, len1, len2, level, max_level, ref1, ref2;
          _this.__poolSelected = pool != null ? pool[0] : void 0;
          if (!mask.isHierarchy()) {
            dfr.resolve();
            return;
          }
          _this.path_dest = {
            path_col_idx: [],
            field: null
          };
          check_dest_fields = [];
          max_level = -1;
          ref1 = _this.getHeaderRow();
          for (csv_field_idx = j = 0, len1 = ref1.length; j < len1; csv_field_idx = ++j) {
            col = ref1[csv_field_idx];
            dest_field = _this.getDestinationFieldByName(_this.__form_data.mapping[csv_field_idx]);
            if (!dest_field) {
              continue;
            }
            config = _this.__form_data.mapping["custom_" + csv_field_idx];
            level = config.level;
            if (!(!isNaN(parseInt(level)) && level >= 0) && !(dest_field instanceof HierarchyCSVImporterDestinationField)) {
              check_dest_fields.push(dest_field);
              continue;
            }
            if (dest_field instanceof HierarchyCSVImporterDestinationField) {
              level = 0;
            }
            max_level = Math.max(level, max_level);
            if (_this.path_dest.field) {
              if (_this.path_dest.field !== dest_field) {
                dfr.reject("objecttype.csv.importer.error.path_multiple_fields_not_allowed");
                return;
              }
            } else {
              _this.path_dest.field = dest_field;
            }
            if (config.use_for_path === void 0) {
              if (_this.path_dest.path_col_idx[level] !== void 0) {
                dfr.reject("objecttype.csv.importer.error.path_multiple_fields_not_allowed");
                return;
              }
              _this.path_dest.path_col_idx[level] = csv_field_idx;
            } else if (config.use_for_path) {
              if (_this.path_dest.path_col_idx[level] !== void 0) {
                dfr.reject("objecttype.csv.importer.error.path_multiple_fields_not_allowed");
                return;
              } else {
                _this.path_dest.path_col_idx[level] = csv_field_idx;
              }
            }
          }
          for (idx = k = 0, ref2 = max_level; k <= ref2; idx = k += 1) {
            if (_this.path_dest.path_col_idx[idx] === void 0) {
              dfr.reject("objecttype.csv.importer.error.path_levels_incomplete");
              return;
            }
          }
          if (_this.path_dest.field) {
            if (_this.path_dest.path_col_idx.length === 0) {
              dfr.reject("objecttype.csv.importer.error.path_levels_incomplete");
              return;
            }
            for (l = 0, len2 = check_dest_fields.length; l < len2; l++) {
              dest_field = check_dest_fields[l];
              if (dest_field === _this.path_dest.field) {
                dfr.reject("objecttype.csv.importer.error.path_level_incomplete");
                return;
              }
            }
          } else {
            _this.path_dest = null;
          }
          return dfr.resolve();
        });
      };
    })(this));
    return dfr.promise();
  };

  ObjecttypeCSVImporter.prototype.preparePathData = function(rows) {
    var _, _path, col_idx, ex, i, j, k, l, len, len1, parentRowIdx, parent_row_idx, path, path_by_row_idx, path_parent, path_str, prev_row_idx, prev_value, ref, ref1, ref2, row, row_idx, row_idx_by_path, value;
    row_idx_by_path = {};
    path_by_row_idx = [];
    for (row_idx = i = 0, len = rows.length; i < len; row_idx = ++i) {
      row = rows[row_idx];
      try {
        path = [];
        ref = this.path_dest.path_col_idx;
        for (j = ref.length - 1; j >= 0; j += -1) {
          col_idx = ref[j];
          value = (ref1 = row[col_idx]) != null ? ref1.trim() : void 0;
          if (this.path_dest.field instanceof HierarchyCSVImporterDestinationField) {
            if (CUI.util.isEmpty(value)) {
              continue;
            }
            path.splice(0, 0, value);
          } else {
            if (CUI.util.isEmpty(value)) {
              if (path.length === 0) {
                continue;
              } else {
                for (prev_row_idx = k = ref2 = row_idx - 1; k >= 0; prev_row_idx = k += -1) {
                  prev_value = rows[prev_row_idx][col_idx].trim();
                  if (!CUI.util.isEmpty(prev_value)) {
                    value = prev_value;
                    break;
                  }
                }
                if (CUI.util.isEmpty(value)) {
                  throw {
                    loca_key: "objecttype.csv.importer.path_misses_parent_value"
                  };
                }
              }
            }
            path.splice(0, 0, value);
          }
        }
        if (path.length === 0) {
          throw {
            loca_key: "objecttype.csv.importer.empty_path"
          };
        }
        if (this.path_dest.field instanceof HierarchyCSVImporterDestinationField) {
          if (path.length > 1) {
            for (_ in path_by_row_idx) {
              _path = path_by_row_idx[_];
              if (_path.length === 1) {
                continue;
              }
              if (_path[_path.length - 1] === path[0]) {
                path = _path.concat(path.slice(1));
              }
            }
          }
        }
        path_by_row_idx[row_idx] = path;
        path_str = JSON.stringify(path);
        if (!row_idx_by_path[path_str]) {
          row_idx_by_path[path_str] = [];
        }
        row_idx_by_path[path_str].push(row_idx);
      } catch (error) {
        ex = error;
        if (ex.loca_key) {
          this.setRowInvalid(row, ex.loca_key);
        } else {
          throw ex;
        }
      }
    }
    for (row_idx = l = 0, len1 = rows.length; l < len1; row_idx = ++l) {
      row = rows[row_idx];
      if (row[this.cf_idx.status] === "invalid") {
        continue;
      }
      if (row[this.cf_idx.id_parent]) {
        continue;
      }
      path = path_by_row_idx[row_idx];
      if (path.length <= 1) {
        row[this.cf_idx.id_parent] = null;
        row[this.cf_idx.depth] = 0;
        if (path.length === 1) {
          row[this.cf_idx.path] = JSON.stringify(path);
        }
        continue;
      }
      path_parent = path.slice(0, path.length - 1);
      parent_row_idx = row_idx_by_path[JSON.stringify(path_parent)];
      if ((parent_row_idx != null ? parent_row_idx.length : void 0) > 0) {
        parentRowIdx = parent_row_idx[parent_row_idx.length - 1];
        if (rows[parentRowIdx][this.cf_idx.status] === "invalid") {
          this.setRowInvalid(row, "objecttype.csv.importer.path_parent_invalid");
          continue;
        }
        row[this.cf_idx.id_parent] = JSON.stringify({
          row_idx: parentRowIdx
        });
        row[this.cf_idx.depth] = path_parent.length;
        row[this.cf_idx.path] = JSON.stringify(path);
      } else {
        this.setRowInvalid(row, "objecttype.csv.importer.path_parent_not_found");
      }
    }
    return this;
  };

  ObjecttypeCSVImporter.prototype.prepareData = function(rows) {
    var deferred;
    if (this.path_dest) {
      this.preparePathData(rows);
      deferred = new CUI.Deferred();
      this.__afterPreparePathData(rows).done((function(_this) {
        return function() {
          return ObjecttypeCSVImporter.__super__.prepareData.call(_this, rows).done(deferred.resolve).fail(deferred.reject);
        };
      })(this));
      return deferred.promise();
    } else {
      return ObjecttypeCSVImporter.__super__.prepareData.call(this, rows);
    }
  };

  ObjecttypeCSVImporter.prototype.__afterPreparePathData = function(rows) {
    var deferred, promises;
    deferred = new CUI.Deferred();
    promises = [];
    this.callOnMappedDestFields((function(_this) {
      return function(dest_field, configs) {
        var promise;
        promise = dest_field.afterPreparePathData(configs, rows);
        if (CUI.util.isPromise(promise)) {
          return promises.push(promise);
        }
      };
    })(this));
    CUI.when(promises).always(deferred.resolve);
    return deferred.promise();
  };

  ObjecttypeCSVImporter.prototype.getPrepareDataSearchOpts = function() {
    var search, search_opts;
    search = [];
    if (this.__form_data.mask && this.__form_data.mask !== "_all_fields") {
      search.push({
        bool: "must",
        type: "in",
        "in": [this.__form_data.mask],
        fields: ["_mask"]
      });
    }
    search_opts = {
      type: "object",
      format: "standard",
      generate_rights: false,
      search: search,
      best_mask_filter: false,
      objecttypes: [this.getObjecttype()]
    };
    if (this.__form_data.match_existing) {
      this.getDestinationFieldByName(this.__form_data.match_existing).fillPrepareDataSearchOpts(search_opts, this.__form_data.match_existing);
    }
    return search_opts;
  };

  ObjecttypeCSVImporter.prototype.getMatchExistingValueFromSearchResponse = function(obj, match_existing) {
    var ref;
    return (ref = obj._fields[this.getDestinationFieldByName(match_existing).getRecordKeyPathForSearch()]) != null ? ref[0] : void 0;
  };

  ObjecttypeCSVImporter.prototype.getDepthSortedCopy = function(rows) {
    var rows_copy;
    rows_copy = rows.slice(0);
    rows_copy.sort((function(_this) {
      return function(a, b) {
        return CUI.util.compareIndex(a[_this.cf_idx.depth], b[_this.cf_idx.depth]);
      };
    })(this));
    return rows_copy;
  };

  ObjecttypeCSVImporter.prototype.prepareExistingDataChunk = function(rows) {
    var dfr, ref, unique_dest_field;
    dfr = new CUI.Deferred();
    unique_dest_field = this.getDestinationFieldByName(this.__form_data.match_existing);
    if (!unique_dest_field) {
      dfr.resolve();
    } else if (((ref = this.path_dest) != null ? ref.field : void 0) !== unique_dest_field) {
      this.prepareMatchExistingDataChunk(rows).done(dfr.resolve).fail(dfr.reject);
    } else {
      this.preparePathMatchDataChunk(rows).done(dfr.resolve).fail(dfr.reject);
    }
    return dfr.promise();
  };

  ObjecttypeCSVImporter.prototype.preparePathMatchDataChunk = function(rows) {
    var all_rows, dfr, get_next_chunk, ot_name, run_next_chunk;
    all_rows = this.getRows();
    ot_name = this.__form_data.objecttype;
    get_next_chunk = (function(_this) {
      return function() {
        var _idx, _rows, all_done, i, len, parent_operation, parent_status, ref, row, row_idx, value;
        _rows = [];
        all_done = true;
        ref = _this.getDepthSortedCopy(rows);
        for (_idx = i = 0, len = ref.length; i < len; _idx = ++i) {
          row = ref[_idx];
          if (row[_this.cf_idx.status]) {
            continue;
          }
          all_done = false;
          try {
            value = JSON.parse(row[_this.cf_idx.id_parent]);
          } catch (error) {}
          if (value != null ? value.hasOwnProperty("row_idx") : void 0) {
            row_idx = value.row_idx;
            parent_status = all_rows[row_idx][_this.cf_idx.status];
            if (!parent_status) {
              continue;
            }
            if (parent_status !== "ready" && parent_status !== "done") {
              _this.setRowInvalid(row, "objecttype.csv.import.parent_status_invalid");
              continue;
            }
            parent_operation = JSON.parse(all_rows[row_idx][_this.cf_idx.operation]);
            if (parent_status === "ready" && indexOf.call(parent_operation, "insert") >= 0) {
              _this.setRowInsert(row);
              continue;
            }
            if (parent_status === "done" || indexOf.call(parent_operation, "update") >= 0) {
              row[_this.cf_idx.id_parent] = all_rows[row_idx][_this.cf_idx.id];
              _rows.push(row);
              continue;
            }
            console.error("ObjecttypeCSVImporter: Unknown ready operation:", parent_operation);
            _this.setRowInvalid(row);
          } else {
            _rows.push(row);
          }
        }
        if (all_done || CUI.util.isEmpty(_rows)) {
          return null;
        }
        return _rows;
      };
    })(this);
    dfr = new CUI.Deferred();
    run_next_chunk = (function(_this) {
      return function() {
        var i, id_parent, len, match_search, next_chunk, path, row, row_by_unique_key, search_opts, unique_key, value;
        next_chunk = get_next_chunk();
        if (next_chunk === null) {
          dfr.resolve();
          return;
        }
        search_opts = _this.getPrepareDataSearchOpts();
        search_opts.search = [];
        row_by_unique_key = {};
        for (i = 0, len = next_chunk.length; i < len; i++) {
          row = next_chunk[i];
          path = JSON.parse(row[_this.cf_idx.path]);
          id_parent = row[_this.cf_idx.id_parent] || null;
          value = path[path.length - 1];
          unique_key = JSON.stringify([id_parent, value]);
          if (row_by_unique_key[unique_key]) {
            _this.setRowInvalid(row, "csv.importer.unique_key_duplicate");
            continue;
          }
          row_by_unique_key[unique_key] = row;
          match_search = _this.path_dest.field.getMatchExistingSearch([value], _this.__form_data.match_existing);
          search_opts.search.push({
            type: "complex",
            bool: "should",
            search: [
              {
                type: "in",
                bool: "must",
                "in": [id_parent],
                fields: [ot_name + "._id_parent"]
              }, {
                type: "complex",
                bool: "must",
                search: match_search
              }
            ]
          });
        }
        if (search_opts.search.length === 0) {
          run_next_chunk();
          return;
        }
        return ez5.api.search({
          json_data: search_opts
        }).done(function(data) {
          var j, len1, obj, ref;
          ref = data.objects;
          for (j = 0, len1 = ref.length; j < len1; j++) {
            obj = ref[j];
            value = _this.getMatchExistingValueFromSearchResponse(obj, _this.__form_data.match_existing);
            id_parent = obj[ot_name]._id_parent || null;
            unique_key = JSON.stringify([id_parent, value]);
            row = row_by_unique_key[unique_key];
            if (!row) {
              continue;
            }
            _this.setRowUpdate(row, obj[ot_name]);
            delete row_by_unique_key[unique_key];
          }
          for (unique_key in row_by_unique_key) {
            row = row_by_unique_key[unique_key];
            _this.setRowInsert(row);
          }
          return run_next_chunk();
        }).fail(function() {
          var j, len1;
          for (j = 0, len1 = next_chunk.length; j < len1; j++) {
            row = next_chunk[j];
            _this.setRowInvalid(row);
          }
          return run_next_chunk();
        });
      };
    })(this);
    run_next_chunk();
    return dfr.promise();
  };

  ObjecttypeCSVImporter.prototype.getOutputSettingFields = function() {
    var dfr, finalize_fields;
    if (this.__form_data.objecttype === void 0) {
      this.__form_data.objecttype = null;
    }
    if (this.__form_data.mask === void 0) {
      this.__form_data.mask = null;
    }
    if (this.__form_data._pool === void 0) {
      this.__form_data._pool = null;
    }
    dfr = new CUI.Deferred();
    finalize_fields = (function(_this) {
      return function() {
        var append_nested_cb, append_reverse_nested_cb, create_linked_objects_cb, dest_field, easType_select, field, fields, getPoolField, i, is_mapped, len, linkedTableName, mapping_select, mask_select, objecttype, opts, poolFieldForEditorOpts, pool_ids, pool_select, pool_select_linked_objects, ref, tagsModeSelect;
        mask_select = null;
        pool_select = null;
        easType_select = null;
        mapping_select = null;
        if (_this.__form_data.objecttype) {
          objecttype = new Objecttype(ez5.schema.CURRENT._table_by_name[_this.__form_data.objecttype]);
          if (_this.__form_data._pool || !objecttype.poolLink()) {
            mask_select = {
              form: {
                label: $$("objecttype.csv.importer.form.mask.label")
              },
              type: CUI.Select,
              undo_and_changed_support: false,
              disabled: _this.__form_data.objecttype === null,
              name: "mask",
              onDataChanged: function() {
                _this.resetInitMapping();
                return _this.reloadFormData();
              },
              options: _this.__mask_opts
            };
          }
          if (objecttype.poolLink()) {
            pool_ids = _this.__mask_dbinfo.getPoolIds();
            opts = {
              pool_ids: pool_ids,
              onDataChanged: function() {
                _this.__updateMasks();
                return _this.reloadFormData();
              }
            };
            poolFieldForEditorOpts = {
              label: $$("objecttype.csv.importer.form.pool.label")
            };
            pool_select = (new PoolFieldForEditor(poolFieldForEditorOpts)).renderEditorInput(_this.__form_data, null, opts);
          }
          if (objecttype.hasTags()) {
            tagsModeSelect = {
              form: {
                label: $$("objecttype.csv.importer.form.tags-mode.label")
              },
              type: CUI.Select,
              name: "tags_mode",
              options: [
                {
                  text: $$("objecttype.csv.importer.form.tags-mode.option.add.label"),
                  value: "tag_add"
                }, {
                  text: $$("objecttype.csv.importer.form.tags-mode.option.replace.label"),
                  value: "tag_replace"
                }
              ]
            };
          }
          ref = _this.dest_fields;
          for (i = 0, len = ref.length; i < len; i++) {
            dest_field = ref[i];
            field = dest_field.getField();
            is_mapped = _this.getMappingConfigsForDestinationField(dest_field).length > 0;
            if (field.getFatherField()) {
              if (field.getFatherField() instanceof ReverseLinkedTable) {
                if (!append_reverse_nested_cb) {
                  append_reverse_nested_cb = {
                    type: CUI.Checkbox,
                    disabled: true,
                    name: "append_reverse_nested",
                    form: {
                      label: $$("objecttype.csv.importer.form.append_reverse_nested|text"),
                      hint: $$("objecttype.csv.importer.form.append_reverse_nested|hint")
                    }
                  };
                }
                if (is_mapped) {
                  append_reverse_nested_cb.disabled = false;
                }
              } else {
                if (!append_nested_cb) {
                  append_nested_cb = {
                    type: CUI.Checkbox,
                    disabled: true,
                    name: "append_nested",
                    form: {
                      label: $$("objecttype.csv.importer.form.append_nested|text"),
                      hint: $$("objecttype.csv.importer.form.append_nested|hint")
                    }
                  };
                }
                if (is_mapped) {
                  append_nested_cb.disabled = false;
                }
              }
            }
            if (field instanceof LinkedObject) {
              if (!create_linked_objects_cb) {
                create_linked_objects_cb = {
                  type: CUI.Checkbox,
                  disabled: true,
                  name: "create_linked_objects",
                  form: {
                    label: $$("objecttype.csv.importer.form.create_linked_objects.label")
                  }
                };
              }
              if (is_mapped) {
                create_linked_objects_cb.disabled = false;
              }
              if (pool_select_linked_objects) {
                continue;
              }
              linkedTableName = field.linkMask().getTable().name();
              if (ez5.schema.CURRENT._table_by_name[linkedTableName].pool_link) {
                getPoolField = function(pool_ids) {
                  var poolFieldOpts;
                  opts = {
                    pool_ids: pool_ids,
                    onDataChanged: function() {
                      return _this.reloadFormData();
                    }
                  };
                  poolFieldOpts = {
                    name: "_pool_linked_objects"
                  };
                  return (new PoolFieldForEditor(poolFieldOpts)).renderEditorInput(_this.__form_data, null, opts);
                };
                pool_select_linked_objects = {
                  type: CUI.DataFieldProxy,
                  form: {
                    label: $$("objecttype.csv.importer.form.pool_linked_objects.label")
                  },
                  element: function() {
                    var dbInfo, div, linkPoolField, table;
                    if (objecttype.poolLink()) {
                      pool_ids = _this.__mask_dbinfo.getPoolIds();
                      linkPoolField = getPoolField(pool_ids);
                      linkPoolField.start();
                      return linkPoolField;
                    } else {
                      div = CUI.dom.div();
                      table = new Table("CURRENT", ez5.schema.CURRENT._table_by_name[linkedTableName]);
                      dbInfo = new DbInfo();
                      dbInfo.load({
                        table: table
                      }).done(function() {
                        pool_ids = dbInfo.getPoolIds();
                        linkPoolField = getPoolField(pool_ids);
                        linkPoolField.start();
                        return CUI.dom.replace(div, linkPoolField);
                      });
                      return div;
                    }
                  }
                };
              }
            }
            if (mask_select && _this.dest_fields.some(function(destinationField) {
              return destinationField instanceof EASColumnCSVImporterDestinationField;
            })) {
              easType_select = {
                form: {
                  label: $$("eas.importer.fields.eas_type.label.text"),
                  hint: $$("eas.importer.fields.eas_type.label.hint.md")
                },
                type: CUI.Select,
                undo_and_changed_support: false,
                name: "easType",
                onDataChanged: function() {
                  return _this.reloadFormData();
                },
                options: _this.__getSupportedEASTypes()
              };
              opts = {
                show_standard_option: true,
                field_opts: {
                  name: "id_mapping"
                },
                mapping_filter: function(mapping) {
                  var idTable;
                  if (!mapping.idTable) {
                    return true;
                  }
                  idTable = ez5.schema.CURRENT._objecttype_by_name[_this.__form_data.objecttype].table_id;
                  return idTable === mapping.idTable;
                }
              };
              mapping_select = ez5.metadata.getMappingField({
                exiftool_import: true
              }, opts);
            }
          }
        }
        fields = [
          {
            form: {
              label: $$("objecttype.csv.importer.form.objecttype.label")
            },
            type: CUI.Select,
            undo_and_changed_support: false,
            name: "objecttype",
            onDataChanged: function() {
              _this.__form_data._pool = null;
              _this.__form_data.mask = null;
              _this.__form_data.id_mapping = null;
              return _this.__updateMasks();
            },
            options: _this.__objecttype_opts
          }, pool_select, mask_select, easType_select, mapping_select, tagsModeSelect, _this.getMatchExistingField(), append_nested_cb, append_reverse_nested_cb, create_linked_objects_cb, pool_select_linked_objects, {
            form: {
              label: $$("objecttype.csv.importer.form.objecttype.comment")
            },
            name: "comment",
            type: CUI.Input,
            undo_support: true,
            textarea: true,
            onDataChanged: function(data, df, ev) {
              if (df.getValue().trim() === "" || df.getLastValue().trim() === "") {
                _this.updateButtons();
              }
              return ev.stopPropagation();
            },
            placeholder: $$("objecttype.csv.importer.comment.default")
          }
        ];
        fields.push.apply(fields, ObjecttypeCSVImporter.__super__.getOutputSettingFields.call(_this));
        return dfr.resolve(fields);
      };
    })(this);
    this.__objecttypes_promise.done((function(_this) {
      return function() {
        _this.__masks_promise.fail(dfr.reject);
        return _this.__masks_promise.done(finalize_fields);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  ObjecttypeCSVImporter.prototype.getRecord = function(row, opts) {
    var availableTags, defaultTags, dest_field, destinationField, field, getTopNestedFieldName, groupModeValue, i, idParent, j, k, len, len1, len2, mask, mask_name, nestedFieldName, ot_name, poolTags, record, ref, ref1, ref2, ref3, tag, tagId;
    if (opts == null) {
      opts = {};
    }
    record = ObjecttypeCSVImporter.__super__.getRecord.call(this, row, opts);
    ot_name = this.__form_data.objecttype;
    if (!ot_name) {
      return record;
    }
    mask_name = this.__form_data.mask;
    if (!mask_name) {
      return record;
    }
    if (!record[ot_name]) {
      record[ot_name] = {};
    }
    mask = this.getMask();
    if (this.__form_data.comment.trim().length > 0) {
      record._comment = this.__form_data.comment.trim();
    } else {
      record._comment = $$("objecttype.csv.importer.comment.default");
    }
    record._mask = mask_name;
    record._objecttype = ot_name;
    if (this.__form_data._pool && opts.operation === "insert" && CUI.util.isEmpty(record[ot_name]._pool)) {
      record[ot_name]._pool = {
        pool: {
          _id: this.__form_data._pool.pool._id
        }
      };
    }
    if (mask.isHierarchy() && (CUI.util.isEmpty(record[ot_name]._id_parent) || !CUI.util.isNumber(record[ot_name]._id_parent))) {
      idParent = row[this.cf_idx.id_parent];
      if (CUI.util.isArray(idParent)) {
        idParent = idParent[0];
      }
      record[ot_name]._id_parent = idParent || null;
    }
    if (opts.operation === "insert") {
      if (CUI.util.isEmpty(record._tags) || record._tags === TagsFieldCSVImporterDestinationField.EMPTY) {
        delete record._tags;
        defaultTags = [];
        availableTags = this.__mask_dbinfo.availableTagIds() || [];
        poolTags = (ref = this.__poolSelected) != null ? ref._compiled_tags : void 0;
        ref1 = ez5.tagForm.getAllTags();
        for (i = 0, len = ref1.length; i < len; i++) {
          tag = ref1[i];
          tagId = tag.getId();
          if (!tag.data.tag.is_default) {
            if (poolTags) {
              if (!poolTags.some((function(_this) {
                return function(_tag) {
                  return _tag._id === tagId && _tag.enabled && _tag.is_default;
                };
              })(this))) {
                continue;
              }
            } else {
              continue;
            }
          }
          if (indexOf.call(availableTags, tagId) < 0) {
            continue;
          }
          defaultTags.push({
            _id: tagId
          });
        }
        if (defaultTags.length > 0) {
          record._tags = defaultTags;
        }
      }
    }
    if (opts.operation === "update" && !CUI.util.isEmpty(record._tags)) {
      if (record._tags === TagsFieldCSVImporterDestinationField.EMPTY) {
        if (this.__form_data.tags_mode === "tag_replace") {
          record._tags = [];
          record["_tags:group_mode"] = "tag_remove_all";
        } else {
          delete record._tags;
        }
      } else {
        record["_tags:group_mode"] = this.__form_data.tags_mode;
      }
    }
    if (!row[this.cf_idx.id]) {
      record[ot_name]._version = 1;
    } else {
      record[ot_name]._id = [row[this.cf_idx.id]];
      delete record[ot_name]._version;
      if (CUI.util.isEmpty(record[ot_name]._id_parent)) {
        delete record[ot_name]._id_parent;
      }
      ref2 = this.getMappedDestinationFields();
      for (j = 0, len1 = ref2.length; j < len1; j++) {
        dest_field = ref2[j];
        field = dest_field.getField();
        if (!field.getFatherField()) {
          continue;
        }
        if (field.getFatherField() instanceof ReverseLinkedTable) {
          continue;
        }
        if (this.__form_data.append_nested) {
          groupModeValue = "append";
        } else {
          groupModeValue = "replace";
        }
        getTopNestedFieldName = function(_field) {
          var fatherField;
          fatherField = _field.getFatherField();
          if (!fatherField) {
            return _field.name();
          }
          return getTopNestedFieldName(fatherField);
        };
        nestedFieldName = getTopNestedFieldName(field);
        if (!record.__nestedFieldNames) {
          record.__nestedFieldNames = [];
        }
        if (!record.__nestedFieldNames.includes(nestedFieldName)) {
          record.__nestedFieldNames.push(nestedFieldName);
        }
        record[ot_name][nestedFieldName + ":group_mode"] = groupModeValue;
      }
    }
    ref3 = this.getDestinationFields();
    for (k = 0, len2 = ref3.length; k < len2; k++) {
      destinationField = ref3[k];
      destinationField.finalizeRecord(record, row, opts);
    }
    return record;
  };

  ObjecttypeCSVImporter.prototype.action = function(ev, op, rows) {
    var all_rows, dfr;
    all_rows = this.getRows();
    dfr = new CUI.Deferred();
    this.callOnMappedDestFields((function(_this) {
      return function(dest_field, configs) {
        return dest_field.action(ev, op, rows);
      };
    })(this)).fail((function(_this) {
      return function(errorMessage) {
        var i, len, row;
        for (i = 0, len = rows.length; i < len; i++) {
          row = rows[i];
          row[_this.cf_idx.status] = "failed";
        }
        return dfr.reject(errorMessage);
      };
    })(this)).done((function(_this) {
      return function() {
        var addRecords, get_next_chunk, mask, mask_name, ot_name, run_next_chunk;
        mask = _this.getMask();
        mask_name = _this.__form_data.mask;
        ot_name = _this.__form_data.objecttype;
        get_next_chunk = function() {
          var _idx, _rows, all_rows_done, i, len, ref, ref1, row, value;
          _rows = [];
          all_rows_done = true;
          ref = _this.getDepthSortedCopy(rows);
          for (_idx = i = 0, len = ref.length; i < len; _idx = ++i) {
            row = ref[_idx];
            if ((ref1 = row[_this.cf_idx.status]) === "done" || ref1 === "failed" || ref1 === "not_changed") {
              continue;
            }
            all_rows_done = false;
            try {
              value = JSON.parse(row[_this.cf_idx.id_parent]);
            } catch (error) {}
            if ((value != null ? value.row_idx : void 0) !== void 0) {
              continue;
            }
            _rows.push(row);
          }
          if (all_rows_done) {
            return null;
          }
          return _rows;
        };
        run_next_chunk = function() {
          var data, foundInvalid, i, id, j, k, l, len, len1, len2, len3, next_chunk, objecttype, record, recordById, recordIds, recordWithReverse, records, recordsWithReverse, ref, row, v, value;
          next_chunk = get_next_chunk();
          if (next_chunk === null || next_chunk.length === 0) {
            if (op !== "update") {
              return dfr.resolve();
            }
            foundInvalid = false;
            for (i = 0, len = rows.length; i < len; i++) {
              row = rows[i];
              try {
                value = JSON.parse(row[_this.cf_idx.id_parent]);
              } catch (error) {}
              if (!CUI.util.isUndef(value != null ? value.row_idx : void 0)) {
                row[_this.cf_idx.warning_text] = $$("csv.importer.update.row-depends-non-inserted-row");
                foundInvalid = true;
              }
            }
            if (foundInvalid) {
              return dfr.reject($$("csv.importer.update.row-dependency-general-message"));
            }
            return dfr.resolve();
          }
          records = [];
          for (j = 0, len1 = next_chunk.length; j < len1; j++) {
            row = next_chunk[j];
            record = _this.getRecord(row, {
              operation: op
            });
            records.push(record);
          }
          if (ev.hasModifierKey()) {
            console.info(CUI.util.dump(records));
            for (k = 0, len2 = next_chunk.length; k < len2; k++) {
              row = next_chunk[k];
              row[_this.cf_idx.status] = "done";
            }
            run_next_chunk();
            return;
          }
          if (op === "update") {
            recordsWithReverse = records.filter(function(record) {
              return record.__reverseLinkedTableNames && record.__reverseLinkedTableNames.length > 0;
            });
            if (recordsWithReverse.length > 0) {
              recordById = {};
              objecttype = _this.__form_data.objecttype;
              for (l = 0, len3 = recordsWithReverse.length; l < len3; l++) {
                recordWithReverse = recordsWithReverse[l];
                if (!recordWithReverse[objecttype]) {
                  continue;
                }
                data = recordWithReverse[objecttype];
                id = (ref = data._id) != null ? ref[0] : void 0;
                if (!id) {
                  console.log("Record with reverse data has no id, skipping.");
                  continue;
                }
                recordById[id] = recordWithReverse;
                recordIds = [];
                for (id in recordById) {
                  v = recordById[id];
                  if (!isNaN(id)) {
                    id = parseInt(id);
                  }
                  recordIds.push(id);
                }
              }
              return ez5.api.search({
                json_data: {
                  format: "long",
                  objecttypes: [objecttype],
                  search: [
                    {
                      type: "in",
                      "in": recordIds,
                      fields: [objecttype + "._id"]
                    }
                  ]
                }
              }).done(function(searchData) {
                var existingNestedRows, existingReverseRows, idObject, len4, len5, len6, len7, m, n, nestedFieldName, o, object, objects, p, ref1, ref2, reverseFieldName, tagsMode;
                objects = searchData.objects;
                for (m = 0, len4 = objects.length; m < len4; m++) {
                  object = objects[m];
                  idObject = object[objecttype]._id;
                  record = recordById[idObject];
                  if (!record) {
                    continue;
                  }
                  data = record[objecttype];
                  ref1 = record.__reverseLinkedTableNames;
                  for (n = 0, len5 = ref1.length; n < len5; n++) {
                    reverseFieldName = ref1[n];
                    if (!data[reverseFieldName]) {
                      data[reverseFieldName] = [];
                    }
                    if (_this.__form_data.append_reverse_nested) {
                      existingReverseRows = object[objecttype][reverseFieldName] || [];
                      for (o = 0, len6 = existingReverseRows.length; o < len6; o++) {
                        row = existingReverseRows[o];
                        row._version += 1;
                      }
                      data[reverseFieldName] = existingReverseRows.concat(data[reverseFieldName]);
                    }
                  }
                  ref2 = record.__nestedFieldNames;
                  for (p = 0, len7 = ref2.length; p < len7; p++) {
                    nestedFieldName = ref2[p];
                    if (!data[nestedFieldName]) {
                      data[nestedFieldName] = [];
                    }
                    delete data[nestedFieldName + ":group_mode"];
                    if (_this.__form_data.append_nested) {
                      existingNestedRows = object[objecttype][nestedFieldName] || [];
                      data[nestedFieldName] = existingNestedRows.concat(data[nestedFieldName]);
                    }
                  }
                  if (!CUI.util.isEmpty(record._tags)) {
                    tagsMode = record["_tags:group_mode"];
                    if (tagsMode === "tag_replace") {
                      record._tags = object._tags;
                    } else {
                      record._tags = record._tags.concat(object._tags || []);
                    }
                    delete record["_tags:group_mode"];
                  }
                  CUI.util.mergeMap(record[objecttype], object[objecttype]);
                  record[objecttype]._id = idObject;
                  record[objecttype]._version += 1;
                }
                addRecords(records, next_chunk);
              });
            } else {
              addRecords(records, next_chunk);
            }
          } else {
            addRecords(records, next_chunk);
          }
        };
        addRecords = function(records, next_chunk) {
          var i, len, record, request_data;
          for (i = 0, len = records.length; i < len; i++) {
            record = records[i];
            delete record.__reverseLinkedTableNames;
            delete record.__nestedFieldNames;
          }
          request_data = {
            format: "short"
          };
          if (_this.__form_data.collection && ez5.version("6")) {
            request_data.collection = _this.__form_data.collection;
          }
          return ez5.api.db({
            api: "/" + ot_name,
            data: request_data,
            json_data: records
          }).done(function(objects) {
            var _row, idx, j, k, l, len1, len2, len3, obj, row, value;
            if (op === "update" && CUI.util.isEmpty(objects)) {
              _this.__addRecordsToReport(objects, op);
              for (j = 0, len1 = next_chunk.length; j < len1; j++) {
                row = next_chunk[j];
                row[_this.cf_idx.status] = "not_changed";
              }
              run_next_chunk();
              return;
            }
            _this.__addRecordsToReport(objects, op);
            for (idx = k = 0, len2 = objects.length; k < len2; idx = ++k) {
              obj = objects[idx];
              row = next_chunk[idx];
              row[_this.cf_idx.status] = "done";
              row[_this.cf_idx.id] = obj[ot_name]._id;
              row[_this.cf_idx.version] = obj[ot_name]._version;
              if (!mask.isHierarchy()) {
                continue;
              }
              row[_this.cf_idx.id_parent] = obj[ot_name]._id_parent;
              for (l = 0, len3 = all_rows.length; l < len3; l++) {
                _row = all_rows[l];
                if (!_row[_this.cf_idx.id_parent]) {
                  continue;
                }
                try {
                  value = JSON.parse(_row[_this.cf_idx.id_parent]);
                } catch (error) {}
                if ((value != null ? value.row_idx : void 0) === row[_this.cf_idx.row_idx]) {
                  _row[_this.cf_idx.id_parent] = row[_this.cf_idx.id];
                }
              }
            }
            return run_next_chunk();
          }).fail(function() {
            var j, len1, row;
            for (j = 0, len1 = rows.length; j < len1; j++) {
              row = rows[j];
              row[_this.cf_idx.status] = "failed";
            }
            return dfr.reject();
          });
        };
        return run_next_chunk();
      };
    })(this));
    return dfr.promise();
  };

  ObjecttypeCSVImporter.prototype.getControlFields = function() {
    var cf, cf_name, field, fields, fields_by_name, i, j, k, len, len1, len2, ref, ref1, ref2;
    fields = ObjecttypeCSVImporter.__super__.getControlFields.call(this);
    ref = [
      {
        name: "id_parent"
      }, {
        name: "depth"
      }, {
        name: "path"
      }
    ];
    for (i = 0, len = ref.length; i < len; i++) {
      field = ref[i];
      fields.push(new CSVImporterControlField(field));
    }
    fields_by_name = {};
    ref1 = this.dest_fields;
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      field = ref1[j];
      ref2 = field.getControlFields();
      for (k = 0, len2 = ref2.length; k < len2; k++) {
        cf = ref2[k];
        fields_by_name[cf.name] = cf;
      }
    }
    for (cf_name in fields_by_name) {
      cf = fields_by_name[cf_name];
      fields.push(new CSVImporterControlField(cf));
    }
    return fields;
  };

  ObjecttypeCSVImporter.prototype.setRowUpdate = function(row, obj) {
    var value;
    ObjecttypeCSVImporter.__super__.setRowUpdate.call(this, row, obj);
    if (obj != null ? obj._id_parent : void 0) {
      try {
        value = JSON.parse(row[this.cf_idx.id_parent]);
        if (value != null ? value.hasOwnProperty("row_idx") : void 0) {
          return;
        }
      } catch (error) {}
      row[this.cf_idx.id_parent] = obj._id_parent;
    }
    return this;
  };

  ObjecttypeCSVImporter.prototype.getFormSaveData = function(forDownload) {
    var i, key, len, ref, sd;
    sd = ObjecttypeCSVImporter.__super__.getFormSaveData.call(this, forDownload);
    ref = ["objecttype", "_pool", "_pool_linked_objects", "mask", "comment", "append_nested", "append_reverse_nested", "create_linked_objects", "easType", "id_mapping", "tags_mode"];
    for (i = 0, len = ref.length; i < len; i++) {
      key = ref[i];
      sd[key] = this.__form_data[key];
    }
    return sd;
  };

  ObjecttypeCSVImporter.prototype.updateRecordPreview = function() {
    ObjecttypeCSVImporter.__super__.updateRecordPreview.call(this);
    this.__record_preview_tab.setContent(this.getRecordPreview());
  };

  ObjecttypeCSVImporter.prototype.getExtraPreviewTabs = function() {
    this.__record_preview_tab = new CUI.Tab({
      name: "record_preview",
      text: $$("csv.importer.tab.record_preview"),
      content: (function(_this) {
        return function() {
          return _this.getRecordPreview();
        };
      })(this)
    });
    return [this.__record_preview_tab];
  };

  ObjecttypeCSVImporter.prototype.getMaskDBInfo = function() {
    return this.__mask_dbinfo;
  };

  ObjecttypeCSVImporter.prototype.addDownloadExtraSettings = function(jsonSettings) {
    jsonSettings.schema_version = ez5.schema.CURRENT.version;
    return jsonSettings;
  };

  ObjecttypeCSVImporter.prototype.getImportSettingsWarnings = function(jsonSettings) {
    if (CUI.util.isUndef(jsonSettings.schema_version)) {
      return $$("objecttype.csv.importer.import-settings.empty-schema-version");
    }
    if (jsonSettings.schema_version !== ez5.schema.CURRENT.version) {
      return $$("objecttype.csv.importer.import-settings.wrong-schema-version", {
        version: jsonSettings.schema_version,
        current_version: ez5.schema.CURRENT.version
      });
    }
    return false;
  };

  ObjecttypeCSVImporter.prototype.__getSupportedEASTypes = function() {
    return EASImporter.getSelectOptions();
  };

  return ObjecttypeCSVImporter;

})(CSVImporter);
// Generated by CoffeeScript 1.12.7
var ObjecttypeCSVImporterDestinationField,
  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;

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

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

  ObjecttypeCSVImporterDestinationField.prototype.initOpts = function() {
    ObjecttypeCSVImporterDestinationField.__super__.initOpts.call(this);
    this.addOpts({
      field: {
        mandatory: true,
        check: function(v) {
          return v instanceof Field && !(v instanceof MaskSplitter);
        }
      },
      supports_hierarchy: {
        mandatory: true,
        "default": true,
        check: Boolean
      },
      read_only: {
        mandatory: true,
        "default": false,
        check: Boolean
      }
    });
    this.mergeOpt("csvImporter", {
      check: ObjecttypeCSVImporter
    });
    this.removeOpt("name");
    return this.removeOpt("label");
  };

  ObjecttypeCSVImporterDestinationField.prototype.readOpts = function() {
    ObjecttypeCSVImporterDestinationField.__super__.readOpts.call(this);
    this.__field = this.getField();
    return this.__is_hierarchy = this._supports_hierarchy && this.__field.getMainMask().isHierarchy();
  };

  ObjecttypeCSVImporterDestinationField.prototype.supportsHierarchy = function() {
    return this.__is_hierarchy && this.getNestedDepth() === 0;
  };

  ObjecttypeCSVImporterDestinationField.prototype.getName = function() {
    return this.getField().getCSVName();
  };

  ObjecttypeCSVImporterDestinationField.prototype.getLabel = function() {
    return this.getField().getCSVLabel();
  };

  ObjecttypeCSVImporterDestinationField.prototype.getRecordKeyPath = function() {
    return this.__field.getCSVRecordKeyPath();
  };

  ObjecttypeCSVImporterDestinationField.prototype.getRecordKeyPathForSearch = function() {
    return this.getRecordKeyPath().replace(/\[\]/g, '');
  };

  ObjecttypeCSVImporterDestinationField.prototype.getColumnNames = function() {
    return [this.getName(), this.__field.fullName(), this.__field.getCSVName()];
  };

  ObjecttypeCSVImporterDestinationField.prototype.getField = function() {
    return this._field;
  };

  ObjecttypeCSVImporterDestinationField.prototype.useForMatchExisting = function() {
    var config;
    if (ObjecttypeCSVImporterDestinationField.__super__.useForMatchExisting.call(this)) {
      return true;
    }
    config = this._csvImporter.getMappingConfigsForDestinationField(this);
    if (config) {
      return true;
    } else {
      return false;
    }
  };

  ObjecttypeCSVImporterDestinationField.prototype.getControlFields = function() {
    return [];
  };

  ObjecttypeCSVImporterDestinationField.prototype.getCustomFields = function() {
    if (!this.supportsHierarchy()) {
      return [];
    }
    return [
      {
        name: "level",
        form: {
          label: $$("objecttype.csv.importer.destination.field.level.label")
        },
        type: CUI.NumberInput,
        undo_and_changed_support: false,
        min: 0,
        max: 99,
        placeholder: $$("objecttype.csv.importer.destination.field.level.placeholder")
      }
    ];
  };

  ObjecttypeCSVImporterDestinationField.prototype.fillPrepareDataSearchOpts = function(search_opts) {
    return search_opts.fields = [
      {
        field: this.getRecordKeyPathForSearch()
      }
    ];
  };

  ObjecttypeCSVImporterDestinationField.prototype.getValueForCustom = function(key, value) {
    if (!this.supportsHierarchy()) {
      return value;
    }
    if (key === "level") {
      if (isNaN(parseInt(value))) {
        return null;
      } else {
        return parseInt(value);
      }
    } else {
      return value;
    }
  };

  ObjecttypeCSVImporterDestinationField.prototype.addToMatchExisting = function(select_opts, set_dest_fields) {
    var config, dest_field, fatherField, field, i, j, len, len1, path_dest_field, ref;
    field = this.getField();
    fatherField = field.getFatherField();
    if (fatherField instanceof ReverseLinkedTable) {
      return;
    }
    if (!ez5.version("6")) {
      if (!(field.isVisible("facet") || field.isVisible("expert"))) {
        return;
      }
      if (fatherField && !(fatherField.isVisible("facet") || fatherField.isVisible("expert"))) {
        return;
      }
    }
    ObjecttypeCSVImporterDestinationField.__super__.addToMatchExisting.call(this, select_opts, set_dest_fields);
    path_dest_field = null;
    for (i = 0, len = set_dest_fields.length; i < len; i++) {
      dest_field = set_dest_fields[i];
      ref = this._csvImporter.getMappingConfigsForDestinationField(dest_field);
      for (j = 0, len1 = ref.length; j < len1; j++) {
        config = ref[j];
        if (!CUI.util.isEmpty(config.config.level)) {
          path_dest_field = dest_field;
          break;
        }
      }
      if (path_dest_field) {
        break;
      }
    }
    if (path_dest_field && path_dest_field !== this) {
      select_opts[select_opts.length - 1].disabled = true;
    }
  };

  ObjecttypeCSVImporterDestinationField.prototype.isReadOnly = function() {
    return this._read_only;
  };

  ObjecttypeCSVImporterDestinationField.prototype.getRecordValue = function(configs, row, opts) {
    var __configs, _configs, config, i, j, len, len1, level, ref, value;
    if (opts == null) {
      opts = {};
    }
    if (this.isReadOnly() && opts.operation) {
      return void 0;
    }
    if (((ref = this._csvImporter.path_dest) != null ? ref.field : void 0) === this) {
      __configs = configs.slice(0);
      __configs.sort(function(a, b) {
        return CUI.util.compareIndex(a.config.level, b.config.level);
      });
      level = void 0;
      for (i = 0, len = __configs.length; i < len; i++) {
        config = __configs[i];
        value = row[config.csv_field_idx];
        if (!CUI.util.isEmpty(value)) {
          level = config.config.level;
        }
      }
      if (level === void 0) {
        _configs = configs.slice(0);
      } else {
        _configs = [];
        for (j = 0, len1 = configs.length; j < len1; j++) {
          config = configs[j];
          if (config.config.level === level) {
            _configs.push(config);
          }
        }
      }
    } else {
      _configs = configs.slice(0);
    }
    if (this.recordFromMultipleColumns()) {
      return this.getRecordValueFromMultipleColumns(_configs, row, opts);
    } else {
      return ObjecttypeCSVImporterDestinationField.__super__.getRecordValue.call(this, _configs, row, opts);
    }
  };

  ObjecttypeCSVImporterDestinationField.prototype.recordFromMultipleColumns = function() {
    return false;
  };

  ObjecttypeCSVImporterDestinationField.prototype.setValuesFromMultipleColumns = function(config, values, value, idx) {
    console.error(CUI.util.getObjectClass(this) + ".setValuesFromMultipleColumns needs implementation.");
  };

  ObjecttypeCSVImporterDestinationField.prototype.getRecordValueFromMultipleColumns = function(configs, row, opts) {
    var _row, addReturnValues, config, i, idx, info, j, len, len1, nestedIndex, nestedValues, ref, ref1, ref2, returnValues, value, values;
    if (opts == null) {
      opts = {};
    }
    values = [];
    for (i = 0, len = configs.length; i < len; i++) {
      config = configs[i];
      value = row[config.csv_field_idx];
      if (this.getNestedDepth() >= 1) {
        nestedIndex = (ref = config.indices) != null ? ref.join() : void 0;
        if (nestedIndex) {
          if (!values[nestedIndex]) {
            values[nestedIndex] = [];
          }
          nestedValues = values[nestedIndex];
        }
        info = this.csvData.parse({
          quotechar: '"',
          delimiter: "",
          text: value,
          defer: false
        });
        ref1 = info.rows;
        for (idx = j = 0, len1 = ref1.length; j < len1; idx = ++j) {
          _row = ref1[idx];
          this.setValuesFromMultipleColumns(config, nestedValues || values, (ref2 = _row[0]) != null ? ref2.trim() : void 0, idx);
        }
      } else {
        this.setValuesFromMultipleColumns(config, values, value, 0);
      }
    }
    if (this.getNestedDepth() > 0) {
      returnValues = [];
      addReturnValues = (function(_this) {
        return function(_values) {
          var k, len2, results;
          if (CUI.util.isArray(_values)) {
            results = [];
            for (k = 0, len2 = _values.length; k < len2; k++) {
              value = _values[k];
              results.push(addReturnValues(value));
            }
            return results;
          } else {
            return returnValues.push(_values);
          }
        };
      })(this);
      addReturnValues(values);
      return returnValues;
    } else {
      return values[0];
    }
  };

  ObjecttypeCSVImporterDestinationField.prototype.finalizeRecord = function(record, row, opts) {
    var field, otName, otRecords, reverseLinkedTable;
    field = this.getField();
    if (field.insideNested() && field.mask.nestedTableField instanceof ReverseLinkedTable) {
      reverseLinkedTable = field.mask.nestedTableField;
      if (reverseLinkedTable.getFatherField()) {
        return;
      }
      otName = this._csvImporter.getFormSaveData().objecttype;
      otRecords = record[otName][reverseLinkedTable.name()];
      if (!otRecords || otRecords.length === 0) {
        return;
      }
      if (!record.__reverseLinkedTableNames) {
        record.__reverseLinkedTableNames = [];
      }
      if (!record.__reverseLinkedTableNames.includes(reverseLinkedTable.name())) {
        record.__reverseLinkedTableNames.push(reverseLinkedTable.name());
      }
      this.__addReverseLinkedTableDefaultVersion(otRecords, reverseLinkedTable.name());
      if (reverseLinkedTable.mainMask.poolLink()) {
        this.__addReverseLinkedTablePool(otRecords);
      }
    }
  };

  ObjecttypeCSVImporterDestinationField.prototype.__addReverseLinkedTableDefaultVersion = function(records, name) {
    var data, i, len;
    if (!records) {
      return;
    }
    for (i = 0, len = records.length; i < len; i++) {
      data = records[i];
      if (!data._version) {
        data._version = 1;
      }
      if (data[name]) {
        this.__addReverseLinkedTableDefaultVersion(data[name], name);
      }
    }
  };

  ObjecttypeCSVImporterDestinationField.prototype.__addReverseLinkedTablePool = function(records) {
    var data, i, len, ref, ref1;
    for (i = 0, len = records.length; i < len; i++) {
      data = records[i];
      if (data._pool) {
        continue;
      }
      data._pool = {
        pool: {
          _id: (ref = this._csvImporter.getFormSaveData()._pool) != null ? (ref1 = ref.pool) != null ? ref1._id : void 0 : void 0
        }
      };
    }
  };

  return ObjecttypeCSVImporterDestinationField;

})(CSVImporterDestinationField);
// Generated by CoffeeScript 1.12.7
var HeadlessObjecttypeCSVImporter,
  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;

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

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

  HeadlessObjecttypeCSVImporter.prototype.startHeadlessImport = function(opts) {
    var importerDfr;
    this.__setingsUploadedText = {
      setText: (function(_this) {
        return function() {
          return {};
        };
      })(this)
    };
    this.resetFile();
    this.__form_data.csv_filename = opts.csv_filename;
    this.__csv_text = opts.csv_text;
    importerDfr = new CUI.Deferred();
    this.__objecttypes_promise.done((function(_this) {
      return function() {
        return _this.__startImport(opts).done(function() {
          return importerDfr.resolve(_this.__report);
        }).fail(function(err) {
          return importerDfr.reject(err);
        });
      };
    })(this));
    return importerDfr.promise();
  };

  HeadlessObjecttypeCSVImporter.prototype.__startImport = function(opts) {
    var action_done, action_fail, dfr;
    dfr = new CUI.Deferred();
    if (opts.collection) {
      this.__form_data.collection = opts.collection;
    }
    action_done = (function(_this) {
      return function() {
        return _this.__finishImport().done(dfr.resolve);
      };
    })(this);
    action_fail = (function(_this) {
      return function(err) {
        console.error("HeadlessObjecttypeCSVImporter.startHeadlessImport: action_fail", err);
        return dfr.reject(err);
      };
    })(this);
    this.__loadCSVData().done((function(_this) {
      return function() {
        return _this.loadSettings(opts.settings, true).done(function() {
          var mappingForm;
          _this.reloadFormData();
          _this.initMapping();
          mappingForm = _this.getMappingForm();
          return _this.getReadyForPrepare().done(function() {
            return _this.__prepareData().done(function() {
              var doInserts, doUpdates, effectiveInserts, effectiveUpdates, ev, importMode, inserts, skippedInserts, skippedUpdates, updates;
              _this.collectReadyRows();
              updates = _this.__readyRows.update.length;
              inserts = _this.__readyRows.insert.length;
              importMode = opts.import_mode || "both";
              doInserts = importMode !== "update_only";
              doUpdates = importMode !== "insert_only";
              effectiveInserts = doInserts ? inserts : 0;
              effectiveUpdates = doUpdates ? updates : 0;
              skippedInserts = doInserts ? 0 : inserts;
              skippedUpdates = doUpdates ? 0 : updates;
              console.log("HeadlessObjecttypeCSVImporter.startHeadlessImport: mode: " + importMode + ", updates: " + updates + " (skipped: " + skippedUpdates + "), inserts: " + inserts + " (skipped: " + skippedInserts + ")");
              ev = {};
              ev.hasModifierKey = function() {
                if (opts.debug_mode) {
                  return true;
                } else {
                  return false;
                }
              };
              if (effectiveInserts === 0 && effectiveUpdates > 0) {
                _this.__action(ev, "update").done(action_done).fail(action_fail);
              }
              if (effectiveInserts > 0) {
                _this.__action(ev, "insert").done(function() {
                  if (effectiveUpdates > 0) {
                    return _this.__action(ev, "update").done(action_done).fail(action_fail);
                  } else {
                    return action_done();
                  }
                }).fail(action_fail);
              }
              if (effectiveInserts === 0 && effectiveUpdates === 0) {
                return action_done();
              }
            });
          });
        });
      };
    })(this));
    return dfr.promise();
  };

  HeadlessObjecttypeCSVImporter.prototype.__prepareData = function() {
    var promise, rows;
    rows = this.getRows();
    this.__beforePrepareData(rows);
    promise = this.prepareData(rows);
    promise.fail((function(_this) {
      return function() {
        return _this.resetReadyRows();
      };
    })(this));
    promise.done((function(_this) {
      return function() {
        return _this.collectReadyRows();
      };
    })(this));
    return promise;
  };

  HeadlessObjecttypeCSVImporter.prototype.updateModal = function() {};

  HeadlessObjecttypeCSVImporter.prototype.updateStatsTable = function() {};

  HeadlessObjecttypeCSVImporter.prototype.__finishImport = function() {
    return new CUI.Deferred().resolve().promise();
  };

  HeadlessObjecttypeCSVImporter.prototype.__getActionConfirmation = function() {
    return new CUI.resolvedPromise();
  };

  HeadlessObjecttypeCSVImporter.prototype.__getSupportedEASTypes = function() {
    return [
      {
        text: $$("eas.importer.fields.eas_type.url.option.label"),
        value: EASImporter.EAS_TYPE.URL
      }, {
        text: $$("eas.importer.fields.eas_type.ignore.option.label"),
        value: EASImporter.EAS_TYPE.IGNORE
      }
    ];
  };

  HeadlessObjecttypeCSVImporter.prototype.__addRecordsToReport = function(records, op) {
    var base;
    if (this.__report == null) {
      this.__report = {};
    }
    if ((base = this.__report)[op] == null) {
      base[op] = {};
    }
    return records.forEach((function(_this) {
      return function(record) {
        var base1, name;
        if ((base1 = _this.__report[op])[name = record._objecttype] == null) {
          base1[name] = [];
        }
        return _this.__report[op][record._objecttype].push(record[record._objecttype]._id);
      };
    })(this));
  };

  return HeadlessObjecttypeCSVImporter;

})(ObjecttypeCSVImporter);
// Generated by CoffeeScript 1.12.7
var LinkedObjectCSVImporterDestinationField,
  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,
  slice = [].slice;

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

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

  LinkedObjectCSVImporterDestinationField.prototype.initOpts = function() {
    LinkedObjectCSVImporterDestinationField.__super__.initOpts.call(this);
    return this.mergeOpt("field", {
      check: LinkedObject
    });
  };

  LinkedObjectCSVImporterDestinationField.prototype.readOpts = function() {
    var field, fieldLabel, i, j, lang, len, len1, ref, ref1, split_opts, tooltipLabel;
    LinkedObjectCSVImporterDestinationField.__super__.readOpts.call(this);
    this.__mask = this.getField().linkMask();
    this.__mask_name = this.__mask.name();
    this.__ot_name = this.__mask.getTable().name();
    this.__obj_keys = ["_id", "_version"];
    if (this.__mask.isHierarchy()) {
      this.__obj_keys.push("_id_parent");
    }
    this.__custom_opts = [];
    ref = this.__mask.getFields("csv-import");
    for (i = 0, len = ref.length; i < len; i++) {
      field = ref[i];
      if (field instanceof GlobalObjectIdColumn) {
        continue;
      }
      if (!(field instanceof PrimaryKeyColumn) && !field.isVisible("expert")) {
        continue;
      }
      fieldLabel = this._csvImporter.getFormData().show_localized_names ? field.nameLocalized() : field.name();
      tooltipLabel = this._csvImporter.getFormData().show_localized_names ? field.name() : field.nameLocalized();
      if (field instanceof LocaTextColumn) {
        ref1 = ez5.loca.getDatabaseLanguages();
        for (j = 0, len1 = ref1.length; j < len1; j++) {
          lang = ref1[j];
          this.__custom_opts.push({
            text: fieldLabel + '#' + lang,
            value: field.name() + '#' + lang,
            tooltip: {
              text: tooltipLabel + '#' + lang
            }
          });
        }
        continue;
      }
      if (field instanceof TextColumn || field instanceof PrimaryKeyColumn) {
        this.__custom_opts.push({
          text: fieldLabel,
          value: field.name(),
          tooltip: {
            text: tooltipLabel
          }
        });
        continue;
      }
    }
    this.__custom_opts.sort(function(a, b) {
      return a.text.localeCompare(b.text);
    });
    this.__custom_opts.unshift({
      text: $$("linked.object.csv.importer.destination.field.column.placeholder"),
      value: null
    });
    this.__custom_fields = [
      {
        name: "column",
        undo_and_changed_support: false,
        form: {
          label: $$("linked.object.csv.importer.destination.field.column.label")
        },
        type: CUI.Select,
        options: this.__custom_opts
      }
    ];
    if (this.__mask.isHierarchy()) {
      split_opts = [
        {
          value: null,
          text: $$("linked.object.csv.importer.destination.field.hierarchy_split.none")
        }, {
          value: ">",
          text: ">"
        }, {
          value: "/",
          text: "/"
        }
      ];
      this.__custom_fields.push({
        name: "hierarchy_split",
        form: {
          label: $$("linked.object.csv.importer.destination.field.hierarchy_split.label")
        },
        type: CUI.Select,
        options: split_opts
      });
    }
    return this;
  };

  LinkedObjectCSVImporterDestinationField.prototype.getControlFields = function() {
    var fields;
    return fields = [
      {
        name: this.getControlName()
      }
    ];
  };

  LinkedObjectCSVImporterDestinationField.prototype.getControlName = function() {
    return this.__ot_name + "|" + this.__mask_name;
  };

  LinkedObjectCSVImporterDestinationField.prototype.getCustomFields = function() {
    return this.__custom_fields;
  };

  LinkedObjectCSVImporterDestinationField.prototype.getValueForCustom = function(key, value) {
    var i, len, opt, ref;
    ref = this.__custom_opts;
    for (i = 0, len = ref.length; i < len; i++) {
      opt = ref[i];
      if (opt.value === value) {
        return value;
      }
    }
    return null;
  };

  LinkedObjectCSVImporterDestinationField.prototype.getReadyForPrepare = function(configs) {
    var col, config, differentIndices, i, j, l, len, len1, len2, len3, linkedObject, linkedObjects, m, ref, row, search_columns, storedLinkedObject, uniqueIndices;
    this.__linked_objects = this._csvImporter.linked_objects_by_mask[this.getControlName()];
    this.__control_idx = this._csvImporter.cf_idx[this.getControlName()];
    if (!this.__linked_objects) {
      this.__linked_objects = this._csvImporter.linked_objects_by_mask[this.getControlName()] = [];
    }
    this.__identifier_keys = this.getIdentifierKeys(configs);
    search_columns = {};
    for (i = 0, len = configs.length; i < len; i++) {
      config = configs[i];
      col = config.config.column;
      if ((this.__mask.isHierarchy() && config.config.hierarchy_split) && (!col || configs.length > 1)) {
        return CUI.rejectedPromise("linked.object.csv.importer.destination.field.error.duplicate_mapping", {
          field: this.getField().getCSVLabel()
        });
      }
      if ((!col && configs.length > 1) || search_columns[col]) {
        if (config.nestedDepth > 0) {
          continue;
        }
        differentIndices = false;
        if (!CUI.util.isEmpty(configs[0].indices)) {
          uniqueIndices = new Set();
          for (j = 0, len1 = configs.length; j < len1; j++) {
            config = configs[j];
            uniqueIndices.add(config.indices.join());
          }
          differentIndices = uniqueIndices.size === configs.length;
        }
        if (!differentIndices) {
          return CUI.rejectedPromise("linked.object.csv.importer.destination.field.error.duplicate_mapping", {
            field: this.getField().getCSVLabel()
          });
        }
      }
      search_columns[col] = true;
    }
    ref = this._csvImporter.getRows();
    for (l = 0, len2 = ref.length; l < len2; l++) {
      row = ref[l];
      linkedObjects = this.__getLinkedObjectsFromRow(configs, row);
      if (linkedObjects.length === 0) {
        continue;
      }
      for (m = 0, len3 = linkedObjects.length; m < len3; m++) {
        linkedObject = linkedObjects[m];
        if (CUI.util.isEmpty(linkedObject)) {
          continue;
        }
        storedLinkedObject = this.__findLinkedObject(linkedObject);
        if (storedLinkedObject) {
          continue;
        }
        if (!linkedObject._row_idx) {
          linkedObject._row_idx = [];
        }
        this.__linked_objects.push(linkedObject);
      }
    }
    return CUI.resolvedPromise();
  };

  LinkedObjectCSVImporterDestinationField.prototype.__getLinkedRecord = function(linked_object) {
    var idPool, record, ref, ref1;
    if (!linked_object) {
      return null;
    }
    record = {
      _mask: this.__mask.name(),
      _objecttype: this.__ot_name
    };
    if (parseInt(linked_object._id) > 0) {
      record[this.__ot_name] = {
        _id: linked_object._id
      };
    } else if (parseInt(linked_object._system_object_id) > 0) {
      record._system_object_id = parseInt(linked_object._system_object_id);
      record[this.__ot_name] = {};
    } else if (linked_object._id === "new") {
      record[this.__ot_name] = this.getLinkedObjectValue(linked_object);
      record[this.__ot_name]._id = null;
      record[this.__ot_name]._version = 1;
      if (ez5.schema.CURRENT._table_by_name[this.__ot_name].pool_link) {
        idPool = (ref = this._csvImporter.getFormData()._pool_linked_objects) != null ? (ref1 = ref.pool) != null ? ref1._id : void 0 : void 0;
        record[this.__ot_name]._pool = {
          pool: {
            _id: idPool
          }
        };
      }
    } else {
      return null;
    }
    if (this.__mask.isHierarchy()) {
      record[this.__ot_name]._id_parent = linked_object._id_parent || null;
    }
    return record;
  };

  LinkedObjectCSVImporterDestinationField.prototype.getRecordValue = function(configs, row, opts) {
    var _linked, _linkedObjects, _linked_object, found, i, idx, j, len, len1, linked, linked_object, linked_objects, ret_linked;
    if (opts == null) {
      opts = {};
    }
    ret_linked = [];
    linked_objects = this.__getLinkedObjectsFromRow(configs, row, opts) || [];
    for (idx = i = 0, len = linked_objects.length; i < len; idx = ++i) {
      linked_object = linked_objects[idx];
      if (!linked_object) {
        continue;
      }
      if (linked_object.__hierarchy_split && !linked_object.__actual) {
        continue;
      }
      if (!opts.for_preview) {
        _linked_object = this.__findLinkedObject(linked_object);
        found = this.__getLinkedRecord(_linked_object);
        if (!found) {
          continue;
        }
      } else {
        found = linked_object;
      }
      if (!this.getNestedDepth() && idx === linked_objects.length - 1) {
        return found;
      }
      ret_linked.push(found);
    }
    if (!this.getNestedDepth()) {

    } else {
      if (opts.for_preview_detail) {
        _linkedObjects = [];
        for (j = 0, len1 = ret_linked.length; j < len1; j++) {
          linked = ret_linked[j];
          _linked = {};
          _linked[this.__ot_name] = linked[this.__ot_name];
          _linked._mask = this.__mask_name;
          _linked._objecttype = this.__ot_name;
          _linked._format = "long";
          if (_linked[this.__ot_name]._system_object_id) {
            _linked._system_object_id = _linked[this.__ot_name]._system_object_id;
          }
          if (this.__identifier_keys.length === 1 && this.__identifier_keys[0] === "_id") {
            _linked._standard = {};
            _linked._standard["1"] = {
              html: {}
            };
            _linked._standard["1"].html[ez5.loca.culture] = _linked[this.__ot_name]._id;
          }
          _linkedObjects.push(_linked);
        }
        return _linkedObjects;
      }
      return ret_linked;
    }
  };

  LinkedObjectCSVImporterDestinationField.prototype.getLinkedObjectValue = function(linked_object) {
    var _key, field, i, info, key, languages, len, ref, ref1;
    info = {};
    ref = this.__identifier_keys;
    for (i = 0, len = ref.length; i < len; i++) {
      key = ref[i];
      if (CUI.util.isEmpty(linked_object[key])) {
        info[key] = void 0;
      } else {
        ref1 = key.split('#'), _key = ref1[0], languages = 2 <= ref1.length ? slice.call(ref1, 1) : [];
        if (languages.length > 0) {
          info[_key] = {};
          info[_key][languages[0]] = linked_object[key];
        } else {
          field = this.getIdentifierKeyField(key);
          if (field instanceof NumberColumn) {
            info[key] = parseInt(linked_object[key]);
          } else if (field instanceof DecimalColumn) {
            info[key] = parseFloat(linked_object[key]);
          } else if (field instanceof DoubleColumn) {
            info[key] = parseFloat(linked_object[key]);
          } else {
            info[key] = linked_object[key];
          }
        }
      }
    }
    return info;
  };

  LinkedObjectCSVImporterDestinationField.prototype.getIdentifierKeyField = function(key) {
    var ref, ref1;
    return (ref = this.getField().linkMask()) != null ? (ref1 = ref.fields) != null ? ref1.find((function(_this) {
      return function(f) {
        return f.name() === key;
      };
    })(this)) : void 0 : void 0;
  };

  LinkedObjectCSVImporterDestinationField.prototype.getIdentifierKeys = function(configs) {
    var config, i, identifier_keys, len;
    identifier_keys = [];
    for (i = 0, len = configs.length; i < len; i++) {
      config = configs[i];
      CUI.util.pushOntoArray(this.getColName(config), identifier_keys);
    }
    return identifier_keys;
  };

  LinkedObjectCSVImporterDestinationField.prototype.getColName = function(config) {
    if (!config.config.column) {
      return "_id";
    } else {
      return config.config.column;
    }
  };

  LinkedObjectCSVImporterDestinationField.prototype.__getLinkedObjectsFromRow = function(configs, row, opts) {
    var __value, _intValue, _linked, _linkedObjects, _value, cell_info, cell_row, col_field, col_name, config, i, idx, j, l, len, len1, len2, len3, linked, linked_objects, lobj, m, n, path, pidx, ref, ref1, ref2, value;
    if (opts == null) {
      opts = {};
    }
    linked_objects = [];
    for (i = 0, len = configs.length; i < len; i++) {
      config = configs[i];
      value = row[config.csv_field_idx];
      if (CUI.util.isEmpty(value)) {
        continue;
      }
      if (!CUI.util.isString(value)) {
        continue;
      }
      if (this.__mask.isHierarchy() && config.config.hierarchy_split) {
        cell_info = this.csvData.parse({
          quotechar: '"',
          delimiter: config.config.hierarchy_split,
          text: value,
          defer: false
        });
      } else {
        cell_info = this.csvData.parse({
          quotechar: '"',
          delimiter: "",
          text: value,
          defer: false
        });
      }
      col_name = this.getColName(config);
      ref = cell_info.rows;
      for (idx = j = 0, len1 = ref.length; j < len1; idx = ++j) {
        cell_row = ref[idx];
        if (!this.__mask.isHierarchy() || !config.config.hierarchy_split) {
          _value = (ref1 = cell_row[0]) != null ? ref1.trim() : void 0;
          if (!linked_objects[idx]) {
            linked_objects[idx] = {};
          } else if (this.getNestedDepth()) {
            idx = linked_objects.length + idx;
            linked_objects[idx] = {};
          }
          if (CUI.util.isEmpty(_value)) {
            continue;
          }
          if (col_name === "_id" || col_name === "_system_object_id") {
            _intValue = parseInt(_value);
            if (isNaN(_intValue)) {
              linked_objects[idx][col_name] = "invalid: " + _value;
              this._csvImporter.setRowInvalid(row, "number.column.csv.importer.destination.field.number_invalid", {
                number: _value
              });
            } else {
              linked_objects[idx][col_name] = _intValue;
            }
          } else {
            col_field = this.getIdentifierKeyField(col_name);
            if (col_field instanceof NumberColumn) {
              _value = parseInt(_value);
            } else if (col_field instanceof DecimalColumn || col_field instanceof DoubleColumn) {
              _value = parseFloat(_value);
            }
            linked_objects[idx][col_name] = _value;
          }
          continue;
        }
        path = [];
        for (l = 0, len2 = cell_row.length; l < len2; l++) {
          __value = cell_row[l];
          _value = __value.trim();
          if (_value === "") {
            break;
          }
          path.push(_value);
        }
        if (path.length === 0) {
          continue;
        }
        for (pidx = m = 0, ref2 = path.length; 0 <= ref2 ? m < ref2 : m > ref2; pidx = 0 <= ref2 ? ++m : --m) {
          lobj = {};
          lobj[col_name] = path[pidx];
          lobj._depth = pidx;
          if (pidx === 0) {
            lobj._id_parent = null;
          } else {
            lobj._id_parent = JSON.stringify(path.slice(0, pidx));
          }
          if (this.__mask.isHierarchy()) {
            lobj.__hierarchy_split = config.config.hierarchy_split;
          }
          if (pidx === path.length - 1) {
            lobj.__actual = true;
          } else {
            lobj.__actual = false;
          }
          lobj._path = JSON.stringify(path.slice(0, pidx + 1));
          linked_objects.push(lobj);
        }
      }
    }
    if (opts.for_preview_detail) {
      _linkedObjects = [];
      this.__identifier_keys = this.getIdentifierKeys(configs);
      for (n = 0, len3 = linked_objects.length; n < len3; n++) {
        linked = linked_objects[n];
        _linked = {};
        _linked[this.__ot_name] = this.getLinkedObjectValue(linked);
        _linked._mask = this.__mask_name;
        _linked._objecttype = this.__ot_name;
        _linked._format = "long";
        _linked._depth = linked._depth;
        _linked.__actual = linked.__actual;
        _linked.__hierarchy_split = linked.__hierarchy_split;
        if (this.__identifier_keys.length === 1 && this.__identifier_keys[0] === "_id") {
          _linked._standard = {};
          _linked._standard["1"] = {
            html: {}
          };
          _linked._standard["1"].html[ez5.loca.culture] = _linked[this.__ot_name]._id;
        }
        _linkedObjects.push(_linked);
      }
      return _linkedObjects;
    }
    return linked_objects;
  };

  LinkedObjectCSVImporterDestinationField.prototype.action = function(ev, op, rows) {
    var allRows, availableRowIndicesMap, depth, dfr, i, j, len, len1, linked_object, max_depth, next_depth, ref, row;
    allRows = this._csvImporter.getRows();
    availableRowIndicesMap = {};
    for (i = 0, len = rows.length; i < len; i++) {
      row = rows[i];
      availableRowIndicesMap[allRows.indexOf(row)] = true;
    }
    max_depth = 0;
    depth = null;
    ref = this.__linked_objects;
    for (j = 0, len1 = ref.length; j < len1; j++) {
      linked_object = ref[j];
      if (linked_object._id !== "new") {
        continue;
      }
      if (this.__mask.isHierarchy()) {
        linked_object._depth = linked_object._depth || 0;
        max_depth = Math.max(max_depth, linked_object._depth);
      }
    }
    next_depth = (function(_this) {
      return function() {
        var l, len2, linked_objects, objects, records, ref1;
        if (max_depth === depth) {
          dfr.resolve();
          return;
        }
        if (depth === null) {
          depth = 0;
        } else {
          depth = depth + 1;
        }
        records = [];
        linked_objects = [];
        ref1 = _this.__linked_objects;
        for (l = 0, len2 = ref1.length; l < len2; l++) {
          linked_object = ref1[l];
          if (linked_object._id !== "new") {
            continue;
          }
          if (_this.__mask.isHierarchy() && depth !== linked_object._depth) {
            continue;
          }
          if (!linked_object._row_idx.some(function(index) {
            return availableRowIndicesMap[index];
          })) {
            continue;
          }
          records.push(_this.__getLinkedRecord(linked_object));
          linked_objects.push(linked_object);
        }
        if (records.length === 0) {
          next_depth();
          return;
        }
        if (ev.hasModifierKey()) {
          console.debug(CUI.util.dump(records));
          next_depth();
          return;
        }
        objects = [];
        CUI.chunkWork.call(_this, {
          items: records,
          chunk_size: 1000,
          call: function(items) {
            return ez5.api.db({
              api: "/" + _this.__ot_name,
              data: {
                format: "short"
              },
              json_data: items
            }).done(function(_objects) {
              return objects.push.apply(objects, _objects);
            });
          }
        }).done(function() {
          var idx, key, len3, len4, len5, m, n, o, obj, ref2, ref3;
          for (idx = m = 0, len3 = objects.length; m < len3; idx = ++m) {
            obj = objects[idx];
            if (_this.__mask.isHierarchy()) {
              ref2 = _this.__linked_objects;
              for (n = 0, len4 = ref2.length; n < len4; n++) {
                linked_object = ref2[n];
                if (linked_object._id_parent && linked_object._id_parent === linked_objects[idx]._path) {
                  linked_object._id_parent = obj[_this.__ot_name]._id;
                }
              }
            }
            ref3 = _this.__obj_keys;
            for (o = 0, len5 = ref3.length; o < len5; o++) {
              key = ref3[o];
              linked_objects[idx][key] = obj[_this.__ot_name][key];
            }
          }
          console.info("Created objects.", depth, objects);
          return next_depth();
        }).fail(dfr.reject);
      };
    })(this);
    dfr = new CUI.Deferred();
    next_depth();
    return dfr.promise();
  };

  LinkedObjectCSVImporterDestinationField.prototype.__findLinkedObject = function(search_linked_object, use_hierarchy_setting) {
    var i, j, key, len, len1, linked_object, match, ref, ref1;
    if (use_hierarchy_setting == null) {
      use_hierarchy_setting = true;
    }
    ref = this.__linked_objects;
    for (i = 0, len = ref.length; i < len; i++) {
      linked_object = ref[i];
      if (search_linked_object._path && search_linked_object._path === linked_object._path) {
        return linked_object;
      }
      match = true;
      ref1 = this.__identifier_keys;
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        key = ref1[j];
        if (linked_object[key] !== search_linked_object[key]) {
          match = false;
          break;
        }
      }
      if (this.__mask.isHierarchy() && (!use_hierarchy_setting || linked_object.__hierarchy_split)) {
        if (linked_object._id_parent) {
          if (linked_object._id_parent !== search_linked_object._id_parent) {
            match = false;
          }
        }
      }
      if (match) {
        return linked_object;
      }
    }
    return null;
  };

  LinkedObjectCSVImporterDestinationField.prototype.prepareDataChunk = function(configs, rows, offset) {
    var _key, dfr, do_next_search, fieldName, fields, i, j, key, l, languages, len, len1, len2, linked_object, linked_objects, max_depth, ref, ref1, row, row_idx, search_depth, search_opts, storedLinkedObject;
    dfr = new CUI.Deferred();
    max_depth = null;
    for (row_idx = i = 0, len = rows.length; i < len; row_idx = ++i) {
      row = rows[row_idx];
      linked_objects = this.__getLinkedObjectsFromRow(configs, row);
      if (linked_objects.length === 0) {
        continue;
      }
      for (j = 0, len1 = linked_objects.length; j < len1; j++) {
        linked_object = linked_objects[j];
        if (CUI.util.isEmpty(linked_object)) {
          continue;
        }
        storedLinkedObject = this.__findLinkedObject(linked_object);
        if (!storedLinkedObject) {
          console.error("Linked object stored not found", linked_object, this.__linked_objects);
          continue;
        }
        if (storedLinkedObject._depth !== void 0) {
          max_depth = Math.max(max_depth, storedLinkedObject._depth);
        }
        if (!storedLinkedObject._id) {
          storedLinkedObject._id = "search";
        }
        CUI.util.pushOntoArray(row_idx + offset, storedLinkedObject._row_idx);
      }
    }
    fields = [];
    ref = this.__identifier_keys;
    for (l = 0, len2 = ref.length; l < len2; l++) {
      key = ref[l];
      ref1 = key.split('#'), _key = ref1[0], languages = 2 <= ref1.length ? slice.call(ref1, 1) : [];
      if (_key === "_system_object_id") {
        fieldName = _key;
      } else {
        fieldName = this.__ot_name + "." + _key;
      }
      fields.push({
        key: _key,
        field: fieldName
      });
    }
    search_opts = {
      type: "object",
      fields: fields,
      format: "short",
      generate_rights: false,
      objecttypes: [this.__ot_name],
      search: []
    };
    search_depth = void 0;
    do_next_search = (function(_this) {
      return function() {
        var len3, len4, m, n, ref2, ref3, ref4, ref5, ref6, ref7, search, searchValue;
        search_opts.search = [];
        if (search_depth === void 0) {
          if (max_depth === null) {
            search_depth = null;
          } else {
            search_depth = 0;
          }
        } else if (search_depth === null) {
          dfr.resolve();
          return;
        } else {
          search_depth = search_depth + 1;
          if (search_depth === max_depth + 1) {
            search_depth = null;
          }
        }
        ref2 = _this.__linked_objects;
        for (m = 0, len3 = ref2.length; m < len3; m++) {
          linked_object = ref2[m];
          if (linked_object._id !== "search") {
            continue;
          }
          if (search_depth !== null && search_depth !== linked_object._depth) {
            continue;
          }
          if (CUI.util.isString(linked_object._id_parent)) {
            linked_object._id = "new";
            continue;
          }
          linked_object._id = "searching";
          search = {
            type: "complex",
            bool: "should",
            search: []
          };
          ref3 = _this.__identifier_keys;
          for (n = 0, len4 = ref3.length; n < len4; n++) {
            key = ref3[n];
            ref4 = key.split('#'), _key = ref4[0], languages = 2 <= ref4.length ? slice.call(ref4, 1) : [];
            searchValue = linked_object[key];
            if (CUI.util.isString(searchValue) && searchValue.length > SearchUtil.SEARCH_MAX_LENGTH) {
              searchValue = searchValue.substring(0, SearchUtil.SEARCH_MAX_LENGTH);
            }
            if (_key === "_system_object_id") {
              fieldName = _key;
            } else {
              fieldName = _this.__ot_name + "." + _key;
            }
            if (!isNaN(searchValue)) {
              if ((ref5 = (ref6 = ez5.schema.CURRENT._objecttype_by_name[_this.__ot_name]) != null ? (ref7 = ref6._column_by_name[_key]) != null ? ref7.type : void 0 : void 0) === "number" || ref5 === "integer.2") {
                searchValue = parseFloat(searchValue);
              }
            }
            search.search.push({
              type: "in",
              bool: "must",
              fields: [fieldName],
              "in": [searchValue],
              languages: languages
            });
          }
          if (linked_object._id_parent !== void 0) {
            search.search.push({
              type: "in",
              bool: "must",
              fields: [_this.__ot_name + "._id_parent"],
              "in": [linked_object._id_parent]
            });
          }
          search_opts.search.push(search);
        }
        if (search_opts.search.length === 0) {
          _this.__updateFoundLinkedObjects();
          do_next_search();
        } else {
          if (languages && languages[0]) {
            search_opts.language = languages[0];
          }
          ez5.api.search({
            json_data: search_opts
          }).done(function(data) {
            var ex;
            try {
              _this.__updateFoundLinkedObjects(data.objects);
              return do_next_search();
            } catch (error) {
              ex = error;
              if (ex === "not_allowed_to_create_linked_objects") {
                return dfr.reject("linked.object.csv.importer.destination.field." + ex);
              } else {
                throw ex;
              }
            }
          }).fail(dfr.reject);
        }
      };
    })(this);
    dfr.always((function(_this) {
      return function() {
        var len3, len4, len5, len6, linked_object_per_row_idx, m, n, o, p, ref2, ref3;
        linked_object_per_row_idx = {};
        ref2 = _this.__linked_objects;
        for (m = 0, len3 = ref2.length; m < len3; m++) {
          linked_object = ref2[m];
          ref3 = linked_object._row_idx;
          for (n = 0, len4 = ref3.length; n < len4; n++) {
            row_idx = ref3[n];
            if (row_idx < offset) {
              continue;
            }
            if (!linked_object_per_row_idx[row_idx]) {
              linked_object_per_row_idx[row_idx] = [];
            }
            CUI.util.pushOntoArray(linked_object, linked_object_per_row_idx[row_idx]);
          }
        }
        for (o = 0, len5 = rows.length; o < len5; o++) {
          row = rows[o];
          row[_this.__control_idx] = "";
        }
        for (row_idx in linked_object_per_row_idx) {
          linked_objects = linked_object_per_row_idx[row_idx];
          for (p = 0, len6 = linked_objects.length; p < len6; p++) {
            linked_object = linked_objects[p];
            rows[row_idx - offset][_this.__control_idx] += JSON.stringify(_this.getLinkedObjectValue(linked_object)) + ": " + linked_object._id + "\n";
          }
        }
      };
    })(this));
    do_next_search();
    return dfr.promise();
  };

  LinkedObjectCSVImporterDestinationField.prototype.__updateFoundLinkedObjects = function(objs) {
    var _key, found_linked_object, i, j, k, key, l, languages, len, len1, len2, len3, len4, linked_object, m, n, obj, ref, ref1, ref2, ref3, ref4, stored_linked_object, v;
    if (objs == null) {
      objs = [];
    }
    for (i = 0, len = objs.length; i < len; i++) {
      obj = objs[i];
      found_linked_object = {};
      ref = this.__identifier_keys;
      for (j = 0, len1 = ref.length; j < len1; j++) {
        key = ref[j];
        ref1 = key.split('#'), _key = ref1[0], languages = 2 <= ref1.length ? slice.call(ref1, 1) : [];
        found_linked_object[key] = obj._fields[_key][0];
        if (_key === "_system_object_id") {
          found_linked_object[key] = parseInt(found_linked_object[key]);
        }
      }
      if (obj[this.__ot_name]._id_parent) {
        found_linked_object._id_parent = obj[this.__ot_name]._id_parent;
      }
      stored_linked_object = this.__findLinkedObject(found_linked_object, false);
      if (!stored_linked_object) {
        console.error("Linked Object not found in store:", obj, found_linked_object, this.__linked_objects);
        continue;
      }
      if (parseInt(stored_linked_object._id) > 0) {
        found_linked_object._id = "duplicate";
        console.error("Linked Object found multiple times:", obj, found_linked_object);
      }
      for (k in found_linked_object) {
        v = found_linked_object[k];
        stored_linked_object[k] = v;
      }
      ref2 = this.__obj_keys;
      for (l = 0, len2 = ref2.length; l < len2; l++) {
        key = ref2[l];
        stored_linked_object[key] = obj[this.__ot_name][key];
      }
      if (stored_linked_object._path) {
        ref3 = this.__linked_objects;
        for (m = 0, len3 = ref3.length; m < len3; m++) {
          linked_object = ref3[m];
          if (linked_object._id_parent === stored_linked_object._path) {
            linked_object._id_parent = stored_linked_object._id;
          }
        }
      }
    }
    ref4 = this.__linked_objects;
    for (n = 0, len4 = ref4.length; n < len4; n++) {
      linked_object = ref4[n];
      if (linked_object._id === "searching") {
        if (!this._csvImporter.getFormData().create_linked_objects) {
          throw "not_allowed_to_create_linked_objects";
        }
        linked_object._id = "new";
      }
    }
  };

  LinkedObjectCSVImporterDestinationField.prototype.matchesColumnName = function(name) {
    var customOpt, fieldName, fixedMatch, i, len, ref, val;
    val = LinkedObjectCSVImporterDestinationField.__super__.matchesColumnName.call(this, name);
    if (!val) {
      name = name.replace(/\.(?=[^.]*$)/, '#');
      val = LinkedObjectCSVImporterDestinationField.__super__.matchesColumnName.call(this, name);
      fixedMatch = true;
      if (!val) {
        return val;
      }
    }
    fieldName = name.split("#")[1];
    ref = this.__custom_opts;
    for (i = 0, len = ref.length; i < len; i++) {
      customOpt = ref[i];
      if (customOpt.text === fieldName) {
        if (fixedMatch) {
          this.__fixed_matched_column_name = name;
        }
        return true;
      }
    }
    return false;
  };

  LinkedObjectCSVImporterDestinationField.prototype.getDefaultConfigFromColumnName = function(name) {
    if (this.__fixed_matched_column_name) {
      return LinkedObjectCSVImporterDestinationField.__super__.getDefaultConfigFromColumnName.call(this, this.__fixed_matched_column_name);
    }
    return LinkedObjectCSVImporterDestinationField.__super__.getDefaultConfigFromColumnName.call(this, name);
  };

  LinkedObjectCSVImporterDestinationField.prototype.addToMatchExisting = function() {};

  LinkedObjectCSVImporterDestinationField.prototype.hasPrepareError = function(configs) {
    var config, i, label, len, ref;
    for (i = 0, len = configs.length; i < len; i++) {
      config = configs[i];
      if ((ref = config.config) != null ? ref.column : void 0) {
        continue;
      }
      label = new CUI.Label({
        "class": "ez5-csv-importer-prepare-data-error",
        icon: "warning",
        text: $$("linked.object.csv.importer.destination.field.column.mapping.invalid", {
          fieldName: this.getField().nameLocalized()
        })
      });
      return label;
    }
    return false;
  };

  return LinkedObjectCSVImporterDestinationField;

})(ObjecttypeCSVImporterDestinationField);
// Generated by CoffeeScript 1.12.7
var HierarchyCSVImporterDestinationField,
  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;

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

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

  HierarchyCSVImporterDestinationField.prototype.initOpts = function() {
    HierarchyCSVImporterDestinationField.__super__.initOpts.call(this);
    return this.mergeOpt("field", {
      check: TreeColumn
    });
  };

  HierarchyCSVImporterDestinationField.prototype.readOpts = function(opts) {
    HierarchyCSVImporterDestinationField.__super__.readOpts.call(this, opts);
    CUI.util.removeFromArray(null, this.__custom_fields, (function(_this) {
      return function(v) {
        return v.name === "hierarchy_split";
      };
    })(this));
    return this;
  };

  HierarchyCSVImporterDestinationField.prototype.getControlName = function() {
    return "hierarchy-" + HierarchyCSVImporterDestinationField.__super__.getControlName.call(this);
  };

  HierarchyCSVImporterDestinationField.prototype.getRecordValue = function(configs, row, opts) {
    var _value, column, config, i, len, linkedObject, parent, recordValue, ref, statusText, value;
    if (opts == null) {
      opts = {};
    }
    config = configs[0];
    value = row[config.csv_field_idx];
    column = config.config.column;
    delete row[this._csvImporter.cf_idx.warning_text];
    if (CUI.util.isEmpty(value)) {
      return null;
    }
    if (column === "_id") {
      _value = parseInt(value);
      if (isNaN(_value)) {
        statusText = $$("hierarchy.column.csv.importer.destination.field.parent_invalid", {
          value: value
        });
        return "invalid: " + statusText;
      }
      return _value;
    }
    if (column === "_system_object_id") {
      value = parseInt(value);
      if (isNaN(value)) {
        statusText = $$("hierarchy.column.csv.importer.destination.field.parent_invalid", {
          value: value
        });
        return "invalid: " + statusText;
      }
    }
    ref = this.__linked_objects || [];
    for (i = 0, len = ref.length; i < len; i++) {
      linkedObject = ref[i];
      if (linkedObject[column] === parseInt(value)) {
        value = parseInt(value);
      }
      if (linkedObject[column] === value) {
        if (opts.for_preview_detail) {
          parent = {};
          parent[this.__ot_name] = linkedObject;
          parent._mask = this.__mask_name;
          parent._objecttype = this.__ot_name;
          parent._format = "long";
          return parent;
        }
        recordValue = linkedObject._id;
        if (opts.for_preview) {
          parent = {
            _id: recordValue
          };
          parent[column] = value;
          return parent;
        }
        if (!CUI.util.isNumber(recordValue)) {
          return value;
        }
        return recordValue;
      }
    }
    row[this._csvImporter.cf_idx.warning_text] = $$("hierarchy.column.csv.importer.destination.field.warning.parent_not_found", {
      value: value
    });
    return null;
  };

  HierarchyCSVImporterDestinationField.prototype.action = function(ev, op, rows) {
    return ObjecttypeCSVImporterDestinationField.prototype.action.call(this, ev, op, rows);
  };

  HierarchyCSVImporterDestinationField.prototype.matchesColumnName = function(name) {
    return ObjecttypeCSVImporterDestinationField.prototype.matchesColumnName.call(this, name);
  };

  HierarchyCSVImporterDestinationField.prototype.prepareDataChunk = function(configs, rows) {
    var data, dfr, i, j, len, len1, parent_id, parents, ref, row, statusText;
    if ((configs != null ? (ref = configs[0]) != null ? ref.config.column : void 0 : void 0) === "_id") {
      dfr = new CUI.Deferred();
      parents = [];
      for (i = 0, len = rows.length; i < len; i++) {
        row = rows[i];
        parent_id = this.getRecordValue(configs, row);
        if (parent_id) {
          parents.push(parent_id);
        }
      }
      if (parents.length > 0) {
        ez5.api.search({
          json_data: {
            objecttypes: [this.__ot_name],
            search: [
              {
                type: "in",
                bool: "should",
                fields: [this.__ot_name + "._id"],
                "in": parents
              }
            ]
          }
        }).done((function(_this) {
          return function(responseData) {
            var found, j, k, len1, len2, objectData, ref1, statusText;
            for (j = 0, len1 = rows.length; j < len1; j++) {
              row = rows[j];
              parent_id = _this.getRecordValue(configs, row);
              if (parent_id) {
                found = false;
                ref1 = responseData.objects;
                for (k = 0, len2 = ref1.length; k < len2; k++) {
                  objectData = ref1[k];
                  if (objectData[_this.__ot_name]._id === parent_id) {
                    found = true;
                    break;
                  }
                }
                if (!found) {
                  statusText = $$("hierarchy.column.csv.importer.destination.field.parent_not_found");
                  _this._csvImporter.setRowInvalidWithText(row, statusText);
                }
              }
            }
          };
        })(this)).fail((function(_this) {
          return function() {
            var j, len1, results;
            results = [];
            for (j = 0, len1 = rows.length; j < len1; j++) {
              row = rows[j];
              results.push(_this._csvImporter.setRowInvalidWithText(row, $$("hierarchy.column.csv.importer.destination.field.parent_not_found")));
            }
            return results;
          };
        })(this)).always((function(_this) {
          return function() {
            return dfr.resolve();
          };
        })(this));
      } else {
        return dfr.resolve();
      }
      return dfr.promise();
    } else {
      for (j = 0, len1 = rows.length; j < len1; j++) {
        row = rows[j];
        data = this.getRecordValue(configs, row);
        if (CUI.util.isString(data) && data.startsWith("invalid:")) {
          statusText = data.split(": ")[1];
          this._csvImporter.setRowInvalidWithText(row, statusText);
        }
      }
      return CUI.resolvedPromise;
    }
  };

  HierarchyCSVImporterDestinationField.prototype.beforePrepareData = function(configs, rows) {
    var column, config, destinationField, destinationFieldConfigs, foundConfig, foundConfigs, i, j, len, len1, ref;
    HierarchyCSVImporterDestinationField.__super__.beforePrepareData.call(this, configs, rows);
    config = configs[0];
    column = config.config.column;
    if (column === "_id") {
      if (this._csvImporter.path_dest.field === this) {
        this._csvImporter.path_dest = null;
      }
      return;
    }
    foundConfigs = [];
    ref = this._csvImporter.dest_fields;
    for (i = 0, len = ref.length; i < len; i++) {
      destinationField = ref[i];
      if (destinationField.getField().name() !== column) {
        continue;
      }
      destinationFieldConfigs = this._csvImporter.getMappingConfigsForDestinationField(destinationField);
      if (!destinationFieldConfigs || destinationFieldConfigs.length === 0) {
        continue;
      }
      foundConfigs.push(destinationFieldConfigs[0]);
    }
    if (this._csvImporter.path_dest.field === this) {
      for (j = 0, len1 = foundConfigs.length; j < len1; j++) {
        foundConfig = foundConfigs[j];
        this._csvImporter.path_dest.path_col_idx.push(foundConfig.csv_field_idx);
      }
    }
  };

  HierarchyCSVImporterDestinationField.prototype.afterPreparePathData = function(configs, rows) {
    var column, config, data, deferred, fieldName, i, idParent, include_fields, lang, len, markRowAsNotFound, ref, row, rowsByData, search, searchOpts;
    config = configs[0];
    column = config.config.column;
    if (column !== "_system_object_id" && column !== "_id") {
      lang = (ref = column.split("#")) != null ? ref[1] : void 0;
    } else {
      lang = null;
    }
    rowsByData = {};
    search = [];
    for (i = 0, len = rows.length; i < len; i++) {
      row = rows[i];
      if (column === "_system_object_id" || column === "_id") {
        idParent = row[this._csvImporter.cf_idx.id_parent];
        if (row[this._csvImporter.cf_idx.status] !== "invalid" && !CUI.util.isInteger(idParent)) {
          if (column !== "_system_object_id") {
            continue;
          }
        }
      }
      data = this.getRecordValue(configs, row);
      if (CUI.util.isEmpty(data)) {
        continue;
      }
      if (!rowsByData[data]) {
        rowsByData[data] = [];
      }
      rowsByData[data].push(row);
      if (column === "_system_object_id") {
        fieldName = column;
        data = parseInt(data);
      } else {
        column = column.split("#")[0];
        fieldName = this.__ot_name + "." + column;
      }
      search.push({
        type: "in",
        bool: "should",
        fields: [fieldName],
        "in": [data]
      });
    }
    if (search.length === 0) {
      return CUI.resolvedPromise();
    }
    deferred = new CUI.Deferred();
    if (column === "_system_object_id") {
      include_fields = ["" + column, this.__ot_name + "._id"];
    } else {
      include_fields = [this.__ot_name + "." + column, this.__ot_name + "._id"];
    }
    searchOpts = {
      format: "short",
      generate_rights: false,
      include_fields: include_fields,
      objecttypes: [this.__ot_name],
      search: search,
      limit: 1000000
    };
    markRowAsNotFound = (function(_this) {
      return function(data, rows) {
        var j, len1, statusText;
        for (j = 0, len1 = rows.length; j < len1; j++) {
          row = rows[j];
          idParent = row[_this._csvImporter.cf_idx.id_parent];
          if (CUI.util.isInteger(idParent)) {
            continue;
          }
          statusText = $$("hierarchy.column.csv.importer.destination.field.object-not-found", {
            value: data
          });
          _this._csvImporter.setRowInvalidWithText(row, statusText);
        }
      };
    })(this);
    ez5.api.search_no_limit({
      data: {
        debug: "CSVImporter.Hierarchy.afterPreparePathData"
      },
      json_data: searchOpts
    }).done((function(_this) {
      return function(responseData) {
        var c, foundValue, j, k, l, len1, len2, len3, len4, len5, len6, linkedObject, m, n, o, objectData, objectTopLevelData, pathColIdx, ref1, ref2, ref3, ref4, rowFound, rowParentIndex, rowsFound, rowsNotFound, value;
        if (lang) {
          column = column + "#" + lang;
        }
        ref1 = responseData.objects;
        for (j = 0, len1 = ref1.length; j < len1; j++) {
          objectTopLevelData = ref1[j];
          objectData = objectTopLevelData[_this.__ot_name];
          if (column === "_system_object_id") {
            foundValue = objectTopLevelData[column];
          } else {
            c = column.split("#")[0];
            foundValue = objectData[c];
            if (lang) {
              foundValue = foundValue[lang];
            }
          }
          ref2 = _this.__linked_objects;
          for (k = 0, len2 = ref2.length; k < len2; k++) {
            linkedObject = ref2[k];
            if (linkedObject[column] !== foundValue) {
              continue;
            }
            linkedObject._id = objectData._id;
          }
        }
        rowsNotFound = {};
        rowsFound = [];
        ref3 = _this.__linked_objects;
        for (l = 0, len3 = ref3.length; l < len3; l++) {
          linkedObject = ref3[l];
          value = linkedObject[column];
          if (!rowsByData[value]) {
            continue;
          }
          if (CUI.util.isUndef(linkedObject._id)) {
            rowsNotFound[value] = rowsByData[value];
            continue;
          }
          ref4 = rowsByData[value];
          for (m = 0, len4 = ref4.length; m < len4; m++) {
            row = ref4[m];
            delete row[_this._csvImporter.cf_idx.status_text];
            delete row[_this._csvImporter.cf_idx.status];
            rowsFound.push(row);
          }
        }
        pathColIdx = _this._csvImporter.path_dest.path_col_idx[1];
        for (value in rowsNotFound) {
          rows = rowsNotFound[value];
          rowParentIndex = null;
          for (n = 0, len5 = rowsFound.length; n < len5; n++) {
            rowFound = rowsFound[n];
            if (rowFound[pathColIdx] === value) {
              rowParentIndex = rowFound[_this._csvImporter.cf_idx.row_idx];
              break;
            }
          }
          if (!CUI.util.isNull(rowParentIndex)) {
            for (o = 0, len6 = rows.length; o < len6; o++) {
              row = rows[o];
              row[_this._csvImporter.cf_idx.id_parent] = JSON.stringify({
                row_idx: rowParentIndex
              });
              delete row[_this._csvImporter.cf_idx.status_text];
              delete row[_this._csvImporter.cf_idx.status];
            }
          } else {
            markRowAsNotFound(value, rows);
          }
        }
        return deferred.resolve();
      };
    })(this)).fail((function(_this) {
      return function() {
        for (data in rowsByData) {
          rows = rowsByData[data];
          markRowAsNotFound(data, rows);
        }
        return deferred.resolve();
      };
    })(this));
    return deferred.promise();
  };

  return HierarchyCSVImporterDestinationField;

})(LinkedObjectCSVImporterDestinationField);
// Generated by CoffeeScript 1.12.7
var EASColumnCSVImporterDestinationField,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  EASColumnCSVImporterDestinationField.prototype.initOpts = function() {
    EASColumnCSVImporterDestinationField.__super__.initOpts.call(this);
    this.mergeOpt("field", {
      check: EASColumn
    });
    return this.addOpts({
      type: {
        check: ["original_filename", "url"]
      }
    });
  };

  EASColumnCSVImporterDestinationField.prototype.readOpts = function() {
    EASColumnCSVImporterDestinationField.__super__.readOpts.call(this);
    this.__eas_types = ["url", "original_filename"];
    this.__eas_opts = [
      {
        text: this.__eas_types[0]
      }
    ];
    if (!this._field.insideNested()) {
      this.__eas_opts.push({
        text: this.__eas_types[1]
      });
    }
    this.__easRows = [];
    return this;
  };

  EASColumnCSVImporterDestinationField.prototype.getCustomFields = function() {
    return [
      {
        name: "type",
        form: {
          label: $$("eas.column.csv.importer.destination.field.type.label"),
          hint: $$("eas.column.csv.importer.destination.field.type.hint")
        },
        type: CUI.Select,
        undo_and_changed_support: false,
        options: this.__eas_opts,
        onDataInit: (function(_this) {
          return function(_, data) {
            return _this.__type = data.type || "url";
          };
        })(this),
        onDataChanged: (function(_this) {
          return function(data) {
            return _this.__type = data.type;
          };
        })(this)
      }
    ];
  };

  EASColumnCSVImporterDestinationField.prototype.supportsHierarchy = function() {
    return false;
  };

  EASColumnCSVImporterDestinationField.prototype.getLabel = function() {
    return EASColumnCSVImporterDestinationField.__super__.getLabel.call(this);
  };

  EASColumnCSVImporterDestinationField.prototype.getControlFields = function() {
    return [
      {
        name: this.getControlName()
      }, {
        name: this.getControlMetadataName()
      }
    ];
  };

  EASColumnCSVImporterDestinationField.prototype.getControlName = function() {
    return "eas_ids|" + (this.getField().name());
  };

  EASColumnCSVImporterDestinationField.prototype.getControlMetadataName = function() {
    return "eas_ids|" + (this.getField().name()) + "|metadata";
  };

  EASColumnCSVImporterDestinationField.prototype.getRecordValue = function(configs, row, opts) {
    var _recordValues, _values, addDataToRecord, cfIdx, data, easType, hasMultipleValues, i, idEAS, idEASArray, index, j, k, l, len, len1, len2, len3, len4, m, orderIndex, record, recordValue, ref, ref1, ref2, ref3, standardVersion, value, values;
    if (this.__type === "original_filename") {
      if (opts.operation || opts.for_preview) {
        return void 0;
      }
      return EASColumnCSVImporterDestinationField.__super__.getRecordValue.call(this, configs, row, opts);
    }
    easType = this._csvImporter.getFormData().easType;
    if (!this.__isUploadAvailable(easType)) {
      return void 0;
    }
    recordValue = [];
    data = EASColumnCSVImporterDestinationField.__super__.getRecordValue.call(this, configs, row, opts);
    addDataToRecord = (function(_this) {
      return function(value) {
        if (CUI.util.isNull(value)) {
          return;
        }
        if (_this.__type === "url") {
          return recordValue.push({
            _id: null,
            url: value
          });
        } else {
          value = CUI.util.getInt(value);
          if (value) {
            return recordValue.push({
              eas_id: parseInt(value)
            });
          }
        }
      };
    })(this);
    hasMultipleValues = CUI.util.isArray(data);
    if (hasMultipleValues) {
      for (i = 0, len = data.length; i < len; i++) {
        value = data[i];
        addDataToRecord(value);
      }
    } else {
      addDataToRecord(data);
    }
    if (CUI.util.isEmpty(recordValue)) {
      return void 0;
    }
    cfIdx = this._csvImporter.cf_idx[this.getControlName()];
    if (row[cfIdx]) {
      idEASArray = row[cfIdx];
      for (orderIndex = j = 0, len1 = idEASArray.length; j < len1; orderIndex = ++j) {
        idEAS = idEASArray[orderIndex];
        recordValue[orderIndex]._id = idEAS;
        recordValue[orderIndex].preferred = true;
        delete recordValue[orderIndex].eas_id;
      }
    }
    if (hasMultipleValues) {
      for (index = k = 0, len2 = recordValue.length; k < len2; index = ++k) {
        record = recordValue[index];
        recordValue[index] = [record];
      }
    }
    if (opts.for_preview_detail) {
      _recordValues = [];
      standardVersion = ((ref = ez5.session.getEASConfig().image) != null ? (ref1 = ref.versions) != null ? (ref2 = ref1.filter((function(_this) {
        return function(version) {
          return version.standard;
        };
      })(this))) != null ? (ref3 = ref2[0]) != null ? ref3.version : void 0 : void 0 : void 0 : void 0) || "original";
      for (l = 0, len3 = recordValue.length; l < len3; l++) {
        values = recordValue[l];
        _values = [];
        for (m = 0, len4 = values.length; m < len4; m++) {
          value = values[m];
          value.versions = {};
          value.versions[standardVersion] = {
            url: value.url,
            "class": "image",
            status: "done"
          };
          value["class"] = "image";
          value.status = "done";
          value.original_filename = ez5.basename(value.url);
          value.original_filename_basename = ez5.bareBasename(value.url);
          value.preferred = true;
          value.class_version_status = [];
          value.class_version_status.push("image." + standardVersion + ".done");
          value._id = 1;
          _values.push(value);
        }
        if (_values.length > 0) {
          _recordValues.push(_values);
        }
      }
      return _recordValues;
    }
    return recordValue;
  };

  EASColumnCSVImporterDestinationField.prototype.prepareDataChunk = function(configs, rows, offset) {
    var addEASField, data, easType, i, index, j, len, len1, record, records, row;
    if (this.__type === "original_filename") {
      return EASColumnCSVImporterDestinationField.__super__.prepareDataChunk.call(this, configs, rows, offset);
    }
    easType = this._csvImporter.getFormData().easType;
    if (!this.__isUploadAvailable(easType)) {
      return void 0;
    }
    for (index = i = 0, len = rows.length; i < len; index = ++i) {
      row = rows[index];
      records = this.getRecordValue(configs, row, {});
      if (CUI.util.isNull(records)) {
        continue;
      }
      addEASField = (function(_this) {
        return function(data) {
          if (!CUI.util.isEmpty(data)) {
            if (_this.__type === "url") {
              return _this.__easRows.push({
                urls: data,
                row: row
              });
            } else {
              return _this.__easRows.push({
                ids: data,
                row: row
              });
            }
          }
        };
      })(this);
      if (CUI.util.isArray(records)) {
        data = [];
        for (j = 0, len1 = records.length; j < len1; j++) {
          record = records[j];
          if (record[0]) {
            record = record[0];
          }
          if (!record._id) {
            if (this.__type === "url") {
              data.push(record.url);
            } else {
              data.push(record.eas_id);
            }
          }
        }
      }
      addEASField(data);
    }
    return EASColumnCSVImporterDestinationField.__super__.prepareDataChunk.call(this, configs, rows, offset);
  };

  EASColumnCSVImporterDestinationField.prototype.action = function(ev, op, rows) {
    var allRowsChunkWorksPromises, controlMetadataColumn, controlNameColumn, deferred, easRow, easRows, easType, error, fn, i, len, statusTextColumn;
    if (this.__type === "original_filename") {
      return EASColumnCSVImporterDestinationField.__super__.action.call(this, ev, op, rows);
    }
    easType = this._csvImporter.getFormData().easType;
    if (!this.__isUploadAvailable(easType)) {
      return CUI.resolvedPromise();
    }
    controlNameColumn = this._csvImporter.cf_idx[this.getControlName()];
    controlMetadataColumn = this._csvImporter.cf_idx[this.getControlMetadataName()];
    statusTextColumn = this._csvImporter.cf_idx.status_text;
    easRows = this.__easRows.filter((function(_this) {
      return function(easRow) {
        var ref;
        return ref = easRow.row, indexOf.call(rows, ref) >= 0;
      };
    })(this));
    if (easRows.length === 0) {
      return CUI.resolvedPromise();
    }
    deferred = new CUI.Deferred();
    allRowsChunkWorksPromises = [];
    error = false;
    fn = (function(_this) {
      return function(easRow) {
        return allRowsChunkWorksPromises.push(CUI.chunkWork.call(_this, {
          items: easRow.urls,
          chunk_size: EASImporter.uploadChunkSize,
          call: (function(urls) {
            var chunkWorkDeferred, fn1, j, len1, promises, url;
            chunkWorkDeferred = new CUI.Deferred();
            promises = [];
            fn1 = function(url) {
              var easDeferred;
              easDeferred = new CUI.Deferred();
              EASImporter.prototype.downloadAndUpload(url, easType).done(function(idEAS) {
                var mainTable, mapping, object, objecttype, orderIndex, poll, pool_id, ref;
                if (!easRow.row[controlNameColumn]) {
                  easRow.row[controlNameColumn] = [];
                }
                orderIndex = easRow.urls.indexOf(url);
                easRow.urls[orderIndex] = "";
                easRow.row[controlNameColumn][orderIndex] = idEAS;
                mapping = _this._csvImporter.getFormSaveData().id_mapping;
                if (!mapping) {
                  return easDeferred.resolve();
                }
                mainTable = _this._field.getMainMask().getTable();
                pool_id = null;
                if (mainTable.poolLink()) {
                  pool_id = (ref = _this._csvImporter.getFormData()._pool) != null ? ref.pool._id : void 0;
                }
                objecttype = mainTable.name();
                object = {
                  _mask: _this._csvImporter.getFormSaveData().mask
                };
                object[objecttype] = {};
                poll = easType === EASImporter.EAS_TYPE.URL;
                return EASImporter.prototype.mergeMetadata(idEAS, object, objecttype, mapping, pool_id, poll).done(function() {
                  EAS.replaceMappedMetadata(object[objecttype]);
                  if (!easRow.row[controlMetadataColumn]) {
                    easRow.row[controlMetadataColumn] = [];
                  }
                  easRow.row[controlMetadataColumn].push(JSON.stringify(object));
                  return easDeferred.resolve();
                }).fail(easDeferred.reject);
              }).fail(easDeferred.reject);
              return promises.push(easDeferred.promise());
            };
            for (j = 0, len1 = urls.length; j < len1; j++) {
              url = urls[j];
              fn1(url);
            }
            CUI.when(promises).fail(function(errorMessage) {
              easRow.row[statusTextColumn] = errorMessage;
              return error = true;
            }).always(function() {
              return chunkWorkDeferred.resolve();
            });
            return chunkWorkDeferred;
          })
        }).done(function() {
          return CUI.util.removeFromArray(easRow, _this.__easRows);
        }));
      };
    })(this);
    for (i = 0, len = easRows.length; i < len; i++) {
      easRow = easRows[i];
      fn(easRow);
    }
    CUI.whenAll(allRowsChunkWorksPromises).always((function(_this) {
      return function() {
        if (error) {
          return deferred.reject($$("eas.column.csv.importer.destination.field.error-message"));
        }
        return deferred.resolve();
      };
    })(this));
    return deferred.promise();
  };

  EASColumnCSVImporterDestinationField.prototype.__isUploadAvailable = function(easType) {
    return easType && easType !== EASImporter.EAS_TYPE.IGNORE;
  };

  EASColumnCSVImporterDestinationField.prototype.getRecordKeyPath = function() {
    return EASColumnCSVImporterDestinationField.__super__.getRecordKeyPath.call(this);
  };

  EASColumnCSVImporterDestinationField.prototype.getRecordKeyPathForSearch = function() {
    var superValue;
    superValue = EASColumnCSVImporterDestinationField.__super__.getRecordKeyPathForSearch.call(this);
    return superValue + ".original_filename";
  };

  EASColumnCSVImporterDestinationField.prototype.getMatchExistingSearch = function(values) {
    var i, len, search, value;
    search = [];
    if (this.__type === "original_filename") {
      for (i = 0, len = values.length; i < len; i++) {
        value = values[i];
        search.push({
          type: "in",
          fields: [this.getRecordKeyPathForSearch()],
          "in": [value],
          bool: "should"
        });
      }
    }
    return search;
  };

  EASColumnCSVImporterDestinationField.prototype.finalizeRecord = function(record, row, opts) {
    var controlMetadataColumn, i, len, metadataObject, objects, objecttype;
    EASColumnCSVImporterDestinationField.__super__.finalizeRecord.call(this, record, row, opts);
    if (opts.for_preview || opts.operation !== "insert") {
      return;
    }
    controlMetadataColumn = this._csvImporter.cf_idx[this.getControlMetadataName()];
    objects = row[controlMetadataColumn];
    if (!CUI.util.isArray(objects) || objects.length === 0) {
      return;
    }
    objecttype = this._field.table.name();
    for (i = 0, len = objects.length; i < len; i++) {
      metadataObject = objects[i];
      metadataObject = JSON.parse(metadataObject);
      if (!CUI.util.isPlainObject(metadataObject)) {
        continue;
      }
      EAS.mergeMetadata(metadataObject[objecttype], record[objecttype]);
      EAS.replaceMappedMetadata(record[objecttype]);
      EAS.cleanMappedMetadata(record[objecttype]);
    }
    row[controlMetadataColumn] = [];
  };

  return EASColumnCSVImporterDestinationField;

})(ObjecttypeCSVImporterDestinationField);
// Generated by CoffeeScript 1.12.7
var DateColumnCSVImporterDestinationField,
  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;

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

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

  DateColumnCSVImporterDestinationField.prototype.initOpts = function() {
    DateColumnCSVImporterDestinationField.__super__.initOpts.call(this);
    return this.mergeOpt("field", {
      check: DateColumn
    });
  };

  DateColumnCSVImporterDestinationField.prototype.supportsHierarchy = function() {
    return false;
  };

  DateColumnCSVImporterDestinationField.prototype.formatValues = function(values) {
    var value;
    value = CUI.DateTime.format(values[0], "store");
    if (!value && !CUI.util.isEmpty(values[0])) {
      value = "invalid:" + values[0];
    }
    if (value) {
      return {
        value: value
      };
    } else {
      return null;
    }
  };

  DateColumnCSVImporterDestinationField.prototype.prepareDataChunk = function(configs, rows, offset) {
    var _rec, checkRecord, i, len, row;
    checkRecord = (function(_this) {
      return function(rec, row) {
        var i, k, len, record, v;
        if (!rec) {
          return;
        }
        if (CUI.util.isArray(rec)) {
          for (i = 0, len = rec.length; i < len; i++) {
            record = rec[i];
            checkRecord(record, row);
          }
        } else {
          for (k in rec) {
            v = rec[k];
            if (CUI.util.isPlainObject(v)) {
              continue;
            }
            if (v != null ? v.startsWith("invalid:") : void 0) {
              _this._csvImporter.setRowInvalid(row, "date.column.csv.importer.destination.field.date_invalid", {
                date: v.substr("invalid:".length)
              });
            }
          }
        }
      };
    })(this);
    for (i = 0, len = rows.length; i < len; i++) {
      row = rows[i];
      _rec = this.getRecordValue(configs, row, {
        prepare: true
      });
      checkRecord(_rec, row);
    }
    return CUI.resolvedPromise();
  };

  return DateColumnCSVImporterDestinationField;

})(ObjecttypeCSVImporterDestinationField);
// Generated by CoffeeScript 1.12.7
var DateTimeColumnCSVImporterDestinationField,
  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;

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

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

  DateTimeColumnCSVImporterDestinationField.prototype.initOpts = function() {
    DateTimeColumnCSVImporterDestinationField.__super__.initOpts.call(this);
    return this.mergeOpt("field", {
      check: DateTimeColumn
    });
  };

  DateTimeColumnCSVImporterDestinationField.prototype.formatValues = function(values) {
    var value;
    value = CUI.DateTime.format(values[0], "store", "date_time_seconds", true);
    if (value) {
      return {
        value: value
      };
    } else {
      return null;
    }
  };

  return DateTimeColumnCSVImporterDestinationField;

})(ObjecttypeCSVImporterDestinationField);
// Generated by CoffeeScript 1.12.7
var DateRangeColumnCSVImporterDestinationField,
  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;

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

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

  DateRangeColumnCSVImporterDestinationField.prototype.initOpts = function() {
    DateRangeColumnCSVImporterDestinationField.__super__.initOpts.call(this);
    return this.mergeOpt("field", {
      check: DateRangeColumn
    });
  };

  DateRangeColumnCSVImporterDestinationField.prototype.locaKeyPrefix = "date.range.column.csv.importer.destination.field.from_to.";

  DateRangeColumnCSVImporterDestinationField.prototype.recordFromMultipleColumns = function() {
    return true;
  };

  DateRangeColumnCSVImporterDestinationField.prototype.setValuesFromMultipleColumnsForNested = function(config, values, value, idx) {
    var _value, _values, base, base1, base2, base3, base4, dateRangeValue, i, j, len, len1, locale, ref, row, val;
    _values = this.csvData.parse({
      quotechar: '"',
      delimiter: "",
      text: value,
      defer: false
    })["rows"];
    for (row = i = 0, len = _values.length; i < len; row = ++i) {
      val = _values[row];
      if (CUI.util.isArray(val)) {
        val = val[0];
      }
      if (config.config.from_to === "textual_representation") {
        if (val === "") {
          values[idx][row] = null;
          return;
        }
        dateRangeValue = CUI.DateTime.stringToDateRange(val);
        if (values[idx] == null) {
          values[idx] = [];
        }
        if ((base = values[idx])[row] == null) {
          base[row] = {};
        }
        values[idx][row].text = {};
        if ((base1 = values[idx][row]).from == null) {
          base1.from = dateRangeValue.from;
        }
        if ((base2 = values[idx][row]).to == null) {
          base2.to = dateRangeValue.to;
        }
        if (dateRangeValue && !dateRangeValue.error) {
          ref = ez5.loca.getDatabaseLanguages();
          for (j = 0, len1 = ref.length; j < len1; j++) {
            locale = ref[j];
            values[idx][row].text[locale] = val;
          }
        } else {
          values[idx][row].text = "invalid:" + val;
        }
        return;
      } else {
        _value = CUI.DateTime.format(val, "store");
        if (!_value && !CUI.util.isEmpty(val)) {
          _value = "invalid:" + val;
        }
      }
      if (!CUI.util.isEmpty(_value)) {
        if (!values[idx]) {
          values[idx] = [];
          values[idx][row] = {
            from: null,
            to: null
          };
        }
        if ((base3 = values[idx])[row] == null) {
          base3[row] = {};
        }
        values[idx][row][config.config.from_to] = _value;
      } else if (CUI.util.isEmpty(val)) {
        if (values[idx] == null) {
          values[idx] = [];
        }
        if ((base4 = values[idx])[row] == null) {
          base4[row] = {};
        }
        values[idx][row][config.config.from_to] = null;
      }
    }
  };

  DateRangeColumnCSVImporterDestinationField.prototype.setValuesFromMultipleColumns = function(config, values, value, idx) {
    var _value, base, base1, dateRangeValue, i, len, locale, ref;
    if (this.getField().insideNested()) {
      this.setValuesFromMultipleColumnsForNested(config, values, value, idx);
      return;
    }
    if (config.config.from_to === "textual_representation") {
      if (value === "") {
        values[idx] = null;
        return;
      }
      dateRangeValue = CUI.DateTime.stringToDateRange(value);
      if (values[idx] == null) {
        values[idx] = {};
      }
      values[idx].text = {};
      if ((base = values[idx]).from == null) {
        base.from = dateRangeValue.from;
      }
      if ((base1 = values[idx]).to == null) {
        base1.to = dateRangeValue.to;
      }
      if (dateRangeValue && !dateRangeValue.error) {
        ref = ez5.loca.getDatabaseLanguages();
        for (i = 0, len = ref.length; i < len; i++) {
          locale = ref[i];
          values[idx].text[locale] = value;
        }
      } else {
        values[idx].text = "invalid:" + value;
      }
      return;
    } else {
      _value = CUI.DateTime.format(value, "store");
      if (!_value && !CUI.util.isEmpty(value)) {
        _value = "invalid:" + value;
      }
    }
    if (!CUI.util.isEmpty(_value)) {
      if (!values[idx]) {
        values[idx] = {
          from: null,
          to: null
        };
      }
      values[idx][config.config.from_to] = _value;
    } else if (CUI.util.isEmpty(value)) {
      if (values[idx] == null) {
        values[idx] = {};
      }
      values[idx][config.config.from_to] = null;
    }
  };

  DateRangeColumnCSVImporterDestinationField.prototype.prepareDataChunk = function(configs, rows, offset) {
    return DateColumnCSVImporterDestinationField.prototype.prepareDataChunk.call(this, configs, rows, offset);
  };

  DateRangeColumnCSVImporterDestinationField.prototype.getReadyForPrepare = function(configs) {
    var config, i, len, ref, suffix, used, usedKey;
    used = {};
    for (i = 0, len = configs.length; i < len; i++) {
      config = configs[i];
      suffix = ((ref = config.indices) != null ? ref.join() : void 0) || "";
      usedKey = config.config.from_to + suffix;
      if (used[usedKey]) {
        return CUI.rejectedPromise(this.locaKeyPrefix + "error.config");
      }
      used[usedKey] = true;
    }
    return CUI.resolvedPromise();
  };

  DateRangeColumnCSVImporterDestinationField.prototype.getCustomFields = function() {
    return [
      {
        name: "from_to",
        form: {
          label: $$(this.locaKeyPrefix + "label")
        },
        type: CUI.Select,
        options: [
          {
            value: "from",
            text: $$(this.locaKeyPrefix + "option.from")
          }, {
            value: "to",
            text: $$(this.locaKeyPrefix + "option.to")
          }, {
            value: "textual_representation",
            text: $$(this.locaKeyPrefix + "option.textual_representation")
          }
        ]
      }
    ];
  };

  return DateRangeColumnCSVImporterDestinationField;

})(ObjecttypeCSVImporterDestinationField);
// Generated by CoffeeScript 1.12.7
var LocaTextColumnCSVImporterDestinationField,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  LocaTextColumnCSVImporterDestinationField.prototype.initOpts = function() {
    LocaTextColumnCSVImporterDestinationField.__super__.initOpts.call(this);
    return this.mergeOpt("field", {
      check: LocaTextColumn
    });
  };

  LocaTextColumnCSVImporterDestinationField.prototype.readOpts = function() {
    var i, lang, len, ref;
    LocaTextColumnCSVImporterDestinationField.__super__.readOpts.call(this);
    this.__lang_opts = [];
    this.__empty_record = {};
    ref = ez5.session.getConfigDatabaseLanguages();
    for (i = 0, len = ref.length; i < len; i++) {
      lang = ref[i];
      this.__lang_opts.push({
        value: lang,
        text: lang
      });
      this.__empty_record[lang] = "";
    }
    return this;
  };

  LocaTextColumnCSVImporterDestinationField.prototype.addToMatchExisting = function(select_opts, set_dest_fields) {
    var config, disabled, i, j, lang, langs, len, len1, path_mode, ref, ref1, text, tooltipText;
    if (!this.useForMatchExisting()) {
      return;
    }
    disabled = indexOf.call(set_dest_fields, this) < 0;
    langs = [];
    if (!disabled) {
      path_mode = false;
      ref = this._csvImporter.getMappingConfigsForDestinationField(this);
      for (i = 0, len = ref.length; i < len; i++) {
        config = ref[i];
        if (!config.config.language) {
          disabled = true;
          continue;
        }
        if (CUI.util.isEmpty(config.config.level)) {
          langs.push(config.config.language);
          continue;
        }
        path_mode = true;
        if (config.config.use_for_path) {
          langs.push(config.config.language);
        }
      }
      if (path_mode) {
        disabled = true;
      }
    }
    text = this._csvImporter.getFormData().show_localized_names ? this.getLabel() : this.getName();
    tooltipText = this._csvImporter.getFormData().show_localized_names ? this.getName() : this.getLabel();
    ref1 = ez5.session.getConfigDatabaseLanguages();
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      lang = ref1[j];
      select_opts.push({
        text: text + "#" + lang,
        disabled: indexOf.call(langs, lang) < 0,
        value: this.getName() + "#" + lang,
        tooltip: {
          text: tooltipText + "#" + lang
        }
      });
    }
    return this;
  };

  LocaTextColumnCSVImporterDestinationField.prototype.getCustomFields = function() {
    var field, fields, i, len, ref;
    fields = [
      {
        name: "language",
        form: {
          label: $$("loca.text.column.csv.importer.destination.field.language.label")
        },
        type: CUI.Select,
        undo_and_changed_support: false,
        options: this.__lang_opts
      }
    ];
    ref = LocaTextColumnCSVImporterDestinationField.__super__.getCustomFields.call(this);
    for (i = 0, len = ref.length; i < len; i++) {
      field = ref[i];
      fields.push(field);
    }
    if (this.supportsHierarchy()) {
      fields.push({
        type: CUI.Checkbox,
        form: {
          label: $$("loca.text.column.csv.importer.destination.field.use_for_path.label")
        },
        undo_and_changed_support: false,
        name: "use_for_path"
      });
    }
    return fields;
  };

  LocaTextColumnCSVImporterDestinationField.prototype.recordFromMultipleColumns = function() {
    return true;
  };

  LocaTextColumnCSVImporterDestinationField.prototype.setValuesFromMultipleColumns = function(config, values, value, idx) {
    var lang;
    lang = config.config.language;
    if (!values[idx]) {
      values[idx] = CUI.util.copyObject(this.__empty_record, true);
    }
    if (!CUI.util.isEmpty(value)) {
      if (CUI.util.isEmpty(values[idx][lang])) {
        values[idx][lang] = value;
      } else {
        values[idx][lang] = values[idx][lang] + ", " + value;
      }
    }
  };

  LocaTextColumnCSVImporterDestinationField.prototype.getMatchExistingValue = function(obj, match_existing) {
    var parts, value;
    value = LocaTextColumnCSVImporterDestinationField.__super__.getMatchExistingValue.call(this, obj, match_existing);
    parts = match_existing.split("#");
    return value[parts[1]];
  };

  LocaTextColumnCSVImporterDestinationField.prototype.getMatchExistingSearch = function(values, match_existing) {
    var parts, search;
    parts = match_existing.split("#");
    search = LocaTextColumnCSVImporterDestinationField.__super__.getMatchExistingSearch.call(this, values, match_existing);
    search[0].languages = [parts[1]];
    return search;
  };

  LocaTextColumnCSVImporterDestinationField.prototype.fillPrepareDataSearchOpts = function(search_opts, match_existing) {
    var parts;
    parts = match_existing.split("#");
    LocaTextColumnCSVImporterDestinationField.__super__.fillPrepareDataSearchOpts.call(this, search_opts);
    if (ez5.version("6")) {
      search_opts.languages = [parts[1]];
    } else {
      search_opts.language = parts[1];
    }
    return search_opts;
  };

  return LocaTextColumnCSVImporterDestinationField;

})(ObjecttypeCSVImporterDestinationField);
// Generated by CoffeeScript 1.12.7
var BooleanColumnCSVImporterDestinationField,
  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;

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

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

  BooleanColumnCSVImporterDestinationField.prototype.initOpts = function() {
    BooleanColumnCSVImporterDestinationField.__super__.initOpts.call(this);
    return this.mergeOpt("field", {
      check: BooleanColumn
    });
  };

  BooleanColumnCSVImporterDestinationField.prototype.supportsHierarchy = function() {
    return false;
  };

  BooleanColumnCSVImporterDestinationField.prototype.getFormat = function() {
    return "boolean";
  };

  return BooleanColumnCSVImporterDestinationField;

})(ObjecttypeCSVImporterDestinationField);
// Generated by CoffeeScript 1.12.7
var NumberColumnCSVImporterDestinationField,
  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;

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

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

  NumberColumnCSVImporterDestinationField.prototype.initOpts = function() {
    NumberColumnCSVImporterDestinationField.__super__.initOpts.call(this);
    this.addOpts({
      fixed: {
        mandatory: true,
        "default": 0,
        check: function(v) {
          return CUI.util.isInteger(v) && (v >= 0 || v === -1);
        }
      }
    });
    return this.removeOpt("use_for_match_existing");
  };

  NumberColumnCSVImporterDestinationField.prototype.supportsHierarchy = function() {
    return false;
  };

  NumberColumnCSVImporterDestinationField.prototype.getFormat = function() {
    return "number";
  };

  NumberColumnCSVImporterDestinationField.prototype.useForMatchExisting = function() {
    return true;
  };

  NumberColumnCSVImporterDestinationField.prototype.formatValues = function(values, row, opts) {
    var final_value, float_value, str_value, value;
    if (opts == null) {
      opts = {};
    }
    str_value = values.join("");
    if (CUI.util.isEmpty(str_value)) {
      return str_value;
    }
    value = CUI.NumberInput.parse(str_value, this._fixed);
    if (value === null || value === void 0) {
      return "invalid:" + str_value;
    }
    if (this._fixed === -1) {
      return value;
    }
    final_value = value.toFixed(this._fixed);
    if (this._fixed === 0 && opts.prepare) {
      float_value = CUI.NumberInput.parse(str_value, -1);
      if (float_value !== parseInt(final_value)) {
        row[this._csvImporter.cf_idx.warning_text] = $$("number.column.csv.importer.destination.field.number_rounded");
      }
    }
    return final_value;
  };

  NumberColumnCSVImporterDestinationField.prototype.getRecordValue = function(configs, row, opts) {
    var _value, i, j, len, len1, prepareValue, v, value, values;
    if (opts == null) {
      opts = {};
    }
    value = NumberColumnCSVImporterDestinationField.__super__.getRecordValue.call(this, configs, row, opts);
    if (opts.for_preview && !opts.for_preview_detail) {
      return value;
    }
    prepareValue = (function(_this) {
      return function(_value) {
        if (CUI.util.isString(_value)) {
          if (_value.startsWith("invalid:")) {
            return _value;
          } else {
            _value = CUI.NumberInput.parse(_value, _this._fixed);
          }
        }
        if (_this._fixed === -1) {
          return _value;
        }
        _value = _value * Math.pow(10, _this._fixed);
        return parseInt(_value.toFixed());
      };
    })(this);
    if (CUI.util.isArray(value)) {
      values = [];
      for (i = 0, len = value.length; i < len; i++) {
        _value = value[i];
        if (CUI.util.isArray(_value)) {
          for (j = 0, len1 = _value.length; j < len1; j++) {
            v = _value[j];
            values.push(prepareValue(v));
          }
        } else {
          values.push(prepareValue(_value));
        }
      }
      return values;
    } else {
      return prepareValue(value);
    }
  };

  NumberColumnCSVImporterDestinationField.prototype.prepareDataChunk = function(configs, rows, offset) {
    var _rec, checkRecord, i, len, row;
    checkRecord = (function(_this) {
      return function(value, row) {
        var i, len, v;
        if (CUI.util.isArray(value)) {
          for (i = 0, len = value.length; i < len; i++) {
            v = value[i];
            checkRecord(v, row);
          }
        } else {
          if (!CUI.util.isString(value)) {
            return;
          }
          if (value.startsWith("invalid:")) {
            _this._csvImporter.setRowInvalid(row, "number.column.csv.importer.destination.field.number_invalid", {
              number: value.substr("invalid:".length)
            });
          }
        }
      };
    })(this);
    for (i = 0, len = rows.length; i < len; i++) {
      row = rows[i];
      _rec = this.getRecordValue(configs, row, {
        prepare: true
      });
      checkRecord(_rec, row);
    }
    return CUI.resolvedPromise();
  };

  return NumberColumnCSVImporterDestinationField;

})(ObjecttypeCSVImporterDestinationField);
// Generated by CoffeeScript 1.12.7
var PoolFieldCSVImporterDestinationField,
  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;

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

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

  PoolFieldCSVImporterDestinationField.prototype.initOpts = function() {
    PoolFieldCSVImporterDestinationField.__super__.initOpts.call(this);
    return this.mergeOpt("field", {
      check: PoolField
    });
  };

  PoolFieldCSVImporterDestinationField.prototype.supportsHierarchy = function() {
    return false;
  };

  PoolFieldCSVImporterDestinationField.prototype.getCustomFields = function() {
    var customFields, opts;
    opts = [
      {
        value: "_id",
        text: $$("pool.object.csv.importer.destination.field.id")
      }, {
        value: "reference",
        text: $$("pool.object.csv.importer.destination.field.reference")
      }, {
        value: "shortname",
        text: $$("pool.object.csv.importer.destination.field.shortname")
      }
    ];
    customFields = [
      {
        name: "field",
        form: {
          label: $$("pool.object.csv.importer.destination.field.label")
        },
        type: CUI.Select,
        options: opts
      }
    ];
    return customFields;
  };

  PoolFieldCSVImporterDestinationField.prototype.getRecordValue = function(configs, row, opts) {
    var _value, availablePools, i, idPool, len, pool, poolField, ref, statusText, value;
    if (opts == null) {
      opts = {};
    }
    _value = PoolFieldCSVImporterDestinationField.__super__.getRecordValue.call(this, configs, row, opts);
    if (CUI.util.isEmpty(_value)) {
      return _value;
    }
    poolField = configs[0].config.field;
    value = _value;
    if (poolField === "_id") {
      value = parseInt(_value);
    }
    availablePools = this._csvImporter.getMaskDBInfo().getPoolIds();
    for (i = 0, len = availablePools.length; i < len; i++) {
      idPool = availablePools[i];
      pool = ez5.pools.findPoolById(idPool);
      if (!(pool != null ? (ref = pool.data) != null ? ref.pool : void 0 : void 0)) {
        continue;
      }
      if (pool.data.pool[poolField] === value) {
        if (opts.for_preview_detail) {
          return pool.data;
        }
        return {
          pool: {
            _id: idPool
          }
        };
      }
    }
    statusText = $$("pool.object.csv.importer.destination.field.pool_not_found", {
      value: value
    });
    return "invalid: " + statusText;
  };

  PoolFieldCSVImporterDestinationField.prototype.prepareDataChunk = function(configs, rows) {
    var i, len, pool, row, statusText;
    for (i = 0, len = rows.length; i < len; i++) {
      row = rows[i];
      pool = this.getRecordValue(configs, row);
      if (CUI.util.isString(pool) && pool.startsWith("invalid:")) {
        statusText = pool.split(": ")[1];
        this._csvImporter.setRowInvalidWithText(row, statusText);
      }
    }
    return CUI.resolvedPromise();
  };

  return PoolFieldCSVImporterDestinationField;

})(ObjecttypeCSVImporterDestinationField);
// Generated by CoffeeScript 1.12.7
var TagsFieldCSVImporterDestinationField,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  TagsFieldCSVImporterDestinationField.EMPTY = 'EMPTY';

  TagsFieldCSVImporterDestinationField.prototype.initOpts = function() {
    TagsFieldCSVImporterDestinationField.__super__.initOpts.call(this);
    return this.mergeOpt("field", {
      check: TagsField
    });
  };

  TagsFieldCSVImporterDestinationField.prototype.supportsHierarchy = function() {
    return false;
  };

  TagsFieldCSVImporterDestinationField.prototype.getCustomFields = function() {
    var customFields, fieldOpts, separatorOpts;
    fieldOpts = [
      {
        value: "_id",
        text: $$("tags.object.csv.importer.destination.field.id")
      }, {
        value: "display_name",
        text: $$("tags.object.csv.importer.destination.field.display_name")
      }, {
        value: "reference",
        text: $$("tags.object.csv.importer.destination.field.reference")
      }, {
        value: "shortname",
        text: $$("tags.object.csv.importer.destination.field.short_name")
      }
    ];
    separatorOpts = [",", ";", "|", "\\n"].map(function(value) {
      return {
        value: value,
        text: value
      };
    });
    customFields = [
      {
        name: "field",
        form: {
          label: $$("tags.object.csv.importer.destination.field.label")
        },
        type: CUI.Select,
        options: fieldOpts
      }, {
        name: "separator",
        form: {
          label: $$("tags.object.csv.importer.destination.separator.label")
        },
        type: CUI.Select,
        options: separatorOpts
      }
    ];
    return customFields;
  };

  TagsFieldCSVImporterDestinationField.prototype.getRecordValue = function(configs, row, opts) {
    var _values, availableTags, field, i, id, len, message, separator, tag, tags, val, value;
    if (opts == null) {
      opts = {};
    }
    value = TagsFieldCSVImporterDestinationField.__super__.getRecordValue.call(this, configs, row, opts);
    if (CUI.util.isEmpty(value)) {
      return TagsFieldCSVImporterDestinationField.EMPTY;
    }
    separator = configs[0].config.separator;
    field = configs[0].config.field;
    tags = [];
    availableTags = this._csvImporter.getMaskDBInfo().availableTagIds() || [];
    if (separator === "\\n") {
      separator = new RegExp(separator);
    }
    _values = value.split(separator);
    for (i = 0, len = _values.length; i < len; i++) {
      val = _values[i];
      val = val.trim();
      if (field === "_id") {
        id = parseInt(val);
        if (isNaN(id)) {
          message = $$("tag.object.csv.importer.destination.field.not_number", {
            value: val
          });
          return "invalid: " + message;
        }
      } else {
        tag = null;
        if (field === "display_name") {
          tag = ez5.tagForm.findTagByDisplayName(val);
        } else if (field === "reference") {
          tag = ez5.tagForm.findTagByReference(val);
        } else if (field === "shortname") {
          tag = ez5.tagForm.findTagByShortname(val);
        }
        if (!tag) {
          message = $$("tag.object.csv.importer.destination.field.not_found", {
            value: val
          });
          return "invalid: " + message;
        }
        id = tag.getId();
      }
      if (indexOf.call(availableTags, id) < 0) {
        message = $$("tag.object.csv.importer.destination.field.not_available", {
          value: val
        });
        return "invalid: " + message;
      }
      tags.push({
        _id: id
      });
    }
    return tags;
  };

  TagsFieldCSVImporterDestinationField.prototype.prepareDataChunk = function(configs, rows) {
    var i, len, row, statusText, tags;
    for (i = 0, len = rows.length; i < len; i++) {
      row = rows[i];
      tags = this.getRecordValue(configs, row);
      if (CUI.util.isString(tags) && tags.startsWith("invalid:")) {
        statusText = tags.split(": ")[1];
        this._csvImporter.setRowInvalidWithText(row, statusText);
      }
    }
    return CUI.resolvedPromise();
  };

  return TagsFieldCSVImporterDestinationField;

})(ObjecttypeCSVImporterDestinationField);
// Generated by CoffeeScript 1.12.7
var GeoJsonColumnCSVImporterDestinationField,
  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;

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

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

  GeoJsonColumnCSVImporterDestinationField.prototype.initOpts = function() {
    GeoJsonColumnCSVImporterDestinationField.__super__.initOpts.call(this);
    return this.mergeOpt("field", {
      check: GeoJsonColumn
    });
  };

  GeoJsonColumnCSVImporterDestinationField.prototype.supportsHierarchy = function() {
    return false;
  };

  GeoJsonColumnCSVImporterDestinationField.prototype.getFormat = function() {
    return "json";
  };

  GeoJsonColumnCSVImporterDestinationField.prototype.formatValues = function(values) {
    var geo_json;
    geo_json = GeoJsonColumn.parse(values[0]);
    if (CUI.util.isEmpty(geo_json)) {
      return null;
    }
    return geo_json;
  };

  return GeoJsonColumnCSVImporterDestinationField;

})(ObjecttypeCSVImporterDestinationField);
// Generated by CoffeeScript 1.12.7
var CSVImporterConfigurator,
  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;

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

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

  CSVImporterConfigurator.prototype.initOpts = function() {
    CSVImporterConfigurator.__super__.initOpts.call(this);
    return this.addOpts({
      settings: {
        "default": {}
      },
      onSaveConfig: {
        check: Function,
        mandatory: true
      }
    });
  };

  CSVImporterConfigurator.prototype.updateButtons = function() {
    var buttons, hasMapping;
    if (this.readyForImport()) {
      hasMapping = this.__hasMappedColumns();
      buttons = [];
      if (!hasMapping) {
        buttons.push(new LocaLabel({
          "class": "ez5-csv-importer-prepare-data-error",
          icon: "warning",
          loca_key: "objecttype.csv.importer.required.fields.mapping"
        }));
      }
      buttons.push({
        loca_key: "csv.importer.button.save",
        disabled: !hasMapping,
        onClick: (function(_this) {
          return function(ev, btn) {
            return _this.__saveSettingAndClose();
          };
        })(this)
      });
      return this.__modal.replace(buttons, "footer_right");
    } else {
      return CSVImporterConfigurator.__super__.updateButtons.call(this);
    }
  };

  CSVImporterConfigurator.prototype.__hasMappedColumns = function() {
    var dest_field_name, key, mapping, ref;
    mapping = (ref = this.__form_data) != null ? ref.mapping : void 0;
    if (!mapping) {
      return false;
    }
    for (key in mapping) {
      dest_field_name = mapping[key];
      if (typeof key === "string" && key.indexOf("custom_") === 0) {
        continue;
      }
      if (this.getDestinationFieldByName(dest_field_name)) {
        return true;
      }
    }
    return false;
  };

  CSVImporterConfigurator.getConfigButton = function(pname) {
    var field, getButtonLabel;
    getButtonLabel = (function(_this) {
      return function(settings) {
        if (CUI.util.isEmpty(settings)) {
          return $$("objecttype.csv.importer.configure.button.label");
        } else {
          return $$("objecttype.csv.importer.edit.button.label");
        }
      };
    })(this);
    field = {
      type: CUI.DataFieldProxy,
      name: pname,
      element: (function(_this) {
        return function(dataField) {
          var button;
          button = new CUI.FormButton({
            text: getButtonLabel(dataField.getData()[dataField.getName()]),
            onClick: function(ev, button) {
              var csvImporter, settings;
              settings = dataField.getData()[dataField.getName()];
              csvImporter = new CSVImporterConfigurator({
                settings: settings,
                onSaveConfig: function(new_settings) {
                  dataField.getData()[dataField.getName()] = new_settings;
                  button.setText(getButtonLabel(new_settings));
                  return CUI.Events.trigger({
                    node: dataField,
                    type: "data-changed"
                  });
                }
              });
              return csvImporter.startWithSettings();
            }
          });
          return button.start();
        };
      })(this)
    };
    return field;
  };

  CSVImporterConfigurator.prototype.startWithSettings = function() {
    if (!CUI.util.isEmpty(this._settings)) {
      this.__setingsUploadedText = new CUI.Label({
        text: ""
      });
      this.resetFile();
      this.showModal();
      this.loadCachedCSV(this._settings);
      return this.__loadCSVData().done((function(_this) {
        return function() {
          return _this.loadSettings(_this._settings.settings, true).done(function() {
            _this.reloadFormData();
            return _this.initMapping();
          });
        };
      })(this));
    } else {
      return this.start();
    }
  };

  CSVImporterConfigurator.prototype.getFormSaveData = function() {
    var sd;
    sd = CSVImporterConfigurator.__super__.getFormSaveData.call(this, true);
    sd.csv_filename = this.__form_data.csv_filename;
    sd.cached_csv_text = this.__csv_text;
    return sd;
  };

  CSVImporterConfigurator.prototype.loadCachedCSV = function(settings) {
    var ref;
    if (settings != null ? (ref = settings.settings) != null ? ref.cached_csv_text : void 0 : void 0) {
      return this.__csv_text = settings.settings.cached_csv_text;
    }
  };

  CSVImporterConfigurator.prototype.__saveSettingAndClose = function() {
    var settings;
    if (!this.__hasMappedColumns()) {
      return;
    }
    settings = {
      __EASYDB_CSV_IMPORTER_SETTINGS: true,
      version: 2,
      settings: this.getFormSaveData()
    };
    this._onSaveConfig(settings);
    return this.__modal.destroy();
  };

  CSVImporterConfigurator.prototype.__getSupportedEASTypes = function() {
    return [
      {
        text: $$("eas.importer.fields.eas_type.url.option.label"),
        value: EASImporter.EAS_TYPE.URL
      }, {
        text: $$("eas.importer.fields.eas_type.ignore.option.label"),
        value: EASImporter.EAS_TYPE.IGNORE
      }
    ];
  };

  return CSVImporterConfigurator;

})(ObjecttypeCSVImporter);
// Generated by CoffeeScript 1.12.7
var CSVExporter,
  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;

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

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

  CSVExporter.prototype.initOpts = function() {
    return CSVExporter.__super__.initOpts.call(this);
  };

  CSVExporter.prototype.getTitle = function() {
    return this.__cls;
  };

  CSVExporter.prototype.getFileName = function() {
    return "users-" + ez5.session.getSystemName() + ".csv";
  };

  CSVExporter.prototype.start = function() {
    var dfr, promise, show_toaster, toaster;
    dfr = new CUI.Deferred();
    this.__stopExport = false;
    toaster = null;
    show_toaster = (function(_this) {
      return function(txt) {
        return toaster = CUI.toaster({
          title: _this.getTitle(),
          cancel: true,
          onCancel: function() {
            _this.__stopExport = true;
            return promise;
          },
          show_ms: 0,
          text: txt,
          text_icon: $$("csv.exporter.progress|icon")
        });
      };
    })(this);
    promise = this.getRows().progress((function(_this) {
      return function(progress) {
        var txt;
        txt = $$("csv.exporter.progress", {
          offset: progress.offset + 1,
          count: progress.count
        });
        if (!toaster) {
          show_toaster(txt);
        } else {
          toaster.updateText(txt);
        }
      };
    })(this)).always((function(_this) {
      return function() {
        return toaster.destroy();
      };
    })(this)).done((function(_this) {
      return function(rows) {
        var csv, hrow, i, ref;
        ref = _this.getHeaderRows();
        for (i = ref.length - 1; i >= 0; i += -1) {
          hrow = ref[i];
          rows.splice(0, 0, hrow);
        }
        csv = new CUI.CSVData({
          rows: rows
        });
        CUI.downloadData('\uFEFF' + csv.toText(), _this.getFileName());
        return dfr.resolve();
      };
    })(this)).fail((function(_this) {
      return function() {
        return dfr.reject();
      };
    })(this));
    return dfr.promise();
  };

  CSVExporter.prototype.getHeaderRows = function() {
    return [];
  };

  CSVExporter.prototype.getRowsChunk = function() {
    return [];
  };

  CSVExporter.prototype.getCount = function() {
    return 0;
  };

  CSVExporter.prototype.getLimit = function() {
    return 10;
  };

  CSVExporter.prototype.getRows = function() {
    var count, dfr, get_next_chunk, limit, offset, rows;
    dfr = new CUI.Deferred();
    count = this.getCount();
    limit = this.getChunkSize();
    offset = 0;
    rows = [];
    get_next_chunk = (function(_this) {
      return function() {
        var _limit;
        if (offset >= count) {
          dfr.resolve(rows);
          return;
        }
        dfr.notify({
          offset: offset,
          count: count
        });
        _limit = Math.min(count - offset, limit);
        return _this.getRowsChunk(offset, _limit).progress(function(info) {
          return dfr.notify({
            offset: info.offset,
            count: count
          });
        }).done(function(more_rows) {
          if (_this.exportStopRequested()) {
            dfr.reject();
            return;
          }
          rows.push.apply(rows, more_rows);
          offset = offset + limit;
          get_next_chunk();
        }).fail(dfr.reject);
      };
    })(this);
    get_next_chunk();
    return dfr.promise();
  };

  CSVExporter.prototype.exportStopRequested = function() {
    return this.__stopExport;
  };

  return CSVExporter;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var CustomDataTypeColumnCSVImporterDestinationField,
  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;

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

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

  CustomDataTypeColumnCSVImporterDestinationField.prototype.initOpts = function() {
    CustomDataTypeColumnCSVImporterDestinationField.__super__.initOpts.call(this);
    return this.mergeOpt("field", {
      check: CustomDataType
    });
  };

  CustomDataTypeColumnCSVImporterDestinationField.prototype.supportsHierarchy = function() {
    return false;
  };

  CustomDataTypeColumnCSVImporterDestinationField.prototype.getFormat = function() {
    return "json";
  };

  return CustomDataTypeColumnCSVImporterDestinationField;

})(ObjecttypeCSVImporterDestinationField);
// Generated by CoffeeScript 1.12.7
var JSONImporterReport;

JSONImporterReport = (function() {
  function JSONImporterReport() {}

  JSONImporterReport.KEY_EAS = "eas";

  JSONImporterReport.clear = function() {
    this.__report = null;
  };

  JSONImporterReport.start = function() {
    this.__report = {};
    this.__report[this.KEY_EAS] = {
      success: [],
      failure: []
    };
  };

  JSONImporterReport.get = function() {
    var blocks, easBlock, easReport, objectTypesBlock;
    if (CUI.util.isNull(this.__report)) {
      return null;
    }
    blocks = [];
    if (Object.keys(this.__report).length > 1) {
      objectTypesBlock = new CUI.Block({
        text: $$("json.importer.report.quantity-object-type.title"),
        content: (function(_this) {
          return function() {
            var key, label, labels, ref, value;
            labels = [];
            ref = _this.__report;
            for (key in ref) {
              value = ref[key];
              if (key === _this.KEY_EAS) {
                continue;
              }
              label = new CUI.Label({
                multiline: true,
                markdown: true,
                text: $$("json.importer.report.quantity-object-type", {
                  objectType: key,
                  quantity: value
                })
              });
              labels.push(label);
            }
            return new CUI.VerticalList({
              content: labels
            });
          };
        })(this)
      });
      blocks.push(objectTypesBlock);
    }
    easReport = this.__report[this.KEY_EAS];
    if (easReport.success.length > 0 || easReport.failure.length > 0) {
      easBlock = new CUI.Block({
        text: $$("json.importer.report.eas.title"),
        content: (function(_this) {
          return function() {
            var content, i, label, len, li, ref, ul, url;
            content = [];
            if (easReport.success.length > 0) {
              label = new CUI.Label({
                multiline: true,
                markdown: true,
                text: $$("json.importer.report.eas.success-quantity-display-name", {
                  quantity: easReport.success.length
                })
              });
              content.push(label);
            }
            if (easReport.failure.length > 0) {
              label = new CUI.Label({
                multiline: true,
                markdown: true,
                text: $$("json.importer.report.eas.failure-quantity-display-name", {
                  quantity: easReport.failure.length
                })
              });
              content.push(label);
              label = new CUI.Label({
                multiline: true,
                markdown: true,
                text: $$("json.importer.report.eas.failure-url-display-name")
              });
              content.push(label);
              ul = CUI.dom.ul();
              ref = easReport.failure;
              for (i = 0, len = ref.length; i < len; i++) {
                url = ref[i];
                li = CUI.dom.li();
                CUI.dom.append(li, url);
                CUI.dom.append(ul, li);
              }
              content.push(ul);
              return content;
            }
          };
        })(this)
      });
      blocks.push(easBlock);
    }
    if (blocks.length === 0) {
      return null;
    }
    return new CUI.VerticalList({
      content: blocks
    });
  };

  JSONImporterReport.add = function(objectType, quantity) {
    if (CUI.util.isNull(this.__report)) {
      return;
    }
    if (!this.__report[objectType]) {
      this.__report[objectType] = 0;
    }
    this.__report[objectType] += quantity;
  };

  JSONImporterReport.addEAS = function(url, success) {
    var easReport, report;
    if (success == null) {
      success = true;
    }
    if (CUI.util.isNull(this.__report)) {
      return;
    }
    easReport = this.__report[this.KEY_EAS];
    report = success ? easReport.success : easReport.failure;
    report.push(url);
  };

  return JSONImporterReport;

})();
// Generated by CoffeeScript 1.12.7
var JSONImporterLogs;

JSONImporterLogs = (function() {
  function JSONImporterLogs() {}

  JSONImporterLogs.LEVEL_ERROR = "ERROR";

  JSONImporterLogs.LEVEL_WARN = "WARN";

  JSONImporterLogs.LEVEL_INFO = "INFO";

  JSONImporterLogs.OPERATION_UPDATE = "UPDATE";

  JSONImporterLogs.OPERATION_INSERT = "INSERT";

  JSONImporterLogs.OPERATION_GET = "GET";

  JSONImporterLogs.OPERATION_INSERT_SKIPPED = "INSERT_SKIPPED";

  JSONImporterLogs.OPERATION_UPDATE_SKIPPED = "UPDATE_SKIPPED";

  JSONImporterLogs.currentPayload = null;

  JSONImporterLogs.__logs = [];

  JSONImporterLogs.setCurrentPayload = function(payload) {
    this.currentPayload = payload;
  };

  JSONImporterLogs.add = function(opts) {
    var log;
    log = CUI.Element.readOpts(opts, "add", {
      level: {
        mandatory: true,
        check: (function(_this) {
          return function(value) {
            return value === JSONImporterLogs.LEVEL_INFO || value === JSONImporterLogs.LEVEL_WARN || value === JSONImporterLogs.LEVEL_ERROR;
          };
        })(this)
      },
      operation: {
        check: (function(_this) {
          return function(value) {
            return value === JSONImporterLogs.OPERATION_UPDATE || value === JSONImporterLogs.OPERATION_INSERT || value === JSONImporterLogs.OPERATION_GET || value === JSONImporterLogs.OPERATION_INSERT_SKIPPED || value === OPERATION_UPDATE_SKIPPED;
          };
        })(this)
      },
      objectType: {
        check: (function(_this) {
          return function(value) {
            return CUI.util.isString(value);
          };
        })(this)
      },
      baseType: {
        check: (function(_this) {
          return function(value) {
            return CUI.util.isString(value);
          };
        })(this)
      },
      payloadIndex: {
        check: (function(_this) {
          return function(value) {
            return CUI.util.isString(value) || CUI.util.isNumber(value);
          };
        })(this)
      },
      objectId: {
        check: (function(_this) {
          return function(value) {
            return CUI.util.isString(value) || CUI.util.isNumber(value) || CUI.util.isArray(value);
          };
        })(this)
      },
      systemObjectId: {
        check: (function(_this) {
          return function(value) {
            return CUI.util.isString(value) || CUI.util.isNumber(value);
          };
        })(this)
      },
      uniqueKeys: {
        check: Array,
        "default": []
      },
      duration: {
        check: (function(_this) {
          return function(value) {
            return CUI.util.isString(value) || CUI.util.isNumber(value);
          };
        })(this)
      },
      message: {
        check: String
      },
      chunk: {
        check: String
      },
      url: {
        check: String
      },
      easFilename: {
        check: String
      },
      easExtension: {
        check: String
      },
      easFilesize: {
        check: "Integer"
      },
      easClass: {
        check: String
      }
    });
    log.date = ez5.format_date_and_time(new Date(), true);
    if (this.currentPayload) {
      log.payload = this.currentPayload;
      if (log.chunk) {
        log.payload += " [" + log.chunk + "]";
      }
    }
    this.__logs.push(log);
  };

  JSONImporterLogs.LOGS_LOCAL_STORAGE_KEY = "json-importer-table-logs";

  JSONImporterLogs.getAll = function() {};

  JSONImporterLogs.clear = function() {
    this.__logs.length = 0;
  };

  JSONImporterLogs.download = function() {
    var csv, duration, header, i, len, log, objectId, ref, rows;
    if (this.__logs.length === 0) {
      CUI.alert({
        text: $$("json.importer.error.message.logs.no-logs-available")
      });
      return;
    }
    header = [$$("json.importer.csv.table.header-title.level"), $$("json.importer.csv.table.header-title.date"), $$("json.importer.csv.table.header-title.message"), $$("json.importer.csv.table.header-title.payload"), $$("json.importer.csv.table.header-title.payloadIndex"), $$("json.importer.csv.table.header-title.operation"), $$("json.importer.csv.table.header-title.duration"), $$("json.importer.csv.table.header-title.objectType"), $$("json.importer.csv.table.header-title.baseType"), $$("json.importer.csv.table.header-title.objectId"), $$("json.importer.csv.table.header-title.uniqueKeys"), $$("json.importer.csv.table.header-title.systemObjectId"), $$("json.importer.csv.table.header-title.easFilename"), $$("json.importer.csv.table.header-title.url"), $$("json.importer.csv.table.header-title.easClass"), $$("json.importer.csv.table.header-title.easExtension"), $$("json.importer.csv.table.header-title.easFilesize")];
    rows = [header];
    ref = this.__logs;
    for (i = 0, len = ref.length; i < len; i++) {
      log = ref[i];
      objectId = log.objectId;
      if (CUI.util.isArray(objectId)) {
        objectId.join(", ");
      }
      if (CUI.util.isString(log.duration)) {
        duration = log.duration;
      } else if (log.duration) {
        duration = ez5.format_seconds(Math.round(log.duration / 1000));
      }
      rows.push([log.level, log.date, log.message, log.payload, log.payloadIndex, log.operation, duration, log.objectType, log.baseType, objectId, log.uniqueKeys.join(","), log.systemObjectId, log.easFilename, log.url, log.easClass, log.easExtension, log.easFilesize]);
    }
    csv = new CUI.CSVData({
      rows: rows
    });
    CUI.FileReader.save("json_importer_logs.csv", '\uFEFF' + csv.toText());
  };

  return JSONImporterLogs;

})();
// Generated by CoffeeScript 1.12.7
var JSONImporterUtils;

JSONImporterUtils = (function() {
  function JSONImporterUtils() {}

  JSONImporterUtils.getFile = function(url) {
    var headers, xhr;
    url = Session.cleanServerUrl(url);
    if (CUI.util.isEmpty(url)) {
      return CUI.rejectedPromise();
    }
    headers = {};
    headers["content-type"] = "application/x-www-form-urlencoded";
    xhr = new CUI.XHR({
      url: url
    });
    return xhr.start();
  };

  JSONImporterUtils.getErrorMessageFromResponse = function(response, statusText) {
    var code, description, message, parameters, ref;
    if (response instanceof XMLHttpRequest) {
      if (!statusText) {
        if (CUI.util.isFunction(response.statusText)) {
          statusText = response.statusText();
        } else {
          statusText = response.statusText;
        }
      }
      if (response.responseJSON) {
        ref = response.responseJSON, code = ref.code, parameters = ref.parameters, description = ref.description;
        if (ez5.version("6")) {
          description = response.responseJSON.error;
        }
      }
    } else if (CUI.util.isPlainObject(response)) {
      code = response.code, parameters = response.parameters, description = response.description;
    }
    if (code && parameters) {
      if (ez5.loca.has(code)) {
        message = $$(code, parameters);
      }
      if (description) {
        if (!message) {
          message = "";
        } else {
          message += " | ";
        }
        message += description;
      }
      if (statusText) {
        message = statusText + " | " + message;
      }
      return message;
    }
  };

  JSONImporterUtils.updateEASProgress = function(easFieldsCreated) {
    if (easFieldsCreated == null) {
      easFieldsCreated = 0;
    }
    return CUI.Events.trigger({
      type: "json-importer-update-progress",
      info: {
        objectsCreated: 0,
        easFieldsCreated: easFieldsCreated
      }
    });
  };

  JSONImporterUtils.updateProgress = function(payloadUrl, type, objectsTotal, batchSize, objectsCreated) {
    if (objectsCreated == null) {
      objectsCreated = 0;
    }
    return CUI.Events.trigger({
      type: "json-importer-update-progress",
      info: {
        payloadUrl: payloadUrl,
        type: type,
        objectsTotal: objectsTotal,
        batchSize: batchSize,
        objectsCreated: objectsCreated,
        easFieldsCreated: 0
      }
    });
  };

  return JSONImporterUtils;

})();
// Generated by CoffeeScript 1.12.7
var JSONImporter,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  JSONImporter.preferenceHistoryKey = "json-importer-url-history";

  JSONImporter.localStorageKey = "json-importer-data";

  function JSONImporter(opts) {
    this.opts = opts != null ? opts : {};
    JSONImporter.__super__.constructor.call(this, this.opts);
    this.__init();
  }

  JSONImporter.prototype.initOpts = function() {
    JSONImporter.__super__.initOpts.call(this);
    return this.addOpts({
      manifestUrl: {
        check: String
      }
    });
  };

  JSONImporter.prototype.__preparePayloads = function() {
    var currentIndex, deferred, load, processablePayloads;
    deferred = new CUI.Deferred();
    ez5.splash.show("json.importer.splash.validate-payloads");
    JSONImporterLogs.add({
      level: JSONImporterLogs.LEVEL_INFO,
      message: $$("json.importer.modal.validate.start")
    });
    processablePayloads = this.__getProcessablePayloads();
    currentIndex = 0;
    load = (function(_this) {
      return function() {
        var payload;
        payload = processablePayloads[currentIndex];
        if (!payload) {
          JSONImporterLogs.add({
            level: JSONImporterLogs.LEVEL_INFO,
            message: $$("json.importer.modal.validate.finish")
          });
          ez5.splash.hide();
          deferred.resolve();
          return;
        }
        return _this.__preparePayload(payload).done(function() {
          payload.status = $$("json.importer.fields.payloads.status.ready");
          currentIndex++;
          return load();
        }).fail(function(errorMessage) {
          ez5.splash.hide();
          payload.status = $$("json.importer.fields.payloads.status.error");
          return deferred.reject(errorMessage);
        });
      };
    })(this);
    load();
    return deferred.promise();
  };

  JSONImporter.prototype.__preparePayload = function(payload, includePayloadData) {
    var jsonPayload;
    if (includePayloadData == null) {
      includePayloadData = false;
    }
    jsonPayload = new JSONPayload({
      payload: payload,
      settings: this.__data
    });
    return jsonPayload.getTotalCount(includePayloadData).done((function(_this) {
      return function(countData) {
        payload.count = countData;
        payload.objecttype = countData.objecttype;
        payload.easCount = countData.easFieldsTotal || "-";
        payload.objectsCount = countData.objectsTotal;
        payload.batchCount = Math.ceil(payload.objectsCount / _this.__data.batchSize);
        return payload.status = $$("json.importer.fields.payloads.status.pending");
      };
    })(this)).fail((function(_this) {
      return function() {
        return payload.status = $$("json.importer.fields.payloads.status.error");
      };
    })(this)).always((function(_this) {
      return function() {
        return jsonPayload.destroy();
      };
    })(this));
  };

  JSONImporter.prototype.__startImport = function() {
    var abortListenerFallback, currentProcessIndex, deferred, jsonImporterProgressModal, onSuccess, processPayload, processablePayloads, progressCounters, startTime, stopListener, stopNextImport;
    deferred = new CUI.Deferred();
    startTime = new Date().getTime();
    abortListenerFallback = CUI.Events.listen({
      type: "json-importer-abort-upload",
      call: (function(_this) {
        return function() {
          var ref;
          if ((ref = deferred.state()) === "rejected" || ref === "resolved") {
            ez5.splash.hide();
          }
          return abortListenerFallback.destroy();
        };
      })(this)
    });
    processablePayloads = this.__getProcessablePayloads();
    progressCounters = {
      easFieldsTotal: 0,
      easFieldsDone: 0,
      objectsTotal: 0,
      objectsDone: 0
    };
    processablePayloads.forEach((function(_this) {
      return function(payload) {
        if (!payload.success) {
          progressCounters.objectsTotal += payload.count.objectsTotal;
          return progressCounters.easFieldsTotal += payload.count.easFieldsTotal || 0;
        }
      };
    })(this));
    jsonImporterProgressModal = new JSONImporterProgressModal({
      progressCounters: progressCounters,
      easType: this.__data.easType
    });
    currentProcessIndex = 0;
    onSuccess = (function(_this) {
      return function(isAbort) {
        var millisecondsElapsed, time;
        stopListener.destroy();
        jsonImporterProgressModal.destroy();
        millisecondsElapsed = (new Date().getTime()) - startTime;
        time = ez5.format_seconds(Math.round(millisecondsElapsed / 1000));
        return deferred.resolve(isAbort, time);
      };
    })(this);
    stopNextImport = false;
    stopListener = CUI.Events.listen({
      type: "json-importer-abort-upload",
      call: (function(_this) {
        return function() {
          return stopNextImport = true;
        };
      })(this)
    });
    processPayload = (function(_this) {
      return function() {
        var jsonPayload, payload;
        payload = processablePayloads[currentProcessIndex];
        if (!payload) {
          return onSuccess(false);
        }
        if (payload.success) {
          currentProcessIndex++;
          processPayload();
          return;
        }
        jsonPayload = new JSONPayload({
          payload: payload,
          settings: _this.__data
        });
        return jsonPayload["import"]().done(function(jsonPayloadRollback) {
          payload.status = $$("json.importer.fields.payloads.status.success");
          payload.success = true;
          delete payload.count;
          currentProcessIndex++;
          if (stopNextImport) {
            return onSuccess(true);
          } else {
            return processPayload();
          }
        }).fail(function(response, batchOffset) {
          if (batchOffset == null) {
            batchOffset = payload.batchOffset;
          }
          stopListener.destroy();
          jsonImporterProgressModal.destroy();
          payload.status = $$("json.importer.fields.payloads.status.error");
          payload.batchOffset = batchOffset;
          return deferred.reject(response);
        }).always(function() {
          jsonPayload.destroy();
          if (stopNextImport) {
            ez5.splash.hide();
            return stopNextImport = false;
          }
        });
      };
    })(this);
    JSONImporterLogs.add({
      level: JSONImporterLogs.LEVEL_INFO,
      message: $$("json.importer.modal.process.start")
    });
    JSONImporterLogs.add({
      level: JSONImporterLogs.LEVEL_INFO,
      message: $$("json.importer.modal.process.start.config.payload_base_uri", {
        value: this.__data.payloadBaseUri
      })
    });
    JSONImporterLogs.add({
      level: JSONImporterLogs.LEVEL_INFO,
      message: $$("json.importer.modal.process.start.config.batch_size", {
        value: this.__data.batchSize
      })
    });
    JSONImporterLogs.add({
      level: JSONImporterLogs.LEVEL_INFO,
      message: $$("json.importer.modal.process.start.config.eas_type", {
        value: $$("eas.importer.fields.eas_type." + this.__data.easType + ".option.label")
      })
    });
    JSONImporterLogs.add({
      level: JSONImporterLogs.LEVEL_INFO,
      message: $$("json.importer.modal.process.start.config.eas_skip_errors", {
        value: this.__data.easSkipErrors
      })
    });
    JSONImporterLogs.add({
      level: JSONImporterLogs.LEVEL_INFO,
      message: $$("json.importer.modal.process.start.config.skip_unique_constraint_errors", {
        value: this.__data.skipUniqueConstraintErrors
      })
    });
    if (this.__data.easReplaceUrl) {
      JSONImporterLogs.add({
        level: JSONImporterLogs.LEVEL_INFO,
        message: $$("json.importer.modal.process.start.config.eas_replace_url", {
          value: this.__data.easReplaceUrl
        })
      });
    }
    if (this.__data.mapping) {
      JSONImporterLogs.add({
        level: JSONImporterLogs.LEVEL_INFO,
        message: $$("json.importer.modal.process.start.config.mapping", {
          value: this.__data.mapping
        })
      });
    }
    jsonImporterProgressModal.show();
    processPayload();
    return deferred.promise();
  };

  JSONImporter.prototype.__init = function() {
    var data;
    data = CUI.getLocalStorage(JSONImporter.localStorageKey);
    if (!CUI.util.isEmpty(data)) {
      this.__data = data;
      this.__setPendingAllProcessablePayloads();
    } else {
      this.__data = {
        url: this._manifestUrl,
        payloads: [],
        easSkipErrors: true,
        skipUniqueConstraintErrors: false
      };
    }
    this.__modal = this.__buildModal();
    this.__initRightPaneValues();
    if (this._manifestUrl) {
      this.__getManifest(this._manifestUrl).done((function(_this) {
        return function(responseData) {
          return _this.__onManifestLoaded(responseData, _this._manifestUrl);
        };
      })(this));
    }
  };

  JSONImporter.prototype.__initRightPaneValues = function() {
    this.__payloadSelected = null;
    this.__currentPage = 0;
    if (CUI.dom.isVisible(this.__modalContent.right())) {
      this.__updateNavigation();
    }
  };

  JSONImporter.prototype.__onFail = function(response, addLog) {
    if (addLog == null) {
      addLog = true;
    }
    if (CUI.util.isPlainObject(response) && response.message && response.level) {
      if (addLog) {
        JSONImporterLogs.add(response);
      }
      CUI.alert({
        text: response.message
      });
      return;
    }
    if (!CUI.util.isString(response)) {
      response = $$("json.importer.modal.process.failure");
    }
    if (addLog) {
      JSONImporterLogs.add({
        level: JSONImporterLogs.LEVEL_ERROR,
        message: response
      });
    }
    CUI.alert({
      text: response
    });
  };

  JSONImporter.prototype.__buildModal = function() {
    this.__mainForm = new CUI.Form({
      padded: true,
      data: this.__data,
      maximize_vertical: true,
      fields: this.__getMainFormFields()
    });
    this.__mainForm.start();
    this.__toggleSkipHeadCheckbox();
    this.__changeSelectButtonStatus(false, false);
    this.__prepareButton = new LocaButton({
      loca_key: "json.importer.modal.footer.prepare.button",
      onClick: (function(_this) {
        return function() {
          _this.__disableStart();
          if (_this.__getProcessablePayloads().length === 0 || _this.__hasFinished()) {
            CUI.alert({
              text: $$("json.importer.modal.process.no-data")
            });
            return;
          }
          return _this.__preparePayloads().done(function() {
            return _this.__startButton.enable();
          }).fail(_this.__onFail).always(function() {
            _this.__mainForm.reload();
            return _this.__payloadsDataTable.loadPage(_this.__lastDataTablePage);
          }).always(function() {
            if (_this.__payloadDetailsButton.isActive()) {
              return _this.__initRightPaneValues();
            }
          });
        };
      })(this)
    });
    this.__buildRightPane();
    this.__startButton = new LocaButton({
      loca_key: "json.importer.modal.footer.import.button",
      disabled: true,
      onClick: (function(_this) {
        return function() {
          _this.__startButton.disable();
          CUI.setLocalStorage(JSONImporter.localStorageKey, _this.__data);
          JSONImporterReport.start();
          return _this.__startImport().done(function(isAbort, time) {
            var successMessage;
            if (!isAbort) {
              successMessage = $$("json.importer.modal.process.success", {
                time: time
              });
              JSONImporterLogs.add({
                level: JSONImporterLogs.LEVEL_INFO,
                message: successMessage,
                duration: time
              });
              return CUI.confirm({
                text: successMessage,
                button_text_ok: $$("json.importer.modal.footer.settings.logs.footer.save-csv|text"),
                button_text_cancel: $$("base.ok")
              }).done(function() {
                _this.__openReport();
                return JSONImporterLogs.download();
              });
            }
          }).fail(_this.__onFail).always(function() {
            _this.__mainForm.reload();
            return _this.__payloadsDataTable.loadPage(_this.__lastDataTablePage);
          });
        };
      })(this)
    });
    this.__payloadDetailsButton = new LocaButton({
      loca_key: "json.importer.modal.header.form.button",
      onClick: (function(_this) {
        return function() {
          _this.__payloadDetailsButton.setActive(!_this.__payloadDetailsButton.isActive());
          if (_this.__payloadDetailsButton.isActive()) {
            _this.__updateNavigation(0);
            return _this.__modal.setFillSpace("both");
          } else {
            _this.__hideRightPaneContent();
            return _this.__modal.setFillSpace("vertical");
          }
        };
      })(this)
    });
    this.__modalContent = new CUI.HorizontalLayout({
      center: {
        content: new CUI.SimplePane({
          content: this.__mainForm,
          header_left: new LocaLabel({
            loca_key: "json.importer.modal.header.form.label"
          }),
          header_right: this.__payloadDetailsButton
        })
      },
      right: {
        content: this.__mainPane,
        flexHandle: {
          closable: false,
          hidden: false,
          state_name: "json-importer-form-flex-handle"
        }
      }
    });
    this.__rightContentWaitBlock = new CUI.WaitBlock({
      element: this.__modalContent.right()
    });
    return new CUI.Modal({
      "class": "ez5-json-importer-modal",
      fill_space: "both",
      cancel: true,
      onCancel: (function(_this) {
        return function() {
          return _this.__showConfirmLosingChanges().done(function() {
            CUI.setLocalStorage(JSONImporter.localStorageKey, _this.__data);
            JSONImporterLogs.clear();
            return _this.destroy();
          });
        };
      })(this),
      pane: {
        header_left: new LocaLabel({
          loca_key: "json.importer.modal.header.label"
        }),
        content: this.__modalContent,
        footer_right: [this.__prepareButton, this.__startButton],
        footer_left: {
          loca_key: "json.importer.modal.footer.settings.button",
          menu: {
            items: [
              {
                loca_key: "json.importer.modal.footer.settings.logs.footer.save-csv",
                onClick: (function(_this) {
                  return function() {
                    return JSONImporterLogs.download();
                  };
                })(this)
              }, this.__getClearLogsButton(), this.__getOpenReportButton()
            ]
          }
        }
      }
    });
  };

  JSONImporter.prototype.__buildRightPane = function() {
    this.__navigationFileToolbar = new NavigationToolbar({
      onLoadPage: (function(_this) {
        return function(page) {
          return _this.__updateNavigation(page, true);
        };
      })(this)
    });
    this.__payloadPane = new CUI.SimplePane({
      "class": "cui-border",
      header_left: new CUI.Label({
        text: $$("json.importer.pane.payload.objects.header")
      }),
      footer_right: this.__navigationFileToolbar
    });
    this.__payloadDetails = CUI.dom.div();
    this.__mainPane = new CUI.SimplePane({
      padded: true,
      header_left: {
        content: void 0
      },
      content: new CUI.VerticalLayout({
        top: {
          content: this.__payloadDetails
        },
        center: {
          content: this.__payloadPane
        }
      })
    });
    return this.__mainPane;
  };

  JSONImporter.prototype.__updateNavigation = function(page, updateObjectOnly) {
    var currentPayloadObjects, emptyLabel, headerLabel, i, len, limit, objects, offset, row, rows, table;
    if (page == null) {
      page = this.__currentPage;
    }
    if (updateObjectOnly == null) {
      updateObjectOnly = false;
    }
    this.__modalContent.getFlexHandle("right").open().show();
    if (!this.__payloadSelected) {
      emptyLabel = new CUI.EmptyLabel({
        multiline: true,
        centered: true,
        text: $$("json.importer.pane.payload.empty-text")
      });
      this.__modalContent.replace(emptyLabel, "right");
      return;
    }
    objects = this.__payloadSelected.objects;
    if (!objects || objects.length === 0) {
      emptyLabel = new CUI.EmptyLabel({
        multiline: true,
        centered: true,
        text: $$("json.importer.pane.payload.no-objects")
      });
      this.__modalContent.replace(emptyLabel, "right");
      return;
    }
    this.__modalContent.replace(this.__mainPane, "right");
    limit = 1;
    offset = page * limit;
    currentPayloadObjects = objects.length;
    this.__navigationFileToolbar.update({
      count: currentPayloadObjects,
      offset: offset,
      limit: limit
    });
    this.__currentPage = page;
    this.__payloadPane.replace(new CUI.ObjectDumper({
      object: objects[offset],
      do_open: true
    }));
    if (updateObjectOnly) {
      return;
    }
    headerLabel = new LocaLabel({
      loca_key: "json.importer.pane.payload.header-title",
      loca_key_attrs: {
        payload: this.__payloadSelected.payload.url
      }
    });
    this.__mainPane.replace(headerLabel, "header_left");
    rows = [[$$("json.importer.modal.header.url.label"), this.__payloadSelected.payload.url], [$$("json.importer.modal.header.objecttype.label"), this.__payloadSelected.payload.objecttype], [$$("json.importer.modal.header.batch_count.label"), this.__payloadSelected.payload.batchCount], [$$("json.importer.modal.header.objects_count.label"), this.__payloadSelected.payload.objectsCount], [$$("json.importer.modal.header.eas_count.label"), this.__payloadSelected.payload.easCount]];
    table = CUI.dom.table();
    for (i = 0, len = rows.length; i < len; i++) {
      row = rows[i];
      CUI.dom.append(table, CUI.dom.tr_one_row(row));
    }
    CUI.dom.replace(this.__payloadDetails, table);
  };

  JSONImporter.prototype.__getMainFormFields = function() {
    var fields, manifestForm, onBatchSizeChanged;
    manifestForm = this.__buildManifestForm();
    this.__selectButton = this.__getSelectButton();
    onBatchSizeChanged = (function(_this) {
      return function(field, data) {
        if (data.batchSize === 1) {
          return field.enable();
        } else {
          data.skipUniqueConstraintErrors = false;
          return field.disable();
        }
      };
    })(this);
    fields = [
      manifestForm, {
        type: CUI.Input,
        form: {
          label: $$("json.importer.fields.source.label")
        },
        placeholder: $$("json.importer.fields.source.placeholder"),
        maximize_horizontal: true,
        name: "source"
      }, {
        type: CUI.Input,
        form: {
          label: $$("json.importer.fields.payload_base_uri.label")
        },
        placeholder: $$("json.importer.fields.payload_base_uri.placeholder"),
        maximize_horizontal: true,
        name: "payloadBaseUri",
        onDataChanged: (function(_this) {
          return function() {
            return _this.__disableStart();
          };
        })(this)
      }, {
        type: CUI.Select,
        form: {
          label: $$("json.importer.fields.batch_size.label")
        },
        maximize_horizontal: true,
        name: "batchSize",
        options: [
          {
            value: 1000
          }, {
            value: 500
          }, {
            value: 200
          }, {
            value: 100
          }, {
            value: 50
          }, {
            value: 10
          }, {
            value: 1
          }
        ],
        onDataChanged: (function(_this) {
          return function(data) {
            var field, i, len, payload, ref;
            field = _this.__mainForm.getFieldsByName("skipUniqueConstraintErrors")[0];
            onBatchSizeChanged(field, data);
            ref = _this.__data.payloads;
            for (i = 0, len = ref.length; i < len; i++) {
              payload = ref[i];
              payload.batchOffset = 1;
            }
            _this.__mainForm.reload();
            _this.__payloadsDataTable.loadPage(_this.__lastDataTablePage);
            _this.__disableStart();
          };
        })(this)
      }, {
        type: CUI.Select,
        maximize_horizontal: true,
        form: {
          label: $$("eas.importer.fields.eas_type.label.text"),
          hint: $$("eas.importer.fields.eas_type.label.hint.md")
        },
        name: "easType",
        options: EASImporter.getSelectOptions(),
        onDataChanged: (function(_this) {
          return function(data, field) {
            return _this.__toggleSkipHeadCheckbox(data);
          };
        })(this)
      }, {
        type: CUI.Checkbox,
        hidden: !ez5.version("6"),
        form: {
          label: $$("json.importer.fields.eas_skip_head_request.label")
        },
        name: "skipRPUTHeadRequest"
      }, ez5.metadata.getMappingField({
        exiftool_import: true
      }), {
        type: CUI.Checkbox,
        form: {
          label: $$("json.importer.fields.eas_skip_errors.label")
        },
        name: "easSkipErrors"
      }, {
        type: CUI.Checkbox,
        form: {
          label: $$("json.importer.fields.skip_unique_constraint_errors.label")
        },
        name: "skipUniqueConstraintErrors",
        onDataInit: (function(_this) {
          return function(field) {
            var data;
            data = field.getForm().getData();
            return onBatchSizeChanged(field, data);
          };
        })(this)
      }, {
        type: CUI.Input,
        form: {
          label: $$("json.importer.fields.eas_replace_url.label")
        },
        placeholder: $$("json.importer.fields.eas_replace_url.placeholder"),
        maximize_horizontal: true,
        name: "easReplaceUrl",
        regexp: "^https?://[^/]+?$",
        onDataChanged: (function(_this) {
          return function(_, input) {
            _this.__disableStart();
            if (input.getInputState() === "invalid") {
              return _this.__prepareButton.disable();
            } else {
              return _this.__prepareButton.enable();
            }
          };
        })(this)
      }, this.__payloadsDataTable = new CUI.DataTable({
        "class": "cui-border",
        render_as_block: true,
        name: "payloads",
        maximize: true,
        chunk_size: 20,
        footer_right: this.__selectButton,
        onLoadPage: (function(_this) {
          return function(page) {
            return _this.__lastDataTablePage = page;
          };
        })(this),
        onRowRemove: (function(_this) {
          return function() {
            return _this.__initRightPaneValues();
          };
        })(this),
        onRowDeselect: (function(_this) {
          return function() {
            return _this.__initRightPaneValues();
          };
        })(this),
        onRowSelect: (function(_this) {
          return function(_, info) {
            var payload;
            payload = info.row.getData();
            if (!payload) {
              return;
            }
            _this.__rightContentWaitBlock.show();
            _this.__modal.setFillSpace("both");
            _this.__payloadDetailsButton.setActive(true);
            return _this.__preparePayload(payload, true).done(function(data) {
              var payloadData;
              payloadData = data.payloadData;
              return _this.__payloadSelected = {
                objects: JSONPayload.getObjects(payloadData),
                payload: payload
              };
            }).fail(function(response) {
              _this.__payloadSelected = null;
              return _this.__onFail(response, false);
            }).always(function() {
              var ref;
              _this.__rightContentWaitBlock.hide();
              _this.__updateNavigation(0);
              if ((ref = _this.__payloadSelected) != null ? ref.payload : void 0) {
                delete _this.__payloadSelected.payload.objecttype;
                delete _this.__payloadSelected.payload.easCount;
                delete _this.__payloadSelected.payload.objectsCount;
                delete _this.__payloadSelected.payload.batchCount;
              }
            });
          };
        })(this),
        onDataChanged: (function(_this) {
          return function(_, field) {
            var atLeastOneDeselected, data;
            data = field.getData();
            atLeastOneDeselected = data.payloads.some(function(payload) {
              return !payload.process && !payload.success;
            });
            return _this.__changeSelectButtonStatus(!atLeastOneDeselected, false);
          };
        })(this),
        fields: [
          {
            type: CUI.DataFieldProxy,
            name: "status",
            form: {
              label: $$("json.importer.modal.header.status.label")
            },
            element: (function(_this) {
              return function(field) {
                var data, status;
                data = field.getData();
                if (!data.process) {
                  status = $$("json.importer.fields.payloads.status.disabled");
                } else {
                  status = field.getData().status || $$("json.importer.fields.payloads.status.pending");
                }
                return new CUI.Label({
                  text: status
                });
              };
            })(this)
          }, {
            type: CUI.Input,
            name: "url",
            form: {
              column: "maximize",
              label: $$("json.importer.modal.header.url.label")
            },
            onDataChanged: (function(_this) {
              return function() {
                return _this.__disableStart();
              };
            })(this),
            onDataInit: (function(_this) {
              return function(field) {
                var ref;
                if ((ref = field.getData()) != null ? ref.success : void 0) {
                  return field.disable();
                }
              };
            })(this)
          }, {
            type: CUI.NumberInput,
            name: "batchOffset",
            decimals: 0,
            form: {
              label: $$("json.importer.modal.header.batch_offset.label")
            },
            onDataInit: (function(_this) {
              return function(field) {
                var ref;
                if ((ref = field.getData()) != null ? ref.success : void 0) {
                  return field.disable();
                }
              };
            })(this)
          }, {
            type: CUI.Output,
            name: "batchCount",
            form: {
              label: $$("json.importer.modal.header.batch_count.label")
            }
          }, {
            type: CUI.Output,
            name: "objectsCount",
            form: {
              label: $$("json.importer.modal.header.objects_count.label")
            }
          }, {
            type: CUI.Output,
            name: "easCount",
            form: {
              label: $$("json.importer.modal.header.eas_count.label")
            }
          }, {
            type: CUI.Output,
            name: "objecttype",
            form: {
              label: $$("json.importer.modal.header.objecttype.label")
            }
          }, {
            type: CUI.DataFieldProxy,
            name: "actions",
            form: {
              label: $$("json.importer.modal.header.actions.label")
            },
            element: (function(_this) {
              return function(field) {
                return (new LocaButton({
                  loca_key: "json.importer.fields.actions.open-url.button",
                  onClick: function() {
                    var url;
                    url = _this.__data.payloadBaseUri + field.getData().url;
                    return window.open(url, '_blank');
                  }
                })).DOM;
              };
            })(this)
          }, {
            type: CUI.Checkbox,
            name: "process",
            group: "process_cb",
            form: {
              label: $$("json.importer.modal.header.enabled.label")
            },
            onDataInit: (function(_this) {
              return function(field) {
                var ref;
                if ((ref = field.getData()) != null ? ref.success : void 0) {
                  return field.disable();
                }
              };
            })(this),
            onDataChanged: (function(_this) {
              return function() {
                return _this.__disableStart();
              };
            })(this)
          }
        ]
      })
    ];
    return fields;
  };

  JSONImporter.prototype.__toggleSkipHeadCheckbox = function(data) {
    var field, ref, ref1;
    if (data == null) {
      data = this.__data;
    }
    if (!ez5.version("6")) {
      return;
    }
    field = (ref = this.__mainForm) != null ? (ref1 = ref.getFieldsByName("skipRPUTHeadRequest")) != null ? ref1[0] : void 0 : void 0;
    if (!field) {
      return;
    }
    if (data.easType === EASImporter.EAS_TYPE.URL) {
      field.show(true);
    } else {
      field.hide(true);
    }
  };

  JSONImporter.prototype.__fillMainFormWithManifestData = function(data, url) {
    delete this.__lastDataTablePage;
    this.__data.source = data.source;
    this.__data.batchSize = data.batch_size;
    this.__data.easType = data.eas_type;
    if (ez5.version("6") && !CUI.util.isNull(data.skip_head_request)) {
      this.__data.skipRPUTHeadRequest = data.skip_head_request;
    }
    this.__data.mapping = data.mapping;
    this.__data.easReplaceUrl = data.eas_replace_url;
    this.__data.easSkipErrors = CUI.util.isUndef(data.eas_skip_errors) ? true : data.eas_skip_errors;
    this.__data.payloads = data.payloads.map((function(_this) {
      return function(payload) {
        return {
          url: "" + payload,
          status: payload.status || $$("json.importer.fields.payloads.status.pending"),
          process: true,
          batchOffset: 1
        };
      };
    })(this));
    if (CUI.util.isEmpty(data.payload_base_uri)) {
      this.__data.payloadBaseUri = url.substring(0, url.lastIndexOf("/")) + "/";
    } else {
      this.__data.payloadBaseUri = data.payload_base_uri;
    }
    this.__initRightPaneValues();
    this.__changeSelectButtonStatus(true);
    this.__disableStart();
    this.__toggleSkipHeadCheckbox();
  };

  JSONImporter.prototype.__getManifest = function(url) {
    var deferred;
    deferred = new CUI.Deferred();
    JSONImporterUtils.getFile(url).done((function(_this) {
      return function(response) {
        if (response && CUI.util.isArray(response.payloads)) {
          return deferred.resolve(response);
        } else {
          return deferred.reject();
        }
      };
    })(this)).fail(deferred.reject);
    return deferred.promise();
  };

  JSONImporter.prototype.__buildManifestForm = function() {
    var form, getManifestPromise, historySuggestionMenu;
    getManifestPromise = (function(_this) {
      return function() {
        var urlInput;
        urlInput = form.getFieldsByName("url")[0];
        return _this.__getManifest(_this.__data.url).done(function() {
          return urlInput.checkInput(true);
        }).fail(function() {
          return urlInput.checkInput(false);
        });
      };
    })(this);
    historySuggestionMenu = null;
    form = new CUI.Form({
      horizontal: true,
      form: {
        label: $$("json.importer.settings.manifest.modal.label")
      },
      fields: [
        {
          form: {
            maximize_horizontal: true
          },
          type: CUI.Input,
          placeholder: $$("json.importer.settings.manifest.modal.field.url.placeholder"),
          name: "url",
          maximize_horizontal: true,
          onDataChanged: (function(_this) {
            return function() {
              return CUI.scheduleCallback({
                ms: 200,
                call: getManifestPromise
              });
            };
          })(this),
          onInit: (function(_this) {
            return function(input) {
              var i, items, len, ref, url;
              items = [];
              ref = _this.__getHistoryUrls();
              for (i = 0, len = ref.length; i < len; i++) {
                url = ref[i];
                items.push({
                  text: url,
                  value: url
                });
              }
              return historySuggestionMenu = new CUI.Menu({
                element: input.DOM,
                use_element_width_as_min_width: true,
                itemList: {
                  items: items,
                  onClick: function(_, __, item) {
                    historySuggestionMenu.hide();
                    input.setValue(item.value);
                    return getManifestPromise();
                  }
                }
              });
            };
          })(this),
          checkInput: (function(_this) {
            return function(isValidManifest) {
              return isValidManifest;
            };
          })(this),
          onFocus: (function(_this) {
            return function() {
              if (historySuggestionMenu.hasItems()) {
                return historySuggestionMenu.show();
              }
            };
          })(this),
          onBlur: (function(_this) {
            return function() {
              return historySuggestionMenu.hide();
            };
          })(this)
        }, {
          type: CUI.DataFieldProxy,
          element: (function(_this) {
            return function() {
              return (new LocaButton({
                loca_key: "json.importer.settings.manifest.modal.load.button",
                disabled: false,
                onClick: function() {
                  return getManifestPromise().done(function(responseData) {
                    return _this.__showConfirmLosingChanges().done(function() {
                      JSONImporterLogs.clear();
                      JSONImporterReport.clear();
                      return _this.__onManifestLoaded(responseData, _this.__data.url);
                    });
                  });
                }
              })).DOM;
            };
          })(this)
        }
      ]
    });
    return form;
  };

  JSONImporter.prototype.__onManifestLoaded = function(responseData, url) {
    JSONImporterLogs.add({
      level: JSONImporterLogs.LEVEL_INFO,
      message: $$("json.importer.settings.manifest.load-success"),
      url: url
    });
    this.__fillMainFormWithManifestData(responseData, url);
    return this.__addUrlToHistory(url);
  };

  JSONImporter.prototype.__addUrlToHistory = function(url) {
    var urls;
    urls = this.__getHistoryUrls();
    if (indexOf.call(urls, url) < 0) {
      urls.push(url);
      ez5.session.savePref(JSONImporter.preferenceHistoryKey, urls);
    }
  };

  JSONImporter.prototype.__getHistoryUrls = function() {
    return ez5.session.getPref(JSONImporter.preferenceHistoryKey) || [];
  };

  JSONImporter.prototype.__hasFinished = function() {
    return this.__data.payloads.every((function(_this) {
      return function(payload) {
        return payload.success;
      };
    })(this));
  };

  JSONImporter.prototype.__getProcessablePayloads = function() {
    return this.__data.payloads.filter((function(_this) {
      return function(payload) {
        return payload.process && !payload.success;
      };
    })(this));
  };

  JSONImporter.prototype.__showConfirmLosingChanges = function() {
    if (this.__hasFinished()) {
      return CUI.resolvedPromise();
    }
    if (!CUI.util.isEmpty(this.__data.source) || !CUI.util.isEmpty(this.__data.payloadBaseUri) || this.__data.payloads.length > 0) {
      return CUI.confirm({
        text: $$("json.importer.modal.confirmation-losing-changes")
      });
    } else {
      return CUI.resolvedPromise();
    }
  };

  JSONImporter.prototype.__getClearLogsButton = function(rows, onClose) {
    return new LocaButton({
      loca_key: "json.importer.modal.footer.settings.logs.footer.clear-logs",
      disabled: (rows != null ? rows.length : void 0) === 0,
      onClick: function() {
        var confirmationDialog;
        confirmationDialog = new CUI.ConfirmationDialog({
          title: $$("json.importer.modal.footer.settings.logs.footer.clear-logs.confirmation.title"),
          content: new LocaLabel({
            loca_key: "json.importer.modal.footer.settings.logs.footer.clear-logs.confirmation"
          }),
          buttons: [
            {
              text: $$("base.cancel"),
              onClick: (function(_this) {
                return function() {
                  return confirmationDialog.destroy();
                };
              })(this)
            }, {
              text: $$("base.ok"),
              onClick: (function(_this) {
                return function() {
                  JSONImporterLogs.clear();
                  confirmationDialog.destroy();
                  return typeof onClose === "function" ? onClose() : void 0;
                };
              })(this)
            }
          ]
        });
        return confirmationDialog.show();
      }
    });
  };

  JSONImporter.prototype.__getOpenReportButton = function() {
    return {
      loca_key: "json.importer.modal.footer.settings.logs.footer.open-report",
      onClick: (function(_this) {
        return function() {
          return _this.__openReport();
        };
      })(this)
    };
  };

  JSONImporter.prototype.__openReport = function() {
    var report, reportDialog;
    report = JSONImporterReport.get();
    if (CUI.util.isNull(report)) {
      CUI.alert({
        text: $$("json.importer.error.message.report.no-report-available")
      });
      return;
    }
    reportDialog = new CUI.ConfirmationDialog({
      title: $$("json.importer.modal.footer.settings.logs.footer.open-report.title"),
      content: report,
      buttons: [
        {
          text: $$("base.ok"),
          onClick: (function(_this) {
            return function() {
              return reportDialog.destroy();
            };
          })(this)
        }
      ]
    });
    reportDialog.show();
  };

  JSONImporter.prototype.__getSelectButton = function() {
    var button;
    button = new CUI.Button({
      text: "",
      onClick: (function(_this) {
        return function() {
          _this.__changeSelectButtonStatus(!button.isActive());
          return _this.__disableStart();
        };
      })(this)
    });
    return button;
  };

  JSONImporter.prototype.__changeSelectButtonStatus = function(selectAll, triggerSelect) {
    var buttonDeselectAllText, buttonSelectAllText;
    if (triggerSelect == null) {
      triggerSelect = true;
    }
    if (!this.__selectButton) {
      return;
    }
    buttonSelectAllText = $$("json.importer.buttons.select-all");
    buttonDeselectAllText = $$("json.importer.buttons.deselect-all");
    if (selectAll) {
      this.__selectButton.setText(buttonDeselectAllText);
    } else {
      this.__selectButton.setText(buttonSelectAllText);
    }
    this.__selectButton.setActive(selectAll);
    if (triggerSelect) {
      return this.__toggleSelectAll(selectAll);
    }
  };

  JSONImporter.prototype.__toggleSelectAll = function(select) {
    var i, len, payload, ref;
    if (select == null) {
      select = true;
    }
    ref = this.__data.payloads;
    for (i = 0, len = ref.length; i < len; i++) {
      payload = ref[i];
      if (payload.success) {
        continue;
      }
      payload.process = select;
    }
    this.__mainForm.reload();
    this.__payloadsDataTable.loadPage(this.__lastDataTablePage);
  };

  JSONImporter.prototype.__hideRightPaneContent = function() {
    this.__modalContent.getFlexHandle("right").close().hide();
  };

  JSONImporter.prototype.__disableStart = function() {
    this.__setPendingAllProcessablePayloads();
    this.__startButton.disable();
  };

  JSONImporter.prototype.__setPendingAllProcessablePayloads = function() {
    var payloads;
    if (!this.__data) {
      return;
    }
    payloads = this.__getProcessablePayloads();
    return payloads.forEach((function(_this) {
      return function(payload) {
        return payload.status = $$("json.importer.fields.payloads.status.pending");
      };
    })(this));
  };

  JSONImporter.prototype.show = function() {
    this.__hideRightPaneContent();
    this.__modal.show();
  };

  return JSONImporter;

})(CUI.Element);

CUI.ready((function(_this) {
  return function() {
    CUI.Events.registerEvent({
      type: "json-importer-abort-upload",
      bubble: true
    });
    return CUI.Events.registerEvent({
      type: "json-importer-update-progress"
    });
  };
})(this));
// Generated by CoffeeScript 1.12.7
var JSONImporterMenuApp,
  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;

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

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

  JSONImporterMenuApp.click = function() {
    ez5.rootMenu.closeMenu();
    if (ez5.session.isReadOnly()) {
      CUI.alert({
        text: $$("base.error.user.read_only_mode")
      });
      return;
    }
    return (new JSONImporter()).show();
  };

  JSONImporterMenuApp.label = function() {
    return "main.list.extra.json_import|text";
  };

  JSONImporterMenuApp.is_allowed = function() {
    return ez5.session.hasSystemRight("root", "frontend_features[json_importer]");
  };

  JSONImporterMenuApp.group = function() {
    return "za_importer";
  };

  JSONImporterMenuApp.submenu = function() {
    return "plugins";
  };

  JSONImporterMenuApp.isStartApp = function() {
    return false;
  };

  return JSONImporterMenuApp;

})(RootMenuApp);

ez5.session_ready(function() {
  return ez5.rootMenu.registerApp(JSONImporterMenuApp);
});
// Generated by CoffeeScript 1.12.7
var EASImporter,
  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;

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

  function EASImporter() {
    this.mergeMetadata = bind(this.mergeMetadata, this);
    this.__showPreviewImage = bind(this.__showPreviewImage, this);
    return EASImporter.__super__.constructor.apply(this, arguments);
  }

  EASImporter.uploadChunkSize = 5;

  EASImporter.prefix = "eas:";

  EASImporter.previewImageUrlKey = EASImporter.prefix + "preview:url";

  EASImporter.imageUrlKey = EASImporter.prefix + "url";

  EASImporter.imageFilenameKey = EASImporter.prefix + "filename";

  EASImporter.previewContainerClass = "ez5-json-importer-preview-images";

  EASImporter.EAS_TYPE = {
    DIRECT: "direct",
    URL: "url",
    IGNORE: "ignore"
  };

  EASImporter.prototype.initOpts = function() {
    EASImporter.__super__.initOpts.call(this);
    return this.addOpts({
      objects: {
        check: Array,
        mandatory: true
      },
      objectType: {
        check: String,
        mandatory: true
      },
      settings: {
        check: "PlainObject",
        easType: {
          check: String
        },
        easReplaceUrl: {
          check: String,
          mandatory: false
        },
        mapping: {
          check: String
        },
        skipRPUTHeadRequest: {
          check: Boolean
        }
      }
    });
  };

  EASImporter.prototype.getTotalCount = function() {
    return this.__getAllEASFields().length;
  };

  EASImporter.prototype.__getAllEASFields = function() {
    var easField, easFields, i, j, len, len1, object, ref;
    easFields = [];
    ref = this._objects;
    for (i = 0, len = ref.length; i < len; i++) {
      object = ref[i];
      easFields = easFields.concat(this.__seekForEASFields(object));
    }
    if (this._settings.easType === EASImporter.EAS_TYPE.IGNORE) {
      for (j = 0, len1 = easFields.length; j < len1; j++) {
        easField = easFields[j];
        this.__cleanEASField(easField);
      }
      return [];
    }
    return easFields;
  };

  EASImporter.prototype.upload = function() {
    var abortListener, abortNextChunk, deferred, easFields;
    easFields = this.__getAllEASFields();
    if (easFields.length === 0) {
      return CUI.resolvedPromise();
    }
    deferred = new CUI.Deferred();
    abortNextChunk = false;
    this.__previewContainer = CUI.dom.find("." + EASImporter.previewContainerClass)[0];
    abortListener = CUI.Events.listen({
      type: "json-importer-abort-upload",
      call: (function(_this) {
        return function() {
          return abortNextChunk = true;
        };
      })(this)
    });
    CUI.chunkWork.call(this, {
      items: easFields,
      chunk_size: EASImporter.uploadChunkSize,
      call: ((function(_this) {
        return function(fields) {
          var easField, i, len, processEASField, promises;
          if (abortNextChunk) {
            return CUI.rejectedPromise({
              level: JSONImporterLogs.LEVEL_INFO,
              message: $$("json.importer.error.message.eas.abort")
            });
          }
          promises = [];
          for (i = 0, len = fields.length; i < len; i++) {
            easField = fields[i];
            processEASField = _this.__processEASField(easField).done(function() {
              return JSONImporterUtils.updateEASProgress(1);
            });
            promises.push(processEASField);
          }
          return CUI.when(promises);
        };
      })(this))
    }).done((function(_this) {
      return function() {
        var easField, i, len;
        if (_this._settings.easSkipErrors) {
          for (i = 0, len = easFields.length; i < len; i++) {
            easField = easFields[i];
            if (!easField.object._id && easField.objectParent) {
              _this.__cleanEASField(easField);
            }
          }
        }
        return deferred.resolve(easFields.length);
      };
    })(this)).fail((function(_this) {
      return function(message, statusText, timeTook) {
        return deferred.reject(message || $$("json.importer.error.message.eas.generic"), statusText, timeTook);
      };
    })(this)).always((function(_this) {
      return function() {
        abortListener.destroy();
        if (_this.__previewContainer) {
          return CUI.setTimeout(function() {
            return CUI.dom.removeClass(_this.__previewContainer, "animation-open");
          }, 5000);
        }
      };
    })(this));
    return deferred.promise();
  };

  EASImporter.prototype.__seekForEASFields = function(rootObject) {
    var data, easFields, handleValue, iterateArray, iterateObject;
    data = rootObject[this._objectType];
    easFields = [];
    handleValue = (function(_this) {
      return function(value, objectParent) {
        if (CUI.util.isPlainObject(value)) {
          iterateObject(value, objectParent);
        }
        if (CUI.util.isArray(value)) {
          return iterateArray(value);
        }
      };
    })(this);
    iterateObject = (function(_this) {
      return function(object, objectParent) {
        var easField, key, results, value;
        results = [];
        for (key in object) {
          value = object[key];
          if (typeof key.startsWith === "function" ? key.startsWith(EASImporter.imageUrlKey) : void 0) {
            easField = {
              key: key,
              object: object,
              _id: data._id,
              _objectType: _this._objectType,
              rootObject: rootObject
            };
            if (_this._settings.easSkipErrors) {
              easField.objectParent = objectParent;
            }
            easFields.push(easField);
          }
          results.push(handleValue(value, object));
        }
        return results;
      };
    })(this);
    iterateArray = (function(_this) {
      return function(array) {
        var i, len, results, value;
        results = [];
        for (i = 0, len = array.length; i < len; i++) {
          value = array[i];
          results.push(handleValue(value, array));
        }
        return results;
      };
    })(this);
    iterateObject(data);
    return easFields;
  };

  EASImporter.prototype.__replaceUrl = function(url, easReplaceUrl) {
    var cuiLocation;
    cuiLocation = CUI.parseLocation(url);
    if (CUI.util.isNull(cuiLocation)) {
      return null;
    }
    if (!CUI.util.isEmpty(easReplaceUrl) && /^https?:\/\/[^\/]+?$/.test(easReplaceUrl)) {
      url = easReplaceUrl + cuiLocation.path;
      return url;
    }
    return cuiLocation.href;
  };

  EASImporter.prototype.__getFilename = function(url, filename) {
    if (!filename) {
      filename = url.substring(url.lastIndexOf("/") + 1);
      filename = decodeURI(filename);
    }
    return filename;
  };

  EASImporter.prototype.downloadAndUpload = function(_url, easType, filename, easReplaceUrl) {
    var deferred, downloadPromise, downloadStartTime, specifiedFilename, url, xhrDownload;
    deferred = new CUI.Deferred();
    specifiedFilename = filename;
    url = this.__replaceUrl(_url, easReplaceUrl);
    if (CUI.util.isNull(url)) {
      return CUI.rejectedPromise($$("json.importer.error.message.eas.url-not-valid", {
        url: _url
      }));
    }
    if (easType === EASImporter.EAS_TYPE.URL) {
      downloadPromise = CUI.resolvedPromise();
    } else {
      xhrDownload = new CUI.XHR({
        method: "GET",
        url: url,
        responseType: "blob"
      });
      downloadStartTime = new Date().getTime();
      downloadPromise = xhrDownload.start();
    }
    downloadPromise.done((function(_this) {
      return function(blob) {
        var checkValidFileName, contentDisposition, formData, parameters, ref, uploadStartTime, xhrUpload, xhrUploadPromise;
        filename = _this.__getFilename(url, filename);
        if (easType === EASImporter.EAS_TYPE.URL) {
          parameters = {
            url: url,
            filename: filename,
            token: ez5.session.token
          };
          if (ez5.version("6")) {
            if (!specifiedFilename) {
              delete parameters.filename;
            }
          }
          if ((ref = _this._settings) != null ? ref.skipRPUTHeadRequest : void 0) {
            parameters.skip_head_request = 1;
            parameters.filename = filename;
          }
          xhrUploadPromise = ez5.api.eas({
            type: "POST",
            api: "/rput?" + (CUI.encodeUrlData(parameters)),
            handle_error: function() {
              return true;
            }
          });
        } else {
          checkValidFileName = function(filename) {
            var filenameRegex;
            filenameRegex = /^.+\.[a-zA-Z0-9]+$/;
            return filenameRegex.test(filename);
          };
          if (!checkValidFileName(filename)) {
            contentDisposition = xhrDownload.getResponseHeader("Content-Disposition");
            if (contentDisposition) {
              filename = contentDisposition.match(/filename="(.+)"/)[1];
            }
          }
          if (!checkValidFileName(filename)) {
            deferred.reject($$("json.importer.error.message.eas.filename-not-valid"));
          }
          formData = new FormData();
          formData.append("files[]", blob, filename);
          xhrUpload = new CUI.XHR({
            method: "POST",
            url: ez5.eas.getUploadUrl(),
            body: formData
          });
          xhrUploadPromise = xhrUpload.start();
        }
        uploadStartTime = new Date().getTime();
        return xhrUploadPromise.done(function(data) {
          var idEAS;
          idEAS = data != null ? data[0]._id : void 0;
          if (idEAS) {
            return deferred.resolve(idEAS, data[0]);
          } else {
            return deferred.reject($$("json.importer.error.message.eas.url", {
              url: url
            }));
          }
        }).fail(function(response) {
          var message, statusText, uploadMs;
          uploadMs = (new Date().getTime()) - uploadStartTime;
          statusText = xhrUpload != null ? xhrUpload.statusText() : void 0;
          message = JSONImporterUtils.getErrorMessageFromResponse(response, statusText);
          if (!message) {
            message = $$("json.importer.error.message.upload-generic", {
              filename: filename
            });
          }
          return deferred.reject(message, statusText, uploadMs);
        });
      };
    })(this)).fail((function(_this) {
      return function() {
        var downloadMs, message, statusText;
        downloadMs = (new Date().getTime()) - downloadStartTime;
        statusText = xhrDownload.statusText();
        message = $$("json.importer.error.message.download-file-not-found");
        return deferred.reject(message, statusText, downloadMs);
      };
    })(this));
    return deferred.promise();
  };

  EASImporter.prototype.__processEASField = function(easField) {
    var chunkStartTime, deferred, downloadAndUploadPromise, easReplaceUrl, easType, filename, key, object, rootObject, type, url;
    key = easField.key;
    object = easField.object;
    rootObject = easField.rootObject;
    easType = this._settings.easType;
    easReplaceUrl = this._settings.easReplaceUrl;
    type = key != null ? key.split(EASImporter.prefix)[1] : void 0;
    if (type === 'url') {
      url = object[key];
      filename = object[EASImporter.imageFilenameKey];
      deferred = new CUI.Deferred();
      chunkStartTime = performance.now();
      downloadAndUploadPromise = this.downloadAndUpload(url, easType, filename, easReplaceUrl);
      downloadAndUploadPromise.done((function(_this) {
        return function(idEAS, easExtraData) {
          var replacedUrl;
          if (easExtraData == null) {
            easExtraData = {};
          }
          replacedUrl = _this.__replaceUrl(url, easReplaceUrl);
          if (idEAS) {
            object._id = idEAS;
            JSONImporterReport.addEAS(replacedUrl);
            JSONImporterLogs.add({
              level: JSONImporterLogs.LEVEL_INFO,
              operation: JSONImporterLogs.OPERATION_INSERT,
              duration: performance.now() - chunkStartTime,
              objectId: idEAS,
              objectType: easField._objectType,
              baseType: "asset",
              url: replacedUrl,
              message: $$("json.importer.modal.payload.process.file-upload"),
              easFilename: _this.__getFilename(replacedUrl, filename),
              easClass: easExtraData["class"],
              easFilesize: easExtraData.filesize,
              easExtension: easExtraData.extension
            });
          }
          if (CUI.util.isNull(_this._settings.mapping)) {
            return deferred.resolve(idEAS);
          }
          return _this.mergeMetadata(idEAS, rootObject, _this._objectType, _this._settings.mapping).done(function() {
            EAS.cleanMappedMetadata(rootObject);
            return deferred.resolve(idEAS);
          });
        };
      })(this)).fail((function(_this) {
        return function(message) {
          var replacedUrl;
          replacedUrl = _this.__replaceUrl(url, easReplaceUrl);
          JSONImporterReport.addEAS(replacedUrl, false);
          if (_this._settings.easSkipErrors) {
            JSONImporterLogs.add({
              level: JSONImporterLogs.LEVEL_WARN,
              duration: performance.now() - chunkStartTime,
              objectId: easField._id,
              baseType: "asset",
              url: replacedUrl,
              message: message
            });
            return deferred.resolve(null);
          } else {
            return deferred.reject(message);
          }
        };
      })(this));
      return deferred.promise();
    } else {
      return CUI.rejectedPromise($$("json.importer.error.message.eas.field-key-not-valid", {
        key: key
      }));
    }
  };

  EASImporter.prototype.__cleanEASField = function(easField) {
    var key, ref, results, value;
    if (CUI.util.isArray(easField.objectParent)) {
      return CUI.util.removeFromArray(easField.object, easField.objectParent);
    } else {
      ref = easField.objectParent;
      results = [];
      for (key in ref) {
        value = ref[key];
        if (value === easField.object) {
          delete easField.objectParent[key];
          break;
        } else {
          results.push(void 0);
        }
      }
      return results;
    }
  };

  EASImporter.prototype.__showPreviewImage = function(urlPreview) {
    var previewImage;
    previewImage = new Image();
    previewImage.src = urlPreview;
    return previewImage.onload = (function(_this) {
      return function() {
        if (!_this.__previewContainer) {
          return;
        }
        if (!CUI.dom.hasClass(_this.__previewContainer, "animation-open")) {
          CUI.dom.addClass(_this.__previewContainer, "animation-open");
        }
        CUI.dom.prepend(_this.__previewContainer, previewImage);
        return CUI.setTimeout(function() {
          CUI.dom.addClass(previewImage, "animation-right");
          return CUI.setTimeout(function() {
            return CUI.dom.remove(previewImage);
          }, 4000);
        }, 100);
      };
    })(this);
  };

  EASImporter.prototype.__askForLinkedPools = function(data, preMergedData, mainObjecttype) {
    var askObjecttypes, confirmButton, dfr, field, fn, getPoolFields, getPoolSelectionContent, mod, ot, poolFormData, toggleConfirmButton, value;
    if (window.headless_mode) {
      return CUI.resolvedPromise();
    }
    dfr = new CUI.Deferred();
    poolFormData = {};
    askObjecttypes = [];
    if (this.__poolSelectedByUserPerObjecttype == null) {
      this.__poolSelectedByUserPerObjecttype = {};
    }
    confirmButton = new LocaButton({
      loca_key: "json.importer.linked_object_pool_modal.save",
      primary: true,
      disabled: true,
      onClick: (function(_this) {
        return function() {
          var i, len, obj, ref;
          for (i = 0, len = askObjecttypes.length; i < len; i++) {
            obj = askObjecttypes[i];
            if ((ref = poolFormData[obj]) != null ? ref.pool : void 0) {
              _this.__poolSelectedByUserPerObjecttype[obj] = poolFormData[obj].pool._id;
            }
          }
          mod.destroy();
          dfr.resolve();
        };
      })(this)
    });
    toggleConfirmButton = (function(_this) {
      return function() {
        var i, len, obj;
        confirmButton.enable();
        for (i = 0, len = askObjecttypes.length; i < len; i++) {
          obj = askObjecttypes[i];
          if (CUI.util.isEmpty(poolFormData[obj])) {
            confirmButton.disable();
            break;
          }
        }
      };
    })(this);
    getPoolFields = (function(_this) {
      return function(objecttypes) {
        var fn, i, len, obj, poolsSelectors;
        poolsSelectors = [];
        fn = function(obj) {
          var poolSelector;
          poolSelector = {
            type: CUI.DataFieldProxy,
            maximize_horizontal: true,
            form: {
              label: obj
            },
            name: obj,
            element: function() {
              var dbInfo, element;
              dbInfo = new DbInfo();
              dbInfo.load({
                table: new Table("CURRENT", ez5.schema.CURRENT._table_by_name[obj].table_id),
                ignore_not_found: true
              }).fail(function() {
                console.error("EASImporter :: getPoolFields | Error loading dbInfo for objecttype: ", obj, " when creating pool selector.");
                return dfr.resolve();
              }).done(function() {
                var _linkedPoolSelector, opts, parentElement, poolField, pool_ids;
                pool_ids = dbInfo.getPoolIds() || [];
                poolField = new PoolFieldForEditor({
                  name: obj
                });
                opts = {
                  pool_ids: pool_ids
                };
                _linkedPoolSelector = poolField.renderEditorInput(poolFormData, null, opts);
                _linkedPoolSelector.start();
                parentElement = CUI.dom.parent(element);
                if (!parentElement) {
                  return;
                }
                return CUI.dom.replace(parentElement, _linkedPoolSelector);
              });
              element = new LocaLabel({
                loca_key: "main.editor.modal.new.form.pool.loading.label"
              });
              return element;
            }
          };
          return poolsSelectors.push(poolSelector);
        };
        for (i = 0, len = objecttypes.length; i < len; i++) {
          obj = objecttypes[i];
          fn(obj);
        }
        return poolsSelectors;
      };
    })(this);
    getPoolSelectionContent = (function(_this) {
      return function(objecttypes) {
        var descriptionLabel, form;
        form = new CUI.Form({
          name: "pool_selection",
          fields: getPoolFields(objecttypes),
          data: poolFormData,
          onDataChanged: function() {
            return toggleConfirmButton();
          }
        });
        descriptionLabel = new CUI.Label({
          text: $$("json.importer.linked_object_pool_modal.description")
        });
        return new CUI.VerticalList({
          content: [descriptionLabel, form.start()]
        });
      };
    })(this);
    ot = new Objecttype(ez5.schema.CURRENT._objecttype_by_name[mainObjecttype]);
    fn = (function(_this) {
      return function(field, value) {
        var i, idx, len, linkedObjecttype, nestedField, nestedFields, nf, poolId, ref, ref1, ref2, ref3, results, val;
        if (CUI.util.isPlainObject(value) && !CUI.util.isEmpty(value._objecttype)) {
          if (CUI.util.isEmpty(value._id) && !CUI.util.isEmpty(value._mapped_metadata_created)) {
            linkedObjecttype = value._objecttype;
            if (ez5.schema.CURRENT._objecttype_by_name[linkedObjecttype].pool_link) {
              poolId = ((ref = preMergedData[field]) != null ? (ref1 = ref[linkedObjecttype]) != null ? (ref2 = ref1._pool) != null ? (ref3 = ref2.pool) != null ? ref3._id : void 0 : void 0 : void 0 : void 0) || null;
              if (!poolId) {
                if (!askObjecttypes.includes(linkedObjecttype)) {
                  if (!_this.__poolSelectedByUserPerObjecttype[linkedObjecttype]) {
                    return askObjecttypes.push(linkedObjecttype);
                  }
                }
              }
            }
          }
        } else if (CUI.util.isArray(value)) {
          ot.addAllMasks();
          nestedField = ot.getFields("editor", true, function(f) {
            return f instanceof NestedTable && f.name() === field;
          });
          if (nestedField && nestedField.length > 0) {
            nestedFields = nestedField[0].getFields("editor");
            results = [];
            for (i = 0, len = nestedFields.length; i < len; i++) {
              nf = nestedFields[i];
              if (nf instanceof LinkedObject) {
                linkedObjecttype = nf.linkMask().table.name();
                results.push((function() {
                  var j, len1, results1;
                  results1 = [];
                  for (idx = j = 0, len1 = value.length; j < len1; idx = ++j) {
                    val = value[idx];
                    if (!CUI.util.isEmpty(val[nf.name()]) && val[nf.name()]._mapped_metadata_created) {
                      if (ez5.schema.CURRENT._objecttype_by_name[linkedObjecttype].pool_link) {
                        if (!askObjecttypes.includes(linkedObjecttype)) {
                          if (!this.__poolSelectedByUserPerObjecttype[linkedObjecttype]) {
                            results1.push(askObjecttypes.push(linkedObjecttype));
                          } else {
                            results1.push(void 0);
                          }
                        } else {
                          results1.push(void 0);
                        }
                      } else {
                        results1.push(void 0);
                      }
                    } else {
                      results1.push(void 0);
                    }
                  }
                  return results1;
                }).call(_this));
              } else {
                results.push(void 0);
              }
            }
            return results;
          }
        }
      };
    })(this);
    for (field in data) {
      value = data[field];
      fn(field, value);
    }
    if (askObjecttypes.length === 0) {
      return dfr.resolve();
    }
    mod = new CUI.ConfirmationDialog({
      title: $$("json.importer.linked_object_pool_modal.title"),
      content: getPoolSelectionContent(askObjecttypes),
      buttons: (function(_this) {
        return function() {
          return [confirmButton];
        };
      })(this)
    });
    mod.show();
    return dfr.promise();
  };

  EASImporter.prototype.mergeMetadata = function(easId, object, objecttype, mapping, pool_id, poll) {
    var data, deferred, preMergedData;
    if (poll == null) {
      poll = false;
    }
    if (!object._mask) {
      console.error("EASImporter :: mergeMetadata | 'object._mask' can not be null. Object: ", object);
      return CUI.resolvedPromise();
    }
    data = object[objecttype] || {};
    preMergedData = CUI.util.copyObject(data, true);
    deferred = new CUI.Deferred();
    EAS.mapMetadata({
      data: data,
      eas_id: easId,
      mask_name: object._mask,
      objecttype: objecttype,
      mapping: mapping,
      pool_id: pool_id,
      poll: poll
    }).done((function(_this) {
      return function() {
        var create_linked_objects_promises;
        EAS.replaceMappedMetadata(data);
        create_linked_objects_promises = [];
        return _this.__askForLinkedPools(data, preMergedData, objecttype).done(function() {
          var field, fn, value;
          fn = function(field, value) {
            var _dfr, fn1, i, idx, j, len, len1, linkedObject, linkedObjecttype, linked_data, nestedField, nestedFields, nf, ot, poolId, ref, ref1, ref2, ref3, ref4, val;
            if (CUI.util.isArray(value)) {
              ot = new Objecttype(ez5.schema.CURRENT._objecttype_by_name[objecttype]);
              if (!ot) {
                return;
              }
              ot.addAllMasks();
              nestedField = ot.getFields("editor", true, function(f) {
                return f instanceof NestedTable && f.name() === field;
              });
              if (!nestedField || nestedField.length === 0) {
                return;
              }
              nestedFields = nestedField[0].getFields("editor");
              for (i = 0, len = nestedFields.length; i < len; i++) {
                nf = nestedFields[i];
                if (nf instanceof LinkedObject) {
                  fn1 = function(val, idx) {
                    var _dfr, linkedData, linkedObjecttype, poolId;
                    if (!CUI.util.isEmpty(val[nf.name()]) && val[nf.name()]._mapped_metadata_created) {
                      linkedObjecttype = nf.linkMask().table.name();
                      linkedData = val[nf.name()];
                      linkedData[linkedObjecttype]._id = null;
                      linkedData[linkedObjecttype]._version = 1;
                      delete linkedData._mapped_metadata_created;
                      if (ez5.schema.CURRENT._objecttype_by_name[linkedObjecttype].pool_link) {
                        poolId = _this.__poolSelectedByUserPerObjecttype[linkedObjecttype] || 2;
                        linkedData[linkedObjecttype]._pool = {
                          pool: {
                            _id: poolId
                          }
                        };
                      }
                      _dfr = ez5.api.db({
                        api: "/" + linkedObjecttype + "?format=standard",
                        json_data: [linkedData]
                      }).done(function(newLinkedData) {
                        var linkedObject, nlinkedObjecttype;
                        if (newLinkedData.length > 0) {
                          newLinkedData = newLinkedData[0];
                          nlinkedObjecttype = newLinkedData._objecttype;
                          linkedObject = {};
                          linkedObject._objecttype = nlinkedObjecttype;
                          linkedObject._mask = newLinkedData._mask;
                          linkedObject._global_object_id = newLinkedData._global_object_id;
                          linkedObject[nlinkedObjecttype] = {
                            _id: newLinkedData[nlinkedObjecttype]._id
                          };
                        }
                        return data[field][idx][nf.name()] = newLinkedData;
                      });
                      return create_linked_objects_promises.push(_dfr);
                    }
                  };
                  for (idx = j = 0, len1 = value.length; j < len1; idx = ++j) {
                    val = value[idx];
                    fn1(val, idx);
                  }
                }
              }
            }
            if (CUI.util.isPlainObject(value) && !CUI.util.isEmpty(value._objecttype) && !((ref = value[value._objecttype]) != null ? ref["lookup:_id"] : void 0)) {
              if (CUI.util.isEmpty(value._id) && !CUI.util.isEmpty(value._mapped_metadata_created)) {
                linkedObjecttype = value._objecttype;
                linked_data = {};
                linked_data[linkedObjecttype] = value[linkedObjecttype];
                linked_data[linkedObjecttype]._id = null;
                linked_data[linkedObjecttype]._version = 1;
                linked_data._mask = value._mask;
                linked_data._objecttype = linkedObjecttype;
                if (ez5.schema.CURRENT._objecttype_by_name[linkedObjecttype].pool_link) {
                  poolId = ((ref1 = preMergedData[field]) != null ? (ref2 = ref1[linkedObjecttype]) != null ? (ref3 = ref2._pool) != null ? (ref4 = ref3.pool) != null ? ref4._id : void 0 : void 0 : void 0 : void 0) || null;
                  if (!poolId) {
                    poolId = _this.__poolSelectedByUserPerObjecttype[linkedObjecttype];
                  }
                  if (poolId) {
                    linked_data[linkedObjecttype]._pool = {
                      pool: {
                        _id: poolId
                      }
                    };
                  }
                }
                _dfr = ez5.api.db({
                  api: "/" + linkedObjecttype + "?format=standard",
                  json_data: [linked_data]
                }).done(function(newLinkedData) {
                  var linkedObject;
                  if (newLinkedData.length > 0) {
                    newLinkedData = newLinkedData[0];
                    linkedObjecttype = newLinkedData._objecttype;
                    linkedObject = {};
                    linkedObject._objecttype = linkedObjecttype;
                    linkedObject._mask = newLinkedData._mask;
                    linkedObject._global_object_id = newLinkedData._global_object_id;
                    linkedObject[linkedObjecttype] = {
                      _id: newLinkedData[linkedObjecttype]._id
                    };
                    if (value[linkedObjecttype]._pool) {
                      linkedObject[linkedObjecttype]._pool = value[linkedObjecttype]._pool;
                    }
                    return data[field] = linkedObject;
                  } else {
                    deferred.reject(e);
                    return console.error("JSONImporter - EASImporter :: mergeMetadata | EAS.mapMetadata returned an error. EAS ID: " + easId + ". Objecttype: " + objecttype + ". Mapping: " + mapping, object, e);
                  }
                }).fail((function(e) {
                  return deferred.reject(e);
                }));
                return create_linked_objects_promises.push(_dfr);
              } else {
                linkedObjecttype = value._objecttype;
                linkedObject = {};
                linkedObject._objecttype = linkedObjecttype;
                linkedObject._mask = value._mask;
                linkedObject._global_object_id = value._global_object_id;
                linkedObject[linkedObjecttype] = {
                  _id: value[linkedObjecttype]._id
                };
                if (value[linkedObjecttype]._pool) {
                  linkedObject[linkedObjecttype]._pool = value[linkedObjecttype]._pool;
                }
                return data[field] = linkedObject;
              }
            }
          };
          for (field in data) {
            value = data[field];
            fn(field, value);
          }
          if (create_linked_objects_promises.length > 0) {
            return CUI.when(create_linked_objects_promises).done(function() {
              return deferred.resolve();
            }).fail(function(e) {
              return deferred.reject(e);
            });
          } else {
            return deferred.resolve();
          }
        }).fail(function(e) {
          console.log("EASImporter :: mergeMetadata | Error asking for linked pools. EAS ID: " + easId + ". Objecttype: " + objecttype + ". Mapping: " + mapping, object);
          return deferred.reject(e);
        });
      };
    })(this)).fail((function(_this) {
      return function(e) {
        console.error("EASImporter :: mergeMetadata | EAS.mapMetadata returned an error. EAS ID: " + easId + ". Objecttype: " + objecttype + ". Mapping: " + mapping, object, e);
        return deferred.resolve();
      };
    })(this));
    return deferred.promise();
  };

  EASImporter.prototype.destroy = function() {
    delete this.__previewContainer;
    return EASImporter.__super__.destroy.call(this);
  };

  EASImporter.getSelectOptions = function() {
    return [
      {
        text: $$("eas.importer.fields.eas_type.direct.option.label"),
        value: EASImporter.EAS_TYPE.DIRECT
      }, {
        text: $$("eas.importer.fields.eas_type.url.option.label"),
        value: EASImporter.EAS_TYPE.URL
      }, {
        text: $$("eas.importer.fields.eas_type.ignore.option.label"),
        value: EASImporter.EAS_TYPE.IGNORE
      }
    ];
  };

  return EASImporter;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var JSONPayloadRollback,
  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;

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

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

  JSONPayloadRollback.prototype.initOpts = function() {
    JSONPayloadRollback.__super__.initOpts.call(this);
    this.addOpts({
      payload: {
        check: "PlainObject",
        url: {
          check: String,
          mandatory: true
        }
      },
      importType: {
        check: String,
        mandatory: true
      },
      objectType: {
        check: String
      }
    });
    this.__init();
  };

  JSONPayloadRollback.prototype.start = function() {
    if (this._importType === "tags") {
      return ez5.api.tags({
        api: "/",
        json_data: this.__items,
        type: "POST"
      }).done((function(_this) {
        return function() {
          return _this.__init();
        };
      })(this));
    } else {
      if (this.__items.length === 0) {
        return CUI.resolvedPromise();
      }
      return CUI.chunkWork.call(this, {
        items: this.__items,
        chunk_size: this._importType === "db" ? 1000 : 1,
        call: (function(_this) {
          return function(items) {
            var idObject;
            switch (_this._importType) {
              case "group":
              case "user":
              case "pool":
              case "tags":
              case "collection":
                idObject = items[0];
                return ez5.api[_this._importType]({
                  api: "/" + idObject,
                  type: "DELETE"
                });
              default:
                return ez5.api.db({
                  api: "/" + _this._objectType,
                  json_data: items,
                  type: "DELETE"
                });
            }
          };
        })(this)
      }).done((function(_this) {
        return function() {
          return _this.__init();
        };
      })(this));
    }
  };

  JSONPayloadRollback.prototype.addData = function(data) {
    var i, items, j, len, len1, object, version;
    switch (this._importType) {
      case "tags":
        this.__items = data;
        break;
      case "collection":
        this.__items.unshift(data.collection._id);
        break;
      case "group":
      case "user":
      case "pool":
        for (i = 0, len = data.length; i < len; i++) {
          object = data[i];
          this.__items.unshift(object[this._importType]._id);
        }
        break;
      default:
        items = [];
        for (j = 0, len1 = data.length; j < len1; j++) {
          object = data[j];
          version = object[this._objectType]._version;
          if (version !== 1) {
            continue;
          }
          items.push([object[this._objectType]._id, version]);
        }
        items.reverse();
        this.__items = items.concat(this.__items);
    }
  };

  JSONPayloadRollback.prototype.getPayloadUrl = function() {
    return this._payload.url;
  };

  JSONPayloadRollback.prototype.destroy = function() {
    delete this.__items;
    return JSONPayloadRollback.__super__.destroy.call(this);
  };

  JSONPayloadRollback.prototype.__init = function() {
    this.__items = [];
  };

  return JSONPayloadRollback;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var JSONPayload,
  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;

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

  JSONPayload.COLLECTION_MAX_OBJECTS_LENGTH = 1000;

  JSONPayload.UPDATE_VERSION_ATTRIBUTE_NAME = "_version:auto_increment";

  JSONPayload.LOOKUP_ID_ATTRIBUTE_NAME = "lookup:_id";

  function JSONPayload(opts) {
    this.opts = opts != null ? opts : {};
    JSONPayload.__super__.constructor.call(this, this.opts);
    JSONImporterLogs.setCurrentPayload(this.opts.payload.url);
  }

  JSONPayload.prototype.initOpts = function() {
    JSONPayload.__super__.initOpts.call(this);
    return this.addOpts({
      payload: {
        check: "PlainObject",
        url: {
          check: String,
          mandatory: true
        },
        batchOffset: {
          check: "Integer",
          "default": 1
        }
      },
      settings: {
        check: "PlainObject",
        payloadBaseUri: {
          check: String,
          mandatory: true
        },
        batchSize: {
          check: "Integer",
          "default": 1000
        },
        easType: {
          check: String
        },
        easReplaceUrl: {
          check: String,
          mandatory: false
        },
        skipRPUTHeadRequest: {
          check: Boolean,
          "default": false
        },
        mapping: {
          check: String
        },
        easSkipErrors: {
          check: Boolean,
          "default": true
        },
        skipUniqueConstraintErrors: {
          check: Boolean,
          "default": true
        }
      }
    });
  };

  JSONPayload.prototype.getTotalCount = function(includePayloadData) {
    var deferred;
    if (includePayloadData == null) {
      includePayloadData = false;
    }
    deferred = new CUI.Deferred();
    this.load().done((function(_this) {
      return function(payloadData) {
        var countData, objects;
        objects = _this.__getObjects(payloadData);
        countData = {
          objecttype: payloadData.objecttype || payloadData.import_type,
          objectsTotal: objects.length
        };
        if (includePayloadData) {
          countData.payloadData = payloadData;
        }
        if (payloadData.import_type === "db") {
          _this.__easImporter = new EASImporter({
            objects: objects,
            objectType: payloadData.objecttype,
            settings: _this._settings
          });
          countData.easFieldsTotal = _this.__easImporter.getTotalCount();
        }
        return deferred.resolve(countData);
      };
    })(this)).fail(deferred.reject);
    return deferred.promise();
  };

  JSONPayload.prototype["import"] = function() {
    var deferred, startTime;
    JSONImporterLogs.add({
      level: JSONImporterLogs.LEVEL_INFO,
      message: $$("json.importer.modal.payload.process.start")
    });
    startTime = new Date().getTime();
    deferred = new CUI.Deferred();
    this.load().done((function(_this) {
      return function(payloadData) {
        return _this.__upload(payloadData).done(function() {
          var millisecondsElapsed, time;
          millisecondsElapsed = (new Date().getTime()) - startTime;
          time = ez5.format_seconds(Math.round(millisecondsElapsed / 1000));
          JSONImporterLogs.add({
            level: JSONImporterLogs.LEVEL_INFO,
            objectType: payloadData.objecttype,
            baseType: !payloadData.objecttype ? payloadData.import_type : void 0,
            duration: millisecondsElapsed,
            message: $$("json.importer.modal.payload.process.finish", {
              objects: _this.__getObjects(payloadData).length,
              time: time
            })
          });
          return deferred.resolve();
        }).fail(deferred.reject);
      };
    })(this)).fail(deferred.reject);
    return deferred.promise();
  };

  JSONPayload.prototype.load = function() {
    var deferred, url;
    deferred = new CUI.Deferred();
    url = this._settings.payloadBaseUri + this._payload.url;
    JSONImporterUtils.getFile(url).done((function(_this) {
      return function(payloadData) {
        var i, j, key, len, len1, object, objects, ref;
        if (CUI.util.isEmpty(payloadData)) {
          deferred.reject($$("json.importer.error.message.payload-not-found", {
            url: url
          }));
          return;
        }
        if (CUI.util.isEmpty(payloadData.import_type)) {
          deferred.reject($$("json.importer.error.message.import-type-not-found", {
            url: url
          }));
          return;
        }
        objects = _this.__getObjects(payloadData);
        if (!CUI.util.isArray(objects)) {
          deferred.reject($$("json.importer.error.message.payload-array-not-found", {
            url: url
          }));
          return;
        }
        if (payloadData.import_type === "db") {
          if (CUI.util.isEmpty(payloadData.objecttype)) {
            deferred.reject($$("json.importer.error.message.object-type-not-found", {
              url: url
            }));
            return;
          }
          for (i = 0, len = objects.length; i < len; i++) {
            object = objects[i];
            ref = ["_objecttype", "_mask"];
            for (j = 0, len1 = ref.length; j < len1; j++) {
              key = ref[j];
              if (object[key]) {
                continue;
              }
              deferred.reject($$("json.importer.error.message.object-key-not-found-" + key, {
                objectType: payloadData.objecttype,
                url: _this._payload.url
              }));
              return;
            }
            if (object._objecttype !== payloadData.objecttype) {
              deferred.reject($$("json.importer.error.message.objecttype-not-equals", {
                objectType: payloadData.objecttype,
                url: _this._payload.url
              }));
              return;
            }
            if (!CUI.util.isPlainObject(object[payloadData.objecttype])) {
              deferred.reject($$("json.importer.error.message.object-data-not-found", {
                objectType: payloadData.objecttype,
                url: _this._payload.url
              }));
              return;
            }
          }
        }
        return deferred.resolve(payloadData);
      };
    })(this)).fail((function(_this) {
      return function(message) {
        if (!CUI.util.isString(message)) {
          message = $$("json.importer.error.message.payload-file-not-found", {
            url: url
          });
        }
        return deferred.reject(message);
      };
    })(this));
    return deferred.promise();
  };

  JSONPayload.prototype.__getChunkSize = function(payloadData) {
    if (!ez5.version("6") && payloadData.import_type === "collection") {
      return 1;
    } else if (payloadData.import_type === "tags") {
      return 1000;
    }
    return this._settings.batchSize;
  };

  JSONPayload.prototype.__upload = function(payloadData) {
    var abortListener, abortNextChunk, chunkSize, deferred, lookupIdsPromise, objects, uploadChunk;
    deferred = new CUI.Deferred();
    abortNextChunk = false;
    objects = this.__getObjects(payloadData);
    chunkSize = this.__getChunkSize(payloadData);
    uploadChunk = null;
    abortListener = CUI.Events.listen({
      type: "json-importer-abort-upload",
      call: (function(_this) {
        return function() {
          abortNextChunk = true;
          return uploadChunk != null ? uploadChunk.abort() : void 0;
        };
      })(this)
    });
    if (payloadData.import_type === "db" && !ez5.version("6")) {
      lookupIdsPromise = this.__lookupIds(objects, payloadData.objecttype);
    } else {
      lookupIdsPromise = CUI.resolvedPromise();
    }
    lookupIdsPromise.done((function(_this) {
      return function() {
        var chunkStartTime, currentChunk, currentOffset, currentPayloadIndex, progressType;
        progressType = payloadData.objecttype || payloadData.import_type;
        JSONImporterUtils.updateProgress(_this._payload.url, progressType, objects.length, chunkSize);
        chunkStartTime = null;
        currentOffset = 0;
        currentChunk = _this._payload.batchOffset - 1;
        currentPayloadIndex = 0;
        return CUI.chunkWork.call(_this, {
          items: objects,
          chunk_size: chunkSize,
          call: function(items, offset) {
            var chunkDeferred, easImporterPromise, logObjects, updateVersionPromise, uploadObjects;
            currentChunk++;
            chunkStartTime = performance.now();
            currentOffset = offset;
            if (abortNextChunk) {
              return CUI.rejectedPromise({
                level: JSONImporterLogs.LEVEL_INFO,
                message: $$("json.importer.error.message.eas.abort")
              });
            }
            if (payloadData.import_type === "db") {
              _this.__easImporter = new EASImporter({
                objects: items,
                objectType: payloadData.objecttype,
                settings: _this._settings
              });
              easImporterPromise = _this.__easImporter.upload();
            } else {
              easImporterPromise = CUI.resolvedPromise();
            }
            if (payloadData.import_type === "db" && !ez5.version("6")) {
              updateVersionPromise = _this.__updateVersion(items, payloadData.objecttype);
              updateVersionPromise.fail(function() {
                return CUI.Events.trigger({
                  type: "json-importer-abort-upload"
                });
              });
            } else {
              updateVersionPromise = CUI.resolvedPromise();
            }
            chunkDeferred = new CUI.Deferred();
            logObjects = function(objectsCreated) {
              var chunk, duration, i, index, indexCreated, item, itemCreated, j, key, len, len1, level, message, object, objectCreated, objectId, operation, ref, ref1, skippedOnly, uniqueKey, uniqueKeys, uniqueKeysLog, untilOffset;
              duration = performance.now() - chunkStartTime;
              indexCreated = 0;
              skippedOnly = CUI.util.isNull(objectsCreated);
              for (index = i = 0, len = items.length; i < len; index = ++i) {
                item = items[index];
                currentPayloadIndex = offset + index + 1;
                if (skippedOnly && !item.__skipped) {
                  continue;
                }
                object = item[progressType];
                if (!ez5.version("6") && payloadData.import_type === "collection") {
                  chunk = (offset + 1) + "/" + objects.length;
                } else {
                  untilOffset = offset + chunkSize;
                  if (untilOffset > objects.length) {
                    untilOffset = objects.length;
                  }
                  chunk = (offset + 1) + "-" + untilOffset;
                }
                uniqueKeys = (ref = ez5.schema.CURRENT._objecttype_by_name[progressType]) != null ? ref.unique_keys : void 0;
                if ((uniqueKeys != null ? uniqueKeys.length : void 0) > 0) {
                  uniqueKeysLog = [];
                  for (j = 0, len1 = uniqueKeys.length; j < len1; j++) {
                    uniqueKey = uniqueKeys[j];
                    key = (ref1 = uniqueKey.columns[0]) != null ? ref1.column_name_hint : void 0;
                    if (object[key]) {
                      uniqueKeysLog.push(object[key]);
                    }
                  }
                }
                if (item.__skipped) {
                  level = JSONImporterLogs.LEVEL_ERROR;
                  operation = (object != null ? object._id : void 0) ? JSONImporterLogs.OPERATION_UPDATE_SKIPPED : JSONImporterLogs.OPERATION_INSERT_SKIPPED;
                  objectId = object != null ? object._id : void 0;
                  message = $$("json.importer.modal.payload.process.skipped-object");
                } else {
                  itemCreated = CUI.util.isArray(objectsCreated) ? objectsCreated[indexCreated] : objectsCreated;
                  objectCreated = itemCreated != null ? itemCreated[progressType] : void 0;
                  indexCreated++;
                  level = JSONImporterLogs.LEVEL_INFO;
                  operation = (object != null ? object._id : void 0) ? JSONImporterLogs.OPERATION_UPDATE : JSONImporterLogs.OPERATION_INSERT;
                  objectId = objectCreated != null ? objectCreated._id : void 0;
                  message = $$("json.importer.modal.payload.process." + ((object != null ? object._id : void 0) ? "update" : "insert") + "-object");
                }
                JSONImporterLogs.add({
                  level: level,
                  operation: operation,
                  duration: duration,
                  objectId: objectId,
                  systemObjectId: (item != null ? item._system_object_id : void 0) || (itemCreated != null ? itemCreated._system_object_id : void 0),
                  objectType: payloadData.objecttype,
                  baseType: !payloadData.objecttype ? payloadData.import_type : void 0,
                  message: message,
                  payloadIndex: currentPayloadIndex,
                  uniqueKeys: uniqueKeysLog,
                  chunk: chunk
                });
              }
              JSONImporterUtils.updateProgress(_this._payload.url, progressType, objects.length, chunkSize, chunkSize);
              if (!skippedOnly) {
                return JSONImporterReport.add(progressType, (objectsCreated != null ? objectsCreated.length : void 0) || chunkSize);
              }
            };
            uploadObjects = function(itemsToUpload) {
              if (itemsToUpload.length === 0) {
                logObjects(null);
                return chunkDeferred.resolve();
              }
              uploadChunk = _this.__uploadChunk(itemsToUpload, payloadData);
              return uploadChunk.done(function(objectsCreated) {
                logObjects(objectsCreated);
                return chunkDeferred.resolve();
              }).fail(function(response, status, statusText) {
                var code, columnPath, columnValue, filteredItems, ref;
                if (_this._settings.skipUniqueConstraintErrors) {
                  code = response != null ? (ref = response.responseJSON) != null ? ref.code : void 0 : void 0;
                  if (chunkSize === 1 && (code === "error.user.unique_constraint_violation_with_column_and_value" || code === "error.user.unique_constraint_violation_with_column_values" || code === "error.user.unique_constraint_violation" || code === "error.user.reference_unique_violation_simple" || code === "error.user.collection_name_repeated" || code === "error.user.login_already_exists")) {
                    itemsToUpload[0].__skipped = true;
                    return uploadObjects(itemsToUpload.slice(1));
                  }
                  if (code === "error.user.unique_constraint_violation_with_column_and_value") {
                    columnPath = response.responseJSON.parameters.column_name;
                    columnValue = response.responseJSON.parameters.column_value;
                    if (columnPath && columnValue) {
                      filteredItems = itemsToUpload.filter(function(item) {
                        var itemValue;
                        try {
                          itemValue = eval("item." + columnPath);
                          if (itemValue === columnValue) {
                            item.__skipped = true;
                            return false;
                          }
                        } catch (error) {}
                        return true;
                      });
                      if (filteredItems.length >= 0 && filteredItems.length !== itemsToUpload.length) {
                        return uploadObjects(filteredItems);
                      }
                    }
                  }
                }
                return chunkDeferred.reject(response, status, statusText);
              });
            };
            CUI.when([easImporterPromise, updateVersionPromise]).done(function() {
              return uploadObjects(items);
            }).fail(chunkDeferred.reject);
            return chunkDeferred.promise();
          }
        }).always(function() {
          return abortListener.destroy();
        }).done(function() {
          return deferred.resolve();
        }).fail(function(response, statusText, timeTook) {
          var doReject, message;
          doReject = function(message) {
            var untilOffset;
            if (timeTook) {
              message = message + " | " + timeTook + "ms";
            }
            if (CUI.util.isString(message)) {
              message = {
                level: JSONImporterLogs.LEVEL_ERROR,
                duration: chunkStartTime ? performance.now() - chunkStartTime : void 0,
                message: message,
                objectType: payloadData.objecttype,
                baseType: !payloadData.objecttype ? payloadData.import_type : void 0
              };
            }
            if (!CUI.util.isUndef(currentOffset)) {
              untilOffset = currentOffset + chunkSize;
              if (untilOffset > objects.length) {
                untilOffset = objects.length;
              }
              message.payloadIndex = (payloadData.import_type === "collection" && !ez5.version("6")) ? currentPayloadIndex + 1 : void 0;
              message.chunk = (payloadData.import_type === "collection" && !ez5.version("6")) ? (currentOffset + 1) + "/" + objects.length : currentOffset + "-" + untilOffset;
              message.objectType = progressType;
            }
            return deferred.reject(message, currentChunk);
          };
          if (CUI.util.isPlainObject(response) && response.level && response.message) {
            return doReject(response);
          }
          if (CUI.util.isString(response)) {
            if (statusText) {
              return doReject(statusText + " | " + response);
            } else {
              return doReject(response);
            }
          }
          message = JSONImporterUtils.getErrorMessageFromResponse(response, statusText);
          if (message) {
            return doReject(message);
          }
          if (response && response.CUI_status && response.CUI_statusText) {
            return doReject(response.CUI_status + " | " + response.CUI_statusText);
          } else {
            return doReject(statusText || $$("json.importer.error.message.no-status"));
          }
        });
      };
    })(this)).fail(deferred.reject);
    return deferred.promise();
  };

  JSONPayload.prototype.__uploadChunk = function(items, payloadData) {
    switch (payloadData.import_type) {
      case "group":
      case "user":
      case "pool":
      case "tags":
        return ez5.api[payloadData.import_type]({
          api: "",
          json_data: items,
          type: "POST",
          handle_error: (function(_this) {
            return function() {
              return true;
            };
          })(this)
        });
      case "collection":
        return this.__uploadCollection(items);
      default:
        return ez5.api.db({
          api: "/" + payloadData.objecttype,
          json_data: items,
          type: "POST",
          handle_error: (function(_this) {
            return function() {
              return true;
            };
          })(this),
          data: {
            skip_bidirectional_update: true,
            skip_reverse_nested: true,
            confirmTransition: "SKIP",
            skip_constraints: true
          }
        });
    }
  };

  JSONPayload.prototype.__uploadFylrCollection = function(items) {
    return ez5.api.collection({
      api: "/list",
      json_data: items,
      type: "PUT",
      handle_error: (function(_this) {
        return function() {
          return true;
        };
      })(this)
    });
  };

  JSONPayload.prototype.__uploadCollection = function(items) {
    var collectionData, deferred, objects;
    if (ez5.version("6")) {
      return this.__uploadFylrCollection(items);
    }
    collectionData = items[0];
    if (!collectionData._objects || collectionData._objects.length <= JSONPayload.COLLECTION_MAX_OBJECTS_LENGTH) {
      return ez5.api.collection({
        api: "",
        json_data: collectionData,
        type: "PUT",
        handle_error: (function(_this) {
          return function() {
            return true;
          };
        })(this)
      });
    } else {
      deferred = new CUI.Deferred();
      objects = collectionData._objects;
      collectionData._objects = [];
      ez5.api.collection({
        api: "",
        json_data: collectionData,
        type: "PUT",
        handle_error: (function(_this) {
          return function() {
            return true;
          };
        })(this)
      }).done((function(_this) {
        return function(responseData) {
          var idCollection;
          idCollection = responseData.collection._id;
          return CUI.chunkWork.call(_this, {
            items: objects,
            chunk_size: JSONPayload.COLLECTION_MAX_OBJECTS_LENGTH,
            call: function(items) {
              return ez5.api.collection({
                api: "/push/" + idCollection,
                json_data: {
                  _objects: items
                },
                type: "POST",
                handle_error: function() {
                  return true;
                }
              }).fail(function() {});
            }
          }).done(function() {
            return deferred.resolve(responseData);
          }).fail(deferred.reject);
        };
      })(this)).fail(deferred.reject);
      return deferred.promise();
    }
  };

  JSONPayload.prototype.__lookupIds = function(objects, objectType) {
    var chunkStartTime, deferred, findObjects, i, idIncludeField, includeFields, item, len, lookup, lookupIncludeField, lookupKey, lookupKeys, message, object, objectsToLookup, searchInKeys;
    this.__retryLookup = 0;
    if (!objectType) {
      return CUI.resolvedPromise();
    }
    lookupKey = null;
    objectsToLookup = {};
    searchInKeys = [];
    for (i = 0, len = objects.length; i < len; i++) {
      item = objects[i];
      object = item[objectType];
      if (object._id || !object[JSONPayload.LOOKUP_ID_ATTRIBUTE_NAME]) {
        continue;
      }
      if (!object[JSONPayload.UPDATE_VERSION_ATTRIBUTE_NAME]) {
        continue;
      }
      lookup = object[JSONPayload.LOOKUP_ID_ATTRIBUTE_NAME];
      if (CUI.util.isArray(lookup)) {
        return CUI.resolvedPromise();
      }
      lookupKeys = Object.keys(lookup);
      if (lookupKeys.length === 0) {
        continue;
      }
      if (lookupKeys.length > 1) {
        message = $$("json.importer.error.message.version-auto-increment.multiple-keys", {
          keys: lookupKeys,
          objectType: objectType
        });
        return CUI.rejectedPromise({
          level: JSONImporterLogs.LEVEL_ERROR,
          message: message,
          references: lookupKeys.join(",")
        });
      }
      if (lookupKey === null) {
        lookupKey = lookupKeys[0];
      } else if (lookupKey !== lookupKeys[0]) {
        message = $$("json.importer.error.message.version-auto-increment.different-keys", {
          keyFound: lookupKey,
          key: lookupKeys[0],
          objectType: objectType
        });
        return CUI.rejectedPromise({
          level: JSONImporterLogs.LEVEL_ERROR,
          message: message,
          references: lookupKey + ", " + lookupKeys[0]
        });
      }
      searchInKeys.push(lookup[lookupKey]);
      objectsToLookup[lookup[lookupKey]] = object;
      delete object[JSONPayload.LOOKUP_ID_ATTRIBUTE_NAME];
    }
    if (CUI.util.isEmpty(objectsToLookup)) {
      return CUI.resolvedPromise();
    }
    chunkStartTime = performance.now();
    idIncludeField = objectType + "._id";
    includeFields = [idIncludeField];
    lookupIncludeField = objectType + "." + lookupKey;
    if (idIncludeField !== lookupIncludeField) {
      includeFields.push(lookupIncludeField);
    }
    ez5.splash.show("json.importer.splash.process-lookup");
    deferred = new CUI.Deferred();
    findObjects = (function(_this) {
      return function() {
        var foundObjects;
        foundObjects = [];
        return CUI.chunkWork.call(_this, {
          items: searchInKeys,
          chunk_size: 1000,
          call: function(items) {
            return ez5.api.search({
              handle_error: function() {
                return true;
              },
              json_data: {
                objecttypes: [objectType],
                format: "short",
                include_fields: includeFields,
                generate_rights: false,
                search: [
                  {
                    type: "in",
                    fields: [objectType + "." + lookupKey],
                    "in": items
                  }
                ]
              }
            }).done(function(data) {
              return foundObjects = foundObjects.concat(data.objects);
            });
          }
        }).done(function() {
          var duration, j, keyValue, len1, log;
          for (j = 0, len1 = foundObjects.length; j < len1; j++) {
            item = foundObjects[j];
            object = item[objectType];
            if (!object[lookupKey] || !objectsToLookup[object[lookupKey]]) {
              continue;
            }
            objectsToLookup[object[lookupKey]]._id = object._id;
          }
          duration = performance.now() - chunkStartTime;
          for (keyValue in objectsToLookup) {
            object = objectsToLookup[keyValue];
            if (!object._id) {
              if (_this.__retryLookup < 3) {
                _this.__retryLookup++;
                setTimeout(findObjects, 5000);
                return;
              }
              message = $$("json.importer.error.message.version-auto-increment.non-existing-lookup-id", {
                key: lookupKey,
                value: keyValue
              });
              log = {
                level: JSONImporterLogs.LEVEL_ERROR,
                operation: JSONImporterLogs.OPERATION_GET,
                message: message,
                objectType: objectType
              };
              ez5.splash.hide();
              return deferred.reject(log);
            } else {
              JSONImporterLogs.add({
                level: JSONImporterLogs.LEVEL_INFO,
                operation: JSONImporterLogs.OPERATION_GET,
                objectId: object._id,
                objectType: objectType,
                duration: duration,
                message: $$("json.importer.modal.payload.process.lookup-id", {
                  reference: lookupKey
                })
              });
            }
          }
          ez5.splash.hide();
          return deferred.resolve();
        }).fail(function(response, statusText) {
          ez5.splash.hide();
          message = JSONImporterUtils.getErrorMessageFromResponse(response, statusText);
          return deferred.reject({
            level: JSONImporterLogs.LEVEL_ERROR,
            message: message,
            references: searchInKeys.join(",")
          });
        });
      };
    })(this);
    findObjects();
    return deferred.promise();
  };

  JSONPayload.prototype.__updateVersion = function(items, objectType) {
    var abortListener, abortNextChunk, chunkWork;
    if (!objectType) {
      return CUI.resolvedPromise();
    }
    abortNextChunk = false;
    abortListener = CUI.Events.listen({
      type: "json-importer-abort-upload",
      call: (function(_this) {
        return function() {
          return abortNextChunk = true;
        };
      })(this)
    });
    chunkWork = CUI.chunkWork.call(this, {
      items: items,
      chunk_size: 1,
      call: (function(_this) {
        return function(itemArray) {
          var chunkStartTime, deferred, item, object;
          chunkStartTime = performance.now();
          item = itemArray[0];
          if (abortNextChunk) {
            return CUI.rejectedPromise($$("json.importer.error.message.eas.abort"));
          }
          object = item[objectType];
          if (!object[JSONPayload.UPDATE_VERSION_ATTRIBUTE_NAME]) {
            return CUI.resolvedPromise();
          }
          if (!object._id) {
            return CUI.rejectedPromise($$("json.importer.error.message.version-auto-increment.missing-id", {
              objectType: objectType
            }));
          }
          deferred = new CUI.Deferred();
          ez5.api.db({
            type: "GET",
            api: "/" + objectType + "/" + item._mask + "/" + object._id,
            data: {
              format: "long"
            },
            handle_error: function() {
              return true;
            }
          }).done(function(data) {
            var key, objectStored, storedValue, value;
            JSONImporterLogs.add({
              level: JSONImporterLogs.LEVEL_INFO,
              operation: JSONImporterLogs.OPERATION_GET,
              objectId: object._id,
              systemObjectId: item._system_object_id,
              objectType: objectType,
              duration: performance.now() - chunkStartTime,
              message: $$("json.importer.modal.payload.process.get-object")
            });
            objectStored = data != null ? data[0][objectType] : void 0;
            if (objectStored) {
              object = item[objectType];
              for (key in objectStored) {
                storedValue = objectStored[key];
                if (!object.hasOwnProperty(key)) {
                  object[key] = storedValue;
                } else {
                  value = object[key];
                  if (CUI.util.isArray(value) && object[key + ":group_mode"] === "append") {
                    object[key] = storedValue.concat(value);
                  }
                }
              }
              object._version = objectStored._version + 1;
              delete object[JSONPayload.UPDATE_VERSION_ATTRIBUTE_NAME];
            }
            return deferred.resolve();
          }).fail(function(response, statusText) {
            var log, message;
            message = JSONImporterUtils.getErrorMessageFromResponse(response, statusText);
            if (!message) {
              message = $$("json.importer.error.message.version-auto-increment.search-fail");
            }
            log = {
              level: JSONImporterLogs.LEVEL_ERROR,
              operation: JSONImporterLogs.OPERATION_GET,
              objectId: object._id,
              systemObjectId: item._system_object_id,
              objectType: objectType,
              message: message
            };
            return deferred.reject(log);
          });
          return deferred.promise();
        };
      })(this)
    }).always((function(_this) {
      return function() {
        return abortListener.destroy();
      };
    })(this));
    return chunkWork;
  };

  JSONPayload.prototype.__getObjects = function(payloadData) {
    var chunkIndexOffset, chunkSize, objects, startChunkOffset;
    objects = JSONPayload.getObjects(payloadData);
    chunkIndexOffset = this._payload.batchOffset;
    chunkSize = this.__getChunkSize(payloadData);
    startChunkOffset = chunkSize * (chunkIndexOffset - 1);
    return objects.slice(startChunkOffset);
  };

  JSONPayload.getObjects = function(payloadData) {
    var objects;
    if (!payloadData) {
      console.warn("JSONPayload.getObjects :: payloadData is not defined.");
      return [];
    }
    objects = (function() {
      switch (payloadData.import_type) {
        case "group":
          return payloadData.groups;
        case "user":
          return payloadData.users;
        case "pool":
          return payloadData.pools;
        case "tags":
          return payloadData.tags;
        case "collection":
          return payloadData.collections;
        default:
          return payloadData.objects;
      }
    })();
    return objects || [];
  };

  JSONPayload.prototype.destroy = function() {
    var ref;
    JSONImporterLogs.setCurrentPayload(null);
    if ((ref = this.__easImporter) != null) {
      ref.destroy();
    }
    return JSONPayload.__super__.destroy.call(this);
  };

  return JSONPayload;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var JSONImporterProgressModal,
  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;

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

  JSONImporterProgressModal.prototype.initOpts = function() {
    JSONImporterProgressModal.__super__.initOpts.call(this);
    return this.addOpts({
      progressCounters: {
        check: "PlainObject",
        objectsTotal: {
          check: "Integer",
          mandatory: true
        },
        easFieldsTotal: {
          check: "Integer",
          mandatory: true
        }
      },
      easType: {
        check: String,
        mandatory: true
      }
    });
  };

  function JSONImporterProgressModal(opts) {
    var countEASTotalLabel, countLabel, countTotalLabel, currentBatchSize, currentCount, currentPayload, headerLabel, objectsPerSecondLabel, previewLabel, progressMeter;
    this.opts = opts != null ? opts : {};
    JSONImporterProgressModal.__super__.constructor.call(this, this.opts);
    this.__detailTemplate = new CUI.Template({
      name: "json-importer-progress-modal",
      map: {
        progressMeter: true,
        count: true,
        countTotal: true,
        countEASTotal: true,
        objectsPerSecond: true,
        timeElapsed: true,
        timeRemaining: true,
        previewImages: true
      }
    });
    this.__detailTemplate.hide();
    previewLabel = new CUI.Label({
      text: $$("json.importer.modal.processing.upload-eas-files.label"),
      centered: true,
      appearance: "muted"
    });
    this.__detailTemplate.append(previewLabel, "previewImages");
    this.__detailTemplate.addClass(EASImporter.previewContainerClass, "previewImages");
    progressMeter = new CUI.ProgressMeter({
      state: "spinning"
    });
    this.__detailTemplate.append(progressMeter, "progressMeter");
    countLabel = new CUI.Label();
    this.__detailTemplate.append(countLabel, "count");
    countTotalLabel = new CUI.Label();
    this.__detailTemplate.append(countTotalLabel, "countTotal");
    objectsPerSecondLabel = new CUI.Label();
    this.__detailTemplate.append(objectsPerSecondLabel, "objectsPerSecond");
    this.__timeRemainingLabel = new CUI.Label();
    this.__detailTemplate.append(this.__timeRemainingLabel, "timeRemaining");
    this.__timeElapsedLabel = new CUI.Label();
    this.__detailTemplate.append(this.__timeElapsedLabel, "timeElapsed");
    if (this._easType !== EASImporter.EAS_TYPE.IGNORE) {
      countEASTotalLabel = new CUI.Label();
      this.__detailTemplate.append(countEASTotalLabel, "countEASTotal");
    }
    headerLabel = new CUI.Label({
      text: $$("json.importer.modal.processing.header.label")
    });
    this.__processingModal = new CUI.Modal({
      cancel: false,
      pane: {
        padded: true,
        header_left: headerLabel,
        content: this.__detailTemplate,
        footer_right: [
          {
            loca_key: "json.importer.modal.footer.stop-import-icon.button",
            onClick: (function(_this) {
              return function(_, button) {
                return CUI.confirm({
                  text: $$("json.importer.modal.confirmation-abort")
                }).done(function() {
                  button.disable();
                  ez5.splash.show("json.importer.splash.abort.in-progress");
                  return CUI.Events.trigger({
                    type: "json-importer-abort-upload"
                  });
                });
              };
            })(this)
          }
        ]
      }
    });
    currentPayload = null;
    currentCount = 0;
    currentBatchSize = 0;
    this.__increaseProcessedListener = CUI.Events.listen({
      type: "json-importer-update-progress",
      call: (function(_this) {
        return function(_, info) {
          var count, countOffset, objectsDone, objectsDoneOffset, objectsPerSecond, remainingObjects, secondsElapsed, totalObjects, totalObjectsCreated, totalPercentage;
          _this.__detailTemplate.show();
          if (info.batchSize) {
            currentBatchSize = info.batchSize;
          }
          if (info.payloadUrl && info.type) {
            headerLabel.setText(info.payloadUrl + " | " + info.type);
            if (currentPayload !== info.payloadUrl) {
              currentPayload = info.payloadUrl;
              currentCount = 0;
            }
            currentCount += info.objectsCreated;
            count = currentCount;
            countOffset = count + currentBatchSize;
            if (countOffset > info.objectsTotal) {
              countOffset = info.objectsTotal;
            }
            if (count < info.objectsTotal) {
              count++;
            }
            countLabel.setText($$("json.importer.modal.processing.count.label", {
              count: count,
              countOffset: countOffset,
              total: info.objectsTotal
            }));
          }
          _this._progressCounters.easFieldsDone += info.easFieldsCreated;
          _this._progressCounters.objectsDone += info.objectsCreated;
          objectsDoneOffset = _this._progressCounters.objectsDone + currentBatchSize;
          if (objectsDoneOffset > _this._progressCounters.objectsTotal) {
            objectsDoneOffset = _this._progressCounters.objectsTotal;
          }
          objectsDone = _this._progressCounters.objectsDone;
          if (objectsDone < _this._progressCounters.objectsTotal) {
            objectsDone++;
          }
          countTotalLabel.setText($$("json.importer.modal.processing.count.total.label", {
            objectsDone: objectsDone,
            objectsDoneOffset: objectsDoneOffset,
            objectsTotal: _this._progressCounters.objectsTotal
          }));
          if (countEASTotalLabel && _this._progressCounters.easFieldsTotal > 0) {
            countEASTotalLabel.setText($$("json.importer.modal.processing.count.eas.total.label", {
              easFieldsDone: _this._progressCounters.easFieldsDone,
              easFieldsTotal: _this._progressCounters.easFieldsTotal,
              easType: $$("eas.importer.fields.eas_type." + _this._easType + ".option.label")
            }));
          }
          totalObjectsCreated = _this._progressCounters.objectsDone + (_this._progressCounters.easFieldsDone * 12);
          totalObjects = _this._progressCounters.objectsTotal + (_this._progressCounters.easFieldsTotal * 12);
          totalPercentage = (totalObjectsCreated * 100) / totalObjects;
          if (CUI.util.isNumber(totalPercentage) && totalPercentage >= 0 && totalPercentage <= 100) {
            progressMeter.setState(totalPercentage);
          }
          secondsElapsed = ((new Date().getTime()) - _this.__startTime) / 1000;
          objectsPerSecond = totalObjectsCreated / secondsElapsed;
          objectsPerSecondLabel.setText($$("json.importer.modal.processing.objects-per-second.label", {
            objectsLength: Math.round(objectsPerSecond)
          }));
          remainingObjects = totalObjects - totalObjectsCreated;
          _this.__secondsRemaining = Math.round(remainingObjects / objectsPerSecond);
          _this.__timeRemainingLabel.setText($$("json.importer.modal.processing.time-remaining.label", {
            time: ez5.format_seconds(_this.__secondsRemaining)
          }));
          CUI.Events.trigger({
            type: "content-resize",
            node: _this.__processingModal
          });
        };
      })(this)
    });
  }

  JSONImporterProgressModal.prototype.show = function() {
    var updateTime;
    this.__secondsRemaining = 0;
    this.__triggerUpdateTime = true;
    this.__startTime = new Date().getTime();
    updateTime = (function(_this) {
      return function() {
        var dateNow, secondsElapsed;
        if (_this.__triggerUpdateTime) {
          _this.__secondsRemaining--;
          if (_this.__secondsRemaining > 0) {
            _this.__timeRemainingLabel.setText($$("json.importer.modal.processing.time-remaining.label", {
              time: ez5.format_seconds(_this.__secondsRemaining)
            }));
          }
          dateNow = new Date();
          secondsElapsed = (dateNow.getTime() - _this.__startTime) / 1000;
          _this.__timeElapsedLabel.setText($$("json.importer.modal.processing.time-elapsed.label", {
            time: ez5.format_seconds(Math.round(secondsElapsed))
          }));
          return CUI.setTimeout({
            ms: 1000,
            call: updateTime
          });
        }
      };
    })(this);
    updateTime();
    this.__processingModal.show();
  };

  JSONImporterProgressModal.prototype.destroy = function() {
    delete this.__triggerUpdateTime;
    delete this.__secondsRemaining;
    delete this.__startTime;
    this.__increaseProcessedListener.destroy();
    this.__timeRemainingLabel.destroy();
    this.__timeElapsedLabel.destroy();
    this.__processingModal.destroy();
    this.__detailTemplate.destroy();
    delete this.__detailTemplate;
    delete this.__timeRemainingLabel;
    delete this.__increaseProcessedListener;
    delete this.__processingModal;
    return JSONImporterProgressModal.__super__.destroy.call(this);
  };

  return JSONImporterProgressModal;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var StatsTable,
  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;

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

  function StatsTable() {
    this.__addStatRows = bind(this.__addStatRows, this);
    return StatsTable.__super__.constructor.apply(this, arguments);
  }

  StatsTable.prototype.initOpts = function() {
    StatsTable.__super__.initOpts.call(this);
    return this.addOpts({
      data: {
        mandatory: true,
        check: function(v) {
          return !CUI.util.isEmpty(v);
        }
      }
    });
  };

  StatsTable.prototype.render = function() {
    var nodes, statTree;
    statTree = new ListViewEditTree({
      cols: this.__getStatCols(),
      "class": "ez5-pool-stat-list-tree",
      fields: this.__getStatFields(),
      extra_header: this.__getExtraHeader(),
      extra_header_below: true,
      no_hierarchy: true,
      rowMove: false,
      focusable: true,
      colResize: false,
      useCSSGridLayout: true
    });
    statTree.addHeader([
      {
        th_text: ""
      }, {
        th_text: $$("admin.pool.statistics.header.originals"),
        th_colspan: 8
      }, {
        th_text: $$("admin.pool.statistics.header.versions"),
        th_colspan: 8
      }
    ]);
    nodes = [];
    this.__addStatRows(this._data.files, nodes, "sum", false);
    this.__addStatRows(this._data.files, nodes, "by_class");
    this.__addStatRows(this._data.files, nodes, "by_extension");
    statTree.load_data(nodes);
    return statTree.render();
  };

  StatsTable.prototype.__getStatFields = function() {
    var fields, i, j;
    fields = [];
    fields.push("");
    for (i = j = 0; j <= 7; i = ++j) {
      fields.push({
        th_text: $$("admin.pool.statistics.column.count")
      });
      fields.push({
        th_text: $$("admin.pool.statistics.column.size")
      });
    }
    return fields;
  };

  StatsTable.prototype.__getExtraHeader = function() {
    var deletedLabel, historyLabel, latestLabel, sumLabel;
    latestLabel = $$("admin.pool.statistics.column.latest");
    historyLabel = $$("admin.pool.statistics.column.history");
    deletedLabel = $$("admin.pool.statistics.column.deleted");
    sumLabel = $$("admin.pool.statistics.column.sum");
    return [
      {
        th_text: ""
      }, {
        th_text: latestLabel,
        th_colspan: 2
      }, {
        th_text: historyLabel,
        th_colspan: 2
      }, {
        th_text: deletedLabel,
        th_colspan: 2
      }, {
        th_text: sumLabel,
        th_colspan: 2
      }, {
        th_text: latestLabel,
        th_colspan: 2
      }, {
        th_text: historyLabel,
        th_colspan: 2
      }, {
        th_text: deletedLabel,
        th_colspan: 2
      }, {
        th_text: sumLabel,
        th_colspan: 2
      }
    ];
  };

  StatsTable.prototype.__getStatCols = function() {
    var cols, i, j;
    cols = [];
    for (i = j = 0; j <= 16; i = ++j) {
      cols.push("auto");
    }
    return cols;
  };

  StatsTable.prototype.__addStatRows = function(pool, nodes, filter_name, label) {
    var base, base1, base2, className, classNamesSorted, classValue, j, len, list, ref, results, subTypeName, subtype, sumMode, type, typename;
    if (label == null) {
      label = true;
    }
    if (label) {
      nodes.push(new CUI.ListViewTreeNode({
        html: new CUI.Label({
          text: "**" + ($$("admin.pool.statistics.row." + filter_name)) + "**",
          markdown: true
        })
      }));
    }
    if (filter_name === "sum") {
      sumMode = true;
      filter_name = "by_class";
    }
    list = {};
    for (typename in pool) {
      type = pool[typename];
      for (subTypeName in type) {
        subtype = type[subTypeName];
        if (subtype.hasOwnProperty(filter_name)) {
          ref = subtype[filter_name];
          for (className in ref) {
            classValue = ref[className];
            if (sumMode) {
              if (list["sum"] == null) {
                list["sum"] = {};
              }
              if ((base = list["sum"])[typename] == null) {
                base[typename] = {};
              }
              if ((base1 = list["sum"][typename])[subTypeName] == null) {
                base1[subTypeName] = {
                  count: 0,
                  size: 0
                };
              }
              list["sum"][typename][subTypeName]["count"] += classValue.count;
              list["sum"][typename][subTypeName]["size"] += classValue.size;
            } else {
              if (list[className] == null) {
                list[className] = {};
              }
              if ((base2 = list[className])[typename] == null) {
                base2[typename] = {};
              }
              list[className][typename][subTypeName] = classValue;
            }
          }
        }
      }
    }
    classNamesSorted = Object.keys(list).sort();
    results = [];
    for (j = 0, len = classNamesSorted.length; j < len; j++) {
      className = classNamesSorted[j];
      classValue = list[className];
      results.push((function(_this) {
        return function(className, classValue) {
          return nodes.push(new CUI.ListViewTreeNode({
            html: function(node) {
              var k, l, len1, len2, partialCount, partialSum, ref1, ref2, subType, subTypeValue, typeValue;
              ref1 = ["originals", "versions"];
              for (k = 0, len1 = ref1.length; k < len1; k++) {
                type = ref1[k];
                typeValue = classValue[type];
                partialSum = 0;
                partialCount = 0;
                ref2 = ["latest", "history", "deleted", "sum"];
                for (l = 0, len2 = ref2.length; l < len2; l++) {
                  subType = ref2[l];
                  if (subType === "sum") {
                    node.addColumn(new CUI.ListViewColumn({
                      text: "" + partialCount
                    }));
                    if (!partialSum) {
                      node.addColumn(new CUI.ListViewColumn({
                        text: "0"
                      }));
                    } else {
                      node.addColumn(new CUI.ListViewColumn({
                        text: "" + (ez5.format_filesize(partialSum))
                      }));
                    }
                    continue;
                  }
                  if (!typeValue || !typeValue.hasOwnProperty(subType)) {
                    node.addColumn(new CUI.ListViewColumn({
                      text: "0"
                    }));
                    node.addColumn(new CUI.ListViewColumn({
                      text: "0"
                    }));
                    continue;
                  }
                  subTypeValue = typeValue[subType];
                  if (subTypeValue) {
                    node.addColumn(new CUI.ListViewColumn({
                      text: "" + subTypeValue.count
                    }));
                    if (!subTypeValue.size) {
                      node.addColumn(new CUI.ListViewColumn({
                        text: "0"
                      }));
                    } else {
                      partialSum += subTypeValue.size;
                      node.addColumn(new CUI.ListViewColumn({
                        text: "" + (ez5.format_filesize(subTypeValue.size))
                      }));
                    }
                    if (subTypeValue.count) {
                      partialCount += subTypeValue.count;
                    }
                  } else {
                    node.addColumn(new CUI.ListViewColumn({
                      text: "0"
                    }));
                    node.addColumn(new CUI.ListViewColumn({
                      text: "0"
                    }));
                  }
                }
              }
              if (className === "sum") {
                return new CUI.Label({
                  text: $$("admin.pool.statistics.column.sum")
                });
              } else {
                return new CUI.Label({
                  text: "" + className
                });
              }
            }
          }));
        };
      })(this)(className, classValue));
    }
    return results;
  };

  return StatsTable;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var NewObjectRootMenuApp,
  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;

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

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

  NewObjectRootMenuApp.label = function() {
    return "top.menu.new_objects";
  };

  NewObjectRootMenuApp.group = function() {
    return "aa_main";
  };

  NewObjectRootMenuApp.submenu = function() {
    return "root";
  };

  NewObjectRootMenuApp.isStartApp = function() {
    return false;
  };

  NewObjectRootMenuApp.is_allowed = function() {
    if (!ez5.mask) {
      return false;
    }
    this.otm = new ObjecttypeManager();
    this.otm.addObjecttypes(function(table) {
      return table.inMainSearch();
    });
    return DbInfo.canCreate({
      objecttypes: this.otm.objecttypes
    });
  };

  NewObjectRootMenuApp.is_open = false;

  NewObjectRootMenuApp.getDisplay = function() {
    var button_opts;
    button_opts = NewObjectRootMenuApp.__super__.constructor.getDisplay.call(this);
    button_opts.onConstruct = (function(_this) {
      return function(el) {
        return NewObjectRootMenuApp.btn = el;
      };
    })(this);
    button_opts._no_radio = true;
    return button_opts;
  };

  NewObjectRootMenuApp.click = function() {
    var editor, unload;
    if (this.is_open) {
      return;
    }
    editor = null;
    NewObjectRootMenuApp.btn.activate();
    unload = (function(_this) {
      return function() {
        editor.destroy();
        editor = null;
        _this.is_open = false;
        return NewObjectRootMenuApp.btn.deactivate();
      };
    })(this);
    this.is_open = true;
    editor = new EditorModalNew({
      mode: "new",
      object_list: new ObjectList({
        remove_button_per_object: ez5.version("6"),
        onRemove: (function(_this) {
          return function(object, idx) {
            return editor.__onObjectListRemove(object, idx);
          };
        })(this)
      }),
      onCancel: unload,
      onSaveReadOnly: unload,
      onSave: (function(_this) {
        return function(ed, received_data) {
          var main, ref, ref1, ref2, ref3, ref4, search;
          main = ez5.rootMenu.getActiveApp();
          search = main != null ? typeof main.getSearch === "function" ? main.getSearch() : void 0 : void 0;
          if (ez5.version("6") && (search != null) && ((ref = ez5.session.user) != null ? (ref1 = ref.data) != null ? (ref2 = ref1.user) != null ? (ref3 = ref2.frontend_prefs) != null ? (ref4 = ref3.webfrontend) != null ? ref4.avoid_insert_today : void 0 : void 0 : void 0 : void 0 : void 0)) {
            setTimeout(function() {
              return search.execute();
            }, 1000);
          } else if ((search != null ? search.getElementClass() : void 0) === "SearchMain") {
            search.addCollectionAfterSave(received_data);
          }
          return unload();
        };
      })(this)
    });
    return editor.openEmpty();
  };

  return NewObjectRootMenuApp;

})(RootMenuApp);

ez5.session_ready(function() {
  CUI.Events.listen({
    node: document.body,
    type: ["dragover"],
    instance: this,
    call: (function(_this) {
      return function(ev) {
        ev.stopPropagation();
        ev.preventDefault();
        if (NewObjectRootMenuApp.is_open) {
          return false;
        }
        CUI.FileUpload.setDropClassByEvent(ev);
        return false;
      };
    })(this)
  });
  CUI.Events.listen({
    node: document.body,
    instance: this,
    type: ["drop"],
    call: (function(_this) {
      return function(ev) {
        var dt, file, queueFiles, ref, target;
        if (!NewObjectRootMenuApp.btn) {
          return;
        }
        ev.stopPropagation();
        ev.preventDefault();
        if (NewObjectRootMenuApp.is_open) {
          return false;
        }
        target = ev.getNativeEvent().target;
        if (target.closest(".ez5-detail-container") || target.closest(".ez5-editor")) {
          return false;
        }
        CUI.FileUpload.setDropClassByEvent(ev);
        dt = ev.getNativeEvent().dataTransfer;
        if (!((ref = dt.files) != null ? ref.length : void 0)) {
          return;
        }
        queueFiles = (function() {
          var i, len, ref1, results;
          ref1 = dt.files;
          results = [];
          for (i = 0, len = ref1.length; i < len; i++) {
            file = ref1[i];
            results.push(file);
          }
          return results;
        })();
        NewObjectRootMenuApp.click().done(function(editor) {
          return editor.queueFiles(queueFiles);
        });
        return false;
      };
    })(this)
  });
  CUI.Events.listen({
    node: document.body,
    instance: this,
    type: ["keydown"],
    call: (function(_this) {
      return function(event) {
        if (event.hasModifierKey() && event.code() === "KeyN") {
          event.stopPropagation();
          event.preventDefault();
          NewObjectRootMenuApp.click();
        }
      };
    })(this)
  });
  return ez5.rootMenu.registerApp(NewObjectRootMenuApp);
});
// Generated by CoffeeScript 1.12.7
var Main,
  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;

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

  function Main(opts1) {
    this.opts = opts1;
    Main.__super__.constructor.call(this, this.opts);
    this.search = null;
    this.mode = "long";
  }

  Main.is_allowed = function() {
    return ez5.session.hasSystemRight("root", "search", "search_collection_only");
  };

  Main.group = function() {
    return "aa_main";
  };

  Main.path = function() {
    return ["search"];
  };

  Main.label = function() {
    return "top.menu.main";
  };

  Main.prototype.load = function(path) {
    var loading;
    Main.__super__.load.call(this);
    if (!path[0]) {
      if (document.location.hash === "") {
        this.replaceState();
      } else {
        path = document.location.hash.split("/");
        this.pushState(path);
      }
    }
    console.time("Main.load");
    loading = this.loadLayout();
    ez5.rootLayout.replace(this.mainLayout, "center");
    console.timeLog("Main.load", "loadLayout appended to rootLayout");
    loading.always((function(_this) {
      return function() {
        return console.timeEnd("Main.load");
      };
    })(this));
    return loading;
  };

  Main.prototype.allow_unload = function() {
    if (!this.sidebar) {
      return CUI.resolvedPromise();
    } else {
      return this.sidebar.allow_unload();
    }
  };

  Main.prototype.update_path = function(path) {
    return this.search.update_path(path);
  };

  Main.prototype.destroy = function() {
    delete Main.__loadingLayout;
    return Main.__super__.destroy.call(this);
  };

  Main.prototype.unload = function() {
    var dfr;
    dfr = new CUI.Deferred();
    Main.__super__.unload.call(this).done((function(_this) {
      return function() {
        var ref, ref1, ref2, ref3;
        delete Main.__loadingLayout;
        if ((ref = _this.search) != null) {
          ref.destroy();
        }
        if ((ref1 = _this.cm) != null) {
          ref1.destroy();
        }
        if ((ref2 = _this.sidebar) != null) {
          ref2.destroy();
        }
        if ((ref3 = _this.mainLayout) != null) {
          ref3.destroy();
        }
        delete _this.search;
        delete _this.cm;
        delete _this.sidebar;
        delete _this.mainLayout;
        ez5.rootLayout.empty("center");
        return dfr.resolve();
      };
    })(this));
    return dfr.promise();
  };

  Main.prototype.loadLayout = function() {
    var flexHandle;
    this.searchLayout = new CUI.HorizontalLayout({
      "class": "ez5-main-layout-search",
      left: {
        "class": "ez5-main-collection",
        flexHandle: {
          hidden: false,
          state_name: "main-collection-split"
        }
      },
      center: {
        "class": "ez5-main-search"
      }
    });
    this.mainLayout = new CUI.HorizontalLayout({
      "class": "ez5-main-layout ez5-finder ez5-event-poller",
      absolute: false,
      left: {
        "class": "ez5-main-left",
        flexHandle: {
          "class": "ez5-main-left-flex-handle",
          label: {
            loca_key: "collection.manager.title",
            icon: "right",
            tooltip: {
              text: $$("collection.manager.title|text")
            }
          },
          state_name: "main-finder",
          closable: true,
          hidden: false
        }
      },
      right: {
        "class": "ez5-main-right",
        flexHandle: {
          label: {
            text: ""
          },
          hidden: false,
          closable: false,
          state_name: "main-sidebar",
          closed: true
        }
      },
      center: {
        "class": "ez5-main-center",
        content: this.searchLayout
      }
    });
    this.sidebar = new Sidebar({
      mainLayout: this.mainLayout,
      getSearch: (function(_this) {
        return function() {
          return _this.search;
        };
      })(this)
    });
    this.cm = this.getCollectionManager({
      mainLayout: this.mainLayout,
      detailDiv: this.searchLayout.left(),
      sidebar: this.sidebar,
      preventBlurOnSelect: true,
      onRender: (function(_this) {
        return function() {
          if (!_this.cm) {
            return;
          }
          if (_this.cm.hasContent()) {
            if (!ez5.session.getPref("quick_access_open")) {
              return flexHandle.close();
            } else {
              return _this.mainLayout.show("left");
            }
          } else {
            return flexHandle.hide();
          }
        };
      })(this)
    });
    this.mainLayout.hide("left");
    flexHandle = this.mainLayout.getFlexHandle("left");
    CUI.Events.listen({
      node: flexHandle.getPane(),
      type: "flex-close",
      call: (function(_this) {
        return function() {
          ez5.session.savePref("quick_access_open", false);
        };
      })(this)
    });
    CUI.Events.listen({
      node: flexHandle.getHandle(),
      type: "click",
      call: (function(_this) {
        return function() {
          ez5.session.savePref("quick_access_open", true);
        };
      })(this)
    });
    this.mainLayout.replace(this.cm.render(), "left");
    return this.loadSearch();
  };

  Main.prototype.getCollectionManager = function(opts) {
    return new CollectionManager(opts);
  };

  Main.prototype.loadSearch = function() {
    var sel_col;
    sel_col = this.cm.getCollectionSelection();
    this.search = new SearchMain({
      container: this.searchLayout.center(),
      collection: sel_col,
      collectionManager: this.cm
    });
    this.cm.setSearch(this.search);
    return this.search.init().done((function(_this) {
      return function() {
        return _this.loadDeepLink(sel_col).done(function() {
          return _this.cm.loadSearch();
        });
      };
    })(this));
  };

  Main.prototype.getSearch = function() {
    return this.search;
  };

  Main.prototype.loadDeepLink = function(sel_col) {
    var globalObjectId, loadPromise, uuid;
    globalObjectId = Main.getGlobalObjectIdFromLocation(document.location);
    if (globalObjectId) {
      loadPromise = ResultObject.loadFromGlobalObjectId(globalObjectId, "short", null, true, false, TrashSearchManager.canSeeDeleted());
    } else {
      uuid = Main.getUUIDFromLocation(document.location);
      if (!uuid) {
        return CUI.resolvedPromise();
      }
      loadPromise = ResultObject.loadFromUUID(uuid, "standard", null, true, false);
    }
    loadPromise.done((function(_this) {
      return function(ro) {
        var ref;
        _this.sidebar.showSidebar();
        _this.search.showInSearch(new QueryElementSystemObjectId({
          system_object_id: "" + (ro.getSystemObjectId())
        }));
        if (((ref = _this.search.getWelcomeSearchMessages()) != null ? ref.length : void 0) > 0) {
          _this.sidebar.loadDetail({
            global_object_id: ro.getGlobalObjectId()
          });
        }
        return sel_col.insertObjects([ro.getCollectionObject()]);
      };
    })(this));
    return loadPromise;
  };

  Main.getGlobalObjectIdFromLocation = function(location) {
    var id, match;
    match = location.pathname.match("^\/(?:detail|lists/.+|trash/.+)/([1-9][0-9]*(?:|@[a-z0-9\-]{36}))$");
    if (!match) {
      match = location.hash.match("^#\/?(?:detail|lists/.+|trash/.+)/([1-9][0-9]*(?:|@[a-z0-9\-]{36}))$");
      if (!match) {
        return null;
      }
    }
    id = match[1];
    if (!id.match(/@/)) {
      id = id + "@" + ez5.session.getInstance().name;
    }
    return id;
  };

  Main.getUUIDFromLocation = function(location) {
    var match;
    match = location.hash.match("^#\/?(?:detail|lists/.+|trash/.+)/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$");
    if (!match) {
      return null;
    }
    return match[1];
  };

  return Main;

})(RootMenuApp);

ez5.session_ready(function() {
  return ez5.rootMenu.registerApp(Main);
});
// Generated by CoffeeScript 1.12.7
var DetailDeepLink,
  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;

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

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

  DetailDeepLink.askLogin = function(key_prefix) {
    var anon, dfr;
    if (ez5.session.getAuthMethod() === "anonymous") {
      anon = ".anonymous";
    } else {
      anon = "";
    }
    dfr = new CUI.Deferred();
    CUI.choice({
      text: $$(key_prefix + anon),
      choices: [
        {
          text: $$(key_prefix + ".button.cancel"),
          _choice: "cancel"
        }, {
          text: $$(key_prefix + ".button.login"),
          _choice: "login",
          primary: true
        }
      ]
    }).done((function(_this) {
      return function(choice) {
        if (choice._choice === "cancel") {
          dfr.reject();
        } else {
          ez5.session.loginAgain(false).done(function() {
            return ez5.start.loadApps().fail(dfr.reject).done(dfr.resolve);
          }).fail(function() {
            return _this.askLogin(key_prefix);
          });
        }
      };
    })(this));
    return dfr.promise();
  };

  DetailDeepLink.prototype.findAppByLocation = function(location, apps) {
    var dfr, globalObjectId, load_app, load_object, uuid;
    if (location.pathname.match("^" + window.easydb_base_prefix + "/lists") || location.pathname.match("^" + window.easydb_base_prefix + "/trash")) {
      return CUI.rejectedPromise();
    }
    globalObjectId = Main.getGlobalObjectIdFromLocation(location);
    if (!globalObjectId) {
      uuid = Main.getUUIDFromLocation(location);
      if (!uuid) {
        return CUI.rejectedPromise();
      }
    }
    dfr = new CUI.Deferred();
    load_object = (function(_this) {
      return function() {
        var promise;
        if (globalObjectId) {
          promise = ResultObject.loadFromGlobalObjectId(globalObjectId, "short", null, true, false);
        } else {
          promise = ResultObject.loadFromUUID(uuid, "short", null, true, false, TrashSearchManager.canSeeDeleted());
        }
        promise.done(function(ro) {
          var ref, ref1, ref2, sid;
          if (ro.getMask().inMainSearch() && !((ref = location.hash) != null ? ref.includes("lists/") : void 0) && !((ref1 = location.hash) != null ? ref1.includes("trash/") : void 0)) {
            return load_app("/search");
          } else if ((ref2 = location.hash) != null ? ref2.includes("trash/") : void 0) {
            if (!globalObjectId) {
              globalObjectId = ro.getGlobalObjectId();
            }
            sid = globalObjectId.match(/(.*)@/)[1];
            window.history.replaceState({}, null, window.easydb_base_prefix + "/trash/" + ro.getMask().getTable().name() + "/" + sid);
            load_app("/trash");
          } else {
            if (!globalObjectId) {
              globalObjectId = ro.getGlobalObjectId();
            }
            sid = globalObjectId.match(/(.*)@/)[1];
            window.history.replaceState({}, null, window.easydb_base_prefix + "/lists/" + ro.getMask().getTable().name() + "/" + sid);
            dfr.reject();
          }
        });
        return promise.fail(function() {
          return DetailDeepLink.askLogin("main.deep_link_needs_login").done(function() {
            return load_object();
          }).fail(dfr.reject);
        });
      };
    })(this);
    load_app = (function(_this) {
      return function(pathname) {
        var app, i, len;
        for (i = 0, len = apps.length; i < len; i++) {
          app = apps[i];
          if ((typeof app.getPathname === "function" ? app.getPathname() : void 0) === pathname) {
            return dfr.resolve(app);
          }
        }
        return dfr.reject();
      };
    })(this);
    load_object();
    return dfr.promise();
  };

  return DetailDeepLink;

})(RootMenuAppLoader);

ez5.session_ready(function() {
  return ez5.rootMenu.registerAppLoader(new DetailDeepLink());
});
// Generated by CoffeeScript 1.12.7
var Sidebar,
  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;

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

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

  Sidebar.prototype.initOpts = function() {
    Sidebar.__super__.initOpts.call(this);
    return this.addOpts({
      getSearch: {
        check: Function
      },
      mainLayout: {
        mandatory: true,
        check: CUI.HorizontalLayout
      },
      detailSidebarClass: {
        "default": DetailSidebar
      },
      collection: {
        check: CollectionWithDetail,
        mandatory: false
      }
    });
  };

  Sidebar.prototype.readOpts = function() {
    Sidebar.__super__.readOpts.call(this);
    this.__flexHandle = this._mainLayout.getFlexHandle("right");
    this.__waitBlock = new CUI.WaitBlock({
      ui: "sidebar.wait.block",
      element: this._mainLayout.right()
    });
    this.hideSidebar();
    return this.empty();
  };

  Sidebar.prototype.updateAssetBrowserIdx = function(asset_browser_idx) {
    var ref;
    return (ref = this.detail) != null ? ref.updateAssetBrowserIdx(asset_browser_idx) : void 0;
  };

  Sidebar.prototype.loadCollectionObject = function(_opts) {
    var opts;
    if (_opts == null) {
      _opts = {};
    }
    opts = CUI.Element.readOpts(_opts, "Sidebar.loadCollectionObject", {
      global_object_id: {
        mandatory: true,
        check: String
      },
      read_only: {
        check: Boolean
      },
      search: {
        check: Search
      },
      offset: {
        check: function(v) {
          return v >= 0;
        }
      },
      asset_browser_idx: {
        check: "Integer"
      },
      next_previous_global_object_ids: {
        check: Array
      }
    });
    if (this.getLoadedGlobalObjectId() === opts.global_object_id) {
      return;
    }
    if (this.__last_loaded === "editor" && opts.read_only !== true) {
      return this.loadEditor(opts);
    } else {
      return this.loadDetail(opts);
    }
  };

  Sidebar.prototype.__pushState = function(sidebarContent, opts) {
    var url;
    if (opts.push_state === false) {
      return;
    }
    url = DetailSidebar.getDetailShareUrl(sidebarContent.object, sidebarContent.getSearch());
    if (url && sidebarContent.object && location.href.endsWith("" + (sidebarContent.object.getSystemObjectId()))) {
      url = url.replace(/detail.*/, "detail/" + (sidebarContent.object.getSystemObjectId()));
    }
    if (url) {
      return window.history.pushState({}, null, url);
    }
  };

  Sidebar.prototype.loadDetail = function(opts) {
    var detailContainer, loading_failed, mainDiv, nextPreviousGlobalObjectIds, ref, ref1, updateTimeout;
    if (this.isEmpty() || this.__last_loaded === "editor") {
      this.__waitBlock.show();
    }
    loading_failed = (function(_this) {
      return function(opts) {
        var ref;
        if (opts == null) {
          opts = {};
        }
        if (opts.cancelled) {
          return;
        }
        if ((ref = _this.detail) != null) {
          ref.destroy();
        }
        _this.detail = null;
        return _this.empty();
      };
    })(this);
    this.__is_empty = false;
    this.__loaded_gid = opts.global_object_id;
    if (!opts.next_previous_global_object_ids) {
      nextPreviousGlobalObjectIds = (ref = opts.search) != null ? (ref1 = ref.getLastData()) != null ? ref1.objects.map(function(object) {
        return object._global_object_id;
      }) : void 0 : void 0;
    }
    if (this.__last_loaded === "detail" && this.detail && this.detail.canUpdate()) {
      detailContainer = this.detail.getContainer();
      updateTimeout = CUI.setTimeout({
        ms: 200,
        call: (function(_this) {
          return function() {
            return _this.__waitBlock.show();
          };
        })(this)
      });
      return this.detail.update({
        global_object_id: opts.global_object_id,
        offset: opts.offset,
        search: opts.search,
        asset_browser_idx: opts.asset_browser_idx,
        next_previous_global_object_ids: opts.next_previous_global_object_ids || nextPreviousGlobalObjectIds
      }).always((function(_this) {
        return function() {
          CUI.clearTimeout(updateTimeout);
          return _this.__waitBlock.hide();
        };
      })(this)).fail(loading_failed).done((function(_this) {
        return function() {
          return _this.__pushState(_this.detail, opts);
        };
      })(this));
    }
    this.__last_loaded = "detail";
    if (this.editor) {
      this.editor.destroy();
      this.editor = null;
    }
    if (this.detail) {
      this.detail.destroy();
      this.detail = null;
    }
    this.detail = new this._detailSidebarClass({
      global_object_id: opts.global_object_id,
      asset_browser_idx: opts.asset_browser_idx,
      offset: opts.offset,
      sidebar: this,
      search: opts.search,
      next_previous_global_object_ids: opts.next_previous_global_object_ids || nextPreviousGlobalObjectIds,
      wait_for_index: opts.wait_for_index
    });
    mainDiv = this.detail.render();
    this.__showLoading();
    return this.detail.load().always((function(_this) {
      return function() {
        _this.__waitBlock.hide();
        return _this.__unshowLoading();
      };
    })(this)).fail(loading_failed).done((function(_this) {
      return function() {
        _this.__pushState(_this.detail, opts);
        return _this._mainLayout.replace(mainDiv, "right");
      };
    })(this));
  };

  Sidebar.prototype.__showLoading = function() {
    if (this._mainLayout.isDestroyed()) {
      return;
    }
    return CUI.dom.addClass(this._mainLayout.right(), "ez5-sidebar-is-loading");
  };

  Sidebar.prototype.__unshowLoading = function() {
    if (this._mainLayout.isDestroyed()) {
      return;
    }
    return CUI.dom.removeClass(this._mainLayout.right(), "ez5-sidebar-is-loading");
  };

  Sidebar.prototype.allow_unload = function() {
    var dfr;
    dfr = new CUI.Deferred();
    if (this.editor) {
      this.editor.doClose().done(dfr.resolve).fail(dfr.reject);
    } else {
      dfr.resolve();
    }
    return dfr.promise();
  };

  Sidebar.prototype.getLoadedGlobalObjectId = function() {
    return this.__loaded_gid;
  };

  Sidebar.prototype.destroy = function() {
    var ref, ref1;
    if ((ref = this.detail) != null) {
      ref.destroy();
    }
    if ((ref1 = this.editor) != null) {
      ref1.destroy();
    }
    delete this.detail;
    delete this.editor;
    return Sidebar.__super__.destroy.call(this);
  };

  Sidebar.prototype.loadEditor = function(_opts) {
    var copySkipFields, destroyEditor, editor, mainDiv, mode, nextPreviousGlobalObjectIds, opts, ref, ref1;
    if (ez5.session.isReadOnly()) {
      CUI.alert({
        text: $$("base.error.user.read_only_mode")
      });
      return;
    }
    this.__last_loaded = "editor";
    this.__waitBlock.show();
    destroyEditor = (function(_this) {
      return function() {
        if (_this.editor) {
          _this.editor.destroy();
          return _this.editor = null;
        }
      };
    })(this);
    if (this.detail && this.detail.object) {
      ez5.maskMemoryManager.storeMask(this.detail.object.objecttype(), this.detail.detail_data.mask_name, "detail");
    }
    if (this.detail) {
      this.detail.destroy();
      this.detail = null;
    }
    this.__is_empty = false;
    opts = CUI.Element.readOpts(_opts, "Sidebar.loadEditor", {
      table_id: {
        check: "Integer"
      },
      parent_id: {
        check: "Integer"
      },
      offset: {
        check: "Integer"
      },
      search: {
        check: Search
      },
      read_only: {
        check: Boolean
      },
      copy: {
        "default": false,
        check: Boolean
      },
      copyMask: {
        check: String
      },
      copySkipFields: {
        check: "Array",
        "default": []
      },
      global_object_id: {
        check: String
      },
      asset_browser_idx: {
        check: "Integer"
      },
      next_previous_global_object_ids: {
        check: Array
      },
      fullscreen: {
        check: Boolean,
        "default": false
      }
    });
    copySkipFields = null;
    if (opts.global_object_id) {
      if (opts.copy) {
        mode = "copy";
        copySkipFields = opts.copySkipFields;
        this.__loaded_gid = null;
      } else {
        mode = "single";
        this.__loaded_gid = opts.global_object_id;
      }
    } else {
      this.__loaded_gid = null;
      mode = "new";
    }
    if (!opts.next_previous_global_object_ids) {
      nextPreviousGlobalObjectIds = (ref = opts.search) != null ? (ref1 = ref.getLastData()) != null ? ref1.objects.map(function(object) {
        return object._global_object_id;
      }) : void 0 : void 0;
    }
    editor = new EditorSidebar({
      global_object_id: opts.global_object_id,
      table_id: opts.table_id,
      parent_id: opts.parent_id,
      asset_browser_idx: opts.asset_browser_idx,
      mode: mode,
      copySkipFields: copySkipFields,
      copyMask: opts.copyMask,
      sidebar: this,
      next_previous_global_object_ids: opts.next_previous_global_object_ids || nextPreviousGlobalObjectIds,
      onCancel: (function(_this) {
        return function() {
          destroyEditor();
          _this.empty();
          return _this.hideSidebar();
        };
      })(this),
      onCloseEditor: (function(_this) {
        return function() {
          if (editor && editor.object) {
            ez5.maskMemoryManager.storeMask(editor.object.objecttype(), editor.editor_data.mask_name, "editor");
          }
          destroyEditor();
          if (_this.__loaded_gid) {
            _this.loadDetail({
              global_object_id: _this.__loaded_gid,
              next_previous_global_object_ids: opts.next_previous_global_object_ids || nextPreviousGlobalObjectIds
            });
          } else {
            _this.hideSidebar();
          }
        };
      })(this),
      onDelete: (function(_this) {
        return function() {
          destroyEditor();
          return _this.empty();
        };
      })(this),
      onCopy: (function(_this) {
        return function(_, opts) {
          if (opts == null) {
            opts = {};
          }
          return _this.loadEditor({
            global_object_id: _this.__loaded_gid,
            copy: true,
            search: _this.getSearch(),
            copyMask: editor.editor_data.mask_name,
            copySkipFields: opts.copySkipFields,
            fullscreen: _this.editor.__openFullScreenAfterCopy
          });
        };
      })(this),
      onCreateNewChild: (function(_this) {
        return function() {
          return _this.loadEditor({
            table_id: editor.object.getMask().getTable().id(),
            parent_id: editor.object.getId()
          });
        };
      })(this),
      onSaveReadOnly: (function(_this) {
        return function(editor, received_data) {
          var gid, ref2, ref3, ref4, ref5, ref6, ref7, wait_for_index;
          wait_for_index = false;
          if (_this.editor.getMode() === "new") {
            wait_for_index = true;
          }
          destroyEditor();
          gid = received_data[0]._global_object_id;
          if (ez5.version("6") && _this.editor.getMode() === "new" && (opts.search != null) && ((ref2 = ez5.session.user) != null ? (ref3 = ref2.data) != null ? (ref4 = ref3.user) != null ? (ref5 = ref4.frontend_prefs) != null ? (ref6 = ref5.webfrontend) != null ? ref6.avoid_insert_today : void 0 : void 0 : void 0 : void 0 : void 0)) {
            setTimeout(function() {
              return opts.search.execute();
            }, 1000);
          } else {
            if ((ref7 = opts.search) != null) {
              ref7.addCollectionAfterSave(received_data);
            }
          }
          return _this.loadDetail({
            global_object_id: gid,
            wait_for_index: wait_for_index
          });
        };
      })(this),
      onSave: (function(_this) {
        return function(editor, received_data) {
          var ref2, ref3, ref4, ref5, ref6, ref7;
          if (ez5.version("6") && _this.editor.getMode() === "new" && (opts.search != null) && ((ref2 = ez5.session.user) != null ? (ref3 = ref2.data) != null ? (ref4 = ref3.user) != null ? (ref5 = ref4.frontend_prefs) != null ? (ref6 = ref5.webfrontend) != null ? ref6.avoid_insert_today : void 0 : void 0 : void 0 : void 0 : void 0)) {
            setTimeout(function() {
              return opts.search.execute();
            }, 1000);
          } else {
            if ((ref7 = opts.search) != null) {
              ref7.addCollectionAfterSave(received_data);
            }
          }
          if (_this.editor.getMode() === "new") {
            _this.editor.setMode("single");
            _this.__loaded_gid = received_data[0]._global_object_id;
          }
          return _this.editor.load();
        };
      })(this),
      onSaveAndNew: (function(_this) {
        return function(editor, received_data) {
          var ref2, ref3, ref4, ref5, ref6, ref7;
          if (ez5.version("6") && (opts.search != null) && ((ref2 = ez5.session.user) != null ? (ref3 = ref2.data) != null ? (ref4 = ref3.user) != null ? (ref5 = ref4.frontend_prefs) != null ? (ref6 = ref5.webfrontend) != null ? ref6.avoid_insert_today : void 0 : void 0 : void 0 : void 0 : void 0)) {
            setTimeout(function() {
              return opts.search.execute();
            }, 1000);
          } else {
            if ((ref7 = opts.search) != null) {
              ref7.addCollectionAfterSave(received_data);
            }
          }
          return _this.loadEditor({
            table_id: _this.editor.editor_data.table.id(),
            search: opts.search
          });
        };
      })(this)
    });
    this.__showLoading();
    mainDiv = editor.render();
    return editor.load().always((function(_this) {
      return function() {
        _this.__waitBlock.hide();
        return _this.__unshowLoading();
      };
    })(this)).fail((function(_this) {
      return function() {
        if (editor != null) {
          editor.destroy();
        }
        editor = null;
        _this.empty();
        if (opts.global_object_id) {
          return _this.loadDetail({
            global_object_id: opts.global_object_id
          });
        } else {
          return _this.hideSidebar();
        }
      };
    })(this)).done((function(_this) {
      return function() {
        destroyEditor();
        _this.editor = editor;
        _this.__pushState(_this.editor, opts);
        _this._mainLayout.replace(mainDiv, "right");
        if (opts.fullscreen) {
          return _this.editor.openFullScreen();
        }
      };
    })(this));
  };

  Sidebar.prototype.getCloseButton = function() {
    return new LocaButton({
      icon: "close",
      loca_key: "base.help.flex_handle.hide",
      onClick: (function(_this) {
        return function(ev, df) {
          return _this.hideSidebar();
        };
      })(this)
    });
  };

  Sidebar.prototype.__setLabel = function(label) {
    var ref, ref1;
    return (ref = this.__flexHandle) != null ? (ref1 = ref.getLabel()) != null ? ref1.setText($$("sidebar.label." + label)) : void 0 : void 0;
  };

  Sidebar.prototype.getSearch = function() {
    CUI.util.assert(this._mainLayout, "Sidebar.getSearch", "MainLayout not set.");
    return typeof this._getSearch === "function" ? this._getSearch() : void 0;
  };

  Sidebar.prototype.resetState = function() {
    var ref, url;
    url = (ref = this.getSearch()) != null ? typeof ref.getSharePath === "function" ? ref.getSharePath() : void 0 : void 0;
    if (url && url !== document.location.pathname) {
      window.history.pushState({}, null, url);
    }
    return this;
  };

  Sidebar.prototype.empty = function() {
    this.__is_empty = true;
    this.__loaded_gid = null;
    this.resetState();
    this.__setLabel("empty");
    if (!this._mainLayout.isDestroyed()) {
      this.__waitBlock.hide();
      this._mainLayout.replace(new CUI.SimplePane({
        "class": "cui-pane--window",
        header_left: (function(_this) {
          return function() {
            return new CUI.Label({
              text: $$("sidebar.label.empty")
            });
          };
        })(this),
        header_right: (function(_this) {
          return function() {
            return _this.getCloseButton();
          };
        })(this),
        content: new CUI.EmptyLabel({
          centered: true,
          icon: $$("main.sidebar.empty.icon"),
          text: $$("main.sidebar.empty.hint")
        })
      }), "right");
    }
    return this;
  };

  Sidebar.prototype.getMainLayout = function() {
    return this._mainLayout;
  };

  Sidebar.prototype.hideSidebar = function() {
    var ref;
    this.resetState();
    if ((ref = this.__flexHandle) != null) {
      ref.close().hide();
    }
    return this;
  };

  Sidebar.prototype.hideSidebarWithWarning = function() {
    var dfr;
    dfr = new CUI.Deferred();
    if (this.editor) {
      this.allow_unload().done((function(_this) {
        return function() {
          _this.editor.destroy();
          delete _this.editor;
          _this.hideSidebar();
          return dfr.resolve();
        };
      })(this)).fail((function(_this) {
        return function() {
          return dfr.reject();
        };
      })(this));
    } else {
      this.hideSidebar();
      dfr.resolve();
    }
    return dfr.promise();
  };

  Sidebar.prototype.showSidebar = function() {
    this.__flexHandle.open().show();
    return this;
  };

  Sidebar.prototype.scrollLoadedObjectIntoView = function() {
    var rc, ref, scroll_el;
    if (!this.__loaded_gid) {
      return;
    }
    rc = (ref = this.getSearch()) != null ? ref.getResultContainer() : void 0;
    if (rc) {
      scroll_el = CUI.dom.matchSelector(rc, "[global-object-id='" + this.__loaded_gid + "']")[0];
      CUI.dom.scrollIntoView(scroll_el);
    }
    return this;
  };

  Sidebar.prototype.isShown = function() {
    return this.__flexHandle.isOpen();
  };

  Sidebar.prototype.isEmpty = function() {
    return this.__is_empty;
  };

  Sidebar.getCopyTool = function(object, onRun, toolOpts) {
    var copySkipFields, copyTool, defaultToolOpts, hasReverseLinked, toolName, tools;
    if (toolOpts == null) {
      toolOpts = {};
    }
    defaultToolOpts = {
      name: "editor.copy",
      loca_key: "tool.editor.copy",
      run: (function(_this) {
        return function() {
          if (hasReverseLinked) {
            return;
          }
          return onRun({});
        };
      })(this)
    };
    CUI.util.mergeMap(toolOpts, defaultToolOpts);
    copySkipFields = [];
    object.mask.getFields("editor").forEach(function(field) {
      if (field instanceof ReverseLinkedTable) {
        copySkipFields.push(field.fullName());
      }
    });
    hasReverseLinked = copySkipFields.length > 0;
    tools = [];
    if (hasReverseLinked) {
      tools.push(new ToolboxTool({
        name: toolOpts.name + ".with-reverse",
        loca_key: toolOpts.loca_key + ".with-reverse",
        run: (function(_this) {
          return function() {
            return onRun({
              toolName: toolOpts.name + ".with-reverse"
            });
          };
        })(this)
      }));
    }
    toolName = hasReverseLinked ? toolOpts.name + ".skip-reverse" : "" + toolOpts.name;
    tools.push(new ToolboxTool({
      name: toolName,
      loca_key: hasReverseLinked ? toolOpts.loca_key + ".skip-reverse" : "" + toolOpts.loca_key,
      run: (function(_this) {
        return function() {
          return onRun({
            copySkipFields: copySkipFields,
            toolName: toolName
          });
        };
      })(this)
    }));
    tools.push(new ToolboxTool({
      name: "object.copy.adhoc_template",
      run: (function(_this) {
        return function() {
          return onRun({
            copyAsTemplate: true,
            toolName: "object.copy.adhoc_template"
          });
        };
      })(this)
    }));
    toolOpts.tools = tools;
    copyTool = new ToolboxTool(toolOpts);
    return copyTool;
  };

  return Sidebar;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var UserManager,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  UserManager.is_allowed = function() {
    if (ez5.session.hasSystemRight("root")) {
      return true;
    }
    if (ez5.session.hasSystemRight("user") && !ez5.session.hasSystemRight("user[hide_frontend_app]")) {
      return true;
    }
    return false;
  };

  UserManager.group = function() {
    return "rightsmanagement";
  };

  UserManager.label = function() {
    return "admin.menu.user";
  };

  UserManager.submenu = function() {
    return "rightsmanagement";
  };

  UserManager.path = function() {
    return ["usermanager"];
  };

  UserManager.prototype.load = function() {
    var firstColumn;
    if (!this.__sortableFieldsMap) {
      this.__sortableFieldsMap = {
        id: "_id",
        name: "_generated_displayname"
      };
    }
    firstColumn = this.__filter_data.columns[0];
    if (this.__sortableFieldsMap[firstColumn]) {
      firstColumn = this.__sortableFieldsMap[firstColumn];
    }
    this.__sortField = "user." + firstColumn;
    this.__sortOrder = "ASC";
    return UserManager.__super__.load.call(this);
  };

  UserManager.prototype.hideFieldsByConfig = function(fields) {
    if (ez5.version("6")) {
      fields = fields.filter((function(_this) {
        return function(f) {
          return !User.fieldHidden(f);
        };
      })(this));
    }
    return fields;
  };

  UserManager.prototype.initFilterData = function() {
    var column, columns, i, len;
    if (ez5.version("6")) {
      this._valid_columns = this.hideFieldsByConfig(["name", "login", "first_name", "last_name", "_last_seen_at", "company", "department", "town", "state", "country", "type", "id"]);
    } else {
      this._valid_columns = ["name", "login", "first_name", "last_name", "company", "department", "type", "id"];
    }
    if (this.__filter_data) {
      this.__filter_data.search = "";
      return;
    }
    columns = ez5.session.getPref("usermanager-columns") || [];
    for (i = 0, len = columns.length; i < len; i++) {
      column = columns[i];
      if (indexOf.call(this._valid_columns, column) < 0) {
        columns.splice(columns.indexOf(column), 1);
      }
    }
    if (CUI.util.isEmpty(columns)) {
      columns = this.hideFieldsByConfig(["name", "login", "type", "id"]);
    }
    this.__filter_data = {
      search: "",
      types: [],
      columns: columns,
      not_groups: false,
      login_disabled: null,
      custom_group_ids: [],
      __group_ids: []
    };
  };

  UserManager.prototype.getColumns = function() {
    return this.__filter_data.columns.concat();
  };

  UserManager.prototype.getMissingName = function() {
    return $$("admin.user.missing.name");
  };

  UserManager.prototype.getLeftTitle = function() {
    return $$("admin.user.pane.left.title");
  };

  UserManager.prototype.getCenterTitle = function() {
    return $$("admin.user.pane.center.title");
  };

  UserManager.prototype.getNavigationLocaKeyPrefix = function() {
    return "result.navigation.toolbar.user";
  };

  UserManager.prototype.getNoRecordLocaKey = function() {
    return $$("result.navigation.toolbar.user.no_user");
  };

  UserManager.prototype.getListFields = function() {
    var column, i, len, listFields, ref;
    listFields = [];
    ref = this.__filter_data.columns;
    for (i = 0, len = ref.length; i < len; i++) {
      column = ref[i];
      listFields.push({
        th_label: "admin.user.list." + column,
        sortable: {
          key: "user." + (this.__sortableFieldsMap[column] || column)
        }
      });
    }
    listFields[0].sortable.order = this.__sortOrder;
    return listFields;
  };

  UserManager.prototype.getPlusButton = function() {
    var ref;
    if (((ref = ez5.session.getSystemRight("user")) != null ? ref.create : void 0) || ez5.session.hasSystemRight("root")) {
      return UserManager.__super__.getPlusButton.call(this);
    } else {

    }
  };

  UserManager.prototype.getExtraButton = function() {
    return new LocaButton({
      loca_key: "user.manager.button.extra",
      group: "plus-minus",
      menu: {
        items: [
          {
            loca_key: "user.manager.extra.download_csv",
            onClick: (function(_this) {
              return function() {
                return _this.showCSVExport();
              };
            })(this)
          }, {
            loca_key: "user.manager.extra.upload_csv",
            onClick: (function(_this) {
              return function() {
                return _this.showCSVImport().done(function() {
                  return _this.loadFilter();
                });
              };
            })(this)
          }
        ]
      }
    });
  };

  UserManager.prototype.showCSVImport = function() {
    return new UserCSVImporter().start();
  };

  UserManager.prototype.showCSVExport = function() {
    return new UserCSVExporter({
      userManager: this
    }).start();
  };

  UserManager.prototype.addRow = function() {
    var new_node;
    new_node = new ez5.defaults["class"].User({
      manager: this
    });
    return this.tree.addNode(new_node).done((function(_this) {
      return function() {
        return new_node.select().fail(function() {
          return new_node["delete"]();
        }).done(function() {
          return new_node.scrollIntoView();
        });
      };
    })(this));
  };

  UserManager.prototype.getTreeOpts = function() {
    var opts;
    opts = UserManager.__super__.getTreeOpts.call(this);
    opts.onSort = (function(_this) {
      return function(key, order) {
        if (ez5.version("6.8")) {
          if (key === "user._last_seen_at") {
            key = "_last_seen_at";
          }
        }
        _this.__sortField = key;
        _this.__sortOrder = order;
        _this.loadTree(true);
      };
    })(this);
    opts.filterManager = (function(_this) {
      return function() {
        var aclm, custom_groups, fields, filter_form, input, lay;
        input = ListViewEditTree.getFilterManager(function(filter) {
          _this.__filter_data.search = filter;
          return _this.loadFilter();
        });
        fields = null;
        aclm = new AclWhoManager({
          store_full_data: true,
          name: "custom_group",
          filter_groups: ["system", "easydb"],
          who_filter: ["group"]
        });
        custom_groups = [];
        filter_form = new CUI.FormPopover({
          data: _this.__filter_data,
          fields: function() {
            var c, columnOptions, columnsField, fc, filterColumns, filterColumnsOptions, i, j, k, l, len, len1, len2, len3, login_disabled_opts, m, ref, ref1, ref2, searchColumns, term;
            if (!_this.data) {
              return [];
            }
            if (!fields) {
              fields = [];
              opts = [];
              ref = _this.data.aggregations._users.terms;
              for (i = 0, len = ref.length; i < len; i++) {
                term = ref[i];
                opts.push({
                  text: term.term,
                  value: term.term
                });
              }
              opts.sort(function(a, b) {
                return CUI.util.compareIndex(a.text, b.text);
              });
              fields.push({
                form: {
                  label: $$("user.manager.filter.types")
                },
                type: CUI.Options,
                horizontal: false,
                name: "types",
                undo_and_changed_support: false,
                options: opts
              });
              fields.push.apply(fields, Group.getGroupFields(["easydb"]));
              fields.push({
                type: CUI.Checkbox,
                text: $$("user.manager.filter.not_groups"),
                name: "not_groups",
                options: custom_groups
              });
              fields.push({
                type: UserGroupSelector,
                aclWhoManager: aclm,
                name: "custom_group",
                form: {
                  label: $$("user.manager.filter.custom_groups.label")
                },
                onDataChanged: function(data, field) {
                  var group, group_data, group_id;
                  group_data = data["custom_group"];
                  if (!group_data) {
                    return;
                  }
                  field.setValue();
                  group = Group.newInstance({
                    group: group_data
                  });
                  group_id = group.getId();
                  if (CUI.util.idxInArray(null, custom_groups, (function(v) {
                    return v.value === group_id;
                  })) === -1) {
                    custom_groups.push({
                      value: group.getId(),
                      text: group.getDisplayText()
                    });
                  }
                  CUI.util.pushOntoArray(group_id, _this.__filter_data.custom_group_ids);
                  return filter_form.getFieldsByName("custom_group_ids")[0].reload();
                }
              });
              fields.push({
                type: CUI.Options,
                placeholder: "",
                name: "custom_group_ids",
                options: custom_groups
              });
              if (ez5.version("6") || ez5.version("5.82")) {
                fields.push({
                  type: CUI.Checkbox,
                  form: {
                    label: $$("user.manager.filter.show_archived")
                  },
                  name: "show_archived",
                  onDataChanged: function(data, field) {
                    var archivedFrom, archivedTo, form;
                    form = field.getForm();
                    archivedFrom = form.getFieldsByName("archived_from")[0];
                    archivedTo = form.getFieldsByName("archived_to")[0];
                    if (data.show_archived) {
                      archivedFrom.enable();
                      archivedTo.enable();
                    } else {
                      archivedFrom.disable();
                      archivedTo.disable();
                    }
                  }
                });
              }
              fields.push({
                type: CUI.DateTime,
                form: {
                  label: $$("user.manager.filter.archived_from")
                },
                name: "archived_from",
                disabled: function() {
                  return !_this.__filter_data.show_archived;
                }
              });
              fields.push({
                type: CUI.DateTime,
                form: {
                  label: $$("user.manager.filter.archived_to")
                },
                name: "archived_to",
                disabled: function() {
                  return !_this.__filter_data.show_archived;
                }
              });
              login_disabled_opts = [];
              ref1 = [null, true, false];
              for (j = 0, len1 = ref1.length; j < len1; j++) {
                k = ref1[j];
                login_disabled_opts.push({
                  text: $$("user.manager.filter.login_disabled." + k),
                  value: k
                });
              }
              fields.push({
                type: CUI.Select,
                form: {
                  label: $$("user.manager.filter.login_disabled.label")
                },
                options: login_disabled_opts,
                name: "login_disabled"
              });
              filterColumns = ["login", "first_name", "last_name", "displayname", "company", "department", "address_supplement", "street", "house_number", "postal_code", "town", "country", "phone", "reference"];
              if (ez5.version("6")) {
                filterColumns.splice(1, 0, "email");
                filterColumns = _this.hideFieldsByConfig(filterColumns);
              }
              filterColumnsOptions = [];
              for (l = 0, len2 = filterColumns.length; l < len2; l++) {
                fc = filterColumns[l];
                filterColumnsOptions.push({
                  text: $$("admin.user." + fc),
                  value: "user." + fc
                });
              }
              searchColumns = {
                type: CUI.Options,
                form: {
                  label: $$("user.manager.filter.fiter_columns")
                },
                name: "filter_columns",
                horizontal: false,
                options: filterColumnsOptions,
                onDataChanged: function(data) {
                  CUI.Events.trigger({
                    type: "viewport-resize",
                    node: filter_form.DOM
                  });
                  ez5.session.savePref("usermanager-filter-columns", _this.__filter_data.filter_columns);
                }
              };
              fields.push(searchColumns);
              columnOptions = [];
              ref2 = _this._valid_columns;
              for (m = 0, len3 = ref2.length; m < len3; m++) {
                c = ref2[m];
                columnOptions.push({
                  text: $$("admin.user.list." + c),
                  value: c
                });
              }
              columnsField = {
                type: CUI.Options,
                form: {
                  label: $$("user.manager.filter.columns")
                },
                name: "columns",
                horizontal: false,
                sortable: true,
                options: columnOptions,
                onDataChanged: function(data) {
                  if (data["columns"].length === 0) {
                    data["columns"] = ["id"];
                  }
                  CUI.Events.trigger({
                    type: "viewport-resize",
                    node: filter_form.DOM
                  });
                  ez5.session.savePref("usermanager-columns", _this.__filter_data.columns);
                  _this.load();
                }
              };
              fields.push(columnsField);
            }
            return fields;
          },
          trigger_data_changed_while_open: true,
          button: {
            "class": "ez5-user-manager-filter-button",
            loca_key: "user.manager.filter.button"
          },
          renderDisplayButton: function() {
            return _this.__filter_data.__group_ids.length > 0 || _this.__filter_data.types.length > 0 || !!_this.__filter_data.show_archived;
          },
          onDataChanged: function() {
            return _this.loadFilter();
          }
        });
        lay = new CUI.HorizontalLayout({
          "class": "ez5-filter-manager",
          center: {
            content: [input]
          },
          right: {
            content: filter_form.start()
          }
        });
        return lay;
      };
    })(this);
    return opts;
  };

  UserManager.prototype.loadList = function(filter, opts) {
    var group_ids, id, phrase, ref, search, searchOpts, searchText, search_string, str;
    if (opts == null) {
      opts = {};
    }
    search = [
      {
        type: "in",
        bool: "must_not",
        fields: ["user.type"],
        "in": ["anonymous", "collection"]
      }
    ];
    group_ids = [];
    group_ids.push.apply(group_ids, this.__filter_data.__group_ids);
    group_ids.push.apply(group_ids, this.__filter_data.custom_group_ids);
    if (group_ids.length > 0) {
      search.push({
        type: "in",
        bool: this.__filter_data.not_groups ? "must_not" : "must",
        fields: ["_groups.group._id"],
        "in": group_ids
      });
    }
    if (this.__filter_data.types.length > 0) {
      search.push({
        type: "in",
        bool: "must",
        fields: ["user.type"],
        "in": this.__filter_data.types
      });
    }
    if (this.__filter_data.login_disabled !== null) {
      search.push({
        type: "in",
        bool: "must",
        fields: ["user.login_disabled"],
        "in": [this.__filter_data.login_disabled]
      });
    }
    if (ez5.version("6") || ez5.version("5.82")) {
      if (this.__filter_data.show_archived) {
        if (this.__filter_data.archived_from || this.__filter_data.archived_to) {
          search.push({
            type: "range",
            field: "_archived_at",
            bool: "must",
            from: this.__filter_data.archived_from || null,
            to: this.__filter_data.archived_to || null
          });
        } else {
          search.push({
            type: "in",
            bool: "must_not",
            fields: ["_archived_at"],
            "in": [null]
          });
        }
      } else {
        search.push({
          type: "in",
          bool: "must",
          fields: ["_archived_at"],
          "in": [null]
        });
      }
    }
    searchText = this.__filter_data.search;
    if (searchText) {
      if (searchText.startsWith("#")) {
        id = parseInt(searchText.substring(1));
        if (!isNaN(id)) {
          search.push({
            type: "in",
            bool: "should",
            fields: ["user._id"],
            "in": [id]
          });
        }
      }
      ref = Search.getPhrase(searchText), str = ref[0], phrase = ref[1];
      search_string = "*" + str + "*";
      if (ez5.version("6")) {
        search_string = SearchUtil.cleanWildCard(search_string);
        if (!CUI.util.isEmpty(search_string)) {
          search.push({
            type: "text",
            query: "text",
            string: search_string,
            fields: this.__filter_data.filter_columns
          });
        }
      } else {
        if (!CUI.util.isEmpty(search_string)) {
          search.push({
            type: "match",
            bool: "should",
            mode: "wildcard",
            phrase: phrase,
            string: search_string,
            fields: this.__filter_data.filter_columns
          });
        }
      }
    }
    searchOpts = opts.searchOpts || {};
    CUI.mergeMap(searchOpts, {
      type: "user",
      search: search,
      limit: 100,
      generate_rights: false,
      aggregations: {
        _users: {
          field: "user.type",
          type: "term",
          limit: 10000
        }
      },
      sort: [
        {
          field: this.__sortField,
          order: this.__sortOrder
        }
      ]
    });
    return UserManager.__super__.loadList.call(this, null, {
      searchOpts: searchOpts,
      newInstanceFunc: (function(_this) {
        return function(user) {
          return User.newInstance({
            user: user,
            manager: _this
          });
        };
      })(this)
    });
  };

  return UserManager;

})(SystemListManager);

ez5.session_ready(function() {
  return ez5.rootMenu.registerApp(UserManager);
});
// Generated by CoffeeScript 1.12.7
var UserCSVImporter,
  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;

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

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

  UserCSVImporter.prototype.getDestinationFields = function() {
    var destFields, dest_field, dest_fields, fields, fylrDestFields, i, j, k, len, len1;
    dest_fields = [
      {
        name: "_basetype"
      }, {
        name: "user.type"
      }, {
        name: "user._id",
        format: "number",
        use_for_match_existing: true
      }, new UserCSVLoginDestinationField({
        csvImporter: this,
        name: "user.login"
      }), {
        name: "user.frontend_prefs",
        format: "json"
      }, {
        name: "user.login_disabled",
        format: "boolean"
      }, {
        name: "user.require_password_change",
        format: "boolean"
      }, new UserCSVImporterGroupsField({
        csvImporter: this,
        name: "_groups#find"
      }), {
        name: "_emails",
        format: "json"
      }, {
        name: "_emails[].email",
        format: "string"
      }, {
        name: "_emails[].use_for_login",
        format: "boolean"
      }, {
        name: "_emails[].use_for_email",
        format: "boolean"
      }, {
        name: "_emails[].needs_confirmation",
        format: "boolean"
      }, {
        name: "_emails[].send_email",
        format: "boolean"
      }, {
        name: "_emails[].send_email_include_password",
        format: "boolean"
      }, {
        name: "_emails[].intended_primary",
        format: "boolean"
      }, {
        name: "_emails[].is_primary",
        format: "boolean"
      }, {
        name: "_password",
        format: "string"
      }
    ];
    destFields = ["first_name", "last_name", "displayname", "company", "department", "address_supplement", "street", "house_number", "postal_code", "town", "country", "phone", "reference", "remarks", "_new_primary_email"];
    if (ez5.version("6")) {
      fylrDestFields = ["state", "_version", "frontend_language", "email", "_generated_displayname"];
      destFields = destFields.concat(fylrDestFields);
      dest_fields = dest_fields.concat([
        {
          name: "user.welcome_email",
          format: "boolean"
        }, {
          name: "user.confirm_email",
          format: "boolean"
        }, {
          name: "user.mail_schedule",
          format: "json"
        }, {
          name: "user.custom_data",
          format: "json"
        }, {
          name: "user.database_languages",
          format: "array"
        }, {
          name: "user.search_languages",
          format: "array"
        }, {
          name: "user.picture",
          format: "json"
        }, {
          name: "user.login_valid_from",
          format: "datetime"
        }, {
          name: "user.login_valid_to",
          format: "datetime"
        }, {
          name: "user.confirm_email_sent_at",
          format: "datetime"
        }
      ]);
    }
    for (i = 0, len = destFields.length; i < len; i++) {
      k = destFields[i];
      dest_fields.push({
        name: "user." + k,
        label: $$("admin.user." + k)
      });
    }
    fields = [];
    for (j = 0, len1 = dest_fields.length; j < len1; j++) {
      dest_field = dest_fields[j];
      if (dest_field instanceof CSVImporterDestinationField) {
        fields.push(dest_field);
      } else {
        dest_field.csvImporter = this;
        if (!dest_field.label) {
          dest_field.label = $$("user.csv.importer.field." + dest_field.name);
        }
        fields.push(new CSVImporterDestinationField(dest_field));
      }
    }
    return fields;
  };

  UserCSVImporter.prototype.getTitleLocaKey = function() {
    return "user.csv.importer.title";
  };

  UserCSVImporter.prototype.getOutputSettingFields = function() {
    var fields, match_existing;
    fields = UserCSVImporter.__super__.getOutputSettingFields.call(this);
    match_existing = this.getMatchExistingField();
    if (match_existing) {
      fields.splice(0, 0, match_existing);
    }
    return fields;
  };

  UserCSVImporter.prototype.getObjecttype = function() {
    return "user";
  };

  UserCSVImporter.prototype.getPrepareDataSearchOpts = function() {
    return {
      type: "user"
    };
  };

  UserCSVImporter.prototype.supportsDelete = function() {
    return true;
  };

  UserCSVImporter.prototype.getRecord = function(row, opts) {
    var record;
    if (opts == null) {
      opts = {};
    }
    record = UserCSVImporter.__super__.getRecord.call(this, row, opts);
    record._basetype = "user";
    if (!record.user) {
      record.user = {};
    }
    if (!record.user.type) {
      record.user.type = "easydb";
    }
    if (row[this.cf_idx.id]) {
      record.user._id = row[this.cf_idx.id];
      record.user._version = parseInt(row[this.cf_idx.version]) + 1;
    } else {
      if (opts.operation) {
        record.user._id = null;
      }
      record.user._version = 1;
    }
    return record;
  };

  UserCSVImporter.prototype.action = function(ev, op, rows) {
    var delete_ids, i, idx, idx_by_id, j, len, len1, promise, record, records, row;
    records = [];
    for (i = 0, len = rows.length; i < len; i++) {
      row = rows[i];
      record = this.getRecord(row, {
        operation: op
      });
      records.push(record);
    }
    if (ev.hasModifierKey()) {
      console.info("UserCSVImporter:", CUI.util.dump(records));
      return CUI.rejectedPromise();
    }
    if (op === "delete") {
      delete_ids = [];
      idx_by_id = {};
      for (idx = j = 0, len1 = records.length; j < len1; idx = ++j) {
        record = records[idx];
        if (!record.user._id) {
          continue;
        }
        delete_ids.push(record.user._id);
        idx_by_id[record.user._id] = idx;
      }
      promise = CUI.chunkWork.call(this, {
        timeout: -1,
        chunk_size: 1,
        items: delete_ids,
        call: (function(_this) {
          return function(_delete_ids) {
            console.debug("deleting ids..", _delete_ids);
            return ez5.api.user({
              type: "DELETE",
              api: "/" + _delete_ids[0]
            }).done(function() {
              row = rows[idx_by_id[_delete_ids[0]]];
              row[_this.cf_idx.status] = "done";
              row[_this.cf_idx.status_text] = "deleted";
              return row[_this.cf_idx.id] = _delete_ids[0];
            });
          };
        })(this)
      });
      promise.fail((function(_this) {
        return function() {
          var l, len2;
          for (l = 0, len2 = rows.length; l < len2; l++) {
            row = rows[l];
            if (row[_this.cf_idx.status] !== "done") {
              row[_this.cf_idx.status] = "failed";
            }
          }
        };
      })(this));
      return promise;
    }
    return ez5.api.user({
      type: "POST",
      json_data: records
    }).done((function(_this) {
      return function(users) {
        var l, len2, user;
        for (idx = l = 0, len2 = users.length; l < len2; idx = ++l) {
          user = users[idx];
          row = rows[idx];
          row[_this.cf_idx.status] = "done";
          row[_this.cf_idx.id] = user.user._id;
          row[_this.cf_idx.version] = user.user._version;
        }
      };
    })(this)).fail((function(_this) {
      return function() {
        var l, len2;
        for (l = 0, len2 = rows.length; l < len2; l++) {
          row = rows[l];
          row[_this.cf_idx.status] = "failed";
        }
      };
    })(this));
  };

  UserCSVImporter.prototype.__loadCSVData = function() {
    return UserCSVImporter.__super__.__loadCSVData.call(this).done((function(_this) {
      return function() {
        _this.__form_data.header_row = 1;
        _this.__form_data.dest_field_row = 1;
        _this.initMapping();
        _this.__mapping_tab.setContent(_this.getMappingForm());
        _this.__form_data.match_existing = "user.login";
        return _this.reloadFormData();
      };
    })(this));
  };

  return UserCSVImporter;

})(CSVImporter);
// Generated by CoffeeScript 1.12.7
var UserCSVImporterGroupsField,
  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;

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

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

  UserCSVImporterGroupsField.prototype.__matchGroup = function(_value) {
    var data, displayname, grp, i, lang, len, ref, ref1, value;
    value = _value.trim();
    ref = ez5.groupManager.getGroups();
    for (i = 0, len = ref.length; i < len; i++) {
      grp = ref[i];
      data = grp.getData();
      if (data.group._id + "" === value) {
        return grp;
      }
      if (data.group.name === value) {
        return grp;
      }
      ref1 = data.group.displayname;
      for (lang in ref1) {
        displayname = ref1[lang];
        if (displayname === value) {
          return grp;
        }
      }
    }
    return null;
  };

  UserCSVImporterGroupsField.prototype.getRecordKeyPath = function() {
    return this.getName().split("#")[0];
  };

  UserCSVImporterGroupsField.prototype.matchesColumnName = function(name) {
    return this.getName() === name;
  };

  UserCSVImporterGroupsField.prototype.getRecordValue = function(configs, row, opts) {
    var _value, config, groups, grp, i, j, len, len1, ref, value;
    if (opts == null) {
      opts = {};
    }
    groups = [];
    for (i = 0, len = configs.length; i < len; i++) {
      config = configs[i];
      _value = row[config.csv_field_idx];
      if (CUI.util.isEmpty(_value)) {
        continue;
      }
      ref = _value.split(",");
      for (j = 0, len1 = ref.length; j < len1; j++) {
        value = ref[j];
        grp = this.__matchGroup(value);
        if (!grp) {
          continue;
        }
        groups.push({
          _basetype: "group",
          group: {
            _id: grp.id
          }
        });
      }
    }
    if (groups.length === 0) {
      return void 0;
    } else {
      return groups;
    }
  };

  UserCSVImporterGroupsField.prototype.getLabel = function() {
    return $$("user.csv.importer.field.groups");
  };

  return UserCSVImporterGroupsField;

})(CSVImporterDestinationField);
// Generated by CoffeeScript 1.12.7
var UserCSVLoginDestinationField,
  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;

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

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

  UserCSVLoginDestinationField.prototype.useForMatchExisting = function() {
    return true;
  };

  UserCSVLoginDestinationField.prototype.getMatchExistingValue = function(obj, match_existing) {
    var value;
    value = UserCSVLoginDestinationField.__super__.getMatchExistingValue.call(this, obj, match_existing);
    return value != null ? value.toUpperCase() : void 0;
  };

  UserCSVLoginDestinationField.prototype.getMatchExistingSearch = function(values) {
    var i, len, search, value;
    search = [];
    for (i = 0, len = values.length; i < len; i++) {
      value = values[i];
      search.push({
        type: "match",
        bool: "should",
        mode: "fulltext",
        string: value
      });
    }
    return [
      {
        type: "complex",
        bool: "should",
        search: search
      }
    ];
  };

  UserCSVLoginDestinationField.prototype.getMatchExistingValueFromSearchResponse = function(obj, match_existing) {
    var value;
    value = UserCSVLoginDestinationField.__super__.getMatchExistingValueFromSearchResponse.call(this, obj, match_existing);
    return value != null ? value.toUpperCase() : void 0;
  };

  UserCSVLoginDestinationField.prototype.getLabel = function() {
    return $$("user.csv.importer.field.login");
  };

  return UserCSVLoginDestinationField;

})(CSVImporterDestinationField);
// Generated by CoffeeScript 1.12.7
var UserCSVExporter,
  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;

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

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

  UserCSVExporter.prototype.initOpts = function() {
    UserCSVExporter.__super__.initOpts.call(this);
    return this.addOpts({
      userManager: {
        mandatory: true,
        check: (function(_this) {
          return function(v) {
            if (v instanceof UserManager && v.getLastData()) {
              return true;
            } else {
              return false;
            }
          };
        })(this)
      }
    });
  };

  UserCSVExporter.prototype.readOpts = function() {
    UserCSVExporter.__super__.readOpts.call(this);
    this.__data = this._userManager.getLastData();
    return this.__searchOpts = this._userManager.getLastSearchOptions();
  };

  UserCSVExporter.prototype.getTitle = function() {
    return $$("csv.exporter.label");
  };

  UserCSVExporter.prototype.getCount = function() {
    return this.__data.count;
  };

  UserCSVExporter.prototype.getChunkSize = function() {
    return this.__data.limit;
  };

  UserCSVExporter.prototype.getFileName = function() {
    return ez5.session.getEasydbName() + "_Users_" + CUI.util.moment().format('YYYY-MM-DD') + ".csv";
  };

  UserCSVExporter.prototype.getRows = function() {
    this.__column_keys = [];
    return UserCSVExporter.__super__.getRows.call(this);
  };

  UserCSVExporter.prototype.getHeaderRows = function() {
    return [this.__column_keys];
  };

  UserCSVExporter.prototype.getRowsChunk = function(offset, limit) {
    var dfr, rows, sopts;
    dfr = new CUI.Deferred();
    rows = [];
    sopts = CUI.util.copyObject(this.__searchOpts, true);
    sopts.offset = offset;
    sopts.limit = limit;
    sopts.generate_rights = false;
    ez5.api.search({
      json_data: sopts
    }).done((function(_this) {
      return function(data) {
        var i, len1, obj, ref, user_ids;
        user_ids = [];
        ref = data.objects;
        for (i = 0, len1 = ref.length; i < len1; i++) {
          obj = ref[i];
          user_ids.push(obj.user._id);
        }
        return CUI.chunkWork.call(_this, {
          timeout: 0,
          items: user_ids,
          chunk_size: 1,
          call: function(items, idx, len) {
            var dfr2;
            if (_this.exportStopRequested()) {
              return false;
            }
            dfr2 = new CUI.Deferred();
            dfr.notify({
              offset: idx + offset
            });
            ez5.api.user({
              api: "/" + items[0]
            }).done(function(objects) {
              var user;
              obj = objects[0];
              user = User.newInstance({
                user: obj
              });
              user.getCSVDataRow().fail(dfr2.reject).done(function(row2) {
                var item, j, len2, row;
                row = [];
                for (j = 0, len2 = row2.length; j < len2; j++) {
                  item = row2[j];
                  _this.__addData(row, item.key, item.value);
                }
                rows.push(row);
                return dfr2.resolve();
              });
            });
            return dfr2.promise();
          }
        }).done(function() {
          return dfr.resolve(rows);
        }).fail(dfr.reject);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  UserCSVExporter.prototype.__addData = function(row, key, value) {
    var colidx;
    colidx = this.__column_keys.indexOf(key);
    if (colidx === -1) {
      colidx = this.__column_keys.length;
      this.__column_keys.push(key);
    }
    row[colidx] = value;
  };

  return UserCSVExporter;

})(CSVExporter);
// Generated by CoffeeScript 1.12.7
var GroupManager,
  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;

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

  GroupManager.is_allowed = function() {
    if (ez5.session.hasSystemRight("root")) {
      return true;
    }
    if (ez5.session.hasSystemRight("group") && !ez5.session.hasSystemRight("group[hide_frontend_app]")) {
      return true;
    }
    return false;
  };

  GroupManager.group = function() {
    return "rightsmanagement";
  };

  GroupManager.label = function() {
    return "admin.menu.group";
  };

  GroupManager.submenu = function() {
    return "rightsmanagement";
  };

  GroupManager.path = function() {
    return ["groupmanager"];
  };

  function GroupManager(opts1) {
    this.opts = opts1 != null ? opts1 : {};
    this.getListFields = bind(this.getListFields, this);
    GroupManager.__super__.constructor.call(this, this.opts);
    if (this._auto_reload) {
      EventPoller.listen({
        instance: this,
        filter: {
          type: ["OBJECT_INDEX", "OBJECT_DELETE"],
          basetype: "group"
        },
        call: (function(_this) {
          return function(events) {
            return _this.loadAllGroups();
          };
        })(this)
      });
    }
  }

  GroupManager.prototype.destroy = function() {
    CUI.Events.ignore({
      instance: this
    });
    return GroupManager.__super__.destroy.call(this);
  };

  GroupManager.prototype.initOpts = function() {
    GroupManager.__super__.initOpts.call(this);
    return this.addOpts({
      auto_reload: {
        "default": false,
        mandatory: true,
        check: Boolean
      }
    });
  };

  GroupManager.prototype.initFilterData = function() {
    return this.__filter_data = {
      search: "",
      types: []
    };
  };

  GroupManager.prototype.getMissingName = function() {
    return $$("admin.group.missing.name");
  };

  GroupManager.prototype.getLeftTitle = function() {
    return $$("admin.group.pane.left.title");
  };

  GroupManager.prototype.getCenterTitle = function() {
    return $$("admin.group.pane.center.title");
  };

  GroupManager.prototype.getListFields = function() {
    return [
      {
        th_label: "admin.group.list.name"
      }, {
        th_label: "admin.group.list.type"
      }
    ];
  };

  GroupManager.prototype.getNavigationLocaKeyPrefix = function() {
    return "result.navigation.toolbar.group";
  };

  GroupManager.prototype.getNoRecordLocaKey = function() {
    return $$("result.navigation.toolbar.group.no_groups");
  };

  GroupManager.prototype.getPlusButton = function() {
    var ref;
    if (((ref = ez5.session.getSystemRight("group")) != null ? ref.create : void 0) || ez5.session.hasSystemRight("root")) {
      return GroupManager.__super__.getPlusButton.call(this);
    } else {

    }
  };

  GroupManager.prototype.addRow = function() {
    return this.tree.addNode(new Group({
      manager: this
    })).done((function(_this) {
      return function(node) {
        return node.select().done(function() {
          return node.scrollIntoView();
        });
      };
    })(this));
  };

  GroupManager.prototype.loadNodes = function() {
    var ref, ref1, ref2, ref3;
    GroupManager.__super__.loadNodes.call(this);
    if (((ref = this.filter_button) != null ? ref.__rendered : void 0) && ((ref1 = this.filter_button) != null ? ref1.__popover : void 0)) {
      if ((ref2 = this.filter_button) != null) {
        ref2.__closePopover();
      }
      return (ref3 = this.filter_button) != null ? ref3.__openPopover() : void 0;
    }
  };

  GroupManager.prototype.loadList = function(filter, opts) {
    var _s, cat, i, j, k, len, len1, len2, ref, ref1, ref2, search, searchOpts;
    if (opts == null) {
      opts = {};
    }
    search = [
      {
        bool: "must",
        type: "in",
        fields: ["_basetype"],
        "in": ["group"]
      }
    ];
    if (this.__filter_data.types.length > 0) {
      search.push({
        type: "in",
        bool: "must",
        fields: ["group.type"],
        "in": this.__filter_data.types
      });
      console.debug("Added Types:", this.__filter_data.types);
    }
    if (ez5.version("6.18")) {
      ref = ["a", "b", "c"];
      for (i = 0, len = ref.length; i < len; i++) {
        cat = ref[i];
        if (this.__filter_data["category_" + cat]) {
          search.push({
            type: "in",
            bool: "must",
            fields: ["group.category_" + cat],
            "in": [this.__filter_data["category_" + cat]]
          });
        }
      }
    }
    if (opts.searchOpts) {
      searchOpts = CUI.util.copyObject(opts.searchOpts, true);
      if (searchOpts.search) {
        ref1 = searchOpts.search;
        for (j = 0, len1 = ref1.length; j < len1; j++) {
          _s = ref1[j];
          search.push(_s);
        }
      }
      delete searchOpts.search;
    } else {
      searchOpts = {};
    }
    CUI.mergeMap(searchOpts, {
      type: "group",
      search: search,
      generate_rights: ez5.version("6"),
      limit: 100,
      offset: 0,
      aggregations: {
        _groups: {
          field: "group.type",
          type: "term",
          limit: 10000
        }
      },
      sort: [
        {
          field: "group.displayname",
          order: "ASC"
        }
      ]
    });
    if (ez5.version("6.18")) {
      ref2 = ["a", "b", "c"];
      for (k = 0, len2 = ref2.length; k < len2; k++) {
        cat = ref2[k];
        searchOpts.aggregations["category_" + cat] = {
          field: "group.category_" + cat,
          type: "term",
          limit: 10000
        };
      }
    }
    return GroupManager.__super__.loadList.call(this, this.__filter_data.search, {
      searchOpts: searchOpts,
      newInstanceFunc: (function(_this) {
        return function(group) {
          return Group.newInstance({
            group: group,
            manager: _this
          });
        };
      })(this)
    });
  };

  GroupManager.prototype.getGroups = function() {
    CUI.util.assert(CUI.util.isArray(this.groups), "GroupManager.getGroups", ".loadAllGroups not called");
    return this.groups;
  };

  GroupManager.prototype.getGroupById = function(groupId) {
    var group, i, len, ref;
    CUI.util.assert(CUI.util.isArray(this.groups), "GroupManager.getGroupById", ".loadAllGroups not called", {
      groupId: groupId
    });
    ref = this.groups;
    for (i = 0, len = ref.length; i < len; i++) {
      group = ref[i];
      if (group.id === groupId) {
        return group;
      }
    }
    return null;
  };

  GroupManager.prototype.loadAllGroups = function() {
    return this.loadList(null, {
      searchOpts: {
        type: "acl",
        search: [
          {
            type: "complex",
            search: [
              {
                type: "in",
                bool: "should",
                fields: ["group.type"],
                "in": ["easydb", "system"]
              }, {
                type: "in",
                bool: "should",
                fields: ["group._id"],
                "in": ez5.session.getGroupIds()
              }
            ]
          }
        ],
        sort: [
          {
            field: "group._id"
          }
        ],
        limit: 100000
      }
    }).done((function(_this) {
      return function(groups) {
        _this.groups = groups;
      };
    })(this));
  };

  GroupManager.prototype.addGroupToAllGroups = function(group) {
    CUI.util.assert(group instanceof Group && group.getId(), "GroupManager.addGroupToAllGroups", "group needs to be instance of Group.", {
      group: group
    });
    CUI.util.pushOntoArray(group, this.groups, function(v) {
      return v.getId() === group.getId();
    });
    return this;
  };

  GroupManager.prototype.getTreeOpts = function() {
    var opts;
    opts = GroupManager.__super__.getTreeOpts.call(this);
    opts.filterManager = (function(_this) {
      return function() {
        var fields, input, lay;
        input = ListViewEditTree.getFilterManager(function(filter) {
          _this.__filter_data.search = filter;
          return _this.loadFilter();
        });
        fields = null;
        lay = new CUI.HorizontalLayout({
          "class": "ez5-filter-manager",
          center: {
            content: [input]
          },
          right: {
            content: _this.getFilterButton()
          }
        });
        return lay;
      };
    })(this);
    return opts;
  };

  GroupManager.prototype.getFilterButton = function() {
    this.filter_button = new CUI.FormPopover({
      data: this.__filter_data,
      fields: (function(_this) {
        return function() {
          var cat, fields, i, j, k, len, len1, len2, opts, ref, ref1, ref2, ref3, ref4, ref5, ref6, term;
          if (!((ref = _this.data) != null ? ref.aggregations : void 0)) {
            return [
              {
                type: CUI.Output,
                text: $$("group.manager.filter.no_data")
              }
            ];
          }
          opts = [];
          ref3 = ((ref1 = _this.data.aggregations) != null ? (ref2 = ref1._groups) != null ? ref2.terms : void 0 : void 0) || [];
          for (i = 0, len = ref3.length; i < len; i++) {
            term = ref3[i];
            opts.push({
              text: term.term,
              value: term.term
            });
          }
          opts.sort(function(a, b) {
            return CUI.util.compareIndex(a.text, b.text);
          });
          fields = [];
          if (opts.length > 0) {
            fields.push({
              form: {
                label: $$("group.manager.filter.types")
              },
              type: CUI.Options,
              name: "types",
              undo_and_changed_support: false,
              horizontal: false,
              options: opts
            });
          }
          if (ez5.version("6.18") && _this.data.aggregations) {
            ref4 = ["a", "b", "c"];
            for (j = 0, len1 = ref4.length; j < len1; j++) {
              cat = ref4[j];
              opts = [];
              opts.push({
                text: "-- Select a category --",
                value: null
              });
              ref6 = ((ref5 = _this.data.aggregations["category_" + cat]) != null ? ref5.terms : void 0) || [];
              for (k = 0, len2 = ref6.length; k < len2; k++) {
                term = ref6[k];
                if (CUI.util.isEmpty(term.term)) {
                  continue;
                } else {
                  opts.push({
                    text: term.term,
                    value: term.term
                  });
                }
              }
              fields.push({
                form: {
                  label: $$("group.manager.filter.category_" + cat)
                },
                type: CUI.Select,
                name: "category_" + cat,
                options: opts
              });
            }
          }
          return fields;
        };
      })(this),
      trigger_data_changed_while_open: true,
      onRender: (function(_this) {
        return function(df) {
          var btn;
          btn = df.getButton();
          return CUI.Events.listen({
            type: "click",
            capture: true,
            node: btn.DOM,
            call: function(ev) {
              if (!btn.isActive()) {
                return;
              }
              _this.__filter_data.types.splice(0);
              _this.loadFilter();
              btn.deactivate();
              return ev.stopImmediatePropagation();
            }
          });
        };
      })(this),
      button: {
        loca_key: "group.manager.filter.button"
      },
      renderDisplayButton: (function(_this) {
        return function() {
          return _this.__filter_data.types.length > 0;
        };
      })(this),
      onDataChanged: (function(_this) {
        return function() {
          return _this.loadFilter();
        };
      })(this)
    });
    return this.filter_button.start();
  };

  return GroupManager;

})(SystemListManager);

ez5.session_ready(function() {
  return ez5.rootMenu.registerApp(GroupManager);
});
// Generated by CoffeeScript 1.12.7
var ObjecttypeAdminManager,
  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;

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

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

  ObjecttypeAdminManager.is_allowed = function() {
    return ez5.session.hasSystemRight("root", "objecttypemanager");
  };

  ObjecttypeAdminManager.label = function() {
    return "admin.menu.objecttype";
  };

  ObjecttypeAdminManager.group = function() {
    return "rightsmanagement";
  };

  ObjecttypeAdminManager.submenu = function() {
    return "rightsmanagement";
  };

  ObjecttypeAdminManager.path = function() {
    return ["objecttypeadminmanager"];
  };

  ObjecttypeAdminManager.prototype.hasFooter = function() {
    return false;
  };

  ObjecttypeAdminManager.prototype.getTreeOpts = function() {
    return {
      no_hierarchy: true
    };
  };

  ObjecttypeAdminManager.prototype.getMissingName = function() {
    return $$("admin.easydb.objecttype.missing.name");
  };

  ObjecttypeAdminManager.prototype.getLeftTitle = function() {
    return $$("admin.easydb.objecttype.pane.left.title");
  };

  ObjecttypeAdminManager.prototype.getCenterTitle = function() {
    return $$("admin.easydb.objecttype.pane.center.title");
  };

  ObjecttypeAdminManager.prototype.getListFields = function() {
    return [
      {
        th_label: "admin.easydb.objecttype.list.title"
      }
    ];
  };

  ObjecttypeAdminManager.prototype.itemClass = function() {
    return ObjecttypeListViewItem;
  };

  ObjecttypeAdminManager.prototype.loadList = function() {
    var cls, dfr, i, len, o, ref, tb;
    dfr = new CUI.Deferred();
    this.objecttypes = [];
    cls = this.itemClass();
    ref = ez5.schema.CURRENT._objecttypes;
    for (i = 0, len = ref.length; i < len; i++) {
      o = ref[i];
      if (o._instance) {
        continue;
      }
      tb = new Table("CURRENT", o.table_id);
      if (tb.poolLink()) {
        cls = window.ObjecttypeListViewItem;
      } else {
        cls = window.ObjecttypeWithoutPoolListViewItem;
      }
      this.objecttypes.push(new cls({
        objecttype: new Objecttype(tb),
        manager: this
      }));
    }
    return dfr.resolve(this.objecttypes).promise();
  };

  ObjecttypeAdminManager.prototype.loadFilter = false;

  return ObjecttypeAdminManager;

})(SystemListManager);

ez5.session_ready(function() {
  return ez5.rootMenu.registerApp(ObjecttypeAdminManager);
});
// Generated by CoffeeScript 1.12.7
var ObjecttypeAdminManagerMaskItem,
  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;

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

  function ObjecttypeAdminManagerMaskItem() {
    this.getSaveData = bind(this.getSaveData, this);
    return ObjecttypeAdminManagerMaskItem.__super__.constructor.apply(this, arguments);
  }

  ObjecttypeAdminManagerMaskItem.prototype.initOpts = function() {
    ObjecttypeAdminManagerMaskItem.__super__.initOpts.call(this);
    return this.addOpts({
      data: {
        mandatory: true,
        check: "PlainObject"
      },
      mask: {
        mandatory: true,
        check: Mask
      },
      objecttypeListViewItem: {
        mandatory: true,
        check: ObjecttypeListViewItem
      },
      tagForm: {
        mandatory: true,
        check: TagForm
      }
    });
  };

  ObjecttypeAdminManagerMaskItem.prototype.readOpts = function() {
    var ref;
    ObjecttypeAdminManagerMaskItem.__super__.readOpts.call(this);
    this.mask = this._mask;
    this.data = ((ref = this._data) != null ? ref[this.mask.id()] : void 0) || {};
    this.objecttypeListViewItem = this._objecttypeListViewItem;
    this.tagForm = this._tagForm;
    this.opts.fields = [
      new CUI.ListViewColumn({
        text: this.mask.nameLocalized()
      })
    ];
    if (this.mask.isStandard()) {
      this.opts.fields.push(new CUI.ListViewColumn({
        element: new CUI.EmptyLabel({
          text: $$("objecttype.admin.manager.mask.item")
        })
      }));
    } else {
      this.tagfilter = new TagFilter({
        data: this.data,
        name: "tagfilter",
        tagForm: this.tagForm
      });
      this.opts.fields.push(this.tagfilter.getField({
        onDataChanged: (function(_this) {
          return function() {
            return _this.update();
          };
        })(this)
      }));
    }
    return this;
  };

  ObjecttypeAdminManagerMaskItem.prototype.getSaveData = function(sd) {
    if (sd == null) {
      sd = {};
    }
    if (!this.tagfilter) {
      return;
    }
    sd[this.mask.id()] = {
      tagfilter: this.tagfilter.getSaveData()
    };
    return sd;
  };

  return ObjecttypeAdminManagerMaskItem;

})(ListViewEditTreeNode);
// Generated by CoffeeScript 1.12.7
var ColumnRightItem,
  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;

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

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

  ColumnRightItem.prototype.readOpts = function() {
    var acl, field, fields, i, j, key, len, len1, ref, ref1, ref2, value, who;
    ColumnRightItem.__super__.readOpts.call(this);
    if (!this._data.columns) {
      this._data.columns = [];
    }
    if (this._data.system_fields) {
      ref = this._data.system_fields;
      for (key in ref) {
        value = ref[key];
        if (value) {
          this._data.columns.push(key);
        }
      }
    }
    acl = [];
    if (this._data.who) {
      ref1 = this._data.who;
      for (i = 0, len = ref1.length; i < len; i++) {
        who = ref1[i];
        acl.push({
          who: who
        });
      }
    }
    this.aclManager = new AclManager({
      data: acl,
      tagForm: this._tagForm,
      right: false,
      tagfilter: false,
      allowOwner: true,
      acl_counter_loca_key: "acl.manager.tag.acl-counter",
      onUpdate: (function(_this) {
        return function() {
          return _this.update();
        };
      })(this)
    });
    if (this._objecttype.hasTags()) {
      if (!this._data.tagfilter) {
        this._data.tagfilter = {};
      }
      this.tagfilter = new TagFilter({
        data: this._data,
        name: "tagfilter",
        tagForm: ez5.tagForm
      });
    }
    fields = [];
    ref2 = this._objecttype.getAllFields();
    for (j = 0, len1 = ref2.length; j < len1; j++) {
      field = ref2[j];
      if (field.isRightsEnabled()) {
        fields.push(field);
      }
    }
    this.opts.fields = [
      {
        type: CUI.Input,
        name: "internal_name"
      }, AclRight.getFieldColumnSelector({
        name: 'columns',
        fields: fields,
        placeholder_loca: $$('acl.right.column_select.placeholder.objecttypes')
      })
    ];
    if (this._objecttype.hasTags()) {
      this.opts.fields.push(this.tagfilter.getField());
    }
    this.opts.fields.push(this.aclManager.getField());
    return this;
  };

  ColumnRightItem.prototype.initOpts = function() {
    ColumnRightItem.__super__.initOpts.call(this);
    this.mergeOpt('data', {
      mandatory: true
    });
    return this.addOpts({
      tagForm: {
        mandatory: true,
        check: TagFormForManager
      },
      objecttype: {
        mandatory: true,
        check: Objecttype
      }
    });
  };

  ColumnRightItem.prototype.getSaveData = function() {
    var acl_item, i, id, j, len, len1, ref, ref1, sd, tagfilter_missing, value, who, who_id, who_ids;
    sd = {
      who: [],
      columns: [],
      system_fields: {},
      internal_name: this._data.internal_name.trim()
    };
    ref = this._data.columns;
    for (i = 0, len = ref.length; i < len; i++) {
      value = ref[i];
      if (CUI.util.isNumber(value)) {
        sd.columns.push(value);
      } else {
        sd.system_fields[value] = true;
      }
    }
    tagfilter_missing = false;
    if (this._objecttype.hasTags()) {
      sd.tagfilter = CUI.util.copyObject(this._data.tagfilter, true);
      if (CUI.util.isEmptyObject(sd.tagfilter)) {
        tagfilter_missing = true;
      }
    }
    who_ids = {};
    ref1 = this.aclManager.getSaveData();
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      acl_item = ref1[j];
      who = acl_item.who;
      switch (who._basetype) {
        case 'user':
          id = who.user._id;
          break;
        case 'group':
          id = who.group._id;
      }
      who_id = who._basetype + id;
      if (who_ids[who_id]) {
        continue;
      }
      who_ids[who_id] = true;
      sd.who.push(acl_item.who);
    }
    if (sd.who.length === 0 && tagfilter_missing) {
      throw new InvalidSaveDataException();
    }
    if (sd.columns.length === 0 && CUI.util.isEmpty(sd.system_fields)) {
      throw new InvalidSaveDataException();
    }
    if (CUI.util.isEmpty(this._data.internal_name)) {
      throw new InvalidSaveDataException();
    }
    return sd;
  };

  return ColumnRightItem;

})(ListViewEditTreeNode);
// Generated by CoffeeScript 1.12.7
var LinkedObjectFilterTreeNode,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  LinkedObjectFilterTreeNode.prototype.initOpts = function() {
    LinkedObjectFilterTreeNode.__super__.initOpts.call(this);
    this.mergeOpt('data', {
      mandatory: true
    });
    return this.addOpts({
      objecttype: {
        mandatory: true,
        check: Objecttype
      }
    });
  };

  LinkedObjectFilterTreeNode.prototype.readOpts = function() {
    var checkboxesField, field, fieldsMap, filtersSelectedText, i, lastColumn, len, ref, searchExpertButton, setButtonStatus, spacedFiltersSelectedText, updateCountText;
    LinkedObjectFilterTreeNode.__super__.readOpts.call(this);
    if (!this._data.fields) {
      this._data.fields = [];
    } else {
      this._data.fields = this._data.fields.filter((function(_this) {
        return function(storedFieldName) {
          return _this._objecttype.getAllFields().some(function(field) {
            return field.fullName() === storedFieldName;
          });
        };
      })(this));
    }
    if (!this._data.filters) {
      this._data.filters = [];
    }
    if (!this._data.expert_search_data) {
      this._data.expert_search_data = {};
    }
    fieldsMap = {};
    ref = this._objecttype.getAllFields();
    for (i = 0, len = ref.length; i < len; i++) {
      field = ref[i];
      if (field instanceof LinkedObject && !(field instanceof TreeColumn)) {
        fieldsMap[field.fullName()] = field;
      }
    }
    checkboxesField = new CUI.DataFieldProxy({
      element: (function(_this) {
        return function(field) {
          var checkboxes, fieldName, fields, fn, j, len1, ref1;
          fields = (ref1 = field.getData()) != null ? ref1.fields : void 0;
          checkboxes = [];
          fn = function(fieldName) {
            var checkbox;
            checkbox = new CUI.Checkbox({
              text: fieldsMap[fieldName].fullNameLocalized(),
              active: true,
              onClick: function() {
                CUI.util.removeFromArray(fieldName, fields);
                checkbox.destroy();
                field.reload();
                checkboxesField.reload();
                setButtonStatus();
              }
            });
            checkbox.start();
            return checkboxes.push(checkbox);
          };
          for (j = 0, len1 = fields.length; j < len1; j++) {
            fieldName = fields[j];
            fn(fieldName);
          }
          if (checkboxes.length === 0) {
            return new EmptyLocaLabel({
              loca_key: "objecttype.list.view.item.linked_objects_filters.node.select-empty"
            });
          }
          return new CUI.VerticalList({
            content: checkboxes
          });
        };
      })(this)
    });
    filtersSelectedText = new CUI.Label({
      text: "",
      appearance: "secondary"
    });
    spacedFiltersSelectedText = CUI.dom.append(CUI.dom.space("small"), filtersSelectedText);
    updateCountText = (function(_this) {
      return function() {
        var count;
        count = _this._data.filters.length;
        if (count > 0) {
          filtersSelectedText.setText($$("objecttype.list.view.item.linked_objects_filters.node.search-options|text", {
            count: count
          }));
        } else {
          filtersSelectedText.setText("");
        }
      };
    })(this);
    updateCountText();
    searchExpertButton = new LocaButton({
      loca_key: "objecttype.list.view.item.linked_objects_filters.node.expert-search-button",
      onClick: (function(_this) {
        return function() {
          var _mask, j, k, len1, len2, mask, masks, ref1, ref2, searchExpertOptions;
          masks = [];
          ref1 = _this._data.fields.map(function(fieldName) {
            return fieldsMap[fieldName].linkMask();
          });
          for (j = 0, len1 = ref1.length; j < len1; j++) {
            mask = ref1[j];
            masks.push(mask);
            ref2 = ez5.mask.CURRENT._masks_by_table_id[mask.table.id()];
            for (k = 0, len2 = ref2.length; k < len2; k++) {
              _mask = ref2[k];
              if (_mask.mask_id === mask.id()) {
                continue;
              }
              masks.push(new Mask("CURRENT", _mask.mask_id));
            }
          }
          searchExpertOptions = new ObjecttypeSearchExpertOptions({
            button: searchExpertButton,
            masks: masks,
            data: _this._data.expert_search_data,
            onHide: function() {
              _this._data.filters = searchExpertOptions.getSearchFilterExpert();
              _this._data.expert_search_data = searchExpertOptions.data;
              updateCountText();
              searchExpertOptions.destroy();
              CUI.Events.trigger({
                type: "data-changed",
                node: searchExpertButton
              });
            }
          });
          searchExpertOptions.openPopover();
          searchExpertOptions.updateForm();
        };
      })(this)
    });
    setButtonStatus = (function(_this) {
      return function() {
        if (CUI.util.isEmpty(_this._data.fields)) {
          searchExpertButton.disable();
        } else {
          searchExpertButton.enable();
        }
      };
    })(this);
    lastColumn = new CUI.VerticalList({
      content: [searchExpertButton, spacedFiltersSelectedText]
    });
    this.opts.fields = [
      {
        type: CUI.Input,
        name: "internal_name"
      }, {
        type: CUI.Form,
        condensed: true,
        onDataInit: setButtonStatus,
        onDataChanged: setButtonStatus,
        fields: [
          {
            type: CUI.Select,
            name: "field",
            options: (function(_this) {
              return function(select) {
                var fieldName, fieldNames, options;
                fieldNames = select.getData().fields;
                options = [];
                for (fieldName in fieldsMap) {
                  field = fieldsMap[fieldName];
                  if (indexOf.call(fieldNames, fieldName) >= 0) {
                    continue;
                  }
                  options.push({
                    text: field.fullNameLocalized(),
                    value: fieldName
                  });
                }
                options.sort(function(a, b) {
                  return a.text.localeCompare(b.text);
                });
                options.unshift({
                  text: $$("objecttype.list.view.item.linked_objects_filters.node.select-placeholder"),
                  value: null
                });
                return options;
              };
            })(this),
            onDataChanged: (function(_this) {
              return function(data, field) {
                if (!data.field) {
                  return;
                }
                data.fields.push(data.field);
                data.field = null;
                field.reload();
                return checkboxesField.reload();
              };
            })(this)
          }, checkboxesField
        ]
      }, {
        type: CUI.Checkbox,
        name: "only_allow_select_last_children"
      }, {
        type: CUI.DataFieldProxy,
        element: lastColumn
      }
    ];
    return this;
  };

  LinkedObjectFilterTreeNode.prototype.getSaveData = function() {
    var saveData;
    saveData = {
      fields: this._data.fields,
      filters: this._data.filters,
      expert_search_data: ObjecttypeSearchExpertOptions.getSaveData(this._data.expert_search_data),
      internal_name: this._data.internal_name,
      only_allow_select_last_children: this._data.only_allow_select_last_children
    };
    if (!saveData.internal_name) {
      throw new InvalidSaveDataException();
    }
    if (CUI.util.isEmpty(saveData.fields)) {
      throw new InvalidSaveDataException();
    }
    return saveData;
  };

  return LinkedObjectFilterTreeNode;

})(ListViewEditTreeNode);
// Generated by CoffeeScript 1.12.7
var Objecttypes,
  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;

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

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

  Objecttypes.prototype.load = function() {
    var opts;
    opts = ez5.session.fylrCacheParams();
    opts.format = 'short';
    return ez5.api.objecttype({
      data: opts
    }).done((function(_this) {
      return function(__ots) {
        _this.__ots = __ots;
      };
    })(this));
  };

  Objecttypes.prototype.init = function() {
    var cf, i, j, k, key, len, len1, len2, ot, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, value, who;
    if (!this.__ots) {
      return;
    }
    ref = this.__ots;
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      ref1 = ot._columnfilters || [];
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        cf = ref1[j];
        if (!ez5.schema.CURRENT._objecttype_by_name[ot.objecttype.name].has_tags) {
          delete cf.tagfilter;
        } else {
          if (!((ref2 = cf.tagfilter) != null ? (ref3 = ref2.not) != null ? ref3.length : void 0 : void 0) && !((ref4 = cf.tagfilter) != null ? (ref5 = ref4.any) != null ? ref5.length : void 0 : void 0) && !((ref6 = cf.tagfilter) != null ? (ref7 = ref6.all) != null ? ref7.length : void 0 : void 0)) {
            cf.tagfilter = {};
          }
        }
        if (cf.system_fields) {
          ref8 = cf.system_fields;
          for (key in ref8) {
            value = ref8[key];
            if (value) {
              cf.columns.push(key);
            }
          }
        }
        if (!cf.acl) {
          cf.acl = [];
          if (cf.who) {
            ref9 = cf.who;
            for (k = 0, len2 = ref9.length; k < len2; k++) {
              who = ref9[k];
              cf.acl.push({
                who: who
              });
            }
          }
          delete cf.who;
        }
      }
    }
  };

  Objecttypes.prototype.getColumnFilters = function(ot_name) {
    var _ot, i, len, ot, ref;
    if (ot_name.indexOf('@') > -1) {
      return [];
    }
    ref = this.__ots;
    for (i = 0, len = ref.length; i < len; i++) {
      _ot = ref[i];
      if (_ot.objecttype.name === ot_name) {
        ot = _ot;
        break;
      }
    }
    CUI.util.assert(ot, "ObjecttypeRights.getColumnFilter", "Objecttype '" + ot_name + "' not found.", {
      objecttype: ot_name,
      objecttypes: this.__ots
    });
    return ot._columnfilters || [];
  };

  Objecttypes.prototype.getLinkedObjectsFilters = function(objecttypeName) {
    var _objecttype, i, len, objecttype, objecttypes, ref, ref1;
    if (objecttypeName.indexOf('@') > -1) {
      return [];
    }
    objecttypes = this.__ots;
    for (i = 0, len = objecttypes.length; i < len; i++) {
      _objecttype = objecttypes[i];
      if (_objecttype.objecttype.name === objecttypeName) {
        objecttype = _objecttype;
        break;
      }
    }
    if (!objecttype) {
      console.error("ObjecttypeRights.getLinkedObjectFilters", "Objecttype '" + objecttypeName + "' not found.", {
        objecttype: objecttypeName,
        objecttypes: objecttypes
      });
    }
    return ((ref = objecttype.objecttype.custom_data) != null ? (ref1 = ref.webfrontend) != null ? ref1.linkedObjectsFilters : void 0 : void 0) || [];
  };

  Objecttypes.prototype.getObjecttypes = function() {
    return this.__ots || [];
  };

  return Objecttypes;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var SearchMain,
  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;

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

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

  SearchMain.prototype.initOpts = function() {
    SearchMain.__super__.initOpts.call(this);
    return this.addOpts({
      container: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isElement(v);
        }
      },
      collection: {
        mandatory: true,
        check: Collection
      },
      collectionManager: {
        check: CollectionManager
      }
    });
  };

  SearchMain.prototype.emptyCollection = function() {
    this._collection.removeObjects();
    return this;
  };

  SearchMain.prototype.searchButtonBeforeExecute = function() {
    this.emptyCollection();
    return this;
  };

  SearchMain.prototype.execute = function(request) {
    if (request == null) {
      request = new Request();
    }
    this.__searchInput.prepareSearch(request);
    return SearchMain.__super__.execute.call(this, request);
  };

  SearchMain.prototype.__poolDeepLink = function() {
    var loc, m;
    loc = document.location.pathname.substr(window.easydb_base_prefix.length);
    m = loc.match("^/pool/(.+)");
    return m;
  };

  SearchMain.prototype.executeOnLoad = function() {
    var dfr, fulltext, loc, m, pool, search, url_data;
    loc = document.location.pathname.substr(window.easydb_base_prefix.length);
    if (document.location.pathname.startsWith(this.getSharePath())) {
      fulltext = loc.split("/")[2];
      if ((fulltext != null ? fulltext.length : void 0) > 0) {
        fulltext = decodeURIComponent(fulltext);
      }
    }
    m = this.__poolDeepLink();
    if (m) {
      pool = m[1];
    }
    search = document.location.search.substring(1);
    if (!fulltext && !search && !pool) {
      return this.runFirstSearch();
    }
    url_data = CUI.decodeUrlDataArray(search, CUI.decodeURIComponentNicely);
    if (!url_data.pool && pool) {
      url_data.pool = pool;
    }
    dfr = new CUI.Deferred();
    this.getSearchInitializedPromise().fail(dfr.reject).done((function(_this) {
      return function() {
        return _this.initFromUrlData(url_data, [fulltext]).always(function() {
          return _this.executeWithLog().done(dfr.resolve).fail(dfr.reject);
        });
      };
    })(this));
    return dfr.promise();
  };

  SearchMain.prototype.initFromUrlData = function(url_data, fulltext) {
    var fn, funcs, i, j, len, len1, ref, sm, txt;
    if (fulltext == null) {
      fulltext = null;
    }
    if (fulltext) {
      if (!url_data.inp) {
        url_data.inp = [];
      }
      for (i = 0, len = fulltext.length; i < len; i++) {
        txt = fulltext[i];
        if (CUI.util.isEmpty(txt)) {
          continue;
        }
        url_data.inp.push("fulltext:" + txt);
      }
    }
    funcs = [];
    ref = this.searchManagers;
    fn = (function(_this) {
      return function(sm) {
        return funcs.push(function() {
          return sm.initFromUrlData(url_data);
        });
      };
    })(this);
    for (j = 0, len1 = ref.length; j < len1; j++) {
      sm = ref[j];
      fn(sm);
    }
    return CUI.chainedCall.apply(CUI, funcs);
  };

  SearchMain.prototype.update_path = function(path) {
    var globalObjectId, ref, ref1, uuid;
    globalObjectId = Main.getGlobalObjectIdFromLocation(document.location);
    if (globalObjectId) {
      if ((ref = this._collectionManager) != null) {
        ref.showSearch();
      }
      this._collection.selectObjectByGlobalId(globalObjectId);
      this._collection.loadInSidebar({
        global_object_id: globalObjectId,
        push_state: false
      });
    } else {
      uuid = Main.getUUIDFromLocation(document.location);
      if (!uuid) {
        this.executeOnLoad();
        return;
      }
      if ((ref1 = this._collectionManager) != null) {
        ref1.showSearch();
      }
      this._collection.selectObjectByUUID(uuid).done((function(_this) {
        return function(obj) {
          return _this._collection.loadInSidebar({
            global_object_id: obj._global_object_id,
            push_state: false
          });
        };
      })(this));
    }
  };

  SearchMain.prototype.storeSearch = function() {
    var c, cdata, cm, ref, ref1, sd;
    cm = this._collectionManager;
    sd = this.getStoreSearchData();
    if (!((ref = sd.search) != null ? (ref1 = ref.SearchInput) != null ? ref1.query.length : void 0 : void 0)) {
      CUI.problem({
        text: $$("search.main.store.search.unable_to_store")
      });
      return;
    }
    cdata = {
      collection: {
        webfrontend_props: {
          search: sd
        }
      }
    };
    c = new CollectionStoredSearch({
      collection: cdata,
      manager: cm
    });
    return cm.addStoredSearch(c);
  };

  SearchMain.prototype.init = function() {
    var bottomToolbar, dfr, error, go_on, i, len, managerPlugin, managers, mapManagerSettingsBtn, mapManagerSlot, paneHeader, ref, resultManager, searchInputContainer, vl;
    console.time("SearchMain.init");
    if (this._collectionManager && !this._collectionManager.hasSearchCollection()) {
      CUI.dom.hideElement(this._container);
    }
    paneHeader = new CUI.PaneHeader({
      "class": "ez5-search-main-header",
      left: {
        content: new CUI.Label({
          text: $$("main.menu.search")
        })
      }
    });
    searchInputContainer = CUI.dom.element("DIV", {
      "class": "ez5-search-input-toolbar"
    });
    this.__buttonToolbar = new CUI.PaneToolbar({
      "class": "ez5-search-main-button-toolbar"
    });
    vl = new CUI.VerticalLayout({
      top: {
        content: null
      }
    });
    mapManagerSlot = null;
    if (GeoJsonColumn.isPluginInstalled()) {
      mapManagerSlot = {
        "class": "ez5-map-manager",
        flexHandle: {
          hidden: true,
          state_name: "search-main-map",
          closed: true,
          unit: "%"
        }
      };
    }
    this.__mainSearch = new CUI.HorizontalLayout({
      "class": "ez5-tmp-mainSearch",
      absolute: true,
      left: {
        "class": "ez5-facet-manager",
        flexHandle: {
          hidden: true,
          state_name: "search-main-facets",
          closed: true
        }
      },
      center: {
        content: new CUI.HorizontalLayout({
          center: {
            content: vl
          },
          left: mapManagerSlot
        })
      }
    });
    this.rc = vl.center();
    bottomToolbar = new CUI.PaneToolbar();
    this.__searchTypeSelector = new SearchTypeSelector({
      pref_name: "search_type_selector",
      ignoreSelection: (function(_this) {
        return function() {
          if (_this.__searchInput.ignoreSearchManager(_this.__searchTypeSelector)) {
            return true;
          }
          if (_this.__searchHierarchyManager.isActive()) {
            return true;
          }
          return false;
        };
      })(this)
    });
    this.addSearchManager(this.__searchTypeSelector);
    this.__searchInput = new SearchInput({
      expert: this,
      searchTypeSelector: this.__searchTypeSelector,
      input_opts: {
        attr: {
          "aria-labelledby": "main-search-button"
        }
      }
    });
    this.addSearchManager(this.__searchInput);
    this.__searchInput.getInputLayout().append(this.getSearchButton(), "right", false);
    this.__searchInput.addPlaceholder();
    this.__pane = new CUI.Pane({
      "class": "ez5-search-main-pane cui-pane--window",
      absolute: true,
      top: {
        content: [paneHeader, this.__searchInput.getInputLayout(), this.__buttonToolbar]
      },
      center: {
        content: this.__mainSearch
      },
      bottom: false
    });
    CUI.dom.empty(this._container);
    CUI.dom.append(this._container, this.__pane.DOM);
    this.__facetManager = new FacetManager();
    this.facetBtns = [];
    this.facetButton = this.__initFacetButton("main");
    this.facetSettingsBtn = new LocaButton({
      ui: "result.manager.view.options.button",
      "class": "ez5-result-manager-button-options",
      loca_key: "result.manager.button.options",
      group: "facet",
      onClick: (function(_this) {
        return function() {
          return _this.showFacetSettingsPopover();
        };
      })(this)
    });
    this.facetBtns.push(this.facetButton, this.facetSettingsBtn);
    this.__buttonToolbar.append(this.facetBtns, "left");
    this.addSearchManager(this.__facetManager);
    if (GeoJsonColumn.isPluginInstalled() && (typeof MapSearchManager !== "undefined" && MapSearchManager !== null) && ez5.session.getCapability("geo_support")) {
      try {
        this.__mapManager = new MapSearchManager({
          collection: this._collection
        });
        this.addSearchManager(this.__mapManager);
        mapManagerSettingsBtn = this.__mapManager.getManagerSettingButton();
        this.__mapManagerBtn = MapSearchManager.getManagerButton({
          onActivate: (function(_this) {
            return function(_, flags) {
              _this.__mainSearch._center.content.getFlexHandle("left").show().open();
              _this.__mapManager.enable();
              if (!flags.initial_activate) {
                ez5.session.savePref("search.main.map", true);
                return _this.execute();
              }
            };
          })(this),
          onDeactivate: (function(_this) {
            return function(_, flags) {
              var executeSearch, ref;
              _this.__mainSearch._center.content.getFlexHandle("left").hide().close();
              executeSearch = !flags.initial_activate;
              if ((ref = _this.__mapManager) != null) {
                ref.disable(executeSearch);
              }
              if (executeSearch) {
                return ez5.session.savePref("search.main.map", false);
              }
            };
          })(this)
        });
        this.__buttonToolbar.append([this.__mapManagerBtn, mapManagerSettingsBtn], "left");
      } catch (error1) {
        error = error1;
        console.error("Error trying to initialize the search map manager", error);
      }
    }
    CUI.Events.listen({
      type: "toolbox",
      node: this.rc,
      call: (function(_this) {
        return function(ev, info) {
          return info.tools.push.apply(info.tools, _this.getCurrentTools());
        };
      })(this)
    });
    this.registerResultContainer(this.rc);
    this._collection.on({
      type: ["remove", "insert", "select"],
      instance: this,
      call: (function(_this) {
        return function(ev, info) {
          if (info.skip_update) {
            return;
          }
          _this.updateFlyoutButtonbar();
        };
      })(this)
    });
    managers = [
      new ResultStandard({
        ui: "search.main.result.standard",
        container: this.rc,
        selectable_opts: {
          collection: this._collection
        }
      }), new ResultText({
        ui: "search.main.result.text",
        container: this.rc,
        selectable_opts: {
          collection: this._collection
        }
      }), new ez5.ResultTableV2({
        ui: "search.main.result.table",
        container: this.rc,
        selectable_opts: {
          collection: this._collection
        }
      })
    ];
    if (SearchMain.managerPlugins && SearchMain.managerPlugins.length > 0) {
      ref = SearchMain.managerPlugins;
      for (i = 0, len = ref.length; i < len; i++) {
        managerPlugin = ref[i];
        managers.push(new managerPlugin({
          container: this.rc,
          selectable_opts: {
            collection: this._collection
          }
        }));
      }
    }
    resultManager = new ResultManager({
      pref: "search_main_view_data",
      managers: managers
    });
    this.addSearchManager(resultManager);
    this.__searchHierarchyManager = new SearchHierarchyManager({
      container: vl.top(),
      searchInput: this.getSearchInput(),
      savePrefName: "search_hierarchy_manager"
    });
    this.addSearchManager(this.__searchHierarchyManager);
    this.__collectionSearchManager = this.addSearchManager(new CollectionSearchManager({
      getPageSize: function() {
        return resultManager.getCurrentViewData().page_size;
      },
      collection: this._collection
    }));
    this.addSearchManager(new SortManager({
      pref: "search_main_sort_data"
    }));
    this.registerKeyboardShortcuts(this._container);
    dfr = new CUI.Deferred();
    dfr.always((function(_this) {
      return function() {
        return console.timeEnd("SearchMain.init");
      };
    })(this));
    go_on = (function(_this) {
      return function() {
        return SearchMain.__super__.init.call(_this).fail(dfr.reject).done(function() {
          if (!CUI.dom.find(".cui-layer-root")[0]) {
            _this.__searchInput.focusQueryContainer();
          }
          CUI.Events.trigger({
            type: "content-resize",
            node: _this.__pane.top()
          });
          if (ez5.session.getPref("search.main.filter")) {
            _this.facetButton.activate({
              initial_activate: true
            });
          }
          if (_this.__mapManagerBtn && !_this.__mapManagerBtn.isHidden() && ez5.session.getPref("search.main.map")) {
            _this.__mapManagerBtn.activate({
              initial_activate: true
            });
          }
          return dfr.resolve();
        });
      };
    })(this);
    console.timeLog("SearchMain.init", "AdminMessage.load...");
    if (this.__poolDeepLink()) {
      go_on();
      return dfr.promise();
    }
    AdminMessage.load("search_welcome").always((function(_this) {
      return function() {
        return console.timeLog("SearchMain.init", "AdminMessage.load done");
      };
    })(this)).fail(go_on).done((function(_this) {
      return function(__welcome_messages) {
        var ref1;
        _this.__welcome_messages = __welcome_messages;
        if (((ref1 = _this.__welcome_messages) != null ? ref1.length : void 0) > 0) {
          CUI.dom.append(_this.rc, _this.getWelcomeMessagesDiv());
          console.timeLog("SearchMain.init", "Show welcome");
        }
        return go_on();
      };
    })(this));
    return dfr.promise();
  };

  SearchMain.prototype.showFacetSettingsPopover = function() {
    return this.__facetManager.getSettingsPopover({
      element: this.facetSettingsBtn.DOM,
      onHide: (function(_this) {
        return function(changedSettings) {
          if (changedSettings) {
            return _this.execute();
          }
        };
      })(this)
    }).show();
  };

  SearchMain.prototype.getCurrentTools = function() {
    var data, share_url, tools;
    tools = SearchMain.__super__.getCurrentTools.call(this);
    tools.push(new ToolboxTool({
      group: "search",
      name: "search.refresh",
      sort: "A:3",
      run: (function(_this) {
        return function() {
          return _this.refresh();
        };
      })(this)
    }));
    if (this._collectionManager && this.hasUserInput() && this.getStoreSearchData() && ez5.session.hasSystemRight("root", "frontend_features[stored_searches]")) {
      tools.push(new ToolboxTool({
        group: "search",
        name: "search.save",
        sort: "A:5",
        run: (function(_this) {
          return function() {
            return _this.storeSearch();
          };
        })(this)
      }));
    }
    if (ez5.session.hasSystemRight("root", "frontend_features[deep_link_sharing]", "frontend_features[link_sharing]")) {
      share_url = this.getShareUrl();
      if (share_url) {
        tools.push(new ToolboxTool({
          group: "search",
          sort: "F:1",
          favorite: false,
          name: "search.present_share_url",
          run: (function(_this) {
            return function() {
              return _this.presentShareUrl();
            };
          })(this)
        }));
      }
    }
    data = this.getLastData();
    if ((data != null ? data.count : void 0) > 0) {
      if (ez5.session.hasSystemRight("root", "frontend_features[download]") && this.hasEASFields()) {
        tools.push(new ToolboxTool({
          group: "search",
          name: "search.download",
          sort: "D:1",
          disabled: this.getLastData().count > DownloadManager.maxObjects,
          loca_key: "tool.search.download",
          run: (function(_this) {
            return function() {
              var cls;
              cls = _this.getDownloadManagerClass();
              return new cls({
                search: _this
              }).startExport();
            };
          })(this)
        }));
      }
      if (ez5.session.hasSystemRight("root", "frontend_features[export]")) {
        tools.push(new ToolboxTool({
          group: "search",
          name: "search.export",
          sort: "D:2",
          run: (function(_this) {
            return function() {
              return new ExportManager({
                search: _this
              }).prepareExport();
            };
          })(this)
        }));
      }
      if (ez5.session.hasSystemRight("root", "frontend_features[print]")) {
        tools.push(new ToolboxTool({
          group: "search",
          name: "search.print",
          sort: "D:3",
          loca_key_attrs: {
            count: PrintManager.getLimit()
          },
          run: (function(_this) {
            return function() {
              var printManager;
              printManager = new PrintManager({
                search: _this,
                printFullSearch: true
              });
              return printManager.getOptionsModal().show();
            };
          })(this)
        }));
      }
      if (ez5.session.hasSystemRight("root", "frontend_features[script_runner]")) {
        tools.push(new ToolboxTool({
          group: "search",
          name: "search.script_runner",
          sort: "D:4",
          run: (function(_this) {
            return function() {
              return _this.startScriptRunner();
            };
          })(this)
        }));
      }
      if (this.hasEASFields()) {
        tools.push(new ToolboxTool({
          group: "search",
          name: "search.show.fullscreen",
          sort: "B:2",
          run: (function(_this) {
            return function() {
              return new DetailFullscreen({
                search: _this,
                offset: _this.getLastData().offset
              });
            };
          })(this)
        }));
      }
    }
    return tools;
  };

  SearchMain.prototype.getSearchHierarchyManager = function() {
    return this.__searchHierarchyManager;
  };

  SearchMain.prototype.getDetailShareUrl = function(id) {
    return window.easydb_base_prefix + ("#/detail/" + id);
  };

  SearchMain.prototype.getSharePath = function() {
    return window.easydb_base_prefix + "/search";
  };

  SearchMain.prototype.getShareUrl = function() {
    var url, url_data;
    url_data = this.getStoreAsUrlData();
    if (!url_data) {
      return null;
    }
    url = CUI.encodeUrlData(url_data, CUI.encodeURIComponentNicely);
    if (CUI.util.isEmpty(url)) {
      return null;
    }
    return document.location.origin + this.getSharePath() + "?" + url;
  };

  SearchMain.prototype.addToRequest = function(request) {
    if (ez5.version("6")) {
      if (!request.hasOwnProperty("generated_rights")) {
        request.generate_rights = true;
      }
    }
    return SearchMain.__super__.addToRequest.call(this, request);
  };

  SearchMain.prototype.startScriptRunner = function() {
    var req, search_json;
    req = new Request();
    req.for_export = true;
    this.addToRequest(req);
    search_json = req.cleanRequestForSearch();
    search_json.offset = 0;
    search_json.limit = 0;
    search_json.format = "short";
    ez5.api.search({
      json_data: search_json
    }).fail((function(_this) {
      return function() {
        return CUI.problem({
          text: $$("search.main.start.error_starting_script_runner")
        });
      };
    })(this)).done((function(_this) {
      return function(data) {
        return new ez5.ScriptRunner({
          caller: _this,
          count: data.count,
          getChunk: function(offset, limit) {
            var dfr;
            search_json.offset = offset;
            search_json.limit = limit;
            search_json.format = "short";
            dfr = new CUI.Deferred();
            ez5.api.search({
              json_data: search_json
            }).done(function(data) {
              var cos, i, len, obj, ref;
              cos = [];
              ref = data.objects;
              for (i = 0, len = ref.length; i < len; i++) {
                obj = ref[i];
                cos.push(new CollectionObject(obj));
              }
              return dfr.resolve(cos);
            }).fail(dfr.reject);
            return dfr.promise();
          }
        }).show();
      };
    })(this));
  };

  SearchMain.prototype.getShareHint = function() {
    return $$("search.main.share_url_hint", {
      url: document.location.origin + this.getSharePath()
    });
  };

  SearchMain.prototype.hasEASFields = function(user_selected) {
    if (user_selected == null) {
      user_selected = true;
    }
    if (SearchMain.__super__.hasEASFields.call(this, user_selected)) {
      return true;
    }
    return this.hasLinkedEASFields(user_selected);
  };

  SearchMain.prototype.hasLinkedEASFields = function(user_selected) {
    var f, i, j, len, len1, ot, ref, ref1;
    if (user_selected == null) {
      user_selected = true;
    }
    ref = this.getSearchObjecttypes(user_selected);
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      ref1 = ot.getAllFields();
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        f = ref1[j];
        if (f instanceof LinkedObject && f.getFirstStandardEASColumn()) {
          return true;
        }
      }
    }
    return false;
  };

  SearchMain.prototype.presentShareUrl = function() {
    var block1, block2, content, createLinkButton, createLinkResult, defaultTabContent, dia, hint, request, shareButtonbar, share_url;
    share_url = this.getShareUrl();
    if (window.easydb_server_url) {
      share_url += "&server=" + encodeURIComponent(window.easydb_server_url);
    }
    shareButtonbar = Asset.getShareButtonbar(share_url, "search.share_url");
    hint = this.getShareHint();
    defaultTabContent = new CUI.VerticalLayout({
      center: {
        content: new CUI.HorizontalLayout({
          center: {
            content: new CUI.Label({
              text: $$("search.share_url.text")
            })
          },
          right: {
            content: shareButtonbar
          }
        })
      },
      bottom: {
        content: hint ? new CUI.Label({
          text: hint,
          multiline: true,
          appearance: "secondary",
          "class": "ez5-search-share-default-hint"
        }) : void 0
      }
    });
    if (ez5.version("6")) {
      request = {
        path: new URL(share_url).pathname + new URL(share_url).search,
        alias: null,
        expires_at: null
      };
      createLinkResult = new CUI.VerticalList({
        maximize: true
      });
      createLinkButton = new CUI.Button({
        text: $$("search.share_url.shortener.create_link"),
        onClick: (function(_this) {
          return function() {
            return ez5.api.system({
              api: "/share_link",
              type: "POST",
              json_data: request
            }).done(function(data) {
              var createLink;
              createLink = function(suffix) {
                var url;
                url = (window.easydb_server_url || document.location.origin) + "/share/" + suffix;
                return new CUI.HorizontalLayout({
                  center: {
                    content: new CUI.Label({
                      text: url
                    })
                  },
                  right: {
                    content: Asset.getShareButtonbar(url, "search.share_url")
                  }
                });
              };
              createLinkResult.replace(createLink(data.share_id), "center");
              if (data.alias) {
                createLinkResult.append(createLink(data.alias), "center");
              }
              return dia.autoSize();
            });
          };
        })(this)
      });
      block1 = new CUI.Block({
        padded: false,
        "class": "ez5-search-share-block-default",
        text: $$("search.share_url.tab.default"),
        content: defaultTabContent
      });
      block2 = new CUI.Block({
        padded: false,
        "class": "ez5-search-share-block-short",
        text: $$("search.share_url.tab.short_link"),
        content: new CUI.VerticalList({
          content: [
            new CUI.Label({
              text: $$("search.share_url.shortener.info")
            }), new CUI.Form({
              fields: [
                {
                  type: CUI.Input,
                  name: "alias",
                  data: request,
                  form: {
                    label: $$("search.share_url.shortener.alias.label"),
                    hint: $$("search.share_url.shortener.alias.hint")
                  },
                  regexp: "^$|^[a-zA-Z0-9][a-zA-Z0-9\\-_~\\.]*[a-zA-Z0-9]$",
                  onDataChanged: (function(_this) {
                    return function(data, element) {
                      data.alias || (data.alias = null);
                      if (element.checkInput()) {
                        return createLinkButton.enable();
                      } else {
                        return createLinkButton.disable();
                      }
                    };
                  })(this)
                }, {
                  type: CUI.DateTime,
                  name: "expires_at",
                  data: request,
                  form: {
                    label: $$("search.share_url.shortener.expiration_date.label"),
                    hint: $$("search.share_url.shortener.expiration_date.hint")
                  },
                  onDataChanged: (function(_this) {
                    return function(data, element) {
                      data.expires_at || (data.expires_at = null);
                      if (element.checkInput()) {
                        return createLinkButton.enable();
                      } else {
                        return createLinkButton.disable();
                      }
                    };
                  })(this)
                }
              ]
            }).start(), createLinkButton, createLinkResult
          ]
        })
      });
      content = [block1, block2];
    } else {
      content = defaultTabContent;
    }
    return dia = new CUI.ConfirmationDialog({
      "class": "ez5-search-share-modal",
      title: $$("search.share_url.title"),
      content: content,
      cancel: true,
      buttons: [
        {
          loca_key: "search.share_url.button.ok",
          primary: true,
          onClick: function() {
            return dia.destroy();
          }
        }
      ]
    }).show();
  };

  SearchMain.prototype.getSearchTypeSelector = function() {
    return this.__searchTypeSelector;
  };

  SearchMain.prototype.destroy = function() {
    var ref, ref1, ref2;
    if ((ref = this.__searchTypeSelector) != null) {
      ref.destroy();
    }
    delete this.__searchTypeSelector;
    delete this.__welcome_messages;
    if ((ref1 = this._collection) != null) {
      ref1.off({
        instance: this
      });
    }
    if ((ref2 = this.layout) != null) {
      ref2.destroy();
    }
    this.layout = null;
    return SearchMain.__super__.destroy.call(this);
  };

  SearchMain.prototype.refresh = function() {
    var ref;
    if ((ref = this.__flyoutButtonbar) != null) {
      ref.destroy();
    }
    this.__flyoutButtonbar = null;
    return SearchMain.__super__.refresh.call(this).done((function(_this) {
      return function() {
        var ref1, ref2;
        if ((ref1 = _this.searchManagers) != null) {
          if ((ref2 = ref1.find(function(sm) {
            return sm instanceof SearchTypeSelector;
          })) != null) {
            ref2.__activateAll();
          }
        }
        return _this.runFirstSearch();
      };
    })(this));
  };

  SearchMain.prototype.runFirstSearch = function() {
    var dfr, ref;
    dfr = new CUI.Deferred();
    if (((ref = this.__welcome_messages) != null ? ref.length : void 0) > 0) {
      dfr.resolve();
    } else {
      this.execute().done(dfr.resolve).fail(dfr.reject);
    }
    return dfr.promise();
  };

  SearchMain.prototype.getEmptyResultDiv = function(request) {
    if (this.request_counter > 0) {
      return SearchMain.__super__.getEmptyResultDiv.call(this, request);
    }
    return this.getWelcomeMessagesDiv();
  };

  SearchMain.prototype.getWelcomeMessagesDiv = function(check_request) {
    var i, len, msg, msgs, ref, ref1, vl;
    if (check_request == null) {
      check_request = false;
    }
    if (!((ref = this.__welcome_messages) != null ? ref.length : void 0)) {
      return;
    }
    if (check_request && this.request_counter > 0) {
      return;
    }
    msgs = [];
    ref1 = this.__welcome_messages;
    for (i = 0, len = ref1.length; i < len; i++) {
      msg = ref1[i];
      msgs.push(new CUI.Block({
        content: new CUI.Label({
          markdown: true,
          multiline: true,
          text: msg.getMessageLocalized()
        })
      }));
    }
    vl = new CUI.VerticalList({
      "class": "ez5-search-main-welcome",
      content: msgs,
      maximize: true,
      attr: {
        "data-message-count": msgs.length
      }
    });
    return vl.DOM;
  };

  SearchMain.prototype.objecttypesUpdated = function(initiator) {
    var dfr, go_on;
    dfr = new CUI.Deferred();
    go_on = (function(_this) {
      return function() {
        return SearchMain.__super__.objecttypesUpdated.call(_this, initiator).done(function() {
          var ref;
          if ((ref = _this._collectionManager) != null) {
            ref.objecttypesUpdated();
          }
          _this.updateSearchButtonState();
          return dfr.resolve();
        }).fail(dfr.reject);
      };
    })(this);
    if (this.__searchTypeSelector && initiator !== this.__searchTypeSelector) {
      this.__searchTypeSelector.updateContent().done((function(_this) {
        return function() {
          return go_on();
        };
      })(this)).fail(dfr.reject);
    } else {
      go_on();
    }
    return dfr.promise();
  };

  SearchMain.prototype.executeAlwaysCallback = function() {
    this.enableSearchButton();
    return this.updateSearchButtonState();
  };

  SearchMain.prototype.updateSearchButtonState = function() {
    var ots;
    if (!this.getSearchButton()) {
      return;
    }
    ots = this.getSearchObjecttypes();
    if (ots.length === 0) {
      this.getSearchButton().disable();
    } else {
      this.getSearchButton().enable();
    }
    this.updateFlyoutButtonbar();
  };

  SearchMain.prototype.updateFlyoutButtonbar = function() {
    var collectionButtons, collectionTools, current, ref, ref1, search_btns;
    if (!this.getButtonToolbar()) {
      return;
    }
    current = this.__flyoutButtonbar;
    collectionTools = (ref = this._collection) != null ? ref.getCurrentTools(false) : void 0;
    collectionButtons = (ref1 = this._collection) != null ? ref1.getButtons(collectionTools) : void 0;
    search_btns = Toolbox.getFlyoutButtons(this.getCurrentTools());
    this.__flyoutButtonbar = new CUI.Buttonbar({
      buttons: Toolbox.mergeFlyoutButtons(collectionButtons, search_btns)
    });
    if (current) {
      return CUI.dom.replaceWith(current.DOM, this.__flyoutButtonbar.DOM);
    } else {
      return this.getButtonToolbar().append(this.__flyoutButtonbar, "right");
    }
  };

  SearchMain.prototype.getDefaultSortFilter = function() {
    return [
      {
        "field": "_system_object_id",
        "order": "DESC",
        "_level": 0
      }
    ];
  };

  SearchMain.prototype.getDefaultSortKey = function() {
    return "main.search.sort.latest";
  };

  SearchMain.prototype.getButtonToolbar = function() {
    return this.__buttonToolbar;
  };

  SearchMain.prototype.getFacetsContainer = function() {
    return this.__mainSearch.left();
  };

  SearchMain.prototype.getMapManagerContainer = function() {
    if (GeoJsonColumn.isPluginInstalled()) {
      return this.__mainSearch._center.content.left();
    } else {
      return null;
    }
  };

  SearchMain.prototype.__initFacetButton = function(mode) {
    return new LocaButton({
      "switch": true,
      ui: "search.list.filter.button",
      loca_key: "search.main.button.filter",
      "class": "ez5-button-open-facet-manager",
      group: "facet",
      onActivate: (function(_this) {
        return function(_, flags) {
          if (!flags.initial_activate) {
            ez5.session.savePref("search." + mode + ".filter", true);
          }
          _this.__mainSearch.getFlexHandle("left").show().open();
          if (!flags.initial_activate) {
            return _this.execute();
          }
        };
      })(this),
      onDeactivate: (function(_this) {
        return function(btn, flags) {
          _this.__mainSearch.getFlexHandle("left").hide().close();
          if (!flags.initial_activate) {
            ez5.session.savePref("search." + mode + ".filter", false);
            _this.__facetManager.resetFacets();
            _this.execute();
          }
        };
      })(this)
    });
  };

  SearchMain.prototype.hasFacets = function() {
    return !this.__mainSearch.getFlexHandle("left").isClosed();
  };

  SearchMain.prototype.hideFacets = function() {
    return this.facetButton.deactivate();
  };

  SearchMain.prototype.hasUserInput = function(request, excludedSearchManager) {
    if (excludedSearchManager == null) {
      excludedSearchManager = [];
    }
    return !this.__searchInput.isEmpty() || SearchMain.__super__.hasUserInput.call(this, request, excludedSearchManager);
  };

  SearchMain.prototype.getSearchInput = function() {
    return this.__searchInput;
  };

  SearchMain.prototype.getFacetManager = function() {
    return this.__facetManager;
  };

  SearchMain.prototype.addCollectionAfterSave = function(received_data) {
    var gids, i, len, obj;
    gids = [];
    for (i = 0, len = received_data.length; i < len; i++) {
      obj = received_data[i];
      if (obj[obj._objecttype]._version === 1) {
        gids.push(obj._global_object_id);
      }
    }
    if (gids.length > 0) {
      this.__searchInput.addCollectionFixedSearchInsertToday(gids);
    }
    return this;
  };

  SearchMain.prototype.showInSearch = function(queryElement, append) {
    var dfr, ref;
    if (append == null) {
      append = false;
    }
    DetailFullscreen.triggerClose();
    if ((ref = this._collectionManager) != null) {
      ref.showSearch();
    }
    dfr = new CUI.Deferred();
    this.getSearchInitializedPromise().done((function(_this) {
      return function() {
        if (append) {
          _this.getSearchInput().append(queryElement);
        } else {
          _this.emptyRequest();
          _this.getSearchInput().replaceSearchInput(queryElement);
        }
        _this.emptyCollection();
        return _this.execute().done(dfr.resolve).fail(dfr.reject);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  SearchMain.prototype.getWelcomeSearchMessages = function() {
    return this.__welcome_messages;
  };

  SearchMain.prototype.getSearchButtonOpts = function() {
    var opts;
    opts = SearchMain.__super__.getSearchButtonOpts.call(this);
    opts.id = "main-search-button";
    return opts;
  };

  SearchMain.prototype.getExpertOptionsCurrentMode = function() {
    var ref;
    return (ref = this.getSearchInput().getExpertOptions()) != null ? ref.getCurrentGroup() : void 0;
  };

  SearchMain.prototype.getAvailableMaskNames = function() {
    return this.getSearchTypeSelector().getMaskNames();
  };

  SearchMain.prototype.enableMapManager = function() {
    var ref;
    if ((ref = this.__mapManagerBtn) != null) {
      ref.show();
    }
    if (this.__mapManagerBtn.isActive() || ez5.session.getPref("search.main.map")) {
      return this.__mapManagerBtn.activate({
        initial_activate: true
      });
    }
  };

  SearchMain.prototype.disableMapManager = function() {
    var ref, ref1;
    this.__mainSearch.getFlexHandle("right").hide().close();
    if ((ref = this.__mapManager) != null) {
      ref.disable();
    }
    return (ref1 = this.__mapManagerBtn) != null ? ref1.hide() : void 0;
  };

  return SearchMain;

})(Search);

ez5.session_ready(function() {
  return SearchMain.managerPlugins = [];
});
// Generated by CoffeeScript 1.12.7
var SearchMainHeadless,
  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;

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

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

  SearchMainHeadless.prototype.initOpts = function() {
    SearchMainHeadless.__super__.initOpts.call(this);
    this.removeOpt("container");
    return this.removeOpt("collection");
  };

  SearchMainHeadless.prototype.runFirstSearch = function() {
    return this.execute();
  };

  SearchMainHeadless.prototype.init = function() {};

  return SearchMainHeadless;

})(SearchMain);
// Generated by CoffeeScript 1.12.7
var CollectionSearchManager, CollectionSearchManagerProxy,
  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;

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

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

  CollectionSearchManager.prototype.initOpts = function() {
    CollectionSearchManager.__super__.initOpts.call(this);
    return this.addOpts({
      toolbox_group: {
        "default": "search",
        check: String
      },
      collection: {
        mandatory: true,
        check: Collection
      },
      getPageSize: {
        check: Function
      }
    });
  };

  CollectionSearchManager.prototype.getCurrentTools = function() {
    var data, isPageSelectDisabled, objectsSelectedCount, ref, search, selectCurrentObjects, tools;
    tools = [];
    data = this.getSearch().getLastData();
    if ((data != null ? data.count : void 0) > 0) {
      search = (function(_this) {
        return function(limit, offset) {
          return _this.getSearch().execute(new Request({
            searchManagers: [
              new CollectionSearchManagerProxy({
                collection: _this._collection,
                limit: limit,
                offset: offset
              })
            ],
            exclusive_show: true
          })).always(function() {
            return ez5.splash.hide();
          });
        };
      })(this);
      selectCurrentObjects = (function(_this) {
        return function() {
          var collectionObjects, i, len, object, ref, ref1;
          if (!(_this._collection instanceof CollectionSelection)) {
            return;
          }
          collectionObjects = [];
          ref1 = (ref = _this.getSearch().getLastData()) != null ? ref.objects : void 0;
          for (i = 0, len = ref1.length; i < len; i++) {
            object = ref1[i];
            collectionObjects.push(new CollectionObject(object));
          }
          return _this._collection.insertObjects(collectionObjects);
        };
      })(this);
      if (!this._collection.isSingleMode()) {
        tools.push(new ToolboxTool({
          group: this._toolbox_group,
          name: "selection.all",
          sort: "A:1",
          disabled: data.count > SearchUtil.MAX_OBJECTS_COUNT,
          run: (function(_this) {
            return function() {
              ez5.splash.show("main.list.objecttypes.tool.select-all");
              return search();
            };
          })(this)
        }));
      }
      if (this._getPageSize) {
        objectsSelectedCount = ((ref = this._collection.getObjects()) != null ? ref.length : void 0) || 0;
        isPageSelectDisabled = (function(_this) {
          return function() {
            var ref1, ref2;
            if (objectsSelectedCount === 0 && ((ref1 = _this.getSearch().getLastData()) != null ? (ref2 = ref1.objects) != null ? ref2.length : void 0 : void 0) > 0) {
              return false;
            }
            return _this._collection.areAllObjectsSelectedInContainer() || objectsSelectedCount >= SearchUtil.MAX_OBJECTS_COUNT;
          };
        })(this);
        tools.push(new ToolboxTool({
          group: this._toolbox_group,
          name: "selection.page",
          sort: "A:1",
          disabled: isPageSelectDisabled(),
          run: (function(_this) {
            return function() {
              if (ez5.version("6")) {
                return selectCurrentObjects();
              } else {
                ez5.splash.show("main.list.objecttypes.tool.select-page");
                return search(_this._getPageSize(), data.offset);
              }
            };
          })(this)
        }));
        if (objectsSelectedCount > 0) {
          tools.push(new ToolboxTool({
            group: this._toolbox_group,
            name: "selection.clear",
            sort: "A:3",
            run: (function(_this) {
              return function() {
                var ref1;
                return (ref1 = _this._collection) != null ? ref1.removeObjects() : void 0;
              };
            })(this)
          }));
        }
      }
    }
    return tools;
  };

  CollectionSearchManager.prototype.selectCurrentObjects = function() {};

  return CollectionSearchManager;

})(SearchManager);

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

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

  CollectionSearchManagerProxy.prototype.initOpts = function() {
    CollectionSearchManagerProxy.__super__.initOpts.call(this);
    return this.addOpts({
      limit: {
        mandatory: true,
        "default": 1000
      },
      offset: {
        mandatory: true,
        "default": 0
      },
      collection: {
        mandatory: true,
        check: Collection
      }
    });
  };

  CollectionSearchManagerProxy.prototype.addToRequest = function(request) {
    request.format = "standard";
    request.offset = this._offset;
    request.limit = this._limit;
    return request;
  };

  CollectionSearchManagerProxy.prototype.showResult = function(request, data) {
    var collectionObjects, deferred, i, len, obj, objectByGlobalObjectId, ref, tempCollection;
    deferred = new CUI.Deferred();
    objectByGlobalObjectId = {};
    ref = data.objects;
    for (i = 0, len = ref.length; i < len; i++) {
      obj = ref[i];
      objectByGlobalObjectId[obj._global_object_id] = new CollectionObject(obj);
    }
    collectionObjects = Object.values(objectByGlobalObjectId);
    tempCollection = new CollectionMemory();
    tempCollection.insertObjects(collectionObjects).done((function(_this) {
      return function() {
        var req, search;
        search = new SearchCollectionHeadless({
          collection: tempCollection
        });
        req = new Request();
        req.format = "short";
        req.limit = _this._limit;
        req.offset = _this._offset;
        return search.execute(req).done(function(req, data) {
          var j, len1, object, ref1;
          ref1 = data.objects;
          for (j = 0, len1 = ref1.length; j < len1; j++) {
            object = ref1[j];
            if (objectByGlobalObjectId[object._global_object_id].getObject()._format === "standard") {
              continue;
            }
            objectByGlobalObjectId[object._global_object_id].setObject(object);
          }
          return _this._collection.insertObjects(collectionObjects).done(deferred.resolve).fail(deferred.reject);
        }).fail(deferred.reject);
      };
    })(this)).fail(deferred.reject);
    return deferred.promise();
  };

  return CollectionSearchManagerProxy;

})(SearchManager);
// Generated by CoffeeScript 1.12.7
var TrashSearchManager,
  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;

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

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

  TrashSearchManager.prototype.initOpts = function() {
    TrashSearchManager.__super__.initOpts.call(this);
    return this.addOpts({
      active: {
        "default": false,
        check: Boolean
      },
      only_deleted: {
        "default": true,
        check: Boolean
      }
    });
  };

  TrashSearchManager.prototype.readOpts = function() {
    TrashSearchManager.__super__.readOpts.call(this);
    this.__layout = new CUI.PaneToolbar({
      "class": "ez5-trash-search-manager",
      left: {}
    });
    this.__active = this._active;
    return this.__onlyDeleted = this._only_deleted;
  };

  TrashSearchManager.prototype.init = function() {
    return TrashSearchManager.__super__.init.call(this);
  };

  TrashSearchManager.prototype.addToRequest = function(request) {
    var deletedFilter;
    if (!TrashSearchManager.canSeeDeleted()) {
      return request;
    }
    if (this.isActive()) {
      request.include_deleted = true;
      if (this.__onlyDeleted) {
        if (!request.search) {
          request.search = [];
        }
        deletedFilter = {
          type: "in",
          bool: "must_not",
          fields: ["_latest_version_deleted_at"],
          "in": [null],
          __filter: "TrashSearchManager"
        };
        request.search.push(deletedFilter);
      }
    }
    return request;
  };

  TrashSearchManager.prototype.hasUserInput = function() {
    return false;
  };

  TrashSearchManager.prototype.isActive = function() {
    return this.__active;
  };

  TrashSearchManager.prototype.isOnlyDeleted = function() {
    return this.__onlyDeleted;
  };

  TrashSearchManager.prototype.setActive = function(active, executeSearch) {
    var ref;
    if (executeSearch == null) {
      executeSearch = true;
    }
    this.__active = active;
    if (executeSearch) {
      return (ref = this.getSearch()) != null ? ref.execute() : void 0;
    }
  };

  TrashSearchManager.prototype.emptyRequest = function() {};

  TrashSearchManager.prototype.getStoreData = function(data) {};

  TrashSearchManager.prototype.getStoreAsUrlData = function(url_data) {};

  TrashSearchManager.prototype.initFromUrlData = function(url_data) {};

  TrashSearchManager.canPurge = function() {
    return ez5.session.hasSystemRight("root", "trash_access[level][purge]");
  };

  TrashSearchManager.canUndelete = function() {
    if (this.canPurge()) {
      return true;
    }
    return ez5.session.hasSystemRight("root", "trash_access[level][undelete]");
  };

  TrashSearchManager.canSeeDeleted = function() {
    return ez5.version("6") && ez5.session.hasSystemRight("root", "trash_access[level]");
  };

  return TrashSearchManager;

})(SearchManager);
// Generated by CoffeeScript 1.12.7
var PermanentTrayMessagesApp,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

ez5.getPermanentMessageApp = function(adminMessage) {
  var PermanentMessageApp;
  return PermanentMessageApp = (function(superClass) {
    extend(PermanentMessageApp, superClass);

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

    PermanentMessageApp.is_allowed = function() {
      return true;
    };

    PermanentMessageApp.isStartApp = function() {
      return false;
    };

    PermanentMessageApp.group = function() {
      return "zzz_info";
    };

    PermanentMessageApp.submenu = function() {
      return "zzz_info";
    };

    PermanentMessageApp.label = function() {
      return "permanent.messages.label";
    };

    PermanentMessageApp.getDisplay = function() {
      return {
        text: adminMessage.getTitleLocalized(),
        onClick: (function(_this) {
          return function() {
            return adminMessage.showMessage();
          };
        })(this)
      };
    };

    return PermanentMessageApp;

  })(RootMenuApp);
};

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

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

  PermanentTrayMessagesApp.prototype.readOpts = function() {
    PermanentTrayMessagesApp.__super__.readOpts.call(this);
    return this.msgs_shown_json = [];
  };

  PermanentTrayMessagesApp.prototype.__addButton = function(message) {
    var btn_opts, customIcon, ref;
    btn_opts = {
      appearance: "transparent-border",
      "class": "ez5-permanent-messages ez5-permanent-messages--" + message.getWebfrontendType(),
      onClick: (function(_this) {
        return function() {
          return message.showMessage();
        };
      })(this)
    };
    switch (message.getWebfrontendType()) {
      case "maintenance":
      case "maintenance_warning":
        btn_opts.icon = "warning";
        break;
      default:
        customIcon = (ref = message.getWebfrontendProps()) != null ? ref.icon : void 0;
        if (!CUI.util.isEmpty(customIcon)) {
          btn_opts.icon = customIcon;
        }
        btn_opts.text = message.getTitleLocalized();
    }
    return CUI.dom.append(this.display, new CUI.Button(btn_opts));
  };

  PermanentTrayMessagesApp.prototype.load = function() {
    var msgs, msgs_show;
    CUI.clearTimeout(this.reload_timeout);
    msgs = [];
    msgs_show = [];
    AdminMessage.load("maintenance_warning").done((function(_this) {
      return function(adminMessages) {
        var i, len, msg;
        for (i = 0, len = adminMessages.length; i < len; i += 1) {
          msg = adminMessages[i];
          msgs.push(msg);
          msgs_show.push({
            msg: msg,
            ok_button: true
          });
        }
        return AdminMessage.load("maintenance", null, false).done(function(adminMessages) {
          var idx, j, len1, ms, now, ok_button, schedule_reload, start;
          schedule_reload = null;
          now = new Date();
          for (idx = j = 0, len1 = adminMessages.length; j < len1; idx = ++j) {
            msg = adminMessages[idx];
            if (idx === adminMessages.length - 1) {
              ok_button = false;
            } else {
              ok_button = true;
            }
            if (ez5.session.hasSystemRight("system.root")) {
              ok_button = true;
            }
            start = msg.getStartDate();
            if (start && start > now) {
              if (schedule_reload === null || start < schedule_reload) {
                schedule_reload = start;
              }
            } else {
              msgs.push(msg);
              msgs_show.push({
                msg: msg,
                ok_button: ok_button
              });
            }
          }
          if (schedule_reload !== null) {
            ms = (schedule_reload - now) + 1000;
            console.info("PermanentMessages: Schedule reload of tray at: ", schedule_reload, ms);
            _this.reload_timeout = CUI.setTimeout({
              ms: ms,
              call: function() {
                return _this.load();
              }
            });
          }
          return AdminMessage.load("permanent_tray").done(function(adminMessages) {
            var k, l, len2, len3, show_next_msg;
            for (k = 0, len2 = adminMessages.length; k < len2; k += 1) {
              msg = adminMessages[k];
              msgs.push(msg);
            }
            CUI.dom.empty(_this.display);
            for (l = 0, len3 = msgs.length; l < len3; l++) {
              msg = msgs[l];
              _this.__addButton(msg);
            }
            show_next_msg = function() {
              var info, msg_json;
              msgs = msgs_show.splice(0, 1);
              if (msgs.length === 0) {
                return;
              }
              info = msgs[0];
              msg_json = JSON.stringify(info.msg.getStringifiedMessage());
              if (indexOf.call(_this.msgs_shown_json, msg_json) >= 0) {
                show_next_msg();
                return;
              }
              _this.msgs_shown_json.push(msg_json);
              return info.msg.showMessage(null, info.ok_button).done(function() {
                return show_next_msg();
              });
            };
            return show_next_msg();
          });
        });
      };
    })(this));
  };

  PermanentTrayMessagesApp.prototype.getDisplay = function() {
    PermanentTrayMessagesApp.__super__.getDisplay.call(this);
    EventPoller.listen({
      instance: this,
      filter: {
        type: "OBJECT_INDEX",
        basetype: "message"
      },
      call: (function(_this) {
        return function() {
          return _this.load();
        };
      })(this)
    });
    this.load();
    return this.display;
  };

  PermanentTrayMessagesApp.prototype.getSortValue = function() {
    return -1;
  };

  PermanentTrayMessagesApp.prototype.getClass = function() {
    return "ez5-permanent-messages";
  };

  PermanentTrayMessagesApp.prototype.destroy = function() {
    PermanentTrayMessagesApp.__super__.destroy.call(this);
    CUI.clearTimeout(this.reload_timeout);
    return CUI.Events.ignore({
      instance: this
    });
  };

  return PermanentTrayMessagesApp;

})(TrayApp);

ez5.session_ready(function() {
  var dfr;
  ez5.tray.registerApp(new PermanentTrayMessagesApp());
  dfr = new CUI.Deferred();
  console.timeLog("Start", "AdminMessage loading...");
  AdminMessage.load("permanent").done((function(_this) {
    return function(adminMessages) {
      var adminMessage, i, len;
      for (i = 0, len = adminMessages.length; i < len; i++) {
        adminMessage = adminMessages[i];
        ez5.rootMenu.registerApp(ez5.getPermanentMessageApp(adminMessage));
      }
      console.timeLog("Start", "AdminMessage loaded");
      return dfr.resolve();
    };
  })(this)).fail(dfr.reject);
  return dfr.promise();
});
// Generated by CoffeeScript 1.12.7
var BaseConfigManager,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  BaseConfigManager.label = function() {
    return "admin.menu.configmanager";
  };

  BaseConfigManager.group = function() {
    return "zza_administration";
  };

  BaseConfigManager.submenu = function() {
    return "administration";
  };

  BaseConfigManager.path = function() {
    return ["configmanager"];
  };

  BaseConfigManager.is_allowed = function() {
    return ez5.session.hasSystemRight("root", "config");
  };

  BaseConfigManager.prototype.readOpts = function() {
    BaseConfigManager.__super__.readOpts.call(this);
    return this.config = [];
  };

  BaseConfigManager.prototype.allow_unload = function() {
    if (this.hasChanges()) {
      return CUI.confirm({
        text: $$("base.config.manager.unsaved_changes.text"),
        button_text_ok: $$("base.config.manager.unsaved_changes.button_ok"),
        button_text_cancel: $$("base.config.manager.unsaved_changes.button_cancel")
      });
    } else {
      return CUI.resolvedPromise();
    }
  };

  BaseConfigManager.prototype.load = function() {
    BaseConfigManager.__super__.load.call(this);
    this.pane = new CUI.HorizontalLayout();
    ez5.rootLayout.replace(this.pane, "center");
    new CUI.WaitBlock({
      element: this.pane,
      text: $$("base.config.manager.loading")
    }).show();
    return ez5.server({
      api: "/config/list"
    }).done((function(_this) {
      return function(baseConfig) {
        _this.baseConfig = baseConfig;
        return ez5.api.config().done(function(config1) {
          _this.config = config1;
          _this.show();
          return _this.initData();
        });
      };
    })(this));
  };

  BaseConfigManager.prototype.unload = function() {
    var ref;
    this.baseConfigs = null;
    this.config = null;
    this.baseConfig = null;
    if ((ref = this.pane) != null) {
      ref.destroy();
    }
    this.pane = null;
    return BaseConfigManager.__super__.unload.call(this);
  };

  BaseConfigManager.prototype.initData = function() {
    return this.initialData = JSON.stringify(this.getSaveData());
  };

  BaseConfigManager.prototype.show = function() {
    var downloadButton, fileReader, i, len, listViewBlock, listViewBlockPlugins, listViewTree, listViewTreePlugins, openPromises, pluginRow, ref, rows, select_node, simplePane, uploadButton, verticalLayout;
    rows = this.getRows();
    this.saveButton = new LocaButton({
      ui: "base-config-manager-save-button",
      loca_key: "base.config.manager.button.save",
      disabled: true,
      text: $$("base.save"),
      primary: true,
      onClick: (function(_this) {
        return function(ev, btn) {
          if (_this.__preSaveValidation()) {
            btn.disable();
            ez5.splash.show('system.list.manager.item.saving');
            return _this.saveForm(ev).done(function() {
              console.log(ez5.splash);
              ez5.splash.done('system.list.manager.item.saved');
              return ez5.splash.hide(function() {
                return ez5.session.handleBaseConfigUpdate();
              });
            }).fail(function() {
              return ez5.splash.hide();
            }).always(function() {
              return btn.enable();
            });
          }
        };
      })(this)
    });
    downloadButton = new LocaButton({
      loca_key: "base.config.manager.button.download",
      onClick: (function(_this) {
        return function(ev) {
          var cleaned, ref, ref1, sd;
          sd = _this.getDownloadData();
          if (ev.hasModifierKey()) {
            sd.system["export"].xslts = [];
            if ((ref = sd.system["login.background_image"]) != null) {
              ref.image = {};
            }
            if ((ref1 = sd.system["logo"]) != null) {
              ref1.logo = {};
            }
            cleaned = "-no-files";
          } else {
            cleaned = "";
          }
          sd.__EASYDB_BASE_CONFIG__ = true;
          return CUI.FileReader.save(ez5.session.getEasydbName() + "_BaseConfig_" + CUI.util.moment().format('YYYY-MM-DD') + cleaned + ".json", JSON.stringify(sd, null, "    "));
        };
      })(this)
    });
    fileReader = new CUI.FileReader({
      onDone: (function(_this) {
        return function(file) {
          var cleanedSourceConfig, config, finishUpload, i, info, k, key, len, localizedProtectedParams, param, plugin, pluginName, pname, protectedParams, ref, ref1, ref2, ref3, ref4, ref5, ref6, targetConfig, v, value;
          try {
            config = JSON.parse(file.getResult());
          } catch (error) {}
          if (!(config != null ? config.__EASYDB_BASE_CONFIG__ : void 0) || !CUI.util.isPlainObject(config.system)) {
            CUI.problem({
              text: $$("base.config.manager.error.loading")
            });
            return;
          }
          finishUpload = function() {
            _this.show();
            _this.setStatus();
            return CUI.alert({
              text: $$("base.config.manager.success.loading")
            });
          };
          protectedParams = [];
          ref = _this.config.system;
          for (key in ref) {
            info = ref[key];
            for (param in info) {
              value = info[param];
              if (param === "email" || param === "email_server" || param === "objectstore" || param === "license") {
                cleanedSourceConfig = CUI.util.copyObject(_this.config.system[key][param]);
                for (k in cleanedSourceConfig) {
                  v = cleanedSourceConfig[k];
                  if (k.match(/:info$/)) {
                    delete cleanedSourceConfig[k];
                  }
                }
                if (!((ref1 = config.system[key]) != null ? ref1[param] : void 0)) {
                  continue;
                }
                targetConfig = CUI.util.copyObject(config.system[key][param]);
                if (ez5.version("6")) {
                  for (k in targetConfig) {
                    v = targetConfig[k];
                    if (k.match(/:info$/)) {
                      delete targetConfig[k];
                    }
                  }
                }
                if (!CUI.util.isEmpty(cleanedSourceConfig) && !CUI.util.isEqual(targetConfig, cleanedSourceConfig)) {
                  protectedParams.push(param);
                  continue;
                }
              }
              if (((ref2 = config.system[key]) != null ? ref2[param] : void 0) !== void 0) {
                _this.config.system[key][param] = config.system[key][param];
              }
            }
          }
          if (ez5.version("6")) {
            if (config.plugin) {
              ref3 = _this.config.plugin;
              for (pluginName in ref3) {
                plugin = ref3[pluginName];
                for (key in plugin) {
                  info = plugin[key];
                  for (param in info) {
                    value = info[param];
                    if (((ref4 = config.plugin[pluginName]) != null ? (ref5 = ref4[key]) != null ? ref5[param] : void 0 : void 0) !== void 0) {
                      _this.config.plugin[pluginName][key][param] = config.plugin[pluginName][key][param];
                    }
                  }
                }
              }
            } else {
              ref6 = _this.config.plugin;
              for (pluginName in ref6) {
                plugin = ref6[pluginName];
                for (key in plugin) {
                  info = plugin[key];
                  for (param in info) {
                    value = info[param];
                    if (config.system[param] !== void 0) {
                      _this.config.plugin[pluginName][key][param] = config.system[param];
                    }
                  }
                }
              }
            }
          }
          if (protectedParams.length > 0) {
            localizedProtectedParams = [];
            for (i = 0, len = protectedParams.length; i < len; i++) {
              pname = protectedParams[i];
              localizedProtectedParams.push($$("base.config.manager.alert.protected_params." + pname));
            }
            CUI.confirm({
              markdown: true,
              text: $$("base.config.manager.alert.protected_params", {
                params: "**" + (localizedProtectedParams.join(", ")) + "**"
              }),
              button_text_ok: $$("base.config.manager.alert.protected_params.button_ok"),
              button_text_cancel: $$("base.config.manager.alert.protected_params.button_cancel")
            }).done(function() {
              var ref7, results;
              ref7 = _this.config.system;
              results = [];
              for (key in ref7) {
                info = ref7[key];
                results.push((function() {
                  var ref8, results1;
                  results1 = [];
                  for (param in info) {
                    value = info[param];
                    if (indexOf.call(protectedParams, param) >= 0) {
                      if (((ref8 = config.system[key]) != null ? ref8[param] : void 0) !== void 0) {
                        results1.push(this.config.system[key][param] = config.system[key][param]);
                      } else {
                        results1.push(void 0);
                      }
                    } else {
                      results1.push(void 0);
                    }
                  }
                  return results1;
                }).call(_this));
              }
              return results;
            }).always(function() {
              return finishUpload();
            });
          } else {
            finishUpload();
          }
        };
      })(this)
    });
    if (ez5.session.isReadOnly()) {
      uploadButton = new CUI.Button({
        text: $$("base.config.manager.button.upload|text"),
        icon: $$("base.config.manager.button.upload|icon"),
        onClick: (function(_this) {
          return function() {
            return CUI.problem({
              text: $$("base.error.user.read_only_mode")
            });
          };
        })(this)
      });
    } else {
      uploadButton = new CUI.FileUploadButton({
        text: $$("base.config.manager.button.upload|text"),
        icon: $$("base.config.manager.button.upload|icon"),
        multiple: false,
        fileUpload: fileReader
      });
    }
    this.menuButton = new LocaButton({
      loca_key: "base.config.manager.menu",
      menu: {
        items: [downloadButton, uploadButton]
      }
    });
    simplePane = new CUI.SimplePane({
      "class": "cui-pane--window",
      title: $$("base.config.manager.pane.left.title"),
      footer_right: this.menuButton
    });
    if (ez5.version("6")) {
      listViewTree = new CUI.ListViewTree({
        cols: ["maximize"],
        selectableRows: true,
        no_hierarchy: true,
        rowMove: false,
        onSelect: (function(_this) {
          return function() {
            var ref;
            if ((ref = listViewTreePlugins.getSelectedNode()) != null) {
              ref.deselect();
            }
            if (ez5.version("6")) {
              _this.__lastSelectInfo = {
                type: "base",
                idx: listViewTree.getSelectedNode().getNodeId()
              };
            }
          };
        })(this)
      });
      listViewBlock = new CUI.Block({
        text: $$("base.config.manager.pane.left.base-plugins.title"),
        "class": "ez5-base-config-manager-list-block",
        padded: false,
        level: 3,
        appearance: "muted"
      });
      listViewBlock.append(listViewTree.render(), "content");
      listViewTreePlugins = new CUI.ListViewTree({
        cols: ["maximize"],
        selectableRows: true,
        no_hierarchy: true,
        rowMove: false,
        onSelect: (function(_this) {
          return function() {
            var ref;
            if ((ref = listViewTree.getSelectedNode()) != null) {
              ref.deselect();
            }
            if (ez5.version("6")) {
              _this.__lastSelectInfo = {
                type: "plugin",
                idx: listViewTreePlugins.getSelectedNode().getNodeId()
              };
            }
          };
        })(this)
      });
      listViewBlockPlugins = new CUI.Block({
        text: $$("base.config.manager.pane.left.plugins.title"),
        "class": "ez5-base-config-manager-list-block",
        padded: false,
        level: 3,
        appearance: "muted"
      });
      listViewBlockPlugins.append(listViewTreePlugins.render(), "content");
      simplePane.append(listViewBlock, "center");
      simplePane.append(listViewBlockPlugins, "center");
    } else {
      listViewTree = new CUI.ListViewTree({
        cols: ["maximize"],
        selectableRows: true,
        no_hierarchy: true,
        rowMove: false
      });
      simplePane.append(listViewTree.render(), "center");
    }
    verticalLayout = new CUI.VerticalLayout({
      maximize: true,
      bottom: {
        content: new CUI.Toolbar({
          right: {
            content: this.saveButton
          }
        })
      }
    });
    this.pane = new CUI.HorizontalLayout({
      left: {
        "class": "ez5-base-config-manager-west",
        content: simplePane,
        flexHandle: {
          label: new LocaLabel({
            loca_key: "base.config.manager.flex.label"
          }),
          state_name: "admin-manager-left",
          hidden: false
        }
      },
      center: {
        content: verticalLayout
      }
    });
    ref = rows.plugin_rows;
    for (i = 0, len = ref.length; i < len; i++) {
      pluginRow = ref[i];
      if (ez5.version("6") && pluginRow.plugin) {
        listViewTreePlugins.root.children.push(new PluginBaseConfigItem({
          row: pluginRow,
          container: verticalLayout.center()
        }));
      } else {
        listViewTree.root.children.push(new BaseConfigItem({
          row: pluginRow,
          container: verticalLayout.center()
        }));
      }
    }
    this.registerDataChangedListener(this.pane.DOM);
    openPromises = [];
    if (ez5.version("6")) {
      select_node = function(list, nodeId) {
        var c, j, len1, ref1, ref2;
        ref2 = ((ref1 = list.root) != null ? ref1.children : void 0) || [];
        for (j = 0, len1 = ref2.length; j < len1; j++) {
          c = ref2[j];
          if (c.getNodeId() === nodeId) {
            c.select();
            return;
          }
        }
      };
      openPromises.push(listViewTreePlugins.root.open());
      openPromises.push(listViewTree.root.open());
      CUI.whenAll(openPromises).done((function(_this) {
        return function() {
          if (_this.__lastSelectInfo) {
            if (_this.__lastSelectInfo.type === "plugin") {
              return select_node(listViewTreePlugins, _this.__lastSelectInfo.idx);
            } else {
              return select_node(listViewTree, _this.__lastSelectInfo.idx);
            }
          } else {
            return listViewTree.root.children[0].select();
          }
        };
      })(this));
    } else {
      listViewTree.root.open().done((function(_this) {
        return function() {
          return listViewTree.root.children[0].select();
        };
      })(this));
    }
    ez5.rootLayout.replace(this.pane, "center");
    return this;
  };

  BaseConfigManager.prototype.hasChanges = function() {
    if (!this.initialData) {
      return false;
    }
    if (this.initialData === JSON.stringify(this.getSaveData())) {
      return false;
    } else {
      return true;
    }
  };

  BaseConfigManager.prototype.registerDataChangedListener = function(div) {
    CUI.Events.listen({
      type: ["data-changed", "editor-changed", "editor-update-asset-browser"],
      node: div,
      call: (function(_this) {
        return function(ev, info) {
          return _this.setStatus();
        };
      })(this)
    });
    return div;
  };

  BaseConfigManager.prototype.setStatus = function() {
    if (this.hasChanges()) {
      return this.saveButton.enable();
    } else {
      return this.saveButton.disable();
    }
  };

  BaseConfigManager.prototype.getRows = function() {
    var initializeData, initializePluginData, plugin, pluginName, plugin_rows, ref, ref1, ref2, ref3;
    if (ez5.version("6")) {
      initializeData = BaseConfig.initialize({
        data: ((ref = this.config.system) != null ? ref.config : void 0) || {},
        config: this.baseConfig.system.defs,
        group_order: this.baseConfig.system.group_order,
        l10n_prefix: "server.config.group",
        BaseConfigClass: SystemBaseConfig
      });
      this.baseConfigs = initializeData.baseConfigs;
      plugin_rows = initializeData.plugin_rows;
      ref1 = this.baseConfig.plugin;
      for (pluginName in ref1) {
        plugin = ref1[pluginName];
        initializePluginData = BaseConfig.initialize({
          data: ((ref2 = this.config.plugin) != null ? (ref3 = ref2[pluginName]) != null ? ref3.config : void 0 : void 0) || {},
          config: plugin.defs,
          l10n_prefix: "server.config.group",
          BaseConfigClass: PluginBaseConfig
        });
        this.baseConfigs = this.baseConfigs.concat(initializePluginData.baseConfigs);
        plugin_rows = plugin_rows.concat(initializePluginData.plugin_rows);
      }
    } else {
      initializeData = BaseConfig.initialize({
        data: this.config.system || {},
        config: this.baseConfig.system,
        l10n_prefix: "server.config.group",
        BaseConfigClass: SystemBaseConfig
      });
      this.baseConfigs = initializeData.baseConfigs;
      plugin_rows = initializeData.plugin_rows;
    }
    plugin_rows.sort(function(a, b) {
      if (a.sort > -1 && b.sort > -1) {
        return CUI.util.compareIndex(a.sort, b.sort);
      }
      if (ez5.version("6")) {
        return a.name.localeCompare(b.name);
      } else {
        return a.text.localeCompare(b.text);
      }
    });
    return {
      plugin_rows: plugin_rows
    };
  };

  BaseConfigManager.prototype.getDownloadData = function() {
    return this.getSaveData(true);
  };

  BaseConfigManager.prototype.getSaveData = function(forDownload) {
    var bc, i, j, len, len1, pluginName, ref, ref1, save_data;
    if (forDownload == null) {
      forDownload = false;
    }
    if (ez5.version("6")) {
      save_data = {
        system: {
          config: {}
        },
        plugin: {}
      };
      ref = this.baseConfigs;
      for (i = 0, len = ref.length; i < len; i++) {
        bc = ref[i];
        if (bc instanceof PluginBaseConfig) {
          pluginName = bc.getPluginName();
          if (!save_data.plugin[pluginName]) {
            save_data.plugin[pluginName] = {
              config: {}
            };
          }
          bc.getSaveData(save_data.plugin[pluginName].config, forDownload);
        } else {
          bc.getSaveData(save_data.system.config, forDownload);
        }
      }
    } else {
      save_data = {
        system: {}
      };
      ref1 = this.baseConfigs;
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        bc = ref1[j];
        bc.getSaveData(save_data.system);
      }
    }
    return save_data;
  };

  BaseConfigManager.prototype.__preSaveValidation = function() {
    var bc, error_text, errors, errors_markdown_list, i, len, ref;
    if (!ez5.version("6")) {
      return true;
    }
    errors = [];
    ref = this.baseConfigs;
    for (i = 0, len = ref.length; i < len; i++) {
      bc = ref[i];
      bc.validateData(errors);
    }
    if (errors.length > 0) {
      errors_markdown_list = errors.map(function(e) {
        return "\n - " + e;
      });
      errors_markdown_list = errors_markdown_list.join();
      error_text = $$("base.config.manager.error.validation", {
        errors: errors_markdown_list
      });
      CUI.problem({
        text: error_text,
        title: $$("base.config.manager.error.validation.title"),
        markdown: true
      });
      return false;
    }
    return true;
  };

  BaseConfigManager.prototype.saveForm = function(ev) {
    var dfr, save_data;
    save_data = this.getSaveData();
    if (ev.hasModifierKey()) {
      console.debug(CUI.util.dump(save_data));
      return CUI.rejectedPromise();
    }
    dfr = new CUI.Deferred();
    ez5.server({
      api: "/config",
      type: "POST",
      json_data: save_data
    }).fail(dfr.reject).done((function(_this) {
      return function(config1) {
        _this.config = config1;
        if (!_this.config) {
          CUI.problem({
            text: $$("base.config.manager.error.loading")
          });
          dfr.reject();
          return;
        }
        _this.show();
        _this.initData();
        return dfr.resolve();
      };
    })(this));
    return dfr.promise();
  };

  return BaseConfigManager;

})(RootMenuApp);

ez5.session_ready(function() {
  return ez5.rootMenu.registerApp(BaseConfigManager);
});
ez5.admin = ez5.admin || {}
ez5.admin.version = "CURRENT";

ez5.admin.datatypes = [
	["text_oneline", { group: 0, check: ["not_empty", "email", "regexp"], length: true } ],
	["text_l10n_oneline", { group: 0, check: ["not_empty", "regexp"], length: true } ],
	["text", { group: 0, check: ["not_empty", "regexp"], length: true } ],
	["text_l10n", { group: 0, check: ["not_empty", "regexp"], length: true } ],
	["string", { group: 0, check: ["not_empty", "email", "regexp"], length: true } ],

	["date", { group: 1, check: ["not_empty", "daterange"] } ],
	["daterange", { group: 1, check: ["not_empty", "daterange"] } ],
	["datetime", { group: 1, check: ["not_empty", "datetimerange"] } ],

	["number", { group: 2, check: ["not_empty", "numberrange"] } ],
	["integer.2", { group: 2, check: ["not_empty", "numberrange.2"] } ],
	["double", { group: 2, check: ["not_empty", "doublerange"] }],

	["eas", { group: 3, check: ["not_empty"] } ],
	["geo_json", { group: 3, check: ["not_empty"] } ], // This will be removed if version is not greater than 6.7
	["boolean", { group: 3, check: [] } ]
];

ez5.admin.fylrDataTypes = [
	"double"
];

ez5.admin.datatype = function(type) {
	return CUI.util.findInArray(null, ez5.admin.datatypes, function(v) { return v[0] == type; });
}

// return all table ids of nested tables
ez5.admin.get_dependent_table_ids = function(table_id, dependent_table_ids) {
	if (!dependent_table_ids) {
		dependent_table_ids = [];
	}
	ez5.schema[ez5.admin.version].tables.forEach(function(table) {
		if (table.owned_by && table.owned_by.other_table_id === table_id) {
			dependent_table_ids.push(table.table_id);
			ez5.admin.get_dependent_table_ids(table.table_id, dependent_table_ids);
		}
	});
	return dependent_table_ids;
}

// return all table ids of linked tables other
// than the nested tables
ez5.admin.get_linked_table_ids = function(table_id, linked_table_ids, already_checked) {
	if (!already_checked) {
		already_checked = [];
	}
	already_checked.push(table_id);

	if (!linked_table_ids) {
		linked_table_ids = [];
	}
	// console.debug("checking for table_id", table_id, already_checked);
	var dependent_table_ids = ez5.admin.get_dependent_table_ids(table_id);
	ez5.schema[ez5.admin.version].tables.forEach(function(table) {
		if (CUI.util.idxInArray(table.table_id, already_checked) > -1) {
			return;
		}

		table.foreign_keys.forEach(function(fk) {
			if (fk.referenced_table.table_id !== table_id) {
				return;
			}
			if (CUI.util.inArray(table.table_id, dependent_table_ids) === -1) {
				linked_table_ids.push(table.table_id);
				ez5.admin.get_linked_table_ids(table.table_id, linked_table_ids, already_checked);
			}
		})
		table.columns.forEach(function(col) {
			if (col.other_table_id == table_id && col.kind == "reverse_link") {
				linked_table_ids.push(table.table_id);
			}
		})
	});
	return linked_table_ids;
}

ez5.admin.post_schema = function(schema) {

	if (schema.version === ez5.schema.CURRENT.version) {
		// increment head version by one
		schema.version++;
	}

	ez5.schema.clean_schema(schema);

	// console.debug("POST schema", schema);
	var dfr = new CUI.Deferred();

	ez5.api.schema({
		type: "POST",
		api: "/user/HEAD",
		json_data: schema
	}).done(function(data) {
		delete schema.__warnings;
		ez5.schema.load_schema()
			.done(dfr.resolve)
			.fail(dfr.reject)
	}).fail(dfr.reject)
	return dfr.promise()
}


ez5.admin.datamodel = function(opts) {
	opts = opts || {}

	var custom_type_support = new CustomDataTypeDatamodelSupport();

	var $attr_map = [
		["name", "name"],
		["", "displayname_l10n"],
		["", "unique"],
		["", "check"],
		["type", "type"],
		["not_null", "not_null"],
		["column_id", "column_id"],
		["reverse_edit", "reverse_edit"],
		["check", "check"],
		["check_regexp", "check_regexp"],
		["check_regexp_flags", "check_regexp_flags"],
		["", "check_range_upper"],
		["", "check_range_upper_exclusive"],
		["", "check_range_lower"],
		["", "check_range_lower_exclusive"],
		["", "check_range_not_empty"],
		["bidirectional", "bidirectional"]
	];

	var get_new_row = function(type) {

		var row = new ListViewEditTreeNode({data: {_fields: {}}});
		row.data = row.getData();
		row.data._node = row;

		$attr_map.forEach(function(k) {
			switch(k[1]) {
			case "reverse_edit":
			case "bidirectional":
				row.data[k[1]] = false;
				break;
			default:
				row.data[k[1]] = null;
			}
		});
		row.data.type = type;

		switch (type) {
		case "nested_table":
			/*
			if (ez5.admin.version==="HEAD") {
				var add_new_row = function(type) {
					var row_new = get_new_row(type);
					row.data._node.addNode(row_new);
					row.data._node.getTree().layout();
					row_new.select();
					setTimeout(function() { row_new.deselect()}, 300);
				}

				row.opts.renderContent = function(element, node) {
					var div = $div().append(element);
					div.append("</br>");
					div.append(new CUI.Buttonbar({buttons: [
						new CUI.Button({
							role: "minor",
							text: $$("admin.datamodel.new_field"),
							icon: "plus",
							onClick: function() { add_new_row(ez5.admin.datatypes[0][0]); }
						}),
						new CUI.Button({
							role: "minor",
							text: $$("admin.datamodel.new_nested_table"),
							icon: "plus",
							onClick: function() { add_new_row("nested_table"); }
						})
					]}).DOM);
					return div;
				}
			}
*/
			row.children = [];
			break;
		case "reverse_link":
			row.opts.fields = fields_reverse_link;
			break;
		case "hierarchical_reverse_link":
			row.opts.fields = fields_reverse_link;
			row.l10n_key = "schema."+datamodel.table_schema.name+".column.reverse:"+datamodel.table_schema.name;
			row.data.reverse_name =	$$("admin.datamodel.hierarchical_reverse_name");
			row.data.displayname_l10n = ez5.loca.get_user_key(ez5.admin.version, row.l10n_key);
			break;
		}
		row.data.custom_settings = {};

		return row;
	}

	var add_new_row = function(type, node, append_sibling) {
		var row = get_new_row(type);
		var promise;

		if (node) {
			if (append_sibling) {
				promise = node.appendSibling(row);
			} else {
				promise = node.addNode(row);
			}
		} else {
			promise = $columns_table.addNode(row);
		}
		promise.done(function() {
			row.select();
			update_datamodel_data_form();
		});
	}

	var update_row_state = function(row) {
		var hide=[], disable=[];
		// field 2 is "type", field 3 is "check" we need to ise integers
		var check = 3;
		var type = 2;
		// here, as these types are really embedded in formpopovers and cannot
		// be addressed by name
		switch(row.data.type) {
		case "reverse_link":
		case "hierarchical_reverse_link":
			hide = [check, type, "reverse_edit", "bidirectional", "bidirectional_reverse"];
			break;
		case "nested_table":
			hide = [type, "reverse_edit", "bidirectional", "bidirectional_reverse"];
			break;
		case "eas":
			// disable = ["not_null"];
			// check = ["unique"];
			hide = ["reverse_edit", "bidirectional", "bidirectional_reverse"];
		default:
			if (row.data.type.match("^custom:")) {
				custom_type_support.datamodelSetRowState({
					row: row,
					field_numbers: {
						check: check,
						type: type
					},
					hide: hide,
					disable: disable
				});
			} else if (row.data.type.match("^link_")) {
				if (row.getPath().length === 1) {
					if (row.data.type === "link_"+datamodel.table_schema.table_id) {
						hide.push("reverse_edit");
					}
				} else {
					hide.push("reverse_edit");
				}
				// bidirectional is handled in update_all_rows
			} else {
				hide.push("reverse_edit", "bidirectional", "bidirectional_reverse");
			}
		}

		// console.debug("update_row_state", row, row.data.type, datamodel.table_schema.table_id, row.getPath(), hide, disable);
		row.updateFields({hide: hide, disable: disable})
		if (opts.disabled) {
			for (var idx in row.dataFields) {
				row.dataFields[idx].disable()
			}
		}
		update_all_rows(row);
	}

	var update_all_rows = function(row_changed, rows, father_row, depth) {


		if (!depth) {
			depth = 0;
		}
		if (!rows) {
			rows = datamodel.rows;
		}
		// start this only, if all rows have been added to the list view
		for (var idx = 0; idx < rows.length; idx++) {
			if (!rows[idx].isAddedToListView()) {
				return;
			}
		}


		var get_bidirectional_reverse_fields = function(type, others, key) {
			return get_bi_fields(type, others, "bidirectional_reverse");
		}

		var get_bidirectional_fields = function(type, others, key) {
			return get_bi_fields(type, others, "bidirectional");
		}


		var get_bi_fields = function(type, others, key) {
			var bidi_fields = {
				count: 0, // number of links which point to the same top-level table
				enabled: [], // links enabled
				disabled: [], // links disabled
				all: [],
				reverse_edit: 0 // counter for active reverse_edit links
			}
			rows.forEach(function(r) {
				if (!r.data.type.match(/^link_/)) {
					return;
				}
				if (!type || (r.data.type == type && !others) || (r.data.type != type && others)) {
					var bidi_field = r.getOtherField(key);
					if (!bidi_field) {
						// row is not rendered yet
						return;
					}
					bidi_fields.count++;
					if (r.data[key]) {
						bidi_fields.enabled.push(bidi_field);
					} else {
						bidi_fields.disabled.push(bidi_field);
					}
					bidi_fields.all.push(bidi_field);
					if (r.data.reverse_edit) {
						bidi_fields.reverse_edit++;
					}
				}
			});
			return bidi_fields;
		}

		// BI-DIRECTIONAL checks

		var all_bidis = get_bidirectional_fields();


		rows.forEach(function(r) {
			var row_done = function() {
				if (r.children) {
					update_all_rows(row_changed, r.children, r, depth+1);
				}
				return;
			}

			if (!r.data.type.match(/^link_/)) {
				return row_done();
			}

			var bidi_field_reverse = r.getOtherField("bidirectional_reverse");


			if (bidi_field_reverse) {
				// show bidirectional_reverse, if same table
				if (depth === 0 && r.data.type === "link_"+datamodel.table_schema.table_id) {
					CUI.dom.showElement(bidi_field_reverse.DOM);
				} else {
					CUI.dom.hideElement(bidi_field_reverse.DOM);
				}
			}

			// console.debug("name", r.data.name, r, bidi_field, bidi_field_reverse, depth);
			var bidi_field = r.getOtherField("bidirectional");

			if (!bidi_field) {
				return row_done();
			}

			var all_bidi_rev = get_bidirectional_reverse_fields();

			// console.debug("all bidi rev", all_bidi_rev, bidi_field_reverse.getValue());
			if (all_bidi_rev.enabled.length == 1) {
				all_bidi_rev.disabled.forEach(function(dis) {
					dis.disable();
				});
			} else {
				all_bidi_rev.all.forEach(function(en) {
					en.enable();
				});
			}

			var same_bidis = get_bidirectional_fields(r.data.type);
			var other_bidis = get_bidirectional_fields(r.data.type, true);

			var count_needed = false;
			if (r.data.type === "link_"+datamodel.table_schema.table_id) {
				if (depth === 1) {
					count_needed = 1;
				}
			} else if (depth === 0) {
				if (same_bidis.reverse_edit > 0) {
					count_needed = 2;
				}
			}

			// show if we have have enough columns of the same
			// kind
			if (count_needed !== false && same_bidis.count >= count_needed) {
				CUI.dom.showElement(bidi_field.DOM);

				// make sure enough are on, do this only if
				// our box has changed
				if (r == row_changed && bidi_field.getLastValue() != bidi_field.getValue()) {
					if (same_bidis.enabled.length == count_needed) {
						// disable all inactive
						all_bidis.disabled.forEach(function(dis) {
							dis.disable();
						});

						same_bidis.all.forEach(function(cb) {
							cb.getData().__bidirectional_valid = true;
						});
					} else if (same_bidis.enabled.length > 0) {
						// disable all others
						other_bidis.all.forEach(function(dis) {
							dis.disable();
						});
						// enable all from this type
						same_bidis.all.forEach(function(cb) {
							cb.enable();
							cb.getData().__bidirectional_valid = false;
						});
					} else if (other_bidis.enabled.length > 0) {
						// This means that there is another bidirectional enabled.
						// Therefore it is necessary to disable the bidi for this row because it could be enabled only in one OT.
						same_bidis.all.forEach(function(cb) {
							cb.disable();
							cb.getData().__bidirectional_valid = false;
						});
					} else { // enable all
						all_bidis.all.forEach(function(cb) {
							cb.enable();
						});
					}
				}
			} else {
				r.data.__bidirectional_valid = true;
				CUI.dom.hideElement(bidi_field.DOM);
				bidi_field.setValue(false);

				all_bidis.all.forEach(function(cb) {
					cb.enable();
				});
			}

			// console.debug("row:", r.data.name, "bidi state:", r.data.bidirectional, "bidi valid", r.data.__bidirectional_valid, same_bidis.reverse_edit, "depth:", depth, "count:", count_needed);
			return row_done();
		});
	}

	var get_schema_tables = function() {

		var get_nested_table = function(table, column, nested_table_id) {
			nested_table = {
				name: column.name,
				displayname_l10n: column.displayname_l10n,
				es_type: "linked-table",
				table_id: nested_table_id,
				father_table: table,
				columns: []
			};

			nested_table_schema = nested_table_id?ez5.schema[ez5.admin.version]._table_by_id[nested_table_id]:null;

			/*
			// add primary key column
			nested_table.columns.push({
				name: "id",
				system: "primary-key-field",
				type: "serial",
				not_null: true,
				column_id: nested_table_schema?nested_table_schema._primary_key_column.column_id:null
			});

			// add link to father table column
			nested_table.linked_table_column = {
				name: table.name+"_id",
				system: "linked-table-field",
				type: "link",
				not_null: true,
				column_id: nested_table_schema?nested_table_schema.owned_by.column_id:null
			};


			nested_table.linked_table_column.foreign_key = {table: table,
															cascade: true};
			nested_table.columns.push(nested_table.linked_table_column);
			*/

			return nested_table;
		}


		var get_rows = function(table, rows) {

			var nested_table = null;
			var linked_table;

			rows.forEach(function(row) {

				var column = {};
				$attr_map.forEach(function(key) {
					switch(key[1]) {
					case "unique":
						if (CUI.util.isTrue(row.data.unique)) {
							column.unique = row.data.unique_group;
							column.unique_parent = row.data.unique_parent;
						}
						break;
					case "displayname_l10n":
						column.displayname_l10n = row.data.displayname_l10n;
						break;
					default:
						column[key[1]] = row.data[key[1]];
					}
				});

				column.__bidirectional_valid = row.data.__bidirectional_valid;
				column.bidirectional_reverse = row.data.bidirectional_reverse;

				column.check_length = row.data.check_length;
				column.check_length_min = row.data.check_length_min;
				column.check_length_max = row.data.check_length_max;
				column.custom_settings = row.data.custom_settings;

				if (row.children) {
					column.kind = "link";
					column.name = table.name + "__" + column.name;
					var nested_table = get_nested_table(table, column, row.link_table_id);
					tables.push(nested_table);
					get_rows(nested_table, row.children);
					column.link_table_id = row.link_table_id;
				} else if (column.type.match("^link_")) {
					column.foreign_key = {
						table: {table_id: parseInt(column.type.substring(5))},
						cascade: (column.reverse_edit === true || column.bidirectional === true)
					};
					column.type = "link";
				} else if (column.type === "reverse_link") {
					column.kind = "reverse_link";
					column.reverse_link_column = row.reverse_link_column;
				} else if (column.type === "hierarchical_reverse_link") {
					column.kind = "hierarchical_reverse_link";
				}
				column.l10n_key = row.l10n_key;
				table.columns.push(column);
			});
		};

		// merge input in easier to handle json
		// structure
		var tables = [];
		var current = []; // collect all rows hierachically

		var table = {
			table_id: datamodel.table_schema.table_id,
			name: datamodel.datamodel_data.name,
			displayname_l10n: datamodel.datamodel_data.displayname_l10n,
			acl_table: datamodel.datamodel_data.acl_table,
			has_tags: datamodel.datamodel_data.has_tags,
			pool_link: datamodel.datamodel_data.pool_link,
			comment: datamodel.datamodel_data.comment,
			is_hierarchical: datamodel.datamodel_data.is_hierarchical,
			polyhierarchical: datamodel.datamodel_data.polyhierarchical,
			in_main_search: datamodel.datamodel_data.in_main_search,
			columns: []
		};

		var table_schema = table.table_id?ez5.schema[ez5.admin.version]._table_by_id[table.table_id]:null

		tables.push(table);

		/*
		// add primary key column
		table.columns.push({
			name: "id",
			system: "primary-key-field",
			type: "serial",
			not_null: true,
			column_id: table_schema?table_schema._primary_key_column.column_id:null
		});
		*/

		get_rows(table, datamodel.rows);

		return tables;

	}

	var save_schema = function(opts) {
        opts = opts ? opts : {}
		var dfr = new CUI.Deferred();
		// send to server
		if (ez5.admin.version !== "HEAD") {
			alert("cannot post schema for: "+ez5.admin.version);
			return;
		}

		var schema = CUI.util.copyObject(ez5.schema.HEAD, true);

		// the deep copy de-referenced all _* references, so
		// we need to re-enrich the schema
		ez5.schema.clean_schema(schema);
		ez5.schema.enrich_schema(schema, "HEAD");

		// updates the existing schema an saves it to the server
		var tables = get_schema_tables();
		// $schema.children("schema").children().remove();

		// update xml schema
		var tables_by_id = {};
		var tables_by_name = {};
		for (var i = 0; i < tables.length; i++) {
			var t = tables[i];
			if (t.table_id) {
				tables_by_id[t.table_id] = tables[i];
			}
			tables_by_name[t.name] = tables[i];
			for (var j = 0; j < t.columns.length; j++) {
				var c = t.columns[j];
				/*
				if (c.system === "primary-key-field") {
					t.pk_col = c;
				}
				*/
			}
		}

		// the first table is the top level table
		var dependent_table_ids = ez5.admin.get_dependent_table_ids(tables[0].table_id);

		var l10n_keys = {}; // collect all l10n keys

		// for debug purposes
		var debug_table_schemas = [];

		for (var i = 0; i < tables.length; i++) {
			var t = tables[i];
			l10n_keys["schema."+t.name+".name"] = t.displayname_l10n;

			var table_schema = schema._table_by_id[t.table_id];
			if (!table_schema) {
				// generate a new table stub
				table_schema = {"columns":[], "_column_by_id": {}}
				schema.tables.push(table_schema);
			}
			debug_table_schemas.push(table_schema);

			table_schema.name = t.name;
			table_schema.pool_link = t.pool_link;
			table_schema.acl_table = t.acl_table;
			table_schema.comment = t.comment;
			table_schema.has_tags = t.has_tags;
			table_schema.in_main_search = t.in_main_search;
			table_schema.is_hierarchical = t.is_hierarchical;
			table_schema.polyhierarchical = t.polyhierarchical;

			table_schema.unique_keys = [];
			table_schema.foreign_keys = [];
			table_schema._bidirectional_by_other_table_id = {};

			delete(table_schema.owned_by);
			if (t.father_table) {
				table_schema.owned_by = {
					/*
					"column_id": t.linked_table_column.column_id,
					"column_name_hint": t.linked_table_column.name,
					*/
					"other_table_name_hint": t.father_table.name,
					"other_table_id": t.father_table.table_id
				}
			}

			var reverse_link_columns_active = [];
			var reverse_link_columns_inactive = [];
			var reverse_link_table_ids = [];

			table_schema.new_columns = [] // this links the new columns, we might have a new order
			for (var j = 0; j < t.columns.length; j++) {
				var c = t.columns[j];
				if (!c.l10n_key) {
					c.l10n_key = "schema."+t.name+".column."+c.name;
				}
				var col;

				l10n_keys[c.l10n_key] =  c.displayname_l10n;

				switch (c.kind) {
				case "link": // nested table uplink
					col = {
						kind: "link",
						other_table_name_hint: c.name,
						other_table_id: c.link_table_id
					}
					break;
				case "reverse_link": // table link to reversed link table
					col = {
						kind: "reverse_link",
						other_table_name_hint: c.name,
						other_table_id: c.reverse_link_column.other_table_id,
						other_column_id: c.reverse_link_column.other_column_id
					}
					break;
				case "hierarchical_reverse_link": // table link to self reversed link table
					col = {
						kind: "reverse_link",
						is_hierarchical: true
					}
					break;
				default:
					// col = table_schema._column_by_id[c.column_id];
					// if (!col) {
					col = {
						"kind": "column"
					}
					// }
				}

				table_schema.new_columns.push(col);

				// not_null is stored here

				/* FIXME: make this explicit in the block above */
				$attr_map.forEach(function( key, idx) {
					if (CUI.util.isEmpty(key[0])) {
						return;
					}
					switch (c.kind) {
					case "link":
						switch(key[0]) {
						case "table_id":
						case "not_null":
							break;
						default:
							return;
						}
						break;
					case "reverse_link":
					case "hierarchical_reverse_link":

						// dont map anything
						return;
					default:
						switch(key[0]) {
						case "sort":
							return;
						}
					}

					col[key[0]] = c[key[1]];
				});

				// delete(col.check_range_upper);
				// delete(col.check_range_upper_open);
				// delete(col.check_range_lower);
				// delete(col.check_range_lower_open);

				if (c.unique) {
					var unique_key = null;
					// console.debug("saving unique key", CUI.util.copyObject(c, true));
					if (c.unique !== "single") {
						table_schema.unique_keys.forEach(function(uk) {
							if (uk.group === c.unique) {
								unique_key = uk;
							}
						});
						if (!unique_key) {
							unique_key = {
								"group": c.unique,
								"columns": []
							}
							table_schema.unique_keys.push(unique_key);
						}
					} else {
						unique_key = {
							"columns": []
						}
						table_schema.unique_keys.push(unique_key);
					}
					if (t.father_table && unique_key.columns.length === 0) {
						unique_key.columns.push({
							"auto_column_uplink": true
						});
					}
					if (t.is_hierarchical && unique_key.columns.length === 0 && c.unique_parent) {
						unique_key.columns.push({
							"auto_column_parent": true
						});
					}

					var unique_info = {
						"column_id": c.column_id,
						"column_name_hint": c.name,
					}

					if (c.type == "boolean") {
						unique_info.unique_true = true;
					}

					unique_key.columns.push(unique_info);
				}

				col.custom_settings = CUI.util.copyObject(c.custom_settings, true);

				if (c.type == 'nested_table' && c.check == 'not_empty') {
					col.check = 'not_empty';
				}

				if (c.check == "range") {
					// console.debug("BEFORE", CUI.util.dump(col));
					if (!CUI.util.isEmpty(c.check_range_upper)) {
						if (c.check_range_upper_exclusive) {
							col.check_range_upper_open = c.check_range_upper;
						} else {
							col.check_range_upper = c.check_range_upper;
						}
					}

					if (!CUI.util.isEmpty(c.check_range_lower)) {
						if (c.check_range_lower_exclusive) {
							col.check_range_lower_open = c.check_range_lower;
						} else {
							col.check_range_lower = c.check_range_lower;
						}
					}

					if (!CUI.util.isEmpty(c.check_range_not_empty)) {
						col.check_range_not_empty = c.check_range_not_empty;
					}

				}

				if (c.check_length) {
					if (!CUI.util.isEmpty(c.check_length_min)) {
						col.length_min = c.check_length_min;
					}
					if (!CUI.util.isEmpty(c.check_length_max)) {
						col.length_max = c.check_length_max;
					}
				}

				if (c.bidirectional) {
					console.debug("column ", c.name, "check save", c, "column:", col);
					if (c.__bidirectional_valid === false) {
						throw new InvalidSaveDataException();
					}
					var tid = c.foreign_key.table.table_id;
					CUI.util.assert(tid,"save_schema","Column has no table_id for bidirectional link");
					if (!table_schema._bidirectional_by_other_table_id[tid]) {
						table_schema._bidirectional_by_other_table_id[tid] = {
							columns: []
						}
					}
					var bidi = table_schema._bidirectional_by_other_table_id[tid];
					/*
					if (t.linked_table_column && bidi.columns.length === 0) {
						bidi.columns.push(
							{
								column_id: t.linked_table_column.column_id,
								column_name_hint: t.linked_table_column.name
							}
						)
					}
					*/
					if (t.father_table && bidi.columns.length === 0) {
						bidi.columns.push(
							{
								"auto_column_uplink": true
							}
						);
					}
					bidi.columns.push(
						{
							column_id: col.column_id,
							column_name_hint: col.name
						}
					)
					// console.debug("*bidi", c, col, tid,t , bidi);
				}

				if (c.bidirectional_reverse) {
					col.bidirectional_reverse = true;
				}

				if (c.type == "boolean") {
					col.not_null = true;
				}

				if (c.foreign_key) {
					var ref_table;
					var fk = {}
					table_schema.foreign_keys.push(fk);

					if (c.foreign_key.cascade) {
						fk.on_delete = "cascade";
						fk.on_update = "cascade";
					} else {
						fk.on_delete = "restrict";
						fk.on_update = "cascade";
					}

					if (c.foreign_key.table.table_id) {
						ref_table = tables_by_id[c.foreign_key.table.table_id];
						if (!ref_table) {
							// this table is not the current and not a linked_table
							var ref_table = schema._table_by_id[c.foreign_key.table.table_id];

							ref_table = {
								/* pk_col: {column_id: ref_table._primary_key_column.column_id,
								   name: ref_table._primary_key_column.name_hint},
								   */
								name: ref_table.name,
								table_id: ref_table.table_id
							};
						}
					} else {
						ref_table = tables_by_name[c.foreign_key.table.name];
					}

					fk.columns = [{
						"column_id": c.column_id,
						"column_name_hint": c.name
					}];
					fk.referenced_table = {
						"table_id": ref_table.table_id,
						"name_hint": ref_table.name,
						"columns": [{
							"auto_column_primary_key": true
							/*
							"column_id": ref_table.pk_col.column_id,
							"column_name_hint": ref_table.pk_col.name
							*/
						}]
					}
				}

				// maintain reverse linked column in the linked table
				// for new columns, we need to simply add a reversed link column
				// for existing columns we need to add or remove or leave the reversed
				// link untouched
				if (c.type === "link" && !table_schema.owned_by) {
					if (c.reverse_edit === true) {
						reverse_link_columns_active.push(c);
					} else {
						reverse_link_columns_inactive.push(c);
					}
					// maintain a list of references other tables
					CUI.util.pushOntoArray(c.foreign_key.table.table_id, reverse_link_table_ids);
				}
			}

			// console.debug("reverse_link_column in my table:", reverse_link_columns_active, "inactive:", reverse_link_columns_inactive, "table:", t, "table reverse id:", reverse_link_table_ids);
			// c.foreign_key.table.table_id should be set for this datatype
			// for existing tables, we need to check if someone looks us up
			if (t.table_id) {
				for (var j0 = 0; j0 < reverse_link_table_ids.length; j0++) {
					var reverse_link_table = schema._table_by_id[reverse_link_table_ids[j0]];
					for (var j1 = 0; j1 < reverse_link_table.columns.length; j1++) {
						var col1 = reverse_link_table.columns[j1];
						if (!(col1.kind === "reverse_link" && col1.other_table_id === t.table_id)) {
							continue;
						}
						// this column points to us, now we have to check if we need
						// to remove it or leave it

						// run thru active columns and remove them from the active list if
						// they already exist
						for (var j2 = 0; j2 < reverse_link_columns_active.length; j2++) {
							var col2 = reverse_link_columns_active[j2];
							if (col2.column_id == col1.other_column_id) {
								// this column is already there, all good
								console.debug("Col already exists:", col2.name, "table:", reverse_link_table.name);
								reverse_link_columns_active.splice(j2, 1);
								j2--;
							}
						}

						// run thru inactive columns and remove them from the table
						for (var j2 = 0; j2 < reverse_link_columns_inactive.length; j2++) {
							var col2 = reverse_link_columns_inactive[j2];
							if (col2.column_id == col1.other_column_id) {
								// this column needs to be removed from the reverse linked table
								console.debug("Removing already existing col:", col2.name, "table:", reverse_link_table.name);
								reverse_link_table.columns.splice(j1, 1);
								j1--;
							}
						}
					}
				}
			}

			// add missing active columns
			for (var j0 = 0; j0 < reverse_link_columns_active.length; j0++) {
				var col0 = reverse_link_columns_active[j0];
				var reverse_link_table = schema._table_by_id[col0.foreign_key.table.table_id];
				console.debug("Col add:", col0.name, "table:", reverse_link_table.name);
				reverse_link_table.columns.push({
					kind: "reverse_link",
					other_table_name_hint: t.name,
					other_table_id: t.table_id,
					other_column_id: col0.column_id,
					other_column_name_hint: col0.name
				});
			}

			// this deletes left over from the old solution how
			// to handle hierarchical tables
			delete(table_schema.hierarchical);
			delete(table_schema.primary_key);
			/*
			if (t.pk_col) {
				table_schema.primary_key = {
					"columns": [{
						"column_name_hint": t.pk_col.name,
						"column_id": t.pk_col.column_id
					}]
				}
			}
			*/
			table_schema.columns = table_schema.new_columns;
			table_schema.bidirectional = [];

			for(var table_id in table_schema._bidirectional_by_other_table_id) {
				var bidi = table_schema._bidirectional_by_other_table_id[table_id];
				table_schema.bidirectional.push(bidi);
			}

			delete(table_schema._bidirectional_by_other_table_id);
			delete(table_schema.new_columns);
		}

		// console.debug("copy of schema", CUI.util.dump(schema));

		// remove all unused tables, owned-by already exists for existing tables
		dependent_table_ids.forEach(function(t_id) {
			if (!tables_by_id[t_id]) {
				var table = schema._table_by_id[t_id];
				CUI.util.removeFromArray(table, schema.tables);
			}
		});

		ez5.schema.clean_schema(schema);
		ez5.loca.clean_keys(l10n_keys);

		if (opts.return_data) {
			return {
				l10n_keys: l10n_keys,
				schema: schema
			}
		}

		var ev = opts.event;
		if (ev && (ev.altKey() || ev.shiftKey() || ev.ctrlKey())) {
			if (ev.altKey() && ev.ctrlKey()) {
				console.debug(CUI.util.dump(schema));
				console.warn("dumped full schema post", schema);
			} else {
				console.debug(CUI.util.dump(debug_table_schemas));
				console.warn("dumped updated schema post only, use ctrl+alt for full dump", debug_table_schemas);
			}
			return dfr.reject();
		}

		ez5.admin.post_schema(schema)
			.done(function() {
				// save loca keys
				var valid_prefixes = ez5.loca.get_valid_user_key_prefixes(ez5.admin.version);
				// console.debug("valid prefixes", valid_prefixes);
				// console.debug("save loca keys:", l10n_keys);
				ez5.loca.update({
					valid_prefixes: valid_prefixes,
					delete_prefix: "schema."+tables[0].name+".",
					realm: ez5.admin.version,
					keys: l10n_keys
				})
					.done(function() {
						ez5.schema.clean_schema(ez5.schema.HEAD);
						ez5.schema.enrich_schema(ez5.schema.HEAD, "HEAD");
						dfr.resolve();
					})
					.fail(dfr.reject)
			})
			.fail(dfr.reject);

		return dfr.promise();
	}

	var get_datamodel_for_table =  function(table_id, $attr_map) {

		var datamodel = {
			table_schema: ez5.schema[ez5.admin.version]._table_by_id[table_id],
			datamodel_data: {_fields:{}}
		};

		datamodel.get_row_data_for_datamodel = function(table_schema) {
			var rows = [];

			table_schema.columns.forEach(function(column) {

				// console.debug(row.data.name, row.data.system, row.data.type);
				switch(column._system_type) {
				case "primary-key-field":
				case "tree-field":
				case "linked-table-field":
				case "object-rights-linked-table":
					// skip this, we add it back later when we save the schema
					return;
				}

				var row;

				switch (column.kind) {
				case "link": // nested linked table (owned_by table)

					var link_table_id = column.other_table_id
					var link_table_schema = ez5.schema[ez5.admin.version]._table_by_id[link_table_id];

					row = get_new_row("nested_table");

					row.link_table_id = link_table_id;

					row.data.name = link_table_schema.name.substr(table_schema.name.length+2);

					row.data.displayname_l10n =	ez5.loca.get_user_key(ez5.admin.version, column._l10n_key);

					row.data.check = column.check;
					row.data.not_null = column.not_null;
					row.children = datamodel.get_row_data_for_datamodel(link_table_schema);
					break;
				case "reverse_link":
					if (!column.is_hierarchical) {
						row = get_new_row("reverse_link");
						// console.debug("loading reverser link", column);
						var reverse_link_table_schema = ez5.schema[ez5.admin.version]._table_by_id[column.other_table_id];

						// hint for save_schema when sending, server uses this to look up the
						// linked table
						row.reverse_link_column = column;
						// row.reverse_link_column_id = reverse_link_column_id;

						row.data.name = reverse_link_table_schema.name+"."+column.name;
						// row.data.reverse_name = $$("admin.datamodel.reverse_link_prefix", {
						// 	'name': reverse_link_table_schema._name_localized+' / '+reverse_link_table_schema._column_by_id[column.other_column_id]._name_localized
						// });
						row.data.reverse_name = reverse_link_table_schema._name_localized+' / '+reverse_link_table_schema._column_by_id[column.other_column_id]._name_localized;

						row.l10n_key = column._l10n_key;

                        // col._l10n_key_old contains the old key before the fix in #51099.
						row.data.displayname_l10n = ez5.loca.get_user_key(ez5.admin.version, column._l10n_key_old);
                        if (CUI.util.isEmpty(row.data.displayname_l10n)) {
							row.data.displayname_l10n = ez5.loca.get_user_key(ez5.admin.version, row.l10n_key);
                        }

					} else {
						datamodel.datamodel_data.hierarchical_reverse_edit = true;
						// ignore column here, the main form for datamodel will add the column
						return;
					}

					break;
				default:
					row = get_new_row();
					row.data.column = column;

					$attr_map.forEach(function(key) {
						if (!CUI.util.isUndef(column[key[0]])) {
							row.data[key[1]] = column[key[0]];
						}
					});

					row.data.bidirectional_reverse = column.bidirectional_reverse;

					if (!CUI.util.isNull(column.length_min) || !CUI.util.isNull(column.length_max)) {
						row.data.check_length = true;
						row.data.check_length_min = column.length_min;
						row.data.check_length_max = column.length_max;
					} else {
						row.data.check_length = false;
						row.data.check_length_min = null;
						row.data.check_length_max = null;
					}

					if (!CUI.util.isNull(column.check_range_lower)) {
						row.data.check_range_lower = column.check_range_lower;
						row.data.check_range_lower_exclusive = false;
					} else if (!CUI.util.isNull(column.check_range_lower_open)) {
						row.data.check_range_lower = column.check_range_lower_open;
						row.data.check_range_lower_exclusive = true;
					}
					if (!CUI.util.isNull(column.check_range_upper)) {
						row.data.check_range_upper = column.check_range_upper;
						row.data.check_range_upper_exclusive = false;
					} else if (!CUI.util.isNull(column.check_range_upper_open)) {
						row.data.check_range_upper = column.check_range_upper_open;
						row.data.check_range_upper_exclusive = true;
					}

					if (!CUI.util.isNull(column.check_range_not_empty)) {
						row.data.check_range_not_empty = column.check_range_not_empty;
					}

					row.data.displayname_l10n =
						ez5.loca.get_user_key(ez5.admin.version, "schema."+table_schema.name+".column."+
											  column.name);

					if (column._foreign_key) {
						// $column.attr("type", "link_"+link_table_id);
						row.data.type = "link_"+column._foreign_key.referenced_table.table_id;
					}

					row.data.custom_settings = column.custom_settings || {};

					if (column.type.match("^custom:")) {
						// check if type is available, if not add it to
						// the list
						var exists = false;
						for (var idx in datamodel.custom_types) {
							var opt = datamodel.custom_types[idx];
							if (opt.value == column.type) {
								exists = true;
								break;
							}
						}
						if (!exists) {
							console.warn("Adding non existing datatype for column", column, datamodel.custom_types);
							var dt = CustomDataType.get(column.type);
							datamodel.custom_types.push({value: column.type, text: dt.getCustomDataTypeNameLocalized()});
						}
					}

					if (column._unique_keys) {
						// console.debug("table:", table_schema, "column:", column);
						var parent_table_link_column_id = null;
						var children_count = 1;

						if (table_schema.owned_by) {
							parent_table_link_column_id = table_schema.owned_by.column_id;
							children_count = 2;
						}

						try {
							switch (column._unique_keys.length) {
							case 1:
								var unique_key = column._unique_keys[0];
								if (parent_table_link_column_id) {
									// check if the unique key contains the parent link column
									var good = false;
									unique_key.columns.forEach(function(col) {
										if (col.column_id === parent_table_link_column_id) {
											good = true;
										}
									});
									if (!good) {
										throw "admin.datamodel.error.single_unique_key";
									}
								}

								if (table_schema.is_hierarchical) {
									unique_key.columns.forEach(function(col) {
										if (col.auto_column_parent) {
											row.data.unique_parent = true;
											children_count++;
										}
									});
								}

								row.data.unique_group = unique_key.group;

								switch(row.data.unique_group) {
								case "a":
								case "b":
								case "c":
									// group key
									row.data.unique = true;
									break;
								default:
									if (unique_key.columns.length <= children_count) {
										// single unique key
										row.data.unique = true;
										row.data.unique_group = "single";
									} else {
										throw "admin.datamodel.error.no_group_in_unique_key";
									}
								}

								break;
							default:
								// we cannot have the same column in multiple unique keys. this
								// is an error we have to warn the user about
								throw "admin.datamodel.error.multiple_unique_keys";
							}
						} catch (error_label) {
							console.error(error_label, "column", column, "table", table_schema);
							CUI.problem({text: $$(error_label+".text",
												  [row.data.name, table_schema._name_localized])});
						}
					}
				}

				row.data.system = column._system_type;
				rows.push(row);

			});
			return rows;
		};

		if (!datamodel.table_schema) {
			datamodel.table_schema = {
				name: "",
				acl_table: false,
				has_tags: false,
				pool_link: false,
				comment: "",
				in_main_search: false,
				polyhierarchical: false,
				hierarchical_reverse_edit: false,
				columns:[]
			}
		}

		datamodel.datamodel_data.table_id = datamodel.table_schema.table_id;
		datamodel.datamodel_data.name = datamodel.table_schema.name;
		datamodel.datamodel_data.displayname_l10n =
			ez5.loca.get_user_key(ez5.admin.version, "schema."+datamodel.datamodel_data.name+".name");

		datamodel.datamodel_data.pool_link = datamodel.table_schema.pool_link;
		datamodel.datamodel_data.is_hierarchical = datamodel.table_schema.is_hierarchical;
		datamodel.datamodel_data.polyhierarchical = datamodel.table_schema.polyhierarchical;

		datamodel.datamodel_data.comment = datamodel.table_schema.comment;
		datamodel.datamodel_data.in_main_search = datamodel.table_schema.in_main_search;
		datamodel.datamodel_data.acl_table = datamodel.table_schema.acl_table;
		datamodel.datamodel_data.has_tags = datamodel.table_schema.has_tags;

		datamodel.additional_types = [];

		ez5.schema[ez5.admin.version]._objecttypes.forEach(function(table) {
			datamodel.additional_types.push({value: "link_"+table.table_id,
											 text: table._name_localized});
		});

		datamodel.custom_types = [];
		CustomDataType.getTypes().forEach(function(ctype) {
			var type = ctype.getCustomDataTypeName()
			if (!ez5.session.getCustomDataTypes()[type]) {
				console.warn("Datamodel load: Custom Type loaded but not supported by server:", type);
			}
			datamodel.custom_types.push({value: type, text: ctype.getCustomDataTypeNameLocalized()});
		});

		return datamodel;
	}

	var update_datamodel_data_form = function() {
		var d = datamodel.datamodel_data;
		// console.debug("update_datamodel_data_form", d, d.hierarchical_reverse_edit)
		if (d.polyhierarchical) {
			dm_form.getFieldsByName("hierarchical_reverse_edit")[0].disable()
			dm_form.getFieldsByName("is_hierarchical")[0].disable()
			dm_form.getFieldsByName("acl_table")[0].setValue(false).disable()
		} else {
			dm_form.getFieldsByName("is_hierarchical")[0].enable()
			dm_form.getFieldsByName("acl_table")[0].enable()
		}
		if (d.is_hierarchical) {
			if (!opts.disabled) {
				dm_form.getFieldsByName("hierarchical_reverse_edit")[0].enable()
			}
			var polyhierarchicalField = dm_form.getFieldsByName("polyhierarchical")[0];
			if (polyhierarchicalField) {
				polyhierarchicalField.disable()
			}
		} else {
			dm_form.getFieldsByName("hierarchical_reverse_edit")[0].setValue(false).disable()
			var polyhierarchicalField = dm_form.getFieldsByName("polyhierarchical")[0];
			if (polyhierarchicalField) {
				polyhierarchicalField.enable()
			}
		}
		if (!d.hierarchical_reverse_edit && d._hierarchical_reverse_edit_old_value) {
			// console.debug("switched off", datamodel.rows);
			datamodel.rows.forEach(function( row, idx) {
				if (row.data.type === "hierarchical_reverse_link") {
					if ($columns_table.isLoaded()) {
						row.remove();
					} else {
						datamodel.rows.splice(idx,1);
					}
				}
			});
		} else if (d.hierarchical_reverse_edit && !d._hierarchical_reverse_edit_old_value) {
			var row = get_new_row("hierarchical_reverse_link");
			if ($columns_table.isLoaded()) {
				$columns_table.addNode(row);
			} else {
				datamodel.rows.push(row);
			}
		}
		d._hierarchical_reverse_edit_old_value = d.hierarchical_reverse_edit;
		if (minusButton && !opts.disabled) {
			if ($columns_table.getSelectedNode()) {
				var type = $columns_table.getSelectedNode().getData().type;
				if (type !== "reverse_link" && type !== "hierarchical_reverse_link") {
					minusButton.enable();
				}
			} else {
				minusButton.disable();
			}
		}
	};

	let form_options_fields = [
		{
			ui: "datamodel.form.checkbox:pool",
			type: CUI.Checkbox,
			text: $$("admin.datamodel.form.pool_link"),
			name: "pool_link"
		},
		{
			ui: "datamodel.form.checkbox:hierarchical",
			type: CUI.Checkbox,
			text: $$("admin.datamodel.form.hierarchical"),
			name: "is_hierarchical"
		},
		// this is an internal field only, it appends
		// a field to the list of fields
		{
			ui: "datamodel.form.checkbox:hierarchical_reverse",
			type: CUI.Checkbox,
			text: $$("admin.datamodel.form.hierarchical_reverse_edit"),
			name: "hierarchical_reverse_edit"
		}
	]

	if (ez5.version("6")) {
		form_options_fields.push(
			{
				ui: "datamodel.form.checkbox:polyhierarchical",
				type: CUI.Checkbox,
				text: $$("admin.datamodel.form.polyhierarchical"),
				name: "polyhierarchical"
			}
		)
	}

	var dm_form_opts = { fields: [
		{
			ui: "datamodel.form.output:table_id",
			type: CUI.Output,
			form: {
				label: $$("admin.datamodel.form.id")
			},
			name: "table_id"
		},
		{
			ui: "datamodel.form.input:name",
			type: CUI.Input,
			maximize: true,
			form: {
				label: $$("admin.datamodel.form.name")
			},
			regexp: "^[a-z][a-z0-9_]{0,61}[a-z0-9]$",
			name: "name",
			required: true
		},
		{
			ui: "datamodel.form.multiinput:displayname",
			type: CUI.MultiInput,
			user_selectable: ez5.session.getPref("languages_user_selection"),
			maximize: true,
			control: ez5.loca.getLanguageControlAdmin(),
			form: {
				label: $$("admin.datamodel.form.displayname_l10n")
			},
			name: "displayname_l10n"
		},
		{
			ui: "datamodel.form.input:comment",
			type: CUI.Input,
			maximize: true,
			textarea: true,
			form: {
				label: $$("admin.datamodel.form.comment")
			},
			name: "comment"
		},
		{
			type: CUI.Form,
			form: {
				label: $$("admin.datamodel.form.options")
			},
			onDataChanged: update_datamodel_data_form,
			fields: form_options_fields
		},
		{
			form: {
				label: $$("admin.datamodel.form.frontendoptions")
			},
			type: CUI.Form,
			onDataChanged: update_datamodel_data_form,
			fields: [
				{
					ui: "datamodel.form.checkbox:search",
					type: CUI.Checkbox,
					text: $$("admin.datamodel.form.in_main_search"),
					name: "in_main_search"
				}
			]
		},
		{
			form: {
				label: $$("admin.datamodel.form.rightsmanagement")
			},
			type: CUI.Form,
			onDataChanged: update_datamodel_data_form,
			fields: [
				{
					ui: "datamodel.form.checkbox:rights",
					type: CUI.Checkbox,
					text: $$("admin.datamodel.form.acl_table"),
					name: "acl_table"
				},
				{
					ui: "datamodel.form.checkbox:tags",
					type: CUI.Checkbox,
					text: $$("admin.datamodel.form.has_tags"),
					name: "has_tags"
				}

			]
		}
	] };

	var get_check_db_fields = function(formField) {
		var data = formField.getData();
		if (!data) {
			return [];
		}

		if (data.type == "nested_table") {
			return [{
				type: CUI.Checkbox,
				text: $$("admin.datamodel.col.not_null"),
				name: "not_null"
            }];
		}

		var uniqueFields = [
			{
				type: CUI.Select,
				class: "ez5-datamodel-field-unique-select",
				name: "unique_group",
				options: [
					{
						value: "single",
						text: $$("admin.datamodel.col.unique.key.single")
					},
					{
						value: "a",
						text: $$("admin.datamodel.col.unique.key.a")
					}
					,
					{
						value: "b",
						text: $$("admin.datamodel.col.unique.key.b")
					}
					,
					{
						value: "c",
						text: $$("admin.datamodel.col.unique.key.c")
					}
				]
			}
		]

		if (!(data._node.father instanceof ListViewEditTreeNode)) {
			uniqueFields.push(unique_parent_checkbox);
		}

        fields = [
            {
                type: CUI.Checkbox,
                text: $$("admin.datamodel.col.not_null"),
                name: "not_null"
            },
            {
                type: CUI.Form,
                fields: [
                    {
                        type: CUI.Checkbox,
                        text: $$("admin.datamodel.col.unique"),
                        name: "unique"
                    },
                    {
                        type: CUI.Form,
                        fields: uniqueFields
                    }
                ]
            }
        ];

		if (ez5.admin.datatype(data.type) && ez5.admin.datatype(data.type)[1].length) {
			fields.splice(1,0, {
				type: CUI.Form,
				horizontal: true,
				fields: [
					{
						type: CUI.Checkbox,
						text: $$("admin.datamodel.col.length"),
						name: "check_length"
					},
					{
						type: CUI.Form,
						class: "ez5-datamodel-form-database-max-min",
						fields: [
							{
								form: { label: $$("admin.datamodel.col.length.min") },
								type: CUI.NumberInput,
								min: 0,
								name: "check_length_min"
							},
							{
								form: { label: $$("admin.datamodel.col.length.max") },
								type: CUI.NumberInput,
								min: 1,
								name: "check_length_max"
							}
						]
					}
				]
			})
		}

		switch (data.type) {
		case 'boolean':
			fields[0].hidden = true;
			break;
		case 'eas':
			fields[1].hidden = true;
			break;
		}

		return fields;
	}

	var get_check_options = function(data) {
		var extra_form = null;
		var check_options = [];
		if (!data) {
			return check_options;
		}
		var check = null;

		var dt = ez5.admin.datatype(data.type);
		if (dt) {
			check = dt[1].check.slice(0);
		} else {
			check = [];
		}

		check.splice(0, 0, 'none');

		/* If it is nested_table or link, not_empty check is added. */
		if (data.type === 'nested_table' || data.type.match(/^link/) || data.type.match(/^custom:/)) {
			check.push('not_empty');
		}

		var get_range_field = function(opts) {
			return new CUI.Form(
				{
					class: "ez5-datamodel-form-input-extra",
					data: data,
					fields: [
						{
							type: opts.type,
							json_number: opts.json_number,
							decimals: opts.decimals, //This is for number inputs
							store_as_integer: opts.store_as_integer,
							input_types: opts.input_types, //This is for dates inputs.
							placeholder: $$("admin.datamodel.range_from.placeholder"),
							name: "check_range_lower"
						},
						{
							type: CUI.Checkbox,
							text: $$("admin.datamodel.range.exclusive"),
							name: "check_range_lower_exclusive"
						},
						{
							type: opts.type,
							json_number: opts.json_number,
							decimals: opts.decimals, //This is for number inputs
							store_as_integer: opts.store_as_integer,
							input_types: opts.input_types, //This is for dates inputs.
							placeholder: $$("admin.datamodel.range_to.placeholder"),
							name: "check_range_upper"
						},
						{
							type: CUI.Checkbox,
							text: $$("admin.datamodel.range.exclusive"),
							name: "check_range_upper_exclusive"
						},
						{
							type: CUI.Checkbox,
							text: $$("admin.datamodel.range.not_empty"),
							name: "check_range_not_empty"
						}
					]
				}
			)
		}

		check.forEach(function(value) {
				   var value_parsed;
				   if (value.match(/range/)) {
					   value_parsed = "range";
				   } else {
					   value_parsed = value;
				   }
				   var o = {
					   // this is the not empty checkbox here
					   text: $$("admin.datamodel.check."+value),
					   value: value==="none"?null:value_parsed,
				   };

				   // console.debug("check", idx, value, o);
				   switch (value) {
				   case "regexp":
					   extra_form = new CUI.Form({
						   data: data,
                           class: "ez5-datamodel-form-input-extra",
						   fields: [
							   {
								   form: { label: "Regexp" },
								   type: CUI.Input,
								   name: "check_regexp"
							   },
							   {
								   form: { label: "Regexp Flags" },
								   type: CUI.Input,
								   name: "check_regexp_flags"
							   }
						   ]})
					   break;
				   case "numberrange":
					   extra_form = get_range_field(
						   {
							   type: CUI.NumberInput,
							   decimals: 0
						   }
					   );
					   break;
				   case "numberrange.2":
					   extra_form = get_range_field(
						   {
							   type: CUI.NumberInput,
							   decimals: 2,
							   store_as_integer: true
						   }
					   );
					   break;
				   case "doublerange":
					   extra_form = get_range_field(
						   {
							   type: CUI.NumberInput,
							   json_number: true
						   }
					   );
					   break;
				   case "daterange":
					   extra_form = get_range_field(
						   {
							   type: CUI.DateTime,
							   input_types: ["date"]
						   }
					   );
					   break;
				   case "datetimerange":
					   extra_form = get_range_field(
						   {
							   type: CUI.DateTime,
							   input_types: ["date_time"]
						   }
					   );
					   break;
				   }
				   check_options.push(o);
			   });

		return {
			check_options: check_options,
			extra_form: extra_form
		};
	}

	var datamodel = get_datamodel_for_table(opts.table_id, $attr_map);

	var unique_parent_checkbox;
	if (datamodel.table_schema.is_hierarchical) {
		unique_parent_checkbox = {
			type: CUI.Checkbox,
			name: "unique_parent",
			text: $$("admin.datamodel.col.unique_parent")
		}
	}

	var options_field = { // 3
		th_label: "admin.datamodel.col.check",
		class: "ez5-datamodel-form-popover",
		type: CUI.FormPopover,
		popover:  {
			pane: {
				padded: true,
				"class": "ez5-admin-datamodel-check-popover",
				header_left: new CUI.Label({text: $$("admin.datamodel.col.check.popover.title")})
			},
			placements: ["es","e","ws","w"]
		},
		fields: function(form) {
			var data = form.getData();
			if (!data) {
				return [];
			}

			var info = get_check_options(data);
			var fields = []

			// add type dependent options
			if (info.check_options.length > 0) {
				fields.push(
					{
						type: CUI.Form,
						class: "ez5-datamodel-form-input",
						render_as_block: true,
						form: {
							label: $$("admin.datamodel.col.check.label")
						},
						fields: [
							{
								type: CUI.Options,
								horizontal: false,
								radio: true,
								name: "check",
								options: info.check_options
							},
							info.extra_form
						]
					}
				)
			}

			// add custom settings
			if (data.type.match("^custom:")) {
				var custom_fields = custom_type_support.getCustomSchemaOptions(data)
				if (custom_fields.length > 0) {
					fields.push(
						{
							type: CUI.Form,
							render_as_block: true,
							form: {
								label: $$("admin.datamodel.col.custom.schema.options.label")
							},
							fields: custom_fields
						}
					);
				}
			}

			// add plugin settings
			fields.push.apply(fields, ez5.schema_inst.getCustomSettings(data))

			// add db constraints
			fields.push(
				{
					type: CUI.Form,
					class: "ez5-datamodel-form-database",
					render_as_block: true,
					form: {
						label: $$("admin.datamodel.col.check.db.label")
					},
					fields: get_check_db_fields
				}
			);

			return fields
		},
		button: {
			text: $$("admin.datamodel.col.check.button")
		},
		renderDisplayContent: function(df, data) {
            var customInfoArray;
			if (data.type.match("^custom:")) {
				customInfoArray = custom_type_support.renderDisplayForCustomSchemaOptions(data);
			}
			var info = [];

			if (data) {
				if (data.check) {
					info.push($$("admin.datamodel.check."+data.check));
				}
				if (CUI.util.isTrue(data.not_null)) {
					info.push($$("admin.datamodel.check.not_null.display"));
				}
				if (CUI.util.isTrue(data.check_range_not_empty)) {
					info.push($$("admin.datamodel.check.check_range_not_empty"));
				}
				if (CUI.util.isTrue(data.check_length)) {
					var len_min;
					var len_max;
					if (CUI.util.isNull(data.check_length_min)) {
						len_min = "";
					} else {
						len_min = data.check_length_min;
					}
					if (CUI.util.isNull(data.check_length_max)) {
						len_max = "";
					} else {
						len_max = data.check_length_max;
					}
					if (len_min != "" || len_max != "") {
						info.push($$("admin.datamodel.check.length.display",
									 {
										 min: len_min,
										 max: len_max
									 }));
					}
				}
				if (info.length == 0) { // && !customInfoArray) {
					info.push($$("admin.datamodel.check.none"));
				}
				if (CUI.util.isTrue(data.unique)) {
					if (!data.unique_group) {
						data.unique_group = "single";
					}
					info.push($$("admin.datamodel.col.unique.key."+data.unique_group));
				}
			}
			info.push.apply(info, ez5.schema_inst.getCustomSettingsDisplay(data))
			var div = CUI.dom.element("DIV", {"class": "ez5-tag-holder ez5-datamodel-check"})
			for (var i=0; i < info.length; i++) {
				div.appendChild(new CUI.Label({"class": "ez5-tag", text: info[i]}).DOM);
			}
			if (customInfoArray) {
				div.appendChild(customInfoArray)
			}
			return div;
		}
	}

	var fields = [
		{ // 0
			th_label: "admin.datamodel.col.name",
			name: "name",
			type: CUI.Input,
			regexp: "^[a-z][a-z0-9_]{0,61}[a-z0-9]$",
			required: true
		},
		{ // 1
			th_label: "admin.datamodel.col.displayname_l10n",
			name: "displayname_l10n",
			type: CUI.MultiInput,
			control: ez5.loca.getLanguageControlAdmin(),
			user_selectable: ez5.session.getPref("languages_user_selection")
		},
		{ // 2
			th_label: "admin.datamodel.col.type",
			type: CUI.FormPopover,
			popover:  {
				placements: ["es","e","ws","w"],
				pane: {
					padded: true,
					header_left: new LocaLabel({loca_key: "admin.datamodel.col.type.popover.title"})
				}
			},
			fields: (function() {
				var fields = [];
				for (var i=0; i < 6; i++) {
					fields.push({
						type: CUI.Options,
						horizontal: false,
						radio: "type",
						placeholder: $$("admin.datamodel.type.group_label."+i+".placeholder"),
						form: {
							label: $$("admin.datamodel.type.group_label."+i)
						},
						name: "type",
						options: []
					});
				}
				return fields;
			})(),
			renderDisplayButton: function(df, data) {
				return ez5.schema_inst.getDatatypeLocalized(data.type, ez5.admin.version)
			},
			onDataChanged: function(data) {
				update_row_state(data._node);
			}
		},
		// 3
		options_field,
		{ // 4
			th_label: "admin.datamodel.col.reverse_edit",
			name: "reverse_edit",
			th_rotate_90: true,
			type: CUI.Checkbox,
			onDataChanged: function(data) {
				update_row_state(data._node);
			}
		},
		{ // 5
			th_label: "admin.datamodel.col.bidirectional",
			name: "bidirectional",
			th_rotate_90: true,
			undo_support: true,
			type: CUI.Checkbox,
			onDataChanged: function(data) {
				update_row_state(data._node);
			}
		},
		{ // 6
			th_label: "admin.datamodel.col.bidirectional_reverse",
			name: "bidirectional_reverse",
			th_rotate_90: true,
			type: CUI.Checkbox,
			onDataChanged: function(data) {
				update_row_state(data._node);
			}
		}

	];

	var minusButton = null;

	if (ez5.admin.version==="HEAD") {
		minusButton = new LocaButton({
			icon: "minus",
			loca_key: "datamodel.fields.button.minus",
			group: "plusminus",
			disabled: opts.disabled,
			onClick: function() {
				removeRow();
			}
		})
	}

	var removeRow = function() {
		var row = $columns_table.getSelectedNode();
		CUI.confirm({
			text: $$("admin.datamodel.remove_row.confirm"),
			button_text_ok: $$("base.delete")
		}).done(function() {
			var data = row.getData();
			if (data.reverse_edit && data.column && data.column._foreign_key) {
				// It is necessary to remove the referenced column of the referenced table in this moment
				// because after the row is removed we lost track of it and we cannot remove it in
				// enrich_schema or clean_schema.
				var referenceTableId = data.column._foreign_key.referenced_table.table_id;
				var referenceTable = ez5.schema.HEAD._table_by_id[referenceTableId];
				CUI.util.removeFromArray(null, referenceTable.columns, function(column) {
					return column.other_column_id === data.column_id;
				});
			}
			row.remove(true)
		})
	};

	var fields_reverse_link = fields.slice(0); // make a shallow copy
	fields_reverse_link[0] = { // 0
		th_label: "admin.datamodel.col.name",
		name: "reverse_name",
		type: CUI.Output
	};

	datamodel.rows = datamodel.get_row_data_for_datamodel(datamodel.table_schema);

	// bind data to the form
	dm_form_opts.data = datamodel.datamodel_data;

	// populate datatype pulldown
	var type_idx = CUI.util.idxInArray(null, fields, function(v) { return v.th_label == "admin.datamodel.col.type"; })

	var fields_tmp = fields[type_idx].fields;

	// console.debug("datatype", ez5.admin.datatypes);

	ez5.admin.datatypes.forEach(function(type) {

		if (!ez5.version("6.7") && type[0] === "geo_json") {
			return;
		}
		if (!ez5.version("6") && ez5.admin.fylrDataTypes.indexOf(type[0]) > -1) {
			return;
		}

		fields_tmp[type[1].group].options.
			push({text: $$("datamodel.type."+type[0]),
				  value: type[0]});
	});

	datamodel.additional_types.sort(function(a, b){
		return CUI.util.compareIndex(a.text.toLowerCase(), b.text.toLowerCase());
	});

	datamodel.custom_types.sort(function(a, b){
		return CUI.util.compareIndex(a.text.toLowerCase(), b.text.toLowerCase());
	});

	// the 4th group is the objecttypes
	fields_tmp[4].options = datamodel.additional_types;

	// the 5th group is the custom types
	fields_tmp[5].options = datamodel.custom_types;

	// console.debug("datamodel", datamodel);

	dm_form_opts.disabled = opts.disabled;
	dm_form_opts.padded = true;

	var dm_form = new CUI.Form(dm_form_opts);
	dm_form.start()
	// $ele.append($("<h2/>").text($$("admin.datamodel.edit.title")));

	var get_menu_items = function () {
		var items = [
			{
				label: $$("admin.datamodel.label_topmost_level"),
				group: "topmost_level"
			},
			{
				onClick: function (e) {
					add_new_row(ez5.admin.datatypes[0][0]);
				},
				loca_key: "admin.datamodel.new_field",
				sort: "A:2",
				group: "topmost_level"
			},
			{
				sort: "A:3",
				group: "topmost_level",
				onClick: function (e) {
					CUI.prompt({
						text: $$('admin.datamodel.x_new_fields.prompt')
					}).done(function (quantity) {
						quantity = CUI.util.getInt(quantity)
						if (quantity && quantity > 0) {
							for (var i = 0; i < quantity; i++) {
								add_new_row(ez5.admin.datatypes[0][0]);
							}
						}
					})
				},
				loca_key: "admin.datamodel.x_new_fields"
			},
			{
				sort: "A:4",
				group: "topmost_level",
				onClick: function (e) {
					add_new_row("nested_table");
				},
				loca_key: "admin.datamodel.new_nested_table"
			}
		];
		items.push({
			divider: true
		});
		items.push({
			label: $$("admin.datamodel.label_below_nested_table"),
			group: "label_below_nested_table"
		});
		var row = $columns_table.getSelectedNode();
		if (!row || row.data.type != "nested_table") {
			items.push(new CUI.EmptyLabel({
				text: $$("admin.datamodel.no_nested_table_selected")
			}))
		} else {
			items.push({
				loca_key: "admin.datamodel.new_field",
				sort: "B:1",
				group: "label_below_nested_table",
				onClick: function () {
					add_new_row(ez5.admin.datatypes[0][0], row.data._node);
				}
			});
			items.push({
				loca_key: "admin.datamodel.new_nested_table",
				sort: "B:2",
				group: "label_below_nested_table",
				onClick: function () {
					add_new_row("nested_table", row.data._node);
				}
			})
		}

		items.push({
			divider: true
		});
		items.push({
			label: $$("admin.datamodel.label_append_sibling_to_field"),
			group: "label_append_sibling_to_field"
		});
		var row = $columns_table.getSelectedNode();
		if (!row) {
			items.push(new CUI.EmptyLabel({
				text: $$("admin.datamodel.no_field_selected")
			}))
		} else {
			items.push({
				loca_key: "admin.datamodel.new_field",
				sort: "C:1",
				group: "label_append_sibling_to_field",
				onClick: function () {
					add_new_row(ez5.admin.datatypes[0][0], row.data._node, true);
				}
			});
			items.push({
				loca_key: "admin.datamodel.new_nested_table",
				sort: "C:2",
				group: "label_append_sibling_to_field",
				onClick: function () {
					add_new_row("nested_table", row.data._node, true);
				}
			})
		}

		return items;
	}

	var $columns_table = new ListViewEditTree({
		fields: fields,
		"class": 'cui-lv--has-datafields',
		fixedCols: 0, // 2,
		selectableRows: ez5.admin.version == "HEAD",
		rowMove: ez5.admin.version == "HEAD",
		rowMoveWithinNodesOnly: true,
		onSelect: function() {
			update_datamodel_data_form();
		},
		onDeselect: function() {
			update_datamodel_data_form();
		},
		end_add_row: function(row) {
			CUI.Events.listen({
				node: row.getDOMNodes()[0],
				type: "toolbox",
				call: function(ev, info) {
					row.select();
					info.tools.push(new ToolboxTool({
						run: function() {
							removeRow();
							return;
						},
						group: "row_actions",
						name: "remove_row",
						loca_key: "datamodel.fields.button.minus_text",
						sort: "A:1"
					}));
					return;
				}
			});
			update_row_state(row);
		},
		onRender: function() {
			CUI.Events.listen({
				node: $columns_table.getScrollingContainer(),
				type: "toolbox",
				call: function(ev, info) {
					var selectedNode = $columns_table.getSelectedNode();

					if (selectedNode) {
						if (CUI.dom.parentsUntil(ev.getTarget(), ".cui-list-view-row-selectable").length === 0) {
							selectedNode.deselect();
							selectedNode = null;
						}
					}

					// Iterate the menu items and map some attributes to instantiate toolbox tools.
					get_menu_items().forEach(function(item, index) {
						if (!CUI.util.isPlainObject(item) || item.divider || !item.onClick) {
							return;
						}

						if (selectedNode) {
							if (item.group === "topmost_level") {
								return;
							}
							if (selectedNode.data.type != "nested_table" && item.group == "label_below_nested_table") {
								return
							}
						} else {
							if (item.group === "label_append_sibling_to_field") {
								return;
							}
						}

						item.name = "name-" + index;
						item.run = item.onClick;
						delete item.onClick;
						info.tools.push(new ToolboxTool(item));
					});
					return;
				}
			})
		},
		footer_left: function() {
			if (ez5.admin.version==="HEAD") {
				return [
					{
						icon: "plus",
						loca_key: "datamodel.fields.button.plus",
						group: "plusminus",
						disabled: opts.disabled,
						menu: {
							items: get_menu_items
						}
					}
					,
					minusButton
				];
			} else {
				return;
			}
		}
	});

	update_datamodel_data_form();

	/* Save / Cancel Buttons */

	return {
		save_schema: save_schema,
		datamodel: datamodel,
		form: dm_form,
		$columns_table: $columns_table
	};
}
ez5.admin.save_masks = function(_opts) {
	var opts = CUI.Element.readOpts(
		_opts, "ez5.admin.save_masks",
		{
			mask: {
				mandatory: true,
				check: MaskSchema
			},
			return_data: {
				"check": Boolean
			},
			"delete": {
				"check": Boolean
			},
			event: {
				"check": CUI.Event
			}
		}
	);

	var l10n_prefix = null;

	var parse_data = function(rows, mask, l10n_keys) {
		mask.fields = [];

		rows.forEach(function(row) {

			if (row.getFieldToSave) {
				mask.fields.push(row.getFieldToSave(
					{
						mask: mask,
						l10n_prefix: l10n_prefix,
						l10n_keys: l10n_keys
					}
				));
				return;
			}

			var field = {
				"kind": row.type
			};

			mask.fields.push(field);

			field.edit = {};
			field.output = {};
			field.search = {};

			if (row.data.edit_show) {
				field.edit.mode = "show";
			} else if (row.data.edit_edit) {
				field.edit.mode = "edit";
			} else {
				field.edit.mode = "off";
			}

			field.output.detail = row.data.output_detail;
			field.output.text = row.data.output_text;
			field.output.table = row.data.output_table;

			field.custom_settings = CUI.util.copyObject(row.data.custom_settings, true);


			// remove custom settings that are the same as the default, this is to keep the mask schema clean
			// also avoid false positives when checking the mask schema
			custom_data_defaults = {
				"show_in_summary": false,
				"format_output": null,
				"editor_frontend_mode": "default",
				"blockWidth": "100%",
				"render_markdown": false,
			};

			for (let k of Object.keys(custom_data_defaults)) {
				if(field.custom_settings[k] === custom_data_defaults[k])
				{
					delete field.custom_settings[k];
				}
			}

			var defaultCustomSettings = {};

			if (row.column_type === "daterange") {
				defaultCustomSettings.textual_representation_show_internal_dates = true
			}

			if (row.type === "linked-table") {
				defaultCustomSettings.show_first_empty_nested = true
			}

			CUI.util.mergeMap(field.custom_settings, defaultCustomSettings);

			if (row.data.standard_order) {
				field.output.standard = {
					format: row.data.standard_format,
					order: row.data.standard_order || null
				}
				if(ez5.version("6.7")) {
					field.output.standard.stop_if_set = row.data.stop_if_set || false;
				}
			} else {
				field.output.standard = {
					order: row.data.standard_order || null
				}
			}

			if(ez5.version("6")) {
				// Support nested linked-table formatting options from customize popover
				if (!field.output.standard.format && row.data.format) {
					field.output.standard.format = row.data.format;
				}
				if (row.data.format_inner) {
					field.output.standard.format_inner = row.data.format_inner;
				}
			}

			field.output.standard_eas = {
				order: row.data.standard_eas_order || null
			}

			if(ez5.version("6.7")) {
				field.output.standard_geo = {
					order: row.data.standard_geo_order || null
				}
			}

			switch(row.type) {
				case "linked-table":
					field.nested_sort = CUI.util.copyObject(row.data.nested_sort, true);
					if (!CUI.util.isUndef(row.data.nested_standard_first_only)) {
						field.nested_standard_first_only = row.data.nested_standard_first_only;
					}
					if(ez5.version("6") && row.data.field.inheritance) {
						field.inheritance = CUI.util.copyObject(row.data.field.inheritance, true);
					}
				case "reverse-linked-table":
					if (!CUI.util.isUndef(row.data.nested_standard_first_only)) {
						field.nested_standard_first_only = row.data.nested_standard_first_only;
					}

					if (row.data.field.is_hierarchical) {
						field.is_hierarchical = true;
						// console.debug("adding reverse linked table", row, field);
					} else {
						field.other_table_id = row.data.field.other_table_id;
						field.other_column_id = row.data.field.other_column_id;
					}
					field.edit.as_table = row.data.edit_as_table;
					field.edit.append_only = row.data.edit_append_only;
					field.search.fulltext = row.data.search_fulltext;
					field.search.facet = row.data.search_facet;
					field.search.expert = row.data.search_expert;
					field.search.nested = row.data.search_nested;

					if (!row.data.field.hierarchical_mask_hint) {
						if (row.children) {
							field.mask = CUI.util.copyObject(row.data.field.mask, true);
							parse_data(row.children, field.mask, l10n_keys);
						}
					} else {
						field.hierarchical_mask_hint = true;
					}
					break;
				case "field":
					field.column_id = row.data.field.column_id;
					field.search.fulltext = row.data.search_fulltext;
					field.search.facet = row.data.search_facet;
					field.search.expert = row.data.search_expert;
					if(ez5.version("6") && row.data.field.inheritance) {
						field.inheritance = CUI.util.copyObject(row.data.field.inheritance, true);
					}

				break;
				case "link":
					// $field.attr("type", row.data.$field.attr("type"));
					field.column_id = row.data.field.column_id;
					field.other_table_id = row.data.field.other_table_id;
					field.mask_id = row.data.mask_id;
					// console.debug("row data", row.data.inline, row.data);
					field.inline = row.data.inline;

					field.search.fulltext = row.data.search_fulltext;
					field.search.facet = row.data.search_facet;
					field.search.expert = row.data.search_expert;
					if(ez5.version("6") && row.data.field.inheritance) {
						field.inheritance = CUI.util.copyObject(row.data.field.inheritance, true);
					}
					break;
				default:
					CUI.util.assert(false, "save_masks", "Unsupported row.type", {row: row});
				}
				l10n_keys[row.data.field._user_hint_loca_key()] = row.data.edit_user_hint_l10n;
				l10n_keys[row.data.field._user_hint_loca_key()]._comment = row.data.field._full_name;

				l10n_keys[row.data.field._user_output_hint_loca_key()] = row.data.output_user_hint_l10n;
				l10n_keys[row.data.field._user_output_hint_loca_key()]._comment = row.data.field._full_name;

				if (ez5.version("6.22")) {
					l10n_keys[row.data.field._user_search_hint_loca_key()] = row.data.search_user_hint_l10n;
					l10n_keys[row.data.field._user_search_hint_loca_key()]._comment = row.data.field._full_name;
				}
		});
	}

	var mask = opts.mask;
	var data = mask.getData();

	var new_mask = null;
	var l10n_keys = {}

	const l10nDisplayName = new CUI.Deferred();

	if (opts["delete"]) {
		l10nDisplayName.resolve();
	} else {
		CUI.util.assert(data.table_id, "ez5.admin.save_masks", "No table_id set, cannot save mask", {opts: opts});
		new_mask = {
			"table_id": data.table_id,
			"mask_id": data.mask_id,
			"name": data.name,
			"comment": data.comment,
			"is_preferred": data.is_preferred,
			"hide_in_detail": data.hide_in_detail,
			"hide_in_editor": data.hide_in_editor,
			"hide_in_print_dialog": data.hide_in_print_dialog,
			"require_comment": data.require_comment,
			"system_fields": {}
		}

		if(ez5.version("6.7")) {
			new_mask.custom_settings = {};
			new_mask.custom_settings.system_fields = {
				"other_fields_edit" : data.other_fields_edit,
				"other_fields_output" : data.other_fields_output
			}
		}

		var tb = ez5.schema[ez5.admin.version]._table_by_id[new_mask.table_id]

		if (tb.is_hierarchical || tb.polyhierarchical) {
			new_mask.system_fields.parent = {
				"output": {
					"mode": data.parent_output
				},
				"edit": {
					"mode": data.parent_edit
				},
				"inline": data.parent_inline,
				"mask_id": data.parent_mask_id
			};
			new_mask.standard_numbering = data.standard_numbering
		}

		if (tb.has_tags) {
			new_mask.system_fields.tags = {
				"output": {
					"mode": data.tags_output
				},
				"edit": {
					"mode": data.tags_edit
				}
			};
		}

		new_mask.system_fields.object_id = {
			"output": {
				"mode": data.object_id_output
			},
			"edit": {
				"mode": data.object_id_edit
			}
		};

		new_mask.system_fields.owner = {
			"output": {
				"mode": data.owner_output
			},
			"edit": {
				"mode": data.owner_edit
			}
		};

		new_mask.system_fields.publish = {
			"output": {
				"mode": data.publish_output
			}
		};

		if (tb.acl_table) {
			new_mask.system_fields.acl = {
				"output": {
					"mode": data.acl_output
				},
				"edit": {
					"mode": data.acl_edit
				}
			};
		}

		if (tb.in_main_search) {
			new_mask.system_fields.collections = {
				"output": {
					"mode": data.collections_output
				},
				"edit": {
					"mode": data.collections_edit
				}
			};
		}

		if (tb.pool_link) {
			new_mask.system_fields.pool = {
				"output": {
					"mode": data.pool_output
				}
			};

			if (ez5.version("6") && tb.columns.some(function(columns) { return columns.kind == "reverse_link"})) {
				new_mask.system_fields.pool.edit = {
					mode: data.pool_edit
				}
			}
		}

		l10n_prefix = function() { return "mask."+new_mask.table_id+"."+new_mask.name+"."; }

		const maskNameLocaKey = mask.getNameLocaKey();

		if (ez5.version("6") && mask.schema._is_all_fields) {
			for (const locale of ez5.session.getConfigFrontendLanguages()) {
				if (!ez5.loca.strings[locale]) {
					ez5.loca.load_keys(locale);
				}
			}

			CUI.whenAll(...ez5.loca.__loadingKeys.values())
				.done(() => {
					l10n_keys[maskNameLocaKey] = Object.fromEntries(ez5.session.getConfigFrontendLanguages().map((locale) => [locale, $$("mask.default.displayname", null, locale, "")]));
					ez5.loca.clean_keys(l10n_keys);
				})
				.always(() => l10nDisplayName.resolve());;
		} else {
			l10nDisplayName.resolve();
			l10n_keys[maskNameLocaKey] = data.displayname_l10n;
		}

		// l10n_keys[mask.getUserHintLocaKey()] = data.user_hint_l10n;

		parse_data(mask.getRows(), new_mask, l10n_keys);
	}

	ez5.loca.clean_keys(l10n_keys);

	if (opts.return_data) {
		return {
			l10n_keys: l10n_keys,
			new_mask: new_mask
		}
	}

	var mask_schema = CUI.util.copyObject(ez5.mask[ez5.admin.version], true);

	var old_mask;
	var other_masks = [];
	CUI.util.assert(!opts["delete"] || data.mask_id, "ez5.admin.save_masks", "No table_id set, cannot delete mask", {opts: opts});
	if (data.mask_id) {
		// replace in mask set
		for (idx = 0; idx < mask_schema.masks.length; idx++) {
			if (mask_schema.masks[idx].mask_id === data.mask_id) {
				if (new_mask) {
					old_mask = mask_schema.masks.splice(idx, 1, new_mask)[0];
				} else {
					old_mask = mask_schema.masks.splice(idx, 1)[0];
					idx--;
				}
			} else if (mask_schema.masks[idx].table_id === data.table_id) {
				other_masks.push(mask_schema.masks[idx]);
			}
		};
	} else {
		old_mask = null;
		for (idx = 0; idx < mask_schema.masks.length; idx++) {
			if (mask_schema.masks[idx].table_id === data.table_id) {
				other_masks.push(mask_schema.masks[idx]);
			}
		}
		mask_schema.masks.push(new_mask);
	}

	ez5.schema.clean_mask_schema(mask_schema);

	mask_schema.based_on_schema_version = ez5.schema.HEAD.version;
	mask_schema.version = 1; // right now the version is not used, so we send a "1"

	var dfr = new CUI.Deferred();
	if (opts["delete"]) {
		/* make sure one of our other masks is preferred */
		var preferred = null;
		for (var idx = 0; idx < other_masks.length; idx++) {
			if (other_masks[idx].is_preferred) {
				preferred = idx;
				break;
			}
		}
		if (other_masks.length > 0 && preferred === null) {
			other_masks[0].is_preferred = true;
		}
	} else if (new_mask.is_preferred) {
		/* make sure to reset all other mask's preferred */
		for (var idx = 0; idx < other_masks.length; idx++) {
			other_masks[idx].is_preferred = false;
		}
	}

	/* FIXME: we lower case all mask names, the server does not allow upper case any more */
	/*
	for (var idx = 0; idx < mask_schema.masks.length; idx++) {
		mask_schema.masks[idx].name = mask_schema.masks[idx].name.toLocaleLowerCase();
		}
	*/


	var ev = opts.event;
	if (ev && ev.hasModifierKey()) {
		if (ev.altKey() && ev.ctrlKey() && ev.shiftKey()) {
			console.debug("l10n_keys", l10n_keys);
			console.debug("mask_schema", mask_schema);
			console.warn("dumped full mask post as objects");
		} else if (ev.altKey() && ev.ctrlKey()) {
			console.debug(CUI.util.dump(l10n_keys));
			console.debug(CUI.util.dump(mask_schema));
			console.warn("dumped full mask post, use shift+ctrl+alt for full dump as objects");
		} else {
			console.debug(CUI.util.dump(l10n_keys));
			console.debug("mask schema to save", CUI.util.dump(new_mask));
			console.warn("dumped updated mask post only, use ctrl+alt for full dump, use shift+ctrl+alt for full dump as objects");
		}
		return dfr.reject().promise();
	}

	// console.debug("sending mask schema. l10n_keys:", l10n_keys);

	var send_schema = function() {
		l10nDisplayName
			.promise()
			.fail(() => dfr.reject)
			.done(() => {
				ez5.api.mask({
					api: "/"+ez5.admin.version,
					type: "POST",
					json_data: mask_schema,
					success: function() {
						var valid_prefixes = ez5.loca.get_valid_user_key_prefixes(ez5.admin.version);
						var delete_prefix;
						if (new_mask) {
							delete_prefix = "mask."+new_mask.table_id+"."+new_mask.name+".";
						}
						// console.debug("save loca keys:", l10n_keys, valid_prefixes, delete_prefix);
						ez5.loca.update({
							realm: ez5.admin.version,
							valid_prefixes: valid_prefixes,
							delete_prefix: delete_prefix,
							keys: l10n_keys
						}).done(function() {
							ez5.schema.load_schema()
								.done(dfr.resolve)
								.fail(dfr.reject)
						});
					}
				}).fail(dfr.reject);
			});
	}

	if (ez5.schema.CURRENT.version == ez5.schema.HEAD.version) {
		// if the schema HEAD version === CURRENT version we need to post the
		// schema to increment the HEAD version so that the schema is consistent
		// and comittable. post_schema increments the head version.

		// to not clean_schema which is linked to our tree,
		// we copy the schema to be send

		ez5.admin.post_schema(CUI.util.copyObject(ez5.schema.HEAD, true)).done(send_schema).fail(dfr.reject);
	} else {
		send_schema();
	}


	return dfr.promise();
}
// Generated by CoffeeScript 1.12.7
var DatamodelListView,
  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;

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

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

  DatamodelListView.prototype.check_deselect = function(event, newNode) {
    if (event) {
      return this.allow_deselect();
    } else {
      return CUI.resolvedPromise();
    }
  };

  DatamodelListView.prototype.allow_deselect = function() {
    if (this.hasChanges()) {
      return CUI.confirm({
        text: $$("general.frontend.unsaved_changes.message"),
        button_text_ok: $$("general.frontend.unsaved_changes.confirm"),
        button_primary: "cancel"
      });
    } else {
      return CUI.resolvedPromise();
    }
  };

  DatamodelListView.prototype.hasChanges = function() {
    var e;
    if (ez5.admin.version === "CURRENT") {
      return false;
    }
    try {
      return !CUI.util.isEqual(this.saveData, this.getSaveData());
    } catch (error) {
      e = error;
      if (e instanceof InvalidSaveDataException) {
        return false;
      }
      throw e;
    }
  };

  DatamodelListView.prototype.setStatus = function() {
    var invalidFields, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9;
    if (this.datamodel.lock_status !== 'open') {
      if ((ref = this.saveButton) != null) {
        ref.disable();
      }
      if ((ref1 = this.copyButton) != null) {
        ref1.disable();
      }
      return this;
    }
    invalidFields = CUI.dom.findElements(this.datamodel.pane.center(), ".cui-input-invalid");
    if (invalidFields.length > 0) {
      if ((ref2 = this.saveButton) != null) {
        ref2.disable();
      }
      if ((ref3 = this.copyButton) != null) {
        ref3.disable();
      }
      return;
    } else {
      if ((ref4 = this.saveButton) != null) {
        ref4.enable();
      }
      if ((ref5 = this.copyButton) != null) {
        ref5.enable();
      }
    }
    if (this.hasChanges() && ez5.admin.version === "HEAD") {
      if ((ref6 = this.saveButton) != null) {
        ref6.enable();
      }
      if ((ref7 = this.copyButton) != null) {
        ref7.disable();
      }
    } else {
      if ((ref8 = this.saveButton) != null) {
        ref8.disable();
      }
      if ((ref9 = this.copyButton) != null) {
        ref9.enable();
      }
    }
    return this;
  };

  DatamodelListView.prototype.isInputDisabled = function() {
    if (ez5.admin.version === "CURRENT" || this.datamodel.lock_status !== 'open') {
      return true;
    } else {
      return false;
    }
  };

  DatamodelListView.prototype.select = function(ev) {
    var ret, set_status;
    ret = DatamodelListView.__super__.select.call(this, ev);
    this.showWaitBlock();
    if (ez5.admin.version === "CURRENT") {
      return ret;
    }
    set_status = (function(_this) {
      return function() {
        return _this.setStatus();
      };
    })(this);
    ret.done((function(_this) {
      return function() {
        CUI.Events.ignore({
          instance: _this
        });
        CUI.Events.listen({
          node: _this.datamodel.pane.center(),
          instance: _this,
          type: ["data-changed", "row_added", "row_removed", "row_moved"],
          call: function(ev) {
            return CUI.scheduleCallback({
              call: set_status,
              ms: 200
            });
          }
        });
        CUI.setTimeout({
          call: function() {
            _this.setSaveData();
            _this.datamodel.setStatus();
            return _this.setStatus();
          }
        });
      };
    })(this));
    return ret;
  };

  DatamodelListView.prototype.deselect = function(event, newNode) {
    this.hideWaitBlock();
    return DatamodelListView.__super__.deselect.call(this, event, newNode).done((function(_this) {
      return function() {
        CUI.Events.ignore({
          instance: _this
        });
        return _this.datamodel.empty();
      };
    })(this));
  };

  DatamodelListView.prototype.showWaitBlock = function() {
    if (this.__waitBlock) {
      return;
    }
    this.__waitBlock = new CUI.WaitBlock({
      element: this.datamodel.pane.center()
    }).show();
    return this;
  };

  DatamodelListView.prototype.hideWaitBlock = function() {
    var ref;
    if ((ref = this.__waitBlock) != null) {
      ref.destroy();
    }
    this.__waitBlock = null;
    return this;
  };

  DatamodelListView.prototype.getWaitModalTitleLocaKeyPrefix = function() {
    return "datamodel.list.view.wait.";
  };

  DatamodelListView.prototype.setSaveData = function() {
    return this.saveData = this.getSaveData();
  };

  DatamodelListView.prototype.getCancelButton = function() {
    if (ez5.admin.version === "CURRENT") {
      return;
    }
    return new LocaButton({
      ui: "datamodel-listview-cancel-button",
      loca_key: "datamodel.listview.cancel.button",
      secondary: true,
      onClick: (function(_this) {
        return function(ev) {
          return _this.check_deselect(ev).done(function() {
            return _this.deselect();
          });
        };
      })(this)
    });
  };

  return DatamodelListView;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var DatamodelListViewObjecttype,
  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;

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

  function DatamodelListViewObjecttype() {
    this.setObjecttype = bind(this.setObjecttype, this);
    return DatamodelListViewObjecttype.__super__.constructor.apply(this, arguments);
  }

  DatamodelListViewObjecttype.prototype.initOpts = function() {
    DatamodelListViewObjecttype.__super__.initOpts.call(this);
    return this.addOpts({
      objecttype: {
        check: "PlainObject"
      },
      datamodel: {
        mandatory: true,
        check: Datamodel
      },
      version: {
        check: ["CURRENT", "HEAD"]
      }
    });
  };

  DatamodelListViewObjecttype.prototype.readOpts = function() {
    DatamodelListViewObjecttype.__super__.readOpts.call(this);
    this.datamodel = this._datamodel;
    if (this._objecttype) {
      return this.setObjecttype(this._objecttype);
    }
  };

  DatamodelListViewObjecttype.prototype.setObjecttype = function(objecttype1) {
    var i, len, mask, ref;
    this.objecttype = objecttype1;
    this.children = [];
    ref = ez5.mask[this.opts.version]._masks_by_table_id[this.objecttype.table_id];
    for (i = 0, len = ref.length; i < len; i++) {
      mask = ref[i];
      this.children.push(new DatamodelListViewMask({
        mask: mask,
        datamodel: this.datamodel,
        objecttype: this,
        version: this.opts.version
      }));
      this.children.sort((function(_this) {
        return function(a, b) {
          return a.mask._name_localized.localeCompare(b.mask._name_localized);
        };
      })(this));
    }
    return this.__tableInst = new Table(this.opts.version, this.objecttype);
  };

  DatamodelListViewObjecttype.prototype.getMenuItem = function() {
    if (!this.objecttype) {
      return {
        hidden: true
      };
    }
    return {
      value: this.objecttype,
      text: this.objecttype._name_localized,
      onClick: (function(_this) {
        return function() {
          var new_mask;
          new_mask = new DatamodelListViewMask({
            datamodel: _this.datamodel,
            objecttype: _this,
            version: ez5.admin.version
          });
          return _this.addNode(new_mask).done(function() {
            return new_mask.select();
          });
        };
      })(this)
    };
  };

  DatamodelListViewObjecttype.prototype.renderContent = function() {
    if (this.objecttype) {
      return [
        new CUI.Label({
          "class": "ez5-objecttype-name",
          text: this.__tableInst.nameLocalized(),
          ui: "datamodel.list_view.objecttype_item:" + this.__tableInst.name()
        }), new CUI.Label({
          "class": "ez5-objecttype-table-name",
          text: this.__tableInst.name(),
          size: "mini",
          appearance: "secondary"
        }), new CUI.Label({
          "class": "ez5-objecttype-display-types",
          text: this.__tableInst.getDisplayType(),
          size: "mini",
          appearance: "secondary",
          multiline: true
        })
      ];
    } else {
      return new CUI.EmptyLabel({
        text: $$("admin.easydb.objecttype.list.name.new"),
        ui: "datamodel-list-new-objecttype"
      });
    }
  };

  DatamodelListViewObjecttype.prototype.deselect = function(event, newNode) {
    return DatamodelListViewObjecttype.__super__.deselect.call(this, event, newNode).done((function(_this) {
      return function() {
        return _this.__cleanNode();
      };
    })(this));
  };

  DatamodelListViewObjecttype.prototype.select = function(ev) {
    return DatamodelListViewObjecttype.__super__.select.call(this, ev).done((function(_this) {
      return function() {
        return _this.__initNode();
      };
    })(this)).always((function(_this) {
      return function() {
        return _this.hideWaitBlock();
      };
    })(this));
  };

  DatamodelListViewObjecttype.prototype.__initNode = function() {
    var ref;
    this.datamodelAdmin = ez5.admin.datamodel({
      table_id: (ref = this.objecttype) != null ? ref.table_id : void 0,
      disabled: this.isInputDisabled()
    });
    this.tabs = new CUI.Tabs({
      "class": "ez5-data-model-list-view-objecttype-tabs",
      tabs: [
        {
          ui: "datamodel.content.tab:general",
          name: "general",
          padded: true,
          text: $$("admin.objecttype.tab.general"),
          button_id: 'datamodel.list.view.objectttype.general',
          content: this.datamodelAdmin.form
        }, {
          ui: "datamodel.content.tab:datamodel",
          name: "datamodel",
          text: $$("admin.objecttype.tab.datamodel"),
          button_id: 'datamodel.list.view.objectttype.datamodel',
          content: this.datamodelAdmin.$columns_table.render()
        }
      ],
      footer_right: [this.getCancelButton(), this.getCopyButton(), this.getSaveButton()]
    });
    this.datamodel.pane.replace(new CUI.SimplePane({
      "class": "cui-pane--window",
      title: $$("admin.datamodel.pane.center.objecttype.title"),
      content: this.tabs
    }), "center");
    return this.datamodelAdmin.$columns_table.load_data(this.datamodelAdmin.datamodel.rows);
  };

  DatamodelListViewObjecttype.prototype.__cleanNode = function() {
    delete this.datamodelAdmin;
    delete this.tabs;
    delete this.saveButton;
    return delete this.copyButton;
  };

  DatamodelListViewObjecttype.prototype.getCopyButton = function() {
    var ref;
    if (this._version === "CURRENT") {
      return;
    }
    this.copyButton = new LocaButton({
      ui: "datamodel-list-view-copy-objecttype-button",
      loca_key: "datamodel.list.view.objecttype.button.copy",
      disabled: !((ref = this.objecttype) != null ? ref.table_id : void 0),
      secondary: true,
      onClick: (function(_this) {
        return function() {
          return _this.copy().done(function(newCopiedNode) {
            _this.appendSibling(newCopiedNode);
            return newCopiedNode.select();
          });
        };
      })(this)
    });
    return this.copyButton;
  };

  DatamodelListViewObjecttype.prototype.getSaveButton = function() {
    if (ez5.admin.version === "CURRENT") {
      return;
    }
    return this.saveButton = new CUI.Button({
      ui: "datamodel-listview-save-button",
      disabled: true,
      primary: true,
      onClick: (function(_this) {
        return function(ev) {
          ez5.splash.show('datamodel.list.view.wait.save_in_progress');
          return CUI.setTimeout({
            call: function() {
              return _this.save(ev).done(function() {
                return ez5.splash.done('datamodel.list.view.wait.saved');
              }).fail(function() {
                return ez5.splash.hide();
              });
            }
          });
        };
      })(this),
      text: $$("base.save")
    });
  };

  DatamodelListViewObjecttype.prototype["delete"] = function() {
    var _table, add_owners_to_path, i, len, name, ot_id, ot_ids, path, tns;
    if (!this.objecttype) {
      return this.remove();
    }
    ot_ids = ez5.admin.get_linked_table_ids(this.objecttype.table_id);
    add_owners_to_path = function(table, path, level) {
      var owner_table;
      if (level == null) {
        level = 0;
      }
      if (level > 10) {
        return path;
      }
      if (table.owned_by) {
        owner_table = ez5.schema[ez5.admin.version]._table_by_id[table.owned_by.other_table_id];
        if (owner_table) {
          path = owner_table._name_localized + " > " + path;
        }
        if (owner_table.owned_by) {
          path = add_owners_to_path(owner_table, path, ++level);
        }
      }
      return path;
    };
    if (ot_ids.length) {
      tns = [];
      for (i = 0, len = ot_ids.length; i < len; i++) {
        ot_id = ot_ids[i];
        _table = ez5.schema[ez5.admin.version]._table_by_id[ot_id];
        name = _table._name_localized;
        path = add_owners_to_path(_table, name);
        tns.push(path);
      }
      CUI.problem({
        text: $$("admin.objecttype.remove.error_other_tables", {
          tables: tns.join("\n")
        })
      });
      return;
    }
    return CUI.confirm({
      text: ez5.version("6") ? $$('admin.objecttype.remove.confirm.fylr') : $$('admin.objecttype.remove.confirm'),
      button_text_ok: $$('base.delete'),
      button_text_cancel: $$('base.cancel'),
      button_primary: 'cancel'
    }).done((function(_this) {
      return function() {
        var j, len1, remove_table_ids, schema, table_id;
        ez5.splash.show('datamodel.list.view.wait.delete_objecttype_in_progress');
        remove_table_ids = ez5.admin.get_dependent_table_ids(_this.objecttype.table_id, [parseInt(_this.objecttype.table_id)]);
        schema = CUI.util.copyObject(ez5.schema.HEAD, true);
        for (j = 0, len1 = remove_table_ids.length; j < len1; j++) {
          table_id = remove_table_ids[j];
          CUI.util.removeFromArray(table_id, schema.tables, function(v) {
            return v.table_id === table_id;
          });
        }
        return ez5.admin.post_schema(schema).done(function() {
          return _this.datamodel.copyToStore().always(function() {
            _this.datamodel.setStatus();
            _this.remove();
            return ez5.splash.done('datamodel.list.view.wait.objecttype_deleted');
          });
        }).fail(function() {
          return ez5.splash.hide();
        });
      };
    })(this));
  };

  DatamodelListViewObjecttype.prototype.getSaveData = function() {
    return this.datamodelAdmin.save_schema({
      return_data: true
    });
  };

  DatamodelListViewObjecttype.prototype.save = function(ev) {
    var dfr, ref, ref1;
    if ((ref = this.saveButton) != null) {
      ref.disable();
    }
    if ((ref1 = this.copyButton) != null) {
      ref1.disable();
    }
    dfr = new CUI.Deferred();
    dfr.done((function(_this) {
      return function() {
        return _this.setSaveData();
      };
    })(this));
    this.datamodelAdmin.save_schema({
      event: ev
    }).fail((function(_this) {
      return function() {
        return _this.saveFailed(dfr);
      };
    })(this)).done((function(_this) {
      return function() {
        var ot, preferred_mask;
        ot = ez5.schema.HEAD._table_by_name[_this.datamodelAdmin.datamodel.datamodel_data.name];
        if (ez5.mask.HEAD._masks_by_table_id[ot.table_id].length) {
          _this.datamodel.copyToStore().always(function() {
            _this.saveDone(ot);
            return dfr.resolve();
          });
          return;
        }
        preferred_mask = _this.datamodel.getDefaultMask(ot.table_id);
        console.debug("adding default mask", CUI.util.dump(preferred_mask));
        return (new MaskEditor({
          schema: preferred_mask
        })).save(ev).done(function() {
          return _this.datamodel.copyToStore().always(function() {
            _this.saveDone(ot);
            return dfr.resolve();
          });
        }).fail(function() {
          return _this.saveFailed(dfr);
        });
      };
    })(this));
    return dfr.promise();
  };

  DatamodelListViewObjecttype.prototype.saveFailed = function(dfr) {
    this.saveButton.enable();
    return dfr.reject();
  };

  DatamodelListViewObjecttype.prototype.saveDone = function(objecttype) {
    this.datamodel.setStatus();
    this.removeFromDOM(false);
    this.setObjecttype(objecttype);
    this.update();
    if (this.children.length && this.do_open) {
      this.open();
    }
    this.__cleanNode();
    return this.__initNode();
  };

  DatamodelListViewObjecttype.prototype.copy = function() {
    var datamodelRows, deferred, key, linkedObjectsSameObjectData, locaDisplayNames, newDataModel, newDisplayName, newTableName, onFail, originalTableId, removeColumnIds;
    ez5.splash.show('datamodel.list.view.wait.copy_in_progress');
    originalTableId = this.objecttype.table_id;
    newDataModel = ez5.admin.datamodel();
    newDataModel.datamodel.datamodel_data = CUI.util.copyObject(this.datamodelAdmin.datamodel.datamodel_data, true);
    datamodelRows = CUI.util.copyObject(this.datamodelAdmin.datamodel.rows);
    newDataModel.datamodel.rows = datamodelRows.filter((function(_this) {
      return function(row) {
        return row.data.type !== "reverse_link";
      };
    })(this));
    delete newDataModel.datamodel.datamodel_data.table_id;
    newTableName = this.datamodel.getUniqueName(newDataModel.datamodel.datamodel_data.name, ez5.schema.HEAD._table_by_name);
    newDataModel.datamodel.datamodel_data.name = newTableName;
    locaDisplayNames = newDataModel.datamodel.datamodel_data.displayname_l10n;
    for (key in locaDisplayNames) {
      if (CUI.util.isEmpty(locaDisplayNames[key])) {
        continue;
      }
      newDisplayName = $$("admin.easydb.objecttype.copy_display_name", {
        name: locaDisplayNames[key]
      });
      newDataModel.datamodel.datamodel_data.displayname_l10n[key] = newDisplayName;
    }
    linkedObjectsSameObjectData = {};
    removeColumnIds = (function(_this) {
      return function(listViewEditTreeNodeArray, pathName) {
        var data, i, len, listViewEditTreeNode, results;
        if (pathName == null) {
          pathName = "";
        }
        results = [];
        for (i = 0, len = listViewEditTreeNodeArray.length; i < len; i++) {
          listViewEditTreeNode = listViewEditTreeNodeArray[i];
          data = listViewEditTreeNode.getData();
          delete data.column_id;
          delete data.column;
          if (data.type === ("link_" + originalTableId)) {
            linkedObjectsSameObjectData[pathName + data.name] = {
              bidirectional: data.bidirectional,
              bidirectional_reverse: data.bidirectional_reverse
            };
            data.bidirectional = false;
            data.bidirectional_reverse = false;
            data.type = "text_oneline";
          }
          if (listViewEditTreeNode.children) {
            delete listViewEditTreeNode.link_table_id;
            results.push(removeColumnIds(listViewEditTreeNode.children, pathName + data.name + "."));
          } else {
            results.push(void 0);
          }
        }
        return results;
      };
    })(this);
    removeColumnIds(newDataModel.datamodel.rows);
    deferred = new CUI.Deferred();
    onFail = (function(_this) {
      return function() {
        ez5.splash.hide();
        return deferred.reject();
      };
    })(this);
    newDataModel.save_schema().done((function(_this) {
      return function() {
        var copyAllMasks, dataModelCopied, newObjectTypeCopiedData, newTableId, originalMasks, updateLinkedObjectsSameObject;
        newObjectTypeCopiedData = ez5.schema.HEAD._table_by_name[newTableName];
        newTableId = newObjectTypeCopiedData.table_id;
        originalMasks = ez5.mask.HEAD._masks_by_table_id[originalTableId];
        copyAllMasks = function() {
          var saveMaskSync;
          saveMaskSync = function(index) {
            var changeColumnIds, datamodelListViewObjectTypeCopy, mask, maskEditor, originalDisplayname_l10n;
            if (index < originalMasks.length) {
              mask = CUI.util.copyObject(originalMasks[index], true);
              delete mask.mask_id;
              mask.table_id = newTableId;
              mask.name = _this.datamodel.getUniqueName(mask.name, ez5.mask.HEAD._mask_by_name);
              changeColumnIds = function(fields, table) {
                var field, i, len, nestedTable, newNestedTableName, ref, results;
                results = [];
                for (i = 0, len = fields.length; i < len; i++) {
                  field = fields[i];
                  if (field.kind === "field" || field.kind === "link") {
                    field.column_id = table._column_by_name[field.column_name_hint].column_id;
                    if (field.other_table_id === originalTableId) {
                      results.push(field.other_table_id = newTableId);
                    } else {
                      results.push(void 0);
                    }
                  } else if (field.kind === "linked-table" && ((ref = field.mask) != null ? ref.fields : void 0)) {
                    newNestedTableName = field.mask.table_name_hint.replace(_this.objecttype.name, newTableName);
                    nestedTable = ez5.schema.HEAD._table_by_name[newNestedTableName];
                    field.other_table_id = nestedTable.table_id;
                    field.mask.table_id = nestedTable.table_id;
                    results.push(changeColumnIds(field.mask.fields, nestedTable));
                  } else {
                    results.push(void 0);
                  }
                }
                return results;
              };
              mask.fields = mask.fields.filter(function(field) {
                return field.kind !== "reverse-linked-table";
              });
              changeColumnIds(mask.fields, newObjectTypeCopiedData);
              originalDisplayname_l10n = ez5.loca.get_user_key(ez5.admin.version, mask._name_loca_key());
              mask._name_loca_key = function() {
                return "mask." + newTableId + "." + mask.name + ".name";
              };
              maskEditor = new MaskEditor({
                schema: mask
              });
              maskEditor.getMask().getData().displayname_l10n = originalDisplayname_l10n;
              return maskEditor.save().done(function() {
                return saveMaskSync(++index);
              }).fail(onFail);
            } else {
              datamodelListViewObjectTypeCopy = new DatamodelListViewObjecttype({
                datamodel: _this._datamodel,
                version: _this._version,
                objecttype: newObjectTypeCopiedData
              });
              return _this.datamodel.copyToStore().always(function() {
                _this.setSaveData();
                ez5.splash.done('datamodel.list.view.wait.copied');
                return deferred.resolve(datamodelListViewObjectTypeCopy);
              });
            }
          };
          return saveMaskSync(0);
        };
        if (!CUI.util.isEmpty(linkedObjectsSameObjectData)) {
          dataModelCopied = ez5.admin.datamodel({
            table_id: newTableId
          });
          updateLinkedObjectsSameObject = function(listViewEditTreeNodeArray, pathName) {
            var bidirectionalField, data, i, len, listViewEditTreeNode, results;
            if (pathName == null) {
              pathName = "";
            }
            results = [];
            for (i = 0, len = listViewEditTreeNodeArray.length; i < len; i++) {
              listViewEditTreeNode = listViewEditTreeNodeArray[i];
              data = listViewEditTreeNode.getData();
              bidirectionalField = linkedObjectsSameObjectData[pathName + data.name];
              if (!CUI.util.isNull(bidirectionalField) && data.type !== "nested_table") {
                data.bidirectional = bidirectionalField.bidirectional;
                data.bidirectional_reverse = bidirectionalField.bidirectional_reverse;
                data.type = "link_" + newTableId;
              }
              if (listViewEditTreeNode.children) {
                results.push(updateLinkedObjectsSameObject(listViewEditTreeNode.children, pathName + data.name + "."));
              } else {
                results.push(void 0);
              }
            }
            return results;
          };
          updateLinkedObjectsSameObject(dataModelCopied.datamodel.rows);
          return dataModelCopied.save_schema().done(function() {
            return copyAllMasks();
          }).fail(onFail);
        } else {
          return copyAllMasks();
        }
      };
    })(this)).fail(onFail);
    return deferred.promise();
  };

  return DatamodelListViewObjecttype;

})(DatamodelListView);
// Generated by CoffeeScript 1.12.7
var DatamodelListViewMask,
  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;

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

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

  DatamodelListViewMask.prototype.readOpts = function() {
    var fieldSettings, i, len, mask, ref, ref1, ref2, systemFieldName;
    DatamodelListViewMask.__super__.readOpts.call(this);
    this.datamodel = this._datamodel;
    this.objecttype = this._objecttype;
    this.table_id = this.objecttype.objecttype.table_id;
    if (this._mask) {
      this.setMask(this._mask);
    } else {
      mask = ez5.all_fields_mask_preferred.HEAD._masks_by_table_id[this.table_id][0];
      mask = CUI.util.copyObject(mask, true);
      ref = ["acl", "collections", "object_id", "owner", "publish"];
      for (i = 0, len = ref.length; i < len; i++) {
        systemFieldName = ref[i];
        fieldSettings = mask.system_fields[systemFieldName];
        if (!fieldSettings) {
          continue;
        }
        if ((ref1 = fieldSettings.edit) != null) {
          ref1.mode = "off";
        }
        if ((ref2 = fieldSettings.output) != null) {
          ref2.mode = "off";
        }
      }
      this.setMask(mask);
      ez5.schema.addLocaFunctions(mask);
    }
    return this;
  };

  DatamodelListViewMask.prototype.initOpts = function() {
    DatamodelListViewMask.__super__.initOpts.call(this);
    return this.addOpts({
      datamodel: {
        mandatory: true,
        check: Datamodel
      },
      objecttype: {
        mandatory: true,
        check: function(v) {
          return v instanceof DatamodelListViewObjecttype && CUI.util.isInteger(v.objecttype.table_id);
        }
      },
      mask: {
        check: "PlainObject"
      },
      version: {
        mandatory: true,
        check: ["CURRENT", "HEAD"]
      }
    });
  };

  DatamodelListViewMask.prototype.setMask = function(mask1) {
    this.mask = mask1;
  };

  DatamodelListViewMask.prototype.setStatus = function() {
    var ref, ref1;
    DatamodelListViewMask.__super__.setStatus.call(this);
    if (this.datamodel.lock_status !== 'open') {
      return;
    }
    if (this.hasChanges() || !this.mask.mask_id) {
      return (ref = this.copyButton) != null ? ref.disable() : void 0;
    } else {
      return (ref1 = this.copyButton) != null ? ref1.enable() : void 0;
    }
  };

  DatamodelListViewMask.prototype.renderContent = function() {
    var secondaryText;
    if (this.mask.mask_id) {
      secondaryText = [];
      if (this.mask.is_preferred) {
        secondaryText.push($$("admin.mask.list.secondary.standard|label"));
      }
      if (ez5.session.isDebug()) {
        secondaryText.push(this.mask.name);
      }
      return [
        new CUI.Label({
          "class": "ez5-objecttype-name",
          text: this.mask._name_localized
        }), secondaryText.length > 0 ? new CUI.Label({
          "class": "ez5-objecttype-table-name",
          text: secondaryText.join(" - "),
          size: "mini",
          appearance: "secondary"
        }) : void 0
      ];
    } else {
      return new CUI.EmptyLabel({
        text: $$("admin.mask.list.name.new.placeholder")
      });
    }
  };

  DatamodelListViewMask.prototype["delete"] = function(ev) {
    if (this.mask.mask_id) {
      return this.maskEditor["delete"](ev).progress((function(_this) {
        return function() {
          _this.deselect();
          return ez5.splash.show('datamodel.list.view.wait.delete_mask_in_progress');
        };
      })(this)).done((function(_this) {
        return function() {
          _this.datamodel.setStatus();
          _this.remove(true);
          return _this.datamodel.copyToStore().always(function() {
            return ez5.splash.done('datamodel.list.view.wait.mask_deleted');
          });
        };
      })(this)).fail((function(_this) {
        return function() {
          return ez5.splash.hide();
        };
      })(this));
    } else {
      ez5.splash.show('datamodel.list.view.wait.delete_mask_in_progress');
      this.remove(true);
      return ez5.splash.done('datamodel.list.view.wait.mask_deleted');
    }
  };

  DatamodelListViewMask.prototype.getSaveData = function() {
    return this.maskEditor.getSaveData();
  };

  DatamodelListViewMask.prototype.select = function(ev) {
    if (this.mask.mask_id) {
      this.setMask(ez5.mask[this._version]._mask_by_id[this.mask.mask_id]);
    }
    return DatamodelListViewMask.__super__.select.call(this, ev).done((function(_this) {
      return function() {
        _this.maskEditor = new MaskEditor({
          schema: _this.mask,
          disabled: _this.isInputDisabled()
        });
        return _this.show();
      };
    })(this)).fail((function(_this) {
      return function() {
        return _this.hideWaitBlock();
      };
    })(this));
  };

  DatamodelListViewMask.prototype.deselect = function(event, newNode) {
    return DatamodelListViewMask.__super__.deselect.call(this, event, newNode).done((function(_this) {
      return function() {
        delete _this.maskEditor;
        delete _this.copyButton;
        return delete _this.saveButton;
      };
    })(this));
  };

  DatamodelListViewMask.prototype.show = function() {
    var tabs;
    tabs = this.maskEditor.getTabs();
    tabs.setFooterRight(new CUI.Buttonbar({
      buttons: [
        ez5.session.isDebug() ? {
          "class": "btn-info",
          text: "Dump Mask Fields",
          onClick: (function(_this) {
            return function() {
              return _this.maskEditor.dump_mask_fields();
            };
          })(this)
        } : void 0, this.getCancelButton(), this.getCopyButton(), this.getSaveButton()
      ]
    }));
    tabs.setFooterLeft(new CUI.HorizontalList({
      content: new CUI.Buttonbar({
        buttons: [this.getShowDemoDataButton(), this.getSelectRealObjectDataButton()]
      })
    }));
    this.maskEditor.show();
    this.datamodel.pane.replace(new CUI.SimplePane({
      "class": "cui-pane--window",
      title: $$("admin.datamodel.pane.center.mask.title"),
      content: tabs
    }), "center");
    this.datamodel.setStatus();
    this.setStatus();
    this.maskEditor.loadFields();
    return this.hideWaitBlock();
  };

  DatamodelListViewMask.prototype.getSelectRealObjectDataButton = function() {
    if (!ez5.objecttypes.getObjecttypes().some((function(_this) {
      return function(el) {
        return el.objecttype._id === _this.maskEditor.getMask().table.table_id;
      };
    })(this))) {
      return;
    }
    return new LocaButton({
      loca_key: "datamodel.listview.mask.select_demo_object.button",
      tooltip: {
        text: $$("datamodel.listview.mask.select_demo_object.button|tooltip")
      },
      onClick: (function(_this) {
        return function(ev, btn) {
          var collection, mask;
          mask = Mask.getMaskByMaskName("_all_fields", _this.maskEditor.getMask().table.table_id);
          collection = new CollectionMemory({
            preventBlurOnSelect: true
          });
          return new SearchPopover({
            link_mask: mask,
            popover_element: btn,
            collection: collection,
            request_format: "long",
            onDone: function() {
              var objects, ref;
              objects = collection.getObjects();
              if (objects && objects.length > 0) {
                _this.maskEditor.setDemoObject((ref = objects[0]) != null ? ref.getObject() : void 0);
                _this.maskEditor.renderPreviewDetail();
                _this.maskEditor.renderPreviewSearch();
                return _this.maskEditor.renderPreviewEditor();
              }
            }
          }).openPopover();
        };
      })(this)
    });
  };

  DatamodelListViewMask.prototype.getShowDemoDataButton = function() {
    return new LocaButton({
      loca_key: "datamodel.listview.mask.show-demo-data.button",
      onClick: (function(_this) {
        return function() {
          var bytes, confirmationChoice, data, dataDump, demoResultObject;
          demoResultObject = _this.maskEditor.getDemoResultObject();
          data = demoResultObject.getData();
          dataDump = CUI.util.dump(data);
          bytes = encodeURI(dataDump).split(/%..|./).length - 1;
          if (bytes / 1000000 < 2) {
            _this.__showDemoDataModal(demoResultObject, dataDump);
            return;
          }
          confirmationChoice = new CUI.ConfirmationChoice({
            title: $$("datamodel.listview.mask.show-demo-data-confirmation-title"),
            text: $$("datamodel.listview.mask.show-demo-data-confirmation-message"),
            cancel: true,
            choices: [
              {
                text: $$("datamodel.listview.mask.show-demo-data-confirmation-open"),
                onClick: function() {
                  return _this.__showDemoDataModal(demoResultObject, dataDump);
                }
              }, {
                text: $$("datamodel.listview.mask.show-demo-data-confirmation-download"),
                primary: true,
                onClick: function() {
                  return CUI.FileReader.save("demo-data-" + (demoResultObject.objecttype()) + "-" + (demoResultObject.maskName()) + ".json", JSON.stringify(data, null, "    "));
                }
              }
            ]
          });
          confirmationChoice.open();
        };
      })(this)
    });
  };

  DatamodelListViewMask.prototype.__showDemoDataModal = function(demoResultObject, dataDump) {
    var mod, title;
    title = $$("datamodel.listview.mask.show-demo-data.modal-title", {
      mask: demoResultObject.maskName(),
      objecttype: demoResultObject.objecttype(),
      mask_localized: demoResultObject.getMask().nameLocalized(),
      objecttype_localized: demoResultObject.objecttypeLocalized()
    });
    mod = new CUI.Modal({
      cancel: true,
      fill_space: "both",
      "class": "ez5-datamodel-mask-demo-modal",
      pane: {
        padded: true,
        title: title,
        content: (function(_this) {
          return function() {
            var input;
            input = new CUI.Input({
              appearance: "code",
              textarea: true,
              name: "value",
              maximize_horizontal: true,
              maximize_vertical: true,
              data: {
                value: dataDump
              }
            });
            return input.start();
          };
        })(this)
      }
    });
    return mod.show();
  };

  DatamodelListViewMask.prototype.getCopyButton = function() {
    if (this._version === "CURRENT") {
      return;
    }
    this.copyButton = new LocaButton({
      loca_key: "datamodel.list.view.mask.button.copy",
      disabled: true,
      secondary: true,
      onClick: (function(_this) {
        return function(ev) {
          var new_mask, new_mask_schema, new_schema;
          new_mask_schema = {
            masks: []
          };
          new_schema = CUI.util.copyObject(_this.maskEditor.getMask().getSchema(), true);
          new_schema.mask_id = null;
          new_schema.is_preferred = false;
          new_mask_schema.masks.push(new_schema);
          ez5.schema.enrich_mask_schema(new_mask_schema, ez5.admin.version);
          new_mask = new DatamodelListViewMask({
            datamodel: _this.datamodel,
            mask: new_schema,
            objecttype: _this.getFather(),
            version: ez5.admin.version
          });
          if (ev.hasModifierKey()) {
            return;
          }
          return _this.appendSibling(new_mask).done(function() {
            new_mask.select();
            return CUI.setTimeout({
              call: function() {
                return new_mask.maskEditor.getNameField().setValue(new_schema.name + "__copy", {
                  no_trigger: false
                });
              }
            });
          });
        };
      })(this)
    });
    return this.copyButton;
  };

  DatamodelListViewMask.prototype.getSaveButton = function() {
    if (this._version === "CURRENT") {
      return;
    }
    return this.saveButton = new CUI.Button({
      disabled: true,
      primary: true,
      onClick: (function(_this) {
        return function(ev) {
          _this.saveButton.disable();
          ez5.splash.show('datamodel.list.view.wait.save_in_progress');
          return CUI.setTimeout({
            ms: 0,
            call: function() {
              return _this.maskEditor.save(ev).done(function() {
                return _this.datamodel.copyToStore().always(function() {
                  _this.setSaveData();
                  _this.setMask(_this.maskEditor.getMask().getSchema());
                  _this.showWaitBlock();
                  return CUI.setTimeout({
                    call: function() {
                      _this.update();
                      _this.show();
                      return ez5.splash.done('datamodel.list.view.wait.saved');
                    }
                  });
                });
              }).fail(function() {
                _this.saveButton.enable();
                return ez5.splash.hide();
              });
            }
          });
        };
      })(this),
      text: $$("base.save")
    });
  };

  return DatamodelListViewMask;

})(DatamodelListView);
// Generated by CoffeeScript 1.12.7
var Datamodel, DatamodelLoadSchemaException,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function Datamodel() {
    this.showSpinner = bind(this.showSpinner, this);
    this.loadSchemaFromCSV = bind(this.loadSchemaFromCSV, this);
    return Datamodel.__super__.constructor.apply(this, arguments);
  }

  Datamodel.label = function() {
    return "admin.menu.datamodel_masks";
  };

  Datamodel.group = function() {
    return "zzb_administration";
  };

  Datamodel.submenu = function() {
    return "administration";
  };

  Datamodel.path = function() {
    return ["datamodel"];
  };

  Datamodel.is_allowed = function() {
    if (this.getLevel()) {
      return true;
    } else {
      return false;
    }
  };

  Datamodel.getLevel = function() {
    var level, levels, max_level, ref, ref1;
    levels = ["current", "development", "commit"];
    max_level = (ref = ez5.session.getClientDefault("database")) != null ? ref.level : void 0;
    if (max_level && indexOf.call(levels, max_level) < 0) {
      console.error("Datamodel.getLevel: Unknown level in .yml config default_client.database: ", max_level, ". Supported levels are: ", levels);
      max_level = null;
    }
    if (ez5.session.getSystemRight("root")) {
      level = "commit";
    } else {
      level = (ref1 = ez5.session.getSystemRight("datamodel")) != null ? ref1.level : void 0;
    }
    if (max_level && CUI.util.idxInArray(max_level, levels) < CUI.util.idxInArray(level, levels)) {
      level = max_level;
    }
    return level;
  };

  Datamodel.prototype.readOpts = function() {
    Datamodel.__super__.readOpts.call(this);
    return this.__level = Datamodel.getLevel();
  };

  Datamodel.prototype.unload = function() {
    var ref;
    if ((ref = this.tree) != null) {
      ref.destroy();
    }
    this.tree = null;
    this.pane.destroy();
    CUI.Events.ignore({
      instance: this
    });
    return Datamodel.__super__.unload.call(this);
  };

  Datamodel.prototype.allow_unload = function() {
    var promise, ref;
    promise = (ref = this.tree.getSelectedNode()) != null ? typeof ref.allow_deselect === "function" ? ref.allow_deselect() : void 0 : void 0;
    if (promise) {
      return promise;
    }
    return CUI.resolvedPromise();
  };

  Datamodel.prototype.empty = function() {
    this.setStatus();
    return this.pane.replace(new CUI.SimplePane({
      "class": "cui-pane--window",
      title: $$("admin.datamodel.pane.center.objecttype.title"),
      content: (function(_this) {
        return function() {
          return new CUI.EmptyLabel({
            centered: true,
            text: $$("admin.datamodel.no_objecttype_or_mask.hint")
          });
        };
      })(this)
    }), "center");
  };

  Datamodel.prototype.getLockButton = function() {
    var btn, inst, lock_id, ref, ref1, uid;
    if (ez5.version("6")) {
      this.__lock_config = (ref = ez5.session.getBaseConfig()) != null ? ref.objectstore : void 0;
    } else {
      this.__lock_config = ez5.session.getClientDefault('datamodel');
    }
    if (this.__lock_config) {
      console.info("Datamodel objectstore config:", this.__lock_config);
    }
    uid = (ref1 = this.__lock_config) != null ? ref1.uid : void 0;
    if (!uid) {
      this.lock_status = 'open';
      return;
    }
    inst = this.__lock_config.instance || ez5.session.getInstance().name;
    lock_id = this.__lock_config.server + '/' + inst + '/' + this.__lock_config.uid;
    btn = new CUI.Button({
      disabled: true,
      left: true,
      tooltip: {
        text: lock_id
      },
      activate_initial: false,
      onClick: (function(_this) {
        return function(ev) {
          switch (_this.lock_status) {
            case 'unknown':
              return _this.checkSchemaStatus();
            case 'available':
            case 'taken':
              btn.startSpinner();
              return _this.acquireLock(uid).fail(function(err) {
                var loca_key;
                loca_key = "datamodel." + (err != null ? err.code : void 0);
                if (!ez5.loca.has(loca_key)) {
                  loca_key = "datamodel.objectstore.connect.error";
                }
                CUI.problem({
                  text: $$(loca_key)
                });
                return btn.stopSpinner();
              }).done(function() {
                var action, fail_req;
                fail_req = function() {
                  return _this.releaseLock(uid).always(function() {
                    return btn.stopSpinner();
                  });
                };
                action = "open";
                if (_this.isReadOnlyObjectstore()) {
                  action = "release";
                }
                return _this.saveVersions(null, null, action).fail(fail_req).done(function() {
                  return _this.checkSchemaStatus(ev.hasModifierKey()).fail(fail_req).done(function() {
                    var finish;
                    finish = function() {
                      _this.loadList();
                      btn.stopSpinner();
                      return _this.checkLockStatus();
                    };
                    if (action === "release") {
                      return _this.releaseLock(uid).always(function() {
                        finish();
                        return CUI.alert({
                          text: $$("datamodel.objectstore.readonly", {
                            instance: inst
                          })
                        });
                      });
                    } else {
                      return finish();
                    }
                  });
                });
              });
            case 'open':
              btn.startSpinner();
              return _this.saveVersions(null, null, "release").done(function() {
                return _this.releaseLock(uid).always(function() {
                  btn.stopSpinner();
                  return _this.checkLockStatus();
                });
              });
          }
        };
      })(this)
    });
    this.__lock_btn = btn;
    this.checkLockStatus();
    return btn;
  };

  Datamodel.prototype.setLockIcon = function() {
    var icon;
    icon = (function() {
      switch (this.lock_status) {
        case 'unknown':
          return 'question';
        case 'available':
          return 'fa-lock';
        case 'taken':
          return 'fa-lock';
        case 'open':
          return 'fa-unlock-alt';
      }
    }).call(this);
    return this.__lock_btn.setIcon(icon);
  };

  Datamodel.prototype.isReadOnlyObjectstore = function() {
    var ref, ref1;
    return (ref = this.__lock_config) != null ? (ref1 = ref.instance) != null ? ref1.endsWith("-pull-only") : void 0 : void 0;
  };

  Datamodel.prototype.checkLockStatus = function() {
    var finish;
    this.__lock_btn.disable();
    this.__lock_btn.startSpinner();
    finish = (function(_this) {
      return function() {
        _this.__lock_btn.stopSpinner();
        _this.__lock_btn.enable();
        _this.setLockIcon();
        return _this.setStatus();
      };
    })(this);
    return this.lockStatus(this.__lock_config.uid).done((function(_this) {
      return function(data) {
        _this.lock_status = data.status;
        return console.debug("lock status:", _this.lock_status);
      };
    })(this)).fail((function(_this) {
      return function() {
        _this.lock_status = 'unknown';
        return CUI.problem({
          text: $$("datamodel.objectstore.connect.error")
        });
      };
    })(this)).always((function(_this) {
      return function(data) {
        if ((data != null ? data.status : void 0) === "open" && _this.isReadOnlyObjectstore()) {
          _this.releaseLock(_this.__lock_config.uid).done(function(data) {
            _this.lock_status = data.status;
            return finish();
          });
          return;
        }
        return finish();
      };
    })(this));
  };

  Datamodel.prototype.ask_unload = function() {
    var node;
    if (node = this.tree.getSelectedNode()) {
      return node.check_deselect();
    } else {
      return CUI.resolvedPromise();
    }
  };

  Datamodel.prototype.getDatamodelMenuItems = function() {
    var items, pushMasks;
    items = [
      {
        ui: "datamodel.create_new_objecttype.button",
        value: "",
        text: $$("datamodel.create_new_objecttype"),
        onClick: (function(_this) {
          return function() {
            return _this.ask_unload().done(function() {
              var node;
              node = new DatamodelListViewObjecttype({
                datamodel: _this,
                version: ez5.admin.version
              });
              return _this.tree.addNode(node).done(function() {
                return node.select();
              });
            });
          };
        })(this)
      }, {
        divider: true
      }, {
        disabled: true,
        text: $$("datamodel.plus_button.new_mask")
      }
    ];
    pushMasks = (function(_this) {
      return function(nodes) {
        var i, len, node, results;
        results = [];
        for (i = 0, len = nodes.length; i < len; i++) {
          node = nodes[i];
          if (node instanceof DatamodelListViewObjecttype) {
            items.push(node.getMenuItem());
          }
          if (node.children) {
            results.push(pushMasks(node.children));
          } else {
            results.push(void 0);
          }
        }
        return results;
      };
    })(this);
    pushMasks(this.tree.root.children);
    return items;
  };

  Datamodel.prototype.load = function() {
    var adminVersionButton, check_schema_button, csv_download_button, csv_upload_button, datamodel_download_button, datamodel_upload_button, fr, fr2, params, pd, ref, ref1, ref2, ref3, relevanceGroupButton, reset_button, svg_download_button, warnings;
    Datamodel.__super__.load.call(this);
    if ((ref = this.__level) === "commit" || ref === "development") {
      ez5.admin.version = "HEAD";
    }
    this.currentVersionButton = new CUI.Button({
      radio: "version",
      group: "version",
      tooltip: {
        text: (function(_this) {
          return function() {
            return "version:" + ez5.schema.CURRENT.version + " based on:" + ez5.schema.CURRENT.based_on_version;
          };
        })(this)
      },
      text: $$("admin.version.current"),
      active: ez5.admin.version === "CURRENT",
      onClick: (function(_this) {
        return function() {
          return _this.ask_unload().done(function() {
            ez5.admin.version = "CURRENT";
            return _this.loadList();
          });
        };
      })(this)
    });
    if ((ref1 = this.__level) === "commit" || ref1 === "development") {
      adminVersionButton = new CUI.Button({
        radio: "version",
        group: "version",
        tooltip: {
          text: (function(_this) {
            return function() {
              return "version:" + ez5.schema.HEAD.version + " based on:" + ez5.schema.HEAD.based_on_version;
            };
          })(this)
        },
        text: $$("admin.version.head"),
        active: ez5.admin.version === "HEAD",
        onClick: (function(_this) {
          return function() {
            return _this.ask_unload().done(function() {
              ez5.admin.version = "HEAD";
              return _this.loadList();
            });
          };
        })(this)
      });
    }
    if ((ref2 = this.__level) === "commit") {
      this.commitButton = new LocaButton({
        ui: "datamodel.commit.button",
        loca_key: "datamodel.button.commit",
        hidden: true,
        onClick: (function(_this) {
          return function() {
            return _this.commitConfirm();
          };
        })(this)
      });
    }
    pd = {
      format: "svg"
    };
    pd[ez5.tokenParam] = ez5.session.token;
    params = CUI.encodeUrlData(pd);
    svg_download_button = function() {
      if (!ez5.version("6") || ez5.version("6.10")) {
        return new LocaButtonHref({
          loca_key: "datamodel.button.svg_download",
          target: "_blank",
          download: !ez5.version("6"),
          href: ez5.api.getFullBase() + "/schema/user/" + ez5.admin.version + "?" + params
        });
      }
    };
    csv_download_button = new LocaButton({
      loca_key: "datamodel.button.csv_download",
      onClick: (function(_this) {
        return function() {
          return _this.saveSchemaAsCSV(ez5.admin.version, ez5.schema);
        };
      })(this)
    });
    reset_button = new LocaButton({
      loca_key: "datamodel.button.datamodel_reset",
      onClick: (function(_this) {
        return function() {
          var schema;
          schema = new Schema();
          return schema.getForStore("CURRENT").done(function(store) {
            store.schema.version = ez5.schema.CURRENT.version + 1;
            store.schema.based_on_version = ez5.schema.CURRENT.version;
            store.version = store.schema.version;
            store.mask.based_on_schema_version = store.schema.version;
            return schema.sendToServer(store).done(function() {
              return schema.load(null).done(function() {
                return _this.copyToStore().done(function() {
                  return CUI.alert({
                    text: $$("datamodel.datamodel_reset.done")
                  }).done(function() {
                    return ez5.session.handleSchemaUpdate();
                  });
                });
              });
            });
          });
        };
      })(this)
    });
    datamodel_download_button = new LocaButton({
      loca_key: "datamodel.button.datamodel_download",
      onClick: (function(_this) {
        return function(ev) {
          return new Schema().getForStore(ez5.admin.version).done(function(store) {
            if (ev.hasModifierKey()) {
              store.schema.version = 1;
              store.schema.based_on_version = 0;
            }
            return CUI.FileReader.save(ez5.session.getEasydbName() + "_Datamodel_" + ez5.admin.version + "_V" + store.schema.version + "_" + CUI.util.moment().format('YYYY-MM-DD') + ".json", JSON.stringify(store, null, "    "));
          });
        };
      })(this)
    });
    fr = new CUI.FileReader({
      onDone: (function(_this) {
        return function(frf) {
          var csv_data;
          csv_data = new CUI.CSVData();
          csv_data.parse({
            text: frf.getResult()
          }).done(function() {
            var rows;
            rows = csv_data.getRows();
            return CUI.confirm({
              text: $$("datamodel.upload_csv.confirm.set_table_id_null"),
              button_text_ok: $$("datamodel.upload_csv.buton.set_table_id_null.yes"),
              button_text_cancel: $$("datamodel.upload_csv.buton.set_table_id_null.no")
            }).done(function() {
              return _this.loadSchemaFromCSV(rows, {
                set_table_id_null: true
              });
            }).fail(function() {
              return _this.loadSchemaFromCSV(rows, {
                set_table_id_null: false
              });
            });
          });
        };
      })(this)
    });
    csv_upload_button = new CUI.FileUploadButton({
      fileUpload: fr,
      text: $$("datamodel.button.csv_upload|text"),
      icon: $$("datamodel.button.csv_upload|icon"),
      accept: ".csv,.txt,.text,text/plain,/text/csv",
      multiple: false
    });
    fr2 = new CUI.FileReader({
      onDone: (function(_this) {
        return function(frf) {
          var show_error, store;
          try {
            store = JSON.parse(frf.getResult());
          } catch (error) {
            show_error = true;
          }
          if (show_error || (store != null ? store.format_version : void 0) !== Schema.STORE_FORMAT_VERSION) {
            CUI.problem({
              text: $$("datamodel.datamodel_upload.error.wrong_format")
            });
            return;
          }
          ez5.splash.show("datamodel.datamodel_upload.working");
          if (!ez5.schema.CURRENT.based_on_version) {
            store.schema.version = 1;
            store.schema.based_on_version = void 0;
          } else {
            store.schema.based_on_version = ez5.schema.CURRENT.version;
            store.schema.version = store.schema.based_on_version + 1;
          }
          return (new Schema()).sendToServer(store).always(function() {
            return ez5.splash.done();
          }).done(function() {
            return CUI.alert({
              text: $$("datamodel.datamodel_upload.done"),
              ui: "datamodel.upload.success.alert"
            }).done(function() {
              return ez5.session.handleSchemaUpdate();
            });
          });
        };
      })(this)
    });
    datamodel_upload_button = new CUI.FileUploadButton({
      ui: "datamodel.upload.button",
      fileUpload: fr2,
      text: $$("datamodel.button.datamodel_upload|text"),
      icon: $$("datamodel.button.datamodel_upload|icon"),
      accept: ".json,application/json",
      multiple: false
    });
    relevanceGroupButton = new LocaButton({
      ui: "datamodel.sort_relevance.button",
      loca_key: "datamodel.sort.relevance",
      active: ez5.session.getPref("datamodelSortGroup") === "relevance",
      onClick: (function(_this) {
        return function() {
          var newSort;
          newSort = relevanceGroupButton.isActive() ? "alphabetical" : "relevance";
          ez5.session.savePref("datamodelSortGroup", newSort);
          relevanceGroupButton.toggle();
          return _this.loadList(newSort);
        };
      })(this)
    });
    this.__lock_btn = this.getLockButton();
    if (this.__lock_btn) {
      check_schema_button = new LocaButton({
        ui: "datamodel.list-view.footer_right.lock.button",
        loca_key: "datamodel.button.check_schema_status",
        onClick: (function(_this) {
          return function() {
            return _this.checkSchemaStatus(true).done(function() {
              return CUI.alert({
                text: $$("datamodel.check_schema_status.success_message")
              });
            });
          };
        })(this)
      });
    }
    this.tree = new CUI.ListViewTree({
      ui: "datamodel.list_view",
      cols: ["maximize"],
      selectableRows: true,
      header_center: [this.currentVersionButton, adminVersionButton],
      footer_left: [
        this.plusButton = new LocaButton({
          ui: "datamodel.list-view.footer_left.plus.button",
          loca_key: "datamodel.list.button.plus",
          icon: "plus",
          group: "plus-minus",
          "class": "btn-mini plus-button",
          menu: {
            items: (function(_this) {
              return function() {
                return _this.getDatamodelMenuItems();
              };
            })(this)
          }
        }), this.minusButton = new LocaButton({
          ui: "datamodel.list-view.footer_left.minus.button",
          loca_key: "datamodel.list.button.minus",
          icon: "minus",
          group: "plus-minus",
          "class": "btn-mini minus-button",
          onClick: (function(_this) {
            return function(ev) {
              return _this.tree.getSelectedNode()["delete"](ev);
            };
          })(this)
        })
      ],
      footer_right: [
        this.__lock_btn, new LocaButton({
          ui: "datamodel.list-view.footer_right.extra.button",
          loca_key: "datamodel.button.extra",
          menu: {
            items: (function(_this) {
              return function() {
                var csv_upload, datamodel_upload, ref3, ref4, ref5, reset;
                if (_this.commitButton) {
                  if (((ref3 = _this.tree.getSelectedNode()) != null ? (ref4 = ref3.saveButton) != null ? ref4.isEnabled() : void 0 : void 0) || _this.lock_status !== 'open' || ez5.schema.CURRENT.version === ez5.schema.HEAD.version || ((ref5 = _this.__level) !== "commit")) {
                    _this.commitButton.disable();
                  } else {
                    _this.commitButton.enable();
                  }
                }
                if (ez5.admin.version === "HEAD") {
                  csv_upload = csv_upload_button;
                  datamodel_upload = datamodel_upload_button;
                  reset = reset_button;
                  if (_this.tree.getSelectedNode() || _this.lock_status !== 'open') {
                    csv_upload.disable();
                    datamodel_upload.disable();
                    if (check_schema_button != null) {
                      check_schema_button.disable();
                    }
                    reset.disable();
                  } else {
                    csv_upload.enable();
                    if (check_schema_button != null) {
                      check_schema_button.enable();
                    }
                    datamodel_upload.enable();
                    if (ez5.schema.CURRENT.version === ez5.schema.HEAD.version) {
                      reset.disable();
                    } else {
                      reset.enable();
                    }
                  }
                  if (ez5.schema.CURRENT.tables.length > 0) {
                    csv_upload.disable();
                    datamodel_upload.disable();
                  }
                } else {
                  csv_upload = null;
                  datamodel_upload = null;
                  reset = null;
                }
                return [
                  _this.commitButton, {
                    divider: true
                  }, svg_download_button, svg_download_button() ? {
                    divider: true
                  } : void 0, csv_download_button, csv_upload, {
                    divider: true
                  }, datamodel_download_button, datamodel_upload, {
                    divider: true
                  }, reset, ez5.admin.version === "HEAD" ? check_schema_button : void 0, {
                    divider: true
                  }, relevanceGroupButton
                ];
              };
            })(this)
          }
        })
      ]
    });
    if (ez5.schema.CURRENT.version === 0) {
      CUI.alert({
        ui: "datamodel.message.no_current",
        title: $$("admin.objecttype.message.no_current.title"),
        text: $$("admin.objecttype.message.no_current")
      });
    }
    this.pane = new CUI.BorderLayout({
      "class": "ez5-event-poller",
      absolute: true,
      center: {
        "class": "ez5-datamodel-border-layout-center"
      },
      west: {
        flexHandle: {
          state_name: "admin-manager-left"
        },
        content: (function(_this) {
          return function() {
            return new CUI.SimplePane({
              "class": "cui-pane--window",
              title: $$("admin.datamodel.pane.west.title"),
              content: function() {
                var dom;
                dom = _this.tree.render();
                _this.tree.root.open();
                return dom;
              }
            });
          };
        })(this)
      }
    });
    ez5.rootLayout.replace(this.pane, "center");
    if (warnings = (ref3 = ez5.schema.HEAD) != null ? ref3.__warnings : void 0) {
      console.debug("warnings", warnings);
      new CUI.ConfirmationChoice({
        markdown: true,
        text: $$("admin.datamodel.message.datamodel-warning", {
          messages: warnings
        }),
        title: $$("admin.datamodel.message.datamodel-warning-title"),
        choices: [
          {
            text: $$("admin.datamodel.message.datamodel-warning.ok-button")
          }, {
            text: $$("admin.datamodel.message.datamodel-warning.save-button"),
            onClick: (function(_this) {
              return function(ev) {
                var node;
                node = _this.tree.getRootChildren()[0];
                if (node) {
                  return node.select().done(function() {
                    return node.save().done(function() {
                      return node.deselect();
                    });
                  });
                }
              };
            })(this)
          }
        ]
      }).open();
    }
    return this.loadList();
  };

  Datamodel.prototype.loadSchemaFromCSV = function(rows, opts) {
    var _uk, add_table, cn, col, col_idx, col_map, col_mapping, column, current_table, dfr, dt, ex, existing_col, existing_schema, existing_tb, find_table, find_table_by_name, fk, found, head, head_schema, i, idx, is_empty_row, is_false, is_true, j, k, k2, known_types, l, l10n_delete_prefixes, l10n_keys, lang, lang_mapping, len, len1, len10, len11, len12, len13, len14, len15, len2, len3, len4, len5, len6, len7, len8, len9, m, n, next_row, o, ot, other_table, other_table_name, owned_by, owned_by_tbl, p, q, r, ref, ref1, ref10, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, row, row_idx, s, set_key, t, table_by_id, table_by_name, table_name, table_name2, table_name_stack, table_name_stack2, tables, tb, tid, tn, u, uniq_columns, v, value, w, x, y, z;
    if (opts == null) {
      opts = {};
    }
    tables = [];
    is_empty_row = (function(_this) {
      return function(row) {
        var _item, i, item, len;
        for (i = 0, len = row.length; i < len; i++) {
          _item = row[i];
          if (!_item) {
            continue;
          }
          item = _item.trim();
          if (item.startsWith("# ") || item === "#") {
            continue;
          }
          if (!CUI.util.isEmpty(item)) {
            return false;
          }
        }
        return true;
      };
    })(this);
    row_idx = 0;
    current_table = null;
    col_map = null;
    ex = (function(_this) {
      return function(msg, line) {
        if (line == null) {
          line = row_idx;
        }
        CUI.problem({
          text: (new DatamodelLoadSchemaException(line + 1, msg)).getMsg()
        });
        return CUI.rejectedPromise();
      };
    })(this);
    is_true = (function(_this) {
      return function(str) {
        return CUI.util.isTrue(str.toLowerCase());
      };
    })(this);
    is_false = (function(_this) {
      return function(str) {
        return CUI.util.isFalse(str.toLowerCase());
      };
    })(this);
    find_table = function(table_name) {
      var _table, i, len;
      for (i = 0, len = tables.length; i < len; i++) {
        _table = tables[i];
        if (_table.name === table_name) {
          return _table;
        }
      }
      return null;
    };
    col_mapping = {
      NAME: "name",
      TABLE: "table",
      ID: "column_id",
      TYPE: "type",
      NOT_NULL: "not_null",
      UNIQUE: "_unique"
    };
    known_types = [];
    ref = ez5.admin.datatypes;
    for (i = 0, len = ref.length; i < len; i++) {
      dt = ref[i];
      known_types.push(dt[0]);
    }
    lang_mapping = {};
    ref1 = ez5.session.getConfigDatabaseLanguages();
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      lang = ref1[j];
      col_mapping["DISPLAYNAME:" + lang] = lang;
      lang_mapping["DISPLAYNAME:" + lang] = lang;
    }
    while (row_idx < rows.length) {
      row = rows[row_idx];
      next_row = rows[row_idx + 1];
      if (is_empty_row(row)) {
        row_idx++;
        continue;
      }
      if (row[0].startsWith("### TABLE")) {
        current_table = {
          _displayname: {},
          _line: row_idx
        };
        row_idx++;
        continue;
      }
      if (!current_table) {
        return ex("No ### Table row found.");
      }
      if (!current_table.columns) {
        if (row[0].startsWith("### COLUMNS")) {
          col_map = {};
          for (col_idx = l = 0, len2 = next_row.length; l < len2; col_idx = ++l) {
            col = next_row[col_idx];
            cn = col.trim();
            if (cn === "") {
              continue;
            }
            if (col_mapping[cn]) {
              col_map[cn] = col_idx;
            } else {
              return ex("Unknown Column '" + (col_idx + 1) + "': " + col, row_idx + 1);
            }
          }
          if (col_map.TABLE === void 0 || col_map.NAME === void 0 || col_map.TYPE === void 0) {
            return ex("Minimum columns required: TABLE, NAME, TYPE.", row_idx + 1);
          }
          tables.push(current_table);
          current_table.columns = [];
          row_idx += 2;
          continue;
        }
        switch (row[0]) {
          case "ID":
            current_table.table_id = parseInt(row[1]) || void 0;
            if (opts.set_table_id_null) {
              current_table.table_id = void 0;
            }
            break;
          case "NAME":
            current_table.name = row[1].trim();
            current_table._name_stack = [current_table.name];
            break;
          case "POOL":
            current_table.pool_link = is_true(row[1]);
            break;
          case "HIERARCHICAL":
            current_table.is_hierarchical = is_true(row[1]);
            break;
          case "COMMENT":
            current_table.comment = row[1].trim();
            break;
          case "TAGS":
            current_table.has_tags = is_true(row[1]);
            break;
          case "ACL":
            current_table.acl_table = is_true(row[1]);
            break;
          case "SEARCH":
            current_table.in_main_search = is_true(row[1]);
            break;
          default:
            if (!col_mapping[row[0]]) {
              return ex("Unknown identifier: " + row[0]);
            }
            for (k in col_mapping) {
              v = col_mapping[k];
              if (k.startsWith("DISPLAYNAME") && k === row[0]) {
                current_table._displayname[v] = row[1].trim();
              }
            }
        }
        row_idx += 1;
        continue;
      }
      if (current_table.columns) {
        table_name_stack = row[col_map.TABLE].trim().split(/\s*>\s/);
        for (idx = m = 0, len3 = table_name_stack.length; m < len3; idx = ++m) {
          table_name = table_name_stack[idx];
          if (idx === 0) {
            continue;
          }
          if (table_name.indexOf("__") > -1) {
            return ex("Unsupported table name in nested:" + table_name);
          }
        }
        table_name = table_name_stack.join("__");
        table_name_stack2 = table_name_stack.slice(0);
        table_name_stack2.pop(0);
        table_name2 = table_name_stack2.join("__");
        add_table = (function(_this) {
          return function(owned_by) {
            var nested_col, other_table_id;
            other_table_id = row[col_map.ID] || void 0;
            if (opts.set_table_id_null) {
              other_table_id = void 0;
            }
            nested_col = {
              kind: "link",
              _displayname: {},
              other_table_name_hint: table_name,
              other_table_id: other_table_id
            };
            for (k in col_map) {
              col_idx = col_map[k];
              if (!k.startsWith("DISPLAYNAME")) {
                continue;
              }
              if (row[col_idx] !== void 0) {
                nested_col._displayname[col_mapping[k]] = row[col_idx];
              }
            }
            current_table.columns.push(nested_col);
            current_table = {
              name: table_name,
              _name_stack: table_name_stack,
              _displayname: CUI.util.copyObject(nested_col._displayname, true),
              columns: [],
              table_id: other_table_id,
              owned_by: owned_by
            };
            return tables.push(current_table);
          };
        })(this);
        if (current_table.name !== table_name) {
          if (table_name_stack.length > current_table._name_stack.length + 1) {
            return ex("Table name mismatch: " + table_name + ".");
          }
          if (table_name_stack.length === current_table._name_stack.length + 1) {
            if (current_table.name !== table_name2) {
              return ex("Table name mismatch: " + table_name + ".");
            }
            if (find_table(table_name)) {
              return ex("Table already existing: " + table_name + ".");
            }
            add_table({
              other_table_id: current_table.table_id,
              other_table_name_hint: current_table.name
            });
            row_idx += 1;
            continue;
          }
          for (idx = n = 0, len4 = table_name_stack2.length; n < len4; idx = ++n) {
            tn = table_name_stack2[idx];
            if (current_table._name_stack[idx] !== tn) {
              return ex("Table name mismatch: " + table_name + ".");
            }
          }
          if (!find_table(table_name)) {
            if (!find_table(table_name2)) {
              return ex("Table name mismatch: " + table_name + ".");
            }
            if (table_name_stack.length > 1) {
              owned_by_tbl = find_table(table_name_stack.slice(0, table_name_stack.length - 1).join("__"));
              if (!owned_by_tbl) {
                return ex("Table name mismatch: " + table_name + ".");
              }
              owned_by = {
                other_table_id: owned_by_tbl.table_id,
                other_table_name_hint: owned_by_tbl.name
              };
            } else {
              owned_by = null;
            }
            current_table = find_table(table_name2);
            add_table(owned_by);
            row_idx += 1;
            continue;
          }
          current_table = find_table(table_name);
        }
        column = {
          _displayname: {}
        };
        for (k in col_map) {
          col_idx = col_map[k];
          if (CUI.util.isNull(row[col_idx])) {
            continue;
          }
          k2 = col_mapping[k];
          value = row[col_idx].trim();
          if (col_idx === void 0) {
            continue;
          }
          switch (k) {
            case "NAME":
              column[k2] = value;
              break;
            case "ID":
              column[k2] = parseInt(value);
              if (!column[k2] > 0 || opts.set_table_id_null) {
                delete column[k2];
              }
              break;
            case "NOT_NULL":
              if (is_true(value)) {
                column[k2] = true;
              } else if (is_false(value)) {
                column[k2] = false;
              }
              break;
            case "UNIQUE":
              if (is_true(value)) {
                column[k2] = true;
              } else if ((ref2 = value.toLowerCase()) === "a" || ref2 === "b" || ref2 === "c") {
                column[k2] = value.toLowerCase();
              }
              break;
            case "TABLE":
              break;
            case "TYPE":
              column[k2] = value;
              column.kind = "column";
              if (value.startsWith("custom:")) {

              } else if (value.startsWith("link:")) {

              } else if (indexOf.call(known_types, value) < 0) {
                ex("Column type '" + value + "' unknown. Valid types are: " + known_types.join(", "));
              }
              break;
            default:
              column._displayname[k2] = value;
          }
        }
        if (!((ref3 = column.name) != null ? ref3.length : void 0) || !column.type) {
          return ex("Minimum columns required: NAME, TYPE.");
        }
        column._line = row_idx;
        current_table.columns.push(column);
        row_idx += 1;
        continue;
      }
      return ex("Extra lines detected:" + row.join(";"));
    }
    find_table_by_name = (function(_this) {
      return function(tn) {
        var len5, o, ref4, tb;
        ref4 = ez5.schema.HEAD.tables;
        for (o = 0, len5 = ref4.length; o < len5; o++) {
          tb = ref4[o];
          if (tb.name === tn) {
            return tb;
          }
        }
        return null;
      };
    })(this);
    table_by_name = {};
    table_by_id = {};
    l10n_delete_prefixes = [];
    for (o = 0, len5 = tables.length; o < len5; o++) {
      tb = tables[o];
      if (!tb.name) {
        return ex("Table definition needs a name:", tb._line);
      }
      if (table_by_name[tb.name]) {
        return ex("Duplicate table definition for: " + tb.name, tb._line);
      }
      if (!tb.table_id) {
        if (find_table_by_name(tb.name)) {
          return ex("Unable to update existing table '" + tb.name + "' without table id.", tb._line);
        }
      } else {
        table_by_id[tb.table_id] = tb;
        if (!ez5.schema.HEAD._table_by_id[tb.table_id]) {
          return ex("Unable to find existing table id '" + tb.table_id + "'.", tb._line);
        }
      }
      table_by_name[tb.name] = tb;
      tb.foreign_keys = [];
      tb.unique_keys = [];
    }
    existing_schema = {
      tables: []
    };
    head_schema = CUI.util.copyObject(ez5.schema.HEAD, true);
    for (p = 0, len6 = head_schema.length; p < len6; p++) {
      ot = head_schema[p];
      if (table_by_id[ot.table_id]) {
        continue;
      }
      existing_schema.tables.push(ot);
      table_by_name[ot.name] = ot;
      ref4 = ez5.admin.get_dependent_table_ids(ot.table_id);
      for (q = 0, len7 = ref4.length; q < len7; q++) {
        tid = ref4[q];
        existing_schema.tables.push(head_schema._table_by_id[tid]);
      }
    }
    ez5.schema.clean_schema(existing_schema);
    for (r = 0, len8 = tables.length; r < len8; r++) {
      tb = tables[r];
      l10n_delete_prefixes.push("schema." + tb.name + ".");
      if (tb.table_id) {
        existing_tb = ez5.schema.HEAD._table_by_id[tb.table_id];
        if (existing_tb.name !== tb.name) {
          l10n_delete_prefixes.push("schema." + existing_tb.name + ".");
        }
      } else {
        existing_tb = ez5.schema.HEAD._table_by_name[tb.name];
        if (existing_tb) {
          return ex("Unable to update existing table '" + tb.name + "' without table id. Expected: '" + existing_tb.table_id + "'", tb._line);
        }
      }
      if (existing_tb) {
        if (existing_tb.owned_by) {
          return ex("Unable to update existing nested table '" + existing_tb.name + "'.'", tb._line);
        }
        ref5 = ["comment", "pool_link", "acl_table", "has_tags", "is_hierarchical", "in_main_search"];
        for (s = 0, len9 = ref5.length; s < len9; s++) {
          k = ref5[s];
          if (tb[k] === void 0) {
            tb[k] = existing_tb[v];
          }
        }
      }
      ref6 = tb.columns;
      for (t = 0, len10 = ref6.length; t < len10; t++) {
        col = ref6[t];
        if (col.kind === "link") {
          continue;
        }
        if (col.column_id) {
          existing_col = existing_tb != null ? existing_tb._column_by_id[col.column_id] : void 0;
          if (!existing_col) {
            return ex("Unable to find column id '" + col.column_id + "'.", col._line);
          }
        } else if (existing_tb) {
          existing_col = existing_tb._column_by_name[col.name];
          if (existing_col) {
            return ex("Unable to update existing column '" + col.name + "' without column id. Expected: '" + existing_col.column_id + "'", col._line);
          }
        } else {
          existing_col = null;
        }
        if (existing_col) {
          ref7 = ["check", "length_min", "length_max"];
          for (u = 0, len11 = ref7.length; u < len11; u++) {
            k = ref7[u];
            if (existing_col[k] !== void 0) {
              col[k] = existing_col[k];
            }
          }
        }
        if (col._unique) {
          uniq_columns = [];
          if (tb.owned_by) {
            uniq_columns.push({
              auto_column_uplink: true
            });
          }
          uniq_columns.push({
            column_id: existing_col != null ? existing_col.column_id : void 0,
            column_name_hint: col.name
          });
          if (!tb.unique_keys) {
            tb.unique_keys = [];
          }
          if (col._unique === true) {
            tb.unique_keys.push({
              columns: uniq_columns
            });
          } else {
            found = false;
            ref8 = tb.unique_keys || [];
            for (w = 0, len12 = ref8.length; w < len12; w++) {
              _uk = ref8[w];
              if (_uk.group === col._unique) {
                _uk.columns.push(uc);
                found = true;
                break;
              }
            }
            if (!found) {
              tb.unique_keys.push({
                group: col._unique,
                columns: uniq_columns
              });
            }
          }
        }
        if (col.type.startsWith("link:")) {
          other_table_name = col.type.substr(5).trim();
          other_table = table_by_name[other_table_name];
          if (!other_table) {
            return ex("Link table '" + other_table_name + "' not found for Column", col._line);
          }
          fk = {
            on_delete: "restrict",
            on_update: "cascade",
            columns: [
              {
                column_id: existing_col != null ? existing_col.column_id : void 0,
                column_name_hint: col.name
              }
            ],
            referenced_table: {
              table_id: tb.id,
              name_hint: other_table_name,
              columns: [
                {
                  auto_column_primary_key: true
                }
              ]
            }
          };
          if (!tb.foreign_keys) {
            tb.foreign_keys = [];
          }
          tb.foreign_keys.push(fk);
          col.type = "link";
        }
      }
    }
    l10n_keys = {};
    set_key = (function(_this) {
      return function(l10n_key, value) {
        l10n_keys[l10n_key] = ez5.loca.get_user_key("HEAD", l10n_key);
        for (lang in value) {
          v = value[lang];
          if (!CUI.util.isEmpty(v != null ? v.trim() : void 0)) {
            l10n_keys[l10n_key][lang] = v;
          }
        }
      };
    })(this);
    for (x = 0, len13 = tables.length; x < len13; x++) {
      tb = tables[x];
      for (k in tb) {
        v = tb[k];
        if (k.startsWith("_displayname")) {
          set_key("schema." + tb.name + ".name", v);
        }
        if (k.startsWith("_")) {
          delete tb[k];
        }
        ref9 = tb.columns;
        for (y = 0, len14 = ref9.length; y < len14; y++) {
          col = ref9[y];
          for (k in col) {
            v = col[k];
            if (k.startsWith("_displayname")) {
              if (col.kind === "link") {
                set_key("schema." + tb.name + ".column." + col.other_table_name_hint, v);
              } else {
                set_key("schema." + tb.name + ".column." + col.name, v);
              }
            }
            if (k.startsWith("_")) {
              delete col[k];
            }
          }
        }
      }
    }
    head = {};
    ref10 = ["based_on_base_version", "based_on_version", "max_column_id", "max_table_id", "type", "version", "l10n_languages"];
    for (z = 0, len15 = ref10.length; z < len15; z++) {
      k = ref10[z];
      head[k] = ez5.schema.HEAD[k];
    }
    head.tables = existing_schema.tables;
    head.tables.push.apply(head.tables, tables);
    dfr = new CUI.Deferred();
    ez5.admin.post_schema(head).done((function(_this) {
      return function() {
        var i1, l10n_update, len16, mask_schema, missing_masks, ref11;
        missing_masks = 0;
        ref11 = ez5.schema.HEAD._objecttypes;
        for (i1 = 0, len16 = ref11.length; i1 < len16; i1++) {
          ot = ref11[i1];
          if (!ez5.mask.HEAD._masks_by_table_id[ot.table_id].length) {
            mask_schema = _this.getDefaultMask(ot.table_id);
            l10n_keys["mask." + ot.table_id + "." + mask_schema.name + ".name"] = ez5.loca.get_complete_key("datamodel.standard_mask_name");
            ez5.mask.HEAD.masks.push(mask_schema);
            missing_masks += 1;
          }
        }
        l10n_update = function() {
          var valid_prefixes;
          valid_prefixes = ez5.loca.get_valid_user_key_prefixes("HEAD");
          console.debug("valid prefixes", valid_prefixes);
          console.debug("delete prefixes", l10n_delete_prefixes);
          console.debug("save loca keys:", l10n_keys);
          return ez5.loca.update({
            valid_prefixes: valid_prefixes,
            delete_prefixes: l10n_delete_prefixes,
            realm: "HEAD",
            keys: l10n_keys
          }).done(function() {
            ez5.schema.clean_schema(ez5.schema.HEAD);
            ez5.schema.enrich_schema(ez5.schema.HEAD, "HEAD");
            ez5.schema.clean_mask_schema(ez5.mask.HEAD);
            ez5.schema.enrich_mask_schema(ez5.mask.HEAD, "HEAD");
            return _this.copyToStore().always(dfr.resolve);
          }).fail(dfr.reject);
        };
        if (missing_masks > 0) {
          mask_schema = CUI.util.copyObject(ez5.mask.HEAD, true);
          ez5.schema.clean_mask_schema(mask_schema);
          ez5.api.mask({
            api: "/HEAD",
            type: "POST",
            json_data: mask_schema
          }).fail(dfr.reject).done(function() {
            return ez5.schema.load_schema().fail(dfr.reject).done(l10n_update);
          });
        } else {
          l10n_update();
        }
      };
    })(this));
    dfr.always((function(_this) {
      return function() {
        return _this.loadList();
      };
    })(this));
    return dfr.promise();
  };

  Datamodel.prototype.saveSchemaAsCSV = function(version, _schema) {
    var add_columns, add_table, col, col_by_lang, col_header_row, csv, csv_name, get_tablename, i, idx, lang, len, ot, ref, rows, schema;
    schema = _schema[version];
    add_table = (function(_this) {
      return function(table) {
        var lang, ref, value;
        rows.push(["ID", table.table_id]);
        rows.push(["NAME", table.name]);
        rows.push(["POOL", table.pool_link]);
        rows.push(["HIERARCHICAL", table.is_hierarchical]);
        rows.push(["TAGS", table.has_tags]);
        rows.push(["ACL", table.acl_table]);
        rows.push(["SEARCH", table.in_main_search]);
        rows.push(["COMMENT", table.comment]);
        ref = ez5.loca.get_user_key(version, table._l10n_key);
        for (lang in ref) {
          value = ref[lang];
          if (CUI.util.isEmpty(value.trim())) {
            continue;
          }
          rows.push(["DISPLAYNAME:" + lang, value]);
        }
      };
    })(this);
    get_tablename = (function(_this) {
      return function(table, parents) {
        var i, last_part, len, names, parent;
        if (parents.length > 0) {
          names = [];
          last_part = function(name) {
            var sn;
            sn = name.split("__");
            return sn[sn.length - 1];
          };
          for (i = 0, len = parents.length; i < len; i++) {
            parent = parents[i];
            names.push(last_part(parent.name));
          }
          names.push(last_part(table.name));
          return names.join(" > ");
        } else {
          return table.name;
        }
      };
    })(this);
    add_columns = (function(_this) {
      return function(table, parents, level) {
        var col, col_id, i, j, lang, len, len1, nested_table, parents2, ref, ref1, results, row, type, uk, uniq, value;
        if (parents == null) {
          parents = [];
        }
        if (level == null) {
          level = 0;
        }
        ref = table.columns;
        results = [];
        for (i = 0, len = ref.length; i < len; i++) {
          col = ref[i];
          switch (col.kind) {
            case "link":
              parents2 = parents.slice(0);
              parents2.push(table);
              nested_table = schema._table_by_id[col.other_table_id];
              row = [get_tablename(nested_table, parents2), "", "", "", "", nested_table.table_id];
              rows.push(row);
              add_columns(nested_table, parents2, level + 1);
              break;
            case "column":
              switch (col.type) {
                case "link":
                  type = col.type + ":" + col._foreign_key.referenced_table.name_hint;
                  break;
                default:
                  type = col.type;
              }
              uniq = "";
              ref1 = col._unique_keys || [];
              for (j = 0, len1 = ref1.length; j < len1; j++) {
                uk = ref1[j];
                uniq = uk.group || "true";
                break;
              }
              row = [get_tablename(table, parents), col.name, type, col.not_null ? "true" : "false", uniq, col.column_id];
              rows.push(row);
              break;
            default:
              console.error("Unsupported Column Type:", col);
              continue;
          }
          results.push((function() {
            var ref2, results1;
            ref2 = ez5.loca.get_user_key(version, col._l10n_key);
            results1 = [];
            for (lang in ref2) {
              value = ref2[lang];
              if (CUI.util.isEmpty(value.trim())) {
                continue;
              }
              col_id = col_by_lang[lang];
              if (col_id === void 0) {
                col_id = Object.keys(col_by_lang).length + 6;
                col_by_lang[lang] = col_id;
              }
              results1.push(row[col_id] = value);
            }
            return results1;
          })());
        }
        return results;
      };
    })(this);
    rows = [["# SCHEMA DUMP " + ez5.session.getEasydbName() + ez5.format_date_and_time(new Date())], []];
    ref = schema._objecttypes;
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      ot = ref[idx];
      if (idx > 0) {
        rows.push([]);
        rows.push([]);
      }
      rows.push(["### TABLE " + ot.name.toLocaleUpperCase()]);
      add_table(ot);
      rows.push([]);
      rows.push([]);
      rows.push(["### COLUMNS"]);
      col_header_row = ["TABLE", "NAME", "TYPE", "NOT_NULL", "UNIQUE", "ID"];
      rows.push(col_header_row);
      col_by_lang = {};
      add_columns(ot);
      for (lang in col_by_lang) {
        col = col_by_lang[lang];
        col_header_row[col] = "DISPLAYNAME:" + lang;
      }
    }
    csv = new CUI.CSVData({
      rows: rows
    });
    csv_name = ez5.session.getEasydbName() + "_Datamodel_" + ez5.admin.version + "_V" + schema.version + "_" + CUI.util.moment().format('YYYY-MM-DD') + ".csv";
    return CUI.FileReader.save(csv_name, '\uFEFF' + csv.toText());
  };

  Datamodel.prototype.getUniqueName = function(name, objectsByName) {
    var app_count, appendix;
    appendix = "";
    app_count = 0;
    while (true) {
      if (!objectsByName[name + appendix]) {
        name = name + appendix;
        break;
      }
      appendix = "_" + (++app_count);
    }
    return name;
  };

  Datamodel.prototype.getDefaultMask = function(table_id) {
    var fieldSettings, i, len, mask_name, preferred_mask, ref, ref1, ref2, systemFieldName;
    preferred_mask = ez5.all_fields_mask_preferred.HEAD._masks_by_table_id[table_id][0];
    mask_name = ez5.schema.HEAD._table_by_id[table_id].name + "__all_fields";
    preferred_mask.name = this.getUniqueName(mask_name, ez5.mask.HEAD._mask_by_name);
    preferred_mask.is_preferred = true;
    ref = ["acl", "collections", "object_id", "owner", "publish"];
    for (i = 0, len = ref.length; i < len; i++) {
      systemFieldName = ref[i];
      fieldSettings = preferred_mask.system_fields[systemFieldName];
      if (!fieldSettings) {
        continue;
      }
      if ((ref1 = fieldSettings.edit) != null) {
        ref1.mode = "off";
      }
      if ((ref2 = fieldSettings.output) != null) {
        ref2.mode = "off";
      }
    }
    return preferred_mask;
  };

  Datamodel.prototype.setStatus = function() {
    var ref, ref1, ref2, ref3;
    if (ez5.schema.CURRENT.version === 0) {
      this.currentVersionButton.disable();
    } else {
      this.currentVersionButton.enable();
    }
    if (ez5.admin.version === "HEAD") {
      this.plusButton.show();
      this.minusButton.show();
      if ((ref = this.commitButton) != null) {
        ref.show();
      }
      if (this.lock_status !== 'open') {
        this.plusButton.disable();
        return this.minusButton.disable();
      } else {
        this.plusButton.enable();
        if (!this.tree.getSelectedNode()) {
          this.minusButton.disable();
          return (ref1 = this.__lock_btn) != null ? ref1.enable() : void 0;
        } else {
          this.minusButton.enable();
          return (ref2 = this.__lock_btn) != null ? ref2.disable() : void 0;
        }
      }
    } else {
      this.minusButton.hide();
      this.plusButton.hide();
      return (ref3 = this.commitButton) != null ? ref3.hide() : void 0;
    }
  };

  Datamodel.prototype.commitConfirm = function() {
    return this.ask_unload().done((function(_this) {
      return function() {
        return CUI.confirm({
          ui: "datamodel.commit.confirmation.alert",
          title: $$("admin.easydb.objecttype.commit.modal.title"),
          text: $$("admin.easydb.objecttype.commit.modal.text"),
          button_text_ok: $$("admin.easydb.objecttype.commit.button")
        }).done(function() {
          var ref, spinner;
          if ((ref = _this.commitButton) != null) {
            ref.disable();
          }
          spinner = CUI.spinner({
            text: $$('admin.easydb.objecttype.commit.committing')
          });
          return ez5.api.schema({
            type: 'POST',
            api: '/commit'
          }).always(function() {
            return spinner.destroy();
          }).done(function(data, status, jqXHR) {
            return _this.saveVersions(ez5.schema.HEAD.version, ez5.schema.HEAD.version, "commit").always(function() {
              return ez5.session.handleSchemaUpdate();
            });
          }).fail(function() {
            return _this.setStatus();
          });
        });
      };
    })(this));
  };

  Datamodel.prototype.__sortGroupObjectTypes = function(objectTypes, sortType) {
    var getGroupNode, objectTypesSorted, primaryObjectTypes, secondaryObjectTypes, sortAlphabetical;
    sortAlphabetical = (function(_this) {
      return function(nodeOne, nodeTwo) {
        return nodeOne.objecttype._name_localized.localeCompare(nodeTwo.objecttype._name_localized);
      };
    })(this);
    getGroupNode = (function(_this) {
      return function(title, children) {
        return new CUI.ListViewTreeNode({
          selectable: false,
          children: children,
          html: new CUI.Label({
            text: title
          })
        });
      };
    })(this);
    objectTypes = objectTypes.map((function(_this) {
      return function(objectType) {
        return new DatamodelListViewObjecttype({
          objecttype: objectType,
          datamodel: _this,
          version: ez5.admin.version
        });
      };
    })(this));
    switch (sortType) {
      case "alphabetical":
        objectTypesSorted = objectTypes.sort(sortAlphabetical);
        break;
      case "relevance":
        objectTypesSorted = [];
        primaryObjectTypes = objectTypes.filter((function(_this) {
          return function(objectType) {
            return objectType.objecttype.in_main_search;
          };
        })(this));
        primaryObjectTypes.sort(sortAlphabetical);
        objectTypesSorted.push(getGroupNode($$("datamodel.sort.relevance.primary"), primaryObjectTypes));
        secondaryObjectTypes = objectTypes.filter((function(_this) {
          return function(objectType) {
            return !objectType.objecttype.in_main_search;
          };
        })(this));
        secondaryObjectTypes.sort(sortAlphabetical);
        objectTypesSorted.push(getGroupNode($$("datamodel.sort.relevance.secondary"), secondaryObjectTypes));
        break;
      default:
        objectTypesSorted = objectTypes;
    }
    return objectTypesSorted;
  };

  Datamodel.prototype.loadList = function(sortType) {
    var i, len, ot, ots, ref, ref1;
    if (sortType == null) {
      sortType = ez5.session.getPref("datamodelSortGroup");
    }
    this.tree.removeAllRows();
    if ((ref = this.tree.getSelectedNode()) != null) {
      ref.deselect();
    }
    ots = [];
    ref1 = ez5.schema[ez5.admin.version]._objecttypes;
    for (i = 0, len = ref1.length; i < len; i++) {
      ot = ref1[i];
      if (ot._instance) {
        continue;
      }
      ots.push(ot);
    }
    this.tree.root.children = this.__sortGroupObjectTypes(ots, sortType);
    this.empty();
    return this.tree.root.update(true);
  };

  Datamodel.prototype.lockStatus = function() {
    var connect, inst;
    inst = this.__lock_config.instance || ez5.session.getInstance().name;
    connect = new CUI.XHR({
      url: this.__lock_config.server + '/status/' + inst + '/' + this.__lock_config.uid
    });
    return connect.start();
  };

  Datamodel.prototype.acquireLock = function() {
    var connect, inst;
    inst = this.__lock_config.instance || ez5.session.getInstance().name;
    connect = new CUI.XHR({
      url: this.__lock_config.server + '/acquire/' + inst + '/' + this.__lock_config.uid
    });
    return connect.start();
  };

  Datamodel.prototype.releaseLock = function() {
    var connect, inst;
    inst = this.__lock_config.instance || ez5.session.getInstance().name;
    connect = new CUI.XHR({
      url: this.__lock_config.server + '/release/' + inst + '/' + this.__lock_config.uid
    });
    return connect.start();
  };

  Datamodel.prototype.syncStore = function() {
    var current_version, dfr, head_version, inst, schema, spinner, sync_schema, url, xhr;
    dfr = new CUI.Deferred();
    inst = this.__lock_config.instance || ez5.session.getInstance().name;
    url = this.__lock_config.server + '/file/' + inst + '/' + this.__lock_config.uid;
    schema = new Schema();
    current_version = ez5.schema.CURRENT.version;
    head_version = ez5.schema.HEAD.version;
    console.debug("Syncing store...");
    console.debug("CURRENT schema version:", current_version);
    console.debug("HEAD schema version:", head_version);
    spinner = null;
    spinner = this.showSpinner(spinner, 'datamodel.check_schema_status.spinner.sync', {
      version: '...'
    });
    xhr = new CUI.XHR({
      url: url + '/'
    });
    xhr.start().fail(dfr.reject).done((function(_this) {
      return function(data) {
        var connect, deletes, file, i, len, ref;
        deletes = [];
        ref = data.files;
        for (i = 0, len = ref.length; i < len; i++) {
          file = ref[i];
          connect = new CUI.XHR({
            method: "DELETE",
            url: url + '/' + file.name
          });
          deletes.push(connect.start());
        }
        return CUI.when(deletes).fail(dfr.reject).done(sync_schema);
      };
    })(this));
    dfr.always((function(_this) {
      return function() {
        return spinner.destroy();
      };
    })(this));
    sync_schema = (function(_this) {
      return function() {
        var _versions, i, ref, version;
        _versions = [];
        for (version = i = 1, ref = ez5.schema.CURRENT.version; 1 <= ref ? i <= ref : i >= ref; version = 1 <= ref ? ++i : --i) {
          _versions.push(version);
        }
        return CUI.chunkWork.call(_this, {
          items: _versions,
          chunk_size: 1,
          call: function(items) {
            var dfr2;
            dfr2 = new CUI.Deferred();
            version = items[0];
            spinner = _this.showSpinner(spinner, 'datamodel.check_schema_status.spinner.sync', {
              version: version + " / " + ez5.schema.HEAD.version
            });
            schema.getForStore(version).fail(dfr2.reject).done(function(local_version) {
              return _this.saveFile('datamodel-' + version + '.json', local_version).done(dfr2.resolve).fail(dfr2.reject);
            });
            return dfr2.promise();
          }
        }).fail(dfr.reject).done(function() {
          spinner = _this.showSpinner(spinner, 'datamodel.check_schema_status.spinner.sync', {
            version: ez5.schema.HEAD.version + " / " + ez5.schema.HEAD.version
          });
          return _this.copyToStore().done(dfr.resolve).fail(dfr.reject);
        });
      };
    })(this);
    return dfr.promise();
  };

  Datamodel.prototype.showSpinner = function(spinner, loca_key, loca_key_attrs) {
    var txt;
    txt = $$(loca_key, loca_key_attrs);
    if (!spinner) {
      spinner = CUI.spinner({
        text: txt
      });
    } else {
      spinner.setText(txt);
    }
    return spinner;
  };

  Datamodel.prototype.promptErrorReload = function() {
    return CUI.problem({
      text: "There has been a problem synchronizing the objectstore, we recommend reloading the application.",
      button_text_ok: "Reload",
      markdown: true,
      cancel: true
    }).done((function(_this) {
      return function() {
        return document.location.reload();
      };
    })(this));
  };

  Datamodel.prototype.checkSchemaStatus = function(complete_check) {
    var ask_to_sync, commit_version, current_version, datamodels, go_reload, head_version, load_model, load_models, load_versions, master_dfr, schema, send_to_server, spinner, update_models, version, versions;
    if (complete_check == null) {
      complete_check = false;
    }
    current_version = ez5.schema.CURRENT.version;
    head_version = ez5.schema.HEAD.version;
    console.debug("CURRENT schema version:", current_version);
    console.debug("HEAD schema version:", head_version);
    spinner = null;
    schema = new Schema();
    versions = null;
    version = null;
    datamodels = {};
    master_dfr = new CUI.Deferred();
    load_versions = (function(_this) {
      return function() {
        var dfr, suggest_sync;
        dfr = new CUI.Deferred();
        suggest_sync = function() {
          return ask_to_sync("store_not_initialized").fail(dfr.reject).done(function() {
            return _this.syncStore().done(function() {
              return load_versions().done(dfr.resolve).fail(dfr.reject);
            }).fail(function() {
              _this.promptErrorReload();
              return dfr.reject();
            });
          });
        };
        _this.loadFile('versions.json', [404]).fail(function(data, status) {
          if (status === 404) {
            console.warn("Unable to load versions.json, suggesting sync.");
            return suggest_sync();
          } else {
            return dfr.reject();
          }
        }).done(function(_versions) {
          if (!_versions.instances || CUI.util.isEmpty(_versions.head) || CUI.util.isEmpty(_versions.current)) {
            console.warn("versions.json is outdated, suggesting sync.");
            suggest_sync();
            return;
          }
          versions = _versions;
          versions.local_current = current_version;
          versions.local_head = head_version;
          console.debug("Objecstore version file loaded:", versions);
          return load_models().done(dfr.resolve).fail(dfr.reject);
        });
        return dfr.promise();
      };
    })(this);
    load_model = (function(_this) {
      return function(version) {
        var dfr;
        dfr = new CUI.Deferred();
        _this.loadFile('datamodel-' + version + '.json', [404]).fail(dfr.reject).done(function(datamodel) {
          var ref;
          if ((datamodel != null ? (ref = datamodel.schema) != null ? ref.version : void 0 : void 0) !== version || (datamodel != null ? datamodel.format_version : void 0) !== Schema.STORE_FORMAT_VERSION) {
            console.error("Datamodel has the wrong format:", version, datamodel);
            dfr.reject();
          } else {
            datamodels[datamodel.schema.version] = datamodel;
            dfr.resolve();
          }
        });
        return dfr.promise();
      };
    })(this);
    commit_version = (function(_this) {
      return function(version, skipReindex) {
        var dfr, urlParams;
        spinner = _this.showSpinner(spinner, 'datamodel.check_schema_status.spinner.commit', {
          version: version
        });
        if (ez5.version("6") && skipReindex) {
          urlParams = {
            confirm: "yes",
            reindex: "skip"
          };
        } else {
          urlParams = {};
        }
        dfr = new CUI.Deferred();
        ez5.api.schema({
          type: 'POST',
          api: '/commit',
          data: urlParams
        }).done(function() {
          return _this.saveVersions(null, null, "commit").done(dfr.resolve).fail(dfr.reject);
        }).fail(function() {
          return CUI.problem({
            text: $$('datamodel.check_schema_status.problem.commit')
          }).done(dfr.reject);
        });
        return dfr.promise();
      };
    })(this);
    send_to_server = (function(_this) {
      return function(datamodel) {
        datamodel.schema.based_on_version = datamodel.schema.version - 1;
        spinner = _this.showSpinner(spinner, 'datamodel.check_schema_status.spinner.send', {
          version: datamodel.schema.version
        });
        return schema.sendToServer(datamodel);
      };
    })(this);
    go_reload = (function(_this) {
      return function() {
        spinner.destroy();
        return ez5.session.handleSchemaUpdate();
      };
    })(this);
    ask_to_sync = (function(_this) {
      return function(key) {
        return CUI.confirm({
          text: $$("datamodel.check_schema_status." + key + ".confirm"),
          button_text_ok: $$("datamodel.check_schema_status." + key + ".button.ok"),
          button_text_cancel: $$("datamodel.check_schema_status." + key + ".button.cancel")
        });
      };
    })(this);
    load_models = (function(_this) {
      return function() {
        var dfr, load_next_model;
        dfr = new CUI.Deferred();
        load_next_model = function() {
          var suggest_sync;
          spinner = _this.showSpinner(spinner, 'datamodel.check_schema_status.spinner.check_schema', {
            version: version
          });
          suggest_sync = function() {
            return ask_to_sync("store_not_in_sync").fail(dfr.reject).done(function() {
              return _this.syncStore().done(function() {
                return load_versions().done(dfr.resolve).fail(dfr.reject);
              }).fail(dfr.reject);
            });
          };
          return load_model(version).fail(function(data, status) {
            if (status !== 404) {
              CUI.problem({
                text: $$("datamodel.check_schema_status.problem.load_datamodel", {
                  version: version
                })
              }).done(dfr.reject);
              return;
            }
            console.warn("Unable to load a datamodel version " + version + " from the server, suggesting sync.");
            return suggest_sync();
          }).done(function() {
            if (version < versions.head) {
              if (versions.current > current_version) {
                version = version + 1;
                load_next_model();
              } else {
                schema.getForStore(version).fail(function() {
                  console.debug("Version: " + version + " not found locally, suggesting sync.");
                  return suggest_sync();
                }).done(function(local_schema) {
                  var i, k, len, ref;
                  ref = ["based_on_version", "based_on_base_version"];
                  for (i = 0, len = ref.length; i < len; i++) {
                    k = ref[i];
                    if (datamodels[version].schema[k] === void 0) {
                      delete local_schema.schema[k];
                    } else {
                      local_schema.schema[k] = datamodels[version].schema[k];
                    }
                  }
                  if (CUI.util.isEqual(local_schema, datamodels[version])) {
                    console.info("Schema ", version, "on the server is the same as in the objectstore!");
                    version = version + 1;
                    return load_next_model();
                  } else {
                    console.warn("Local schema and Objectstore schema are not equal.", local_schema, datamodels[version]);
                    suggest_sync();
                  }
                });
              }
              return;
            }
            if (current_version === versions.current) {
              if (versions.local_head > versions.head) {
                dfr.resolve();
                return;
              }
              schema.getForStore('HEAD').fail(dfr.reject).done(function(local_schema) {
                local_schema.schema.based_on_version = datamodels[versions.head].schema.based_on_version;
                if (CUI.util.isEqual(local_schema, datamodels[versions.head], true)) {
                  dfr.resolve();
                  return;
                } else if (local_schema.version === datamodels[versions.head].version) {
                  dfr.resolve();
                  return;
                }
                console.debug("Not equal: Local:", local_schema, "Objectstore:", datamodels[versions.head], versions);
                return CUI.confirm({
                  text: $$('datamodel.check_schema_status.confirm.reload_version', versions)
                }).fail(dfr.reject).done(function() {
                  return send_to_server(datamodels[versions.head]).fail(dfr.reject).done(function() {
                    return go_reload();
                  });
                });
              });
              return;
            }
            if (current_version > versions.current) {
              suggest_sync();
              return;
            }
            return update_models().done(dfr.resolve).fail(dfr.reject);
          });
        };
        if (complete_check) {
          version = 1;
        } else {
          version = current_version;
          if (version === 0) {
            version = 1;
          }
        }
        load_next_model();
        return dfr.promise();
      };
    })(this);
    update_models = (function(_this) {
      return function() {
        var dfr, process_next_version;
        dfr = new CUI.Deferred();
        version = head_version;
        if (head_version === current_version) {
          version = head_version + 1;
          if (version > versions.head) {
            dfr.resolve();
            return dfr.promise();
          }
        }
        process_next_version = function() {
          ez5.session.stopHandleSchemaUpdateEvent();
          if (!datamodels[version]) {
            CUI.problem({
              text: $$('datamodel.check_schema_status.problem.commit')
            });
            dfr.reject();
            return;
          }
          console.debug("processing version:", datamodels, version, datamodels[version].schema.version, datamodels[version].schema.based_on_version);
          return send_to_server(datamodels[version]).done(function() {
            if (version <= versions.current) {
              return commit_version(version, version < versions.current).fail(dfr.reject).done(function() {
                if (version < versions.head) {
                  version = version + 1;
                  return process_next_version();
                } else {
                  return go_reload();
                }
              });
            } else {
              return go_reload();
            }
          }).fail(function() {
            _this.promptErrorReload();
            return dfr.reject();
          });
        };
        CUI.confirm({
          text: $$('datamodel.check_schema_status.confirm.newer_version', versions)
        }).done(process_next_version).fail(dfr.reject);
        return dfr.promise();
      };
    })(this);
    master_dfr.always((function(_this) {
      return function() {
        return spinner != null ? spinner.destroy() : void 0;
      };
    })(this));
    if (!ez5.eventPoller.isStopped()) {
      ez5.eventPoller.stop();
      master_dfr.always((function(_this) {
        return function() {
          return ez5.eventPoller.start();
        };
      })(this));
    }
    load_versions().done(master_dfr.resolve).fail(master_dfr.reject);
    return master_dfr.promise();
  };

  Datamodel.prototype.loadFile = function(filename, no_problem_status) {
    var dfr, inst, xhr, xhr_promise;
    if (no_problem_status == null) {
      no_problem_status = [];
    }
    if (!this.__lock_btn) {
      return CUI.rejectedPromise();
    }
    dfr = new CUI.Deferred();
    inst = this.__lock_config.instance || ez5.session.getInstance().name;
    xhr = new CUI.XHR({
      url: this.__lock_config.server + '/file/' + inst + '/' + this.__lock_config.uid + '/' + filename
    });
    xhr_promise = xhr.start();
    xhr_promise.fail((function(_this) {
      return function(data, status) {
        if (indexOf.call(no_problem_status, status) >= 0) {
          return dfr.reject(data, status);
        } else {
          return CUI.problem({
            text: $$('datamodel.check_schema_status.problem.load_file', {
              filename: filename
            })
          }).done(dfr.reject);
        }
      };
    })(this));
    xhr_promise.done(dfr.resolve);
    return dfr.promise();
  };

  Datamodel.prototype.saveFile = function(filename, json_data) {
    var dfr, inst;
    if (!this.__lock_btn) {
      return CUI.resolvedPromise();
    }
    dfr = new CUI.Deferred();
    inst = this.__lock_config.instance || ez5.session.getInstance().name;
    return new CUI.XHR({
      method: 'POST',
      url: this.__lock_config.server + '/file/' + inst + '/' + this.__lock_config.uid + '/' + filename,
      json_data: json_data
    }).start().fail((function(_this) {
      return function() {
        return CUI.problem({
          text: $$('datamodel.check_schema_status.problem.save_file', {
            filename: filename
          })
        }).done(dfr.reject);
      };
    })(this)).done(dfr.resolve);
  };

  Datamodel.prototype.copyToStore = function() {
    var dfr, inst, schema;
    if (!this.__lock_btn) {
      return CUI.resolvedPromise();
    }
    inst = this.__lock_config.instance || ez5.session.getInstance().name;
    schema = new Schema();
    dfr = new CUI.Deferred();
    schema.getForStore().fail(dfr.reject).done((function(_this) {
      return function(store) {
        var head_version;
        head_version = store.schema.version;
        return _this.saveFile('datamodel-' + head_version + '.json', store).fail(dfr.reject).done(function() {
          return _this.saveVersions(ez5.schema.CURRENT.version, head_version, "save").done(dfr.resolve).fail(dfr.reject);
        });
      };
    })(this));
    return dfr.promise();
  };

  Datamodel.prototype.saveVersions = function(current, head, action) {
    var dfr, inst, save_file;
    if (!this.__lock_btn) {
      return CUI.resolvedPromise();
    }
    dfr = new CUI.Deferred();
    inst = this.__lock_config.instance || ez5.session.getInstance().name;
    save_file = (function(_this) {
      return function(versions) {
        var data, k, my_current, my_head, ref, v;
        if (current && head) {
          my_current = current;
          my_head = head;
          versions.current = current;
          versions.head = head;
        } else {
          my_current = ez5.schema.CURRENT.version;
          my_head = ez5.schema.HEAD.version;
        }
        if (!versions.instances) {
          versions.instances = {};
        }
        if (!versions.instances[inst]) {
          versions.instances[inst] = {};
        }
        data = {
          current: my_current,
          head: my_head,
          last_action: action,
          store_format_version: Schema.STORE_FORMAT_VERSION,
          frontend_version: ez5.FRONTEND_VERSION,
          user: ez5.session.user.getDisplayText()
        };
        ref = versions.instances[inst];
        for (k in ref) {
          v = ref[k];
          if (indexOf.call(Object.keys(data), k) >= 0) {
            continue;
          }
          if (k === "timestamp_commit" || k === "timestamp_open" || k === "timestamp_release" || k === "timestamp_save") {
            continue;
          }
          delete versions.instances[inst][k];
        }
        for (k in data) {
          v = data[k];
          versions.instances[inst][k] = v;
        }
        versions.instances[inst]["timestamp_" + action] = (new Date()).toISOString();
        return _this.saveFile('versions.json', versions).fail(dfr.reject).done(dfr.resolve);
      };
    })(this);
    this.loadFile('versions.json', [404]).fail((function(_this) {
      return function(data, status) {
        if (status === 404) {
          save_file({});
          return;
        }
        dfr.reject();
      };
    })(this)).done((function(_this) {
      return function(versions) {
        return save_file(versions);
      };
    })(this));
    return dfr.promise();
  };

  return Datamodel;

})(RootMenuApp);

DatamodelLoadSchemaException = (function() {
  function DatamodelLoadSchemaException(__line, __msg) {
    this.__line = __line;
    this.__msg = __msg;
    this.getMsg = bind(this.getMsg, this);
  }

  DatamodelLoadSchemaException.prototype.getMsg = function() {
    return "Line:" + this.__line + ": " + this.__msg;
  };

  return DatamodelLoadSchemaException;

})();

ez5.session_ready(function() {
  return ez5.rootMenu.registerApp(Datamodel);
});
// Generated by CoffeeScript 1.12.7
var MaskEditor,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

  function MaskEditor() {
    this.save = bind(this.save, this);
    this["delete"] = bind(this["delete"], this);
    return MaskEditor.__super__.constructor.apply(this, arguments);
  }

  MaskEditor.prototype.initOpts = function() {
    MaskEditor.__super__.initOpts.call(this);
    return this.addOpts({
      disabled: {
        mandatory: true,
        "default": false,
        check: Boolean
      },
      schema: {
        mandatory: true,
        check: "PlainObject"
      }
    });
  };

  MaskEditor.prototype.readOpts = function() {
    var ref, separator, text;
    MaskEditor.__super__.readOpts.call(this);
    this.current_mask = new MaskSchema({
      schema: this._schema,
      maskEditor: this
    });
    this.__separator_options = [];
    ref = StandardField.getSeparatorsMap();
    for (separator in ref) {
      text = ref[separator];
      this.__separator_options.push({
        text: $$("admin.mask.col.format.separator." + separator),
        value: separator
      });
    }
    return this.__custom_type_support = new CustomDataTypeDatamodelSupport();
  };

  MaskEditor.prototype.getMask = function() {
    return this.current_mask;
  };

  MaskEditor.prototype.ensureCurrentMask = function() {
    return CUI.util.assert(this.current_mask instanceof MaskSchema, "MaskEditor.render", "mask needs to be instance of MaskSchema but is " + (CUI.util.getObjectClass(this.current_mask)), {
      mask: this.current_mask
    });
  };

  MaskEditor.prototype["delete"] = function(ev) {
    var dfr;
    dfr = new CUI.Deferred();
    CUI.confirm({
      text: $$("admin.mask.remove.confirm"),
      button_primary: "cancel"
    }).done((function(_this) {
      return function() {
        dfr.notify();
        return _this.save(ev, true).done(dfr.resolve).fail(dfr.reject);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  MaskEditor.prototype.checkNestedIndex = function() {
    var actualMasks, checkSubnested, i, len, mask, newFields, ref, ref1;
    checkSubnested = function(actualNestedFields, newNestedFields, nestedType) {
      var af, i, j, len, len1, nf, ref, ref1;
      for (i = 0, len = actualNestedFields.length; i < len; i++) {
        af = actualNestedFields[i];
        if (af.kind === nestedType && (af.mask != null)) {
          for (j = 0, len1 = newNestedFields.length; j < len1; j++) {
            nf = newNestedFields[j];
            if (nf.kind === nestedType && ((ref = af.mask) != null ? ref.table_id : void 0) === ((ref1 = nf.mask) != null ? ref1.table_id : void 0)) {
              af.search.nested = nf.search.nested;
              checkSubnested(af.mask.fields, nf.mask.fields, nestedType);
              break;
            }
          }
        }
      }
    };
    newFields = (ref = this.getSaveData()) != null ? (ref1 = ref.new_mask) != null ? ref1.fields : void 0 : void 0;
    actualMasks = ez5.mask.HEAD._masks_by_table_id["" + this.current_mask.data.table_id];
    for (i = 0, len = actualMasks.length; i < len; i++) {
      mask = actualMasks[i];
      checkSubnested(mask.fields, newFields, "reverse-linked-table");
      checkSubnested(mask.fields, newFields, "linked-table");
    }
  };

  MaskEditor.prototype.getSaveData = function() {
    if (!this.current_mask) {
      return null;
    }
    return ez5.admin.save_masks({
      mask: this.current_mask,
      return_data: true,
      "delete": false
    });
  };

  MaskEditor.prototype.setDemoObject = function(object) {
    return this.__demo_object = object;
  };

  MaskEditor.prototype.getDemoResultObject = function(opts) {
    var i, idx, k, len, m, mask, promises, ref, ref1, ro, sd, v;
    if (opts == null) {
      opts = null;
    }
    ez5.schema.clean_mask_schema(ez5.mask[ez5.admin.version]);
    ez5.schema.clean_schema(ez5.schema[ez5.admin.version]);
    ez5.mask.TEMP = CUI.util.copyObject(ez5.mask[ez5.admin.version], true);
    ez5.schema.TEMP = CUI.util.copyObject(ez5.schema[ez5.admin.version], true);
    ez5.schema.enrich_schema(ez5.schema.TEMP, "TEMP");
    ez5.schema.enrich_schema(ez5.schema[ez5.admin.version], ez5.admin.version);
    ez5.schema.enrich_mask_schema(ez5.mask[ez5.admin.version], ez5.admin.version);
    ez5.loca.user_keys.TEMP = CUI.util.copyObject(ez5.loca.user_keys[ez5.admin.version], true);
    if (ez5.admin.version === 'HEAD') {
      sd = this.getSaveData();
      if (sd.new_mask.mask_id) {
        ref = ez5.mask.TEMP.masks;
        for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
          m = ref[idx];
          if (m.mask_id === sd.new_mask.mask_id) {
            ez5.mask.TEMP.masks[idx] = sd.new_mask;
            break;
          }
        }
      } else {
        ez5.mask.TEMP.masks.push(sd.new_mask);
      }
      ref1 = sd.l10n_keys;
      for (k in ref1) {
        v = ref1[k];
        ez5.loca.user_keys.TEMP[k] = v;
      }
    } else {
      sd = {
        new_mask: this.current_mask.getSchema()
      };
      ez5.schema_inst.initMaskInstances(ez5.admin.version);
      ez5.schema_inst.initPreferredMask(ez5.admin.version);
    }
    ez5.schema.enrich_mask_schema(ez5.mask.TEMP, "TEMP");
    ez5.schema_inst.initMaskInstances("TEMP");
    ez5.schema_inst.initPreferredMask("TEMP");
    mask = new Mask("TEMP", null, sd.new_mask);
    promises = [];
    ro = new ResultObjectDemo({
      mask: mask,
      version: "TEMP",
      format: "long",
      opts: {
        promises: promises
      }
    });
    if (this.__demo_object) {
      this.__demo_object._standard = ro.getStandardData(this.__demo_object);
      ro.data = this.__demo_object;
    }
    return ro;
  };

  MaskEditor.prototype.save = function(ev, del) {
    var promise;
    if (del == null) {
      del = false;
    }
    this.ensureCurrentMask();
    this.checkNestedIndex();
    promise = ez5.admin.save_masks({
      mask: this.current_mask,
      "delete": del,
      event: ev
    });
    promise.done((function(_this) {
      return function() {
        if (del) {
          return _this.current_mask = null;
        } else {
          return _this.current_mask = new MaskSchema({
            schema: ez5.mask.HEAD._mask_by_name[_this.current_mask.getData().name],
            maskEditor: _this
          });
        }
      };
    })(this));
    return promise;
  };

  MaskEditor.prototype.getNameField = function() {
    return this.__nameField;
  };

  MaskEditor.prototype.dm_form_opts = function() {
    var aclOutputOptions, board, columns, editorValue, get_enum, i, inline_opts, inline_sel, j, k, len, len1, mask, mask_opts, mask_sel, opts, ref, ref1, tb;
    get_enum = function(name, _enum) {
      var e, i, len, optionTooltip, optionTooltipKey, opts, selectTooltip, selectTooltipKey;
      opts = [];
      for (i = 0, len = _enum.length; i < len; i++) {
        e = _enum[i];
        optionTooltip = null;
        optionTooltipKey = "admin.mask.form.board." + name + "." + e + "|tooltip";
        if (ez5.loca.has(optionTooltipKey)) {
          optionTooltip = {
            text: $$(optionTooltipKey)
          };
        }
        opts.push({
          text: $$("admin.mask.form.board." + name + "." + e),
          value: e,
          tooltip: optionTooltip
        });
      }
      selectTooltip = null;
      selectTooltipKey = "admin.mask.form.board." + name + "|tooltip";
      if (ez5.loca.has(selectTooltipKey)) {
        selectTooltip = {
          text: $$(selectTooltipKey)
        };
      }
      return new CUI.Select({
        name: name,
        options: opts,
        tooltip: selectTooltip
      });
    };
    tb = this.current_mask.getTable();
    opts = {
      fields: [
        {
          type: CUI.Output,
          form: {
            label: $$("admin.mask.form.id")
          },
          name: "mask_id"
        }, {
          type: CUI.Input,
          form: {
            label: $$("admin.mask.form.name")
          },
          name: "name",
          maximize: true,
          onConstruct: (function(_this) {
            return function(__nameField) {
              _this.__nameField = __nameField;
            };
          })(this),
          onDataChanged: (function(_this) {
            return function(data) {
              return _this.current_mask.setName(data.name);
            };
          })(this),
          checkInput: (function(_this) {
            return function(value) {
              var ref, regexp, sameNameMask;
              regexp = /^[a-z][a-z0-9_-]+[a-z0-9]$/;
              if (!regexp.test(value)) {
                return false;
              }
              sameNameMask = (ref = ez5.mask.HEAD) != null ? ref._mask_by_name[value] : void 0;
              if (!!sameNameMask) {
                return (sameNameMask != null ? sameNameMask.mask_id : void 0) === _this.current_mask.data.mask_id;
              }
              return true;
            };
          })(this)
        }, {
          type: CUI.MultiInput,
          control: ez5.loca.getLanguageControlAdmin(),
          maximize: true,
          user_selectable: ez5.session.getPref("languages_user_selection"),
          form: {
            label: $$("admin.mask.form.displayname_l10n")
          },
          name: "displayname_l10n"
        }, {
          type: CUI.Input,
          textarea: true,
          name: "comment",
          maximize: true,
          form: {
            label: $$("admin.mask.form.comment")
          }
        }, {
          type: CUI.Checkbox,
          form: {
            label: $$("admin.mask.form.is_preferred")
          },
          name: "is_preferred"
        }, {
          type: CUI.Checkbox,
          form: {
            label: $$("admin.mask.form.hide_in_detail")
          },
          name: "hide_in_detail"
        }, {
          type: CUI.Checkbox,
          form: {
            label: $$("admin.mask.form.hide_in_editor")
          },
          name: "hide_in_editor"
        }, {
          type: CUI.Checkbox,
          form: {
            label: $$("admin.mask.form.hide_in_print_dialog")
          },
          name: "hide_in_print_dialog"
        }, (function(_this) {
          return function(disabled) {
            if (ez5.version("6") && tb.is_hierarchical) {
              return {
                type: CUI.Select,
                name: "standard_numbering",
                form: {
                  label: {
                    text: $$("admin.mask.form.numbering.label")
                  },
                  hint: disabled ? $$("admin.mask.form.numbering.hint.require_reverse_edit") : void 0
                },
                options: ChildNumberingColumn.numberingOptions("admin.mask.form.numbering.off"),
                disabled: disabled
              };
            }
          };
        })(this)(!tb.columns.find((function(_this) {
          return function(column) {
            return column.kind === "reverse_link" && column.is_hierarchical;
          };
        })(this))), {
          type: CUI.Select,
          form: {
            label: $$("admin.mask.form.require_comment")
          },
          name: "require_comment",
          maximize: true,
          options: (function() {
            var i, len, ref, results;
            ref = ["never", "default-disabled", "default-enabled", "always"];
            results = [];
            for (i = 0, len = ref.length; i < len; i++) {
              k = ref[i];
              results.push({
                value: k,
                text: $$("admin.mask.form.require_comment." + k)
              });
            }
            return results;
          })()
        }
      ]
    };
    board = CUI.dom.table("ez5-admin-mask-form-board-table");
    columns = [
      "", new LocaLabel({
        loca_key: "admin.mask.form.board.header.edit"
      }).DOM, new LocaLabel({
        loca_key: "admin.mask.form.board.header.output"
      }).DOM
    ];
    if (tb.is_hierarchical) {
      columns.push.apply(columns, [
        new LocaLabel({
          loca_key: "admin.mask.form.board.header.mask"
        }).DOM, new LocaLabel({
          loca_key: "admin.mask.col.inline"
        }).DOM
      ]);
    }
    CUI.dom.append(board, CUI.dom.tr_one_row.apply(this, columns));
    CUI.dom.append(board, CUI.dom.tr_one_row(new LocaLabel({
      loca_key: "admin.mask.form.board.column.object_id"
    }).DOM, get_enum("object_id_edit", ["show", "off"]), get_enum("object_id_output", ["show", "off"])));
    if (tb.is_hierarchical || tb.polyhierarchical) {
      mask_opts = [
        {
          text: $$("admin.mask.form.mask_id.same"),
          value: "SAME"
        }, {
          text: $$("admin.mask.form.mask_id.preferred"),
          value: "PREFERRED"
        }
      ];
      ref = ez5.mask[ez5.admin.version]._masks_by_table_id[tb.table_id];
      for (i = 0, len = ref.length; i < len; i++) {
        mask = ref[i];
        mask_opts.push({
          text: mask._name_localized,
          value: mask.mask_id
        });
      }
      mask_sel = new CUI.Select({
        name: "parent_mask_id",
        options: mask_opts
      });
      inline_opts = [];
      ref1 = ["standard", "text", "short"];
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        k = ref1[j];
        inline_opts.push({
          text: $$("admin.mask.form.appearance." + k),
          value: k
        });
      }
      inline_sel = new CUI.Select({
        name: "parent_inline",
        options: inline_opts
      });
      CUI.dom.append(board, CUI.dom.tr_one_row(new LocaLabel({
        loca_key: "admin.mask.form.board.column.parent"
      }).DOM, get_enum("parent_edit", ["edit", "show", "off"]), get_enum("parent_output", ["show", "off"]), mask_sel, inline_sel));
    }
    if (tb.has_tags) {
      CUI.dom.append(board, CUI.dom.tr_one_row(new LocaLabel({
        loca_key: "admin.mask.form.board.column.tags"
      }).DOM, get_enum("tags_edit", ["edit", "show", "off"]), get_enum("tags_output", ["show", "off"])));
    }
    CUI.dom.append(board, CUI.dom.tr_one_row(new LocaLabel({
      loca_key: "admin.mask.form.board.column.owner"
    }).DOM, get_enum("owner_edit", ["edit", "show", "off"]), get_enum("owner_output", ["show", "off"])));
    CUI.dom.append(board, CUI.dom.tr_one_row(new LocaLabel({
      loca_key: "admin.mask.form.board.column.publish"
    }).DOM, CUI.dom.space(), get_enum("publish_output", ["show", "off"])));
    if (tb.acl_table) {
      if (ez5.version("6")) {
        aclOutputOptions = get_enum("acl_output", ["show", "off"]);
      }
      CUI.dom.append(board, CUI.dom.tr_one_row(new LocaLabel({
        loca_key: "admin.mask.form.board.column.acl"
      }).DOM, get_enum("acl_edit", ["edit", "show", "off"]), aclOutputOptions));
    }
    if (tb.in_main_search) {
      CUI.dom.append(board, CUI.dom.tr_one_row(new LocaLabel({
        loca_key: "admin.mask.form.board.column.collections"
      }).DOM, get_enum("collections_edit", ["show", "off"]), get_enum("collections_output", ["show", "off"])));
    }
    if (tb.pool_link) {
      if (ez5.version("6") && tb.columns.some((function(_this) {
        return function(column) {
          return column.kind === "reverse_link";
        };
      })(this))) {
        editorValue = get_enum("pool_edit", ["reverse_pool_changed_never", "reverse_pool_changed_always", "reverse_pool_changed_ask"]);
      } else {
        editorValue = new LocaLabel({
          loca_key: "admin.mask.form.board.pool_edit.hint"
        }).DOM;
      }
      CUI.dom.append(board, CUI.dom.tr_one_row(new LocaLabel({
        loca_key: "admin.mask.form.board.column.pool"
      }).DOM, editorValue, get_enum("pool_output", ["show", "off"])));
    }
    if (ez5.version("6.7")) {
      CUI.dom.append(board, CUI.dom.tr_one_row(new LocaLabel({
        loca_key: "admin.mask.form.board.column.other_fields"
      }).DOM, get_enum("other_fields_edit", ["show", "off"]), get_enum("other_fields_output", ["show", "off"])));
    }
    opts.fields.push({
      form: {
        label: $$("admin.mask.form.board")
      },
      type: CUI.DataFieldProxy,
      maximize: true,
      element: board
    });
    return opts;
  };

  MaskEditor.prototype.fields = function() {
    var availableBlockWidths, ret_fields;
    availableBlockWidths = ["100%", "75%", "50%", "25%"];
    ret_fields = [
      {
        name: "field_displayname",
        th_label: "admin.mask.col.field",
        type: CUI.Output
      }, {
        name: "field_name",
        th_label: "admin.mask.col.field_name",
        type: CUI.Output
      }, {
        name: "field_displaytype",
        th_label: "admin.mask.col.type",
        type: CUI.Output
      }, {
        name: "mask_id",
        th_label: "admin.mask.col.mask",
        type: CUI.Select,
        options: (function(_this) {
          return function(dataField) {
            var data, i, len, mask, opts, ref, table_id;
            opts = [
              {
                text: $$("admin.mask.form.mask_id.preferred"),
                value: "PREFERRED"
              }
            ];
            data = dataField.getData();
            if (!data) {
              return opts;
            }
            if (data.field.kind === "link") {
              table_id = data.field.other_table_id;
              ref = ez5.mask[ez5.admin.version]._masks_by_table_id[table_id];
              for (i = 0, len = ref.length; i < len; i++) {
                mask = ref[i];
                opts.push({
                  text: mask._name_localized,
                  value: mask.mask_id
                });
              }
            }
            return opts;
          };
        })(this)
      }, {
        name: "edit_show",
        th_label: "admin.mask.col.edit_show",
        th_rotate_90: true,
        type: CUI.Checkbox,
        onDataChanged: (function(_this) {
          return function(data, field) {
            var append_only;
            if (data.edit_show && data.edit_edit) {
              field.getForm().getFieldsByName("edit_edit")[0].setValue(false);
            }
            append_only = field.getForm().getFieldsByName("edit_append_only")[0];
            if (append_only) {
              if (data.edit_show) {
                return append_only.setValue(false).disable();
              }
            }
          };
        })(this)
      }, {
        name: "edit_edit",
        th_label: "admin.mask.col.edit_edit",
        th_rotate_90: true,
        type: CUI.Checkbox,
        onDataChanged: function(data, field) {
          var append_only;
          if (data.edit_show && data.edit_edit) {
            field.getForm().getFieldsByName("edit_show")[0].setValue(false);
          }
          append_only = field.getForm().getFieldsByName("edit_append_only")[0];
          if (append_only && data.edit_edit) {
            return append_only.enable();
          }
        }
      }, {
        th_label: "admin.mask.col.edit_append_only",
        th_rotate_90: true,
        type: CUI.Checkbox,
        name: "edit_append_only"
      }, {
        th_label: "admin.mask.col.user_hint",
        th_rotate_90: true,
        type: CUI.FormPopover,
        popover: {
          size: 'xl',
          pane: {
            padded: true,
            title: $$("admin.mask.col.user_hint.popover.title")
          }
        },
        button: {
          loca_key: "admin.mask.col.user_hint.button"
        },
        fields: function() {
          var fields, ref, ref1, ref2, ref3, ref4, ref5, ref6, validPlaceholderTypes;
          fields = [
            {
              type: CUI.MultiInput,
              form: {
                label: $$("admin.mask.col.user_hint"),
                hint: $$("admin.mask.col.user_hint.editor.popup_text")
              },
              user_selectable: ez5.session.getPref("languages_user_selection"),
              name: "edit_user_hint_l10n",
              control: ez5.loca.getLanguageControlAdmin(),
              textarea: true
            }
          ];
          validPlaceholderTypes = ["string", "text", "text_oneline", "text_l10n", "text_l10n_oneline", "date", "datetime", "number", "integer.2", "double"];
          if (ez5.version("6")) {
            validPlaceholderTypes.push("link");
          }
          if (ref = (ref1 = this.getData()) != null ? (ref2 = ref1.field) != null ? (ref3 = ref2._column) != null ? ref3.type : void 0 : void 0 : void 0, indexOf.call(validPlaceholderTypes, ref) >= 0) {
            fields.push({
              type: CUI.Form,
              name: "custom_settings",
              fields: [
                {
                  type: CUI.MultiInput,
                  form: {
                    label: $$("admin.mask.col.user_placeholder"),
                    hint: $$("admin.mask.col.user_placeholder.editor.popup_text")
                  },
                  user_selectable: ez5.session.getPref("languages_user_selection"),
                  name: "edit_user_placeholder_l10n",
                  control: ez5.loca.getLanguageControlAdmin(),
                  textarea: false
                }
              ]
            });
          }
          if (((ref4 = this.getData()) != null ? (ref5 = ref4.field) != null ? (ref6 = ref5._column) != null ? ref6.type : void 0 : void 0 : void 0) === "daterange") {
            fields.push({
              type: CUI.Form,
              name: "custom_settings",
              fields: [
                {
                  type: CUI.MultiInput,
                  form: {
                    label: $$("admin.mask.col.user_placeholder_from"),
                    hint: $$("admin.mask.col.user_placeholder.editor.popup_text_from")
                  },
                  user_selectable: ez5.session.getPref("languages_user_selection"),
                  name: "edit_user_placeholder_l10n_from",
                  control: ez5.loca.getLanguageControlAdmin(),
                  textarea: false
                }, {
                  type: CUI.MultiInput,
                  form: {
                    label: $$("admin.mask.col.user_placeholder_to"),
                    hint: $$("admin.mask.col.user_placeholder.editor.popup_text_to")
                  },
                  user_selectable: ez5.session.getPref("languages_user_selection"),
                  name: "edit_user_placeholder_l10n_to",
                  control: ez5.loca.getLanguageControlAdmin(),
                  textarea: false
                }
              ]
            });
          }
          return fields;
        },
        onDataChanged: (function(_this) {
          return function(data) {
            var hasCustomPlaceholder, i, k, len, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, results, target, v;
            hasCustomPlaceholder = false;
            if ((ref = data.custom_settings) != null ? ref.edit_user_placeholder_l10n : void 0) {
              ref2 = (ref1 = data.custom_settings) != null ? ref1.edit_user_placeholder_l10n : void 0;
              for (k in ref2) {
                v = ref2[k];
                if (v === "" || (v && CUI.util.isEmpty(v.trim()))) {
                  delete data.custom_settings.edit_user_placeholder_l10n[k];
                } else {
                  hasCustomPlaceholder = true;
                }
              }
            }
            if (((ref3 = data.custom_settings) != null ? ref3.edit_user_placeholder_l10n_to : void 0) || ((ref4 = data.custom_settings) != null ? ref4.edit_user_placeholder_l10n_from : void 0)) {
              ref5 = ["from", "to"];
              for (i = 0, len = ref5.length; i < len; i++) {
                target = ref5[i];
                ref7 = (ref6 = data.custom_settings) != null ? ref6["edit_user_placeholder_l10n_" + target] : void 0;
                for (k in ref7) {
                  v = ref7[k];
                  if (v === "" || (v && CUI.util.isEmpty(v.trim()))) {
                    delete ((ref8 = data.custom_settings) != null ? ref8["edit_user_placeholder_l10n_" + target][k] : void 0);
                  } else {
                    hasCustomPlaceholder = true;
                  }
                }
              }
            }
            if (!hasCustomPlaceholder && data.custom_settings) {
              delete data.custom_settings.edit_user_placeholder_l10n;
            }
            ref9 = data.edit_user_hint_l10n;
            results = [];
            for (k in ref9) {
              v = ref9[k];
              if (k === "_comment") {
                continue;
              }
              if (v && CUI.util.isEmpty(v.trim())) {
                results.push(delete data.edit_user_hint_l10n[k]);
              } else {
                results.push(void 0);
              }
            }
            return results;
          };
        })(this),
        renderDisplayContent: (function(_this) {
          return function(df, data) {
            var button, hasData, i, k, len, ref, ref1, ref2, ref3, ref4, ref5, target, v;
            hasData = false;
            ref1 = (ref = data.custom_settings) != null ? ref.edit_user_placeholder_l10n : void 0;
            for (k in ref1) {
              v = ref1[k];
              if (v && !CUI.util.isEmpty(v.trim())) {
                hasData = true;
                break;
              }
            }
            ref2 = ["from", "to"];
            for (i = 0, len = ref2.length; i < len; i++) {
              target = ref2[i];
              if (hasData) {
                break;
              }
              ref4 = (ref3 = data.custom_settings) != null ? ref3["edit_user_placeholder_l10n_" + target] : void 0;
              for (k in ref4) {
                v = ref4[k];
                if (v && !CUI.util.isEmpty(v.trim())) {
                  hasData = true;
                  break;
                }
              }
            }
            ref5 = data.edit_user_hint_l10n;
            for (k in ref5) {
              v = ref5[k];
              if (k === "_comment") {
                continue;
              }
              if (v && !CUI.util.isEmpty(v.trim())) {
                hasData = true;
                break;
              }
            }
            button = df.getButton();
            if (hasData) {
              if (button != null) {
                button.addClass("cui-active");
              }
            } else {
              if (button != null) {
                button.removeClass("cui-active");
              }
            }
            return null;
          };
        })(this)
      }, {
        th_label: "admin.mask.col.output_detail",
        th_rotate_90: true,
        type: CUI.Checkbox,
        name: "output_detail"
      }, {
        th_label: "admin.mask.col.output_text",
        th_rotate_90: true,
        type: CUI.Checkbox,
        name: "output_text"
      }, {
        th_label: "admin.mask.col.output_table",
        th_rotate_90: true,
        type: CUI.Checkbox,
        name: "output_table"
      }, this.__getStandardField(), this.__getStandardFieldEAS(), this.__getStandardFieldGeo(), {
        th_label: "admin.mask.col.user_hint",
        th_rotate_90: true,
        type: CUI.FormPopover,
        popover: {
          pane: {
            padded: true,
            title: $$("admin.mask.col.user_hint.popover.title.hint_only")
          }
        },
        button: {
          loca_key: "admin.mask.col.user_hint.button"
        },
        fields: [
          {
            type: CUI.Output,
            text: $$("admin.mask.col.user_hint.detail.popup_text")
          }, {
            type: CUI.MultiInput,
            user_selectable: ez5.session.getPref("languages_user_selection"),
            name: "output_user_hint_l10n",
            control: ez5.loca.getLanguageControlAdmin(),
            textarea: true
          }
        ],
        onDataChanged: (function(_this) {
          return function(data) {
            var k, ref, results, v;
            ref = data.output_user_hint_l10n;
            results = [];
            for (k in ref) {
              v = ref[k];
              if (k === "_comment") {
                continue;
              }
              if (v && CUI.util.isEmpty(v.trim())) {
                results.push(delete data.output_user_hint_l10n[k]);
              } else {
                results.push(void 0);
              }
            }
            return results;
          };
        })(this),
        renderDisplayContent: (function(_this) {
          return function(df, data) {
            var button, k, ref, v;
            button = df.getButton();
            ref = data.output_user_hint_l10n;
            for (k in ref) {
              v = ref[k];
              if (k === "_comment") {
                continue;
              }
              if (v && !CUI.util.isEmpty(v.trim())) {
                if (button != null) {
                  button.addClass("cui-active");
                }
                return null;
              }
            }
            if (button != null) {
              button.removeClass("cui-active");
            }
            return null;
          };
        })(this)
      }, {
        th_label: "admin.mask.col.search_fulltext",
        th_rotate_90: true,
        type: CUI.Checkbox,
        name: "search_fulltext",
        onDataChanged: (function(_this) {
          return function(data, field) {
            var listViewEditTreeMaskRowNode, nestedNode;
            listViewEditTreeMaskRowNode = field.getForm();
            nestedNode = listViewEditTreeMaskRowNode.father;
            _this.__changeNestedFulltextSearchState(nestedNode);
          };
        })(this)
      }, {
        th_label: "admin.mask.col.search_expert",
        th_rotate_90: true,
        type: CUI.Checkbox,
        group: "expert-checkbox",
        name: "search_expert"
      }, {
        th_label: "admin.mask.col.search_facet",
        th_rotate_90: true,
        type: CUI.Checkbox,
        name: "search_facet"
      }, {
        th_label: "admin.mask.col.search_nested",
        th_rotate_90: true,
        type: CUI.Checkbox,
        name: "search_nested"
      }, this.__getSearchUserHintField(), {
        end_add_row_id: "options",
        th_label: "admin.mask.col.options",
        type: CUI.FormPopover,
        button: {
          loca_key: "admin.mask.col.options.button"
        },
        popover: {
          pane: {
            title: $$("admin.mask.col.options.popover.title"),
            "class": "ez5-mask-editor-options-popover"
          }
        },
        onClose: (function(_this) {
          return function(popover) {
            console.log(popover.getData());
            return CUI.Events.trigger({
              type: "data-changed",
              node: popover
            });
          };
        })(this),
        renderDisplayContent: (function(_this) {
          return function(df, data) {
            var blockWidth, condensed_output, div, editor_mode, format_output, i, j, len, len1, nestedSortField, nestedSortFields, ref, ref1, ref10, ref11, ref12, ref13, ref14, ref15, ref16, ref17, ref18, ref19, ref2, ref20, ref3, ref4, ref5, ref6, ref7, ref8, ref9, sort, sortField, tag, tagLabel, tagfilter, tags;
            tags = [];
            tagfilter = (ref = data.custom_settings) != null ? ref.visibility_tagfilter : void 0;
            if (!CUI.util.isEmptyObject(tagfilter)) {
              tags.push($$('admin.mask.form.visibility_tagfilter.tag'));
            }
            editor_mode = (ref1 = data.custom_settings) != null ? ref1.editor_frontend_mode : void 0;
            if (editor_mode && editor_mode !== "default") {
              tags.push($$("admin.mask.form.editor_frontend_mode." + editor_mode));
            }
            blockWidth = (ref2 = data.custom_settings) != null ? ref2.blockWidth : void 0;
            if (blockWidth && blockWidth !== availableBlockWidths[0]) {
              tags.push($$("admin.mask.form.block_width.label", {
                percentage: blockWidth
              }));
            }
            if (data.inline && data.inline !== "standard") {
              tags.push($$("admin.mask.form.tag.inline." + data.inline));
            }
            if ((ref3 = data.custom_settings) != null ? ref3["show_tags_inline"] : void 0) {
              tags.push($$("admin.mask.form.show_tags_inline"));
            }
            if ((ref4 = data.custom_settings) != null ? ref4["show_pool_inline"] : void 0) {
              tags.push($$("admin.mask.form.show_pool_inline"));
            }
            if ((ref5 = data.custom_settings) != null ? ref5["show_objecttype_inline"] : void 0) {
              tags.push($$("admin.mask.form.show_objecttype_inline"));
            }
            if ((ref6 = data.custom_settings) != null ? ref6["show_system_object_id_inline"] : void 0) {
              tags.push($$("admin.mask.form.show_system_object_id_inline"));
            }
            if ((ref7 = data.custom_settings) != null ? ref7["show_hierarchy_path_inline"] : void 0) {
              tags.push($$("admin.mask.form.show_hierarchy_path_inline"));
            }
            if ((ref8 = data.custom_settings) != null ? ref8.render_markdown : void 0) {
              tags.push($$("admin.mask.form.render_markdown"));
            }
            if ((ref9 = data.custom_settings) != null ? ref9.hide_sort : void 0) {
              tags.push($$("admin.mask.form.hide_sort"));
            }
            if ((ref10 = data.custom_settings) != null ? ref10.enable_textual_representation : void 0) {
              tags.push($$("admin.mask.form.date-range.textual_representation"));
            }
            if ((ref11 = data.custom_settings) != null ? ref11.show_in_summary : void 0) {
              tags.push($$("admin.mask.form.show_in_summary"));
            }
            if ((ref12 = data.custom_settings) != null ? ref12.use_select : void 0) {
              tags.push($$("admin.mask.form.link.use_select|text"));
            }
            if (!((ref13 = data.custom_settings) != null ? ref13.use_select : void 0) && ((ref14 = data.custom_settings) != null ? ref14.prevent_onthefly_create : void 0)) {
              tags.push($$("admin.mask.form.link.prevent_onthefly_create"));
            }
            if ((ref15 = data.field) != null ? (ref16 = ref15.inheritance) != null ? ref16.inherit : void 0 : void 0) {
              if (!data.field.inheritance.show_in_detail) {
                tags.push($$("admin.mask.form.inheritance.inherited_hide_detail"));
              } else {
                tags.push($$("admin.mask.form.inheritance.inherited"));
              }
            }
            if (data.field.kind === 'linked-table' || data.field.kind === 'reverse-linked-table') {
              nestedSortFields = data.nested_sort || [];
              nestedSortFields = nestedSortFields.filter(function(nestedSortField) {
                return nestedSortField.order && nestedSortField.field;
              });
              if (nestedSortFields.length > 0) {
                for (i = 0, len = nestedSortFields.length; i < len; i++) {
                  nestedSortField = nestedSortFields[i];
                  sort = $$("admin.mask.form.sort_first_field." + nestedSortField.order);
                  sortField = nestedSortField.field.replace("-", " ");
                  tags.push($$("admin.mask.form.sort_field.tag", {
                    type: sortField,
                    sort: sort
                  }));
                }
              }
              if (data.nested_standard_first_only) {
                tags.push($$("admin.mask.col.nested.nested_standard_first_only.tag.label"));
              }
            }
            if (data.field.kind === 'reverse-linked-table') {
              if ((ref17 = data.custom_settings) != null ? ref17.show_tags_reverse : void 0) {
                tags.push($$("admin.mask.form.show_tags_reverse"));
              }
            }
            format_output = (ref18 = data.custom_settings) != null ? ref18.format_output : void 0;
            if (format_output) {
              tags.push($$("admin.mask.form.format_output.tag." + format_output));
            }
            condensed_output = (ref19 = data.custom_settings) != null ? ref19.condensed_output : void 0;
            if (condensed_output) {
              tags.push($$("admin.mask.form.condensed_output.tag"));
            }
            if ((ref20 = data.field._column) != null ? ref20.type.match("^custom:") : void 0) {
              tags.push.apply(tags, _this.__custom_type_support.getCustomMaskOptionTags(data));
            }
            CUI.setTimeout({
              ms: 0,
              call: function() {
                var ref21;
                return (ref21 = df.getPopover()) != null ? ref21.position() : void 0;
              }
            });
            if (tags.length > 0) {
              div = CUI.dom.element("DIV", {
                "class": "ez5-tag-holder"
              });
              for (j = 0, len1 = tags.length; j < len1; j++) {
                tag = tags[j];
                tagLabel = new CUI.Label({
                  "class": "ez5-tag ez5-tag-mask-editor-option",
                  text: tag,
                  tooltip: {
                    text: tag
                  }
                });
                div.appendChild(tagLabel.DOM);
              }
              return div;
            } else {
              return null;
            }
          };
        })(this),
        fields: (function(_this) {
          return function(df) {
            var _fields, actions, data, fields, frontend_modes, group, groupFields, groups, hasFields, maskTypeExtensionsFieldsByGroup, onFieldOrderChanged, optionsServer, ref, ref1, ref10, ref11, ref12, ref13, ref14, ref15, ref16, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, searchPopupModeInNestedHierarchy, shortOption, showPreventOntheflyCreate, showUseDropdown, sortForm, sortOptionsServer, standardOption, toggleCheckbox;
            data = df.getData();
            if (!data) {
              return [];
            }
            frontend_modes = ["default", "hide", "readonly"];
            groups = {
              detail: [],
              editor: [
                {
                  name: "editor_frontend_mode",
                  data: data.custom_settings,
                  form: {
                    label: $$('admin.mask.col.editor_frontend_mode')
                  },
                  type: CUI.Select,
                  options: function() {
                    var i, k, len, results;
                    results = [];
                    for (i = 0, len = frontend_modes.length; i < len; i++) {
                      k = frontend_modes[i];
                      results.push({
                        text: $$("admin.mask.form.editor_frontend_mode." + k),
                        value: k
                      });
                    }
                    return results;
                  }
                }
              ],
              detail_editor: [],
              detail_editor_text: [
                {
                  name: "blockWidth",
                  data: data.custom_settings,
                  form: {
                    label: $$('admin.mask.col.width.label')
                  },
                  type: CUI.Select,
                  options: function() {
                    var i, len, results, width;
                    results = [];
                    for (i = 0, len = availableBlockWidths.length; i < len; i++) {
                      width = availableBlockWidths[i];
                      results.push({
                        text: width,
                        value: width
                      });
                    }
                    return results;
                  }
                }
              ],
              detail_text: [],
              text: [],
              table: [],
              search: [],
              filter: [],
              other: [],
              inheritance: []
            };
            if (data.field.kind === 'linked-table') {
              hasFields = data.field.mask.fields.length > 0;
              if (ez5.version("6") && hasFields && (data.field.mask.fields.length > 1 || data.field.mask.fields[0].kind === 'linked-table')) {
                frontend_modes.push("popup");
              }
              groups.nested = [
                {
                  type: CUI.Checkbox,
                  name: "nested_standard_first_only",
                  text: $$("admin.mask.col.nested.nested_standard_first_only.label")
                }
              ];
              sortOptionsServer = _this.__getNestedSortOptions(data.field.mask.fields);
              if (sortOptionsServer.length > 0) {
                optionsServer = sortOptionsServer.concat();
                onFieldOrderChanged = function(field, reload) {
                  var sortFieldField;
                  if (reload == null) {
                    reload = false;
                  }
                  sortFieldField = field.getForm().getFieldsByName("field")[0];
                  optionsServer = sortOptionsServer.concat();
                  if (field.getData().order) {
                    sortFieldField.enable();
                    if (field.getData().field === null) {
                      field.getData().field = optionsServer[0].value;
                    }
                  } else {
                    optionsServer.push({
                      text: $$('admin.mask.form.sort_field.none'),
                      value: null
                    });
                    field.getData().field = null;
                    sortFieldField.disable();
                  }
                  if (reload) {
                    sortFieldField.reload();
                  }
                };
                sortForm = {
                  type: CUI.DataForm,
                  name: "nested_sort",
                  maximize_horizontal: true,
                  has_add_button: true,
                  fields: [
                    {
                      name: "order",
                      form: {
                        label: $$("admin.mask.col.sort_first_field")
                      },
                      type: CUI.Select,
                      onDataInit: function(field) {
                        return onFieldOrderChanged(field);
                      },
                      onDataChanged: function(_, field) {
                        return onFieldOrderChanged(field, true);
                      },
                      options: function() {
                        var i, k, len, opts, ref;
                        opts = [
                          {
                            text: $$('admin.mask.form.sort_first_field.none'),
                            value: null
                          }
                        ];
                        ref = ['asc', 'desc'];
                        for (i = 0, len = ref.length; i < len; i++) {
                          k = ref[i];
                          opts.push({
                            text: $$('admin.mask.form.sort_first_field.' + k),
                            value: k
                          });
                        }
                        return opts;
                      }
                    }, {
                      type: CUI.Select,
                      name: "field",
                      form: {
                        label: $$("admin.mask.col.sort_first_field.type")
                      },
                      options: function() {
                        return optionsServer;
                      }
                    }
                  ]
                };
                groups.detail_editor.push(sortForm);
              }
              if ((ref = data.custom_settings) != null ? ref.condensed_output : void 0) {
                data.custom_settings.format_output = "condensed";
              }
              groups.detail_text = [
                {
                  name: "format_output",
                  data: data.custom_settings,
                  form: {
                    label: $$('admin.mask.col.format_output')
                  },
                  type: CUI.Select,
                  options: function() {
                    var i, k, len, opts, ref1;
                    opts = [
                      {
                        text: $$('admin.mask.form.format_output.none'),
                        value: null
                      }
                    ];
                    ref1 = ['condensed', 'table'];
                    for (i = 0, len = ref1.length; i < len; i++) {
                      k = ref1[i];
                      opts.push({
                        text: $$('admin.mask.form.format_output.' + k),
                        value: k
                      });
                    }
                    return opts;
                  },
                  onDataChanged: function() {
                    var ref1, ref2;
                    if ((ref1 = data.custom_settings) != null ? ref1.condensed_output : void 0) {
                      return delete ((ref2 = data.custom_settings) != null ? ref2.condensed_output : void 0);
                    }
                  }
                }
              ];
              if (data.field.mask.fields.length > 1) {
                groups.editor.push({
                  name: "show_first_empty_nested",
                  data: data.custom_settings,
                  form: {
                    label: $$("admin.mask.form.show_first_empty_nested")
                  },
                  type: CUI.Checkbox
                });
              }
            } else if (data.field.kind === "reverse-linked-table") {
              groups.nested = [
                {
                  type: CUI.Checkbox,
                  name: "nested_standard_first_only",
                  text: $$("admin.mask.col.nested.nested_standard_first_only.label")
                }, {
                  name: "format_output",
                  data: data.custom_settings,
                  form: {
                    label: $$('admin.mask.col.format_output')
                  },
                  type: CUI.Select,
                  options: [
                    {
                      text: $$('admin.mask.form.format_output.none'),
                      value: null
                    }, {
                      text: $$('admin.mask.form.format_output.table'),
                      value: 'table'
                    }
                  ]
                }, {
                  name: "hide_reverse_info",
                  data: data.custom_settings,
                  form: {
                    label: $$('admin.mask.form.hide_reverse_info')
                  },
                  type: CUI.Checkbox
                }
              ];
              if (data.field._other_table.has_tags) {
                groups.detail.push({
                  type: CUI.Checkbox,
                  name: "show_tags_reverse",
                  data: data.custom_settings,
                  form: {
                    label: $$("admin.mask.col.show_tags_reverse")
                  }
                });
              }
            } else if (((ref1 = data.field._column) != null ? ref1.type : void 0) === "link") {
              showUseDropdown = !data.field._other_table.is_hierarchical;
              showPreventOntheflyCreate = ez5.version("6") && showUseDropdown && !data.field._other_table.pool_link && !data.field._other_table.polyhierarchical;
              if (showUseDropdown) {
                if (ez5.version("6")) {
                  actions = {
                    search: function(field) {
                      var ontheflyCreate;
                      data.custom_settings.use_select = false;
                      if (showPreventOntheflyCreate) {
                        ontheflyCreate = field.getOtherField("prevent_onthefly_create");
                        ontheflyCreate.enable();
                        return ontheflyCreate.setValue(false);
                      }
                    },
                    dropdown: function(field) {
                      var ontheflyCreate;
                      data.custom_settings.use_select = true;
                      if (showPreventOntheflyCreate) {
                        ontheflyCreate = field.getOtherField("prevent_onthefly_create");
                        ontheflyCreate.disable();
                        return ontheflyCreate.setValue(true);
                      }
                    }
                  };
                  groups.editor.push({
                    type: CUI.Select,
                    name: "input_mode",
                    data: data.custom_settings,
                    form: {
                      label: $$("admin.mask.form.link.input_mode|text")
                    },
                    options: [
                      {
                        text: $$("admin.mask.form.link.input_mode|option.search"),
                        value: "search"
                      }, {
                        text: $$("admin.mask.form.link.input_mode|option.dropdown"),
                        value: "dropdown"
                      }
                    ],
                    onDataChanged: function(data, field) {
                      return actions[field.getValue()](field);
                    }
                  });
                } else {
                  groups.editor.push({
                    type: CUI.Checkbox,
                    name: "use_select",
                    data: data.custom_settings,
                    form: {
                      label: $$("admin.mask.form.link.use_select|text"),
                      hint: $$("admin.mask.form.link.use_select|hint")
                    }
                  });
                }
              }
              if (showPreventOntheflyCreate) {
                groups.editor.push({
                  type: CUI.Checkbox,
                  name: "prevent_onthefly_create",
                  data: data.custom_settings,
                  disabled: ((ref2 = data.custom_settings) != null ? ref2.input_mode : void 0) === "dropdown",
                  active: !((ref3 = data.custom_settings) != null ? ref3.prevent_onthefly_create : void 0),
                  value: false,
                  value_unchecked: true,
                  form: {
                    label: $$("admin.mask.form.link.inline_create|text"),
                    hint: $$("admin.mask.form.link.inline_create|hint")
                  }
                });
              }
              shortOption = "short";
              standardOption = "standard";
              toggleCheckbox = function(field, disallowedOptions) {
                var value;
                value = field.getForm().getData().inline;
                if (indexOf.call(disallowedOptions, value) >= 0) {
                  field.setValue(false);
                  field.disable();
                } else {
                  field.enable();
                }
              };
              groups.detail_editor_text = groups.detail_editor_text.concat([
                {
                  name: "inline",
                  form: {
                    label: $$("admin.mask.col.appearance")
                  },
                  type: CUI.Select,
                  options: function() {
                    var i, k, len, ref4, results;
                    ref4 = [standardOption, "text", shortOption];
                    results = [];
                    for (i = 0, len = ref4.length; i < len; i++) {
                      k = ref4[i];
                      results.push({
                        text: $$("admin.mask.form.appearance." + k),
                        value: k
                      });
                    }
                    return results;
                  },
                  onDataChanged: function(data, field) {
                    var _field, fieldName, fieldNames, i, len;
                    fieldNames = ["show_tags_inline", "show_pool_inline", "show_objecttype_inline", "show_system_object_id_inline", "show_hierarchy_path_inline"];
                    for (i = 0, len = fieldNames.length; i < len; i++) {
                      fieldName = fieldNames[i];
                      _field = field.getForm().getFieldsByName(fieldName)[0];
                      _field.reload();
                    }
                  }
                }, {
                  name: "show_system_object_id_inline",
                  form: {
                    label: $$("admin.mask.col.show_system_object_id_inline")
                  },
                  type: CUI.Checkbox,
                  data: data.custom_settings,
                  onRender: function(field) {
                    return toggleCheckbox(field, [shortOption, standardOption]);
                  }
                }, {
                  name: "show_objecttype_inline",
                  form: {
                    label: $$("admin.mask.col.show_objecttype_inline")
                  },
                  type: CUI.Checkbox,
                  data: data.custom_settings,
                  onRender: function(field) {
                    return toggleCheckbox(field, [shortOption, standardOption]);
                  }
                }, {
                  name: "show_pool_inline",
                  form: {
                    label: $$("admin.mask.col.show_pool_inline")
                  },
                  type: CUI.Checkbox,
                  data: data.custom_settings,
                  onRender: function(field) {
                    return toggleCheckbox(field, [shortOption, standardOption]);
                  }
                }, {
                  name: "show_tags_inline",
                  form: {
                    label: $$("admin.mask.col.show_tags_inline")
                  },
                  type: CUI.Checkbox,
                  data: data.custom_settings,
                  onRender: function(field) {
                    return toggleCheckbox(field, [shortOption]);
                  }
                }, {
                  name: "show_hierarchy_path_inline",
                  form: {
                    label: $$("admin.mask.col.show_hierarchy_path_inline")
                  },
                  type: CUI.Checkbox,
                  data: data.custom_settings,
                  onRender: function(field) {
                    return toggleCheckbox(field, [shortOption]);
                  }
                }
              ]);
            } else if ((ref4 = data.field._column) != null ? ref4.type.match("^custom:") : void 0) {
              groups.other = _this.__custom_type_support.getCustomMaskOptions(data);
            } else if (((ref5 = data.field._column) != null ? ref5.type : void 0) === "boolean") {
              if (CUI.util.isNull(data.custom_settings.boolean_show_false)) {
                data.custom_settings.boolean_show_false = true;
              }
              groups.detail.push({
                name: "boolean_show_false",
                data: data.custom_settings,
                form: {
                  label: $$('admin.mask.col.boolean_show_false')
                },
                type: CUI.Checkbox
              });
            } else {
              switch ((ref6 = data.field._column) != null ? ref6.type : void 0) {
                case "text":
                case "text_oneline":
                case "text_l10n":
                case "text_l10n_oneline":
                  groups.detail_text.push({
                    name: "render_markdown",
                    data: data.custom_settings,
                    form: {
                      label: $$('admin.mask.col.render_markdown')
                    },
                    type: CUI.Checkbox
                  });
              }
            }
            if (data.field.kind === "linked-table" || ((ref7 = data.field._column) != null ? ref7.type : void 0)) {
              groups.search.push({
                name: "hide_sort",
                data: data.custom_settings,
                form: {
                  label: $$('admin.mask.col.hide_sort')
                },
                type: CUI.Checkbox
              });
            }
            if ((ref8 = data.field._column) != null ? ref8.type : void 0) {
              maskTypeExtensionsFieldsByGroup = _this.__getMaskTypeExtensionsFields(data);
              for (group in maskTypeExtensionsFieldsByGroup) {
                _fields = maskTypeExtensionsFieldsByGroup[group];
                groups[group] = groups[group].concat(_fields);
              }
            }
            if (((ref9 = (ref10 = data.field._column) != null ? ref10.type : void 0) === "eas" || ref9 === "date" || ref9 === "daterange" || ref9 === "datetime" || ref9 === "link") || ((ref11 = data.field._column) != null ? ref11.type.match("^custom:") : void 0)) {
              groups.filter.splice(0, 0, {
                name: "hide_field_in_search_facet",
                data: data.custom_settings,
                form: {
                  label: $$('admin.mask.col.hide-field-in-search-facet')
                },
                type: CUI.Checkbox,
                disabled: !data.search_facet
              });
              if ((ref12 = (ref13 = data.field._column) != null ? ref13.type : void 0) === "date" || ref12 === "daterange") {
                groups.detail_editor.push({
                  name: "avoid_bc_conversion",
                  data: data.custom_settings,
                  form: {
                    label: $$('admin.mask.col.avoid_bc_conversion')
                  },
                  type: CUI.Checkbox
                });
              }
              if (((ref14 = data.field._column) != null ? ref14.type : void 0) === "daterange") {
                groups.detail.push({
                  name: "enable_textual_representation",
                  data: data.custom_settings,
                  form: {
                    label: $$('admin.mask.col.date-range.enable-textual-representation')
                  },
                  type: CUI.Checkbox,
                  onDataChanged: function(_, field) {
                    var showInternalDatesField;
                    showInternalDatesField = field.getForm().getFieldsByName("textual_representation_show_internal_dates")[0];
                    if (data.custom_settings.enable_textual_representation) {
                      showInternalDatesField.enable();
                    } else {
                      showInternalDatesField.disable();
                    }
                  }
                });
                if (CUI.util.isUndef(data.custom_settings.textual_representation_show_internal_dates)) {
                  data.custom_settings.textual_representation_show_internal_dates = true;
                }
                groups.detail.push({
                  name: "textual_representation_show_internal_dates",
                  data: data.custom_settings,
                  form: {
                    label: $$('admin.mask.col.date-range.textual-representation.show-internal-dates')
                  },
                  type: CUI.Checkbox,
                  disabled: !data.custom_settings.enable_textual_representation
                });
              }
            }
            if (data.field._level > 0) {
              groups.detail_editor.splice(0, 0, {
                name: "hide_label",
                data: data.custom_settings,
                form: {
                  label: $$('admin.mask.col.hide_label')
                },
                type: CUI.Checkbox
              });
              searchPopupModeInNestedHierarchy = function(current_level, node) {
                if (current_level === 0) {
                  return false;
                }
                node = node.getFather();
                if (!node) {
                  return false;
                }
                if (node.getData().custom_settings.editor_frontend_mode === "popup") {
                  return true;
                }
                return searchPopupModeInNestedHierarchy(current_level - 1, node);
              };
              if (searchPopupModeInNestedHierarchy(data.field._level, df.getForm())) {
                if (groups.nested_popup == null) {
                  groups.nested_popup = [];
                }
                groups.nested_popup.push({
                  name: "show_in_summary",
                  data: data.custom_settings,
                  form: {
                    label: $$('admin.mask.col.show_in_summary')
                  },
                  type: CUI.Checkbox
                });
              }
            }
            if (ez5.version("6") && ((data.field._column == null) || ((ref15 = data.field._column) != null ? ref15.type : void 0) !== "boolean") && !((ref16 = data.field._column) != null ? ref16._in_nested : void 0)) {
              groups.inheritance.push({
                name: "inherit",
                data: data.field.inheritance,
                form: {
                  label: $$('admin.mask.form.inheritance')
                },
                type: CUI.Checkbox
              });
              groups.inheritance.push({
                name: "show_in_detail",
                data: data.field.inheritance,
                form: {
                  label: $$('admin.mask.form.show_in_detail')
                },
                type: CUI.Checkbox
              });
            }
            fields = [];
            for (group in groups) {
              groupFields = groups[group];
              if (groupFields.length === 0) {
                continue;
              }
              fields.push({
                type: CUI.Form,
                form: {
                  label: $$("admin.mask.col.options.popover.group-" + group + ".title")
                },
                render_as_block: true,
                fields: groupFields
              });
            }
            return fields;
          };
        })(this)
      }
    ];
    return ret_fields.filter((function(_this) {
      return function(field, index) {
        if (!field) {
          return false;
        }
        if (field.end_add_row_id) {
          _this.__endAddRowIndexes[field.end_add_row_id] = index;
          delete field.end_add_row_id;
        }
        return true;
      };
    })(this));
  };

  MaskEditor.prototype.__endAddRowIndexes = {
    standard: -1,
    standard_eas: -1,
    standard_geo: -1,
    options: -1
  };

  MaskEditor.prototype.__getSearchUserHintField = function() {
    if (ez5.version("6.22")) {
      return {
        th_label: "admin.mask.col.user_hint",
        th_rotate_90: true,
        type: CUI.FormPopover,
        popover: {
          pane: {
            padded: true,
            title: $$("admin.mask.col.user_hint.popover.title.hint_only")
          }
        },
        button: {
          loca_key: "admin.mask.col.user_hint.button"
        },
        fields: [
          {
            type: CUI.Output,
            text: $$("admin.mask.col.user_hint.search.popup_text")
          }, {
            type: CUI.MultiInput,
            user_selectable: ez5.session.getPref("languages_user_selection"),
            name: "search_user_hint_l10n",
            control: ez5.loca.getLanguageControlAdmin(),
            textarea: true
          }
        ],
        onDataChanged: (function(_this) {
          return function(data) {
            var k, ref, results, v;
            ref = data.search_user_hint_l10n;
            results = [];
            for (k in ref) {
              v = ref[k];
              if (k === "_comment") {
                continue;
              }
              if (v && CUI.util.isEmpty(v.trim())) {
                results.push(delete data.search_user_hint_l10n[k]);
              } else {
                results.push(void 0);
              }
            }
            return results;
          };
        })(this),
        renderDisplayContent: (function(_this) {
          return function(df, data) {
            var button, k, ref, v;
            button = df.getButton();
            ref = data.search_user_hint_l10n;
            for (k in ref) {
              v = ref[k];
              if (k === "_comment") {
                continue;
              }
              if (v && !CUI.util.isEmpty(v.trim())) {
                if (button != null) {
                  button.addClass("cui-active");
                }
                return null;
              }
            }
            if (button != null) {
              button.removeClass("cui-active");
            }
            return null;
          };
        })(this)
      };
    }
    return null;
  };

  MaskEditor.prototype.__getStandardFieldEAS = function() {
    return this.__getStandardField("eas");
  };

  MaskEditor.prototype.__getStandardFieldGeo = function() {
    if (ez5.version("6.7")) {
      return this.__getStandardField("geo");
    } else {
      return null;
    }
  };

  MaskEditor.prototype.__getStandardField = function(mode) {
    var end_add_row_id, field, fields, th_label;
    if (mode == null) {
      mode = "text";
    }
    switch (mode) {
      case "eas":
        end_add_row_id = "standard_eas";
        th_label = "admin.mask.col.standard_eas";
        fields = [
          {
            form: {
              label: $$("admin.mask.col.format.container_asset")
            },
            type: CUI.Options,
            name: "standard_eas_order",
            horizontal: false,
            radio: true,
            options: [
              {
                value: false,
                text: $$("admin.mask.col.format.standard.dont_show")
              }, {
                value: 1,
                text: $$("admin.mask.col.format.standard.show")
              }
            ]
          }
        ];
        break;
      case "text":
        end_add_row_id = "standard";
        th_label = "admin.mask.col.standard";
        fields = (function(_this) {
          return function(df) {
            var data, ref, ret;
            data = df.getData();
            if (!data) {
              return [];
            }
            if (((ref = data.field) != null ? ref.kind : void 0) === 'linked-table') {
              ret = [];
              if (ez5.version("6")) {
                ret.push({
                  type: CUI.Select,
                  name: "format",
                  form: {
                    label: $$("admin.mask.col.nested.format.label")
                  },
                  options: _this.__separator_options
                });
                ret.push({
                  type: CUI.Select,
                  name: "format_inner",
                  form: {
                    label: $$("admin.mask.col.nested.format_inner.label")
                  },
                  options: _this.__separator_options
                });
              }
              return ret;
            } else {
              ret = [
                {
                  form: {
                    label: $$("admin.mask.col.format.container")
                  },
                  type: CUI.Options,
                  name: "standard_order",
                  horizontal: false,
                  radio: true,
                  options: [
                    {
                      value: false,
                      text: $$("admin.mask.col.format.standard.dont_show")
                    }, {
                      value: 1,
                      text: $$("admin.mask.col.format.standard.title")
                    }, {
                      value: 2,
                      text: $$("admin.mask.col.format.standard.subtitle")
                    }, {
                      value: 3,
                      text: $$("admin.mask.col.format.standard.description")
                    }
                  ]
                }, ez5.version("6.7") ? {
                  name: "stop_if_set",
                  form: {
                    label: $$("admin.mask.col.format.stop_if_set")
                  },
                  type: CUI.Checkbox
                } : void 0, {
                  name: "standard_format",
                  type: CUI.Select,
                  form: {
                    label: $$("admin.mask.col.format.separator")
                  },
                  options: _this.__separator_options
                }
              ];
              return ret;
            }
          };
        })(this);
        break;
      case "geo":
        end_add_row_id = "standard_geo";
        th_label = "admin.mask.col.standard_geo";
        fields = [
          {
            form: {
              label: $$("admin.mask.col.format.container_geo")
            },
            type: CUI.Options,
            name: "standard_geo_order",
            horizontal: false,
            radio: true,
            options: [
              {
                value: false,
                text: $$("admin.mask.col.format.standard.dont_show")
              }, {
                value: 1,
                text: $$("admin.mask.col.format.standard.show")
              }
            ]
          }
        ];
    }
    field = {
      end_add_row_id: end_add_row_id,
      th_label: th_label,
      th_rotate_90: true,
      type: CUI.FormPopover,
      popover: {
        pane: {
          title: $$(th_label)
        }
      },
      fields: fields,
      renderDisplayButton: (function(_this) {
        return function(df, data) {
          var ref;
          switch (mode) {
            case "eas":
              if (data != null ? data.standard_eas_order : void 0) {
                return $$("admin.datamodel.standard_eas." + data.standard_eas_order);
              } else {
                return $$("admin.datamodel.standard_eas.empty");
              }
              break;
            case "text":
              if (ez5.version("6")) {
                _this.__updateAllLinkedTableStandard();
              }
              if ((data != null ? (ref = data.field) != null ? ref.kind : void 0 : void 0) === 'linked-table') {
                if (ez5.version("6")) {
                  return new CUI.Icon({
                    icon: CUI.Icon.icon_map.settings
                  });
                } else {
                  return false;
                }
              } else if (data != null ? data.standard_order : void 0) {
                return $$("admin.datamodel.standard." + data.standard_order);
              } else {
                return $$("admin.datamodel.standard.empty");
              }
              break;
            case "geo":
              if (data != null ? data.standard_geo_order : void 0) {
                return $$("admin.datamodel.standard_geo." + data.standard_geo_order);
              } else {
                return $$("admin.datamodel.standard_eas.empty");
              }
          }
        };
      })(this)
    };
    return field;
  };

  MaskEditor.prototype.init_mask_table = function() {
    if (ez5.admin.version === "HEAD") {
      this.minusButton = new LocaButton({
        icon: "minus",
        loca_key: "mask.editor.fields.button.minus",
        group: "plusminus",
        disabled: this._disabled,
        onClick: (function(_this) {
          return function() {
            var node;
            node = _this.mask_table.getSelectedNode();
            node.remove();
            return _this.update_mask_form();
          };
        })(this)
      });
      this.plusButton = new LocaButton({
        icon: "plus",
        loca_key: "mask.editor.fields.button.plus",
        group: "plusminus",
        disabled: this._disabled,
        menu: {
          items: (function(_this) {
            return function() {
              return MaskSplitter.getMenuItems(_this);
            };
          })(this)
        }
      });
      this.moveToBottomButton = new CUI.Button({
        icon: $$("tool.mask_editor.move_to_bottom|icon"),
        tooltip: {
          text: $$("tool.mask_editor.move_to_bottom|text")
        },
        group: "move_row",
        disabled: true,
        onClick: (function(_this) {
          return function(ev) {
            return _this.__moveRowToBottom(_this.mask_table.getSelectedNode(), ev);
          };
        })(this)
      });
      this.moveToTopButton = new CUI.Button({
        icon: $$("tool.mask_editor.move_to_top|icon"),
        tooltip: {
          text: $$("tool.mask_editor.move_to_top|text")
        },
        group: "move_row",
        disabled: true,
        onClick: (function(_this) {
          return function(ev) {
            return _this.__moveRowToTop(_this.mask_table.getSelectedNode(), ev);
          };
        })(this)
      });
      this.moveDownButton = new CUI.Button({
        icon: $$("tool.mask_editor.move_down|icon"),
        tooltip: {
          text: $$("tool.mask_editor.move_down|text")
        },
        group: "move_row",
        disabled: true,
        onClick: (function(_this) {
          return function() {
            return _this.__moveRow(_this.mask_table.getSelectedNode(), true);
          };
        })(this)
      });
      this.moveUpButton = new CUI.Button({
        icon: $$("tool.mask_editor.move_up|icon"),
        tooltip: {
          text: $$("tool.mask_editor.move_up|text")
        },
        group: "move_row",
        disabled: true,
        onClick: (function(_this) {
          return function() {
            return _this.__moveRow(_this.mask_table.getSelectedNode(), false);
          };
        })(this)
      });
    }
    this.mask_table = new ListViewEditTree({
      absolute: true,
      "class": 'cui-lv--has-datafields',
      extra_header: [
        null, null, null, {
          th_label: "admin.mask.col.linked_object"
        }, {
          th_label: "admin.mask.col.editor",
          th_colspan: 4
        }, {
          th_label: "admin.mask.col.output",
          th_colspan: ez5.version("6.7") ? 7 : 6
        }, {
          th_label: "admin.mask.col.search",
          th_colspan: ez5.version("6.22") ? 5 : 4
        }
      ],
      fields: this.fields(),
      fixedCols: 0,
      rowMove: true,
      selectableRows: true,
      onSelect: (function(_this) {
        return function() {
          return _this.update_mask_form();
        };
      })(this),
      onDeselect: (function(_this) {
        return function() {
          return _this.update_mask_form();
        };
      })(this),
      onOpen: (function(_this) {
        return function() {
          return _this.update_mask_form();
        };
      })(this),
      footer_left: [this.plusButton, this.minusButton, this.moveToTopButton, this.moveUpButton, this.moveDownButton, this.moveToBottomButton],
      end_add_row: (function(_this) {
        return function(row) {
          return _this.end_add_row(row);
        };
      })(this)
    });
    CUI.Events.listen({
      type: "toolbox",
      node: this.mask_table,
      call: (function(_this) {
        return function(event, info) {
          var rowSelectableElement, selectedNode;
          rowSelectableElement = CUI.dom.parents(event.getTarget(), ".cui-list-view-row-selectable")[0];
          if (!rowSelectableElement) {
            return;
          }
          selectedNode = CUI.dom.data(rowSelectableElement, "listViewRow");
          if (!_this.__isRowMovableWithButtons(selectedNode)) {
            return;
          }
          selectedNode.select().done(function() {
            var moveDownAvailable, moveUpAvailable;
            moveUpAvailable = _this.__getNextRowIndexForMove(selectedNode, false);
            moveDownAvailable = _this.__getNextRowIndexForMove(selectedNode, true);
            info.tools.push(new ToolboxTool({
              name: "mask_editor.move_to_top",
              group: "mask_editor_tools",
              disabled: !moveUpAvailable,
              run: function(ev) {
                return _this.__moveRowToTop(selectedNode, ev);
              }
            }));
            info.tools.push(new ToolboxTool({
              name: "mask_editor.move_up",
              group: "mask_editor_tools",
              disabled: !moveUpAvailable,
              run: function() {
                return _this.__moveRow(selectedNode, false);
              }
            }));
            info.tools.push(new ToolboxTool({
              name: "mask_editor.move_down",
              group: "mask_editor_tools",
              disabled: !moveDownAvailable,
              run: function() {
                return _this.__moveRow(selectedNode, true);
              }
            }));
            return info.tools.push(new ToolboxTool({
              name: "mask_editor.move_to_bottom",
              group: "mask_editor_tools",
              disabled: !moveDownAvailable,
              run: function(ev) {
                return _this.__moveRowToBottom(selectedNode, ev);
              }
            }));
          });
        };
      })(this)
    });
    return this.mask_table;
  };

  MaskEditor.prototype.__moveRowToBottom = function(listViewRow, ev) {
    var children, lastIdx, lastNode;
    if (ev == null) {
      ev = null;
    }
    children = listViewRow.father.children;
    lastNode = children[children.length - 1];
    if (lastNode.children) {
      lastNode.close();
    }
    lastIdx = lastNode.getRowIdx();
    this.mask_table.moveRow(listViewRow.getRowIdx(), lastIdx, true);
    if (!(ev != null ? ev.hasModifierKey() : void 0)) {
      listViewRow.scrollIntoView();
    }
    this.update_mask_form();
  };

  MaskEditor.prototype.__moveRowToTop = function(listViewRow, ev) {
    var children, topIndex;
    if (ev == null) {
      ev = null;
    }
    children = listViewRow.father.children;
    topIndex = children[0].getRowIdx();
    this.mask_table.moveRow(listViewRow.getRowIdx(), topIndex, false);
    if (!(ev != null ? ev.hasModifierKey() : void 0)) {
      listViewRow.scrollIntoView();
    }
    this.update_mask_form();
  };

  MaskEditor.prototype.__moveRow = function(listViewRow, after) {
    var nextRowIndex;
    if (listViewRow.isOpen()) {
      listViewRow.close();
    }
    nextRowIndex = this.__getNextRowIndexForMove(listViewRow, after);
    if (!nextRowIndex) {
      return;
    }
    this.mask_table.moveRow(listViewRow.getRowIdx(), nextRowIndex, after);
    this.update_mask_form();
  };

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

  MaskEditor.prototype.__isRowMovableWithButtons = function(node) {
    return node && node.isMovable() && !(node instanceof MaskSplitter);
  };

  MaskEditor.prototype.addNode = function(row) {
    return this.mask_table.addNode(row);
  };

  MaskEditor.prototype.end_add_row = function(row) {
    var customDataType, disable, hide, options, ref, ref1, ref2, standard, standard_eas, standard_geo;
    hide = [];
    disable = [];
    ref = this.__endAddRowIndexes, standard = ref.standard, standard_eas = ref.standard_eas, standard_geo = ref.standard_geo, options = ref.options;
    switch (row.type) {
      case "linked-table":
        hide.push("mask_id", standard_eas, standard_geo);
        if (!ez5.version("6")) {
          hide.push(standard);
        }
        if (!ez5.version("6") && row.data.field.hierarchical_mask_hint) {
          hide.push('edit_show', 'edit_edit', "edit_append_only");
        }
        if (ez5.version("6")) {
          disable.push("search_fulltext");
          this.__changeNestedFulltextSearchState(row);
        }
        break;
      case "reverse-linked-table":
        hide.push("mask_id", standard, standard_eas, standard_geo);
        if (!ez5.version("6") && row.data.field.hierarchical_mask_hint) {
          hide.push('edit_show', 'edit_edit', "edit_append_only");
        }
        if (ez5.version("6")) {
          disable.push("search_fulltext");
          this.__changeNestedFulltextSearchState(row);
        }
        break;
      case "link":
        hide.push("edit_append_only", "edit_show_labels", "search_nested");
        break;
      case "field":
        if (row.column_type.match("^custom:")) {
          hide.push("mask_id", "edit_append_only", "search_nested", standard, standard_eas, standard_geo);
          customDataType = CustomDataType.get(row.column_type);
          if (!customDataType.supportsFacet()) {
            hide.push("search_facet");
          }
          if (!customDataType.hasRenderForDetail()) {
            hide.push("output_detail", "output_text");
          }
          if (!customDataType.hasRenderForTable()) {
            hide.push("output_table");
          }
          this.__custom_type_support.maskSetRowState({
            row: row,
            field_numbers: {
              standard: standard,
              standard_eas: standard_eas,
              standard_geo: standard_geo,
              options: options
            },
            hide: hide,
            disable: disable
          });
        } else {
          hide.push("mask_id", "edit_append_only", "search_nested");
          if ((ref1 = row.column_type) !== "eas" && ref1 !== "date" && ref1 !== "daterange" && ref1 !== "datetime" && ref1 !== "boolean") {
            hide.push("search_facet");
          }
          if ((ref2 = row.column_type) === "boolean" || ref2 === "integer.2") {
            hide.push("search_fulltext");
          }
          switch (row.column_type) {
            case "eas":
              if (!ez5.version("6.7")) {
                hide.push(standard);
              }
              break;
            case "geo_json":
              hide.push(standard, standard_eas);
              break;
            default:
              hide.push(standard_eas, standard_geo);
          }
          if (row.column_type === "boolean") {
            hide.push(standard);
          }
        }
    }
    if (row.data.edit_edit === false && row.data.edit_append_only !== void 0) {
      disable.push("edit_append_only");
    }
    hide = hide.filter(function(v) {
      return v !== -1;
    });
    row.updateFields({
      hide: hide,
      disable: disable,
      button_group: row.button_group
    });
    if (this._disabled) {
      row.disableDataFields();
    }
    if (row.type === "linked-table") {
      this.__updateLinkedTableStandard(row);
    }
  };

  MaskEditor.prototype.__updateAllLinkedTableStandard = function() {
    var i, len, node, ref, updateChildren;
    updateChildren = (function(_this) {
      return function(children) {
        var child, i, len, results;
        results = [];
        for (i = 0, len = children.length; i < len; i++) {
          child = children[i];
          if (child.type === "linked-table") {
            _this.__updateLinkedTableStandard(child);
          }
          if (child.children) {
            results.push(updateChildren(child.children));
          } else {
            results.push(void 0);
          }
        }
        return results;
      };
    })(this);
    ref = this.mask_table.nodes;
    for (i = 0, len = ref.length; i < len; i++) {
      node = ref[i];
      if (node.type === "linked-table") {
        this.__updateLinkedTableStandard(node);
        updateChildren(node.children);
      }
    }
  };

  MaskEditor.prototype.__updateLinkedTableStandard = function(row) {
    var has_children_with_standard, standard_button;
    if (!ez5.version("6")) {
      return;
    }
    has_children_with_standard = (function(_this) {
      return function(children) {
        var child, i, len;
        for (i = 0, len = children.length; i < len; i++) {
          child = children[i];
          if (!!child.getData().standard_order) {
            return true;
          }
          if (child.children && has_children_with_standard(child.children)) {
            return true;
          }
        }
        return false;
      };
    })(this);
    standard_button = row.getFieldByIdx(11);
    if (!standard_button) {
      return;
    }
    if (!has_children_with_standard(row.children)) {
      standard_button.disable();
    } else {
      standard_button.enable();
    }
  };

  MaskEditor.prototype.getTabs = function() {
    this.ensureCurrentMask();
    this.tabs = new CUI.Tabs({
      "class": "ez5-mask-editor-tabs",
      absolute: true,
      tabs: [
        {
          name: "mask",
          padded: true,
          text: $$("admin.masks.tab.mask"),
          content: ""
        }, {
          name: "fields",
          text: $$("admin.masks.tab.fields"),
          content: ""
        }, {
          name: "preview_editor",
          text: $$("admin.masks.tab.preview_editor"),
          onActivate: (function(_this) {
            return function() {
              return _this.renderPreviewEditor();
            };
          })(this),
          content: ""
        }, {
          name: "preview_search",
          text: $$("admin.masks.tab.preview_search"),
          onActivate: (function(_this) {
            return function() {
              return _this.renderPreviewSearch();
            };
          })(this),
          content: ""
        }, {
          name: "preview_detail",
          text: $$("admin.masks.tab.preview_detail"),
          onActivate: (function(_this) {
            return function() {
              return _this.renderPreviewDetail();
            };
          })(this),
          content: ""
        }
      ]
    });
    this.form_opts = this.dm_form_opts();
    this.form_opts.disabled = this._disabled;
    this.form_opts.data = this.current_mask.getData();
    this.form_opts.fields[4].disabled = this.form_opts.data.is_preferred;
    return this.tabs;
  };

  MaskEditor.prototype.show = function() {
    this.init_mask_table();
    CUI.dom.append(this.tabs.getTab("mask").getBody(), new CUI.Form(this.form_opts).start().DOM);
    return CUI.dom.append(this.tabs.getTab("fields").getBody(), this.mask_table.render());
  };

  MaskEditor.prototype.loadFields = function() {
    return this.mask_table.load_data(this.current_mask.getRows()).done((function(_this) {
      return function() {
        return _this.update_mask_form();
      };
    })(this));
  };

  MaskEditor.prototype.renderPreviewEditor = function() {
    var body, editorOpts, ro, tmpl;
    tmpl = new CUI.Template({
      name: "mask-editor-preview-editor",
      map: {
        editor: true
      }
    });
    ro = this.getDemoResultObject({
      mode: "editor"
    });
    body = this.tabs.getTab("preview_editor").getBody();
    CUI.dom.empty(body);
    CUI.dom.append(body, tmpl.DOM);
    tmpl.append(ro.renderCardEditor(), "editor");
    editorOpts = {
      skip_columnfilter: true
    };
    ro.getData()._example_object = true;
    return tmpl.append(ro.renderEditor("editor", "editor-header", editorOpts), "editor");
  };

  MaskEditor.prototype.renderPreviewSearch = function() {
    var assetPlaceholder, body, css1, ro, tmpl;
    tmpl = new CUI.Template({
      name: "mask-editor-preview-search",
      map: {
        linked_object: true,
        css_switcher: true,
        standard: true,
        standard_div: true,
        text: true
      }
    });
    ro = this.getDemoResultObject({
      mode: "search"
    });
    body = this.tabs.getTab("preview_search").getBody();
    CUI.dom.empty(body);
    CUI.dom.append(body, tmpl.DOM);
    tmpl.append(ro.renderCardLinkedObjectStandard(), "linked_object");
    css1 = new CSSSwitcher({
      element: tmpl.map.standard,
      variants: ResultStandard.CSSVariants,
      data: {}
    });
    tmpl.append(css1.render(), "css_switcher");
    tmpl.append(ro.renderCardStandard(), "standard_div");
    assetPlaceholder = CUI.dom.div("ez5-asset-placeholder");
    CUI.dom.append(CUI.dom.find(".ez5-result-standard-appearance-info-dummy .ez5-result-card-asset")[0], assetPlaceholder);
    return tmpl.append(ro.renderTextResult({
      skip_columnfilter: true
    }), "text");
  };

  MaskEditor.prototype.renderPreviewDetail = function() {
    var body, ro, tmpl;
    tmpl = new CUI.Template({
      name: "mask-editor-preview-detail",
      map: {
        detail: true
      }
    });
    ro = this.getDemoResultObject({
      mode: "detail"
    });
    body = this.tabs.getTab("preview_detail").getBody();
    CUI.dom.empty(body);
    CUI.dom.append(body, tmpl.DOM);
    tmpl.append(ro.renderCardDetail(), "detail");
    return tmpl.append(ro.renderDetail("detail", "detail-header", {
      skip_columnfilter: true
    }), "detail");
  };

  MaskEditor.prototype.update_mask_form = function() {
    var ref, ref1, ref10, ref11, ref12, ref13, ref14, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, selectedNode;
    if ((ref = this.mask_table.getSelectedNode()) != null ? typeof ref.trashable === "function" ? ref.trashable() : void 0 : void 0) {
      if ((ref1 = this.minusButton) != null) {
        ref1.enable();
      }
    } else {
      if ((ref2 = this.minusButton) != null) {
        ref2.disable();
      }
    }
    selectedNode = this.mask_table.getSelectedNode();
    if (!selectedNode) {
      if ((ref3 = this.moveToBottomButton) != null) {
        ref3.disable();
      }
      if ((ref4 = this.moveToTopButton) != null) {
        ref4.disable();
      }
      if ((ref5 = this.moveUpButton) != null) {
        ref5.disable();
      }
      if ((ref6 = this.moveDownButton) != null) {
        ref6.disable();
      }
    } else if (this.__isRowMovableWithButtons(selectedNode)) {
      if (this.__getNextRowIndexForMove(selectedNode, true)) {
        if ((ref7 = this.moveToBottomButton) != null) {
          ref7.enable();
        }
        if ((ref8 = this.moveDownButton) != null) {
          ref8.enable();
        }
      } else {
        if ((ref9 = this.moveToBottomButton) != null) {
          ref9.disable();
        }
        if ((ref10 = this.moveDownButton) != null) {
          ref10.disable();
        }
      }
      if (this.__getNextRowIndexForMove(selectedNode, false)) {
        if ((ref11 = this.moveToTopButton) != null) {
          ref11.enable();
        }
        if ((ref12 = this.moveUpButton) != null) {
          ref12.enable();
        }
      } else {
        if ((ref13 = this.moveToTopButton) != null) {
          ref13.disable();
        }
        if ((ref14 = this.moveUpButton) != null) {
          ref14.disable();
        }
      }
    }
  };

  MaskEditor.prototype.dump_mask_fields = function() {
    var fieldsRenderer;
    fieldsRenderer = new FieldsRendererTopLevel();
    return console.debug(fieldsRenderer.read(this.mask_table.root.children).dump());
  };

  MaskEditor.prototype.__changeNestedFulltextSearchState = function(row) {
    var checkbox, checkboxButton, enabledCheckboxes, getEnabledCheckboxes, ref, ref1;
    if (!ez5.version("6")) {
      return;
    }
    if (!row) {
      return;
    }
    if (((ref = row.data) != null ? (ref1 = ref.field) != null ? ref1.kind : void 0 : void 0) !== "linked-table") {
      return;
    }
    checkbox = row.getFieldsByName("search_fulltext")[0];
    checkboxButton = checkbox != null ? checkbox.getButton() : void 0;
    if (!checkboxButton) {
      return;
    }
    getEnabledCheckboxes = function(_row, level) {
      if (level == null) {
        level = 0;
      }
      if (level > 10) {
        return [];
      }
      return _row.children.filter(function(childNode) {
        var ref2, ref3;
        if (((ref2 = childNode.data) != null ? (ref3 = ref2.field) != null ? ref3.kind : void 0 : void 0) === "linked-table") {
          return getEnabledCheckboxes(childNode, ++level).length === childNode.children.length;
        }
        return childNode.data.search_fulltext;
      });
    };
    enabledCheckboxes = getEnabledCheckboxes(row);
    CUI.dom.removeClass(checkboxButton, "cui-indeterminate");
    checkbox.deactivate();
    if (enabledCheckboxes.length === row.children.length) {
      checkbox.activate();
    } else if (enabledCheckboxes.length > 0) {
      CUI.dom.addClass(checkboxButton, "cui-indeterminate");
    }
  };

  MaskEditor.prototype.__getMaskTypeExtensionsFields = function(data) {
    var fieldsByGroup, group, i, len, maskTypeExtension, maskTypeExtensions, parameterConfig, parameterName, ref, typeExtensionCustomSettingsConfig;
    fieldsByGroup = {};
    maskTypeExtensions = ez5.pluginManager.getMaskTypeExtensions(data.field._column.type);
    for (i = 0, len = maskTypeExtensions.length; i < len; i++) {
      maskTypeExtension = maskTypeExtensions[i];
      ref = maskTypeExtension.parameters;
      for (parameterName in ref) {
        parameterConfig = ref[parameterName];
        if (CUI.util.isNull(data.custom_settings[parameterName]) && parameterConfig["default"]) {
          data.custom_settings[parameterName] = parameterConfig["default"];
        }
      }
      typeExtensionCustomSettingsConfig = new TypeExtensionCustomSettingsConfig({
        name: maskTypeExtension.name,
        parameters: maskTypeExtension.parameters
      });
      group = maskTypeExtension.group || "other";
      if (!fieldsByGroup[group]) {
        fieldsByGroup[group] = [];
      }
      fieldsByGroup[group] = fieldsByGroup[group].concat(typeExtensionCustomSettingsConfig.getFieldsWithData(data.custom_settings));
    }
    return fieldsByGroup;
  };

  MaskEditor.prototype.__getNestedSortOptions = function(fields, isFrontendSort) {
    var column, columnTypes, field, i, len, options, otherTable, ref, ref1, ref2, value;
    options = [];
    for (i = 0, len = fields.length; i < len; i++) {
      field = fields[i];
      column = field._column;
      if (!column) {
        continue;
      }
      if (column.type === "link") {
        if (isFrontendSort) {
          options.push({
            text: $$("admin.mask.form.sort_first_field.type.linked-object.standard", {
              display_name: column._name_localized
            }),
            value: column.name + "-standard",
            _order: 0
          });
        } else {
          options.push({
            text: $$("admin.mask.form.sort_first_field.type.linked-object.standard", {
              display_name: column._name_localized
            }),
            value: column.name + "._standard.1.text",
            _order: 0
          });
        }
        otherTable = field._other_table;
        if (otherTable != null ? otherTable.pool_link : void 0) {
          if (isFrontendSort) {
            value = column.name + "-pool";
          } else {
            value = column.name + "." + otherTable.name + "._pool.pool.name";
          }
          options.push({
            text: $$("admin.mask.form.sort_first_field.type.linked-object.pool", {
              display_name: column._name_localized
            }),
            value: value,
            _order: 1
          });
        }
      }
      columnTypes = ["boolean", "string", "text", "text_oneline", "eas"];
      if (ref = column.type, indexOf.call(columnTypes, ref) >= 0) {
        options.push({
          text: column._name_localized,
          value: column.name,
          _order: 2
        });
      }
      if ((ez5.version("6") && ((ref1 = column.type) === "number" || ref1 === "integer.2" || ref1 === "double")) || ((ref2 = column.type) === "date" || ref2 === "datetime" || ref2 === "daterange")) {
        options.push({
          text: column._name_localized,
          value: column.name,
          _order: 2
        });
        if (column.type === "daterange") {
          options.push({
            text: $$("admin.mask.form.sort_first_field.type.daterange.from", {
              display_name: column._name_localized
            }),
            value: column.name + ":from",
            _order: 2
          });
          options.push({
            text: $$("admin.mask.form.sort_first_field.type.daterange.to", {
              display_name: column._name_localized
            }),
            value: column.name + ":to",
            _order: 2
          });
        }
      }
    }
    options.sort(function(a, b) {
      return a._order - b._order;
    });
    return options;
  };

  return MaskEditor;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var MaskSchema,
  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;

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

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

  MaskSchema.prototype.initOpts = function() {
    MaskSchema.__super__.initOpts.call(this);
    return this.addOpts({
      maskEditor: {
        mandatory: true,
        check: MaskEditor
      },
      schema: {
        mandatory: true,
        check: "PlainObject"
      }
    });
  };

  MaskSchema.prototype.readOpts = function() {
    var i, k, len, ref, ref1, ref2, ref3, ref4;
    MaskSchema.__super__.readOpts.call(this);
    this.maskEditor = this._maskEditor;
    this.version = this._schema._version;
    this.schema = this._schema;
    this.table = ez5.schema[this.version]._table_by_id[this.schema.table_id];
    this.rows = this.readFieldsFromSchema(this.schema);
    this.data = {};
    ref = ["table_id", "mask_id", "name", "is_preferred", "hide_in_detail", "hide_in_editor", "hide_in_print_dialog", "standard_numbering", "comment", "require_comment"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      this.data[k] = this.schema[k];
    }
    if (this.table.has_tags) {
      this.data.tags_output = this.schema.system_fields.tags.output.mode;
      this.data.tags_edit = this.schema.system_fields.tags.edit.mode;
    }
    if (this.table.acl_table) {
      this.data.acl_output = this.schema.system_fields.acl.output.mode;
      this.data.acl_edit = this.schema.system_fields.acl.edit.mode;
    }
    this.data.object_id_output = this.schema.system_fields.object_id.output.mode;
    this.data.object_id_edit = this.schema.system_fields.object_id.edit.mode;
    this.data.owner_output = this.schema.system_fields.owner.output.mode;
    this.data.owner_edit = this.schema.system_fields.owner.edit.mode;
    if (this.schema.system_fields.publish) {
      this.data.publish_output = this.schema.system_fields.publish.output.mode;
    }
    if (this.table.pool_link) {
      this.data.pool_output = this.schema.system_fields.pool.output.mode;
      if (ez5.version("6") && this.schema.fields.some((function(_this) {
        return function(field) {
          return field.kind === "reverse-linked-table";
        };
      })(this))) {
        this.data.pool_edit = this.schema.system_fields.pool.edit.mode;
      }
    }
    if (this.table.in_main_search) {
      this.data.collections_output = this.schema.system_fields.collections.output.mode;
      this.data.collections_edit = this.schema.system_fields.collections.edit.mode;
    }
    if (this.table.is_hierarchical || this.table.polyhierarchical) {
      this.data.parent_inline = this.schema.system_fields.parent.inline;
      this.data.parent_mask_id = this.schema.system_fields.parent.mask_id;
      this.data.parent_output = this.schema.system_fields.parent.output.mode;
      this.data.parent_edit = this.schema.system_fields.parent.edit.mode;
    }
    if (ez5.version("6.7")) {
      this.data.other_fields_edit = ((ref1 = this.schema.custom_settings) != null ? (ref2 = ref1.system_fields) != null ? ref2.other_fields_edit : void 0 : void 0) || "show";
      this.data.other_fields_output = ((ref3 = this.schema.custom_settings) != null ? (ref4 = ref3.system_fields) != null ? ref4.other_fields_output : void 0 : void 0) || "show";
    }
    if (!this.data.require_comment) {
      this.data.require_comment = "never";
    }
    if (this.data.name === "_all_fields") {
      this.data.name = "";
    }
    if (this.getNameLocaKey()) {
      return this.data.displayname_l10n = ez5.loca.get_user_key(this.version, this.getNameLocaKey());
    } else {
      return this.data.displayname_l10n = {};
    }
  };

  MaskSchema.prototype.getTable = function() {
    return this.table;
  };

  MaskSchema.prototype.setName = function(name) {
    return this.schema.name = name;
  };

  MaskSchema.prototype.getNameLocaKey = function() {
    return this.schema._name_loca_key();
  };

  MaskSchema.prototype.getUserHintLocaKey = function() {
    return this.schema._user_hint_loca_key();
  };

  MaskSchema.prototype.getRows = function() {
    return this.rows;
  };

  MaskSchema.prototype.getData = function() {
    return this.data;
  };

  MaskSchema.prototype.getSchema = function() {
    return this.schema;
  };

  MaskSchema.prototype.readFieldsFromSchema = function(schema, level) {
    var customDataType, field, i, idx, j, k, key, l, len, len1, len10, len2, len3, len4, len5, len6, len7, len8, len9, m, map, n, o, p, q, r, ref, ref1, ref10, ref11, ref12, ref13, ref14, ref15, ref16, ref17, ref18, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, row, rows, s, t, table, u, value;
    if (level == null) {
      level = 0;
    }
    rows = [];
    table = ez5.schema[this.version]._table_by_id[schema.table_id];
    ref = schema.fields;
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      field = ref[idx];
      if (field.kind === "splitter") {
        rows.push(MaskSplitter.getFromField({
          version: this.version,
          l10n_prefix: this.schema._l10n_prefix,
          field: field,
          maskEditor: this.maskEditor
        }));
        continue;
      } else {
        row = new ListViewEditTreeMaskRowNode({
          data: {
            field: field
          }
        });
      }
      row.type = field.kind;
      row.column_type = (ref1 = field._column) != null ? ref1.type : void 0;
      row.button_group = table.table_id;
      row.data.field_displaytype = (function() {
        switch (row.type) {
          case "field":
            return ez5.schema_inst.getDatatypeLocalized(field._column.type, this.version);
          case "link":
            return ez5.schema_inst.getDatatypeLocalized("link_" + field.other_table_id, this.version);
          case "reverse-linked-table":
            if (field.is_hierarchical) {
              return table._name_localized;
            } else {
              return ez5.schema[this.version]._table_by_id[field.other_table_id]._name_localized;
            }
        }
      }).call(this);
      switch (row.type) {
        case "linked-table":
        case "reverse-linked-table":
          ref2 = ["edit_append_only", "edit_show", "edit_edit", "output_detail", "output_text", "output_table", "standard_order", "standard_format", "standard_eas_order", "standard_geo_order", "search_fulltext", "search_expert", "search_nested", "search_facet"];
          for (j = 0, len1 = ref2.length; j < len1; j++) {
            k = ref2[j];
            row.data[k] = false;
          }
          if (ez5.version("6.7")) {
            row.data["stop_if_set"] = false;
          }
          row.data.edit_show = false;
          row.data.edit_edit = false;
          row.data.field_displayname = field._name_localized;
          row.data.field_name = field.name;
          row.data.edit_user_hint_l10n = ez5.loca.get_user_key(this.version, field._user_hint_loca_key());
          row.data.output_user_hint_l10n = ez5.loca.get_user_key(this.version, field._user_output_hint_loca_key());
          if (ez5.version("6.22")) {
            row.data.search_user_hint_l10n = ez5.loca.get_user_key(this.version, field._user_search_hint_loca_key());
          }
          if (!field.is_hierarchical) {
            row.data.table_name = field._other_table.name;
          }
          row.data.nested_sort = field.nested_sort;
          row.data.nested_standard_first_only = field.nested_standard_first_only;
          break;
        case "field":
          ref3 = ["edit_show", "edit_edit", "output_detail", "output_text", "output_table", "user_hint", "search_fulltext", "search_expert", "search_facet"];
          for (l = 0, len2 = ref3.length; l < len2; l++) {
            k = ref3[l];
            row.data[k] = false;
          }
          if (ez5.version("6.7")) {
            row.data["stop_if_set"] = false;
          }
          if (row.column_type === "eas") {
            if (ez5.version("6.7")) {
              s = ["standard_eas_order", "standard_order", "standard_format"];
            } else {
              s = ["standard_eas_order"];
            }
            for (m = 0, len3 = s.length; m < len3; m++) {
              k = s[m];
              row.data[k] = false;
            }
          } else if (row.column_type === "geo_json") {
            ref4 = ["standard_geo_order"];
            for (n = 0, len4 = ref4.length; n < len4; n++) {
              k = ref4[n];
              row.data[k] = false;
            }
          } else {
            ref5 = ["standard_order", "standard_format"];
            for (o = 0, len5 = ref5.length; o < len5; o++) {
              k = ref5[o];
              row.data[k] = false;
            }
            if (ez5.version("6.10")) {
              if (row.column_type.match("^custom:")) {
                customDataType = CustomDataType.get(row.column_type);
                if (customDataType.supportsGeoStandard()) {
                  row.data["standard_geo_order"] = false;
                }
              }
            }
          }
          CUI.util.assert(field._column, "MaskEditor.readFieldsFromSchema", "field._column not found in table, unparsable mask, idx: " + idx, {
            table: table,
            field: field,
            schema: schema,
            version: this.version
          });
          row.data.field_displayname = field._column._name_localized;
          row.data.field_name = field._column.name;
          row.data.edit_user_hint_l10n = ez5.loca.get_user_key(this.version, field._user_hint_loca_key());
          row.data.output_user_hint_l10n = ez5.loca.get_user_key(this.version, field._user_output_hint_loca_key());
          if (ez5.version("6.22")) {
            row.data.search_user_hint_l10n = ez5.loca.get_user_key(this.version, field._user_search_hint_loca_key());
          }
          break;
        case "link":
          ref6 = ["edit_show", "edit_edit", "output_detail", "output_text", "output_table", "standard_order", "standard_format", "standard_eas_order", "standard_geo_order", "search_fulltext", "search_expert", "search_facet"];
          for (p = 0, len6 = ref6.length; p < len6; p++) {
            k = ref6[p];
            row.data[k] = false;
          }
          if (ez5.version("6.7")) {
            row.data["stop_if_set"] = false;
          }
          CUI.util.assert(field._column, "MaskEditor.readFieldsFromSchema", "field._column not found in table, unparsable mask, idx: " + idx, {
            table: table,
            field: field,
            schema: schema,
            version: this.version
          });
          row.data.inline = field.inline;
          row.data.field_displayname = field._column._name_localized;
          row.data.field_name = field._column.name;
          row.data.mask_id = field.mask_id;
          row.data.edit_user_hint_l10n = ez5.loca.get_user_key(this.version, field._user_hint_loca_key());
          row.data.output_user_hint_l10n = ez5.loca.get_user_key(this.version, field._user_output_hint_loca_key());
          if (ez5.version("6.22")) {
            row.data.search_user_hint_l10n = ez5.loca.get_user_key(this.version, field._user_search_hint_loca_key());
          }
          break;
        default:
          CUI.util.assert(false, "MaskEditor.mask_row_from_mask", "field.kind is unknown", {
            table: table,
            field: field,
            schema: schema,
            version: this.version
          });
      }
      switch (row.type) {
        case "linked-table":
        case "reverse-linked-table":
        case "link":
        case "field":
          switch (field.edit.mode) {
            case "off":
              row.data.edit_show = false;
              row.data.edit_edit = false;
              break;
            case "edit":
              row.data.edit_show = false;
              row.data.edit_edit = true;
              break;
            case "show":
              row.data.edit_show = true;
              row.data.edit_edit = false;
          }
      }
      if ((ref7 = row.type) === "linked-table" || ref7 === "reverse-linked-table") {
        map = {
          append_only: "edit_append_only"
        };
        for (key in map) {
          value = map[key];
          if (CUI.util.isUndef(row.data[value])) {
            continue;
          }
          if (field.edit[key]) {
            row.data[value] = true;
          }
        }
        if (ez5.version("6")) {
          if (row.type === "linked-table") {
            if ((((ref8 = field.output) != null ? (ref9 = ref8.standard) != null ? ref9.format : void 0 : void 0) != null) && CUI.util.isUndef(row.data.format)) {
              row.data.format = field.output.standard.format;
            }
            if ((((ref10 = field.output) != null ? (ref11 = ref10.standard) != null ? ref11.format_inner : void 0 : void 0) != null) && CUI.util.isUndef(row.data.format_inner)) {
              row.data.format_inner = field.output.standard.format_inner;
            }
          }
        }
      }
      if (CUI.util.isEmpty(field.custom_settings)) {
        row.data.custom_settings = this.__getDefaultCustomSettingsByField(field);
      } else {
        row.data.custom_settings = field.custom_settings;
      }
      ref12 = ["detail", "text", "table"];
      for (q = 0, len7 = ref12.length; q < len7; q++) {
        k = ref12[q];
        if (CUI.util.isUndef(row.data["output_" + k])) {
          continue;
        }
        if (field.output[k]) {
          row.data["output_" + k] = true;
        }
      }
      ref13 = ["fulltext", "expert", "facet", "nested"];
      for (r = 0, len8 = ref13.length; r < len8; r++) {
        k = ref13[r];
        if (CUI.util.isUndef(row.data["search_" + k])) {
          continue;
        }
        if (field.search[k]) {
          row.data["search_" + k] = true;
        }
      }
      if (row.column_type === "eas") {
        if (ez5.version("6.7")) {
          ref14 = ["order", "format"];
          for (t = 0, len9 = ref14.length; t < len9; t++) {
            k = ref14[t];
            if (CUI.util.isUndef(row.data["standard_" + k])) {
              continue;
            }
            if (field.output.standard[k] !== false) {
              row.data["standard_" + k] = field.output.standard[k];
            }
          }
        }
        if (field.output.standard_eas) {
          row.data["standard_eas_order"] = field.output.standard_eas.order || "";
        } else if ((ref15 = field.output.standard) != null ? ref15.order : void 0) {
          row.data["standard_eas_order"] = field.output.standard.order;
        }
        if (field.output.standard_geo) {
          row.data["standard_geo_order"] = field.output.standard_geo.order || "";
        } else if ((ref16 = field.output.standard) != null ? ref16.order : void 0) {
          row.data["standard_geo_order"] = field.output.standard.order;
        }
      }
      if (row.column_type === "geo_json") {
        if (field.output.standard_geo) {
          row.data["standard_geo_order"] = field.output.standard_geo.order || "";
        } else if ((ref17 = field.output.standard) != null ? ref17.order : void 0) {
          row.data["standard_geo_order"] = field.output.standard.order;
        }
      } else {
        ref18 = ["order", "format"];
        for (u = 0, len10 = ref18.length; u < len10; u++) {
          k = ref18[u];
          if (CUI.util.isUndef(row.data["standard_" + k])) {
            continue;
          }
          if (field.output.standard[k] !== false) {
            row.data["standard_" + k] = field.output.standard[k];
          }
        }
        if (!CUI.util.isUndef(row.data["standard_eas_order"])) {
          row.data["standard_eas_order"] = field.output.standard_eas.order;
        }
        if (ez5.version("6.7")) {
          if (!CUI.util.isUndef(row.data["standard_geo_order"])) {
            row.data["standard_geo_order"] = field.output.standard_geo.order;
          }
          if (!CUI.util.isUndef(row.data["stop_if_set"])) {
            row.data["stop_if_set"] = field.output.standard.stop_if_set;
          }
        }
      }
      row.data.field._level = level;
      if (field.mask) {
        row.children = this.readFieldsFromSchema(field.mask, ++level);
        if (--level < 0) {
          level = 0;
        }
      }
      rows.push(row);
    }
    return rows;
  };

  MaskSchema.prototype.__getDefaultCustomSettingsByField = function(field) {
    var column, customSettings, i, len, maskTypeExtension, maskTypeExtensions, parameterConfig, parameterName, ref;
    customSettings = {};
    if (field.kind === "linked-table") {
      customSettings.show_first_empty_nested = true;
    }
    column = field._column;
    if (CUI.util.isEmpty(column)) {
      return customSettings;
    }
    if (column.type === "boolean") {
      customSettings.boolean_show_false = true;
    }
    maskTypeExtensions = ez5.pluginManager.getMaskTypeExtensions(column.type);
    for (i = 0, len = maskTypeExtensions.length; i < len; i++) {
      maskTypeExtension = maskTypeExtensions[i];
      ref = maskTypeExtension.parameters;
      for (parameterName in ref) {
        parameterConfig = ref[parameterName];
        if (parameterConfig["default"]) {
          customSettings[parameterName] = parameterConfig["default"];
        }
      }
    }
    return customSettings;
  };

  return MaskSchema;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var ExportManager,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  ExportManager.prototype.initOpts = function() {
    ExportManager.__super__.initOpts.call(this);
    return this.addOpts({
      search: {
        mandatory: true,
        check: Search
      },
      "export": {
        check: Export
      },
      sortManager: {
        check: SortManager,
        "default": null,
        mandatory: false
      }
    });
  };

  ExportManager.prototype.readOpts = function() {
    ExportManager.__super__.readOpts.call(this);
    return this.__search = this._search;
  };

  ExportManager.__plugins = [];

  ExportManager.registerPlugin = function(plugin) {
    CUI.util.assert(plugin instanceof ExportManagerPlugin, 'ExportManager.registerPlugin', 'Plugin needs to be instanceof ExportManagerPlugin.', {
      plugin: plugin
    });
    this.__plugins.push(plugin);
    return console.info("ExportManager: Registered Plugin:", plugin.name());
  };

  ExportManager.prototype.init = function() {
    var dfr, ref, ref1, request;
    dfr = new CUI.Deferred();
    if (this._export) {
      this["export"] = this.opts["export"];
    }
    if (!this.__produce_options) {
      this.__produce_options = {
        plugin: ((ref = this["export"]) != null ? (ref1 = ref.getExportData().produce_options) != null ? ref1.plugin : void 0 : void 0) || "easydb"
      };
    }
    this.__plugin = ExportManager.getPluginByName(this.__produce_options.plugin);
    if (!this.__plugin) {
      CUI.problem({
        text: $$("export.manager.plugin_not_found", {
          plugin_name: this.__produce_options.plugin
        })
      });
      return dfr.reject();
    }
    request = this.initRequest();
    this.__search.addToRequest(request);
    this.expandForExport(this.__search, request).done((function(_this) {
      return function() {
        var ref2;
        CUI.util.assert(((ref2 = request.search) != null ? ref2.length : void 0) >= 0, "new ExportManager", "opts.search[" + (CUI.util.getObjectClass(_this.__search)) + "].addToRequest did not fill request with search Array", {
          request: request,
          opts: _this.opts
        });
        if (!_this["export"]) {
          _this.__addSort(request);
          _this["export"] = new Export({
            "export": {
              search: request.cleanRequestForSearch()
            }
          });
        }
        return dfr.resolve();
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  ExportManager.prototype.initRequest = function() {
    var exportSearch, key, request, value;
    request = new Request({
      for_export: true
    });
    if (this["export"]) {
      if (exportSearch = this.getRequest()) {
        for (key in exportSearch) {
          value = exportSearch[key];
          request[key] = value;
        }
      }
    }
    return request;
  };

  ExportManager.prototype.__addSort = function(request) {
    var i, ref, ref1, results, sort;
    if (!ez5.version("6")) {
      return;
    }
    if (this._sortManager) {
      this._sortManager.addToRequest(request);
      if (!request.sort || request.sort.length === 0) {
        return;
      }
      ref = request.sort;
      results = [];
      for (i = ref.length - 1; i >= 0; i += -1) {
        sort = ref[i];
        if (sort.field.startsWith("_")) {
          continue;
        }
        if (ref1 = sort.field.split('.')[0], indexOf.call(request.objecttypes, ref1) < 0) {
          results.push(request.sort.splice(request.sort.indexOf(sort), 1));
        } else {
          results.push(void 0);
        }
      }
      return results;
    }
  };

  ExportManager.prototype.expandForExport = function(search, request) {
    var dfr, fields, lbl, master_dfr, ots, sids, toaster;
    fields = [];
    ots = [];
    toaster = null;
    lbl = new LocaLabel({
      loca_key: 'export.manager.collecting_data',
      multiline: true,
      loca_key_attrs: {
        percent: 0
      }
    });
    sids = [];
    if (request.objecttypes == null) {
      request.objecttypes = [];
    }
    dfr = new CUI.Deferred();
    master_dfr = new CUI.Deferred();
    master_dfr.always((function(_this) {
      return function() {
        return toaster != null ? toaster.destroy() : void 0;
      };
    })(this));
    dfr.fail(master_dfr.reject);
    dfr.done((function(_this) {
      return function() {
        var finish, sid_search;
        if (fields.length === 0 || sids.length === 0) {
          master_dfr.resolve();
          return;
        }
        sid_search = null;
        finish = function() {
          var i, len, original_ots, ot;
          original_ots = (function() {
            var i, len, ref, results;
            ref = request.objecttypes;
            results = [];
            for (i = 0, len = ref.length; i < len; i++) {
              ot = ref[i];
              results.push(ot);
            }
            return results;
          })();
          for (i = 0, len = ots.length; i < len; i++) {
            ot = ots[i];
            CUI.util.pushOntoArray(ot, request.objecttypes);
          }
          request.search = [
            {
              type: "complex",
              bool: "should",
              search: [
                {
                  type: "complex",
                  bool: "must",
                  search: request.search
                }, {
                  type: "in",
                  bool: "must",
                  fields: ["_objecttype"],
                  "in": original_ots
                }
              ]
            }, sid_search
          ];
          return master_dfr.resolve();
        };
        if (request.best_mask_filter === false) {
          ez5.api.search_no_limit({
            data: {
              debug: "expand-sids-check-visibility"
            },
            json_data: {
              limit: sids.length,
              objectttype: ots,
              type: "object",
              best_mask_filter: true,
              generate_rights: false,
              format: "short",
              search: [
                {
                  type: "in",
                  fields: ["_system_object_id"],
                  "in": sids
                }
              ]
            }
          }).fail(master_dfr.reject).done(function(data) {
            var i, j, len, len1, obj, ref, ref1, sid_mask, use_sid_mask;
            sid_search = {
              type: 'complex',
              bool: 'should',
              search: []
            };
            ref = data.objects;
            for (i = 0, len = ref.length; i < len; i++) {
              obj = ref[i];
              use_sid_mask = null;
              ref1 = sid_search.search;
              for (j = 0, len1 = ref1.length; j < len1; j++) {
                sid_mask = ref1[j];
                if (sid_mask.__mask === obj._mask) {
                  use_sid_mask = sid_mask;
                  break;
                }
              }
              if (use_sid_mask === null) {
                use_sid_mask = {
                  __mask: obj._mask,
                  type: "complex",
                  bool: "should",
                  search: [
                    {
                      type: "in",
                      fields: ["_system_object_id"],
                      "in": []
                    }, {
                      type: "in",
                      fields: ["_mask"],
                      "in": [obj._mask]
                    }
                  ]
                };
                sid_search.search.push(use_sid_mask);
              }
              use_sid_mask.search[0]["in"].push(obj._system_object_id);
            }
            return finish();
          });
        } else {
          sid_search = {
            type: 'in',
            bool: 'should',
            "in": sids,
            fields: ["_system_object_id"]
          };
          finish();
        }
      };
    })(this));
    this.__plugin.expandForExport(search, request);
    search.getExportObjecttypesAndCount(request).fail(dfr.reject).done((function(_this) {
      return function(objecttypes, __original_count) {
        var addLinkedObjects, count, eas_column, f, fatherField, i, idx, j, l, len, len1, len2, lf, limit, must_not_search, name, new_eas_column, offset, ot, ref, ref1, ref2, remoteInstance, req_data, search_more, set_percent, targetInstanceIsEZ5;
        _this.__original_count = __original_count;
        addLinkedObjects = (ref = _this.__plugin.data) != null ? ref._export_addLinkedData : void 0;
        if (!(CUI.util.isNull(addLinkedObjects) || addLinkedObjects)) {
          dfr.resolve();
          return;
        }
        for (i = 0, len = objecttypes.length; i < len; i++) {
          ot = objecttypes[i];
          CUI.util.pushOntoArray(ot.name(), request.objecttypes);
          if (ot.getInstance()) {
            remoteInstance = (ref1 = ez5.connector) != null ? ref1.getRemoteEasydbByInstance(ot.getInstance()) : void 0;
          }
          targetInstanceIsEZ5 = (!remoteInstance && !ez5.version("6")) || (remoteInstance && !(typeof remoteInstance.isFylr === "function" ? remoteInstance.isFylr() : void 0));
          ref2 = ot.getAllFields();
          for (j = 0, len1 = ref2.length; j < len1; j++) {
            f = ref2[j];
            if (!(f instanceof LinkedObject)) {
              continue;
            }
            if (targetInstanceIsEZ5) {
              if (!(f.isVisible("facet") || f.isVisible("expert") || f.isVisible("fulltext"))) {
                continue;
              }
              fatherField = f.getFatherField();
              if (fatherField && !(fatherField.isVisible("facet", {
                for_export: true
              }) || fatherField.isVisible("expert", {
                for_export: true
              }) || fatherField.isVisible("fulltext", {
                for_export: true
              }))) {
                continue;
              }
            }
            eas_column = f.getFirstStandardEASColumn();
            if (eas_column) {
              new_eas_column = new EASColumnLinkedObject(eas_column.mask, eas_column.FieldSchema, f);
              fields.push(new_eas_column);
            }
          }
        }
        if (fields.length === 0) {
          dfr.resolve();
          return;
        }
        req_data = CUI.util.copyObject(request.cleanRequestForSearch(), true);
        req_data.fields = [];
        req_data.format = 'short';
        req_data.generate_rights = false;
        must_not_search = [];
        req_data.search.push({
          type: "complex",
          bool: "must",
          search: must_not_search
        });
        for (idx = l = 0, len2 = fields.length; l < len2; idx = ++l) {
          f = fields[idx];
          lf = f.getLinkedObject();
          name = lf.fullName() + '._system_object_id';
          req_data.fields.push({
            key: '_system_object_id',
            field: name
          });
          CUI.util.pushOntoArray(f.getMainMask().table.name(), ots);
          must_not_search.push({
            type: "complex",
            bool: "should",
            search: [
              {
                bool: 'must_not',
                fields: [name],
                type: 'in',
                "in": [null]
              }
            ]
          });
        }
        offset = 0;
        limit = 1000;
        count = -1;
        set_percent = function(percent) {
          if (!toaster) {
            toaster = CUI.toaster({
              content: lbl,
              show_ms: 0
            });
          }
          lbl.setText($$('export.manager.collecting_data|text', {
            percent: Math.ceil(offset / count * 100)
          }));
          return CUI.Events.trigger({
            type: "content-resize",
            node: toaster
          });
        };
        search_more = function() {
          req_data.offset = offset;
          req_data.limit = limit;
          return ez5.api.search({
            json_data: req_data,
            data: {
              debug: "expand-linked-objects"
            }
          }).done(function(data) {
            var len3, len4, m, n, obj, ref3, ref4, ref5, sid;
            ref3 = data.objects;
            for (m = 0, len3 = ref3.length; m < len3; m++) {
              obj = ref3[m];
              if (!((ref4 = obj._fields) != null ? ref4._system_object_id : void 0)) {
                continue;
              }
              ref5 = obj._fields._system_object_id;
              for (n = 0, len4 = ref5.length; n < len4; n++) {
                sid = ref5[n];
                sids.push(parseInt(sid));
              }
            }
            if (offset + limit < data.count) {
              offset = offset + limit;
              count = data.count;
              set_percent();
              return search_more();
            } else {
              return dfr.resolve();
            }
          }).fail(dfr.reject);
        };
        return search_more();
      };
    })(this));
    return master_dfr.promise();
  };

  ExportManager.prototype.prepareExport = function() {
    this.init().done((function(_this) {
      return function() {
        var btn_type;
        _this._schedules = new ScheduleEditor({
          button_type: "apply",
          show_minutes: true,
          onButtonClick: function(ev, schedules) {
            _this["export"].getData()._schedules = schedules;
          },
          loadSchedules: function() {
            return _this["export"].getChildren(function() {
              return this.getData()._schedules;
            });
          }
        });
        _this._transports = new TransportsEditor({
          "export": _this["export"],
          button_type: "apply",
          onButtonClick: function(ev, transports) {
            _this["export"].getData()._transports = transports;
          }
        });
        if (_this["export"].getId()) {
          btn_type = "update";
        } else {
          btn_type = "export";
        }
        _this.saveButton = new LocaButton({
          ui: "export-manager-" + btn_type + "-button",
          loca_key: "export.manager.button." + btn_type,
          primary: true,
          disabled: true,
          onClick: function(ev) {
            if (ev.ctrlKey() || ev.altKey() || ev.shiftKey()) {
              console.debug(CUI.util.dump(_this["export"].setExportData(_this.getExportData()).getSaveData()));
              return;
            }
            _this.openModalToUpdateName().done(function() {
              var autoStart, ref;
              _this.modal.disableAllButtons();
              if (!((ref = _this["export"].getData()._schedules) != null ? ref.length : void 0) && !_this["export"].getId()) {
                autoStart = true;
              } else {
                autoStart = false;
              }
              return _this["export"].setExportData(_this.getExportData()).save().always(function() {
                return _this.modal.enableAllButtons();
              }).done(function() {
                if (autoStart) {
                  _this.modal.disableAllButtons();
                  return _this["export"].start().always(function() {
                    return _this.modal.enableAllButtons();
                  }).done(function() {
                    _this.destroy();
                    return _this.modal.destroy();
                  });
                } else {
                  _this.destroy();
                  return _this.modal.destroy();
                }
              });
            });
          }
        });
        _this.modal = new CUI.Modal({
          "class": "export-manager-modal",
          cancel: true,
          onCancel: function() {
            if (_this.saveButton.isDisabled() || (!_this["export"].getId() && !_this.__isChanged())) {
              _this.destroy();
            } else {
              return CUI.confirm({
                text: $$("export.manager.confirm.close")
              }).done(function() {
                return _this.destroy();
              });
            }
          },
          pane: {
            header_left: new LocaLabel({
              loca_key: "export.manager.title"
            }),
            header_right: _this.getPluginSelect(),
            footer_right: function() {
              return [btn_type === "export" ? _this._schedules.getButton() : void 0, btn_type === "export" ? _this._transports.getButton() : void 0, _this.saveButton];
            }
          }
        });
        CUI.Events.listen({
          type: "data-changed",
          node: _this.modal,
          call: function(ev) {
            return _this.__updateSaveButton();
          }
        });
        return _this.gatherBaseData().done(function() {
          var instances;
          instances = _this.getEASColumnsInfo().instances;
          if (instances && !(instances.length === 1 && instances[0] === "local")) {
            CUI.problem({
              text: $$("export.manager.connector.unable_to_export.md"),
              markdown: true
            });
            return;
          }
          _this.__replaceModalTitle();
          _this.modal.show();
          _this.renderContent();
          _this.__initIsChanged();
          _this.__updateSaveButton();
        });
      };
    })(this));
  };

  ExportManager.prototype.__replaceModalTitle = function() {
    var label;
    if (this._export) {
      label = new LocaLabel({
        loca_key: "export.manager.modal.edit-title"
      });
    } else {
      label = new LocaLabel({
        loca_key: "export.manager.modal.title",
        loca_key_attrs: {
          count: this.getOriginalCount()
        }
      });
    }
    this.modal.replace(label, "header_left");
  };

  ExportManager.prototype.reload = function(opts) {
    if (opts == null) {
      opts = {};
    }
    return this.gatherBaseData().done((function(_this) {
      return function() {
        opts.reload = true;
        _this.renderContent(opts);
        return _this.__updateSaveButton();
      };
    })(this));
  };

  ExportManager.prototype.reloadExport = function() {
    delete this["export"];
    return this.init().done((function(_this) {
      return function() {
        return _this.gatherBaseData().done(function() {
          return _this.renderContent({
            reload: true,
            active_tab: "advanced"
          });
        });
      };
    })(this));
  };

  ExportManager.prototype.getOriginalCount = function() {
    return this.__original_count;
  };

  ExportManager.prototype.renderContent = function(opts) {
    var k, ref, v;
    if (opts == null) {
      opts = {};
    }
    ref = {
      "export": this["export"],
      EASColumnsInfo: this.EASColumnsInfo,
      exportManager: this,
      onClose: (function(_this) {
        return function() {
          return _this.__updateSaveButton();
        };
      })(this)
    };
    for (k in ref) {
      v = ref[k];
      opts[k] = v;
    }
    this.__plugin.init(opts);
    return this.modal.replace(this.__plugin.renderForm(), "center");
  };

  ExportManager.prototype.getFilenameTemplateField = function() {
    return {
      type: CUI.Form,
      form: {
        label: $$("export.manager.form.filename.label")
      },
      fields: [
        {
          type: CUI.Checkbox,
          name: "_template",
          ui: "download.manager.form.template.default",
          value: "default",
          radio: "template",
          text: $$("export.manager.form.filename.default")
        }, {
          type: CUI.Checkbox,
          name: "_template",
          ui: "download.manager.form.template.original",
          value: "original",
          radio: "template",
          text: $$("export.manager.form.filename.original")
        }, {
          type: CUI.Form,
          "class": "has-custom-checkbox",
          horizontal: true,
          fields: [
            {
              type: CUI.Checkbox,
              name: "_template",
              ui: "download.manager.form.template.custom",
              value: "custom",
              radio: "template"
            }, {
              type: CUI.Input,
              name: "_template_custom",
              ui: "download.manager.form.template.custom_input",
              placeholder: $$("export.manager.form.filename.prefix")
            }
          ]
        }
      ]
    };
  };

  ExportManager.prototype.__updateSaveButton = function() {
    var ref;
    if (((ref = this["export"]) != null ? ref.getId() : void 0) && !this.__isChanged()) {
      this.saveButton.disable();
    } else if (this.__plugin.saveAllowed()) {
      this.saveButton.enable();
    } else {
      this.saveButton.disable();
    }
    return this;
  };

  ExportManager.prototype.__initIsChanged = function() {
    var exception;
    try {
      this.__startData = JSON.stringify(this.getExportData());
    } catch (error) {
      exception = error;
      this.__startData = "__invalid_export_data__";
      if (!(exception instanceof InvalidSaveDataException)) {
        throw exception;
      }
    }
    return this;
  };

  ExportManager.prototype.__isChanged = function() {
    var exception;
    try {
      return this.__startData !== JSON.stringify(this.getExportData());
    } catch (error) {
      exception = error;
      if (exception instanceof InvalidSaveDataException) {
        return false;
      } else {
        throw exception;
      }
    }
  };

  ExportManager.prototype.getPluginSelect = function() {
    var i, len, options, plugin, ref;
    if (ExportManager.__plugins.length === 1) {
      this.__produce_options.plugin = ExportManager.__plugins[0].name();
      return;
    }
    options = [];
    ref = ExportManager.__plugins;
    for (i = 0, len = ref.length; i < len; i++) {
      plugin = ref[i];
      options.push({
        value: plugin.name(),
        text: plugin.nameLocalized()
      });
    }
    return new CUI.Select({
      data: this.__produce_options,
      name: "plugin",
      options: options,
      onDataChanged: (function(_this) {
        return function() {
          var ref1;
          if ((ref1 = _this.__plugin) != null) {
            ref1.deinit();
          }
          return _this.init().done(function() {
            _this.__replaceModalTitle();
            _this.renderContent();
            return _this.__updateSaveButton();
          });
        };
      })(this)
    }).start();
  };

  ExportManager.prototype.getMetadataField = function() {
    var i, k, keys, len, mapping, mappingOptions;
    if (ez5.session.hasSystemRight("root")) {
      mapping = "remove";
    } else {
      mapping = ez5.session.getSystemRight("frontend_features[metadata_export]");
    }
    if (!mapping) {
      return null;
    }
    mappingOptions = [];
    keys = ["standard"];
    if (mapping === "keep" || mapping === "remove") {
      keys.push("keep");
    }
    if (mapping === "remove") {
      keys.push("remove");
    }
    for (i = 0, len = keys.length; i < len; i++) {
      k = keys[i];
      mappingOptions.push({
        ui: "export-manager-asset-profile-" + k + "-option",
        text: $$("export.manager.asset_profile." + k),
        value: k
      });
    }
    if (mapping !== "standard_only") {
      mappingOptions = this.getMetadataFieldOptions(mappingOptions);
    }
    if (mappingOptions.length === 0) {
      return null;
    }
    return {
      ui: "export-manager-asset-profile-select",
      type: CUI.Select,
      name: "_metadata",
      form: {
        label: $$("export.manager.asset_profile.profile")
      },
      options: mappingOptions
    };
  };

  ExportManager.prototype.getMetadataFieldOptions = function(mapping_opts) {
    return ez5.metadata.getMappingOpts(mapping_opts, {
      exiftool_export: true
    });
  };

  ExportManager.prototype.getExportManagerResultClass = function() {
    return window.ExportManagerResult;
  };

  ExportManager.prototype.gatherBaseData = function() {
    var count, dfr, eas_info, func, lbl, limit, offset, search_more, set_percent, sm, toaster;
    eas_info = {
      total: 0,
      assets: [],
      instances: null,
      otm: null,
      counts: {
        by_class: {},
        by_instance: {},
        by_field_name: {}
      }
    };
    this.setEASColumnsInfo(eas_info);
    func = new this.getExportManagerResultClass();
    sm = new func({
      manager: this,
      eas_info: eas_info
    });
    offset = 0;
    limit = 100;
    toaster = null;
    count = -1;
    lbl = new LocaLabel({
      loca_key: 'export.manager.collecting_data',
      multiline: true,
      loca_key_attrs: {
        percent: 0
      }
    });
    set_percent = function(percent) {
      if (!toaster) {
        toaster = CUI.toaster({
          content: lbl,
          show_ms: 0
        });
      }
      lbl.setText($$('export.manager.collecting_data|text', {
        percent: Math.ceil(offset / count * 100)
      }));
      CUI.Events.trigger({
        type: "content-resize",
        node: toaster
      });
    };
    dfr = new CUI.Deferred();
    dfr.always((function(_this) {
      return function() {
        sm.destroy();
        return toaster != null ? toaster.destroy() : void 0;
      };
    })(this));
    search_more = (function(_this) {
      return function() {
        var req;
        req = new Request({
          searchManagers: [sm],
          offset: offset,
          limit: limit,
          generate_rights: false,
          exclusive: true,
          for_export: _this.getGatherBaseDataRequestForExport()
        });
        return _this.__search.execute(req).done(function(req, data) {
          eas_info.instances = data.__instances;
          if (req.limit > 0 && offset + limit < data.count) {
            offset = offset + limit;
            count = data.count;
            set_percent();
            return search_more();
          } else {
            return dfr.resolve();
          }
        }).fail(dfr.reject);
      };
    })(this);
    search_more();
    return dfr.promise();
  };

  ExportManager.prototype.getGatherBaseDataRequestForExport = function() {
    return true;
  };

  ExportManager.prototype.acceptVersionForDownload = function(version) {
    return true;
  };

  ExportManager.prototype.openModalToUpdateName = function() {
    var data, ref;
    data = this["export"].getExportData();
    return CUI.prompt({
      title: $$("export.manager.name_modal.title"),
      text: $$("export.manager.name_modal.help"),
      "default": data.name,
      min_length: ((ref = this["export"].getData()._schedules) != null ? ref.length : void 0) > 0 ? 1 : 0,
      placeholder: $$("export.manager.name_modal.input.name.placeholder"),
      button_text_ok: $$("base.save")
    }).done((function(_this) {
      return function(new_name) {
        return data.name = new_name;
      };
    })(this));
  };

  ExportManager.getPluginByName = function(name) {
    var i, len, plugin, ref;
    ref = ExportManager.__plugins;
    for (i = 0, len = ref.length; i < len; i++) {
      plugin = ref[i];
      if (plugin.name() === name) {
        return plugin;
      }
    }
    return null;
  };

  ExportManager.prototype.getRequest = function() {
    var k, ref, request, v;
    request = {};
    ref = this["export"].getData()["export"].search;
    for (k in ref) {
      v = ref[k];
      if (k === 'offset' || k === 'limit') {
        continue;
      }
      request[k] = CUI.util.copyObject(v, true);
    }
    delete request.event_log;
    return this.filterRequest(request);
  };

  ExportManager.prototype.filterRequest = function(request) {
    var ref, reqs;
    if ((ref = ez5.connector) != null ? ref.isAvailable() : void 0) {
      reqs = ez5.connector.splitRequest({
        json_data: request
      });
      return reqs[0].json_data;
    }
    return request;
  };

  ExportManager.prototype.setEASColumnsInfo = function(EASColumnsInfo) {
    this.EASColumnsInfo = EASColumnsInfo;
  };

  ExportManager.prototype.getEASColumnsInfo = function() {
    return this.EASColumnsInfo;
  };

  ExportManager.prototype.destroy = function() {
    var ref, ref1;
    ExportManager.__super__.destroy.call(this);
    delete this["export"];
    if ((ref = this.__plugin) != null) {
      ref.resetData();
    }
    delete this.__plugin;
    if ((ref1 = this.layout) != null) {
      ref1.destroy();
    }
    return this.layout = null;
  };

  ExportManager.prototype.getExportData = function() {
    var exportData, i, k, len, ref, req;
    exportData = this.__plugin.getExportData();
    if (!exportData.produce_options) {
      exportData.produce_options = {};
    }
    exportData.produce_options.plugin = this.__produce_options.plugin;
    exportData.name = this["export"].getExportData().name;
    req = this.getRequest();
    if (!exportData.search) {
      exportData.search = {};
    }
    ref = ["objecttypes", "sort", "search", "best_mask_filter"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      if (req.hasOwnProperty(k)) {
        exportData.search[k] = req[k];
      }
    }
    exportData.search.generate_rights = false;
    return exportData;
  };

  return ExportManager;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var ExportManagerPlugin,
  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;

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

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

  ExportManagerPlugin.prototype.init = function(opts) {
    return CUI.Element.readOpts.call(this, opts, 'ExportManagerPlugin.init', this.getInitOpts());
  };

  ExportManagerPlugin.prototype.deinit = function() {};

  ExportManagerPlugin.prototype.getInitOpts = function() {
    return {
      EASColumnsInfo: {
        mandatory: true,
        check: "PlainObject"
      },
      "export": {
        mandatory: true,
        check: Export
      },
      exportManager: {
        mandatory: true,
        check: ExportManager
      },
      onClose: {
        check: Function
      },
      reload: {
        check: Boolean
      }
    };
  };

  ExportManagerPlugin.prototype.name = function() {
    return "<unknown>";
  };

  ExportManagerPlugin.prototype.nameLocalized = function() {
    return "<unknown>";
  };

  ExportManagerPlugin.prototype.renderForm = function() {
    return new CUI.EmptyLabel({
      text: "<no content>",
      centered: true
    });
  };

  ExportManagerPlugin.prototype.getExportData = function() {
    return this._export.getExportData();
  };

  ExportManagerPlugin.prototype.saveAllowed = function() {
    return true;
  };

  ExportManagerPlugin.prototype.expandForExport = function() {};

  ExportManagerPlugin.prototype.resetData = function() {};

  return ExportManagerPlugin;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var ExportManagerEasydb,
  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;

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

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

  ExportManagerEasydb.prototype.getInitOpts = function() {
    var opts;
    opts = ExportManagerEasydb.__super__.getInitOpts.call(this);
    opts.active_tab = {
      check: String
    };
    return opts;
  };

  ExportManagerEasydb.prototype.name = function() {
    return "easydb";
  };

  ExportManagerEasydb.prototype.nameLocalized = function() {
    return "easydb";
  };

  ExportManagerEasydb.prototype.renderForm = function() {
    var __search, _search, _templates, active_idx, advanced_fields, advanced_form, block_advanced, block_data, block_fields, block_filetypes, block_mask_filter, block_urls, bs, cb, changeButtonText, changelog_opts, check_fields, clean_search_data, cls, cls_tr, csv_hierarchy_opts, data_form, def, defs, eas_form_fields, fieldSelectorButton, formOpts, form_classes, form_classes_table, form_fields, group, groupLabelText, groups, idx, initMappingOpts, j, k, l, len, len1, len2, len3, len4, len5, loadingLabel, m, mapping_opts, mask, maskData, n, o, onFieldSelectorClosed, opts, p, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, searchData, search_data_json, selectFieldsText, set_search_data, tab, tabs, td, tooltip, tt_txt, url_fields, v, versions, xslt, xslts;
    eas_form_fields = this.generateFieldsFormEAS();
    if (eas_form_fields) {
      block_fields = new CUI.Block({
        "class": "ez5-export-manager-block ez5-export-manager-block-fields",
        padded: false,
        text: $$("export.manager.group.fields"),
        description: $$("export.manager.group.fields.description"),
        content: eas_form_fields
      });
      url_fields = [];
      opts = [
        {
          ui: "export-manager-original-no-url-option",
          text: $$("export.manager.form.url.no"),
          value: null
        }
      ];
      ref = this.__getOriginalKeys();
      for (idx = j = 0, len = ref.length; j < len; idx = ++j) {
        k = ref[idx];
        opts.push({
          ui: "export-manager-original-" + k + "-option",
          text: $$("export.manager.original." + k),
          value: idx
        });
      }
      url_fields.push({
        ui: "export-manager-url-original-form",
        form: {
          label: $$("export.manager.form.url.original")
        },
        type: CUI.Select,
        tooltip: {
          text: $$("export.manager.form.url.original.versions")
        },
        name: "_url_original",
        options: opts
      });
      groups = Asset.getExportVersionGroups();
      for (group in groups) {
        defs = groups[group];
        opts = [
          {
            ui: "export-manager-url-no-option",
            text: $$("export.manager.form.url.no"),
            value: false
          }, {
            ui: "export-manager-url-yes-option",
            text: $$("export.manager.form.url.yes"),
            value: true
          }
        ];
        versions = (function() {
          var l, len1, results;
          results = [];
          for (l = 0, len1 = defs.length; l < len1; l++) {
            def = defs[l];
            results.push(Asset.getPrintSizeForVersion(def.__cls, def.version, true));
          }
          return results;
        })();
        if (ez5.version("6")) {
          groupLabelText = $$("fylr.produce.config.form.settings.group") + " " + $$("fylr.produce.config.form.settings.group." + group);
        } else {
          groupLabelText = $$("server.eas.rightsmanagement.group." + group);
        }
        url_fields.push({
          ui: "server-eas-rightsmanagement-" + group + "-group",
          form: {
            label: groupLabelText
          },
          type: CUI.Form,
          type: CUI.Select,
          tooltip: {
            text: versions.join(", ")
          },
          name: "_url_group_" + group,
          options: opts
        });
      }
      if ((ref1 = this.__urlForm) != null) {
        ref1.destroy();
      }
      this.__urlForm = new CUI.Form({
        fields: url_fields,
        onDataChanged: check_fields,
        data: this.data
      });
      block_urls = new CUI.Block({
        level: 2,
        padded: false,
        "class": "ez5-export-manager-block ez5-export-manager-block-urls",
        text: $$("export.manager.group.urls"),
        description: $$("export.manager.group.urls.description"),
        content: this.__urlForm.start()
      });
    }
    form_classes = CUI.dom.div("export-manager-form-classes");
    form_classes_table = CUI.dom.table();
    CUI.dom.append(form_classes, form_classes_table);
    ref2 = Asset.fileclasses(true);
    for (l = 0, len1 = ref2.length; l < len1; l++) {
      cls = ref2[l];
      if (!this._EASColumnsInfo.counts.by_class[cls]) {
        continue;
      }
      if (!this.data.classes[cls]) {
        this.data.classes[cls] = {
          _enabled: !this._export.getId() && !this.data.__isTemplate,
          _class: cls,
          _original: 0
        };
      }
      cls_tr = CUI.dom.tr("export-manager-form-cls");
      CUI.dom.append(form_classes_table, cls_tr);
      cb = new CUI.Checkbox({
        ui: "export.manager.group.filetypes." + cls,
        name: "_enabled",
        text: $$("server.eas.fileclass." + cls),
        onDataChanged: (function(_this) {
          return function() {
            return _this.setStateForm();
          };
        })(this),
        data: this.data.classes[cls]
      }).start();
      td = CUI.dom.append(CUI.dom.td(), cb.DOM);
      CUI.dom.append(cls_tr, td);
      this.data.classes[cls]._form_outer = cls_tr;
      this.data.classes[cls]._cb = cb;
      this.data.classes[cls]._form = (new CUI.Form({
        data: this.data.classes[cls],
        fields: this.getClassFields(cls, (function(_this) {
          return function() {
            return _this.setStateForm();
          };
        })(this))
      })).start();
      td = CUI.dom.append(CUI.dom.td(), this.data.classes[cls]._form.DOM);
      CUI.dom.append(cls_tr, td);
    }
    if (form_classes_table.children.length) {
      block_filetypes = new CUI.Block({
        padded: false,
        "class": "ez5-export-manager-block ez5-export-manager-block-filetypes",
        text: $$("export.manager.group.filetypes"),
        description: $$("export.manager.group.filetypes.description"),
        content: form_classes
      });
    }
    selectFieldsText = ez5.loca.text("export.manager.form.select_fields.button");
    onFieldSelectorClosed = (function(_this) {
      return function() {
        var field, ref3;
        changeButtonText();
        ref3 = _this.data.data_fields;
        for (k in ref3) {
          field = ref3[k];
          if (field._enabled && field._level > 0 && !field._topLevel && !field._sytemField) {
            if (!_this.data.merge_linked_objects || _this.data.merge_linked_objects === "none") {
              _this.data._merge_linked_objects = "all";
              advanced_form.getFieldsByName("_merge_linked_objects")[0].reload();
            }
            if (!_this.data.merge_max_depth || _this.data.merge_max_depth < 1) {
              _this.data.merge_max_depth = 1;
              advanced_form.getFieldsByName("merge_max_depth")[0].reload();
            }
            break;
          }
        }
        return check_fields();
      };
    })(this);
    changeButtonText = (function(_this) {
      return function() {
        var _, countEnabledFields, field, ref3;
        countEnabledFields = 0;
        ref3 = _this.data.data_fields;
        for (_ in ref3) {
          field = ref3[_];
          if (field._enabled) {
            countEnabledFields++;
          }
        }
        if (countEnabledFields > 0) {
          fieldSelectorButton.activate();
          fieldSelectorButton.getButton().setText($$("export.manager.form.select_fields.count_label", {
            count: countEnabledFields
          }));
        } else {
          fieldSelectorButton.deactivate();
          fieldSelectorButton.getButton().setText(selectFieldsText);
        }
      };
    })(this);
    fieldSelectorButton = new CUI.FormButton({
      tooltip: {
        text: ez5.loca.tooltip("export.manager.form.select_fields.button")
      },
      onClick: (function(_this) {
        return function() {
          return _this.showFieldSelector(onFieldSelectorClosed);
        };
      })(this)
    });
    fieldSelectorButton.start();
    changeButtonText();
    check_fields = (function(_this) {
      return function(d, f) {
        var field, len2, len3, len4, len5, len6, m, mergeLinkedObjectsSelect, mergeMaxDepthInput, n, o, p, q, ref3, ref4, ref5, ref6, ref7;
        if (_this.data.xml || _this.data.csv || _this.data.xlsx) {
          fieldSelectorButton.enable();
        } else {
          fieldSelectorButton.disable();
        }
        ref3 = ["_merge_linked_objects", "merge_max_depth", "all_languages"];
        for (m = 0, len2 = ref3.length; m < len2; m++) {
          k = ref3[m];
          field = data_form.getFieldsByName(k)[0] || advanced_form.getFieldsByName(k)[0];
          if (_this.data.csv || _this.data.xml || _this.data.json || _this.data.xlsx) {
            field.enable();
          } else {
            field.disable();
          }
        }
        ref4 = ["mapping", "xml_one_file_per_object", "include_parents"];
        for (n = 0, len3 = ref4.length; n < len3; n++) {
          k = ref4[n];
          if (_this.data.xml) {
            data_form.getFieldsByName(k)[0].enable();
          } else {
            data_form.getFieldsByName(k)[0].disable();
          }
        }
        ref5 = ["csv_hierarchy", "localized_column_names", "include_changelog"];
        for (o = 0, len4 = ref5.length; o < len4; o++) {
          k = ref5[o];
          if (_this.data.csv) {
            data_form.getFieldsByName(k)[0].enable();
          } else {
            data_form.getFieldsByName(k)[0].disable();
          }
        }
        ref6 = ["xlsx_hierarchy", "xlsx_localized_column_names", "xlsx_include_changelog", "xlsx_include_thumbnail"];
        for (p = 0, len5 = ref6.length; p < len5; p++) {
          k = ref6[p];
          if (_this.data.xlsx) {
            data_form.getFieldsByName(k)[0].enable();
          } else {
            data_form.getFieldsByName(k)[0].disable();
          }
        }
        ref7 = ["json_one_file_per_object"];
        for (q = 0, len6 = ref7.length; q < len6; q++) {
          k = ref7[q];
          if (_this.data.json) {
            data_form.getFieldsByName(k)[0].enable();
          } else {
            data_form.getFieldsByName(k)[0].disable();
          }
        }
        if (eas_form_fields) {
          if (_this.data._template === "custom") {
            advanced_form.getFieldsByName("_template_custom")[0].enable();
          } else {
            advanced_form.getFieldsByName("_template_custom")[0].disable();
          }
        }
        if (_this.data._batch_size === "custom") {
          advanced_form.getFieldsByName("_batch_size_custom")[0].enable();
        } else {
          advanced_form.getFieldsByName("_batch_size_custom")[0].disable();
        }
        if (_this.data.xml || _this.data.json || _this.data.csv || _this.data.xlsx) {
          mergeLinkedObjectsSelect = advanced_form.getFieldsByName("_merge_linked_objects")[0];
          mergeMaxDepthInput = advanced_form.getFieldsByName("merge_max_depth")[0];
          if (_this.data.mapping === "easydb_flat") {
            mergeLinkedObjectsSelect.disable();
            mergeLinkedObjectsSelect.deactivate();
          } else {
            mergeLinkedObjectsSelect.enable();
            if (_this.data._merge_linked_objects !== "none") {
              mergeMaxDepthInput.enable();
            }
          }
        }
        if ((f != null ? f.getName() : void 0) === "_export_addLinkedData") {
          return _this._exportManager.reloadExport();
        }
      };
    })(this);
    initMappingOpts = [
      {
        ui: "export-manager-xml-profile-easydb-option",
        text: $$("export.manager.xml_profile.easydb"),
        value: "easydb"
      }
    ];
    if (!ez5.version("6")) {
      initMappingOpts.push({
        ui: "export-manager-xml-profile-easydb-flat-option",
        text: $$("export.manager.xml_profile.easydb_flat"),
        value: "easydb_flat"
      });
    }
    mapping_opts = ez5.metadata.getMappingOpts(initMappingOpts, {
      xml_export: true
    });
    mapping_opts.push({
      divider: true
    });
    xslts = this.__getXSLTs();
    if (xslts.length > 0) {
      for (m = 0, len2 = xslts.length; m < len2; m++) {
        xslt = xslts[m];
        tt_txt = ez5.loca.getBestFrontendValue(xslt.description);
        if (!CUI.util.isEmpty(tt_txt)) {
          tooltip = {
            text: tt_txt
          };
        } else {
          tooltip = void 0;
        }
        mapping_opts.push({
          value: xslt,
          text: ez5.loca.getBestFrontendValue(xslt.displayname) || ((ref3 = xslt.xslt) != null ? ref3.original_filename : void 0),
          tooltip: tooltip
        });
      }
    } else {
      mapping_opts.push({
        label: new CUI.EmptyLabel({
          text: $$("export.manager.no_xslts")
        })
      });
    }
    csv_hierarchy_opts = [];
    csv_hierarchy_opts.push({
      text: $$("export.manager.form.csv.hierarchy.option.none"),
      value: null
    });
    ref4 = {
      'column': $$("export.manager.form.csv.hierarchy.option.column"),
      '>': '>',
      '/': '/'
    };
    for (k in ref4) {
      v = ref4[k];
      csv_hierarchy_opts.push({
        text: v,
        value: k
      });
    }
    changelog_opts = [
      {
        text: $$("export.manager.form.changelog.option.none"),
        value: null
      }, {
        text: $$("export.manager.form.changelog.option.without_user"),
        value: "without_user"
      }
    ];
    if (ez5.session.hasSystemRight("root", "frontend_features[changelog_with_user]")) {
      changelog_opts.push({
        text: $$("export.manager.form.changelog.option.with_user"),
        value: "with_user"
      });
    }
    form_fields = [
      {
        ui: "export-manager-form-csv-checkbox",
        type: CUI.Checkbox,
        form: {
          label: $$("export.manager.form.csv.label")
        },
        name: "csv",
        text: $$("export.manager.form.csv"),
        onDataChanged: function(data, field) {
          var batchSizeField, len3, n, ref5;
          data._batch_size = data.csv ? "unlimited" : "default";
          ref5 = advanced_form.getFieldsByName("_batch_size") || [];
          for (n = 0, len3 = ref5.length; n < len3; n++) {
            batchSizeField = ref5[n];
            batchSizeField.reload();
          }
        }
      }, {
        ui: "export-manager-form-csv-localized-column-names-checkbox",
        type: CUI.Checkbox,
        name: "localized_column_names",
        text: $$("export.manager.form.csv.localized_column_names.text"),
        hidden: !ez5.version("6")
      }, {
        ui: "export-manager-form-csv-include_changelog-select",
        type: CUI.Select,
        form: {
          label: $$("export.manager.form.csv.include_changelog.label")
        },
        name: "include_changelog",
        options: changelog_opts,
        hidden: !ez5.version("6") || !ez5.session.hasSystemRight("root", "frontend_features[changelog]")
      }, {
        ui: "export-manager-form-csv-hierarchy",
        type: CUI.Select,
        form: {
          label: $$("export.manager.form.csv.hierarchy.label"),
          hint: $$("export.manager.form.csv.hierarchy.hint")
        },
        name: "csv_hierarchy",
        options: csv_hierarchy_opts
      }, {
        ui: "export-manager-form-xlsx-checkbox",
        type: CUI.Checkbox,
        form: {
          label: $$("export.manager.form.xlsx.label")
        },
        name: "xlsx",
        text: $$("export.manager.form.xlsx"),
        hidden: !ez5.version("6"),
        onDataChanged: function(data, field) {
          var batchSizeField, len3, n, ref5;
          data._batch_size = data.xlsx ? "unlimited" : "default";
          ref5 = advanced_form.getFieldsByName("_batch_size") || [];
          for (n = 0, len3 = ref5.length; n < len3; n++) {
            batchSizeField = ref5[n];
            batchSizeField.reload();
          }
        }
      }, {
        ui: "export-manager-form-xlsx-localized-column-names-checkbox",
        type: CUI.Checkbox,
        name: "xlsx_localized_column_names",
        text: $$("export.manager.form.xlsx.localized_column_names.text"),
        hidden: !ez5.version("6")
      }, {
        ui: "export-manager-form-xlsx-include_changelog-select",
        type: CUI.Select,
        form: {
          label: $$("export.manager.form.xlsx.include_changelog.label")
        },
        name: "xlsx_include_changelog",
        options: changelog_opts,
        hidden: !ez5.version("6") || !ez5.session.hasSystemRight("root", "frontend_features[changelog]", "frontend_features[changelog_with_user]")
      }, {
        ui: "export-manager-form-xlsx-hierarchy",
        type: CUI.Select,
        form: {
          label: $$("export.manager.form.xlsx.hierarchy.label"),
          hint: $$("export.manager.form.xlsx.hierarchy.hint")
        },
        name: "xlsx_hierarchy",
        options: csv_hierarchy_opts,
        hidden: !ez5.version("6")
      }, {
        ui: "export-manager-form-xlsx-include_thumbnail-checkbox",
        type: CUI.Checkbox,
        name: "xlsx_include_thumbnail",
        text: $$("export.manager.form.xlsx.include_thumbnail.text"),
        hidden: !ez5.version("6")
      }, {
        ui: "export-manager-form-xml-checkbox",
        type: CUI.Checkbox,
        form: {
          label: $$("export.manager.form.xml.label")
        },
        name: "xml",
        text: $$("export.manager.form.xml")
      }, {
        ui: "export-manager-form-xml-one-file-per-object-checkbox",
        type: CUI.Checkbox,
        name: "xml_one_file_per_object",
        text: $$("export.manager.form.xml_one_file_per_object")
      }, {
        ui: "export-manager-form-include-parents",
        type: CUI.Checkbox,
        name: "include_parents",
        text: $$("export.manager.form.include_parents"),
        hidden: !ez5.version("6")
      }, {
        ui: "export-manager-form-xml-profile-select",
        type: CUI.Select,
        form: {
          hint: $$("export.manager.xml_profile.hint")
        },
        name: "mapping",
        options: mapping_opts
      }, {
        ui: "export-manager-form-json-checkbox",
        form: {
          label: $$("export.manager.form.json.label")
        },
        type: CUI.Checkbox,
        name: "json",
        text: $$("export.manager.form.json")
      }, {
        ui: "export-manager-form-json-one-file-per-object-checkbox",
        type: CUI.Checkbox,
        name: "json_one_file_per_object",
        text: $$("export.manager.form.json_one_file_per_object")
      }, {
        type: CUI.Checkbox,
        form: {
          label: $$("export.manager.form.csv.all_languages|label"),
          hint: $$("export.manager.form.csv.all_languages|hint")
        },
        name: "all_languages",
        text: $$("export.manager.form.csv.all_languages|text")
      }, {
        type: CUI.DataFieldProxy,
        form: {
          label: ez5.version("6") ? $$("export.manager.form.select_fields.fylr|label") : $$("export.manager.form.select_fields|label"),
          hint: $$("export.manager.form.select_fields|hint")
        },
        element: function() {
          return new CUI.HorizontalList({
            content: [fieldSelectorButton]
          });
        }
      }
    ];
    data_form = new CUI.Form({
      fields: form_fields,
      onDataChanged: check_fields,
      data: this.data
    });
    block_data = new CUI.Block({
      padded: false,
      "class": "ez5-export-manager-block ez5-export-manager-block-data",
      text: $$("export.manager.group.data"),
      content: data_form.start()
    });
    bs = ((ref5 = ez5.session.getDefaults().server.exporter) != null ? ref5.batch_size : void 0) || 100;
    advanced_fields = [
      {
        type: CUI.Form,
        form: {
          label: $$("export.manager.form.batch_size.label")
        },
        fields: [
          {
            ui: "export-manager-form-batch-size-default-checkbox",
            type: CUI.Checkbox,
            name: "_batch_size",
            value: "default",
            radio: "batch",
            text: $$("export.manager.form.batch_size.default", {
              batch_size: bs
            })
          }, {
            ui: "export-manager-form-batch-size-unlimited-checkbox",
            type: CUI.Checkbox,
            name: "_batch_size",
            value: "unlimited",
            radio: "batch",
            text: $$("export.manager.form.batch_size.unlimited")
          }, {
            type: CUI.Form,
            "class": "has-custom-checkbox",
            horizontal: true,
            fields: [
              {
                ui: "export-manager-form-batch-size-custom-checkbox",
                type: CUI.Checkbox,
                name: "_batch_size",
                value: "custom",
                radio: "batch"
              }, {
                ui: "export-manager-form-batch-size-custom-number-input",
                type: CUI.NumberInput,
                name: "_batch_size_custom",
                placeholder: $$("export.manager.form.placeholder.custom")
              }
            ]
          }
        ]
      }, eas_form_fields ? this._exportManager.getFilenameTemplateField() : void 0, {
        type: CUI.Select,
        name: "_merge_linked_objects",
        form: {
          label: $$("export.manager.form.merge_linked_objects.text")
        },
        text: $$("export.manager.form.merge_linked_objects.text"),
        disabled: this.data.mapping === "easydb_flat",
        options: [
          {
            text: $$("export.manager.form.merge_linked_objects.option.none"),
            value: "none"
          }, {
            text: $$("export.manager.form.merge_linked_objects.option.all"),
            value: "all"
          }, {
            text: $$("export.manager.form.merge_linked_objects.option.not_in_main_search"),
            value: "not_in_main_search"
          }, {
            text: ez5.version("6") ? $$("export.manager.form.merge_linked_objects.option.not_in_main_search_unless_reverse") : $$("export.manager.form.merge_linked_objects.option.not_in_main_search_and_reverse"),
            value: ez5.version("6") ? "not_in_main_search_unless_reverse" : "not_in_main_search_and_reverse"
          }
        ]
      }, {
        type: CUI.Select,
        name: "merge_max_depth",
        form: {
          label: $$("export.manager.form.merge_max_depth.label"),
          hint: $$("export.manager.form.merge_max_depth.hint")
        },
        options: (function() {
          var i, n;
          opts = [
            {
              text: $$("export.manager.form.merge_max_depth.option.none"),
              value: null
            }
          ];
          for (i = n = 1; n <= 9; i = ++n) {
            opts.push({
              text: "" + i,
              value: i
            });
          }
          return opts;
        })()
      }, {
        ui: "export-manager-form-export-no-linked-data-text-checkbox",
        type: CUI.Checkbox,
        name: "_export_addLinkedData",
        form: {
          label: $$("export.manager.form.export_addLinkedData.label")
        },
        text: $$("export.manager.form.export_addLinkedData.text")
      }, ez5.version("6.8") ? {
        ui: "export-manager-form-export-include-file-metadata",
        type: CUI.Checkbox,
        name: "_file_metadata",
        form: {
          label: $$("export.manager.form.export_file_metadata.label")
        },
        text: $$("export.manager.form.export_file_metadata.text")
      } : void 0, ez5.version("6") ? {
        ui: "export-manager-form-export-no-inherited-checkbox",
        type: CUI.Checkbox,
        name: "_no_inheritance",
        form: {
          label: $$("export.manager.form.export_no_inheritance.label")
        },
        text: $$("export.manager.form.export_no_inheritance.text")
      } : void 0, ez5.version("6") ? {
        ui: "export-manager-form-export-include-non-preferred",
        type: CUI.Checkbox,
        name: "_include_non_preferred",
        form: {
          label: $$("export.manager.form.include_non_preferred")
        },
        text: $$("export.manager.form.include_non_preferred.text")
      } : void 0, {
        ui: "export-manager-form-export-incremental-text-checkbox",
        type: CUI.Checkbox,
        name: "_export_incremental",
        form: {
          label: $$("export.manager.form.export_incremental.label")
        },
        text: $$("export.manager.form.export_incremental.text")
      }
    ];
    advanced_form = new CUI.Form({
      fields: advanced_fields,
      onDataChanged: check_fields,
      data: this.data
    });
    block_advanced = new CUI.Block({
      padded: false,
      "class": "ez5-export-manager-block ez5-export-manager-block-advanded",
      text: $$("export.manager.group.advanced"),
      content: advanced_form.start()
    });
    block_mask_filter = new CUI.Block({
      padded: false,
      text: $$("export.manager.easydb.group.mask_filter")
    });
    loadingLabel = new LocaLabel({
      loca_key: "export.manager.easydb.mask.loading",
      "class": "label-for-cui-form-block--has-checkbox"
    });
    block_mask_filter.setContent(loadingLabel);
    searchData = CUI.util.copyObject(this._export.getSearch(), true);
    if (!this.data.maskData) {
      this.data.maskData = {};
    }
    maskData = this.data.maskData;
    if (searchData.best_mask_filter === false) {
      mask = {};
      ref6 = searchData.search;
      for (n = 0, len3 = ref6.length; n < len3; n++) {
        _search = ref6[n];
        if (!_search.__mask_filter) {
          continue;
        }
        ref7 = _search.search;
        for (o = 0, len4 = ref7.length; o < len4; o++) {
          __search = ref7[o];
          mask[__search.search[0]["in"][0]] = __search.search[1]["in"][0];
          break;
        }
      }
      if (maskData.mask == null) {
        maskData.mask = mask;
      }
    }
    set_search_data = (function(_this) {
      return function() {
        var exportSearchData;
        exportSearchData = _this._export.getSearch();
        clean_search_data(exportSearchData);
        if (maskData.mask != null) {
          exportSearchData.best_mask_filter = false;
          if (!CUI.util.isEmpty(maskData.mask)) {
            return exportSearchData.search.push(MaskFieldSelector.getSearchFilter(maskData.mask));
          }
        } else {
          return delete exportSearchData.best_mask_filter;
        }
      };
    })(this);
    clean_search_data = (function(_this) {
      return function(_searchData) {
        return CUI.util.removeFromArray(null, _searchData.search, function(item) {
          return item.__mask_filter;
        });
      };
    })(this);
    clean_search_data(searchData);
    formOpts = {
      data: maskData,
      form: {
        checkbox: {
          text: $$("export.manager.easydb.group.mask_filter.checkbox")
        }
      }
    };
    MaskFieldSelector.getFormSelect(searchData, formOpts).done((function(_this) {
      return function(maskSelectForm) {
        var form;
        form = new CUI.Form({
          onDataChanged: function(ev, df) {
            set_search_data();
            if (search_data_json !== JSON.stringify(_this._export.getSearch())) {
              df.disable();
              _this._exportManager.reload({
                active_tab: "advanced"
              }).fail(function() {
                return df.enable();
              });
            }
          },
          fields: [maskSelectForm]
        });
        return block_mask_filter.setContent(form.start());
      };
    })(this)).fail(function() {
      var label;
      label = new CUI.EmptyLabel({
        text: $$("export.manager.easydb.error_loading_mask_filter"),
        "class": "label-for-cui-form-block--has-checkbox"
      });
      return block_mask_filter.setContent(label);
    });
    tabs = [];
    if (block_filetypes || block_fields) {
      tabs.push({
        ui: "export-manager-files-tab",
        text: $$('export.manager.tab.files'),
        name: "files",
        content: [
          new LocaLabel({
            appearance: 'secondary',
            multiline: true,
            markdown: true,
            loca_key: 'export.manager.tab.files.explain',
            "class": "export-manager-info-label"
          }), block_fields, block_filetypes, block_urls
        ]
      });
    }
    if (block_data) {
      tabs.push({
        ui: "export-manager-data-tab",
        text: $$('export.manager.tab.data'),
        name: "data",
        content: [
          new LocaLabel({
            appearance: 'secondary',
            multiline: true,
            markdown: true,
            loca_key: 'export.manager.tab.data.explain',
            "class": "export-manager-info-label"
          }), block_data
        ]
      });
    }
    if (block_advanced || block_mask_filter) {
      search_data_json = JSON.stringify(this._export.getSearch());
      tabs.push({
        ui: "export-manager-advanced-tab",
        text: $$('export.manager.tab.advanced'),
        name: "advanced",
        content: [
          new LocaLabel({
            appearance: 'secondary',
            multiline: true,
            markdown: true,
            loca_key: 'export.manager.tab.advanced.explain',
            "class": "export-manager-info-label"
          }), block_advanced, block_mask_filter
        ]
      });
    }
    check_fields();
    active_idx = 0;
    for (idx = p = 0, len5 = tabs.length; p < len5; idx = ++p) {
      tab = tabs[idx];
      if (tab.name === this._active_tab) {
        active_idx = idx;
        break;
      }
    }
    this.setStateForm();
    _templates = this.__getTemplatesTool();
    this.__tabs = new CUI.Tabs({
      padded: true,
      tabs: tabs,
      active_idx: active_idx,
      header_right: _templates
    });
    return this.__tabs;
  };

  ExportManagerEasydb.prototype.generateFieldsFormData = function(data) {
    var div;
    this.__fields_form = new FieldsForm({
      exportManagerEasydb: this,
      otm: this._EASColumnsInfo.otm,
      data: data,
      treeNodeClass: ExportManagerFieldTreeNode,
      acceptField: function(field, fieldsFormNodeFather) {
        if (field instanceof MaskSplitter) {
          return false;
        }
        if (field instanceof ReverseLinkedTable && !fieldsFormNodeFather && field.isHierarchical()) {
          return false;
        }
        return field.isVisible("export");
      },
      treeOpts: {
        "class": 'cui-lv--has-datafields',
        maximize: false,
        rowMove: false,
        cols: ["auto"]
      },
      headerNode: function() {
        var headerColumn, headerLabel1, headerLabel2, headerNode;
        headerLabel1 = new CUI.Label({
          text: $$("export.manager.select_fields.header.1")
        });
        headerLabel2 = new CUI.Label({
          text: $$("export.manager.select_fields.header.2")
        });
        headerColumn = {
          element: CUI.dom.table_one_row(CUI.dom.div(), headerLabel1, headerLabel2)
        };
        headerNode = new CUI.ListViewTreeHeaderNode({
          headers: [headerColumn],
          "class": "export-fields-form-header"
        });
        return headerNode;
      }
    });
    div = this.__fields_form.renderForm();
    this.__fields_form.open();
    return div;
  };

  ExportManagerEasydb.prototype.__getOriginalKeys = function(cls) {
    if (!cls || cls === "image") {
      return ["original", "current", "current+original"];
    } else {
      return ["original"];
    }
  };

  ExportManagerEasydb.prototype.getMapWithoutUnderscoreKeys = function(map) {
    var dt, field, k, ref, v;
    dt = {};
    for (k in map) {
      v = map[k];
      if (k.substr(0, 1) === "_") {
        continue;
      }
      field = (ref = map._form) != null ? ref.getFieldsByName(k)[0] : void 0;
      if (field != null ? field.isHidden() : void 0) {
        continue;
      }
      dt[k] = v;
    }
    return dt;
  };

  ExportManagerEasydb.prototype.__getVersionSaveData = function(cdata) {
    var cls, custom, j, key, len, metadata, ref, ref1, versions;
    cls = cdata._class;
    CUI.util.assert(cls, "ExportManager.__getVersionSaveData", "Class not set in cdata, unable to save.", {
      cdata: cdata
    });
    metadata = CUI.util.getIntOrString(cdata._metadata);
    versions = [];
    if (!CUI.util.isNull(cdata._original)) {
      ref = this.__getOriginalKeys(cls)[cdata._original].split(/\+/);
      for (j = 0, len = ref.length; j < len; j++) {
        key = ref[j];
        versions.push({
          type: key,
          metadata: metadata
        });
      }
    }
    if (!CUI.util.isNull(cdata._version)) {
      versions.push({
        type: "version",
        version: cdata._version,
        metadata: metadata
      });
    }
    if (cdata._custom) {
      custom = this.getMapWithoutUnderscoreKeys(cdata);
      if ((ref1 = cdata._value) != null ? ref1.transform.length : void 0) {
        custom.transform = CUI.util.copyObject(cdata._value.transform, true);
      }
      versions.push({
        type: "custom",
        metadata: metadata,
        custom: custom
      });
    }
    return versions;
  };

  ExportManagerEasydb.prototype.generateFieldsFormEAS = function() {
    var _field, _fields, blocks, field, get_field, j, l, len, len1, ot, ref, ref1;
    get_field = (function(_this) {
      return function(field) {
        var cbfn, cls, count, ctext, data, divFileTypes, ext, fname, j, len, ref, ref1, ref2;
        fname = field.fullName();
        if (!(cbfn = _this._EASColumnsInfo.counts.by_field_name[fname])) {
          return;
        }
        if (!_this.data.fields[fname]) {
          _this.data.fields[fname] = {
            _enabled: !_this._export.getId() && !_this.data.__isTemplate
          };
        }
        if (!_this.data.fields[fname]._counts_per_class) {
          _this.data.fields[fname]._counts_per_class = {};
        }
        data = _this.data.fields[fname];
        ctext = [];
        ref = Asset.fileclasses();
        for (j = 0, len = ref.length; j < len; j++) {
          cls = ref[j];
          if (data._counts_per_class[cls] === void 0) {
            data._counts_per_class[cls] = 0;
          }
          if (!((ref1 = cbfn[cls]) != null ? ref1.total : void 0)) {
            continue;
          }
          data._counts_per_class[cls] = data._counts_per_class[cls] + cbfn[cls].total;
          ref2 = cbfn[cls].by_extension;
          for (ext in ref2) {
            count = ref2[ext];
            ctext.push("<span class='ez5-count-filetype'>" + count + " × <span class=\"ez5-filetype\">" + ext + "</span></span>");
          }
        }
        divFileTypes = CUI.dom.div('ez5-filetypes');
        CUI.dom.append(divFileTypes, CUI.dom.htmlToNodes(ctext.join(", ")));
        return {
          ui: "export.manager.group.field." + (field.getMask().name()) + "." + (field.name()) + ".checkbox",
          type: CUI.Checkbox,
          name: "_enabled",
          content: divFileTypes,
          form: {
            label: field.fullNameLocalized()
          },
          onDataChanged: function() {
            _this.setStateForm();
          },
          data: data
        };
      };
    })(this);
    blocks = [];
    ref = this._EASColumnsInfo.otm.objecttypes;
    for (j = 0, len = ref.length; j < len; j++) {
      ot = ref[j];
      _fields = [];
      ref1 = ot.getEASFields();
      for (l = 0, len1 = ref1.length; l < len1; l++) {
        field = ref1[l];
        _field = get_field(field);
        if (!_field) {
          continue;
        }
        _fields.push(_field);
      }
      if (_fields.length) {
        blocks.push(new CUI.Block({
          level: 2,
          padded: false,
          text: ot.nameLocalized(),
          "class": "ez5-export-manager-block-fields-objecttype",
          content: new CUI.Form({
            fields: _fields
          }).start()
        }));
      }
    }
    if (blocks.length) {
      return blocks;
    } else {
      return null;
    }
  };

  ExportManagerEasydb.prototype.getClassFields = function(cls, data_changed, for_assets) {
    var custom_fields, f, field, fields, idx, j, k, key, l, len, len1, len2, len3, len4, localizeOptions, m, mf, n, name1, o, opt, options, ref, ref1, ref2, version_name, version_names, without_option;
    CUI.util.assert(cls, "ExportManager.getClassFields", "cls needs to be set", {
      cls: cls
    });
    fields = [];
    if (for_assets) {
      fields.push({
        type: CUI.Checkbox,
        form: {
          label: $$("export.manager.asset_custom_setting.label")
        },
        name: "_asset_custom_setting"
      });
    }
    options = [
      {
        ui: "export-manager-form-original-url-no-option",
        text: $$("export.manager.form.url.no"),
        value: null
      }
    ];
    ref = this.__getOriginalKeys(cls);
    for (idx = j = 0, len = ref.length; j < len; idx = ++j) {
      k = ref[idx];
      options.push({
        ui: "export-manager-form-original-" + k + "-option",
        text: $$("export.manager.original." + k),
        value: idx
      });
    }
    fields.push({
      ui: "export-manager-form-original-select",
      type: CUI.Select,
      name: "_original",
      form: {
        label: $$("export.manager.original.label")
      },
      options: options
    });
    version_names = Asset.getExportVersionNamesForClass(cls, false);
    if (version_names.length) {
      options = [
        {
          ui: "export-manager-form-version-url-no-option",
          text: $$("export.manager.form.url.no"),
          value: null
        }
      ];
      for (l = 0, len1 = version_names.length; l < len1; l++) {
        version_name = version_names[l];
        options.push({
          ui: "export-manager-form-version-" + version_name + "-option",
          value: version_name,
          text: Asset.getPrintSizeForVersion(cls, version_name)
        });
      }
      fields.push({
        ui: "export-manager-form-version-select",
        type: CUI.Select,
        name: "_version",
        form: {
          label: $$("export.manager.version.label")
        },
        options: options
      });
    }
    if (cls === "image" || cls === "audio" || cls === "video") {
      mf = this._exportManager.getMetadataField();
      if (mf) {
        fields.push(mf);
      }
    }
    custom_fields = typeof this[name1 = "getClassFields_" + cls] === "function" ? this[name1]() : void 0;
    if (custom_fields != null ? custom_fields.length : void 0) {
      for (m = 0, len2 = custom_fields.length; m < len2; m++) {
        field = custom_fields[m];
        key = (ref1 = field.form) != null ? ref1.csv_key : void 0;
        if (key) {
          field.form.label = $$("export.manager.form." + key);
        }
        localizeOptions = true;
        if (ez5.version("6.8") && field.name === "colorprofile") {
          localizeOptions = false;
          without_option = field.options.filter(function(opt) {
            return opt.value === '-';
          });
          if (without_option.length) {
            without_option[0].text = $$("export.manager.option.without_colorprofile");
          }
        }
        if (field.options && localizeOptions) {
          ref2 = field.options;
          for (n = 0, len3 = ref2.length; n < len3; n++) {
            opt = ref2[n];
            if (CUI.util.isEmpty(opt.text)) {
              opt.text = $$("export.manager.option." + opt.value);
            }
          }
        }
      }
      fields.push({
        ui: "export-manager-custom-checkbox",
        type: CUI.Checkbox,
        name: "_custom",
        form: {
          label: $$("export.manager.custom.label")
        }
      });
      fields.push.apply(fields, custom_fields);
    }
    for (o = 0, len4 = fields.length; o < len4; o++) {
      f = fields[o];
      f.onDataChanged = data_changed;
    }
    return fields;
  };

  ExportManagerEasydb.prototype.showFieldSelector = function(onClose) {
    var data_fields_copy, doneButton, fieldSelector, form_fields, hasChanges;
    data_fields_copy = CUI.util.copyObject(this.data.data_fields, true);
    form_fields = this.generateFieldsFormData(data_fields_copy);
    hasChanges = (function(_this) {
      return function() {
        var _, field;
        if (CUI.util.isEmpty(_this.data.data_fields)) {
          for (_ in data_fields_copy) {
            field = data_fields_copy[_];
            if (field._enabled) {
              return true;
            }
          }
          return false;
        }
        return !CUI.util.isEqual(data_fields_copy, _this.data.data_fields);
      };
    })(this);
    doneButton = new LocaButton({
      loca_key: "export.manager.field.selector.button.done",
      primary: true,
      disabled: true,
      onClick: (function(_this) {
        return function(ev) {
          var saved_data_fields;
          if (ev.hasModifierKey()) {
            saved_data_fields = _this.data.data_fields;
            _this.data.data_fields = data_fields_copy;
            console.debug(CUI.util.dump(_this.getExportData()));
            _this.data.data_fields = saved_data_fields;
            return;
          }
          _this.data.data_fields = data_fields_copy;
          if (typeof _this._onClose === "function") {
            _this._onClose();
          }
          return fieldSelector.destroy();
        };
      })(this)
    });
    CUI.Events.listen({
      type: "data-changed",
      node: form_fields,
      call: (function(_this) {
        return function() {
          if (!hasChanges()) {
            doneButton.disable();
            return;
          }
          if (_this.__fields_form.isValid()) {
            return doneButton.enable();
          } else {
            return doneButton.disable();
          }
        };
      })(this)
    });
    fieldSelector = new CUI.Modal({
      "class": "ez5-export-manager-field-selector",
      cancel: true,
      pane: {
        header_left: new LocaLabel({
          loca_key: "export.manager.form.select_fields|label"
        }),
        content: form_fields,
        footer_right: doneButton
      },
      onDestroy: (function(_this) {
        return function() {
          if (typeof onClose === "function") {
            onClose();
          }
        };
      })(this)
    });
    return fieldSelector.show();
  };

  ExportManagerEasydb.prototype.getClassFields_image = function() {
    var fields, getColorProfileOptions, getFormatsOptions, getQualityOptions, sizes;
    getColorProfileOptions = (function(_this) {
      return function() {
        var colorProfiles, j, len, opt, options, recipeParams, ref, ref1, ref2, ref3;
        options = [
          {
            text: $$("export.manager.option.keep"),
            value: ""
          }
        ];
        recipeParams = ((ref = ez5.session.config.eas._produce.recipes[0]) != null ? ref.Params : void 0) || ((ref1 = ez5.session.config.eas._produce.recipes[0]) != null ? ref1.params : void 0);
        colorProfiles = (recipeParams != null ? (ref2 = recipeParams.colorprofile) != null ? ref2.Options : void 0 : void 0) || (recipeParams != null ? (ref3 = recipeParams.colorprofile) != null ? ref3.options : void 0 : void 0);
        for (j = 0, len = colorProfiles.length; j < len; j++) {
          opt = colorProfiles[j];
          if (opt !== "") {
            options.push({
              value: opt
            });
          }
        }
        return options;
      };
    })(this);
    sizes = [
      {
        value: "keep"
      }
    ];
    sizes.push({
      value: "custom"
    });
    getFormatsOptions = function() {
      var formats;
      formats = [
        {
          value: "keep"
        }, {
          value: "jpeg"
        }, {
          value: "tiff"
        }, {
          value: "png"
        }, {
          value: "bmp"
        }
      ];
      if (ez5.version("6")) {
        formats.splice(1, 0, {
          value: "webp"
        });
      }
      return formats;
    };
    getQualityOptions = function() {
      var options;
      options = [
        {
          value: "small"
        }, {
          value: "medium"
        }, {
          value: ez5.version("6") ? "high" : "maximum"
        }
      ];
      if (ez5.version("6")) {
        options.splice(0, 0, {
          value: "",
          text: $$("export.manager.option.keep")
        });
      }
      return options;
    };
    fields = [
      {
        form: {
          label: $$("export.manager.form.watermark")
        },
        type: CUI.Checkbox,
        name: "watermark"
      }, {
        form: {
          csv_key: "format"
        },
        name: "format",
        type: CUI.Select,
        options: getFormatsOptions()
      }, {
        form: {
          csv_key: "quality"
        },
        name: ez5.version("6") ? "quality" : "jpeg_quality",
        type: CUI.Select,
        options: getQualityOptions()
      }, {
        form: {
          csv_key: "colorspace"
        },
        name: "colorspace",
        type: CUI.Select,
        options: [
          {
            value: "keep"
          }, {
            value: "rgb"
          }, {
            value: "cmyk"
          }, {
            value: "gray"
          }
        ]
      }, {
        form: {
          csv_key: "size"
        },
        name: "size",
        type: CUI.Select,
        options: sizes
      }, {
        form: {
          csv_key: "custom_size"
        },
        name: "custom_size",
        type: CUI.Select,
        options: [
          {
            value: "dimension_max"
          }, {
            value: "dimension_min"
          }, {
            value: "height"
          }, {
            value: "width"
          }, {
            value: "cover"
          }
        ]
      }, {
        form: {
          csv_key: "custom_size_pixel"
        },
        name: "custom_size_pixel",
        type: CUI.NumberInput
      }, {
        form: {
          csv_key: "custom_width_pixel"
        },
        name: "custom_width_pixel",
        type: CUI.NumberInput
      }, {
        form: {
          csv_key: "custom_height_pixel"
        },
        name: "custom_height_pixel",
        type: CUI.NumberInput
      }
    ];
    if (ez5.version("6")) {
      fields.push({
        form: {
          csv_key: "dpi"
        },
        name: "dpi",
        placeholder: $$("export.manager.form.dpi|placeholder"),
        type: CUI.NumberInput
      });
      fields.push({
        form: {
          csv_key: "colorprofile"
        },
        name: "colorprofile",
        type: CUI.Select,
        options: getColorProfileOptions()
      });
    }
    return fields;
  };

  ExportManagerEasydb.prototype.setStateForm = function() {
    var cls, cls_data, count, count_per_cls, j, len, ref, ref1, ref2, ref3, total;
    if ((ref = this.__urlForm) != null) {
      ref.disable();
    }
    count_per_cls = (function(_this) {
      return function(cls) {
        var count, fn, info, ref1, ref2;
        count = 0;
        ref1 = _this.data.fields;
        for (fn in ref1) {
          info = ref1[fn];
          if (info._enabled) {
            count = count + (((ref2 = info._counts_per_class) != null ? ref2[cls] : void 0) || 0);
          }
        }
        return count;
      };
    })(this);
    ref1 = Asset.fileclasses();
    for (j = 0, len = ref1.length; j < len; j++) {
      cls = ref1[j];
      if (!((ref2 = this.data.classes[cls]) != null ? ref2._form : void 0)) {
        continue;
      }
      cls_data = this.data.classes[cls];
      total = ((ref3 = this._EASColumnsInfo.counts.by_class[cls]) != null ? ref3.total : void 0) || 0;
      if (total === 0) {
        CUI.dom.hideElement(cls_data._form_outer);
        continue;
      }
      cls_data._class = cls;
      count = count_per_cls(cls);
      CUI.dom.showElement(cls_data._form_outer);
      if (cls_data._enabled && count > 0) {
        cls_data._form.show();
        this.setClassState(cls_data);
      } else {
        cls_data._form.hide();
      }
      if (count > 0) {
        cls_data._cb.enable();
        this.__urlForm.enable();
      } else {
        cls_data._cb.disable();
      }
    }
  };

  ExportManagerEasydb.prototype.setClassState = function(version_data) {
    var disable, f, form, j, l, len, len1, len2, len3, m, n, name1, opt, original, original_pulldown, ref, ref1, ref2, ref3, ref4, show, version, version_name, version_names, version_pulldown;
    form = version_data._form;
    show = ["_asset_custom_setting", "_version", "_original", "_custom", "_metadata"];
    disable = [];
    version_names = Asset.getExportVersionNamesForClass(version_data._class, false);
    if (typeof this[name1 = "setClassState_" + version_data._class] === "function") {
      this[name1](version_data, show, disable);
    }
    original_pulldown = form.getFieldsByName("_original")[0];
    if (!(version_data._version !== null || version_data._original !== null || version_data._custom)) {
      disable.push("_metadata");
    }
    version_pulldown = form.getFieldsByName("_version")[0];
    if (version_pulldown) {
      for (j = 0, len = version_names.length; j < len; j++) {
        version_name = version_names[j];
        ref = version_pulldown.getOptions();
        for (l = 0, len1 = ref.length; l < len1; l++) {
          opt = ref[l];
          if (opt.value !== version_name.value) {
            continue;
          }
          if (version_data._value) {
            version = version_data._value.versions[version_name.value];
            if (!version || version._not_allowed) {
              opt.disabled = true;
              opt.text = $$("tool.asset.download." + version_data._class + "." + version_name.value, ["[nicht verfügbar]"]);
            } else {
              opt.disabled = false;
              opt.text = $$("tool.asset.download." + version_data._class + "." + version_name.value, [Asset.getLabelForVersion(version)]);
            }
          } else {
            opt.disabled = false;
            opt.text = Asset.getPrintSizeForVersion(version_data._class, version_name);
          }
        }
      }
      original = (ref1 = version_data._value) != null ? (ref2 = ref1.versions) != null ? ref2.original : void 0 : void 0;
      ref3 = version_pulldown.getOptions();
      for (m = 0, len2 = ref3.length; m < len2; m++) {
        opt = ref3[m];
        if (opt.value !== 0) {
          continue;
        }
        if (original) {
          opt.text = $$("export.manager.version.current") + " " + Asset.getLabelForVersion(original);
        } else {
          opt.text = $$("export.manager.version.current");
        }
      }
      version_pulldown.displayValue();
    }
    if (version_data.hasOwnProperty("_asset_custom_setting")) {
      if (version_data._asset_custom_setting) {

      } else {
        show = ["_asset_custom_setting"];
      }
    }
    ref4 = form.getDataFields();
    for (n = 0, len3 = ref4.length; n < len3; n++) {
      f = ref4[n];
      if (show.indexOf(f.getName()) > -1) {
        f.show(true);
      } else {
        f.hide(true);
      }
      if (disable.indexOf(f.getName()) > -1) {
        f.disable();
      } else {
        f.enable();
      }
    }
  };

  ExportManagerEasydb.prototype.setClassState_image = function(data, show, disable) {
    var quality, ref;
    if ((ref = data._value) != null ? ref.transform.length : void 0) {
      disable.push("_asset_custom_setting");
      disable.push("_custom");
    }
    if (!data._custom) {
      return;
    }
    show.push("format");
    show.push("watermark");
    switch (data.format) {
      case "jpeg":
      case "webp":
        quality = ez5.version("6") ? "quality" : "jpeg_quality";
        show.push("colorspace", quality, "size");
        break;
      case "keep":
      case "tiff":
      case "png":
      case "bmp":
        show.push("colorspace", "size");
    }
    switch (data.size) {
      case "custom":
        if (show.indexOf("size") > -1) {
          show.push("custom_size");
        }
    }
    if (show.indexOf("custom_size") > -1) {
      switch (data.custom_size) {
        case "cover":
          show.push("custom_width_pixel", "custom_height_pixel");
          break;
        default:
          show.push("custom_size_pixel");
      }
    }
    if (ez5.version("6")) {
      show.push("dpi");
    }
    if (show.indexOf("colorspace") && ez5.version("6.8")) {
      show.push("colorprofile");
    }
  };

  ExportManagerEasydb.prototype.getClassFields_video = function() {
    return [];
  };

  ExportManagerEasydb.prototype.getClassFields_audio = function() {
    return [];
  };

  ExportManagerEasydb.prototype.getClassFields_office = function() {
    return [];
  };

  ExportManagerEasydb.prototype.setClassState_office = function(data, show) {
    if (!data._custom) {
      return;
    }
    return show.push("format");
  };

  ExportManagerEasydb.prototype.getClassFields_unknown = function() {
    return [];
  };

  ExportManagerEasydb.prototype.init = function(opts) {
    ExportManagerEasydb.__super__.init.call(this, opts);
    this.__active_tab = opts.active_tab;
    if (opts.reload) {
      return;
    }
    this.data = this.getFormData();
  };

  ExportManagerEasydb.prototype.deinit = function() {
    return CUI.util.removeFromArray(null, this._export.getSearch().search, function(search) {
      return search.__mask_filter;
    });
  };

  ExportManagerEasydb.prototype.getData = function() {
    return this.data;
  };

  ExportManagerEasydb.prototype.resetData = function() {
    return this.data = {};
  };

  ExportManagerEasydb.prototype.getFormData = function(opts) {
    var cdata, cls, data, dt, fdata, fname, group, groups, info, infos, j, l, len, len1, len2, len3, m, n, objecttype, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, searchObjecttypes, skipFieldsMap, version, versions, xslt;
    if (opts == null) {
      opts = {};
    }
    dt = {
      classes: {},
      fields: {},
      data_fields: {},
      objects: {},
      assets: {},
      name: "",
      __isTemplate: opts.apply_template,
      _template: "default",
      _template_custom: "",
      _batch_size: "default",
      _export_incremental: false,
      _batch_size_custom: null,
      _url_original: null,
      _export_addLinkedData: true,
      _no_inheritance: false,
      _file_metadata: false
    };
    if (ez5.version("6")) {
      dt.include_changelog = null;
      dt.xlsx = false;
      dt.xlsx_hierarchy = null;
      dt.xlsx_localized_column_names = false;
      dt.xlsx_include_changelog = null;
      dt.xlsx_include_thumbnail = false;
      dt._include_non_preferred = false;
    }
    groups = Asset.getExportVersionGroups();
    for (group in groups) {
      dt["_url_group_" + group] = false;
    }
    if (!this._export.getId() && !opts.apply_template) {
      return dt;
    }
    data = this._export.data;
    if (!CUI.util.isNull((ref = data["export"].produce_options) != null ? ref.addLinkedData : void 0)) {
      dt._export_addLinkedData = data["export"].produce_options.addLinkedData;
    }
    skipFieldsMap = false;
    if (opts.objecttypes) {
      searchObjecttypes = ((ref1 = data["export"].search) != null ? ref1.objecttypes : void 0) || [];
      ref2 = opts.objecttypes;
      for (j = 0, len = ref2.length; j < len; j++) {
        objecttype = ref2[j];
        if (searchObjecttypes.includes(objecttype)) {
          continue;
        }
        skipFieldsMap = true;
        break;
      }
    }
    if (!skipFieldsMap) {
      ref3 = data["export"].eas_fields;
      for (fname in ref3) {
        info = ref3[fname];
        if (info.files) {
          dt.fields[fname] = {
            _enabled: true
          };
        }
        if (info.include_non_preferred) {
          dt._include_non_preferred = true;
        }
        if (!((ref4 = info.data) != null ? ref4.length : void 0)) {
          continue;
        }
        dt._url_original = this.__findOriginalInVersions(info.data);
        ref5 = info.data;
        for (l = 0, len1 = ref5.length; l < len1; l++) {
          version = ref5[l];
          if (version.type === "version") {
            for (group in groups) {
              infos = groups[group];
              for (m = 0, len2 = infos.length; m < len2; m++) {
                info = infos[m];
                if (info.__full_version === version.version) {
                  dt["_url_group_" + group] = true;
                }
              }
            }
          }
        }
      }
      ref6 = data["export"].classes;
      for (cls in ref6) {
        versions = ref6[cls];
        cdata = this.__getMapFromVersions(versions);
        cdata._enabled = true;
        dt.classes[cls] = cdata;
      }
    }
    dt.all_languages = data["export"].all_languages || false;
    if (data["export"].xml) {
      dt.xml = true;
    }
    if (data["export"].xml_one_file_per_object) {
      dt.xml_one_file_per_object = true;
    }
    if (data["export"].include_parents) {
      dt.include_parents = true;
    }
    if (data["export"].json) {
      dt.json = true;
    }
    if (data["export"].json_one_file_per_object) {
      dt.json_one_file_per_object = true;
    }
    if (data["export"].xslt_xml_post_processing) {
      ref7 = this.__getXSLTs();
      for (n = 0, len3 = ref7.length; n < len3; n++) {
        xslt = ref7[n];
        if (xslt.xslt._id === data["export"].xslt_xml_post_processing._id) {
          dt.mapping = xslt;
        }
      }
    } else if (data["export"].mapping) {
      if (CUI.util.isString(data["export"].mapping)) {
        dt.mapping = parseInt(data["export"].mapping);
        if (isNaN(dt.mapping)) {
          dt.mapping = data["export"].mapping;
        }
      } else {
        dt.mapping = data["export"].mapping;
      }
    }
    if (data["export"].csv) {
      dt.csv = true;
      if (data["export"].csv.hierarchy) {
        dt.csv_hierarchy = data["export"].csv.hierarchy;
      }
      if (data["export"].csv.localized_column_names && ez5.version("6")) {
        dt.localized_column_names = data["export"].csv.localized_column_names;
      }
      if (data["export"].csv.include_changelog && ez5.version("6")) {
        if (CUI.util.isBoolean(data["export"].csv.include_changelog)) {
          if (data["export"].csv.include_changelog) {
            dt.include_changelog = "without_user";
          } else {
            dt.include_changelog = null;
          }
        } else if (CUI.util.isPlainObject(data["export"].csv.include_changelog)) {
          if (data["export"].csv.include_changelog.with_user && ez5.session.hasSystemRight("root", "frontend_features[changelog_with_user]")) {
            dt.include_changelog = "with_user";
          } else {
            dt.include_changelog = "without_user";
          }
        } else {
          dt.include_changelog = null;
        }
      }
    } else {
      dt.csv = false;
      dt.csv_hierarchy = null;
      if (ez5.version("6")) {
        dt.localized_column_names = null;
        dt.include_changelog = null;
      }
    }
    if (data["export"].xlsx && ez5.version("6")) {
      dt.xlsx = true;
      if (data["export"].xlsx.hierarchy) {
        dt.xlsx_hierarchy = data["export"].xlsx.hierarchy;
      }
      if (data["export"].xlsx.localized_column_names) {
        dt.xlsx_localized_column_names = data["export"].xlsx.localized_column_names;
      }
      if (data["export"].xlsx.include_changelog) {
        if (CUI.util.isBoolean(data["export"].xlsx.include_changelog)) {
          if (data["export"].xlsx.include_changelog) {
            dt.xlsx_include_changelog = "without_user";
          } else {
            dt.xlsx_include_changelog = null;
          }
        } else if (CUI.util.isPlainObject(data["export"].xlsx.include_changelog)) {
          if (data["export"].xlsx.include_changelog.with_user && ez5.session.hasSystemRight("root", "frontend_features[changelog_with_user]")) {
            dt.xlsx_include_changelog = "with_user";
          } else {
            dt.xlsx_include_changelog = "without_user";
          }
        } else {
          dt.xlsx_include_changelog = null;
        }
      }
      if (data["export"].xlsx.include_thumbnail) {
        dt.xlsx_include_thumbnail = data["export"].xlsx.include_thumbnail;
      }
    } else if (ez5.version("6")) {
      dt.xlsx = false;
      dt.xlsx_hierarchy = null;
      dt.xlsx_localized_column_names = false;
      dt.xlsx_include_changelog = null;
      dt.xlsx_include_thumbnail = false;
    }
    if (data["export"].batch_size === 0) {
      dt._batch_size = "unlimited";
    } else if (data["export"].batch_size > 0) {
      dt._batch_size = "custom";
      dt._batch_size_custom = data["export"].batch_size;
    }
    if (data["export"].type === "export_incremental") {
      dt._export_incremental = true;
    } else {
      dt._export_incremental = false;
    }
    if (data["export"].filename_original) {
      dt._template = "original";
    } else if (!CUI.util.isEmpty(data["export"].filename_template)) {
      dt._template = "custom";
      dt._template_custom = data["export"].filename_template;
    }
    dt.name = data["export"].name;
    if (!skipFieldsMap) {
      if (data["export"].fields) {
        ref8 = data["export"].fields;
        for (fname in ref8) {
          fdata = ref8[fname];
          dt.data_fields[fname] = fdata;
          fdata._enabled = true;
          if (fdata.versions) {
            fdata.version = fdata.versions[0];
            delete fdata.versions;
          }
        }
      }
    }
    if (CUI.util.isEmptyObject(data["export"].assets)) {
      dt.show_details = false;
    } else {
      dt.show_details = true;
      dt.assets = CUI.util.copyObject(data["export"].assets, true);
    }
    if (!data["export"].merge_linked_objects) {
      dt._merge_linked_objects = "none";
    } else {
      dt._merge_linked_objects = data["export"].merge_linked_objects;
    }
    if (data["export"].no_inheritance) {
      dt._no_inheritance = true;
    }
    if (data["export"].file_metadata) {
      dt._file_metadata = true;
    }
    dt.merge_max_depth = data["export"].merge_max_depth;
    dt.maskData = data["export"].maskData || {};
    return dt;
  };

  ExportManagerEasydb.prototype.getExportData = function() {
    var cdata, cls, dt, fdata, fname, group, groups, info, infos, j, key, l, len, len1, ref, ref1, ref2, ref3, sd, v, versions;
    sd = {
      classes: {},
      eas_fields: {},
      assets: {},
      search: {}
    };
    sd.maskData = this.data.maskData;
    ref = this.data.classes;
    for (cls in ref) {
      cdata = ref[cls];
      if (!cdata._enabled) {
        continue;
      }
      if (!sd.classes[cls]) {
        sd.classes[cls] = {};
      }
      cdata._class = cls;
      versions = this.__getVersionSaveData(cdata);
      sd.classes[cls] = versions;
    }
    ref1 = this.data.fields;
    for (fname in ref1) {
      fdata = ref1[fname];
      if (!fdata._enabled) {
        continue;
      }
      dt = [];
      if (this.data["_url_original"] !== null) {
        ref2 = this.__getOriginalKeys()[this.data["_url_original"]].split(/\+/);
        for (j = 0, len = ref2.length; j < len; j++) {
          key = ref2[j];
          dt.push({
            type: key,
            format: "short"
          });
        }
      }
      groups = Asset.getExportVersionGroups();
      for (group in groups) {
        infos = groups[group];
        if (!this.data["_url_group_" + group]) {
          continue;
        }
        for (l = 0, len1 = infos.length; l < len1; l++) {
          info = infos[l];
          dt.push({
            type: "version",
            format: "short",
            version: info.__full_version
          });
        }
      }
      sd.eas_fields[fname] = {
        files: true,
        data: dt
      };
      if (this.data._include_non_preferred) {
        sd.eas_fields[fname].include_non_preferred = true;
      }
    }
    sd.all_languages = this.data.all_languages || false;
    if (this.data.csv) {
      sd.csv = {
        delimiter: ";",
        quote: '"',
        escape: '"',
        use_bom: true,
        empty_columns: false
      };
      sd.csv.hierarchy = this.data.csv_hierarchy;
      if (ez5.version("6")) {
        sd.csv.localized_column_names = this.data.localized_column_names;
        switch (this.data.include_changelog) {
          case "with_user":
            sd.csv.include_changelog = {
              with_user: true
            };
            break;
          case "without_user":
            sd.csv.include_changelog = {};
            break;
          default:
            sd.csv.include_changelog = null;
        }
      }
    } else {
      sd.csv = false;
    }
    if (this.data.xlsx && ez5.version("6")) {
      sd.xlsx = {};
      sd.xlsx.hierarchy = this.data.xlsx_hierarchy;
      sd.xlsx.localized_column_names = this.data.xlsx_localized_column_names;
      switch (this.data.xlsx_include_changelog) {
        case "with_user":
          sd.xlsx.include_changelog = {
            with_user: true
          };
          break;
        case "without_user":
          sd.xlsx.include_changelog = {};
          break;
        default:
          sd.xlsx.include_changelog = null;
      }
      sd.xlsx.include_thumbnail = !!this.data.xlsx_include_thumbnail;
    } else {
      sd.xlsx = false;
    }
    sd.xml = !!this.data.xml;
    sd.xml_one_file_per_object = !!this.data.xml_one_file_per_object;
    sd.include_parents = !!this.data.include_parents;
    sd.json = !!this.data.json;
    sd.json_one_file_per_object = !!this.data.json_one_file_per_object;
    if (CUI.util.isPlainObject(this.data.mapping)) {
      sd.mapping = "easydb";
      sd.xslt_xml_post_processing = {
        _id: this.data.mapping.xslt._id
      };
    } else {
      sd.mapping = CUI.util.getIntOrString(this.data.mapping);
      sd.xslt_xml_post_processing = null;
    }
    if (!CUI.util.isEmpty(this.data.name)) {
      sd.name = this.data.name;
    }
    sd.batch_size = null;
    switch (this.data._batch_size) {
      case "unlimited":
        sd.batch_size = 0;
        sd.flat = true;
        break;
      case "custom":
        sd.batch_size = this.data._batch_size_custom;
        sd.flat = false;
        break;
      default:
        sd.flat = false;
    }
    if (this.data._export_incremental) {
      sd.type = "export_incremental";
    } else {
      sd.type = "export";
    }
    sd.filename_template = null;
    sd.filename_original = null;
    switch (this.data._template) {
      case "original":
        sd.filename_original = true;
        break;
      case "custom":
        sd.filename_template = this.data._template_custom;
    }
    sd.fields = {};
    ref3 = this.data.data_fields;
    for (fname in ref3) {
      fdata = ref3[fname];
      if (!fdata._enabled) {
        continue;
      }
      sd.fields[fname] = this.getMapWithoutUnderscoreKeys(fdata);
      if (v = sd.fields[fname].version) {
        delete sd.fields[fname].version;
        sd.fields[fname].versions = [v];
      }
    }
    if (CUI.util.isEmptyObject(sd.fields)) {
      sd.fields = null;
    }
    if (this.data.mapping === "easydb_flat") {
      sd.merge_linked_objects = "none";
    } else {
      sd.merge_linked_objects = this.data._merge_linked_objects;
    }
    sd.merge_max_depth = this.data.merge_max_depth;
    sd.no_inheritance = this.data._no_inheritance;
    sd.file_metadata = this.data._file_metadata;
    if (sd.produce_options == null) {
      sd.produce_options = {};
    }
    sd.produce_options.addLinkedData = this.data._export_addLinkedData;
    return sd;
  };

  ExportManagerEasydb.prototype.__findOriginalInVersions = function(versions) {
    var found, idx, j, len, ref, version;
    found = [];
    for (j = 0, len = versions.length; j < len; j++) {
      version = versions[j];
      if ((ref = version.type) === "original" || ref === "current") {
        found.push(version.type);
      }
    }
    if (found.length === 0) {
      return null;
    }
    found.sort();
    idx = CUI.util.idxInArray(found.join("+"), this.__getOriginalKeys());
    CUI.util.assert(idx > -1, "ExportManager.__findOriginalInVersions: could not match original / current version data");
    return idx;
  };

  ExportManagerEasydb.prototype.__getMapFromVersions = function(versions) {
    var _k, cdata, found, j, k, l, len, len1, len2, len3, m, n, ref, ref1, ref2, ref3, v, version;
    if (versions == null) {
      versions = [];
    }
    cdata = {};
    ref = ["metadata"];
    for (j = 0, len = ref.length; j < len; j++) {
      k = ref[j];
      _k = "_" + k;
      for (l = 0, len1 = versions.length; l < len1; l++) {
        version = versions[l];
        if (!version[k]) {
          continue;
        }
        CUI.util.assert(!cdata[_k] || cdata[_k] === version[k], "ExportManager.__getMapFromVersions: \"" + k + "\" mismatch in versions.");
        cdata[_k] = version[k];
      }
    }
    cdata._original = this.__findOriginalInVersions(versions);
    found = [];
    for (m = 0, len2 = versions.length; m < len2; m++) {
      version = versions[m];
      if ((ref1 = version.type) === "version") {
        found.push(version.version);
      }
    }
    if (found.length > 0) {
      CUI.util.assert(found.length === 1, "ExportManagerEasydb.initData: could not match second type == version");
      cdata._version = found[0];
    }
    for (n = 0, len3 = versions.length; n < len3; n++) {
      version = versions[n];
      if ((ref2 = version.type) === "custom") {
        CUI.util.assert(!cdata._custom, "ExportManagerEasydb.initData: Only one \"custom\" version is supported.");
        cdata._custom = true;
        ref3 = version.custom;
        for (k in ref3) {
          v = ref3[k];
          cdata[k] = v;
        }
      }
    }
    return cdata;
  };

  ExportManagerEasydb.prototype.__getXSLTs = function() {
    var j, len, ref, ref1, ref2, xslt, xslts;
    xslts = [];
    ref1 = ((ref = ez5.session.getBaseConfig()["export"]) != null ? ref.xslts : void 0) || [];
    for (j = 0, len = ref1.length; j < len; j++) {
      xslt = ref1[j];
      if (((ref2 = xslt.xslt) != null ? ref2._id : void 0) > 1) {
        xslts.push(xslt);
      }
    }
    return xslts;
  };

  ExportManagerEasydb.prototype.saveAllowed = function() {
    var cls, fn, info, ref, ref1, show;
    show = this.data.xml || this.data.csv || this.data.xlsx || this.data.json;
    if (!show) {
      ref = this.data.fields;
      for (fn in ref) {
        info = ref[fn];
        if (info._enabled) {
          show = true;
          break;
        }
      }
      if (!show) {
        return false;
      }
      show = false;
      ref1 = this.data.classes;
      for (cls in ref1) {
        info = ref1[cls];
        if (!info._enabled) {
          continue;
        }
        if (!CUI.util.isNull(info._original) || !CUI.util.isNull(info._version) || info._custom) {
          show = true;
          break;
        }
      }
    }
    if (!show) {
      return false;
    } else {
      return true;
    }
  };

  ExportManagerEasydb.prototype.__getTemplatesVersion = function() {
    return 2;
  };

  ExportManagerEasydb.prototype.__getTemplatesPrefKey = function() {
    return "export.templates";
  };

  ExportManagerEasydb.prototype.__openApplyTemplateConfirmation = function(template) {
    new CUI.ConfirmationChoice({
      text: $$("export.template.apply.confirm.msg.md", {
        name: template.name
      }),
      markdown: true,
      choices: [
        {
          cancel: true,
          text: $$("export.template.apply.confirm.cancel")
        }, {
          _value: "replace",
          text: $$("export.template.apply.confirm.replace"),
          primary: true
        }
      ]
    }).open().done((function(_this) {
      return function() {
        _this.__applyTemplate(template);
        _this._exportManager.renderContent({
          reload: true
        });
      };
    })(this));
  };

  ExportManagerEasydb.prototype.__applyTemplate = function(template) {
    var currentExportData;
    template = CUI.util.copyObject(template, true);
    currentExportData = this._export.getExportData();
    template.data.search = currentExportData.search;
    this._export.setExportData(template.data);
    this.data = this.getFormData({
      apply_template: true,
      objecttypes: template.objecttypes
    });
  };

  ExportManagerEasydb.prototype.__saveNewTemplate = function() {
    var canShareTemplates, deferred, e, exportData, saveButton, saveTemplate, saveTemplateModal, templateData;
    try {
      exportData = this._exportManager.getExportData();
    } catch (error) {
      e = error;
      CUI.problem({
        text: $$("export.template.save_as_template.invalid")
      });
      return CUI.rejectedPromise();
    }
    if (!ez5.version("6")) {
      return this.__saveNewTemplateSimple(exportData);
    }
    deferred = new CUI.Deferred();
    deferred.always((function(_this) {
      return function() {
        return saveTemplateModal.destroy();
      };
    })(this));
    templateData = {};
    canShareTemplates = ez5.groupManager.getGroups().some(function(group) {
      if (group.isWritable()) {
        return true;
      }
    });
    saveTemplate = (function(_this) {
      return function(ev) {
        var group, group_id, ref, templates;
        if (!templateData.shared_template) {
          templates = _this.__getTemplates();
          templates.version = _this.__getTemplatesVersion();
          templates.templates.push({
            name: templateData.name.trim(),
            data: exportData,
            objecttypes: (ref = exportData.search) != null ? ref.objecttypes : void 0,
            comment: templateData.comment || "",
            create_date: new Date().toISOString()
          });
          exportData.search = {};
          return ez5.session.savePref(_this.__getTemplatesPrefKey(), templates).done(deferred.resolve).fail(deferred.reject);
        } else {
          group_id = templateData.shared_template_group.group._id;
          group = ez5.groupManager.getGroupById(group_id);
          if (group.isWritable()) {
            return group.load().done(function() {
              var base, base1, base2, exportDataCopy, groupData, ref1;
              groupData = group.getData();
              if ((base = groupData.group).frontend_prefs == null) {
                base.frontend_prefs = {};
              }
              if ((base1 = groupData.group.frontend_prefs).webfrontend == null) {
                base1.webfrontend = {};
              }
              if ((base2 = groupData.group.frontend_prefs.webfrontend).shared_export_templates == null) {
                base2.shared_export_templates = [];
              }
              exportDataCopy = CUI.util.copyObject(exportData, true);
              exportDataCopy.search = {};
              groupData.group.frontend_prefs.webfrontend.shared_export_templates.push({
                name: templateData.name.trim(),
                data: exportDataCopy,
                objecttypes: (ref1 = exportData.search) != null ? ref1.objecttypes : void 0,
                user: ez5.session.getUser().getId(),
                create_date: new Date().toISOString(),
                comment: templateData.comment || ""
              });
              return group.headlessSave(ev).done(deferred.resolve).fail(deferred.reject);
            }).fail(deferred.reject);
          } else {
            return deferred.reject();
          }
        }
      };
    })(this);
    saveButton = new LocaButton({
      loca_key: "export.template.save_as_template.confirm.save",
      disabled: true,
      primary: true,
      onClick: (function(_this) {
        return function(ev) {
          return saveTemplate(ev);
        };
      })(this)
    });
    saveTemplateModal = new CUI.Modal({
      cancel: true,
      "class": "ez5-export-templates-save-modal",
      size: "s",
      onCancel: (function(_this) {
        return function() {
          deferred.reject();
        };
      })(this),
      pane: {
        title: $$("export.template.save_as_template.confirm.msg"),
        footer_right: saveButton,
        content: (function(_this) {
          return function() {
            return new CUI.Form({
              data: templateData,
              fields: [
                {
                  type: CUI.Input,
                  name: "name",
                  form: {
                    label: $$("export.template.save_as_template.name.label")
                  },
                  placeholder: $$("export.template.save_as_template.name.placeholder"),
                  checkInput: function(name) {
                    name = name.trim();
                    return !CUI.util.isEmpty(name);
                  }
                }, {
                  type: CUI.Input,
                  textarea: true,
                  form: {
                    label: $$("export.template.save_as_template.comment.label")
                  },
                  name: "comment",
                  placeholder: $$("export.template.save_as_template.comment.placeholder")
                }, canShareTemplates ? {
                  type: CUI.Checkbox,
                  name: "shared_template",
                  form: {
                    label: $$("export.template.save_as_template.shared")
                  },
                  onDataChanged: function(data, field) {
                    var groupField, ref;
                    groupField = (ref = field.getForm().getFieldsByName("shared_template_group")) != null ? ref[0] : void 0;
                    if (data.shared_template && groupField) {
                      groupField.show(true);
                    } else {
                      groupField.hide(true);
                    }
                    return CUI.Events.trigger({
                      type: "content-resize",
                      node: saveTemplateModal
                    });
                  }
                } : void 0, canShareTemplates ? {
                  type: UserGroupSelector,
                  form: {
                    label: $$("export.template.save_as_template.shared_group")
                  },
                  name: "shared_template_group",
                  generate_rights: true,
                  aclWhoManager: new AclWhoManager({
                    filter_system_groups: false,
                    who_filter: ["group"]
                  }),
                  filterData: function(group) {
                    var ref;
                    group = (ref = AclWho.newInstance(group)) != null ? ref.group : void 0;
                    if (group != null ? group.isWritable() : void 0) {
                      return true;
                    }
                    return false;
                  },
                  hidden: templateData.shared_template !== true
                } : void 0
              ],
              onDataChanged: function(data, input) {
                var nameInput, ref;
                nameInput = (ref = input.getForm()) != null ? ref.getFieldsByName("name")[0] : void 0;
                if (nameInput.getInputState() === "valid") {
                  return saveButton.enable();
                } else {
                  return saveButton.disable();
                }
              }
            }).start();
          };
        })(this)
      }
    });
    saveTemplateModal.show();
    return deferred.promise();
  };

  ExportManagerEasydb.prototype.__saveNewTemplateSimple = function(exportData) {
    var deferred;
    deferred = new CUI.Deferred();
    CUI.prompt({
      text: $$("export.template.save_as_template.confirm.msg"),
      button_text_ok: $$("export.template.save_as_template.confirm.save"),
      button_text_cancel: $$("export.template.save_as_template.confirm.cancel")
    }).done((function(_this) {
      return function(name) {
        var ref, templates;
        templates = _this.__getTemplates();
        templates.version = _this.__getTemplatesVersion();
        templates.templates.push({
          name: name.trim(),
          data: exportData,
          objecttypes: (ref = exportData.search) != null ? ref.objecttypes : void 0
        });
        exportData.search = {};
        return ez5.session.savePref(_this.__getTemplatesPrefKey(), templates).done(deferred.resolve).fail(deferred.reject);
      };
    })(this)).fail(deferred.reject);
    return deferred.promise();
  };

  ExportManagerEasydb.prototype.__customizeTemplates = function(templates) {
    var check_status, data, deferred, group_id, group_templates, init_data, init_data_shared, j, len, modal, ref, saveButton, save_shared_templates, shared_templates, template, templatesByName;
    if (!ez5.version("6")) {
      return this.__customizeTemplatesSimple(templates);
    }
    shared_templates = this.__getSharedTemplates(true);
    data = {
      templates: []
    };
    templatesByName = {};
    ref = templates.templates;
    for (j = 0, len = ref.length; j < len; j++) {
      template = ref[j];
      templatesByName[template.name] = template;
      data.templates.push({
        name: template.name,
        originalName: template.name
      });
    }
    init_data = JSON.stringify(data);
    init_data_shared = {};
    for (group_id in shared_templates) {
      group_templates = shared_templates[group_id];
      init_data_shared[group_id] = JSON.stringify(group_templates);
    }
    deferred = new CUI.Deferred();
    check_status = (function(_this) {
      return function() {
        var check_shared;
        check_shared = function() {
          for (group_id in shared_templates) {
            group_templates = shared_templates[group_id];
            if (init_data_shared[group_id] !== JSON.stringify(group_templates)) {
              return true;
            }
          }
        };
        if (init_data !== JSON.stringify(data) || check_shared()) {
          saveButton.enable();
          return true;
        } else {
          saveButton.disable();
        }
        return false;
      };
    })(this);
    save_shared_templates = (function(_this) {
      return function(ev) {
        var changed_groups, gdfr, group, promises;
        promises = [];
        changed_groups = {};
        for (group_id in shared_templates) {
          group_templates = shared_templates[group_id];
          if (init_data_shared[group_id] !== JSON.stringify(group_templates)) {
            changed_groups[group_id] = group_templates;
          }
        }
        for (group_id in changed_groups) {
          group_templates = changed_groups[group_id];
          gdfr = new CUI.Deferred();
          group = ez5.groupManager.getGroupById(parseInt(group_id));
          if (group.isWritable()) {
            group.load().done(function() {
              var groupData;
              groupData = group.getData();
              groupData.group.frontend_prefs.webfrontend.shared_export_templates = group_templates;
              return group.headlessSave(ev).done(gdfr.resolve).fail(gdfr.reject);
            }).fail(gdfr.reject);
          }
          promises.push(gdfr.promise());
        }
        return promises;
      };
    })(this);
    saveButton = new LocaButton({
      loca_key: "export.templates.customize.save",
      disabled: true,
      primary: true,
      onClick: (function(_this) {
        return function(ev) {
          var _template, l, len1, promises, ref1, shared_promises;
          saveButton.disable();
          templates.templates = [];
          templates.version = _this.__getTemplatesVersion();
          ref1 = data.templates;
          for (l = 0, len1 = ref1.length; l < len1; l++) {
            template = ref1[l];
            _template = templatesByName[template.originalName];
            _template.name = template.name;
            templates.templates.push(_template);
          }
          promises = [];
          promises.push(ez5.session.savePref(_this.__getTemplatesPrefKey(), templates, true));
          shared_promises = save_shared_templates(ev) || [];
          promises = promises.concat(shared_promises);
          return CUI.whenAll(promises).done(function() {
            modal.destroy();
            return deferred.resolve();
          }).fail(function() {
            return saveButton.enable();
          });
        };
      })(this)
    });
    modal = new CUI.Modal({
      cancel: true,
      "class": "export-manager-template-customize-modal",
      onCancel: (function(_this) {
        return function() {
          if (!check_status()) {
            return;
          }
          return CUI.confirm({
            text: $$("export.templates.customize.confirm_unsaved")
          }).done(function() {
            return deferred.reject();
          });
        };
      })(this),
      pane: {
        title: $$("export.templates.customize.title"),
        footer_right: saveButton,
        content: (function(_this) {
          return function() {
            var getOutputTemplateFields, getRowEditButton, tabs, tabsPanel, userTemplatesDt;
            getRowEditButton = function(show_user) {
              if (show_user == null) {
                show_user = false;
              }
              return new LocaButton({
                icon: "fa-pencil",
                onClick: function(ev, btn) {
                  var dt, editPopover, original_data, rows, selected_data;
                  dt = btn._data_table;
                  if (!dt) {
                    return;
                  }
                  rows = dt.listView.getSelectedRows();
                  if (rows.length === 0) {
                    return;
                  }
                  selected_data = rows[0].getData();
                  original_data = CUI.util.copyObject(selected_data, true);
                  editPopover = new CUI.Modal({
                    cancel: true,
                    onCancel: function() {
                      return CUI.confirm({
                        text: $$("export.templates.customize.confirm_unsaved")
                      }).done(function() {
                        Object.assign(selected_data, original_data);
                        return editPopover.destroy();
                      });
                    },
                    pane: {
                      title: $$("export.templates.customize.edit.title"),
                      padded: true,
                      footer_right: [
                        new LocaButton({
                          loca_key: "export.templates.customize.save",
                          primary: true,
                          onClick: function(ev) {
                            CUI.Events.trigger({
                              type: "data-changed",
                              node: dt.listView
                            });
                            check_status();
                            dt.loadPage();
                            return editPopover.destroy();
                          }
                        })
                      ],
                      content: function() {
                        return new CUI.Form({
                          data: selected_data,
                          fields: [
                            {
                              type: CUI.Input,
                              name: "name",
                              form: {
                                label: $$("export.template.save_as_template.name.label")
                              }
                            }, {
                              type: CUI.Output,
                              name: "create_date",
                              form: {
                                label: $$("export.templates.customize.data_table.create_date")
                              },
                              getValue: function(value) {
                                return ez5.format_date_and_time(value);
                              }
                            }, show_user ? {
                              type: CUI.Output,
                              name: "user",
                              form: {
                                label: $$("export.templates.customize.data_table.user")
                              },
                              getValue: function(value) {
                                return value;
                              }
                            } : void 0, {
                              type: CUI.Input,
                              name: "comment",
                              form: {
                                label: $$("export.template.save_as_template.comment.label")
                              },
                              textarea: true
                            }
                          ]
                        }).start();
                      }
                    }
                  });
                  return editPopover.show();
                }
              });
            };
            getOutputTemplateFields = function() {
              return [
                {
                  type: CUI.Output,
                  name: "name",
                  form: {
                    label: $$("export.template.save_as_template.name.label")
                  }
                }, {
                  type: CUI.Output,
                  name: "comment",
                  form: {
                    label: $$("export.template.save_as_template.comment.label"),
                    column: "maximize"
                  }
                }, {
                  type: CUI.Output,
                  name: "create_date",
                  form: {
                    label: $$("export.templates.customize.data_table.create_date")
                  },
                  getValue: function(value) {
                    return ez5.format_date_and_time(value);
                  }
                }
              ];
            };
            userTemplatesDt = new CUI.DataTable({
              data: data,
              name: "templates",
              rowMove: true,
              new_rows: "remove_only",
              buttons: [getRowEditButton(false)],
              onDataChanged: function() {
                return check_status();
              },
              fields: getOutputTemplateFields()
            });
            tabs = [];
            tabs.push({
              name: "user-templates",
              text: $$("export.templates.customize.user_templates_tab"),
              content: function() {
                return userTemplatesDt.start();
              }
            });
            if (!CUI.util.isEmpty(shared_templates)) {
              tabs.push({
                name: "shared-templates",
                text: $$("export.templates.customize.shared_templates_tab"),
                content: function() {
                  var fn1, panels;
                  panels = [];
                  fn1 = function(group_id) {
                    var panel, sharedDt;
                    sharedDt = new CUI.DataTable({
                      data: shared_templates,
                      name: group_id,
                      rowMove: true,
                      new_rows: "remove_only",
                      buttons: [getRowEditButton(true)],
                      onBeforeRowRemove: function(data, ev) {
                        return CUI.confirm({
                          text: $$("export.templates.customize.confirm_remove_shared")
                        });
                      },
                      onDataChanged: function() {
                        return check_status();
                      },
                      fields: getOutputTemplateFields()
                    });
                    panel = new CUI.Panel({
                      text: ez5.groupManager.getGroupById(parseInt(group_id)).getDisplayText(),
                      radio: true,
                      closed: true,
                      maximize_horizontal: true,
                      content: function() {
                        return sharedDt.start();
                      }
                    });
                    return panels.push(panel);
                  };
                  for (group_id in shared_templates) {
                    group_templates = shared_templates[group_id];
                    fn1(group_id);
                  }
                  return new CUI.VerticalList({
                    content: panels,
                    maximize: true
                  });
                }
              });
            }
            tabsPanel = new CUI.Tabs({
              tabs: tabs,
              maximize: true
            });
            return tabsPanel;
          };
        })(this)
      }
    }).show();
    return deferred.promise();
  };

  ExportManagerEasydb.prototype.__customizeTemplatesSimple = function(templates) {
    var data, deferred, init_data, j, len, modal, ref, saveButton, template, templatesByName;
    data = {
      templates: []
    };
    templatesByName = {};
    ref = templates.templates;
    for (j = 0, len = ref.length; j < len; j++) {
      template = ref[j];
      templatesByName[template.name] = template;
      data.templates.push({
        name: template.name,
        originalName: template.name
      });
    }
    init_data = JSON.stringify(data);
    saveButton = new LocaButton({
      loca_key: "export.templates.customize.save",
      disabled: true,
      onClick: (function(_this) {
        return function() {
          var _template, l, len1, ref1;
          saveButton.disable();
          templates.templates = [];
          templates.version = _this.__getTemplatesVersion();
          ref1 = data.templates;
          for (l = 0, len1 = ref1.length; l < len1; l++) {
            template = ref1[l];
            _template = templatesByName[template.originalName];
            _template.name = template.name;
            templates.templates.push(_template);
          }
          return ez5.session.savePref(_this.__getTemplatesPrefKey(), templates).done(function() {
            modal.destroy();
            return deferred.resolve();
          }).fail(function() {
            return saveButton.enable();
          });
        };
      })(this)
    });
    deferred = new CUI.Deferred();
    modal = new CUI.Modal({
      cancel: true,
      onCancel: (function(_this) {
        return function() {
          if (init_data === JSON.stringify(data)) {
            return;
          }
          return CUI.confirm({
            text: $$("export.templates.customize.confirm_unsaved")
          }).done(function() {
            return deferred.reject();
          });
        };
      })(this),
      pane: {
        title: $$("export.templates.customize.title"),
        footer_right: saveButton,
        content: (function(_this) {
          return function() {
            var dataTable;
            dataTable = new CUI.DataTable({
              no_header: true,
              data: data,
              name: "templates",
              rowMove: true,
              new_rows: "remove_only",
              onDataChanged: function() {
                if (init_data === JSON.stringify(data)) {
                  return saveButton.disable();
                } else {
                  return saveButton.enable();
                }
              },
              fields: [
                {
                  type: CUI.Input,
                  name: "name"
                }
              ]
            });
            dataTable.start();
            return dataTable;
          };
        })(this)
      }
    }).show();
    return deferred.promise();
  };

  ExportManagerEasydb.prototype.__getTemplates = function() {
    var templates;
    templates = CUI.util.copyObject(ez5.session.getPref(this.__getTemplatesPrefKey()), true);
    if (!templates) {
      return;
    }
    if (!templates.version || templates.version < this.__getTemplatesVersion()) {
      templates.templates = [];
    }
    return templates;
  };

  ExportManagerEasydb.prototype.__getSharedTemplates = function(onlyWritable) {
    var group, groupData, group_full_data, groups, j, len, ref, ref1, result, templates;
    if (onlyWritable == null) {
      onlyWritable = false;
    }
    result = {};
    if (ez5.session.hasSystemRight("root")) {
      groups = ez5.groupManager.getGroups();
    } else {
      groups = ez5.session.getGroups() || [];
    }
    for (j = 0, len = groups.length; j < len; j++) {
      group = groups[j];
      if (onlyWritable && !ez5.session.hasSystemRight("root")) {
        if (group instanceof SystemGroup) {
          group_full_data = ez5.groupManager.getGroupById(group.getId());
          if (!(group_full_data != null ? group_full_data.isWritable() : void 0)) {
            continue;
          }
        } else if (!group.isWritable()) {
          continue;
        }
      }
      groupData = group.getData();
      templates = ((ref = groupData.group.frontend_prefs) != null ? (ref1 = ref.webfrontend) != null ? ref1.shared_export_templates : void 0 : void 0) || [];
      if (templates.length > 0) {
        result[group.id || group.getId()] = CUI.util.copyObject(templates, true);
      }
    }
    return result;
  };

  ExportManagerEasydb.prototype.__findGroupById = function(group_id) {
    var group, groups, j, len;
    if (ez5.session.hasSystemRight("root")) {
      groups = ez5.groupManager.getGroups();
    } else {
      groups = ez5.session.getGroups();
    }
    for (j = 0, len = groups.length; j < len; j++) {
      group = groups[j];
      if (group.getId() === group_id) {
        return group;
      }
    }
    return null;
  };

  ExportManagerEasydb.prototype.__getTemplatesTool = function() {
    var fn1, fn2, getSharedTemplateTooltip, group_id, group_templates, hasSharedWritable, j, len, ref, reloadTemplatesTool, shared_templates, template, templateTool, templates, tools;
    templates = this.__getTemplates();
    if (!templates) {
      templates = {
        templates: [],
        version: this.__getTemplatesVersion()
      };
      ez5.session.savePref(this.__getTemplatesPrefKey(), templates);
    }
    shared_templates = ez5.version("6") ? this.__getSharedTemplates() : {};
    tools = [];
    ref = templates.templates;
    fn1 = (function(_this) {
      return function(template) {
        return tools.push({
          text: template.name,
          tooltip: {
            text: function() {
              var tooltipText;
              tooltipText = template.name;
              if (!CUI.util.isEmpty(template.comment)) {
                tooltipText += " - " + template.comment;
              }
              return tooltipText;
            }
          },
          onClick: function() {
            return _this.__openApplyTemplateConfirmation(template);
          }
        });
      };
    })(this);
    for (j = 0, len = ref.length; j < len; j++) {
      template = ref[j];
      fn1(template);
    }
    if (tools.length > 0 && !CUI.util.isEmpty(shared_templates)) {
      tools.push({
        divider: true
      });
    }
    if (ez5.version("6")) {
      getSharedTemplateTooltip = (function(_this) {
        return function(group_id, template) {
          var ref1, tooltip;
          tooltip = ((ref1 = _this.__findGroupById(parseInt(group_id))) != null ? ref1.getDisplayText() : void 0) + " - " + template.name;
          if (!CUI.util.isEmpty(template.comment)) {
            tooltip += " - " + template.comment;
          }
          if (template.create_date) {
            tooltip += " - " + ez5.format_date_and_time(template.create_date, true);
          }
          return tooltip;
        };
      })(this);
      fn2 = (function(_this) {
        return function(group_id, group_templates) {
          var l, len1, results;
          results = [];
          for (l = 0, len1 = group_templates.length; l < len1; l++) {
            template = group_templates[l];
            results.push((function(template) {
              var group, groupName;
              group = _this.__findGroupById(parseInt(group_id));
              groupName = (group != null ? group.getDisplayText() : void 0) || group_id;
              return tools.push({
                text: groupName + ": " + template.name,
                tooltip: {
                  text: function() {
                    return getSharedTemplateTooltip(group_id, template);
                  }
                },
                onClick: function() {
                  return _this.__openApplyTemplateConfirmation(template);
                }
              });
            })(template));
          }
          return results;
        };
      })(this);
      for (group_id in shared_templates) {
        group_templates = shared_templates[group_id];
        fn2(group_id, group_templates);
      }
    }
    if (tools.length > 0) {
      tools.push({
        divider: true
      });
    }
    reloadTemplatesTool = (function(_this) {
      return function() {
        _this.__tabs.replace(_this.__getTemplatesTool(), "header_right");
      };
    })(this);
    tools.push({
      loca_key: "export.template.save_as_template",
      onClick: (function(_this) {
        return function() {
          return _this.__saveNewTemplate().done(function() {
            return reloadTemplatesTool();
          });
        };
      })(this)
    });
    hasSharedWritable = ez5.version("6") && !CUI.util.isEmpty(this.__getSharedTemplates(true));
    tools.push({
      loca_key: "export.template.customize",
      disabled: templates.templates.length < 1 && !hasSharedWritable,
      onClick: (function(_this) {
        return function() {
          return _this.__customizeTemplates(templates).done(function() {
            return reloadTemplatesTool();
          });
        };
      })(this)
    });
    templateTool = new LocaButton({
      loca_key: "export.tool.template.menu",
      menu: {
        items: tools
      }
    });
    return templateTool;
  };

  return ExportManagerEasydb;

})(ExportManagerPlugin);

ez5.session_ready(function() {
  return ExportManager.registerPlugin(new ExportManagerEasydb());
});
// Generated by CoffeeScript 1.12.7
var PrintManager,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  PrintManager.prototype.initOpts = function() {
    PrintManager.__super__.initOpts.call(this);
    return this.addOpts({
      search: {
        check: Search
      },
      collection: {
        check: Collection
      },
      printFullSearch: {
        "default": false
      },
      result_object: {
        check: ResultObject
      },
      mode: {
        mandatory: true,
        "default": "window",
        check: ["modal", "iframe", "window"]
      }
    });
  };

  PrintManager.prototype.readOpts = function() {
    var col;
    PrintManager.__super__.readOpts.call(this);
    CUI.util.assert(CUI.util.xor(CUI.util.xor(this._result_object, this._collection), this._search), "new PrintManager", "opts.collection, opts.result_object, opts.search are mutually exclusive.", {
      opts: this.opts
    });
    if (this._search) {
      this.__search = this._search;
    } else if (this._collection) {
      this.__search = new SearchCollectionHeadless({
        collection: this._collection
      });
    } else {
      col = new CollectionTemporary();
      col.insertObjects([this._result_object.getCollectionObject()]).done((function(_this) {
        return function() {
          return _this.__search = new SearchCollectionHeadless({
            collection: col
          });
        };
      })(this)).fail((function(_this) {
        return function() {
          return CUI.problem({
            text: $$("print.manager.generic_error")
          });
        };
      })(this));
    }
    this.__limit = PrintManager.getLimit();
  };

  PrintManager.prototype.print = function(_opts) {
    var dfr, gatherObjects, gatherPromise, isFlexibleHeight, objects, opts, printLowRes, printManagerResultOpts, printMode, resultDivs, spinner, title, win;
    opts = CUI.Element.readOpts(_opts, 'PrintManager.print', {
      printMode: {
        mandatory: true,
        check: String,
        "default": "detail"
      },
      printLowRes: {
        check: Boolean,
        "default": false
      },
      header_title: {
        check: String
      },
      header_subtitle: {
        check: String
      },
      footer: {
        check: String
      },
      rows: {
        check: "Integer",
        "default": 1
      },
      columns: {
        check: "Integer",
        "default": 1
      },
      use_specific_mask: {
        check: Boolean
      },
      mask: {
        check: "PlainObject"
      },
      imageSize: {
        check: "Integer"
      },
      isFlexibleHeight: {
        check: Boolean,
        "default": false
      },
      addChangelog: {
        check: Boolean,
        "default": false
      },
      fields: {
        check: "PlainObject",
        "default": {}
      }
    });
    printMode = opts.printMode;
    printLowRes = opts.printLowRes;
    isFlexibleHeight = opts.isFlexibleHeight;
    if (isFlexibleHeight) {
      opts.rows = 1;
    }
    dfr = new CUI.Deferred();
    title = ez5.session.getEasydbName() + "-" + ez5.session.getUser().getDisplayText();
    if (opts.header_title) {
      title += "-" + opts.header_title;
    }
    win = PrintManager.windowOpen({
      title: title
    });
    spinner = CUI.spinner({
      text: $$("print.manager.collecting_data")
    });
    resultDivs = [];
    printManagerResultOpts = {
      proxy_self: !!this._search,
      limit: this.__limit,
      format: opts.addChangelog ? "full" : "long",
      offset: 0
    };
    if (opts.use_specific_mask) {
      printManagerResultOpts.mask = opts.mask;
    }
    objects = [];
    gatherPromise = new CUI.Deferred();
    gatherObjects = (function(_this) {
      return function() {
        var sm;
        sm = new PrintManagerResult(printManagerResultOpts);
        printManagerResultOpts.offset += objects.length;
        sm = new PrintManagerResult(printManagerResultOpts);
        _this.__search.execute(new Request({
          searchManagers: [sm],
          exclusive: true,
          exclusive_show: true
        })).done(function(req, _data) {
          objects = objects.concat(_data.objects);
          if (objects.length < _data.count && _this.__printFullSearch) {
            return gatherObjects();
          } else {
            return gatherPromise.resolve();
          }
        });
        return gatherPromise;
      };
    })(this);
    gatherObjects().fail(dfr.reject).always((function(_this) {
      return function() {
        return spinner.destroy();
      };
    })(this)).done((function(_this) {
      return function() {
        var count, idx, next_object, spinner2;
        window.focus();
        count = objects.length;
        idx = -1;
        spinner2 = null;
        next_object = function() {
          var isFieldEnabled, ro;
          if (idx === -1) {
            spinner2 = CUI.spinner({
              text: $$("print.manager.collecting_data")
            });
          }
          idx = idx + 1;
          if (idx === objects.length) {
            spinner2.destroy();
            dfr.resolve();
            return;
          }
          spinner2.updateText($$("print.manager.preparing_data", {
            total: objects.length,
            count: idx + 1
          }));
          spinner2.autoSize();
          isFieldEnabled = function(field, _opts) {
            var fieldName;
            if (_opts == null) {
              _opts = {};
            }
            if (field instanceof CustomDataTypeMappingField) {
              return false;
            }
            if (!field.mask) {
              return;
            }
            if (CUI.util.isEmpty(opts.fields)) {
              return;
            }
            if (_opts._path) {
              fieldName = _opts._path + "." + field.name();
            } else {
              fieldName = field.fullName();
            }
            if (!opts.fields[fieldName]) {
              return;
            }
            return opts.fields[fieldName]._enabled;
          };
          ro = new ResultObject().setData(objects[idx]);
          return ro.renderPrint({
            printMode: printMode,
            printLowRes: printLowRes,
            addChangelog: opts.addChangelog,
            isVisible: function(field, mode, visibleOpts) {
              if (opts.printMode === "standard") {
                return;
              }
              if (mode === "detail-footer") {
                return false;
              }
              return isFieldEnabled(field, visibleOpts);
            }
          }).fail(dfr.reject).done(function(div) {
            var images;
            images = div != null ? div.querySelectorAll("img") : void 0;
            if (images && images.length > 0) {
              images.forEach(function(img) {
                return img.removeAttribute("loading");
              });
            }
            resultDivs.push(div);
            return next_object();
          });
        };
        if (count === 0) {
          return CUI.problem({
            text: $$("print.manager.no_objects.message", {
              count: count,
              limit: _this.__limit
            })
          });
        } else if (count > _this.__limit) {
          CUI.confirm({
            button_text_ok: $$("print.manager.too_many_objects.button.print"),
            text: $$("print.manager.too_many_objects.message", {
              count: count,
              limit: _this.__limit
            })
          }).done(function() {});
          next_object().fail(function() {});
          win.close();
          return win = null;
        } else {
          return next_object();
        }
      };
    })(this));
    dfr.done((function(_this) {
      return function() {
        var addPage, attribute, bodyClass, characterThreshold, countLines, i, j, len, len1, metaTemplate, ref, ref1, styleBaseName, wrap;
        metaTemplate = new CUI.Template({
          name: "print-table-header-footer",
          map: {
            header_subtitle: true,
            header_title: true,
            footer: true
          }
        });
        ref = ["header_title", "header_subtitle", "footer"];
        for (i = 0, len = ref.length; i < len; i++) {
          attribute = ref[i];
          if (!CUI.util.isEmpty(opts[attribute])) {
            wrap = CUI.dom.div("inner");
            CUI.dom.append(wrap, opts[attribute]);
            metaTemplate.append(wrap, attribute);
            if (attribute === "footer") {
              styleBaseName = attribute.replace("_", "-");
              CUI.dom.addClass(win.document.body, "has-" + styleBaseName);
              win.document.body.setAttribute("data-" + styleBaseName + "-characters", opts[attribute].length);
              characterThreshold = 90;
              countLines = Math.ceil(opts[attribute].length / characterThreshold);
              win.document.body.style.setProperty("--" + styleBaseName + "-lines", countLines);
            }
          }
        }
        CUI.dom.append(win.document.body, metaTemplate.DOM);
        addPage = function() {
          var holder, j, k, l, len1, len2, m, objectDiv, ref1, ref2, ref3, row, tableTemplate, td, tdHeight, tdWidth, x, y;
          tableTemplate = new CUI.Template({
            name: "print-manager-table",
            map: {
              content: true,
              header_subtitle_spacer: true,
              header_title_spacer: true,
              footer_spacer: true
            }
          });
          ref1 = ["header_title", "header_subtitle", "footer"];
          for (j = 0, len1 = ref1.length; j < len1; j++) {
            attribute = ref1[j];
            if (CUI.util.isEmpty(opts[attribute])) {
              CUI.dom.remove(tableTemplate.map[attribute + '_spacer']);
            }
          }
          tdWidth = (100 / opts.columns) + "%";
          tdHeight = (100 / opts.rows) + "%";
          CUI.dom.setAttribute(tableTemplate, 'data-columns', opts.columns);
          CUI.dom.setAttribute(tableTemplate, 'data-rows', opts.rows);
          CUI.dom.setAttribute(tableTemplate, 'data-image-size', opts.imageSize);
          CUI.dom.setAttribute(tableTemplate, 'data-flexible-height', JSON.stringify(isFlexibleHeight));
          if (isFlexibleHeight && printMode === 'text') {
            row = CUI.dom.$element("tr");
            td = CUI.dom.$element("td");
            holder = CUI.dom.div("ez5-print-object-holder");
            for (k = 0, len2 = resultDivs.length; k < len2; k++) {
              objectDiv = resultDivs[k];
              CUI.dom.append(holder, objectDiv);
            }
            CUI.dom.append(td, holder);
            CUI.dom.append(row, td);
            CUI.dom.append(tableTemplate.map.content, row);
            resultDivs = [];
          } else {
            for (y = l = 0, ref2 = opts.rows; 0 <= ref2 ? l < ref2 : l > ref2; y = 0 <= ref2 ? ++l : --l) {
              row = CUI.dom.$element("tr");
              for (x = m = 0, ref3 = opts.columns; 0 <= ref3 ? m < ref3 : m > ref3; x = 0 <= ref3 ? ++m : --m) {
                objectDiv = resultDivs.shift();
                td = CUI.dom.$element("td");
                CUI.dom.setAttributeMap(td, {
                  width: tdWidth,
                  height: tdHeight
                });
                holder = CUI.dom.div("ez5-print-object-holder");
                if (objectDiv) {
                  CUI.dom.append(holder, objectDiv);
                }
                CUI.dom.append(td, holder);
                CUI.dom.append(row, td);
              }
              CUI.dom.append(tableTemplate.map.content, row);
            }
          }
          CUI.dom.append(win.document.body, tableTemplate.DOM);
          if (resultDivs.length > 0) {
            return addPage();
          }
        };
        addPage();
        ref1 = document.body.classList;
        for (j = 0, len1 = ref1.length; j < len1; j++) {
          bodyClass = ref1[j];
          CUI.dom.addClass(win.document.body, bodyClass);
        }
        CUI.dom.addClass(win.document.body, "print-result-objects-mode-" + printMode);
        return PrintManager.loadCSS(win, [Start.getCSSUrl("print", "local")]).done(function() {
          return PrintManager.waitForImagesAndPrint(win);
        });
      };
    })(this));
    dfr.fail((function(_this) {
      return function() {
        return CUI.problem({
          text: $$("print.manager.generic_error")
        });
      };
    })(this));
  };

  PrintManager.windowOpen = function(opts) {
    var eventName, func, i, len, ref, unload, win;
    if (opts == null) {
      opts = {};
    }
    win = window.open("", "_blank", "width=600,height=400,scrollbars=1,resizable=1");
    unload = (function(_this) {
      return function() {
        var func;
        win.removeEventListener("unload", func);
        win.close();
        func = null;
        return win = null;
      };
    })(this);
    func = (function(_this) {
      return function() {
        window.removeEventListener("unload", unload);
        return func = null;
      };
    })(this);
    window.addEventListener("unload", unload);
    win.addEventListener("unload", func);
    win.document.title = opts.title || ez5.session.getSystemName();
    ref = ["click", "dblclick", "mousedown", "mouseup"];
    for (i = 0, len = ref.length; i < len; i++) {
      eventName = ref[i];
      win.document.addEventListener(eventName, (function(_this) {
        return function(ev) {
          return ev.stopPropagation();
        };
      })(this), true);
    }
    win.document.head.innerHTML += CUI.dom.element("meta", {
      charset: "utf-8"
    }).outerHTML;
    return win;
  };

  PrintManager.loadCSS = function(win, css_hrefs) {
    var baseUrl, css_href, css_mode, fn, i, len, promises;
    promises = [];
    css_hrefs.unshift("/web/css/font-awesome/css/font-awesome.min.css");
    css_mode = ez5.session.getCSSMode();
    switch (css_mode) {
      case "remote":
        baseUrl = window.easydb_server_url;
        break;
      default:
        baseUrl = document.location.origin;
    }
    fn = (function(_this) {
      return function(css_href) {
        var css_node, dfr;
        dfr = new CUI.Deferred();
        css_node = CUI.dom.element("LINK", {
          rel: "stylesheet",
          charset: "utf-8",
          href: ez5.getAbsoluteURL(css_href, baseUrl)
        });
        css_node.addEventListener("load", function() {
          if (dfr.state() === "pending") {
            dfr.resolve();
          }
        });
        css_node.addEventListener("error", function() {
          return dfr.reject();
        });
        win.document.head.append(css_node);
        return promises.push(dfr);
      };
    })(this);
    for (i = 0, len = css_hrefs.length; i < len; i++) {
      css_href = css_hrefs[i];
      fn(css_href);
    }
    return CUI.when(promises);
  };

  PrintManager.waitForImagesAndPrint = function(win) {
    var checkAllLoaded, i, images, img, len, loadedCount, totalImages;
    images = win.document.querySelectorAll('img');
    if (images.length === 0) {
      win.print();
      return;
    }
    loadedCount = 0;
    totalImages = images.length;
    checkAllLoaded = function() {
      loadedCount++;
      if (loadedCount >= totalImages) {
        return win.print();
      }
    };
    for (i = 0, len = images.length; i < len; i++) {
      img = images[i];
      if (img.complete && img.naturalWidth > 0) {
        checkAllLoaded();
      } else {
        img.addEventListener('load', checkAllLoaded);
        img.addEventListener('error', checkAllLoaded);
      }
    }
    return setTimeout((function() {
      if (loadedCount < totalImages) {
        console.warn("PrintManager: Some images did not load within timeout, printing anyway");
        return win.print();
      }
    }), 5000);
  };

  PrintManager.prototype.getOptionsModal = function() {
    var columnOptions, data, disableEnableOptions, enabledOptionsByType, form, formFields, formMaskSelector, formOpts, historyCheckbox, imageSizeOptions, layouts, loadingLabel, maskSelectForm, maskSelector, modal, modalContent, objecttypeNames, onOptionsChanged, onPdfTemplateChanged, opts, pdfTemplateForm, pdfTemplateSelector, reloadFieldSelector, rowOptions, selectMaskCheckbox, selectMaskCheckboxProxy, settings, showPdfCreatorSelect, tabs, usePdfTemplate;
    settings = ez5.session.getPref("print_settings");
    data = settings || {
      printMode: "detail",
      printLowRes: false,
      header_title: ez5.session.getSystemName(),
      rows: 1,
      columns: 1,
      imageSize: 100,
      use_specific_mask: false,
      pdfFields: {},
      fields: {},
      _layout: 0
    };
    data.pdf_template = {};
    columnOptions = [1, 2, 3].map(function(number) {
      return {
        value: number
      };
    });
    rowOptions = [1, 2, 3, 4].map(function(number) {
      return {
        value: number
      };
    });
    rowOptions.unshift({
      value: 0,
      text: $$("print.modal.option.rows.flexible")
    });
    imageSizeOptions = [100, 50, 33].map(function(key) {
      return {
        text: key + "%",
        value: key
      };
    });
    enabledOptionsByType = {
      detail: {
        rows: [0],
        imageSize: [100, 50, 33],
        columns: [1]
      },
      text: {
        rows: [0, 2, 3, 4],
        imageSize: [50, 33],
        columns: [1]
      },
      standard: {
        rows: [1, 2, 3, 4],
        imageSize: [100],
        columns: [1, 2, 3]
      }
    };
    disableEnableOptions = function(data) {
      var checkboxHistory, columnOption, enabledOptions, i, imageSizeOption, isDisabled, j, k, key, l, len, len1, len2, len3, ref, ref1, ref2, ref3, ref4, rowOption;
      enabledOptions = enabledOptionsByType[data.printMode];
      for (i = 0, len = columnOptions.length; i < len; i++) {
        columnOption = columnOptions[i];
        isDisabled = (ref = columnOption.value, indexOf.call(enabledOptions.columns, ref) < 0);
        columnOption.disabled = isDisabled;
      }
      for (j = 0, len1 = imageSizeOptions.length; j < len1; j++) {
        imageSizeOption = imageSizeOptions[j];
        isDisabled = (ref1 = imageSizeOption.value, indexOf.call(enabledOptions.imageSize, ref1) < 0);
        imageSizeOption.disabled = isDisabled;
      }
      for (k = 0, len2 = rowOptions.length; k < len2; k++) {
        rowOption = rowOptions[k];
        isDisabled = (ref2 = rowOption.value, indexOf.call(enabledOptions.rows, ref2) < 0);
        rowOption.disabled = isDisabled;
      }
      ref3 = ["columns", "imageSize", "rows"];
      for (l = 0, len3 = ref3.length; l < len3; l++) {
        key = ref3[l];
        if (ref4 = data[key], indexOf.call(enabledOptions[key], ref4) < 0) {
          data[key] = enabledOptions[key][0];
          form.getFieldsByName(key)[0].reload();
        }
      }
      checkboxHistory = form.getFieldsByName("addChangelog")[0];
      if (checkboxHistory) {
        if (data.printMode === "detail" && data._layout === 0) {
          checkboxHistory.enable();
        } else {
          checkboxHistory.deactivate();
          checkboxHistory.disable();
        }
      }
    };
    onOptionsChanged = function(data) {
      var columns, i, imageSize, index, layout, len, newLayout, printMode, rows;
      rows = data.rows;
      columns = data.columns;
      printMode = data.printMode;
      imageSize = data.imageSize;
      newLayout = null;
      for (index = i = 0, len = layouts.length; i < len; index = ++i) {
        layout = layouts[index];
        if (layout.rows === rows && layout.columns === columns && layout.printMode === printMode && layout.imageSize === imageSize) {
          newLayout = index;
          break;
        }
      }
      data._layout = newLayout;
      form.getFieldsByName("_layout")[0].reload();
    };
    layouts = [
      {
        printMode: "detail",
        imageSize: 100,
        rows: 0,
        columns: 1
      }, {
        printMode: "text",
        imageSize: 50,
        rows: 2,
        columns: 1
      }, {
        printMode: "text",
        imageSize: 33,
        rows: 4,
        columns: 1
      }, {
        printMode: "standard",
        imageSize: 100,
        rows: 4,
        columns: 3
      }
    ];
    pdfTemplateSelector = CUI.dom.div();
    objecttypeNames = [];
    showPdfCreatorSelect = (function(_this) {
      return function() {
        var fn, getObjecttypePromises, i, len, loadingLabel, objecttypeName, pdfSelectFields;
        if (!ez5.pluginManager.getPlugin("pdf-creator")) {
          return;
        }
        loadingLabel = new LocaLabel({
          loca_key: "print.manager.option.pdf_template.loading"
        });
        CUI.dom.append(pdfTemplateSelector, loadingLabel);
        getObjecttypePromises = [];
        pdfSelectFields = [];
        fn = function(objecttypeName) {
          var getObjecttypePromise, idObjecttype;
          idObjecttype = idObjecttype = ez5.schema.CURRENT._table_by_name[objecttypeName].table_id;
          getObjecttypePromise = ez5.api.objecttype({
            api: "/" + idObjecttype
          }).done(function(response) {
            var objecttypeLocalizedName, outputField, pdfCreator, pdfCreatorData, ref, ref1, select;
            pdfCreatorData = (ref = response[0].objecttype.custom_data) != null ? (ref1 = ref.webfrontend) != null ? ref1.pdf_creator : void 0 : void 0;
            objecttypeLocalizedName = ez5.schema.CURRENT._table_by_name[objecttypeName]._name_localized;
            if (!pdfCreatorData) {
              outputField = new CUI.Output({
                text: $$("print.modal.pdf_template.no-templates-available.label"),
                form: {
                  label: objecttypeLocalizedName
                }
              });
              pdfSelectFields.push(outputField);
              return;
            }
            pdfCreator = new ez5.PdfCreator({
              data: pdfCreatorData,
              idObjecttype: idObjecttype
            });
            select = pdfCreator.getTemplateSelect({
              form: {
                label: objecttypeLocalizedName
              },
              name: objecttypeName
            });
            return pdfSelectFields.push(select);
          });
          return getObjecttypePromises.push(getObjecttypePromise);
        };
        for (i = 0, len = objecttypeNames.length; i < len; i++) {
          objecttypeName = objecttypeNames[i];
          fn(objecttypeName);
        }
        return CUI.whenAll(getObjecttypePromises).done(function() {
          var pdfTemplatesForm;
          if (pdfSelectFields.every(function(field) {
            return field instanceof CUI.Output;
          })) {
            tabs[0].disable();
            tabs[1].activate();
          }
          pdfTemplatesForm = new CUI.Form({
            fields: pdfSelectFields,
            name: "pdf_template",
            data: data
          });
          pdfTemplatesForm.start();
          CUI.dom.replace(pdfTemplateSelector, pdfTemplatesForm);
          return CUI.Events.trigger({
            type: "content-resize",
            node: pdfTemplatesForm
          });
        });
      };
    })(this);
    if (this._search) {
      maskSelectForm = null;
      selectMaskCheckbox = new CUI.Checkbox({
        data: data,
        name: "use_specific_mask",
        form: {
          hint: $$("print.manager.option.mask.specific_selection|hint")
        },
        text: $$("print.manager.option.mask.specific_selection|text"),
        disabled: true,
        onClick: function() {
          if (maskSelectForm.isDisabled()) {
            return maskSelectForm.enable();
          } else {
            return maskSelectForm.disable();
          }
        }
      });
      selectMaskCheckbox.start();
      maskSelector = CUI.dom.div();
      loadingLabel = new LocaLabel({
        loca_key: "print.manager.option.mask.loading"
      });
      CUI.dom.append(maskSelector, loadingLabel);
      opts = {
        removeMaskFilter: true,
        filter: function(mask) {
          return !mask.hideInPrintDialog();
        }
      };
      formOpts = {
        data: data
      };
      MaskFieldSelector.getFormSelect(this._search, formOpts, opts).done((function(_this) {
        return function(_maskSelectForm) {
          var collection, foundAtSelectableMask, i, j, k, l, len, len1, len2, len3, maskSelectFormData, object, objects, objecttypeName, ref, ref1, ref2, ref3, select;
          maskSelectForm = _maskSelectForm;
          maskSelectForm.start();
          if (!data.use_specific_mask) {
            maskSelectForm.disable();
          }
          objecttypeNames = Object.keys(maskSelectForm.getData());
          showPdfCreatorSelect();
          maskSelectFormData = maskSelectForm.getData();
          if (_this.__search instanceof SearchCollectionHeadless && _this.__search.collection instanceof CollectionSelection) {
            collection = _this.__search.collection;
            objects = collection.getObjects();
            for (i = 0, len = objecttypeNames.length; i < len; i++) {
              objecttypeName = objecttypeNames[i];
              for (j = 0, len1 = objects.length; j < len1; j++) {
                object = objects[j];
                if (objecttypeName !== object.getObjecttype()) {
                  continue;
                }
                maskSelectFormData[objecttypeName] = object.getObject()._mask;
                break;
              }
            }
          }
          foundAtSelectableMask = false;
          ref = maskSelectForm.getFields();
          for (k = 0, len2 = ref.length; k < len2; k++) {
            select = ref[k];
            if (select.getOptions().length > 1) {
              foundAtSelectableMask = true;
              break;
            }
          }
          if (foundAtSelectableMask) {
            CUI.dom.replace(maskSelector, maskSelectForm);
            maskSelectForm.reload();
            selectMaskCheckbox.enable();
            ref1 = maskSelectForm.getFields();
            for (l = 0, len3 = ref1.length; l < len3; l++) {
              select = ref1[l];
              if (select.getOptions().length === 1) {
                select.hide(true);
              }
            }
          } else {
            if (pdfTemplateForm) {
              pdfTemplateForm.getFields()[1].hide(true);
              pdfTemplateForm.getFields()[2].hide(true);
            }
            form.getFields()[0].hide(true);
            form.getFields()[1].hide(true);
          }
          if ((ref2 = form.getFieldsByName("field_selector")) != null) {
            if ((ref3 = ref2[0]) != null) {
              ref3.reload();
            }
          }
          return CUI.Events.trigger({
            type: "content-resize",
            node: form
          });
        };
      })(this)).fail(function() {
        var label;
        label = new LocaLabel({
          loca_key: "print.manager.option.mask.error-loading"
        });
        return CUI.dom.replace(maskSelector, label);
      });
    } else {
      objecttypeNames = [this._result_object.objecttype()];
      showPdfCreatorSelect();
    }
    if (this._search) {
      reloadFieldSelector = function() {
        var ref, ref1;
        if ((ref = form.getFieldsByName("field_selector")) != null) {
          if ((ref1 = ref[0]) != null) {
            ref1.reload();
          }
        }
      };
      selectMaskCheckboxProxy = {
        type: CUI.DataFieldProxy,
        form: {
          label: $$("print.modal.mask.label")
        },
        name: "mask_selector_checkbox",
        element: selectMaskCheckbox,
        maximize_horizontal: true,
        onDataChanged: reloadFieldSelector
      };
      formMaskSelector = {
        type: CUI.DataFieldProxy,
        name: "mask_selector",
        element: maskSelector,
        maximize_horizontal: true,
        onDataChanged: reloadFieldSelector
      };
    }
    formFields = [
      this._search ? selectMaskCheckboxProxy : void 0, this._search ? formMaskSelector : void 0, {
        type: CUI.Input,
        name: "header_title",
        ui: "print.manager.form.header_title",
        form: {
          label: $$("print.modal.header-title.label")
        },
        maximize_horizontal: true
      }, {
        type: CUI.Input,
        name: "header_subtitle",
        ui: "print.manager.form.header_subtitle",
        form: {
          label: $$("print.modal.header-subtitle.label")
        },
        maximize_horizontal: true
      }, {
        type: CUI.Input,
        name: "footer",
        ui: "print.manager.form.footer",
        form: {
          label: $$("print.modal.footer.label")
        },
        maximize_horizontal: true
      }, {
        type: CUI.Select,
        name: "_layout",
        ui: "print.manager.form.layout",
        form: {
          label: $$("print.modal.select.layout.label")
        },
        maximize_horizontal: true,
        options: function() {
          var _, i, index, len, options;
          options = [];
          for (index = i = 0, len = layouts.length; i < len; index = ++i) {
            _ = layouts[index];
            options.push({
              text: $$("print.modal.select.layout." + index + ".option"),
              value: index
            });
          }
          options.push({
            text: $$("print.modal.select.layout.custom.option"),
            value: null
          });
          return options;
        },
        onDataChanged: function(data, field) {
          var fieldName, form, i, layout, len, ref;
          if (CUI.util.isNull(data._layout)) {
            return;
          }
          layout = layouts[data._layout];
          form = field.getForm();
          ref = ["rows", "columns", "printMode", "imageSize"];
          for (i = 0, len = ref.length; i < len; i++) {
            fieldName = ref[i];
            data[fieldName] = layout[fieldName];
            form.getFieldsByName(fieldName)[0].reload();
          }
          disableEnableOptions(data);
        }
      }, {
        type: CUI.Select,
        form: {
          label: $$("print.modal.option.type.label")
        },
        name: "printMode",
        ui: "print.manager.form.print_mode",
        options: function() {
          var i, key, len, options, ref;
          options = [];
          ref = ["detail", "text", "standard"];
          for (i = 0, len = ref.length; i < len; i++) {
            key = ref[i];
            options.push({
              text: $$("print.modal.option.type." + key),
              value: key
            });
          }
          return options;
        },
        onDataChanged: (function(_this) {
          return function(data) {
            reloadFieldSelector();
            disableEnableOptions(data);
          };
        })(this),
        maximize_horizontal: true
      }, {
        type: CUI.Select,
        form: {
          label: $$("print.modal.select.image_size.label")
        },
        name: "imageSize",
        ui: "print.manager.form.image_size",
        options: function() {
          return imageSizeOptions;
        },
        onDataChanged: onOptionsChanged,
        maximize_horizontal: true
      }, {
        type: CUI.Select,
        name: "rows",
        ui: "print.manager.form.rows",
        form: {
          label: $$("print.modal.select.rows.label")
        },
        options: function() {
          return rowOptions;
        },
        onDataChanged: onOptionsChanged,
        maximize_horizontal: true
      }, {
        type: CUI.Select,
        name: "columns",
        ui: "print.manager.form.columns",
        form: {
          label: $$("print.modal.select.columns.label")
        },
        options: function() {
          return columnOptions;
        },
        onDataChanged: onOptionsChanged,
        maximize_horizontal: true
      }, {
        type: CUI.Options,
        form: {
          label: $$("print.modal.option.resolution.label")
        },
        name: "printLowRes",
        ui: "print.manager.form.print_low_res",
        radio: true,
        horizontal: true,
        options: [
          {
            text: $$("print.modal.option.resolution.high"),
            value: false
          }, {
            text: $$("print.modal.option.resolution.low"),
            value: true
          }
        ]
      }, this._search ? {
        type: CUI.DataFieldProxy,
        name: "field_selector",
        form: {
          label: $$("print.modal.fields.label")
        },
        element: (function(_this) {
          return function() {
            delete data.fields;
            return _this.__getFieldSelectorButton(data);
          };
        })(this),
        maximize_horizontal: true
      } : void 0
    ];
    if (ez5.session.hasSystemRight("root", "frontend_features[changelog]", "frontend_features[changelog_with_user]")) {
      historyCheckbox = {
        type: CUI.Checkbox,
        form: {
          label: $$("print.modal.option.history.label")
        },
        name: "addChangelog"
      };
      formFields.splice(formFields.length - 1, 0, historyCheckbox);
    }
    form = new CUI.Form({
      data: data,
      padded: true,
      fields: formFields
    });
    form.start();
    usePdfTemplate = !!ez5.pluginManager.getPlugin("pdf-creator");
    tabs = [
      new CUI.Tab({
        text: $$("print.modal.tabs.print_page.name"),
        content: form,
        onActivate: function() {
          var ref, ref1;
          if ((ref = form.getFieldsByName("mask_selector")[0]) != null) {
            ref.replace(maskSelector);
          }
          if ((ref1 = form.getFieldsByName("mask_selector_checkbox")[0]) != null) {
            ref1.replace(selectMaskCheckbox);
          }
          usePdfTemplate = false;
          return CUI.Events.trigger({
            type: "content-resize",
            node: form
          });
        }
      })
    ];
    disableEnableOptions(data);
    if (ez5.pluginManager.getPlugin("pdf-creator")) {
      if (ez5.PdfCreator.VERSION < 2) {
        console.warn("PdfCreator :: Wrong version. It is necessary to have the version 2 of the plugin.");
      } else {
        onPdfTemplateChanged = function(data) {
          var ref, ref1;
          if ((ref = pdfTemplateForm.getFieldsByName("field_selector")) != null) {
            if ((ref1 = ref[0]) != null) {
              ref1.reload();
            }
          }
        };
        pdfTemplateForm = new CUI.Form({
          padded: true,
          data: data,
          fields: [
            {
              type: CUI.DataFieldProxy,
              name: "pdf_template_selector",
              form: {
                label: $$("print.modal.pdf_template.label")
              },
              element: pdfTemplateSelector,
              maximize_horizontal: true,
              onDataInit: function(_, data) {
                return onPdfTemplateChanged(data);
              },
              onDataChanged: onPdfTemplateChanged
            }, this._search ? selectMaskCheckboxProxy : void 0, this._search ? formMaskSelector : void 0, this._search ? {
              type: CUI.DataFieldProxy,
              name: "field_selector",
              form: {
                label: $$("print.modal.pdf_template.fields.label")
              },
              element: (function(_this) {
                return function() {
                  delete data.pdfTemplateFields;
                  return _this.__getFieldSelectorButton(data, true);
                };
              })(this),
              maximize_horizontal: true
            } : void 0
          ]
        });
        pdfTemplateForm.start();
        tabs.unshift(new CUI.Tab({
          text: $$("print.modal.tabs.pdf_template.name"),
          content: pdfTemplateForm,
          onActivate: function() {
            var ref, ref1;
            if ((ref = pdfTemplateForm.getFieldsByName("mask_selector")[0]) != null) {
              ref.replace(maskSelector);
            }
            if ((ref1 = pdfTemplateForm.getFieldsByName("mask_selector_checkbox")[0]) != null) {
              ref1.replace(selectMaskCheckbox);
            }
            usePdfTemplate = true;
            return CUI.Events.trigger({
              type: "content-resize",
              node: form
            });
          }
        }));
      }
    }
    modalContent = new CUI.Tabs({
      tabs: tabs,
      maximize_horizontal: true,
      maximize_vertical: true
    });
    modal = new CUI.Modal({
      "class": "print-manager-modal",
      size: "m",
      cancel: true,
      onCancel: (function(_this) {
        return function() {
          modal.destroy();
        };
      })(this),
      pane: {
        header_left: new CUI.Label({
          text: $$("print.modal.header.label")
        }),
        content: modalContent,
        footer_right: new CUI.Button({
          ui: "print.manager.button",
          text: $$("print.modal.button"),
          primary: true,
          left: true,
          onClick: (function(_this) {
            return function(_, button) {
              var fn, idMask, mask, objects, objecttype, objecttypeName, pdfTemplateData, promises, ref, ref1, ref2, value;
              if (usePdfTemplate && data.pdf_template) {
                if (_this._result_object) {
                  objecttype = _this._result_object.objecttype();
                  pdfTemplateData = data.pdf_template[objecttype];
                  if (!pdfTemplateData) {
                    CUI.problem({
                      text: $$("print.modal.pdf_template.no-template-selected.label")
                    });
                    return;
                  }
                  idMask = _this._result_object.getMask().id();
                  objects = [_this._result_object.data];
                  button.startSpinner();
                  ez5.PdfCreator.print(pdfTemplateData, objects, idMask).fail(function() {
                    return CUI.problem({
                      text: $$("print.manager.pdf_template.server-error|label")
                    });
                  }).always(function() {
                    return button.stopSpinner();
                  });
                  return;
                } else {
                  ref = data.pdf_template;
                  for (objecttypeName in ref) {
                    value = ref[objecttypeName];
                    if (CUI.util.inArray(objecttypeName, objecttypeNames) === -1) {
                      continue;
                    }
                    if (CUI.util.isEmpty(value)) {
                      CUI.problem({
                        text: $$("print.modal.pdf_template.no-template-selected.label")
                      });
                      return;
                    }
                  }
                  promises = [];
                  button.startSpinner();
                  ref1 = data.pdf_template;
                  fn = function(objecttypeName, pdfTemplateData) {
                    var deferred, request, requestData;
                    deferred = new CUI.Deferred();
                    request = new Request();
                    _this._search.addToRequest(request);
                    requestData = request.cleanRequestForSearch();
                    requestData.limit = _this.__limit;
                    requestData.objecttypes = [objecttypeName];
                    ez5.api.search_no_limit({
                      json_data: requestData
                    }).done(function(response) {
                      var overrideFields;
                      idMask = ez5.mask.CURRENT._mask_by_name[data.mask[objecttypeName]].mask_id;
                      if (data.pdfTemplateFields) {
                        pdfTemplateData = CUI.util.copyObject(pdfTemplateData, true);
                        overrideFields = function(pdfNodes) {
                          var fieldName, fieldValue, i, len, node, ref2;
                          for (i = 0, len = pdfNodes.length; i < len; i++) {
                            node = pdfNodes[i];
                            if (node.data.dataFields) {
                              ref2 = node.data.dataFields;
                              for (fieldName in ref2) {
                                fieldValue = ref2[fieldName];
                                if (!data.pdfTemplateFields[fieldName]) {
                                  continue;
                                }
                                node.data.dataFields[fieldName] = data.pdfTemplateFields[fieldName];
                              }
                            }
                            if (node.children) {
                              overrideFields(node.children);
                            }
                          }
                        };
                        overrideFields(pdfTemplateData.documentData.children);
                      }
                      return ez5.PdfCreator.print(pdfTemplateData, response.objects, idMask).done(deferred.resolve).fail(function() {
                        CUI.problem({
                          text: $$("print.manager.pdf_template.server-error|label")
                        });
                        return deferred.reject();
                      });
                    }).fail(deferred.reject);
                    return promises.push(deferred.promise());
                  };
                  for (objecttypeName in ref1) {
                    pdfTemplateData = ref1[objecttypeName];
                    if (!data.mask[objecttypeName]) {
                      continue;
                    }
                    fn(objecttypeName, pdfTemplateData);
                  }
                  CUI.whenAll(promises).always(function() {
                    return button.stopSpinner();
                  });
                }
                return;
              }
              ez5.session.savePref("print_settings", data);
              if ((ref2 = _this._result_object) != null ? ref2.getMask() : void 0) {
                mask = _this._result_object.getMask();
                data.mask = {};
                data.mask[mask.getTable().name()] = mask.name();
              }
              data.isFlexibleHeight = data.rows === 0;
              _this.print(data);
              return modal.doCancel();
            };
          })(this)
        })
      }
    });
    return modal;
  };

  PrintManager.prototype.__getFieldSelectorButton = function(data, isPdfTemplate) {
    var allPdfTemplateFields, fieldSelectorButton, fieldsDataCopy, getDisabledButton, openFieldsForm, ref, templateOnlyFields, updateFieldSelectButton;
    if (isPdfTemplate == null) {
      isPdfTemplate = false;
    }
    getDisabledButton = (function(_this) {
      return function() {
        var button;
        return button = new CUI.Button({
          text: $$("print.modal.fields.button.text"),
          disabled: true
        });
      };
    })(this);
    if (!data.mask) {
      return CUI.dom.div();
    }
    if (isPdfTemplate && (!data.pdf_template || !Object.values(data.pdf_template).some((function(_this) {
      return function(pdf_template) {
        return !!pdf_template;
      };
    })(this)))) {
      return getDisabledButton();
    }
    if (!isPdfTemplate && ((ref = data.printMode) !== "detail" && ref !== "text")) {
      return new CUI.MultilineLabel({
        text: $$("print.modal.fields.button.not_available")
      });
    }
    fieldsDataCopy = null;
    allPdfTemplateFields = {};
    templateOnlyFields = {};
    updateFieldSelectButton = function(data, button, isPdfTemplate) {
      var fieldList, fieldName, fieldValue, selectedFieldsCount, text;
      if (isPdfTemplate == null) {
        isPdfTemplate = false;
      }
      if (isPdfTemplate) {
        fieldList = data.pdfTemplateFields;
      } else {
        fieldList = data.fields;
      }
      text = $$("print.modal.fields.button.text");
      if (CUI.util.isNull(fieldList)) {
        button.deactivate();
        button.setText(text);
        return;
      }
      selectedFieldsCount = 0;
      for (fieldName in fieldList) {
        fieldValue = fieldList[fieldName];
        if (!fieldValue._enabled) {
          continue;
        }
        if (isPdfTemplate && !templateOnlyFields[fieldName]) {
          continue;
        }
        selectedFieldsCount++;
      }
      if (selectedFieldsCount === Object.keys(fieldList).length || selectedFieldsCount === 0) {
        button.deactivate();
      } else {
        button.activate();
        text = $$("pdf-creator.settings.node.field.select-fields.count|label", {
          count: selectedFieldsCount
        });
      }
      button.setText(text);
    };
    fieldSelectorButton = new CUI.FormButton({
      text: $$("print.modal.fields.button.text"),
      onClick: (function(_this) {
        return function() {
          var _, fieldName, fieldValue, maskName, objecttypeManager, objecttypeName, pdfTemplateData, ref1, ref2, ref3;
          objecttypeManager = new ObjecttypeManager();
          ref1 = data.mask;
          for (_ in ref1) {
            maskName = ref1[_];
            objecttypeManager.addMask(Mask.getMaskByMaskName(maskName));
          }
          objecttypeManager.initCommonFields("all");
          if (isPdfTemplate) {
            ref2 = data.pdf_template;
            for (objecttypeName in ref2) {
              pdfTemplateData = ref2[objecttypeName];
              if (!pdfTemplateData) {
                continue;
              }
              ref3 = ez5.PdfCreator.getTemplateFields(pdfTemplateData);
              for (fieldName in ref3) {
                fieldValue = ref3[fieldName];
                if (allPdfTemplateFields[fieldName]) {
                  continue;
                }
                allPdfTemplateFields[fieldName] = fieldValue;
                allPdfTemplateFields[fieldName].display_name = ez5.loca.getBestFrontendValue(fieldValue.label);
              }
            }
            if (!data.pdfTemplateFields) {
              data.pdfTemplateFields = allPdfTemplateFields;
            }
            if (CUI.util.isEmptyObject(data.pdfTemplateFields)) {
              return;
            }
          } else {
            if (!data.fields) {
              data.fields = {};
            }
          }
          openFieldsForm(objecttypeManager);
        };
      })(this)
    });
    openFieldsForm = (function(_this) {
      return function(objecttypeManager) {
        var fieldsData, fieldsForm, modal;
        fieldsData = isPdfTemplate ? data.pdfTemplateFields : data.fields;
        fieldsDataCopy = CUI.util.copyObject(fieldsData, true);
        fieldsForm = new FieldsForm({
          otm: objecttypeManager,
          data: fieldsDataCopy,
          treeNodeClass: PrintFieldsFormNode,
          acceptField: function(field, fieldsFormNodeFather) {
            var fieldFullName;
            if (field instanceof CustomDataType && !field.isVisible("detail", {
              for_print: true
            })) {
              return false;
            }
            if (!field.mask) {
              return false;
            }
            if (field instanceof LinkedObject && (fieldsFormNodeFather != null ? fieldsFormNodeFather.field : void 0) instanceof LinkedObject) {
              return false;
            }
            if (!isPdfTemplate && !field.isVisible(data.printMode)) {
              return false;
            }
            if (isPdfTemplate) {
              if (fieldsFormNodeFather) {
                fieldFullName = fieldsFormNodeFather.getFieldFullName() + "." + field.name();
              } else {
                fieldFullName = field.fullName();
              }
              if (!allPdfTemplateFields[fieldFullName]) {
                return false;
              }
              if (!allPdfTemplateFields[fieldFullName]._enabled) {
                return false;
              }
              templateOnlyFields[fieldFullName] = data.pdfTemplateFields[fieldFullName];
            }
            return true;
          },
          treeOpts: {
            "class": 'cui-lv--has-datafields',
            maximize: false,
            rowMove: false,
            cols: ["auto"]
          }
        });
        if (typeof modal !== "undefined" && modal !== null) {
          modal.destroy();
        }
        modal = new CUI.Modal({
          "class": "print-manager-field-selector",
          cancel: true,
          pane: {
            header_left: new CUI.Label({
              text: $$("print.modal.fields.modal.header.text")
            }),
            content: fieldsForm.renderForm(),
            footer_right: new CUI.Button({
              text: $$("print.modal.fields.modal.apply.button.text"),
              primary: true,
              onClick: function() {
                if (isPdfTemplate) {
                  data.pdfTemplateFields = fieldsDataCopy;
                } else {
                  data.fields = fieldsDataCopy;
                }
                CUI.Events.trigger({
                  node: fieldSelectorButton,
                  type: "data-changed",
                  info: {
                    element: fieldSelectorButton
                  }
                });
                modal.hide();
              }
            })
          }
        });
        fieldsForm.open().done(function() {
          return modal.show();
        });
      };
    })(this);
    fieldSelectorButton.start();
    CUI.Events.listen({
      node: fieldSelectorButton,
      type: "data-changed",
      call: (function(_this) {
        return function(ev) {
          fieldSelectorButton.activate();
          return updateFieldSelectButton(data, fieldSelectorButton, isPdfTemplate);
        };
      })(this)
    });
    return fieldSelectorButton;
  };

  PrintManager.getLimit = function() {
    return parseInt(ez5.session.getClientDefault("print_limit")) || 1000;
  };

  return PrintManager;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var PrintManagerResult,
  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;

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

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

  PrintManagerResult.prototype.initOpts = function() {
    PrintManagerResult.__super__.initOpts.call(this);
    return this.addOpts({
      proxy_self: {
        check: Boolean
      },
      limit: {
        "default": 250,
        check: (function(_this) {
          return function(v) {
            return v >= 0;
          };
        })(this)
      },
      offset: {
        "default": 0,
        check: (function(_this) {
          return function(v) {
            return v >= 0;
          };
        })(this)
      },
      mask: {
        check: "PlainObject",
        "default": {}
      },
      format: {
        "default": "long",
        check: (function(_this) {
          return function(v) {
            return v === "long" || v === "short" || v === "long_inheritance" || v === "full";
          };
        })(this)
      }
    });
  };

  PrintManagerResult.prototype.addToRequest = function(request) {
    var filter, found, i, index, j, k, len, len1, maskFilter, ref, ref1, req, v;
    if (!request.exclusive) {
      return;
    }
    if (this._proxy_self) {
      req = {};
      this.getSearch().addToRequest(req);
      for (k in req) {
        v = req[k];
        request[k] = v;
      }
    }
    if (!CUI.util.isEmptyObject(this._mask)) {
      maskFilter = MaskFieldSelector.getSearchFilter(this._mask);
      found = false;
      ref = request.search;
      for (index = i = 0, len = ref.length; i < len; index = ++i) {
        filter = ref[index];
        if (!filter.__mask_filter) {
          continue;
        }
        found = true;
        request.search[index] = maskFilter;
      }
      if (!found) {
        request.search.push(maskFilter);
      }
      request.best_mask_filter = false;
    } else {
      ref1 = request.search;
      for (index = j = 0, len1 = ref1.length; j < len1; index = ++j) {
        filter = ref1[index];
        if (!filter.__mask_filter) {
          continue;
        }
        request.search.splice(index, 1);
        break;
      }
      request.best_mask_filter = true;
    }
    request.offset = this._offset;
    request.limit = this._limit;
    request.format = this._format;
    request.generate_rights = false;
    return delete request.event_log;
  };

  PrintManagerResult.prototype.showResult = function(data, request) {};

  return PrintManagerResult;

})(SearchManager);
// Generated by CoffeeScript 1.12.7
var DownloadManager,
  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;

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

  function DownloadManager(opts) {
    this.getFormFieldsFromStats = bind(this.getFormFieldsFromStats, this);
    DownloadManager.__super__.constructor.call(this, opts);
    this.form_data = {
      _template: "default"
    };
  }

  DownloadManager.prototype.initOpts = function() {
    DownloadManager.__super__.initOpts.call(this);
    this.addOpts({
      result_object: {
        check: function(v) {
          return v instanceof ResultObject;
        }
      },
      collection: {
        check: Collection
      },
      zip_download_name: {
        check: String
      },
      assetsFilter: {
        check: "PlainObject"
      }
    });
    return this.mergeOpts({
      search: {
        mandatory: false
      }
    });
  };

  DownloadManager.maxObjects = 1000;

  DownloadManager.prototype.readOpts = function() {
    DownloadManager.__super__.readOpts.call(this);
    return CUI.util.assert(CUI.util.xor(this._search, CUI.util.xor(this._collection, this._result_object)), "new DownloadManager", "One of opts.collection, opts.search, or opts.result_object must be set.", {
      opts: this.opts
    });
  };

  DownloadManager.prototype.init = function() {
    var col, dfr, go_on;
    dfr = new CUI.Deferred();
    go_on = (function(_this) {
      return function() {
        return DownloadManager.__super__.init.call(_this).done(function() {
          if (_this.getOriginalCount() > DownloadManager.maxObjects) {
            return CUI.problem({
              text: $$("download.manager.error.max_1000_objects")
            }).done(dfr.reject);
          } else {
            return dfr.resolve();
          }
        }).fail(dfr.reject);
      };
    })(this);
    if (this._collection) {
      col = this._collection;
      this.__search = new SearchCollectionHeadless({
        collection: col
      });
      go_on();
    } else if (this._search) {
      this.__search = this._search;
      go_on();
    } else {
      col = new CollectionTemporary();
      col.insertObjects([this._result_object.getCollectionObject()]).done((function(_this) {
        return function() {
          _this.__search = new SearchCollectionHeadless({
            collection: col
          });
          return go_on();
        };
      })(this)).fail(dfr.reject);
    }
    return dfr.promise();
  };

  DownloadManager.prototype.getGatherBaseDataRequestForExport = function() {
    return false;
  };

  DownloadManager.prototype.hasDownloadableVersion = function() {
    var asset, assets, easydb, i, idx, inst, len, ref, value;
    assets = this._result_object.getAssetsForBrowser("detail");
    if (assets.length === 0) {
      return false;
    }
    for (idx = i = 0, len = assets.length; i < len; idx = ++i) {
      asset = assets[idx];
      if (ez5.connector) {
        inst = (ref = asset.data) != null ? ref._instance : void 0;
        if (inst) {
          easydb = ez5.connector.getRemoteEasydbByInstance(inst);
          if (easydb && !easydb.getSession().hasSystemRight("root", "frontend_features[download]")) {
            console.info("Connector: Download not allowed for:", easydb.getDisplayname());
            continue;
          }
        }
      }
      value = asset.getValue();
      if (value._incomplete_versions) {
        return true;
      }
      if (Asset.getDownloadVersions(value).length > 0) {
        return true;
      }
    }
    return false;
  };

  DownloadManager.prototype.getButton = function(button_opts) {
    var download_btn;
    if (button_opts == null) {
      button_opts = {};
    }
    if (!this.hasDownloadableVersion()) {
      return null;
    }
    button_opts.onClick = (function(_this) {
      return function() {
        download_btn.disable();
        return _this.startExport().always(function() {
          return download_btn.enable();
        });
      };
    })(this);
    download_btn = new CUI.defaults["class"].Button(button_opts);
    return download_btn;
  };

  DownloadManager.prototype.getTitle = function(count) {
    if (count == null) {
      count = this.__titleCount;
    }
    if (count === 1) {
      return $$("download.manager.modal.title.one", {
        count: count
      });
    } else {
      return $$("download.manager.modal.title", {
        count: count
      });
    }
  };

  DownloadManager.prototype.getDownloadPrepareError = function() {
    return $$('download.manager.error.prepare.explain');
  };

  DownloadManager.prototype.getButtonStartLocaKey = function() {
    return 'download.manager.modal.button.start';
  };

  DownloadManager.showAdminMessagesFromAsset = function(asset) {
    var assetToFilter, assetsFilter, dfr, dm, i, len, ref, ref1, resultObject;
    dfr = new CUI.Deferred();
    if (!(asset != null ? asset.data : void 0) || !(asset != null ? (ref = asset.data) != null ? ref._global_object_id : void 0 : void 0)) {
      return dfr.resolve();
    }
    resultObject = new ResultObject();
    resultObject.setData(asset.data);
    assetsFilter = {};
    ref1 = resultObject.getAssetsForBrowser("all");
    for (i = 0, len = ref1.length; i < len; i++) {
      assetToFilter = ref1[i];
      if (assetToFilter.getId() === asset.getId()) {
        continue;
      }
      assetsFilter[assetToFilter.getId()] = false;
    }
    dm = new DownloadManager({
      result_object: resultObject,
      assetsFilter: assetsFilter
    });
    dm.init().done((function(_this) {
      return function() {
        return dm.gatherBaseData().fail(dfr.reject).done(function() {
          return dm.showUserAdminMessages().done(dfr.resolve).fail(dfr.reject);
        });
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  DownloadManager.showAdminMessagesFromAssetAndDownloadUrl = function(asset, download_url) {
    return DownloadManager.showAdminMessagesFromAsset(asset).done((function(_this) {
      return function() {
        var downloadBtn;
        downloadBtn = document.createElement('a');
        downloadBtn.href = download_url;
        downloadBtn.download = true;
        return downloadBtn.click();
      };
    })(this));
  };

  DownloadManager.prototype.showUserAdminMessages = function(easydb) {
    var dfr, obj, ref, ref1, repl_rec, ro, run_messages, stats;
    dfr = new CUI.Deferred();
    repl_rec = {};
    if (((ref = this.__search) != null ? ref.collection : void 0) instanceof CollectionSelection) {
      obj = (ref1 = this.__search.collection.getObjects()) != null ? ref1[0].getObject() : void 0;
    }
    if (obj) {
      if (!obj._global_object_id) {
        return dfr.resolve();
      }
      ro = new ResultObject().setData(obj);
    }
    run_messages = (function(_this) {
      return function(msgs, assetInfo) {
        var fn1, funcs, i, len, msg;
        if (assetInfo == null) {
          assetInfo = {};
        }
        if (msgs.length === 0) {
          dfr.resolve();
          return;
        }
        if (ro && CUI.util.isEmpty(repl_rec)) {
          repl_rec = ro.getReplacementRecord();
        }
        funcs = [];
        fn1 = function(msg) {
          return funcs.push(function() {
            var _msg;
            _msg = ez5.replaceMap(msg.getMessageLocalized(), repl_rec, $$("download.manager.default.replacement"));
            return msg.showMessage(_msg, true, false, assetInfo);
          });
        };
        for (i = 0, len = msgs.length; i < len; i++) {
          msg = msgs[i];
          fn1(msg);
        }
        return CUI.chainedCall.apply(CUI, funcs).done(dfr.resolve).fail(dfr.reject);
      };
    })(this);
    stats = this.getEASColumnsInfo().counts;
    ez5.defaults["class"].AdminMessage.load("download", easydb).done((function(_this) {
      return function(adminMessages) {
        var _info, am, asset_info, cls, gids, i, idFound, info, instance, j, l, len, len1, len2, len3, len4, m, map, msgs, n, object, objects, poolInfo, pools, poolsMatch, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, tagMatch, tagfilter, version, vname;
        msgs = [];
        for (i = 0, len = adminMessages.length; i < len; i++) {
          am = adminMessages[i];
          tagfilter = am.getTagfilter();
          pools = am.getPools();
          if (!tagfilter && !pools) {
            msgs.push(am);
            continue;
          }
          if (easydb) {
            instance = easydb.getInstance();
          } else {
            instance = "local";
          }
          map = (ref2 = stats.by_instance[instance]) != null ? ref2.by_class : void 0;
          tagMatch = true;
          if (tagfilter) {
            tagMatch = false;
            for (cls in map) {
              info = map[cls];
              ref3 = info.versions;
              for (vname in ref3) {
                _info = ref3[vname];
                ref4 = _info.versions;
                for (j = 0, len1 = ref4.length; j < len1; j++) {
                  version = ref4[j];
                  if (TagFilter.matchesTags(tagfilter, version.__object_data._tags)) {
                    tagMatch = true;
                    break;
                  }
                }
                if (tagMatch) {
                  break;
                }
              }
              if (tagMatch) {
                break;
              }
            }
          }
          poolsMatch = true;
          if ((pools != null ? (ref5 = pools.ids) != null ? ref5.length : void 0 : void 0) > 0) {
            poolsMatch = false;
            objects = _this.__search.getLastData().objects;
            for (l = 0, len2 = objects.length; l < len2; l++) {
              object = objects[l];
              poolInfo = object[object._objecttype]._pool;
              if (!CUI.util.isEmpty(poolInfo) && pools.ids.includes(poolInfo.pool._id.toString())) {
                poolsMatch = true;
                break;
              }
            }
          }
          if (tagMatch && poolsMatch) {
            msgs.push(am);
          }
        }
        gids = [];
        ref6 = _this.__search.getLastData().objects || [];
        for (m = 0, len3 = ref6.length; m < len3; m++) {
          object = ref6[m];
          gids.push(object._global_object_id);
        }
        asset_info = {
          object_ids: gids,
          assets: new Set()
        };
        for (cls in map) {
          info = map[cls];
          idFound = null;
          ref7 = info.versions;
          for (vname in ref7) {
            _info = ref7[vname];
            ref8 = _info.versions;
            for (n = 0, len4 = ref8.length; n < len4; n++) {
              version = ref8[n];
              idFound = version != null ? (ref9 = version.__asset) != null ? ref9.getId() : void 0 : void 0;
              if (idFound) {
                asset_info.assets.add({
                  id: idFound,
                  basetype: "asset",
                  "class": cls
                });
              }
            }
            if (idFound) {
              break;
            }
          }
        }
        asset_info.assets = Array.from(asset_info.assets);
        return run_messages(msgs, asset_info);
      };
    })(this));
    return dfr.promise();
  };

  DownloadManager.prototype.filterRequest = function(request) {
    return request;
  };

  DownloadManager.prototype.startConnectorDownload = function() {
    var info, instance, ref;
    ref = this.getEASColumnsInfo().counts.by_instance;
    for (instance in ref) {
      info = ref[instance];
      if (instance !== 'local') {
        return true;
      }
    }
    return false;
  };

  DownloadManager.prototype.startExport = function() {
    var dfr;
    dfr = new CUI.Deferred();
    this.init().fail(dfr.reject).done((function(_this) {
      return function() {
        return _this.gatherBaseData().fail(dfr.reject).done(function() {
          if (_this.startConnectorDownload()) {
            ez5.connector.startDownload({
              manager: _this
            }).fail(dfr.reject).done(dfr.resolve);
            return;
          }
          return _this.showUserAdminMessages().fail(dfr.reject).done(function() {
            var content, mod, show_error;
            mod = null;
            _this.saveButton = new LocaButton({
              loca_key: _this.getButtonStartLocaKey(),
              ui: "download.manager:" + (_this.getButtonStartLocaKey()),
              left: true,
              primary: true,
              onClick: function(ev) {
                mod.disableAllButtons();
                _this.saveButton.setIcon("spinner");
                return _this.saveExport(ev).done(function() {
                  dfr.resolve();
                  return mod.destroy();
                }).fail(function() {
                  _this.saveButton.setIcon();
                  return mod.enableAllButtons();
                });
              }
            });
            content = _this.getContent();
            show_error = function() {
              return CUI.problem({
                text: _this.getDownloadPrepareError()
              }).done(dfr.reject);
            };
            if (!content) {
              show_error();
              return;
            }
            return CUI.chainedCall(content).done(function(_content) {
              mod = new CUI.ConfirmationDialog({
                icon: $$("download.manager.modal.icon"),
                title: _this.getTitle(),
                "class": "ez5-download-manager-confirmation-dialog ez5-event-poller",
                cancel: true,
                onCancel: function() {
                  dfr.reject("user_rejected");
                },
                content: _content,
                buttons: function() {
                  return [_this.saveButton];
                }
              }).show();
              return dfr.notify("modal_open");
            }).fail(function() {
              return show_error();
            });
          });
        });
      };
    })(this));
    return dfr.promise();
  };

  DownloadManager.prototype.getFormFieldsFromStats = function(stats, eas_config, loca_key_prefix) {
    var _v, cls, ext, exts, form_fields, i, j, len, len1, loca_key, opts, ref, ref1, ref2, size, stat, version_stat, vn, vprint;
    if (eas_config == null) {
      eas_config = ez5.session.getEASConfig();
    }
    if (loca_key_prefix == null) {
      loca_key_prefix = "download.manager.";
    }
    form_fields = [];
    for (cls in stats) {
      stat = stats[cls];
      if (!stat.total) {
        continue;
      }
      opts = [];
      ref = Asset.getExportVersionNamesForClass(cls, true, eas_config);
      for (i = 0, len = ref.length; i < len; i++) {
        vn = ref[i];
        if (stat.versions) {
          version_stat = stat.versions[vn];
          if (!(version_stat != null ? version_stat.total : void 0)) {
            continue;
          }
        } else {
          if (vn === "original") {
            version_stat = stat;
          } else {
            version_stat = null;
          }
        }
        ext = null;
        if (version_stat) {
          size = ez5.format_filesize(version_stat.acc_filesize);
          if (((ref1 = version_stat.versions) != null ? ref1.length : void 0) > 0) {
            exts = {};
            ref2 = version_stat.versions;
            for (j = 0, len1 = ref2.length; j < len1; j++) {
              _v = ref2[j];
              exts[_v.extension] = true;
            }
            ext = Object.keys(exts).join("+");
            loca_key = loca_key_prefix + "version.with_size_and_extension";
          } else {
            loca_key = loca_key_prefix + "version.with_size";
          }
        } else {
          loca_key = loca_key_prefix + "version.without_size";
        }
        if (vn === "original") {
          vprint = $$("download.manager.format.original");
        } else {
          vprint = Asset.getPrintSizeForVersion(cls, vn, false, eas_config);
        }
        opts.push({
          text: $$(loca_key, {
            size: size,
            version: vprint,
            count: version_stat != null ? version_stat.total : void 0,
            extension: ext
          }),
          value: vn
        });
      }
      if (opts.length > 0) {
        form_fields.push({
          form: {
            label: $$(loca_key_prefix + "class", {
              count: "" + stat.total,
              "class": $$("server.eas.fileclass." + cls)
            })
          },
          name: cls,
          type: CUI.Options,
          horizontal: false,
          options: opts
        });
      }
    }
    return form_fields;
  };

  DownloadManager.prototype.getContent = function() {
    var add_metadata, bottom, cls, eas_info, formFieldFromStats, i, k, label, len, mf, ref, ref1, ref2, ref3, ref4, setCountLabel, stat, stats, v, vn;
    this.form_fields = [];
    eas_info = this.getEASColumnsInfo();
    stats = eas_info.counts;
    this.__titleCount = 0;
    setCountLabel = (function(_this) {
      return function() {
        var cls, count, label_txt, ref, stat;
        if (_this._assetsFilter) {
          return;
        }
        label_txt = [];
        ref = stats.by_class;
        for (cls in ref) {
          stat = ref[cls];
          if (!_this.form_data[cls]) {
            continue;
          }
          count = stat.total * _this.form_data[cls].length;
          label_txt.push((count + "x ") + $$("server.eas.fileclass." + cls));
        }
        label.setText(label_txt.join(", "));
      };
    })(this);
    ref = stats.by_class;
    for (cls in ref) {
      stat = ref[cls];
      if (!stat.total) {
        continue;
      }
      if (cls === "image" || cls === "audio" || cls === "video") {
        add_metadata = true;
      }
      this.__titleCount += stat.total;
      ref1 = Asset.getExportVersionNamesForClass(cls, true);
      for (i = 0, len = ref1.length; i < len; i++) {
        vn = ref1[i];
        if (!((ref2 = stat.versions) != null ? (ref3 = ref2[vn]) != null ? ref3.total : void 0 : void 0)) {
          continue;
        }
        if (!this.form_data[cls]) {
          this.form_data[cls] = [vn];
        }
      }
    }
    if (this._assetsFilter) {
      this.__titleCount = 0;
      ref4 = this._assetsFilter;
      for (k in ref4) {
        v = ref4[k];
        if (v) {
          this.__titleCount++;
        }
      }
    }
    formFieldFromStats = this.getFormFieldsFromStats(stats.by_class);
    if ((formFieldFromStats != null ? formFieldFromStats.length : void 0) > 0) {
      this.form_fields.push.apply(this.form_fields, formFieldFromStats);
    }
    if (this.form_fields.length === 0) {
      return false;
    }
    mf = this.getMetadataField();
    if (add_metadata && mf) {
      this.form_fields.push(mf);
    } else {
      this.form_data._metadata = "standard";
    }
    this.form_fields.push(this.getFilenameTemplateField());
    this.form_data._zip_download = stat.total > 1;
    this.form_fields.push({
      type: CUI.Checkbox,
      name: "_zip_download",
      ui: "download.manager.form.zip_download",
      form: {
        label: $$("download.manager.zip_download")
      }
    });
    if (ez5.version("6")) {
      this.form_data._include_non_preferred = false;
      this.form_fields.push({
        type: CUI.Checkbox,
        name: "_include_non_preferred",
        ui: "download.manager.form.include_non_preferred",
        form: {
          label: $$("download.manager.include_non_preferred")
        }
      });
    }
    bottom = CUI.dom.space();
    if (!this._assetsFilter) {
      label = new CUI.Label({
        "class": "ez5-download-manager-status",
        text: "",
        multiline: true
      });
      setCountLabel();
      bottom.appendChild(label.DOM);
    }
    return [
      new CUI.Form({
        fields: this.form_fields,
        onDataChanged: (function(_this) {
          return function() {
            var count, hasOneChecked, ref5;
            setCountLabel();
            hasOneChecked = false;
            for (cls in stats.by_class) {
              if (!_this.form_data[cls]) {
                continue;
              }
              count = _this.form_data[cls].length;
              if (count > 0) {
                hasOneChecked = true;
                break;
              }
            }
            if (!hasOneChecked) {
              _this.saveButton.disable();
              return;
            }
            ref5 = _this.form_data;
            for (cls in ref5) {
              v = ref5[cls];
              if (cls.startsWith("_")) {
                continue;
              }
              if (v !== false) {
                _this.saveButton.enable();
                return;
              }
            }
            return _this.saveButton.disable();
          };
        })(this),
        data: this.form_data
      }).start(), bottom
    ];
  };

  DownloadManager.prototype.getPluginSelect = function() {};

  DownloadManager.prototype.getExportSaveData = function() {
    var _vn, cls, data, fn, i, len, metadata, ref, req, stats, versionNames;
    stats = this.getEASColumnsInfo().counts;
    req = ExportManager.prototype.filterRequest.call(this, this.getRequest());
    data = {
      search: req,
      xml: false,
      eas_fields: {},
      classes: {},
      type: "download",
      filename_template: null,
      filename_original: null
    };
    for (fn in stats.by_field_name) {
      data.eas_fields[fn] = {
        files: true
      };
      if (this.form_data._include_non_preferred) {
        data.eas_fields[fn].include_non_preferred = true;
      }
    }
    metadata = CUI.util.getIntOrString(this.form_data._metadata);
    switch (this.form_data._template) {
      case "original":
        data.filename_original = true;
        break;
      case "custom":
        data.filename_template = this.form_data._template_custom;
    }
    ref = this.form_data;
    for (cls in ref) {
      versionNames = ref[cls];
      if (cls.startsWith("_")) {
        continue;
      }
      if (!versionNames) {
        continue;
      }
      data.classes[cls] = [];
      if (CUI.util.isArray(versionNames)) {
        for (i = 0, len = versionNames.length; i < len; i++) {
          _vn = versionNames[i];
          if (_vn === "original") {
            data.classes[cls].push({
              type: "current",
              metadata: metadata
            });
          } else {
            data.classes[cls].push({
              type: "version",
              version: _vn,
              metadata: metadata
            });
          }
        }
      }
    }
    return {
      "export": data
    };
  };

  DownloadManager.prototype.filterDownloadableFiles = function(files) {
    return files;
  };

  DownloadManager.prototype.getWaitDialogLocaKey = function() {
    return 'download.manager.preparing_download';
  };

  DownloadManager.prototype.downloadFiles = function(files, zip) {
    if (zip == null) {
      zip = false;
    }
    if (zip) {
      this.sendFile("zip/", this._zip_download_name);
      return CUI.resolvedPromise();
    }
    files = files.map((function(_this) {
      return function(file) {
        return {
          href: _this.getDownloadUrl("file/" + (Export.encodeURIFilePath(file.path))),
          name: file.name
        };
      };
    })(this));
    return ez5.download_files(files);
  };

  DownloadManager.prototype.getDownloadUrl = function(url) {
    return ez5.api.getFullBase() + '/export/' + this["export"].getId() + "/" + url + "?" + ez5.tokenParam + "=" + ez5.session.token + "&disposition=attachment";
  };

  DownloadManager.prototype.sendFile = function(url, zip_download_name) {
    var load_url;
    load_url = this.getDownloadUrl(url);
    if (zip_download_name) {
      load_url = load_url + "&filename=" + encodeURIComponent(zip_download_name);
    }
    return ez5.download_file({
      href: load_url
    });
  };

  DownloadManager.prototype.saveExport = function(ev) {
    var cc, data, dfr, loca_key, mypoll, set_failed, tell_failed, tell_warning;
    dfr = new CUI.Deferred();
    data = this.getExportSaveData();
    if (ev.hasModifierKey()) {
      console.debug(CUI.util.dump(data));
      return dfr.reject().promise();
    }
    loca_key = this.getWaitDialogLocaKey();
    if (loca_key) {
      cc = new CUI.ConfirmationChoice({
        content: new LocaLabel({
          loca_key: loca_key + '.message'
        }),
        choices: [
          {
            loca_key: loca_key + '.button.cancel'
          }
        ]
      });
      cc.open().done((function(_this) {
        return function() {
          CUI.Events.ignore(mypoll);
          return _this["export"]["delete"]().always(function() {
            return dfr.reject();
          });
        };
      })(this));
    } else {
      cc = null;
    }
    if (this._assetsFilter) {
      data["export"].assets = this._assetsFilter;
    }
    this["export"].data = data;
    mypoll = EventPoller.listen({
      instance: this,
      filter: (function(_this) {
        return function(ev) {
          var doneState, ref, ref1;
          doneState = ez5.version("6") ? (ref = (ref1 = ev.info) != null ? ref1.state : void 0) === 'done' || ref === 'done_with_warnings' || ref === 'failed' : true;
          return ev.type === 'OBJECT_UPDATE' && ev.basetype === 'export' && ev.object_id === _this["export"].getId() && doneState;
        };
      })(this),
      call: (function(_this) {
        return function(events) {
          if (cc != null) {
            cc.disableAllButtons();
          }
          _this["export"].load(true).done(function() {
            var files;
            switch (_this["export"].getState()) {
              case "done":
              case "done_with_warnings":
                if (cc != null) {
                  cc.destroy();
                }
                files = _this.filterDownloadableFiles(_this["export"].getFiles());
                if (!(files != null ? files.length : void 0)) {
                  return tell_failed();
                }
                CUI.Events.ignore(mypoll);
                if (_this["export"].getState() === "done_with_warnings") {
                  tell_warning();
                }
                _this.downloadFiles(files, _this.form_data._zip_download).fail(dfr.reject).done(dfr.resolve);
                return;
              case "failed":
                if (cc != null) {
                  cc.destroy();
                }
                tell_failed();
                return;
            }
            if (cc != null) {
              cc.enableAllButtons();
            }
          });
        };
      })(this)
    });
    tell_warning = (function(_this) {
      return function() {
        return CUI.problem({
          markdown: true,
          text: $$("download.manager.warning.export.explain", {
            name: _this["export"].getName(),
            logs: _this["export"].getWarningMessages()
          })
        });
      };
    })(this);
    tell_failed = (function(_this) {
      return function() {
        CUI.problem({
          text: $$("download.manager.error.export.explain", {
            name: _this["export"].getName()
          })
        });
        return dfr.reject();
      };
    })(this);
    set_failed = (function(_this) {
      return function() {};
    })(this);
    dfr.always(function() {
      if (cc != null) {
        cc.destroy();
      }
      return CUI.Events.ignore(mypoll);
    });
    this["export"].save().done((function(_this) {
      return function() {
        return _this["export"].start().fail(dfr.reject);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  return DownloadManager;

})(ExportManager);
// Generated by CoffeeScript 1.12.7
var ExportManagerResult,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  ExportManagerResult.prototype.initOpts = function() {
    ExportManagerResult.__super__.initOpts.call(this);
    return this.addOpts({
      manager: {
        mandatory: true,
        check: ExportManager
      },
      eas_info: {
        mandatory: true,
        check: 'PlainObject'
      }
    });
  };

  ExportManagerResult.prototype.addToRequest = function(request) {
    var _otm, col, eas_columns, i, include_fields, j, k, len, len1, ot_name, ref, ref1, v;
    if (request == null) {
      request = {};
    }
    ref = this._manager.getRequest();
    for (k in ref) {
      v = ref[k];
      request[k] = v;
    }
    request.aggregations = {};
    request.aggregations._mask = {
      field: "_mask",
      limit: 100000,
      type: "term"
    };
    if (this._manager.getOriginalCount() > DownloadManager.maxObjects) {
      this.__useAggregation = true;
      _otm = new ObjecttypeManager();
      _otm.addObjecttypes(function(table, mask) {
        var ref1;
        if (request.objecttypes && (ref1 = table.name(), indexOf.call(request.objecttypes, ref1) < 0)) {
          return false;
        } else {
          return true;
        }
      });
      _otm.initCommonFields("index", true, function(f) {
        return !(f instanceof MaskSplitter);
      });
      eas_columns = _otm.getEASFields("index");
      request.offset = 0;
      request.limit = 0;
      for (i = 0, len = eas_columns.length; i < len; i++) {
        col = eas_columns[i];
        if (!(col instanceof EASColumn)) {
          continue;
        }
        request.aggregations[col.fullName()] = {
          field: (col.fullName()) + ".class_extension",
          limit: 10000,
          value_field: (col.fullName()) + ".filesize",
          type: "term_stats"
        };
        request.aggregations[col.fullName() + ":term"] = {
          field: (col.fullName()) + ".class_extension",
          limit: 10000,
          type: "term"
        };
      }
    } else {
      include_fields = request.include_fields = [];
      ref1 = request.objecttypes || [];
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        ot_name = ref1[j];
        if (CUI.util.isNull(ez5.schema.CURRENT._objecttype_by_name[ot_name])) {
          console.warn("ExportManagerResult.addToRequest :: Skipping objecttype because it does not exist:", ot_name);
          continue;
        }
        include_fields.push.apply(include_fields, Objecttype.getIncludeFieldsForEASFields(ot_name));
      }
      request.format = "standard";
    }
    return this;
  };

  ExportManagerResult.prototype.showResultCollectAssets = function() {
    return false;
  };

  ExportManagerResult.prototype.showResult = function(request, data) {
    var facet, i, len, ref, term;
    facet = data.aggregations._mask;
    this._eas_info.otm = new ObjecttypeManager();
    ref = facet.terms;
    for (i = 0, len = ref.length; i < len; i++) {
      term = ref[i];
      this._eas_info.otm.addMask(ez5.mask.CURRENT._mask_instance_by_name[term.term]);
    }
    this._eas_info.otm.initCommonFields("all", true, function(f) {
      return !(f instanceof MaskSplitter);
    });
    this._eas_info.eas_fields = this._eas_info.otm.getEASFields();
    if ((data.count > DownloadManager.maxObjects || CUI.util.isEmpty(data.objects)) && this.__useAggregation) {
      return this.aggBulk(data);
    } else {
      return this.aggDetail(data);
    }
  };

  ExportManagerResult.prototype.aggBulk = function(data) {
    var cls, ext, facet, fname, inc_counts, ref, results, term;
    ref = data.aggregations;
    results = [];
    for (fname in ref) {
      facet = ref[fname];
      if (fname === "_mask" || fname.endsWith(":term")) {
        continue;
      }
      results.push((function() {
        var i, len, ref1, ref2, results1;
        ref1 = facet.terms;
        results1 = [];
        for (i = 0, len = ref1.length; i < len; i++) {
          term = ref1[i];
          ref2 = term.term.split("."), cls = ref2[0], ext = ref2[1];
          if (indexOf.call(Asset.fileclasses(), cls) < 0) {
            cls = "unknown";
          }
          this._eas_info.total += term.count;
          inc_counts = function(map) {
            if (!map.total) {
              map.total = 0;
            }
            map.total += term.count;
            if (!map[cls]) {
              map[cls] = {
                total: 0,
                acc_filesize: 0,
                by_extension: {}
              };
            }
            if (!map[cls].by_extension[ext]) {
              map[cls].by_extension[ext] = 0;
            }
            map[cls].total += term.count;
            map[cls].acc_filesize += term.sum;
            return map[cls].by_extension[ext] += term.count;
          };
          inc_counts(this._eas_info.counts.by_class);
          if (!this._eas_info.counts.by_field_name[fname]) {
            this._eas_info.counts.by_field_name[fname] = {};
          }
          results1.push(inc_counts(this._eas_info.counts.by_field_name[fname]));
        }
        return results1;
      }).call(this));
    }
    return results;
  };

  ExportManagerResult.prototype.aggDetail = function(data) {
    var asset, cls, ext, fn, i, idx, inc_count, inc_count2, init_count, instance, j, l, len, len1, len2, obj, ref, ref1, ref2, ref3, ro, value, version, vname;
    value = null;
    ext = null;
    cls = null;
    fn = null;
    vname = null;
    init_count = (function(_this) {
      return function(map) {
        if (!map.by_class) {
          map.by_class = {};
        }
        if (!map.by_class[cls]) {
          map.by_class[cls] = {
            total: 0,
            acc_filesize: 0,
            by_extension: {},
            versions: {}
          };
        }
        if (!map.by_field_name) {
          map.by_field_name = {};
        }
        if (!map.by_field_name[fn]) {
          map.by_field_name[fn] = {};
        }
        if (!map.by_field_name[fn][cls]) {
          map.by_field_name[fn][cls] = {
            total: 0,
            by_extension: {},
            acc_filesize: 0
          };
        }
      };
    })(this);
    inc_count = (function(_this) {
      return function(map) {
        map.total += 1;
        map.acc_filesize += value.filesize;
        if (!map.by_extension[ext]) {
          map.by_extension[ext] = 0;
        }
        map.by_extension[ext] += 1;
      };
    })(this);
    inc_count2 = (function(_this) {
      return function(map, version) {
        if (!map.by_class[cls].versions[vname]) {
          map.by_class[cls].versions[vname] = {
            total: 0,
            acc_filesize: 0,
            versions: []
          };
        }
        map.by_class[cls].versions[vname].total += 1;
        map.by_class[cls].versions[vname].versions.push(version);
        map.by_class[cls].versions[vname].acc_filesize += version.filesize;
      };
    })(this);
    ref = data.objects;
    for (i = 0, len = ref.length; i < len; i++) {
      obj = ref[i];
      ro = new ResultObject().setData(obj);
      ref1 = ro.getAssetsForBrowser(["detail", "standard"]);
      for (idx = j = 0, len1 = ref1.length; j < len1; idx = ++j) {
        asset = ref1[idx];
        value = asset.getValue();
        if (value._incomplete_versions) {
          continue;
        }
        if (value._field instanceof EASField) {
          fn = (ref2 = value._field._originField) != null ? ref2.fullName() : void 0;
        } else {
          if (value._field) {
            fn = value._field.fullName();
          } else {
            fn = asset.field.fullName() || "unknown field";
          }
        }
        cls = value["class"];
        ext = value.extension;
        instance = obj._instance || "local";
        this._eas_info.total += 1;
        init_count(this._eas_info.counts);
        inc_count(this._eas_info.counts.by_class[cls]);
        inc_count(this._eas_info.counts.by_field_name[fn][cls]);
        if (!this._eas_info.counts.by_instance[instance]) {
          this._eas_info.counts.by_instance[instance] = {};
        }
        init_count(this._eas_info.counts.by_instance[instance]);
        inc_count(this._eas_info.counts.by_instance[instance].by_class[cls]);
        inc_count(this._eas_info.counts.by_instance[instance].by_field_name[fn][cls]);
        if (this.showResultCollectAssets()) {
          asset.__object_data = obj;
          this._eas_info.assets.push(asset);
        }
        ref3 = Asset.getDownloadVersions(value);
        for (l = 0, len2 = ref3.length; l < len2; l++) {
          version = ref3[l];
          vname = version.version;
          if (!this._manager.acceptVersionForDownload(version)) {
            continue;
          }
          version.__object_data = obj;
          version.__asset = asset;
          inc_count2(this._eas_info.counts, version);
          inc_count2(this._eas_info.counts.by_instance[instance], version);
        }
      }
    }
  };

  return ExportManagerResult;

})(SearchManager);
// Generated by CoffeeScript 1.12.7
var ExportManagerFieldTreeNode,
  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;

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

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

  ExportManagerFieldTreeNode.regexDisplayName = "^[a-zA-Z0-9_:]+$";

  ExportManagerFieldTreeNode.regexpDisplayNameInstance = new RegExp(ExportManagerFieldTreeNode.regexDisplayName);

  ExportManagerFieldTreeNode.prototype.initOpts = function() {
    ExportManagerFieldTreeNode.__super__.initOpts.call(this);
    return this.addOpts({
      exportManagerEasydb: {
        check: ExportManagerEasydb
      }
    });
  };

  ExportManagerFieldTreeNode.prototype.getModeForNested = function() {
    return "export";
  };

  ExportManagerFieldTreeNode.prototype.setCheckbox = function(enable_disable) {
    ExportManagerFieldTreeNode.__super__.setCheckbox.call(this, enable_disable);
    if (enable_disable) {
      if (this.father && this.father instanceof ExportManagerFieldTreeNode && this.father.isOpen() && !this.father.data._enabled) {
        this.father.setCheckbox(true);
      }
    }
    return this;
  };

  ExportManagerFieldTreeNode.prototype.removeFromDOM = function(remove_self) {
    if (remove_self == null) {
      remove_self = true;
    }
    ExportManagerFieldTreeNode.__super__.removeFromDOM.call(this, remove_self);
    this.checkbox = null;
    return this;
  };

  ExportManagerFieldTreeNode.prototype.__getNameInput = function() {
    return new CUI.Output(this.__getNameInputOpts());
  };

  ExportManagerFieldTreeNode.prototype.getLinkedObjectRenderDepth = function() {
    return 0;
  };

  ExportManagerFieldTreeNode.prototype.renderContent = function() {
    var row;
    row = ExportManagerFieldTreeNode.__super__.renderContent.call(this);
    if (this.data._disabled) {
      new CUI.Tooltip({
        element: row,
        text: $$("export.manager.field.selector.disabled.tooltip")
      });
    }
    return row;
  };

  ExportManagerFieldTreeNode.prototype.nodeAdded = function(level) {
    ExportManagerFieldTreeNode.__super__.nodeAdded.call(this, level);
    if (level) {
      this._data[this.fullFieldName()]._level = level;
    }
    if (this.field.isTopLevelField()) {
      this._data[this.fullFieldName()]._topLevel = true;
    }
    if (this.field.isSystemField()) {
      this._data[this.fullFieldName()]._sytemField = true;
    }
    this.data = this._data[this.fullFieldName()];
  };

  ExportManagerFieldTreeNode.prototype.isValid = function() {
    return true;
  };

  ExportManagerFieldTreeNode.prototype.__isNameInputEditable = function() {
    return true;
  };

  ExportManagerFieldTreeNode.prototype.__getNameInputOpts = function() {
    var opts;
    opts = {
      undo_and_changed_support: false,
      name: "display_name",
      data: this.data,
      disabled: this.fieldIsDisabled() || !this.data._enabled
    };
    return opts;
  };

  ExportManagerFieldTreeNode.prototype.__getDefaultEnabled = function() {
    return false;
  };

  return ExportManagerFieldTreeNode;

})(BasicFieldsFormNode);
// Generated by CoffeeScript 1.12.7
var Export,
  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;

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

  function Export(data) {
    this.data = data != null ? data : {};
    if (!this.getId()) {
      this.initData();
    }
  }

  Export.prototype.initData = function() {
    var i, k, len, ref;
    ref = ["_transports", "_schedules"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      if (!this.data.hasOwnProperty(k)) {
        this.data[k] = [];
      }
    }
    if (!this.data["export"].assets) {
      this.data["export"].assets = {};
    }
    if (!this.data["export"].eas_fields) {
      this.data["export"].eas_fields = [];
    }
    return this.__fullyLoaded = true;
  };

  Export.prototype.save = function(ev) {
    var ref, sd, sdfr;
    sd = this.getSaveData();
    if (ev != null ? ev.hasModifierKey(true) : void 0) {
      console.debug("save export", "data:", this.data, CUI.util.dump(sd));
      return;
    }
    if (((ref = sd["export"].search) != null ? ref.aggregations : void 0) != null) {
      delete sd["export"].search.aggregations;
    }
    if (!sd["export"]._version) {
      sd["export"]._version = 1;
      sdfr = ez5.api["export"]({
        type: "PUT",
        json_data: sd
      });
    } else {
      sd["export"]._version++;
      sdfr = ez5.api["export"]({
        api: "/" + this.getId(),
        type: "POST",
        json_data: sd
      });
    }
    return sdfr.done((function(_this) {
      return function(data) {
        _this.data = data;
        return _this.initData();
      };
    })(this));
  };

  Export.prototype.getSearch = function() {
    return this.getData()["export"].search;
  };

  Export.prototype.getName = function() {
    return this.getData()["export"].name;
  };

  Export.prototype.getType = function() {
    return this.getData()["export"].type;
  };

  Export.prototype.getSaveData = function() {
    var i, item, j, k, len, len1, ref, ref1, ref2, sd;
    sd = CUI.util.copyObject(this.data, true);
    ref = ["_transports", "_schedules"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      if (!((ref1 = sd[k]) != null ? ref1.length : void 0)) {
        sd[k] = null;
      } else {
        ref2 = sd[k];
        for (j = 0, len1 = ref2.length; j < len1; j++) {
          item = ref2[j];
          delete item._log;
        }
      }
    }
    delete sd._log;
    delete sd._state;
    delete sd._files;
    if (CUI.util.isEmptyObject(sd["export"].assets)) {
      sd["export"].assets = {};
    }
    return sd;
  };

  Export.prototype.setExportData = function(export_data) {
    if (this.getId()) {
      export_data._id = this.getId();
      export_data._version = this.data["export"]._version;
    }
    this.data["export"] = export_data;
    return this;
  };

  Export.prototype.getDownloadButton = function() {
    var url;
    url = ez5.api.getFullBase() + "/export/" + this.getId() + "/zip/?" + ez5.tokenParam + "=" + ez5.session.token + "&disposition=attachment";
    return new LocaButtonHref({
      loca_key: "export.button.download",
      download: true,
      href: url
    });
  };

  Export.prototype.getFiles = function() {
    var ref;
    return (ref = this.data) != null ? ref._files : void 0;
  };

  Export.prototype.start = function() {
    return ez5.api["export"]({
      api: "/" + (this.getId()) + "/start",
      type: "POST"
    }).done((function(_this) {
      return function(data) {
        _this.data = data;
        return _this.initData();
      };
    })(this));
  };

  Export.prototype.stop = function() {
    return ez5.api["export"]({
      api: "/" + (this.getId()) + "/stop",
      type: "POST"
    }).done((function(_this) {
      return function(data) {
        _this.data = data;
        return _this.initData();
      };
    })(this));
  };

  Export.prototype.load = function(force) {
    if (force == null) {
      force = false;
    }
    if (this.__fullyLoaded && !force) {
      return new CUI.Deferred().resolve(this.data).promise();
    }
    if (this.__loading) {
      return this.__loading;
    }
    return this.__loading = ez5.api["export"]({
      type: "GET",
      api: "/" + this.getId(),
      data: {
        format: "standard"
      }
    }).done((function(_this) {
      return function(data) {
        _this.data = data;
        return _this.initData();
      };
    })(this)).always((function(_this) {
      return function() {
        return _this.__loading = null;
      };
    })(this));
  };

  Export.prototype.getChildren = function(getNodesFunc) {
    var dfr;
    CUI.util.assert(CUI.util.isFunction(getNodesFunc), "Export.getChildren", "Parameter must be Function", {
      getNodesFunc: getNodesFunc
    });
    dfr = new CUI.Deferred();
    this.load().done((function(_this) {
      return function() {
        return dfr.resolve(getNodesFunc.call(_this));
      };
    })(this)).fail(function(xhr) {
      return dfr.reject();
    });
    return dfr.promise();
  };

  Export.prototype.getId = function() {
    return this.data["export"]._id;
  };

  Export.prototype.getState = function() {
    return this.data._state;
  };

  Export.prototype.getStateLocalized = function() {
    return $$("server.export.state." + (this.getState()));
  };

  Export.prototype.getStateColumn = function() {
    return new CUI.ListViewColumn({
      "class": "ez5-export-state-" + (this.getState()),
      text: this.getStateLocalized()
    });
  };

  Export.prototype.getData = function() {
    return this.data;
  };

  Export.prototype.getExportData = function() {
    return this.data["export"];
  };

  Export.prototype.getVersion = function() {
    return this.data["export"]._version;
  };

  Export.prototype["delete"] = function() {
    if (!this.getId()) {
      return CUI.resolvedPromise();
    }
    return ez5.api["export"]({
      type: 'DELETE',
      api: '/' + this.getId()
    });
  };

  Export.prototype.showInSearch = function(search) {
    return this.load().done((function(_this) {
      return function() {
        var si;
        si = search != null ? typeof search.getSearchInput === "function" ? search.getSearchInput() : void 0 : void 0;
        CUI.util.assert(search instanceof Search && si instanceof SearchInput, "Export.showInSearch", "Parameter needs to be instance of Search. Search needs to implement getSearchInput.", {
          search: search,
          searchInput: si
        });
        si.empty();
        si.addPlaceholder();
        si.add(new ExportQueryElement({
          "export": _this
        }));
        si.addPlaceholder();
        return search.execute();
      };
    })(this));
  };

  Export.encodeURIFilePath = function(path) {
    if (ez5.version("6.3.1")) {
      return path.replace(/%2F/g, "/");
    }
    return encodeURIComponent(path).replace(/%2F/g, "/");
  };

  Export.prototype.getWarningMessages = function() {
    var i, len, log, ref, ref1, ref2, ref3;
    if (!this.data._log || this.getState() !== "done_with_warnings") {
      return "";
    }
    ref = this.data._log;
    for (i = 0, len = ref.length; i < len; i++) {
      log = ref[i];
      if (((ref1 = log.event) != null ? (ref2 = ref1.info) != null ? ref2.state : void 0 : void 0) === "done_with_warnings") {
        return (ref3 = log.event.info.protocol) != null ? ref3.split("\n") : void 0;
      }
    }
    return "";
  };

  return Export;

})(CUI.Dummy);
// Generated by CoffeeScript 1.12.7
var ExportManagerList,
  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;

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

  function ExportManagerList(opts) {
    this.opts = opts != null ? opts : {};
    ExportManagerList.__super__.constructor.call(this, this.opts);
    this.exportVersions = {};
    this.__showAll = false;
  }

  ExportManagerList.prototype.is_allowed = function() {
    return ez5.session.hasSystemRight("root", "frontend_features[export]");
  };

  ExportManagerList.prototype.limit = 20;

  ExportManagerList.prototype.getDisplay = function() {
    var container, update_display;
    container = CUI.dom.div("tray-item export-manager-list-tray-container");
    CUI.dom.append(container, new LocaButton({
      ui: "export.manager.list.tray.button",
      loca_key: "export.manager.list.button.tray",
      "class": "ez5-export-manager-list-tray-button",
      appearance: "transparent-border",
      icon: new CUI.Icon({
        "class": "fa-download"
      }),
      onClick: (function(_this) {
        return function(ev) {
          return _this.showModal(ev);
        };
      })(this)
    }).DOM);
    this.badge = CUI.dom.div("export-manager-list-tray-container-badge");
    CUI.dom.hideElement(this.badge);
    CUI.Events.ignore({
      instance: this
    });
    update_display = (function(_this) {
      return function() {
        return _this.updateDisplay();
      };
    })(this);
    EventPoller.listen({
      instance: this,
      filter: {
        type: ['OBJECT_UPDATE', 'OBJECT_DELETE'],
        basetype: 'export'
      },
      call: (function(_this) {
        return function(events) {
          return CUI.scheduleCallback({
            ms: 3000,
            call: update_display
          });
        };
      })(this)
    });
    CUI.dom.append(container, this.badge);
    this.updateDisplay(true);
    return container;
  };

  ExportManagerList.status_badge_map = {
    "new": null,
    pending: "working",
    processing: "working",
    done: "done",
    done_with_warnings: "done",
    failed: "failed"
  };

  ExportManagerList.prototype.__resetExportVersions = function() {
    var badge, id, ref, stats, version;
    ref = this.badgeStats;
    for (badge in ref) {
      stats = ref[badge];
      for (id in stats) {
        version = stats[id];
        this.exportVersions[id] = version;
      }
    }
  };

  ExportManagerList.prototype.updateDisplay = function(init) {
    if (init == null) {
      init = false;
    }
    this.badgeStats = {
      working: {},
      done: {},
      failed: {}
    };
    return this.loadExports().done((function(_this) {
      return function(exports) {
        var badge, c, exp, found, i, id, j, len, len1, ref, version;
        for (i = 0, len = exports.length; i < len; i++) {
          exp = exports[i];
          id = exp.getId();
          version = exp.getVersion();
          if (!_this.exportVersions[id]) {
            if (init) {
              _this.exportVersions[id] = version;
            } else {
              _this.exportVersions[id] = 0;
            }
          }
          badge = ExportManagerList.status_badge_map[exp.getState()];
          if (badge) {
            _this.badgeStats[badge][id] = version;
          }
          if (!_this.modal) {
            continue;
          }
          found = false;
          ref = _this.tree.getRootChildren();
          for (j = 0, len1 = ref.length; j < len1; j++) {
            c = ref[j];
            if (!(c instanceof ExportManagerListTopLevelNode)) {
              continue;
            }
            if (c.getExport().getId() === exp.getId()) {
              found = true;
              if (c.getCurrentVersion() !== exp.getVersion()) {
                c.setExport(exp);
                c.reload();
              }
            }
          }
          if (!found) {
            _this.tree.addNode(new ExportManagerListTopLevelNode({
              "export": exp,
              manager: _this
            }));
          }
        }
        _this.updateDisplayBadge();
      };
    })(this));
  };

  ExportManagerList.prototype.updateDisplayBadge = function() {
    var badge, count, count_badge, i, len, ref;
    count_badge = (function(_this) {
      return function(type) {
        var count, id, ref, version;
        count = 0;
        ref = _this.badgeStats[type];
        for (id in ref) {
          version = ref[id];
          switch (type) {
            case "working":
              count++;
              break;
            default:
              if (version > _this.exportVersions[id]) {
                count++;
              }
          }
        }
        return count;
      };
    })(this);
    ref = ["failed", "done", "working"];
    for (i = 0, len = ref.length; i < len; i++) {
      badge = ref[i];
      count = count_badge(badge);
      if (count > 0) {
        CUI.dom.showElement(this.badge);
        this.badge.textContent = count;
        CUI.dom.setAttribute(this.badge, "badge", badge);
        return;
      }
    }
    CUI.dom.hideElement(this.badge);
  };

  ExportManagerList.prototype.loadExports = function(offset1, show_all) {
    var dfr, filter;
    this.offset = offset1 != null ? offset1 : this.offset;
    dfr = new CUI.Deferred();
    if (show_all) {
      filter = void 0;
    } else {
      filter = "type:download+status:failed|done_with_warnings,type:export|export_incremental";
    }
    ez5.api["export"]({
      type: "GET",
      data: {
        limit: this.limit,
        offset: this.offset,
        filter: filter
      }
    }).done((function(_this) {
      return function(__data) {
        var e, exports, i, j, k, len, len1, ref, ref1;
        _this.__data = __data;
        exports = [];
        ref = _this.__data.objects;
        for (i = 0, len = ref.length; i < len; i++) {
          e = ref[i];
          ref1 = ["_schedules", "_transports", "_files", "_downloads"];
          for (j = 0, len1 = ref1.length; j < len1; j++) {
            k = ref1[j];
            if (!e[k]) {
              e[k] = [];
            }
          }
          exports.push(new Export(e));
        }
        _this.__updateNavigation();
        return dfr.resolve(exports);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  ExportManagerList.prototype.loadTree = function(offset, show_all) {
    var dfr;
    if (offset == null) {
      offset = 0;
    }
    if (show_all == null) {
      show_all = this.__showAll;
    }
    this.tree.showWaitBlock();
    dfr = new CUI.Deferred();
    this.loadExports(offset, show_all).always((function(_this) {
      return function() {
        return _this.tree.hideWaitBlock();
      };
    })(this)).done((function(_this) {
      return function(__exports) {
        var exp, export_nodes;
        _this.__exports = __exports;
        export_nodes = (function() {
          var i, len, ref, results;
          ref = this.__exports;
          results = [];
          for (i = 0, len = ref.length; i < len; i++) {
            exp = ref[i];
            results.push(new ExportManagerListTopLevelNode({
              "export": exp,
              manager: this
            }));
          }
          return results;
        }).call(_this);
        export_nodes.splice(0, 0, new ExportManagerListHeaderNode());
        _this.tree.root.removeFromDOM(false);
        _this.tree.root.children = export_nodes;
        return _this.tree.root.open().done(dfr.resolve).fail(dfr.reject);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  ExportManagerList.prototype.__updateNavigation = function() {
    var navi;
    if (!this.tree) {
      return;
    }
    navi = SystemListManager.renderNavigation({
      count: this.__data.count,
      limit: this.__data.limit,
      offset: this.__data.offset,
      callback: (function(_this) {
        return function(offset) {
          return _this.loadTree(offset);
        };
      })(this)
    });
    if (this.__data.objects.length === 0 && this.__data.count > 0) {
      this.loadTree(0);
    }
    this.tree.replace(navi, "footer_right");
  };

  ExportManagerList.prototype.showModal = function(ev) {
    this.requestOpenModal = false;
    this.tree = new CUI.ListViewTree({
      fixedRows: 1,
      cols: ["maximize", "auto", "auto", "auto", "auto"],
      maximize: true,
      force_footer: true,
      colClasses: ["ez5-export-manager-list-column-main", "ez5-export-manager-list-column-timestamp", "ez5-export-manager-list-column-type", "ez5-export-manager-list-column-status", "ez5-export-manager-list-column-buttons"],
      "class": "export-manager-list-table cui-lv--has-datafields"
    });
    this.modal = new CUI.Modal({
      "class": "export-manager-list-modal",
      cancel: true,
      onCancel: (function(_this) {
        return function() {
          return _this.closeModal();
        };
      })(this),
      pane: {
        header_left: new LocaLabel({
          loca_key: "export.manager.list.title"
        }).DOM,
        content: this.tree.render(),
        footer_right: {
          loca_key: "export.manager.list.button.done",
          primary: true,
          onClick: (function(_this) {
            return function() {
              return _this.closeModal();
            };
          })(this)
        }
      }
    });
    this.__resetExportVersions();
    this.modal.show();
    return this.loadTree(0, ev.altKey()).done((function(_this) {
      return function() {
        return _this.updateDisplayBadge();
      };
    })(this));
  };

  ExportManagerList.prototype.closeModal = function() {
    this.modal.destroy();
    this.modal = null;
    this.tree.destroy();
    this.tree = null;
    return this;
  };

  ExportManagerList.prototype.getSortValue = function() {
    return 2;
  };

  return ExportManagerList;

})(TrayApp);

ez5.session_ready(function() {
  return ez5.tray.registerApp(new ExportManagerList());
});
// Generated by CoffeeScript 1.12.7
var ExportQueryElement,
  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;

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

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

  ExportQueryElement.prototype.initOpts = function() {
    ExportQueryElement.__super__.initOpts.call(this);
    return this.addOpts({
      "export": {
        mandatory: true,
        check: Export
      }
    });
  };

  ExportQueryElement.prototype.getBadge = function() {
    return {
      name: $$("export.query.element.badge.name"),
      value: this._export.getData()["export"].name
    };
  };

  ExportQueryElement.prototype.getSearchFilter = function() {
    var filter, ref, req;
    req = CUI.util.copyObject(this._export.getData()["export"].search, true);
    filter = {
      type: "complex",
      bool: "must",
      search: req.search
    };
    if ((ref = req.objecttypes) != null ? ref.length : void 0) {
      filter.search.push({
        bool: "must",
        type: "in",
        fields: ["_objecttype"],
        "in": req.objecttypes
      });
    }
    return filter;
  };

  return ExportQueryElement;

})(QueryElementSpan);
// Generated by CoffeeScript 1.12.7
var ExportManagerListHeaderNode,
  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;

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

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

  ExportManagerListHeaderNode.prototype.initOpts = function() {
    ExportManagerListHeaderNode.__super__.initOpts.call(this);
    return this.removeOpt("headers");
  };

  ExportManagerListHeaderNode.prototype.readOpts = function() {
    var i, k, len, ref;
    ExportManagerListHeaderNode.__super__.readOpts.call(this);
    this._headers = [];
    ref = ["name", "date", "type", "status"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      this._headers.push({
        label: {
          text: $$("export.manager.list.header.node." + k)
        }
      });
    }
    this._headers.push();
    return this;
  };

  return ExportManagerListHeaderNode;

})(CUI.ListViewTreeHeaderNode);
// Generated by CoffeeScript 1.12.7
var ExportManagerListTopLevelNode,
  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;

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

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

  ExportManagerListTopLevelNode.prototype.initOpts = function() {
    ExportManagerListTopLevelNode.__super__.initOpts.call(this);
    this.addOpts({
      manager: {
        mandatory: true,
        check: ExportManagerList
      },
      "export": {
        mandatory: true,
        check: Export
      }
    });
    return this;
  };

  ExportManagerListTopLevelNode.prototype.readOpts = function() {
    ExportManagerListTopLevelNode.__super__.readOpts.call(this);
    this.manager = this._manager;
    this.setExport(this._export);
    return this;
  };

  ExportManagerListTopLevelNode.prototype.setExport = function(_export) {
    this["export"] = _export;
    this.__currentVersion = this["export"].getVersion();
    if (this.children) {
      this.close();
      delete this.children;
    }
    return this;
  };

  ExportManagerListTopLevelNode.prototype.getCurrentVersion = function() {
    return this.__currentVersion;
  };

  ExportManagerListTopLevelNode.prototype.getExport = function() {
    return this["export"];
  };

  ExportManagerListTopLevelNode.prototype.getChildren = function() {
    return this["export"].getChildren(function() {
      var nodes;
      return nodes = [
        new ExportManagerListEventsNode({
          log: this.getData()._log
        }), new ExportManagerListTransportsNode({
          "export": this
        }), new ExportManagerListFilesNode({
          "export": this
        })
      ];
    });
  };

  ExportManagerListTopLevelNode.prototype.renderContent = function() {
    var buttons, exp, ref, ref1, ref2, search, start_stop, stopDisabled, type;
    exp = this["export"].getData();
    this._schedules = new ScheduleEditor({
      button_type: "save",
      show_minutes: true,
      onButtonClick: (function(_this) {
        return function(ev, schedules) {
          _this["export"].getData()._schedules = schedules;
          return _this["export"].save(ev).done(function() {
            return _this.update();
          });
        };
      })(this),
      has_schedules: this["export"].getData()._has_schedules,
      loadSchedules: (function(_this) {
        return function() {
          return _this["export"].getChildren(function() {
            return this.getData()._schedules;
          });
        };
      })(this)
    });
    this._transports = new TransportsEditor({
      "export": this["export"],
      button_type: "save",
      onButtonClick: (function(_this) {
        return function(ev, transports) {
          _this["export"].getData()._transports = transports;
          return _this["export"].save().done(function() {
            return _this.update();
          });
        };
      })(this)
    });
    if ((ref = this["export"].getState()) === "pending" || ref === "processing") {
      start_stop = "stop";
    } else {
      start_stop = "start";
    }
    stopDisabled = ez5.version("6") && this["export"].getState() === "pending";
    this.startStopButton = new LocaButton({
      loca_key: "export.manager.list.top.level.node.button." + start_stop,
      disabled: stopDisabled,
      onClick: (function(_this) {
        return function(ev, df) {
          df.disable();
          return _this["export"][start_stop]().done(function(data) {
            return _this.update();
          });
        };
      })(this)
    });
    this.addColumn(new CUI.ListViewColumn({
      text: ez5.format_date_and_time(exp._last_updated_date)
    }));
    type = $$("export.manager.list.top.level.node.type." + this["export"].getType());
    this.addColumn(new CUI.ListViewColumn({
      text: type
    }));
    this.addColumn(this["export"].getStateColumn());
    buttons = [
      this["export"].getDownloadButton(), {
        group: "edit",
        loca_key: "export.manager.list.top.level.node.button.edit",
        onClick: (function(_this) {
          return function(_, button) {
            return _this.btnEdit(button);
          };
        })(this)
      }, this._schedules.getButton({
        group: "edit"
      }), this._transports.getButton({
        group: "edit"
      }), this.startStopButton, {
        loca_key: "export.manager.list.top.level.node.button.trash",
        onClick: (function(_this) {
          return function(ev) {
            return CUI.confirm({
              text: $$("export.manager.list.top.level.node.button.trash.confirm")
            }).done(function() {
              return _this.removeFromServer(ev);
            });
          };
        })(this)
      }
    ];
    if ((search = Search.findByName("SearchMain")[0])) {
      if ((ref1 = this.manager.tree) != null) {
        ref1.addClass("ez5-export-manager-list--has-search-button");
      }
      buttons.splice(1, 0, {
        loca_key: "export.manager.list.top.level.node.button.search",
        onClick: (function(_this) {
          return function() {
            return _this["export"].showInSearch(search).done(function() {
              return _this.manager.closeModal();
            });
          };
        })(this)
      });
      if (ez5.version("6") && ez5.session.hasSystemRight("system.root")) {
        if ((ref2 = this.manager.tree) != null) {
          ref2.addClass("ez5-export-manager-list--has-inspect-button");
        }
        buttons.push({
          group: "edit",
          icon: "fa-eye",
          onClick: (function(_this) {
            return function() {
              var ref3;
              return window.open((((ref3 = window.easydb_server_url) != null ? ref3 : "") + "/inspect/exports/") + _this["export"].getId() + "/", "_blank");
            };
          })(this)
        });
      }
    }
    this.addColumn(new CUI.ListViewColumn({
      element: new CUI.Buttonbar({
        buttons: buttons
      })
    }));
    return new CUI.Label({
      text: this["export"].getName(),
      multiline: true
    }).DOM;
  };

  ExportManagerListTopLevelNode.prototype.btnEdit = function(button) {
    button.startSpinner();
    return this["export"].load().done((function(_this) {
      return function() {
        var emptySearch;
        console.debug("export manager open", _this["export"]);
        emptySearch = new Search();
        return emptySearch.init().done(function() {
          button.stopSpinner();
          return (new ExportManager({
            "export": _this["export"],
            search: emptySearch
          })).prepareExport();
        });
      };
    })(this));
  };

  ExportManagerListTopLevelNode.prototype.removeFromServer = function() {
    return this["export"]["delete"]().done((function(_this) {
      return function() {
        return _this.remove();
      };
    })(this));
  };

  return ExportManagerListTopLevelNode;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var ExportManagerListEventNode,
  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;

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

  function ExportManagerListEventNode() {
    this.btnLogProtocol = bind(this.btnLogProtocol, this);
    this.btnShowEvent = bind(this.btnShowEvent, this);
    return ExportManagerListEventNode.__super__.constructor.apply(this, arguments);
  }

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

  ExportManagerListEventNode.prototype.readOpts = function() {
    ExportManagerListEventNode.__super__.readOpts.call(this);
    this.__event = this._event.event;
    this.__info = this.__event.info || {};
    return this.__protocol = this.__info.protocol;
  };

  ExportManagerListEventNode.prototype.renderContent = function() {
    var buttons, info, state;
    this.addColumn(new CUI.ListViewColumn({
      text: ez5.format_date_and_time(this.__event.timestamp)
    }));
    this.addColumn(new CUI.ListViewColumn());
    info = this.__event.info;
    if (ez5.version("6") && !CUI.util.isEmpty(info.transport_state)) {
      state = info.transport_state;
    } else {
      state = info != null ? info.state : void 0;
    }
    if (CUI.util.isEmpty(state)) {
      switch (this.__event.type) {
        case "DOWNLOAD_EXPORT":
          if (info.bytes_loaded === info.bytes_total) {
            state = $$("export.manager.list.event.node.complete_download");
          } else {
            state = $$("export.manager.list.event.node.incomplete_download");
          }
          break;
        default:
          state = "";
      }
    } else {
      state = $$("server.export.state." + state);
    }
    this.addColumn(new CUI.ListViewColumn({
      text: state
    }));
    buttons = [];
    if (!CUI.util.isEmpty(this.__protocol)) {
      buttons.push({
        loca_key: "export.manager.list.event.node.button.protocol",
        onClick: (function(_this) {
          return function(ev, btn) {
            return _this.btnLogProtocol(btn, _this.__protocol);
          };
        })(this)
      });
    }
    if (ez5.session.isDebug() || this.__event.type === "EXPORT_FAILED" || this.__event.type === "DONE_WITH_WARNINGS") {
      buttons.push({
        loca_key: "export.manager.list.event.node.button.info",
        onClick: (function(_this) {
          return function(ev, btn) {
            return _this.btnShowEvent(btn, _this.__event);
          };
        })(this)
      });
    }
    if (this.__info.exception) {
      buttons.push({
        loca_key: "export.manager.list.event.node.button.failed",
        onClick: (function(_this) {
          return function() {
            var ex;
            ex = _this.__info.exception;
            return CUI.problem({
              text: $$(ex.code, ex.parameters)
            });
          };
        })(this)
      });
    }
    if (buttons.length) {
      this.addColumn(new CUI.ListViewColumn({
        element: new CUI.Buttonbar({
          buttons: buttons
        })
      }));
    } else {
      this.addColumn(new CUI.ListViewColumnEmpty());
    }
    return new CUI.Label({
      multiline: true,
      text: $$("server.event." + this.__event.type)
    });
  };

  ExportManagerListEventNode.prototype.btnShowEvent = function(btn, event) {
    var objectDumper, popover;
    objectDumper = new CUI.ObjectDumper({
      object: event,
      do_open: true,
      onAfterRender: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            type: "content-resize",
            node: objectDumper.DOM
          });
        };
      })(this)
    });
    popover = new CUI.Popover({
      element: btn,
      size: "m",
      pane: {
        header_left: new CUI.Label({
          text: $$("export.manager.list.event.node.show.modal.title")
        }),
        content: objectDumper
      }
    }).show();
    return popover;
  };

  ExportManagerListEventNode.prototype.btnLogProtocol = function(btn, txt) {
    return new CUI.Popover({
      element: btn,
      pane: {
        header_left: new CUI.Label({
          text: $$("export.manager.list.event.node.protocol.modal.title")
        }),
        padded: true,
        content: new CUI.Label({
          multiline: true,
          text: txt
        })
      }
    }).show();
  };

  return ExportManagerListEventNode;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var ExportManagerListEventsNode,
  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;

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

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

  ExportManagerListEventsNode.prototype.initOpts = function() {
    ExportManagerListEventsNode.__super__.initOpts.call(this);
    return this.addOpts({
      log: {
        check: "Array"
      }
    });
  };

  ExportManagerListEventsNode.prototype.readOpts = function() {
    ExportManagerListEventsNode.__super__.readOpts.call(this);
    this.log = this._log;
    if (this.log) {
      return this.log.sort(function(a, b) {
        return CUI.util.compareIndex(b.event.timestamp, a.event.timestamp);
      });
    }
  };

  ExportManagerListEventsNode.prototype.hasChildren = function() {
    var ref;
    if (((ref = this.log) != null ? ref.length : void 0) > 0) {
      return true;
    } else {
      return false;
    }
  };

  ExportManagerListEventsNode.prototype.getChildren = function() {
    var i, le, len, ref, results;
    ref = this.log;
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      le = ref[i];
      results.push(new ExportManagerListEventNode({
        event: le
      }));
    }
    return results;
  };

  ExportManagerListEventsNode.prototype.renderContent = function() {
    return new LocaLabel({
      loca_key: "logs.node.name",
      multiline: true
    });
  };

  return ExportManagerListEventsNode;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var ExportManagerListTransportsNode,
  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;

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

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

  ExportManagerListTransportsNode.prototype.initOpts = function() {
    ExportManagerListTransportsNode.__super__.initOpts.call(this);
    this.addOpts({
      "export": {
        check: Export
      }
    });
    return this;
  };

  ExportManagerListTransportsNode.prototype.readOpts = function() {
    ExportManagerListTransportsNode.__super__.readOpts.call(this);
    this["export"] = this._export;
    return this;
  };

  ExportManagerListTransportsNode.prototype.hasChildren = function() {
    return this["export"].getData()._transports.length > 0;
  };

  ExportManagerListTransportsNode.prototype.getChildren = function() {
    var i, len, ref, results, tr;
    ref = this["export"].getData()._transports;
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      tr = ref[i];
      results.push(new ExportManagerListTransportNode({
        transport: tr
      }));
    }
    return results;
  };

  ExportManagerListTransportsNode.prototype.renderContent = function() {
    return new LocaLabel({
      loca_key: "export.manager.list.transports.node.name",
      multiline: true
    });
  };

  return ExportManagerListTransportsNode;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var ExportManagerListTransportNode,
  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;

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

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

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

  ExportManagerListTransportNode.prototype.readOpts = function() {
    ExportManagerListTransportNode.__super__.readOpts.call(this);
    return this.transport = this._transport;
  };

  ExportManagerListTransportNode.prototype.getChildren = function() {
    if (!this.__filesNode) {
      this.__filesNode = new ExportManagerListTransportNodeFiles({
        transport: this.transport
      });
    }
    if (this.__filesNode.hasChildren()) {
      return [this.__filesNode];
    }
    return null;
  };

  ExportManagerListTransportNode.prototype.hasChildren = function() {
    var ref;
    return ((ref = this.getChildren()) != null ? ref.length : void 0) > 0;
  };

  ExportManagerListTransportNode.prototype.renderContent = function() {
    var transport_type;
    this.addColumn(new CUI.ListViewColumnEmpty());
    if (this.transport.packer) {
      this.addColumn(new CUI.ListViewColumn({
        text: $$("transports.editor.col.packer." + this.transport.packer)
      }));
    } else {
      this.addColumn(new CUI.ListViewColumnEmpty());
    }
    if (!CUI.util.isEmpty(this.transport._state)) {
      this.addColumn(new CUI.ListViewColumn({
        text: $$("server.export.state." + this.transport._state)
      }));
    }
    transport_type = this.transport.type || this.transport.plugin;
    if (ez5.version("6") && CUI.util.isEmpty(transport_type)) {
      transport_type = "download";
    }
    return new CUI.Label({
      multiline: true,
      text: $$("export.manager.list.transport.node.type." + transport_type)
    });
  };

  return ExportManagerListTransportNode;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var ExportManagerListTransportNodeFiles,
  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;

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

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

  ExportManagerListTransportNodeFiles.prototype.renderContent = function() {
    return $$("export.manager.list.files.node.name");
  };

  ExportManagerListTransportNodeFiles.prototype.hasChildren = function() {
    var ref, ref1;
    if (((ref = this.transport._download) != null ? (ref1 = ref._files) != null ? ref1.length : void 0 : void 0) > 0) {
      return true;
    } else {
      return false;
    }
  };

  ExportManagerListTransportNodeFiles.prototype.getChildren = function() {
    var f, i, len, ref, ref1, results;
    ref1 = (ref = this.transport._download) != null ? ref._files : void 0;
    results = [];
    for (i = 0, len = ref1.length; i < len; i++) {
      f = ref1[i];
      results.push(new ExportManagerListTransportNodeFile({
        file: f
      }));
    }
    return results;
  };

  return ExportManagerListTransportNodeFiles;

})(ExportManagerListTransportNode);
// Generated by CoffeeScript 1.12.7
var ExportManagerListTransportNodeFile,
  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;

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

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

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

  ExportManagerListTransportNodeFile.prototype.readOpts = function() {
    ExportManagerListTransportNodeFile.__super__.readOpts.call(this);
    return this.file = this._file;
  };

  ExportManagerListTransportNodeFile.prototype.renderContent = function() {
    var buttons;
    this.addColumn(new CUI.ListViewColumnEmpty());
    this.addColumn(new CUI.ListViewColumn({
      text: ez5.format_filesize(this.file.size)
    }));
    this.addColumn(new CUI.ListViewColumnEmpty());
    buttons = [
      new CUI.ButtonHref({
        icon: "download",
        target: "_blank",
        href: this.file.url
      })
    ];
    this.addColumn(new CUI.ListViewColumn({
      element: new CUI.Buttonbar({
        buttons: buttons
      })
    }));
    return ez5.basename(this.file.url);
  };

  return ExportManagerListTransportNodeFile;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var ExportManagerListFilesNode,
  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;

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

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

  ExportManagerListFilesNode.prototype.initOpts = function() {
    ExportManagerListFilesNode.__super__.initOpts.call(this);
    return this.addOpts({
      "export": {
        mandatory: true,
        check: Export
      }
    });
  };

  ExportManagerListFilesNode.prototype.readOpts = function() {
    ExportManagerListFilesNode.__super__.readOpts.call(this);
    return this["export"] = this._export;
  };

  ExportManagerListFilesNode.prototype.hasChildren = function() {
    if (this["export"].getData()._files.length > 0) {
      return true;
    } else {
      return false;
    }
  };

  ExportManagerListFilesNode.prototype.getChildren = function() {
    var _f, _files, dir, dirs, f, file, files, i, idx, j, k, key, keys, l, len, len1, len2, len3, m, nodes, part, parts, path, ref, ref1;
    _files = this["export"].getData()._files;
    files = [];
    ref = this["export"].getData()._files;
    for (i = 0, len = ref.length; i < len; i++) {
      _f = ref[i];
      parts = _f.path.split("/");
      files.push({
        name: parts[parts.length - 1],
        path: _f.path,
        depth: parts.length,
        type: "f",
        size: _f.size,
        date_created: _f.date_created
      });
    }
    dirs = {};
    for (j = 0, len1 = files.length; j < len1; j++) {
      file = files[j];
      path = ez5.dirname(file.path);
      if (path === "") {
        continue;
      }
      parts = [];
      ref1 = path.split("/");
      for (idx = k = 0, len2 = ref1.length; k < len2; idx = ++k) {
        part = ref1[idx];
        parts.push(part);
        dir = parts.join("/");
        if (!dirs[dir]) {
          dirs[dir] = {
            path: dir,
            name: parts[parts.length - 1],
            type: "d",
            depth: parts.length
          };
        }
      }
    }
    keys = Object.keys(dirs);
    keys.sort();
    for (l = keys.length - 1; l >= 0; l += -1) {
      key = keys[l];
      files.splice(0, 0, dirs[key]);
    }
    nodes = [];
    for (m = 0, len3 = files.length; m < len3; m++) {
      f = files[m];
      if (f.depth === 1) {
        nodes.push(new ExportManagerListFileNode({
          "export": this["export"],
          file: f,
          files: files
        }));
      }
    }
    return nodes;
  };

  ExportManagerListFilesNode.prototype.renderContent = function() {
    var buttons;
    this.addColumn(new CUI.ListViewColumnEmpty());
    this.addColumn(new CUI.ListViewColumnEmpty());
    this.addColumn(new CUI.ListViewColumnEmpty());
    if (this.hasChildren()) {
      buttons = [this["export"].getDownloadButton()];
      this.addColumn(new CUI.ListViewColumn({
        element: new CUI.Buttonbar({
          buttons: buttons
        })
      }));
    } else {
      this.addColumn(new CUI.ListViewColumnEmpty());
    }
    return new LocaLabel({
      loca_key: "export.manager.list.files.node.name",
      multiline: true
    }).DOM;
  };

  return ExportManagerListFilesNode;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var ExportManagerListFileNode,
  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;

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

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

  ExportManagerListFileNode.prototype.initOpts = function() {
    ExportManagerListFileNode.__super__.initOpts.call(this);
    return this.addOpts({
      "export": {
        mandatory: true,
        check: Export
      },
      file: {
        mandatory: true,
        check: "PlainObject"
      },
      files: {
        mandatory: true,
        check: "Array"
      }
    });
  };

  ExportManagerListFileNode.prototype.readOpts = function() {
    ExportManagerListFileNode.__super__.readOpts.call(this);
    this["export"] = this._export;
    this.file = this._file;
    return this.files = this._files;
  };

  ExportManagerListFileNode.prototype.isLeaf = function() {
    return this.file.type === "f";
  };

  ExportManagerListFileNode.prototype.getChildren = function() {
    var file, i, len, nodes, ref;
    nodes = [];
    ref = this.files;
    for (i = 0, len = ref.length; i < len; i++) {
      file = ref[i];
      if (file.depth !== this.file.depth + 1) {
        continue;
      }
      if (file.path.substr(0, this.file.path.length) !== this.file.path) {
        continue;
      }
      nodes.push(new ExportManagerListFileNode({
        "export": this["export"],
        file: file,
        files: this.files
      }));
    }
    return nodes;
  };

  ExportManagerListFileNode.prototype.renderContent = function() {
    var base_url, buttons, file_url, file_url_short, ref, ref1;
    if (this.file.date_created) {
      this.addColumn(new CUI.ListViewColumn({
        text: ez5.format_date_and_time(this.file.date_created)
      }));
    } else {
      this.addColumn(new CUI.ListViewColumnEmpty());
    }
    if (this.file.size >= 0) {
      this.addColumn(new CUI.ListViewColumn({
        text: ez5.format_filesize(this.file.size)
      }));
    } else {
      this.addColumn(new CUI.ListViewColumnEmpty());
    }
    this.addColumn(new CUI.ListViewColumnEmpty());
    buttons = [];
    base_url = ez5.api.getFullBase() + "/export/" + this["export"].getId();
    file_url_short = Export.encodeURIFilePath(this.file.path);
    file_url = file_url_short + "?" + ez5.tokenParam + "=" + ez5.session.token;
    if ((ref = this.file.type) === "f") {
      buttons.push(new LocaButtonHref({
        loca_key: "export.manager.file.node.button.download",
        download: true,
        href: base_url + "/file/" + file_url + "&disposition=attachment"
      }));
      buttons.push(new LocaButtonHref({
        loca_key: "export.manager.file.node.button.show",
        disabled: this.file.size > 10000000,
        target: "_blank",
        href: base_url + "/file/" + file_url + "&disposition=inline"
      }));
    }
    if ((ref1 = this.file.type) === "f" || ref1 === "d") {
      buttons.push(new LocaButtonHref({
        loca_key: "export.manager.file.node.button.download_zip",
        download: true,
        href: base_url + "/zip/" + file_url + "&disposition=attachment"
      }));
    }
    this.addColumn(new CUI.ListViewColumn({
      element: new CUI.Buttonbar({
        buttons: buttons
      })
    }));
    return new CUI.Label({
      text: ez5.version("6.3.1") ? decodeURIComponent(this.file.name) : this.file.name,
      multiline: true
    });
  };

  return ExportManagerListFileNode;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var TransportsEditor,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  TransportsEditor.prototype.initOpts = function() {
    TransportsEditor.__super__.initOpts.call(this);
    return this.addOpts({
      "export": {
        mandatory: true,
        check: Export
      },
      button_type: {
        mandatory: true,
        check: ["apply", "save"]
      },
      onButtonClick: {
        check: Function
      }
    });
  };

  TransportsEditor.prototype.getButton = function(opts) {
    if (opts == null) {
      opts = {};
    }
    CUI.util.mergeMap(opts, {
      ui: "transport-editor-button",
      loca_key: "transport.editor.button",
      secondary: true,
      onClick: (function(_this) {
        return function() {
          return _this.openPopover();
        };
      })(this)
    });
    this.openButton = new LocaButton(opts);
    this.setButtonState();
    return this.openButton;
  };

  TransportsEditor.prototype.setButtonState = function() {
    var dt, ref;
    dt = this._export.getData();
    if (((ref = dt._transports) != null ? ref.length : void 0) > 0 || dt._has_transports) {
      this.openButton.activate();
    } else {
      this.openButton.deactivate();
    }
    return this;
  };

  TransportsEditor.prototype.checkChanged = function() {
    var ex;
    if (this.tree.getSelectedNode()) {
      this.minusButton.enable();
    } else {
      this.minusButton.disable();
    }
    try {
      if (this.__startData !== JSON.stringify(this.getSaveData())) {
        this.saveButton.enable();
      } else {
        this.saveButton.disable();
      }
    } catch (error) {
      ex = error;
      this.saveButton.disable();
      if (!(ex instanceof InvalidSaveDataException)) {
        throw ex;
      }
    }
  };

  TransportsEditor.prototype.getPluginByType = function(type) {
    var i, len, plugin, ref;
    ref = TransportsEditor.__plugins;
    for (i = 0, len = ref.length; i < len; i++) {
      plugin = ref[i];
      if (plugin.getType() === type) {
        return plugin;
      }
    }
    return null;
  };

  TransportsEditor.prototype.openPopover = function() {
    var i, len, plugin, ref, type_opts, update_form;
    this.saveButton = new LocaButton({
      loca_key: "transport.editor." + this._button_type + ".button",
      primary: true,
      onClick: (function(_this) {
        return function(ev) {
          var baseKey, d, i, k, len, ref, ret, saved, sd, v;
          sd = _this.getSaveData();
          if (ez5.version("6") && sd) {
            for (i = 0, len = sd.length; i < len; i++) {
              d = sd[i];
              ref = d["options"] || {};
              for (k in ref) {
                v = ref[k];
                if (!d["options"][k]) {
                  continue;
                }
                if (k.endsWith(":secret")) {
                  baseKey = k.slice(0, -7);
                  if (d["options"][baseKey]) {
                    d["options"][k] = d["options"][baseKey];
                    delete d["options"][baseKey];
                  } else if (v === "***" || v === "*****") {
                    delete d["options"][k];
                  }
                }
              }
            }
          }
          if (ev.hasModifierKey()) {
            console.debug("transport save", CUI.util.dump(sd));
            return;
          }
          saved = function() {
            _this.setButtonState();
            return _this.modal.destroy();
          };
          ret = typeof _this._onButtonClick === "function" ? _this._onButtonClick(ev, sd) : void 0;
          if (CUI.util.isPromise(ret)) {
            ret.done(saved);
          } else {
            saved();
          }
        };
      })(this)
    });
    update_form = (function(_this) {
      return function(row) {
        var d, disable, i, key, keys, len, plugin;
        d = row.getData();
        keys = ["type", "options", "packer", "email"];
        switch (d.type) {
          case "download":
            disable = ["options"];
            break;
          default:
            plugin = _this.getPluginByType(d.type);
            disable = ["email"];
            if (!(plugin != null ? plugin.isAllowed() : void 0)) {
              disable.push("type", "options");
            }
        }
        for (i = 0, len = keys.length; i < len; i++) {
          key = keys[i];
          if (indexOf.call(disable, key) >= 0) {
            row.getFieldsByName(key)[0].disable();
          } else {
            row.getFieldsByName(key)[0].enable();
          }
        }
      };
    })(this);
    this.minusButton = new LocaButton({
      loca_key: "transport.editor.minus.button",
      disabled: true,
      group: "plus-minus",
      onClick: (function(_this) {
        return function() {
          var ref;
          return (ref = _this.tree.getSelectedNode()) != null ? ref.remove() : void 0;
        };
      })(this)
    });
    type_opts = [
      {
        icon: ez5.loca.str_default("transports.editor.type.download|icon"),
        text: $$("transports.editor.type.download|text"),
        value: "download"
      }
    ];
    ref = TransportsEditor.__plugins;
    for (i = 0, len = ref.length; i < len; i++) {
      plugin = ref[i];
      type_opts.push({
        text: plugin.getDisplayType(),
        icon: plugin.getDisplayIcon(),
        disabled: !plugin.isAllowed(),
        value: plugin.getType()
      });
    }
    this.tree = new ListViewEditTree({
      selectableRows: true,
      "class": 'cui-lv--has-datafields',
      maximize: true,
      fixedRows: 2,
      rowMove: true,
      onSelect: (function(_this) {
        return function() {
          return _this.checkChanged();
        };
      })(this),
      onDeselect: (function(_this) {
        return function() {
          return _this.checkChanged();
        };
      })(this),
      end_add_row: function() {
        return update_form(this);
      },
      fields: [
        {
          th_label: "transports.editor.col.type",
          type: CUI.Select,
          onDataChanged: function(data, df) {
            var form, k, ref1, v;
            form = df.getForm();
            ref1 = data.options;
            for (k in ref1) {
              v = ref1[k];
              delete data.options[k];
            }
            form.getFieldsByName("options")[0].displayValue();
            form.getFieldsByName("packer")[0].reload();
            return update_form(form);
          },
          options: type_opts,
          name: "type"
        }, {
          th_label: "transports.editor.col.options",
          type: CUI.FormPopover,
          name: "options",
          trigger_data_changed_while_open: true,
          undo_and_changed_support: false,
          popover: {
            "class": "transports-options-popover",
            pane: {
              padded: true,
              header_left: new LocaLabel({
                loca_key: "transports.editor.col.options.header"
              })
            }
          },
          button: {
            loca_key: "transports.editor.col.options.button"
          },
          renderDisplayContent: (function(_this) {
            return function(df) {
              var data, div, form, j, len1, tag, tags;
              form = df.getForm();
              data = form.getData();
              plugin = _this.getPluginByType(data.type);
              if (!plugin) {
                return;
              }
              tags = plugin.getOptionsDisplay(data);
              if (!(tags != null ? tags.length : void 0)) {
                return;
              }
              div = CUI.dom.div("ez5-tag-holder");
              for (j = 0, len1 = tags.length; j < len1; j++) {
                tag = tags[j];
                div.appendChild(new CUI.Label({
                  "class": "ez5-tag",
                  text: tag
                }).DOM);
              }
              return div;
            };
          })(this),
          fields: (function(_this) {
            return function(df) {
              var data, form;
              form = df.getForm();
              if (!form) {
                return [];
              }
              data = form.getData();
              plugin = _this.getPluginByType(data.type);
              if (plugin) {
                return plugin.getOptions(data);
              }
              console.error("TransportEditor[getOptions] Type unknown:", data.type);
              return [];
            };
          })(this)
        }, {
          type: CUI.DataFieldProxy,
          th_label: "transports.editor.col.packer",
          name: "packer",
          element: (function(_this) {
            return function(field) {
              var data, select;
              data = field.getData();
              if (data.type !== "download") {
                plugin = _this.getPluginByType(data.type);
                if (!(plugin != null ? plugin.supportsPacker() : void 0)) {
                  return new CUI.EmptyLabel({
                    text: $$("transports.editor.packer.not-applicable")
                  });
                }
              }
              if (CUI.util.isUndef(data.packer)) {
                data.packer = "zip";
              }
              select = new CUI.Select({
                name: "packer",
                data: data,
                options: function() {
                  var j, k, len1, options, ref1;
                  options = [];
                  if (data.type !== "download") {
                    options.push({
                      text: $$("transports.editor.col.packer.without"),
                      value: null
                    });
                  }
                  ref1 = ["zip", "zip_2gb", "zip_10mb", "tar_bz2"];
                  for (j = 0, len1 = ref1.length; j < len1; j++) {
                    k = ref1[j];
                    options.push({
                      text: $$("transports.editor.col.packer." + k),
                      value: k
                    });
                  }
                  return options;
                }
              });
              select.start();
              return select;
            };
          })(this)
        }, {
          th_label: "transports.editor.col.emails",
          type: CUI.FormPopover,
          name: "email",
          button: {
            loca_key: "transports.editor.col.emails.button"
          },
          fields: [
            {
              form: {
                label: $$("transports.editor.email.form.recipients")
              },
              type: CUI.DataTable,
              no_header: true,
              name: "__recipients",
              fields: [
                {
                  type: UserGroupSelector,
                  aclWhoManager: new AclWhoManager({
                    allowEmailUser: true
                  }),
                  name: "address"
                }
              ]
            }, {
              form: {
                label: $$("transports.editor.email.form.message")
              },
              placeholder: $$("transports.editor.email.form.message_placeholder"),
              name: "message",
              type: CUI.Input,
              textarea: true
            }
          ]
        }
      ],
      footer_left: [
        {
          loca_key: "transport.editor.plus.button",
          group: "plus-minus",
          onClick: (function(_this) {
            return function() {
              var node;
              node = new ListViewEditTreeNode({
                data: {}
              });
              return _this.tree.addNode(node);
            };
          })(this)
        }, this.minusButton
      ]
    });
    CUI.Events.listen({
      node: this.tree,
      type: ["row_added", "row_removed", "row_deselected", "row_selected", "data-changed"],
      call: (function(_this) {
        return function(ev, info) {
          return _this.checkChanged();
        };
      })(this)
    });
    this.modal = new CUI.Modal({
      "class": "transports-editor-modal",
      cancel: true,
      onHide: (function(_this) {
        return function() {
          _this.tree.destroy();
          return _this.tree = null;
        };
      })(this),
      onCancel: (function(_this) {
        return function() {
          if (_this.saveButton.isDisabled()) {

          } else {
            return CUI.confirm({
              text: $$("transport.editor.confirm.close")
            });
          }
        };
      })(this),
      pane: {
        header_left: new CUI.Label({
          text: $$("transports.editor.title")
        }),
        footer_right: [this.saveButton],
        content: (function(_this) {
          return function() {
            var e, t;
            try {
              t = _this.tree.render();
              _this.loadTransports().done(function() {
                return _this.checkChanged();
              });
            } catch (error) {
              e = error;
              console.error("Error thrown in TransportsEditor:", e);
            }
            return t;
          };
        })(this)
      }
    });
    return this.modal.show();
  };

  TransportsEditor.prototype.loadTransports = function() {
    return this._export.getChildren(function() {
      var data, i, j, len, len1, nodes, rec, ref, ref1, t;
      nodes = [];
      ref = this.getData()._transports;
      for (i = 0, len = ref.length; i < len; i++) {
        t = ref[i];
        data = CUI.util.copyObject(t, true);
        if (!data.email) {
          data.email = {};
        }
        data.email.__recipients = [];
        if (data.email.recipients) {
          ref1 = data.email.recipients;
          for (j = 0, len1 = ref1.length; j < len1; j++) {
            rec = ref1[j];
            data.email.__recipients.push({
              address: rec
            });
          }
        }
        if (ez5.version("6")) {
          data.type = data.plugin;
          if (!data.type) {
            data.type = "download";
          }
        }
        nodes.push(new ListViewEditTreeNode({
          data: data
        }));
      }
      return nodes;
    }).done((function(_this) {
      return function(nodes) {
        _this.tree.load_data(nodes);
        return _this.__startData = JSON.stringify(_this.getSaveData());
      };
    })(this));
  };

  TransportsEditor.prototype.getSaveData = function() {
    var data, i, j, len, len1, plugin, rec, ref, ref1, s, sd;
    sd = [];
    ref = this.tree.root.children;
    for (i = 0, len = ref.length; i < len; i++) {
      s = ref[i];
      data = CUI.util.copyObject(s.getData(), true);
      data.email.recipients = [];
      if (data.email.__recipients) {
        ref1 = data.email.__recipients;
        for (j = 0, len1 = ref1.length; j < len1; j++) {
          rec = ref1[j];
          data.email.recipients.push(rec.address);
        }
        delete data.email.__recipients;
      }
      delete data._undo;
      delete data._state;
      delete data._log;
      delete data._downloads;
      delete data.email._undo;
      if (data.type !== "download") {
        plugin = this.getPluginByType(data.type);
        if (!(plugin != null ? plugin.supportsPacker() : void 0)) {
          delete data.packer;
        }
        delete data.email;
        plugin = this.getPluginByType(data.type);
        if (plugin != null) {
          plugin.getSaveData(data);
        }
        if (ez5.version("6")) {
          data.plugin = data.type;
        }
      } else {
        delete data.options._undo;
      }
      sd.push(data);
    }
    return sd;
  };

  TransportsEditor.__plugins = [];

  TransportsEditor.registerPlugin = function(plugin) {
    CUI.util.assert(plugin instanceof ExportTransportPlugin, "TransportEditor.registerPlugin", "Needs to be instanceof ExportTransportPlugin.");
    return this.__plugins.push(plugin);
  };

  return TransportsEditor;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var ExportTransportPlugin,
  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;

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

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

  ExportTransportPlugin.prototype.getType = function() {
    return console.error(CUI.util.getObjectClass(this) + ".getType needs to be implemented.");
  };

  ExportTransportPlugin.prototype.getDisplayType = function() {
    return console.error(CUI.util.getObjectClass(this) + ".getDisplayType needs to be implemented.");
  };

  ExportTransportPlugin.prototype.getDisplayIcon = function() {};

  ExportTransportPlugin.prototype.getOptions = function(data) {
    return console.error(CUI.util.getObjectClass(this) + ".getOptions needs to be implemented.");
  };

  ExportTransportPlugin.prototype.getOptionsDisplay = function(data) {
    if (!CUI.util.isEmptyObject(data.options)) {
      return [$$("export.transport.plugin.options_set")];
    } else {
      return [];
    }
  };

  ExportTransportPlugin.prototype.getSaveData = function(sd) {};

  ExportTransportPlugin.prototype.isAllowed = function() {
    return true;
  };

  ExportTransportPlugin.prototype.supportsPacker = function() {
    return false;
  };

  ExportTransportPlugin.prototype.supportSecretFields = function() {
    return ez5.version("6");
  };

  return ExportTransportPlugin;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var Task,
  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;

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

  function Task(data1) {
    this.data = data1 != null ? data1 : {};
    if (!this.getId()) {
      this.initData();
    }
  }

  Task.prototype.initData = function() {
    return this.data.task._version = 1;
  };

  Task.prototype.getId = function() {
    return this.data.task._id || null;
  };

  Task.prototype.getData = function() {
    return this.data;
  };

  Task.prototype.getTaskData = function() {
    return this.data.task;
  };

  Task.prototype.getCreatedAt = function() {
    return this.data.created_at;
  };

  Task.prototype.getRunStartedAt = function() {
    return this.data.task.run_started_at;
  };

  Task.prototype.getRunFinishedAt = function() {
    return this.data.task.run_finished_at;
  };

  Task.prototype.getId = function() {
    return this.data.task._id;
  };

  Task.prototype.getDescription = function() {
    return this.data.task.description;
  };

  Task.prototype.getStatus = function() {
    return this.data.task.status;
  };

  Task.prototype.getModule = function() {
    return this.data.task.task_module;
  };

  Task.prototype.getNextRunAt = function() {
    return this.data.task.next_run_at;
  };

  Task.prototype.getUser = function() {
    return new AclWhoUser({
      user: this.data._user,
      _basetype: "user"
    });
  };

  Task.prototype["delete"] = function() {
    var dfr, promise;
    dfr = new CUI.Deferred();
    promise = CUI.confirm({
      "class": 'cui-alert-problem',
      text: "Do you really want to delete this task?",
      button_text_ok: "Delete",
      button_text_cancel: "Cancel",
      markdown: true
    });
    promise.done((function(_this) {
      return function() {
        return ez5.api.task({
          api: "/" + (_this.getId()),
          type: "DELETE"
        }).fail(function(err) {
          return CUI.alert({
            "class": 'cui-alert-problem',
            text: "Error deleting task"
          });
        }).always(function() {
          return dfr.resolve();
        });
      };
    })(this));
    return dfr.promise();
  };

  Task.prototype.save = function() {
    return ez5.api.task({
      api: this.getId() ? "/" + (this.getId()) : "",
      type: this.getId() ? "PATCH" : "POST",
      json_data: this.getData()
    });
  };

  Task.loadFromId = function(id) {
    var dfr;
    dfr = new CUI.Deferred();
    ez5.api.task({
      api: "/" + id,
      type: "GET"
    }).done((function(_this) {
      return function(data) {
        var task;
        task = new Task(data);
        return dfr.resolve(task);
      };
    })(this)).fail((function(_this) {
      return function(err) {
        return CUI.alert({
          "class": 'cui-alert-problem',
          text: "Error loading task"
        });
      };
    })(this));
    return dfr.promise();
  };

  Task.prototype.showLogPopover = function(elem) {
    if (!this.__logListView) {
      this.__logListView = new CUI.ListViewTree({
        fixedRows: 1,
        maximize: true,
        cols: ["fixed", "fixed", "maximize"]
      });
      this.__logListView.render();
    } else {
      this.__logListView.removeAllRows();
    }
    this.popover = new CUI.Popover({
      element: elem,
      "class": "task-manager-list-log-popover",
      size: "xl",
      pane: {
        header_left: new CUI.Label({
          text: "Task Log"
        }),
        content: new CUI.VerticalList({
          content: [this.__logListView],
          maximize: true
        })
      }
    });
    this.popover.show();
    this.updateLog();
    return this.popover;
  };

  Task.prototype.updateLog = function() {
    return ez5.api.task({
      api: "/" + this.getId() + "/log",
      type: "GET"
    }).done((function(_this) {
      return function(log_data) {
        _this._log = log_data;
        return _this.showLogData();
      };
    })(this));
  };

  Task.prototype.showLogData = function() {
    var headerRow, i, len, log, ref, row;
    headerRow = new CUI.ListViewHeaderRow();
    headerRow.addColumn(new CUI.ListViewHeaderColumn({
      element: new CUI.Label({
        text: $$('tasks.manager.list.log.created_at')
      })
    }));
    headerRow.addColumn(new CUI.ListViewHeaderColumn({
      element: new CUI.Label({
        text: $$('tasks.manager.list.log.level')
      })
    }));
    headerRow.addColumn(new CUI.ListViewHeaderColumn({
      element: new CUI.Label({
        text: $$('tasks.manager.list.log.message')
      })
    }));
    ref = this._log || [];
    for (i = 0, len = ref.length; i < len; i++) {
      log = ref[i];
      row = new CUI.ListViewRow();
      row.addColumn(new CUI.ListViewColumn({
        element: new CUI.Label({
          text: ez5.format_date_and_time(log.timestamp)
        })
      }));
      row.addColumn(new CUI.ListViewColumn({
        element: new CUI.Label({
          text: log.level
        })
      }));
      row.addColumn(new CUI.ListViewColumn({
        element: this.__getLogMsg(log)
      }));
      this.__logListView.appendRow(row);
    }
    this.__logListView.prependRow(headerRow);
    this.popover.autoSize();
  };

  Task.prototype.__getLogMsg = function(log) {
    var objLinkCallback;
    objLinkCallback = function(matchedText, matchIndex, fullText) {
      var a, id;
      id = parseInt(matchedText.match(/obj #(\d+)/)[1], 10);
      a = CUI.dom.element("a");
      a.textContent = matchedText;
      a.onclick = (function(_this) {
        return function(e) {
          var ro;
          e.preventDefault();
          ro = new ResultObject();
          return ro.loadFromSystemObjectId(parseInt(id), "long").done(function() {
            return ro.showPopover({
              popover: {
                element: a
              }
            });
          });
        };
      })(this);
      return a;
    };
    return new CUI.Label({
      text: log.msg,
      multiline: true,
      text_node_func: (function(_this) {
        return function(text) {
          return CUI.Label.parseWithRegex(text, /obj #(\d+)/g, objLinkCallback);
        };
      })(this)
    });
  };

  return Task;

})(CUI.Dummy);
// Generated by CoffeeScript 1.12.7
var TaskManagerList,
  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;

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

  TaskManagerList.registeredModules = {};

  TaskManagerList.POLL_INTERVAL = 5000;

  TaskManagerList.prototype.limit = 10;

  TaskManagerList.prototype.initOpts = function() {
    TaskManagerList.__super__.initOpts.call(this);
    this.addOpts({
      headless: {
        check: Boolean,
        "default": false
      }
    });
    return this;
  };

  function TaskManagerList(opts1) {
    this.opts = opts1 != null ? opts1 : {};
    TaskManagerList.__super__.constructor.call(this, this.opts);
  }

  TaskManagerList.prototype.is_allowed = function() {
    return ez5.version("6") && ez5.session.hasSystemRight("root", "task");
  };

  TaskManagerList.prototype.getSortValue = function() {
    return 1;
  };

  TaskManagerList.prototype.load = function(path) {
    this.showModal();
    if (!CUI.util.isEmpty(path)) {
      this.loadTaskFromPath(path);
    }
    return CUI.resolvedPromise();
  };

  TaskManagerList.prototype.getPathName = function() {
    return "/tray/tasks";
  };

  TaskManagerList.prototype.loadTaskFromPath = function(path) {
    var dfr, id, match, regex;
    dfr = new CUI.Deferred();
    regex = new RegExp("^" + this.getPathName().replace(/\//g, "\\/") + "/(\\d+)");
    match = path.match(regex);
    if (match == null) {
      return;
    }
    id = match[1];
    Task.loadFromId(id).done((function(_this) {
      return function(task) {
        return _this.editTask(task);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  TaskManagerList.prototype.getDisplay = function() {
    var container;
    container = CUI.dom.div("tray-item tasks-manager-list-tray-container");
    CUI.dom.append(container, new LocaButton({
      loca_key: "tasks.manager.list.button.tray",
      "class": "ez5-tasks-manager-list-tray-button",
      appearance: "transparent-border",
      onClick: (function(_this) {
        return function(ev) {
          return _this.showModal(ev);
        };
      })(this)
    }).DOM);
    return container;
  };

  TaskManagerList.prototype.showModal = function(ev) {
    var minusButton, plusButton;
    plusButton = new CUI.Button({
      icon: new CUI.Icon({
        "class": "fa-plus"
      }),
      group: "plus-minus",
      onClick: (function(_this) {
        return function() {
          return _this.__showEditorModal();
        };
      })(this)
    });
    minusButton = new CUI.Button({
      icon: new CUI.Icon({
        "class": "fa-minus"
      }),
      group: "plus-minus",
      disabled: true,
      onClick: (function(_this) {
        return function() {
          var selected_node, task;
          selected_node = _this.tree.getSelectedNode();
          task = selected_node.getTask();
          if (!task) {
            return;
          }
          return task["delete"]().done(function() {
            _this.loadTree();
            return minusButton.disable();
          });
        };
      })(this)
    });
    this.tree = new CUI.ListViewTree({
      "class": 'cui-lv--has-datafields',
      fixedRows: 1,
      cols: ["fixed", "maximize", "auto", "auto", "auto", "auto", "auto", "auto", "auto"],
      focusable: true,
      maximize: true,
      selectableRows: true,
      force_footer: true,
      onSelect: (function(_this) {
        return function(ev, info) {
          return minusButton.enable();
        };
      })(this),
      onDeselect: (function(_this) {
        return function(ev, info) {
          return minusButton.disable();
        };
      })(this),
      footer_left: new CUI.Buttonbar({
        buttons: [plusButton, minusButton]
      }),
      colClasses: ["ez5-tasks-manager-list-column-idx", "ez5-tasks-manager-list-column-description", "ez5-tasks-manager-list-column-module", "ez5-tasks-manager-list-column-timestamp", "ez5-tasks-manager-list-column-started_at", "ez5-tasks-manager-list-column-fishished_at", "ez5-tasks-manager-list-column-next_run_at", "ez5-tasks-manager-list-column-status", "ez5-tasks-manager-list-column-options"]
    });
    this.modal = new CUI.Modal({
      "class": "task-manager-list-modal",
      cancel: true,
      onCancel: (function(_this) {
        return function() {
          return _this.closeModal();
        };
      })(this),
      pane: {
        header_left: new LocaLabel({
          loca_key: "tasks.manager.list.title"
        }),
        content: this.tree.render(),
        footer_right: {
          loca_key: "tasks.manager.list.button.done",
          primary: true,
          onClick: (function(_this) {
            return function() {
              return _this.closeModal();
            };
          })(this)
        }
      }
    });
    this.modal.show();
    return this.loadTree(0, ev != null ? ev.altKey() : void 0).done((function(_this) {
      return function() {
        return _this.__poll();
      };
    })(this));
  };

  TaskManagerList.prototype.getFilterButton = function() {
    this.filter_button = new CUI.FormPopover({
      data: this.__filter_data,
      fields: (function(_this) {
        return function() {
          return [
            {
              type: CUI.Output,
              text: $$("tasks.manager.list.filter.no_data")
            }
          ];
        };
      })(this)
    });
    return this.filter_button.start();
  };

  TaskManagerList.prototype.loadTree = function(offset, load_current_data) {
    var dfr, render;
    if (offset == null) {
      offset = 0;
    }
    if (load_current_data == null) {
      load_current_data = false;
    }
    dfr = new CUI.Deferred();
    render = (function(_this) {
      return function() {
        var idx, task, task_nodes;
        task_nodes = (function() {
          var i, len, ref, results;
          ref = this.__tasks;
          results = [];
          for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
            task = ref[idx];
            results.push(new TaskManagerListTopLevelNode({
              task: task,
              manager: this,
              index: idx + this.offset + 1
            }));
          }
          return results;
        }).call(_this);
        task_nodes.splice(0, 0, new TaskManagerListHeaderNode());
        _this.tree.root.removeFromDOM(false);
        _this.tree.root.children = task_nodes;
        return _this.tree.root.open().done(dfr.resolve).fail(dfr.reject);
      };
    })(this);
    if (load_current_data) {
      render();
      return dfr.promise();
    }
    this.tree.showWaitBlock();
    this.loadTasks(offset).always((function(_this) {
      return function() {
        return _this.tree.hideWaitBlock();
      };
    })(this)).done((function(_this) {
      return function(__tasks) {
        _this.__tasks = __tasks;
        return render();
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  TaskManagerList.prototype.__updateNavigation = function() {
    var navi;
    if (!this.tree) {
      return;
    }
    navi = SystemListManager.renderNavigation({
      count: this.__data.count,
      limit: this.limit,
      offset: this.offset,
      callback: (function(_this) {
        return function(offset) {
          return _this.loadTree(offset);
        };
      })(this)
    });
    if (this.__data.objects.length === 0 && this.__data.count > 0) {
      this.loadTree(0);
    }
    this.tree.replace(navi, "footer_right");
  };

  TaskManagerList.prototype.loadTasks = function(offset1) {
    var dfr;
    this.offset = offset1 != null ? offset1 : this.offset;
    dfr = new CUI.Deferred();
    ez5.api.task({
      type: "GET",
      data: {
        limit: this.limit,
        offset: this.offset
      }
    }).done((function(_this) {
      return function(data) {
        var i, len, ref, task, tasks;
        _this.__data = data;
        tasks = [];
        ref = _this.__data.objects;
        for (i = 0, len = ref.length; i < len; i++) {
          task = ref[i];
          tasks.push(new Task(task));
        }
        _this.__updateNavigation();
        return dfr.resolve(tasks);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  TaskManagerList.prototype.__poll = function() {
    if (this.__polling) {
      return;
    }
    this.__polling = true;
    return setTimeout((function(_this) {
      return function() {
        return ez5.api.task({
          type: "GET",
          data: {
            limit: _this.limit,
            offset: _this.offset
          }
        }).done(function(pollData) {
          var task;
          if (!_this.tree) {
            _this.__polling = false;
            return;
          }
          if (!_this.__needRefresh(pollData)) {
            _this.__polling = false;
            _this.__poll();
            return;
          }
          _this.__data = pollData;
          _this.__tasks = (function() {
            var i, len, ref, results;
            ref = this.__data.objects;
            results = [];
            for (i = 0, len = ref.length; i < len; i++) {
              task = ref[i];
              results.push(new Task(task));
            }
            return results;
          }).call(_this);
          _this.__updateNavigation();
          return _this.loadTree(_this.offset, true).done(function() {
            _this.__polling = false;
            return _this.__poll();
          });
        });
      };
    })(this), TaskManagerList.POLL_INTERVAL);
  };

  TaskManagerList.prototype.__needRefresh = function(newData) {
    var current_data_tasks, new_data_tasks;
    if (this.__data.count !== newData.count) {
      return true;
    }
    current_data_tasks = this.__data.objects.map((function(_this) {
      return function(task) {
        return task.task;
      };
    })(this));
    new_data_tasks = newData.objects.map((function(_this) {
      return function(task) {
        return task.task;
      };
    })(this));
    return !CUI.util.isEqual(current_data_tasks, new_data_tasks);
  };

  TaskManagerList.prototype.closeModal = function() {
    this.modal.destroy();
    this.modal = null;
    this.tree.destroy();
    this.tree = null;
    return this;
  };

  TaskManagerList.prototype.editTask = function(task) {
    return this.__showEditorModal({
      task: task,
      module_filter: (function(_this) {
        return function(module) {
          return module.name !== task.getModule();
        };
      })(this)
    });
  };

  TaskManagerList.prototype.__showEditorModal = function(opts) {
    var mode, ref, ref1, ref2, task;
    if (opts == null) {
      opts = {};
    }
    if (opts.collection) {
      this.__collection = opts.collection;
    }
    if (this.__create_form_settings == null) {
      this.__create_form_settings = {};
    }
    if (!opts.task) {
      mode = "create";
      this.__create_form_settings.task_id = null;
      this.__create_form_settings.task_module = null;
      this.__create_form_settings._version = null;
      this.__task_data = {};
    } else {
      mode = "edit";
      task = opts.task;
      if (this.__create_form_settings == null) {
        this.__create_form_settings = {};
      }
      this.__create_form_settings.task_module = task.getModule();
      this.__task_data = {
        task: {
          task_config: {
            description: task.getTaskData().description,
            next_run_at: task.getTaskData().next_run_at,
            schedules: task.getTaskData().schedules || [],
            task_timeout_sec: task.getTaskData().task_timeout_sec
          }
        }
      };
      if (!CUI.util.isEmpty((ref = task.getTaskData().email) != null ? ref.recipients : void 0)) {
        this.__task_data.task.task_config.email = (ref1 = task.getTaskData().email.recipients) != null ? (ref2 = ref1[0]) != null ? ref2.email : void 0 : void 0;
        this.__task_data.task.task_config._send_email = true;
      }
      if ((task.getTaskData().next_run_at != null) && !CUI.util.isEmpty(task.getTaskData().next_run_at)) {
        this.__task_data.task.task_config.schedule_select = "manual";
      }
      if ((task.getTaskData().schedules != null) && !CUI.util.isEmpty(task.getTaskData().schedules)) {
        this.__task_data.task.task_config.schedule_select = "scheduled";
      }
      this.__task_data.task.task_params = task.getTaskData().task_params;
      this.__create_form_settings.task_id = task.getId();
      this.__create_form_settings._version = task.getTaskData()._version;
      this.__task_data.task.task_config._id = task.getId();
      this.__task_data.task.task_config.created_at = task.getCreatedAt();
      this.__task_data.task.task_config.run_started_at = task.getRunStartedAt();
      this.__task_data.task.task_config.run_finished_at = task.getRunFinishedAt();
      this.__task_data.task.task_config.status = task.getStatus();
    }
    return this.__getModules(opts.module_filter).done((function(_this) {
      return function() {
        _this.__createButton = new LocaButton({
          loca_key: "tasks.manager.list.button." + mode,
          disabled: true,
          primary: true,
          onClick: function(ev) {
            return _this.__saveTask(ev).done(function() {
              _this.__createModal.destroy();
              if (!_this._headless) {
                return _this.loadTree(0);
              }
            });
          }
        });
        _this.__createModal = new CUI.Modal({
          size: 'm',
          cancel: true,
          onCancel: function() {
            return _this.__createModal.destroy();
          },
          pane: {
            header_left: new LocaLabel({
              loca_key: "tasks.manager." + mode + "_form.title"
            }),
            content: [_this.__getTaskModuleSelector(opts), _this.__getCreateForm(opts)],
            footer_right: [_this.__createButton]
          }
        });
        return _this.__createModal.show();
      };
    })(this));
  };

  TaskManagerList.prototype.__getModules = function(filter) {
    var dfr;
    this.modules = {};
    dfr = new CUI.Deferred();
    ez5.api.task({
      type: "GET",
      api: "/modules"
    }).done((function(_this) {
      return function(data) {
        var i, len, module, ref, ref1;
        if ((ref = data.modules) != null ? ref.length : void 0) {
          ref1 = data.modules;
          for (i = 0, len = ref1.length; i < len; i++) {
            module = ref1[i];
            if (module.name === "sleep" && !ez5.session.isDebug()) {
              continue;
            }
            if (filter && filter(module)) {
              continue;
            }
            _this.modules[module.name] = module;
          }
        }
        return dfr.resolve();
      };
    })(this));
    return dfr.promise();
  };

  TaskManagerList.prototype.__getTaskModuleSelector = function(opts) {
    var options, task_module_selector;
    options = [
      {
        value: null,
        text: $$("tasks.manager.list.module")
      }
    ];
    options = options.concat(Object.keys(this.modules).map((function(_this) {
      return function(module) {
        return {
          value: module,
          text: module
        };
      };
    })(this)));
    task_module_selector = new CUI.Form({
      data: this.__create_form_settings,
      fields: [
        {
          type: CUI.Select,
          name: "task_module",
          form: {
            label: $$("tasks.manager.list.module.label")
          },
          options: options,
          disabled: opts.task != null,
          onDataChanged: (function(_this) {
            return function() {
              var ref;
              if ((ref = _this.__create_form) != null) {
                ref.destroy();
              }
              CUI.dom.replace(_this.__getCreateFormWrapper, _this.__getCreateForm(opts));
              return _this.__createModal.autoSize();
            };
          })(this)
        }
      ]
    });
    return task_module_selector.start();
  };

  TaskManagerList.prototype.__getCreateForm = function(opts) {
    var config, configFields, configForm, extra_fields, moduleImplementationCls, module_def, module_name, paramFields, paramsForm, ref, ref1, ref2, ref3, ref4, ref5;
    if (opts == null) {
      opts = {};
    }
    this.__getCreateFormWrapper = CUI.dom.div("tasks-manager-list-create-form");
    module_name = this.__create_form_settings.task_module;
    if (!module_name) {
      return this.__getCreateFormWrapper;
    }
    module_def = this.modules[module_name];
    moduleImplementationCls = TaskManagerList.registeredModules[module_name] || TaskModuleBase;
    this.__moduleImplementation = new moduleImplementationCls({
      module_definition: module_def,
      manager: this
    });
    if (!CUI.util.isEmpty((ref = opts.task) != null ? (ref1 = ref.getTaskData()) != null ? ref1.frontend_prefs : void 0 : void 0)) {
      this.__moduleImplementation.restoreFrontendPrefs((ref2 = opts.task) != null ? (ref3 = ref2.getTaskData()) != null ? ref3.frontend_prefs : void 0 : void 0);
    }
    paramFields = this.__moduleImplementation.getModuleParamFields(opts);
    if (paramFields.length > 0) {
      paramsForm = {
        type: CUI.Form,
        name: "task_params",
        fields: paramFields,
        form: {
          label: $$("tasks.manager.list.create.params")
        },
        onDataChanged: function(data, elem) {
          return this.getFields().forEach((function(_this) {
            return function(field) {
              if (field instanceof CUI.DataFieldProxy) {
                if (field === elem) {
                  return;
                }
                return field.reload();
              }
            };
          })(this));
        }
      };
    }
    configFields = [
      {
        type: CUI.Input,
        name: "description",
        placeholder: $$("tasks.manager.list.create.description"),
        form: {
          label: $$("tasks.manager.list.create.description")
        }
      }, {
        type: CUI.Select,
        name: "schedule_select",
        options: [
          {
            value: null,
            text: $$("tasks.manager.list.create.schedule_select.none")
          }, {
            value: "manual",
            text: $$("tasks.manager.list.create.schedule_select.manual")
          }, {
            value: "scheduled",
            text: $$("tasks.manager.list.create.schedule_select.scheduled")
          }
        ],
        form: {
          label: $$("tasks.manager.list.create.schedule_select")
        },
        onDataInit: (function(_this) {
          return function(field) {
            if (field.getData().schedule_select === "manual") {
              field.getForm().getFieldsByName("next_run_at")[0].show(true);
              return field.getForm().getFieldsByName("schedules")[0].hide(true);
            } else if (field.getData().schedule_select === "scheduled") {
              field.getForm().getFieldsByName("next_run_at")[0].hide(true);
              return field.getForm().getFieldsByName("schedules")[0].show(true);
            } else {
              field.getForm().getFieldsByName("next_run_at")[0].hide();
              return field.getForm().getFieldsByName("schedules")[0].hide(true);
            }
          };
        })(this),
        onDataChanged: (function(_this) {
          return function(data, field) {
            if (field.getData().schedule_select === "manual") {
              field.getForm().getFieldsByName("next_run_at")[0].show(true);
              field.getForm().getFieldsByName("schedules")[0].hide(true);
            } else if (field.getData().schedule_select === "scheduled") {
              field.getForm().getFieldsByName("next_run_at")[0].hide(true);
              field.getForm().getFieldsByName("schedules")[0].show(true);
            } else {
              field.getForm().getFieldsByName("next_run_at")[0].hide(true);
              field.getForm().getFieldsByName("schedules")[0].hide(true);
            }
            return CUI.Events.trigger({
              type: "content-resize",
              node: field
            });
          };
        })(this)
      }, {
        type: CUI.DateTime,
        name: "next_run_at",
        placeholder: $$("tasks.manager.list.create.start_time|placeholder"),
        form: {
          label: $$("tasks.manager.list.create.start_time"),
          hint: $$("tasks.manager.list.create.start_time|hint")
        }
      }, ScheduleEditor.getSchedulerFormButton({
        name: "schedules",
        modal_class: "ez5-schedule-editor-modal-scheduler",
        multiple: true,
        form: {
          label: $$("tasks.manager.list.create.schedules")
        }
      }), ez5.session.isDebug() ? {
        type: CUI.NumberInput,
        name: "task_timeout_sec",
        placeholder: $$("tasks.manager.list.create.timeout|placeholder"),
        form: {
          label: $$("tasks.manager.list.create.timeout")
        }
      } : void 0, {
        type: CUI.DataFieldProxy,
        name: "email",
        form: {
          label: $$("tasks.manager.list.create.email"),
          hint: $$("tasks.manager.list.create.email|hint")
        },
        element: (function(_this) {
          return function(df) {
            var checkbox, data, dataChanged, ref4, ref5, ref6, userEmail;
            dataChanged = function() {
              return CUI.Events.trigger({
                node: df,
                type: "data-changed",
                info: {
                  element: df
                }
              });
            };
            userEmail = ez5.session.user.getEmail();
            data = df.getData();
            _this.__emailInput = new CUI.EmailInput({
              name: "email",
              data: data,
              disabled: !((ref4 = _this.__task_data) != null ? (ref5 = ref4.task) != null ? (ref6 = ref5.task_config) != null ? ref6._send_email : void 0 : void 0 : void 0),
              placeholder: userEmail || $$("tasks.manager.list.create.email")
            });
            checkbox = new CUI.Checkbox({
              name: "_send_email",
              data: data,
              onActivate: function() {
                _this.__emailInput.enable();
                return dataChanged();
              },
              onDeactivate: function() {
                _this.__emailInput.disable();
                return dataChanged();
              }
            });
            return new CUI.HorizontalList({
              content: [checkbox, _this.__emailInput]
            });
          };
        })(this)
      }
    ];
    if (opts.task) {
      extra_fields = [
        {
          type: CUI.Output,
          name: "_id",
          form: {
            label: $$("task.manager.list.header.node.id")
          }
        }, {
          type: CUI.OutputContent,
          name: "status",
          form: {
            label: $$("task.manager.list.header.node.status")
          },
          getValue: (function(_this) {
            return function(value, field) {
              return new CUI.ButtonHref({
                appearance: "link",
                text: ((value != null ? value.charAt(0).toUpperCase() : void 0) + (value != null ? value.slice(1) : void 0)) + " - (Show Log)",
                onClick: function(ev, f) {
                  ev.stopPropagation();
                  return opts.task.showLogPopover(f);
                }
              });
            };
          })(this)
        }, {
          type: CUI.Output,
          name: "created_at",
          getValue: (function(_this) {
            return function(v) {
              return ez5.format_date_and_time(v, true);
            };
          })(this),
          form: {
            label: $$("task.manager.list.header.node.date")
          }
        }, {
          type: CUI.Output,
          name: "run_started_at",
          getValue: (function(_this) {
            return function(v) {
              return ez5.format_date_and_time(v, true);
            };
          })(this),
          form: {
            label: $$("task.manager.list.header.node.started_at")
          }
        }, {
          type: CUI.Output,
          name: "finished_at",
          getValue: (function(_this) {
            return function(v) {
              return ez5.format_date_and_time(v, true);
            };
          })(this),
          form: {
            label: $$("task.manager.list.header.node.finished_at")
          }
        }
      ];
      configFields = extra_fields.concat(configFields);
    }
    configForm = {
      type: CUI.Form,
      name: "task_config",
      fields: configFields,
      form: {
        label: $$("tasks.manager.list.create.form")
      }
    };
    if (!opts.task) {
      if (((ref4 = this.__task_data) != null ? (ref5 = ref4.task) != null ? ref5.task_config : void 0 : void 0) != null) {
        config = this.__task_data.task.task_config;
      }
      this.__task_data = {};
      if (config != null) {
        this.__task_data.task = {
          task_config: config
        };
      }
    }
    this.__create_form = new CUI.Form({
      name: "task",
      data: this.__task_data,
      fields: [configForm, paramsForm],
      onDataChanged: (function(_this) {
        return function(data) {
          return _this.__updateSaveButton();
        };
      })(this)
    });
    this.__create_form.start();
    return CUI.dom.append(this.__getCreateFormWrapper, this.__create_form);
  };

  TaskManagerList.prototype.getSaveData = function() {
    var config_data, i, k, len, ref, save_data, task_data, userEmail;
    task_data = CUI.util.copyObjectV2(this.__create_form.getData(), true);
    config_data = task_data.task_config;
    if (this.__create_form_settings.task_id != null) {
      config_data._id = this.__create_form_settings.task_id;
      config_data._version = this.__create_form_settings._version + 1;
    }
    config_data.task_module = this.__create_form_settings.task_module;
    if (config_data._send_email) {
      if (CUI.util.isEmpty(config_data.email)) {
        userEmail = {
          email: ez5.session.user.getEmail()
        };
      } else {
        userEmail = {
          email: config_data.email
        };
      }
      if (!CUI.util.isEmpty(userEmail.email)) {
        config_data.email = {
          recipients: [userEmail]
        };
      } else {
        this.__emailInput.addClass("cui-input-invalid");
        throw new InvalidSaveDataException();
      }
    } else {
      delete config_data.email;
    }
    switch (config_data.schedule_select) {
      case "manual":
        config_data.schedules = [];
        if (CUI.util.isEmpty(config_data.next_run_at)) {
          config_data.next_run_at = new Date().toISOString();
        } else {
          config_data.next_run_at = new Date(config_data.next_run_at).toISOString();
        }
        break;
      case "scheduled":
        config_data.next_run_at = null;
        if (config_data.schedules) {
          if (ScheduleEditor.isEmpty(config_data.schedules)) {
            config_data.schedules = [];
          }
        }
        break;
      default:
        config_data.schedules = [];
        config_data.next_run_at = null;
    }
    delete config_data._send_email;
    config_data.task_params = task_data.task_params;
    ref = ["created_at", "run_started_at", "run_finished_at", "status"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      if (config_data[k] != null) {
        delete config_data[k];
      }
    }
    save_data = {
      task: config_data
    };
    save_data = this.__moduleImplementation.getSaveData(save_data);
    return save_data;
  };

  TaskManagerList.prototype.__saveTask = function(ev) {
    var e, save_data, task;
    try {
      save_data = this.getSaveData();
    } catch (error) {
      e = error;
      if (e instanceof InvalidSaveDataException) {
        this.__updateSaveButton();
      } else {
        throw e;
      }
    }
    if (ev.altKey()) {
      console.log(save_data);
      return CUI.rejectedPromise();
    }
    task = new Task(save_data);
    return task.save();
  };

  TaskManagerList.prototype.__updateSaveButton = function() {
    var e, save_data;
    try {
      save_data = this.getSaveData();
    } catch (error) {
      e = error;
      if (e instanceof InvalidSaveDataException) {
        this.__createButton.disable();
        return;
      } else {
        throw e;
      }
    }
    return this.__createButton.enable();
  };

  TaskManagerList.prototype.createTaskFromCollection = function(collection) {
    this.__showEditorModal({
      collection: collection,
      module_filter: (function(_this) {
        return function(module) {
          return !module.params.some(function(p) {
            return p.plugin_type === "search";
          });
        };
      })(this)
    });
  };

  TaskManagerList.registerModule = function(taskModule) {
    return this.registeredModules[taskModule.getModuleName()] = taskModule;
  };

  return TaskManagerList;

})(TrayApp);

ez5.session_ready(function() {
  return ez5.tray.registerApp(new TaskManagerList());
});
// Generated by CoffeeScript 1.12.7
var TaskManagerListHeaderNode,
  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;

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

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

  TaskManagerListHeaderNode.prototype.initOpts = function() {
    TaskManagerListHeaderNode.__super__.initOpts.call(this);
    return this.removeOpt("headers");
  };

  TaskManagerListHeaderNode.prototype.readOpts = function() {
    var i, k, len, ref;
    TaskManagerListHeaderNode.__super__.readOpts.call(this);
    this._headers = [];
    this._headers.push({
      label: {
        text: "#"
      }
    });
    ref = ["description", "module", "date", "started_at", "finished_at", "next_run_at", "status"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      this._headers.push({
        label: {
          text: $$("task.manager.list.header.node." + k)
        }
      });
    }
    this._headers.push();
    return this;
  };

  TaskManagerListHeaderNode.prototype.isSelectable = function() {
    return false;
  };

  return TaskManagerListHeaderNode;

})(CUI.ListViewTreeHeaderNode);
// Generated by CoffeeScript 1.12.7
var TaskManagerListTopLevelNode,
  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;

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

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

  TaskManagerListTopLevelNode.prototype.initOpts = function() {
    TaskManagerListTopLevelNode.__super__.initOpts.call(this);
    this.addOpts({
      manager: {
        mandatory: true,
        check: TaskManagerList
      },
      task: {
        mandatory: true,
        check: Task
      },
      index: {
        check: "Integer"
      }
    });
    return this;
  };

  TaskManagerListTopLevelNode.prototype.readOpts = function() {
    TaskManagerListTopLevelNode.__super__.readOpts.call(this);
    this.manager = this._manager;
    this.setTask(this._task);
    return this;
  };

  TaskManagerListTopLevelNode.prototype.getTask = function() {
    return this.task;
  };

  TaskManagerListTopLevelNode.prototype.setTask = function(task) {
    this.task = task;
    if (this.children) {
      this.close();
      delete this.children;
    }
    return this;
  };

  TaskManagerListTopLevelNode.prototype.renderContent = function() {
    this.addColumn(new CUI.ListViewColumn({
      element: new CUI.Label({
        text: this.task.getDescription(),
        multiline: true
      })
    }));
    this.addColumn(new CUI.ListViewColumn({
      element: new CUI.Label({
        text: this.task.getModule(),
        multiline: true
      })
    }));
    this.addColumn(new CUI.ListViewColumn({
      text: ez5.format_date_and_time(this.task.getCreatedAt())
    }));
    this.addColumn(new CUI.ListViewColumn({
      text: ez5.format_date_and_time(this.task.getRunStartedAt())
    }));
    this.addColumn(new CUI.ListViewColumn({
      text: ez5.format_date_and_time(this.task.getRunFinishedAt())
    }));
    this.addColumn(new CUI.ListViewColumn({
      text: this.task.getNextRunAt() === "0001-01-01T00:00:00Z" ? $$("task.manager.list.header.node.next_run_at.now") : ez5.format_date_and_time(this.task.getNextRunAt())
    }));
    this.addColumn(new CUI.ListViewColumn({
      text: this.task.getStatus()
    }));
    this.addColumn(new CUI.ListViewColumn({
      element: this.getOptionsColumn()
    }));
    return new CUI.Label({
      text: "" + this._index
    });
  };

  TaskManagerListTopLevelNode.prototype.getOptionsColumn = function() {
    return new CUI.Buttonbar({
      buttons: [
        new CUI.Button({
          icon: "fa-file-text-o",
          group: "task-options",
          tooltip: {
            text: "View Task Log"
          },
          onClick: (function(_this) {
            return function(e, btn) {
              return _this._task.showLogPopover(btn);
            };
          })(this),
          disabled: this._task.getStatus() === "new"
        }), new CUI.Button({
          icon: "fa-pencil",
          group: "task-options",
          tooltip: {
            text: "Edit Task"
          },
          onClick: (function(_this) {
            return function(e, btn) {
              return _this._manager.editTask(_this._task);
            };
          })(this)
        })
      ]
    });
  };

  return TaskManagerListTopLevelNode;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var TaskModuleBase,
  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;

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

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

  TaskModuleBase.prototype.initOpts = function() {
    TaskModuleBase.__super__.initOpts.call(this);
    this.addOpts({
      module_definition: {
        mandatory: true,
        check: "PlainObject"
      },
      manager: {
        mandatory: true,
        check: TaskManagerList
      }
    });
    return this;
  };

  TaskModuleBase.prototype.getModuleParamFields = function(opts) {
    var def, field, i, len, paramFields, parameters;
    paramFields = [];
    parameters = this._module_definition.params;
    if (parameters) {
      for (i = 0, len = parameters.length; i < len; i++) {
        def = parameters[i];
        field = this.__getFieldFromDef(def, opts);
        if (field != null) {
          paramFields.push(field);
        }
      }
    }
    return paramFields;
  };

  TaskModuleBase.prototype.__getFieldFromDef = function(def, opts) {
    var collection, field, l10nFn;
    if (opts == null) {
      opts = {};
    }
    field = null;
    l10nFn = (function(_this) {
      return function(type, parentDef) {
        var attrs;
        attrs = ["task." + (_this.getDefinition().name) + ".params"];
        if (type) {
          attrs.push(type);
        }
        if (parentDef) {
          attrs.push(parentDef._parameter_name);
        }
        return attrs.join(".");
      };
    })(this);
    if (def.plugin_type === "search") {
      if (!this.__frontend_prefs) {
        this.__frontend_prefs = {
          search_data: {}
        };
      }
      collection = opts.collection || null;
      field = SearchPopover.getBaseConfigButton("search", null, collection, this.__frontend_prefs["search_data"]);
      field.form = {
        label: $$("task.metadata.params.parameter.search.label")
      };
    } else {
      field = BaseConfig.getFieldDefinitionFromParameter(def.name, def, null, l10nFn);
    }
    return field;
  };

  TaskModuleBase.prototype.getSaveData = function(save_data) {
    return save_data;
  };

  TaskModuleBase.prototype.getDefinition = function() {
    return this._module_definition;
  };

  TaskModuleBase.prototype.restoreFrontendPrefs = function(prefs) {
    this.__frontend_prefs = prefs || {};
    return prefs;
  };

  TaskModuleBase.getModuleName = function() {
    return console.error((CUI.util.getObjectClass(this)) + ".getModuleName method not implemented.");
  };

  return TaskModuleBase;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var MetadataTaskModule,
  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;

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

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

  MetadataTaskModule.getModuleName = function() {
    return "metadata";
  };

  MetadataTaskModule.prototype.restoreFrontendPrefs = function(prefs) {
    var p;
    if (CUI.util.isEmpty(prefs)) {
      p = {
        search_data: {}
      };
    } else {
      p = prefs;
    }
    this.__frontend_prefs = p;
    return p;
  };

  MetadataTaskModule.prototype.__getFieldFromDef = function(def) {
    console.log(def);
    if (def.plugin_type === "search" || def.plugin_type === "create-object") {
      return null;
    }
    return MetadataTaskModule.__super__.__getFieldFromDef.call(this, def);
  };

  MetadataTaskModule.prototype.getModuleParamFields = function(opts) {
    var _getMask, _processSearchData, collection, e, editorHeadlessField, i, len, obj, paramFields, ref, searchPopoverField;
    if (!this.__frontend_prefs) {
      this.__frontend_prefs = {
        search_data: {}
      };
    }
    paramFields = MetadataTaskModule.__super__.getModuleParamFields.call(this, opts);
    if (this._manager.__collection) {
      this.__available_objecttypes = new Set();
      try {
        ref = this._manager.__collection.getObjects();
        for (i = 0, len = ref.length; i < len; i++) {
          obj = ref[i];
          this.__available_objecttypes.add(ez5.schema.CURRENT._objecttype_by_name[obj.getObjecttype()].table_id);
        }
      } catch (error) {
        e = error;
        this.__available_objecttypes = null;
      }
    }
    editorHeadlessField = EditorHeadlessNewBaseConfig.getBaseConfigButton("create_object", {
      text_inactive: $$("editor.headless.new.create_object.button"),
      text_active: $$("editor.headless.edit.create_object.button"),
      filterObjecttypeOption: (function(_this) {
        return function(option) {
          if (!_this.__available_objecttypes) {
            return true;
          }
          if (_this.__available_objecttypes.has(option.value)) {
            return true;
          }
          return false;
        };
      })(this)
    });
    editorHeadlessField.form = {
      label: $$("task.metadata.params.parameter.create_object.label")
    };
    _getMask = (function(_this) {
      return function() {
        return _this.__getMask();
      };
    })(this);
    _processSearchData = (function(_this) {
      return function(data) {
        return _this.__processSearchData(data);
      };
    })(this);
    collection = opts.collection || null;
    searchPopoverField = SearchPopover.getBaseConfigButton("search", _getMask, collection, this.__frontend_prefs["search_data"], _processSearchData);
    searchPopoverField.form = {
      label: $$("task.metadata.params.parameter.search.label")
    };
    paramFields.unshift(searchPopoverField);
    paramFields.unshift(editorHeadlessField);
    return paramFields;
  };

  MetadataTaskModule.prototype.__getMask = function() {
    var data, mask_id, ref, ref1;
    data = this._manager.__create_form.getData();
    mask_id = data != null ? (ref = data["task_params"]) != null ? (ref1 = ref["create_object"]) != null ? ref1["mask_id"] : void 0 : void 0 : void 0;
    if (mask_id) {
      return Mask.getMaskByMaskName(ez5.mask.CURRENT._mask_by_id[mask_id].name);
    }
    return null;
  };

  MetadataTaskModule.prototype.__processSearchData = function(data) {
    var create_object_data, mask_id, ref, ref1, ref2, ref3;
    if (CUI.util.isEmpty(data)) {
      return data;
    }
    create_object_data = this._manager.__create_form.getData();
    mask_id = create_object_data != null ? (ref = create_object_data["task_params"]) != null ? (ref1 = ref["create_object"]) != null ? ref1["mask_id"] : void 0 : void 0 : void 0;
    data.best_mask_filter = false;
    data.objecttypes = [create_object_data != null ? (ref2 = create_object_data["task_params"]) != null ? (ref3 = ref2["create_object"]) != null ? ref3["objecttype"] : void 0 : void 0 : void 0];
    data.search.push({
      type: "in",
      fields: ["_mask"],
      "in": [ez5.mask.CURRENT._mask_by_id[mask_id].name]
    });
    return data;
  };

  MetadataTaskModule.prototype.getSaveData = function(save_data) {
    var ref;
    if (CUI.util.isEmpty((ref = save_data.task.task_params) != null ? ref.create_object : void 0)) {
      throw new InvalidSaveDataException();
    }
    save_data.task.frontend_prefs = this.__frontend_prefs;
    return save_data;
  };

  return MetadataTaskModule;

})(TaskModuleBase);

TaskManagerList.registerModule(MetadataTaskModule);
// Generated by CoffeeScript 1.12.7
var DeleteObjectsTaskModule,
  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;

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

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

  DeleteObjectsTaskModule.getModuleName = function() {
    return "delete_objects";
  };

  DeleteObjectsTaskModule.prototype.restoreFrontendPrefs = function(prefs) {
    var p;
    if (CUI.util.isEmpty(prefs)) {
      p = {
        search_data: {}
      };
    } else {
      p = prefs;
    }
    this.__frontend_prefs = p;
    return p;
  };

  DeleteObjectsTaskModule.prototype.__getFieldFromDef = function(def, opts) {
    var collection;
    if (opts == null) {
      opts = {};
    }
    if (def.plugin_type === "search") {
      collection = opts.collection || null;
      return SearchPopover.getBaseConfigButton(def.name, null, collection, null, null, true);
    }
    return DeleteObjectsTaskModule.__super__.__getFieldFromDef.call(this, def);
  };

  DeleteObjectsTaskModule.prototype.getSaveData = function(save_data) {
    var ref;
    if (CUI.util.isEmpty((ref = save_data.task.task_params) != null ? ref.search : void 0)) {
      throw new InvalidSaveDataException();
    }
    save_data.task.frontend_prefs = this.__frontend_prefs;
    return save_data;
  };

  return DeleteObjectsTaskModule;

})(TaskModuleBase);

TaskManagerList.registerModule(DeleteObjectsTaskModule);
// Generated by CoffeeScript 1.12.7
var AdminMessagesManager,
  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;

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

  function AdminMessagesManager() {
    this.loadListData = bind(this.loadListData, this);
    this.addRow = bind(this.addRow, this);
    this.getListFields = bind(this.getListFields, this);
    return AdminMessagesManager.__super__.constructor.apply(this, arguments);
  }

  AdminMessagesManager.label = function() {
    return "admin.menu.admin_messages";
  };

  AdminMessagesManager.is_allowed = function() {
    return ez5.session.hasSystemRight("root", "message");
  };

  AdminMessagesManager.group = function() {
    return "zzd_administration";
  };

  AdminMessagesManager.submenu = function() {
    return "administration";
  };

  AdminMessagesManager.path = function() {
    return ["adminmessagesmanager"];
  };

  AdminMessagesManager.prototype.getListFields = function() {
    return [
      {
        th_label: "admin.admin_messages.list.title"
      }, {
        th_label: "admin.admin_messages.list.webfrontend_type"
      }
    ];
  };

  AdminMessagesManager.prototype.getMissingName = function() {
    return $$("admin.admin_messages.missing.name");
  };

  AdminMessagesManager.prototype.getLeftTitle = function() {
    return $$("admin.admin_messages.pane.left.title");
  };

  AdminMessagesManager.prototype.getCenterTitle = function() {
    return $$("admin.admin_messages.pane.center.title");
  };

  AdminMessagesManager.prototype.getNavigationLocaKeyPrefix = function() {
    return "result.navigation.toolbar.message";
  };

  AdminMessagesManager.prototype.getNoRecordLocaKey = function() {
    return $$("result.navigation.toolbar.message.no_messages");
  };

  AdminMessagesManager.prototype.addRow = function() {
    return this.tree.addNode(new ez5.defaults["class"].AdminMessage({
      manager: this
    })).done((function(_this) {
      return function(node) {
        return node.select();
      };
    })(this));
  };

  AdminMessagesManager.prototype.loadList = function(filter, opts) {
    if (opts == null) {
      opts = {};
    }
    if (!opts.searchOpts) {
      opts.searchOpts = {};
    }
    CUI.mergeMap(opts.searchOpts, {
      type: "message",
      sort: [
        {
          field: "message.title"
        }
      ]
    });
    opts.newInstanceFunc = (function(_this) {
      return function(msg) {
        return new ez5.defaults["class"].AdminMessage({
          message: msg,
          manager: _this
        });
      };
    })(this);
    return AdminMessagesManager.__super__.loadList.call(this, filter, opts);
  };

  AdminMessagesManager.prototype.loadListData = function(data) {
    var i, len, msg, ref;
    this.msgs = [];
    ref = data.objects;
    for (i = 0, len = ref.length; i < len; i++) {
      msg = ref[i];
      this.msgs.push(new ez5.defaults["class"].AdminMessage({
        message: msg,
        manager: this
      }));
    }
    return this.msgs;
  };

  return AdminMessagesManager;

})(SystemListManager);

ez5.session_ready(function() {
  return ez5.rootMenu.registerApp(AdminMessagesManager);
});
// 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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

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

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

  AdminMessageDeepLink.prototype.findAppByLocation = function(location, apps) {
    var idMessage, loadMessage;
    idMessage = location.hash.match("^#/messages/(.+)");
    if (!idMessage) {
      return CUI.rejectedPromise();
    }
    idMessage = parseInt(idMessage[1]);
    if (!CUI.util.isNumber(idMessage)) {
      return CUI.rejectedPromise();
    }
    loadMessage = (function(_this) {
      return function() {
        if (_this.__shown) {
          return;
        }
        return ez5.api.search({
          json_data: {
            type: "message",
            limit: 1,
            search: [
              {
                bool: "must",
                type: "in",
                fields: ["message._id"],
                "in": [idMessage]
              }
            ]
          },
          handle_error: function() {
            return true;
          }
        }).done(function(data) {
          var adminMessage, hasGroup, idGroups, message;
          message = data.objects[0];
          if (!message) {
            return;
          }
          if (!ez5.session.hasSystemRight("root")) {
            idGroups = ez5.session.getGroups().map(function(group) {
              return group.getId();
            });
            hasGroup = message._groups.find(function(group) {
              var ref;
              return ref = group.group._id, indexOf.call(idGroups, ref) >= 0;
            });
            if (!hasGroup) {
              DetailDeepLink.askLogin("message.deep_link_needs_login").done(function() {
                return loadMessage();
              });
              return;
            }
          }
          adminMessage = new ez5.defaults["class"].AdminMessage({
            message: message
          });
          adminMessage.showMessage();
          return _this.__shown = true;
        });
      };
    })(this);
    loadMessage();
    return CUI.rejectedPromise();
  };

  return AdminMessageDeepLink;

})(RootMenuAppLoader);

ez5.session_ready(function() {
  return ez5.rootMenu.registerAppLoader(new ez5.AdminMessageDeepLink());
});
// Generated by CoffeeScript 1.12.7
var XMLFormField;

XMLFormField = (function() {
  XMLFormField.SELECTED_CLASS = "cui-selected";

  XMLFormField.SEARCH_IMPORT_REGEXP = /\/rdf:Description\/(.*)\/rdf:Description\/(.*)/;

  XMLFormField.SEARCH_IMPORT_LIST = "/rdf:Bag/rdf:li";

  XMLFormField.SEARCH_IMPORT_PRINTABLE = "et:prt";

  XMLFormField.SEARCH_IMPORT_RAW = "et:val";

  function XMLFormField(opts, data1) {
    this.opts = opts != null ? opts : {};
    this.data = data1;
    CUI.util.assert(this.opts.grid instanceof XMLFormGrid, "new XMLFormField", "grid needs to be instance of XMLFormGrid", {
      opts: this.opts
    });
    CUI.util.assert(CUI.util.isPlainObject(this.opts.def), "new XMLFormField", "Definition is no plain Object", {
      opts: this.opts
    });
    this.__def = this.opts.def;
    this.__idx = this.opts.idx;
    this.__def.colspan = this.__def.colspan || 1;
    this.__def.rowspan = this.__def.rowspan || 1;
    this.fields = [];
  }

  XMLFormField.prototype.getText = function() {
    if (CUI.util.isPlainObject(this.__def.text)) {
      return ez5.loca.getBestFrontendValue(this.__def.text);
    } else {
      return this.__def.text;
    }
  };

  XMLFormField.prototype.getPos = function() {
    CUI.util.assert(!isNaN(this.__def.x * this.__def.y), "XMLFormField.getPos", "Definition needs x, y", {
      opts: this.opts
    });
    return {
      x: this.__def.x,
      y: this.__def.y,
      colspan: this.__def.colspan,
      rowspan: this.__def.rowspan
    };
  };

  XMLFormField.prototype.setPos = function(x, y) {
    this.__def.x = x;
    this.__def.y = y;
  };

  XMLFormField.prototype.dump = function(s, spc) {
    var key;
    key = this.getBareKey();
    if (CUI.util.isEmpty(key)) {
      s.push(spc + ("[" + (this.getID()) + ", " + (CUI.util.getObjectClass(this)) + "]"));
    } else {
      s.push(spc + (key + " [" + (this.getID()) + ", " + (CUI.util.getObjectClass(this)) + "]"));
    }
    return s;
  };

  XMLFormField.prototype.getID = function() {
    return this.__def._id || ((this.opts.grid.getID()) + "." + this.__idx);
  };

  XMLFormField.prototype.setIdx = function(idx) {
    return this.__idx = idx;
  };

  XMLFormField.prototype.getBareKey = function() {
    if (CUI.util.isEmpty(this.__def.xml)) {
      return "";
    } else {
      return this.__def.xml;
    }
  };

  XMLFormField.prototype.hasName = function() {
    if (!ez5.version("6.14")) {
      return false;
    }
    return !CUI.util.isEmpty(this.__def.name);
  };

  XMLFormField.prototype.getName = function() {
    return this.__def.name;
  };

  XMLFormField.prototype.getKey = function() {
    var key;
    key = this.getBareKey();
    if ((key != null ? key.substring(0, 1) : void 0) === "/") {
      return key;
    } else if (CUI.util.isEmpty(key)) {
      return this.opts.grid.getKey();
    } else {
      return (this.opts.grid.getKey()) + "/" + key;
    }
  };

  XMLFormField.prototype.getDataKey = function() {
    if (this.hasName()) {
      return this.getName();
    } else {
      return this.getID();
    }
  };

  XMLFormField.prototype.renderTd = function() {
    var content, pos;
    pos = this.getPos();
    this.wrappersDiv = CUI.dom.div("xml-form-wrapper-fields-div");
    this.__td = CUI.dom.$element("td");
    CUI.dom.setAttributeMap(this.__td, {
      colspan: pos.colspan,
      rowspan: pos.rowspan
    });
    CUI.dom.addClass(this.__td, "td-xml-form-field td-xml-form-field-" + (CUI.util.getObjectClass(this).substr('XMLFormField'.length).toLowerCase()));
    content = this.renderContent();
    CUI.dom.append(this.__td, content);
    if (this.__def.align) {
      CUI.dom.addClass(this.__td, "td-align-" + this.__def.align);
    }
    if (this.__def["class"]) {
      CUI.dom.addClass(this.__td, this.__def["class"]);
    }
    CUI.Events.listen({
      type: "click",
      node: this.__td,
      call: (function(_this) {
        return function() {
          var i, j, len, len1, parent, ref, row, tab, tabs, tr;
          row = _this.getRow();
          tabs = [];
          parent = CUI.dom.parents(row, ".ez5-xml-form-tab-tab")[0];
          tabs = tabs.concat(CUI.dom.findPreviousSiblings(parent));
          tabs.push(parent);
          tabs = tabs.concat(CUI.dom.findNextSiblings(parent));
          for (i = 0, len = tabs.length; i < len; i++) {
            tab = tabs[i];
            ref = CUI.dom.findElements(tab, "tr");
            for (j = 0, len1 = ref.length; j < len1; j++) {
              tr = ref[j];
              if (tr === row) {
                continue;
              }
              CUI.dom.removeClass(tr, XMLFormField.SELECTED_CLASS);
            }
          }
          CUI.dom.toggleClass(row, XMLFormField.SELECTED_CLASS);
          CUI.Events.trigger({
            node: row,
            type: "metadata-mapping-field-click",
            info: {
              field: _this,
              indexBlock: CUI.util.idxInArray(parent, tabs)
            }
          });
        };
      })(this)
    });
    return this.__td;
  };

  XMLFormField.prototype.getRow = function() {
    return CUI.dom.parents(this.__td, "tr")[0];
  };

  XMLFormField.prototype.reload = function() {
    var content;
    content = this.renderContent();
    CUI.dom.replace(this.__td, content);
  };

  XMLFormField.prototype.renderContent = function() {
    var p;
    p = this.getPos();
    return CUI.util.getObjectClass(this) + (p.x + "/" + p.y);
  };

  XMLFormField.prototype.renderDropWrapper = function(element) {
    var div;
    this.drop = CUI.dom.div("xml-form-field-drop-wrap");
    this.__droppable = new CUI.Droppable({
      element: this.drop,
      accept: function(ev, info) {
        var ref;
        if (!((ref = info.globalDrag) != null ? ref.dragWrapper : void 0)) {
          return false;
        } else {
          return true;
        }
      },
      drop: (function(_this) {
        return function(ev, info) {
          var dragWrapper, dw;
          dragWrapper = info.globalDrag.dragWrapper;
          if (dragWrapper.isLinked) {
            return _this.getForm().addDragWrapper(dragWrapper, _this.getDataKey());
          } else {
            dw = new window[CUI.util.getObjectClass(dragWrapper)](dragWrapper);
            dw.init();
            return _this.getForm().addDragWrapper(dw, _this.getDataKey());
          }
        };
      })(this)
    });
    CUI.dom.append(this.drop, element);
    CUI.dom.append(this.drop, this.wrappersDiv);
    this.update(false);
    div = CUI.dom.div("ez5-xml-form-field-container");
    CUI.dom.append(div, [XMLFormWrapper.getOutputSpan(this.getBareKey()), this.drop]);
    return div;
  };

  XMLFormField.prototype.getForm = function() {
    return this.opts.grid.getForm();
  };

  XMLFormField.prototype.getBlock = function() {
    return this.opts.grid.getBlock();
  };

  XMLFormField.prototype.update = function() {
    var dw, dws, i, len, ref;
    CUI.dom.empty(this.wrappersDiv);
    dws = (ref = this.data[this.getDataKey()]) != null ? ref.dragWrappers : void 0;
    if (dws) {
      for (i = 0, len = dws.length; i < len; i++) {
        dw = dws[i];
        CUI.dom.append(this.wrappersDiv, dw.renderAsTarget(this));
      }
    }
  };

  XMLFormField.prototype.getDef = function() {
    return this.__def;
  };

  XMLFormField.prototype.setDef = function(def) {
    return this.__def = def;
  };

  XMLFormField.prototype.getCustomDataTags = function() {
    var xmlImportData;
    if (this.__def.xml_export) {
      return this.__def.xml_export.map((function(_this) {
        return function(_tag) {
          return {
            tag: _tag,
            list: _tag.list
          };
        };
      })(this));
    } else if (this.__def.xml_import) {
      xmlImportData = this.__def.xml_import.map((function(_this) {
        return function(tag) {
          var data, list, match, path, printable, rawValue;
          match = tag.search.match(XMLFormField.SEARCH_IMPORT_REGEXP);
          if (match != null ? match[1] : void 0) {
            path = [match[1]];
          } else {
            path = [tag.search];
          }
          if (match != null ? match[2] : void 0) {
            if (match[2].startsWith(XMLFormField.SEARCH_IMPORT_RAW)) {
              printable = false;
              rawValue = true;
            } else if (match[2].startsWith(XMLFormField.SEARCH_IMPORT_PRINTABLE)) {
              printable = true;
              rawValue = false;
            }
          }
          list = tag.search.endsWith(XMLFormField.SEARCH_IMPORT_LIST);
          data = {
            path: path
          };
          return {
            tag: data,
            list: list,
            rawValue: rawValue,
            printable: printable,
            originalPath: tag.search
          };
        };
      })(this));
      return xmlImportData;
    } else {
      return [];
    }
  };

  XMLFormField.prototype.getBaseSaveData = function() {
    var def, entry, f, i, j, k, l, len, len1, len2, len3, ref, ref1, ref2, ref3, sd;
    def = this.getDef();
    sd = {
      _id: this.getID(),
      type: "field",
      xml_import: [],
      xml_export: [],
      strategy_import: def.strategy_import,
      strategy_export: def.strategy_export
    };
    if (this.hasName()) {
      delete sd._id;
      sd.name = this.getName();
    }
    if (def.text) {
      sd.text = def.text;
    }
    if (def.custom) {
      sd.custom = true;
    }
    if (def.xml) {
      if (def.type === "Hidden") {
        sd.xml_export.push({
          type: "element",
          path: def.xml,
          attributes: def.attributes,
          text: ""
        });
      } else {
        sd.xml_import.push({
          search: def.xml,
          strategy: "replace"
        });
        sd.xml_export.push({
          type: "element",
          path: def.xml,
          attributes: def.attributes
        });
      }
    }
    if (def.xml_import) {
      ref = def.xml_import;
      for (i = 0, len = ref.length; i < len; i++) {
        f = ref[i];
        sd.xml_import.push(f);
      }
    }
    if (def.xml_export) {
      ref1 = def.xml_export;
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        f = ref1[j];
        sd.xml_export.push(CUI.util.copyObject(f));
      }
    }
    if (ez5.version("6")) {
      if (!CUI.util.isEmpty(def.elements_js)) {
        ref2 = sd.xml_export;
        for (k = 0, len2 = ref2.length; k < len2; k++) {
          entry = ref2[k];
          entry.elements_js = def.elements_js;
        }
      } else {
        ref3 = sd.xml_export;
        for (l = 0, len3 = ref3.length; l < len3; l++) {
          entry = ref3[l];
          delete entry.elements_js;
        }
      }
    }
    if (sd.xml_import.length === 0) {
      delete sd.xml_import;
    }
    if (sd.xml_export.length === 0) {
      delete sd.xml_export;
    }
    return sd;
  };

  XMLFormField.prototype.destroy = function() {
    var ref;
    CUI.dom.remove(this.wrappersDiv);
    CUI.dom.remove(this.__td);
    if ((ref = this.__droppable) != null) {
      ref.destroy();
    }
    delete this.drop;
    delete this.__td;
    delete this.wrappersDiv;
    delete this.__def;
    delete this.opts;
  };

  return XMLFormField;

})();
// Generated by CoffeeScript 1.12.7
var XMLFormFieldMapping,
  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;

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

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

  XMLFormFieldMapping.prototype.getSaveData = function(save_data) {
    var dw, i, len, ref, sdata, ssdata;
    ssdata = this.getBaseSaveData();
    ssdata.easydb = [];
    ref = this.data[this.getDataKey()].dragWrappers;
    for (i = 0, len = ref.length; i < len; i++) {
      dw = ref[i];
      sdata = {};
      dw.getSaveData(sdata);
      if (!CUI.util.isEmptyObject(sdata)) {
        ssdata.easydb.push(sdata);
      }
    }
    save_data.fields.push(ssdata);
    return save_data;
  };

  XMLFormFieldMapping.prototype.__renderMappingTags = function() {
    var duplicatedTags, i, len, tag, tags, tagsContainer, tagsData;
    if (!this.__def) {
      return;
    }
    duplicatedTags = [];
    tagsData = this.getCustomDataTags();
    tags = tagsData.map((function(_this) {
      return function(_tag) {
        var __tag, duplicatedTag, i, len, originalPaths, tagOptions, tooltip;
        if (duplicatedTags.some(function(_duplicatedTag) {
          return _duplicatedTag.tag.path === _tag.tag.path;
        })) {
          return;
        }
        tooltip = null;
        if (_tag.originalPath) {
          tooltip = {
            markdown: true,
            placement: 'w',
            show_ms: 100,
            hide_ms: 200,
            content: function(tooltip) {
              var i, len, li, op, ul;
              ul = CUI.dom.ul();
              for (i = 0, len = originalPaths.length; i < len; i++) {
                op = originalPaths[i];
                li = CUI.dom.li();
                CUI.dom.append(li, new CUI.Label({
                  text: op,
                  multiline: true
                }));
                CUI.dom.append(ul, li);
              }
              return ul;
            }
          };
          originalPaths = [_tag.originalPath];
        }
        duplicatedTag = tagsData.filter(function(__tag) {
          if (CUI.util.isArray(__tag.tag.path)) {
            return (__tag.tag.path[0] === _tag.tag.path[0]) && !CUI.util.isEqual(__tag, _tag);
          }
          return (__tag.tag.path === _tag.tag.path) && !CUI.util.isEqual(__tag, _tag);
        });
        if (duplicatedTag.length > 0) {
          duplicatedTags = duplicatedTags.concat(duplicatedTag);
          if (tooltip) {
            for (i = 0, len = duplicatedTag.length; i < len; i++) {
              __tag = duplicatedTag[i];
              originalPaths.push(__tag.originalPath);
            }
          }
        }
        _tag.tag.list = _tag.list;
        _tag.tag.printable = _tag.printable;
        _tag.tag.rawValue = _tag.rawValue;
        tagOptions = MetadataTagSelector.getTagOptions(_tag.tag);
        return new CUI.Label({
          content: [_tag.tag.path],
          tooltip: tooltip
        });
      };
    })(this));
    if (!(tags != null ? tags.length : void 0) > 0) {
      return;
    }
    tagsContainer = CUI.dom.div("ez5-metadata-mapping-tags-list");
    for (i = 0, len = tags.length; i < len; i++) {
      tag = tags[i];
      CUI.dom.append(tagsContainer, tag);
    }
    CUI.Events.listen({
      type: "xml-mapping-search",
      node: tagsContainer,
      instance: this,
      call: (function(_this) {
        return function(_, info) {
          var j, len1, tr;
          tr = CUI.dom.parents(tagsContainer, "tr")[0];
          for (j = 0, len1 = tags.length; j < len1; j++) {
            tag = tags[j];
            if (!tag) {
              return;
            }
            if (info.search.length === 0 || tag.DOM.textContent.toUpperCase().indexOf(info.search.toUpperCase()) >= 0) {
              CUI.dom.showElement(tr);
              return;
            }
          }
          CUI.dom.hideElement(tr);
        };
      })(this)
    });
    return tagsContainer;
  };

  XMLFormFieldMapping.prototype.renderContent = function() {
    return new CUI.HorizontalList({
      maximize_horizontal: true,
      content: [this.__renderMappingTags(), this.renderDropWrapper()]
    });
  };

  return XMLFormFieldMapping;

})(XMLFormField);
// Generated by CoffeeScript 1.12.7
var XMLFormFieldCheckbox,
  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;

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

  function XMLFormFieldCheckbox() {
    this.renderContent = bind(this.renderContent, this);
    return XMLFormFieldCheckbox.__super__.constructor.apply(this, arguments);
  }

  XMLFormFieldCheckbox.prototype.renderContent = function() {
    return this.renderDropWrapper(new CUI.Checkbox({
      name: "horst",
      data: {}
    }).start().DOM);
  };

  return XMLFormFieldCheckbox;

})(XMLFormFieldMapping);
// Generated by CoffeeScript 1.12.7
var XMLFormFieldDate,
  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;

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

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

  return XMLFormFieldDate;

})(XMLFormFieldMapping);
// Generated by CoffeeScript 1.12.7
var XMLFormFieldDragWrapper, XMLFormFieldDragWrapperLoader,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

XMLFormFieldDragWrapper = (function() {
  function XMLFormFieldDragWrapper(opts, data) {
    this.opts = opts;
    this.data = data != null ? data : {};
    this.getSaveData = bind(this.getSaveData, this);
    if (this.opts instanceof XMLFormFieldDragWrapper) {
      this.data = this.opts.data;
      this.opts = this.opts.opts;
    }
    CUI.util.assert(this.opts.formWrapper instanceof XMLFormWrapper, "new XMLFormFieldDragWrapper", "opts.formWrapper needs to be instanceof XMLFormWrapper", {
      opts: this.opts
    });
  }

  XMLFormFieldDragWrapper.prototype.renderAsSource = function() {
    var source;
    source = CUI.dom.div("xml-form-field-drag-wrap");
    new CUI.Draggable({
      element: source,
      create: (function(_this) {
        return function() {
          return {
            dragWrapper: _this
          };
        };
      })(this)
    });
    return CUI.dom.append(source, this.contentSource());
  };

  XMLFormFieldDragWrapper.prototype.getXMLFormWrapper = function() {
    return this.opts.formWrapper;
  };

  XMLFormFieldDragWrapper.prototype.renderAsCondition = function() {
    var condition;
    condition = CUI.dom.div("xml-form-field-condition");
    return CUI.dom.append(condition, this.contentSource());
  };

  XMLFormFieldDragWrapper.prototype.renderAsTarget = function(formField) {
    this.__target = CUI.dom.div("xml-form-field-drag-wrap-in-form");
    new CUI.Draggable({
      element: this.__target,
      create: (function(_this) {
        return function() {
          return {
            dragWrapper: _this
          };
        };
      })(this)
    });
    CUI.Events.listen({
      type: "toolbox",
      node: this.__target,
      call: (function(_this) {
        return function(event, info) {
          info.tools.push(new ToolboxTool({
            name: "metadata-mapping-field-wrapper-remove",
            group: "metadata-mapping-field-wrapper-actions",
            run: function() {
              return formField.getForm().removeDragWrapper(_this);
            }
          }));
        };
      })(this)
    });
    CUI.dom.empty(this.__target);
    CUI.dom.append(this.__target, this.contentTarget());
    return this.__target;
  };

  XMLFormFieldDragWrapper.prototype.conditionTypes = ["any", "all", "none"];

  XMLFormFieldDragWrapper.prototype.addEmptyCondition = function(type) {
    return this.conditions.push((new XMLFormWrapperCondition()).loadCondition(this, {
      type: type
    }));
  };

  XMLFormFieldDragWrapper.prototype.init = function() {
    var c, i, j, k, len, len1, ref, ref1, types;
    if (!((ref = this.data.conditions) != null ? ref.length : void 0)) {
      return;
    }
    this.conditions = [];
    types = this.conditionTypes.slice(0);
    ref1 = this.data.conditions;
    for (i = 0, len = ref1.length; i < len; i++) {
      c = ref1[i];
      CUI.util.removeFromArray(c.type, types);
      this.conditions.push((new XMLFormWrapperCondition()).loadCondition(this, c));
    }
    for (j = 0, len1 = types.length; j < len1; j++) {
      k = types[j];
      this.addEmptyCondition(k);
    }
    this.conditions.sort((function(_this) {
      return function(a, b) {
        var a_idx, b_idx;
        a_idx = _this.conditionTypes.indexOf(a.getType());
        b_idx = _this.conditionTypes.indexOf(b.getType());
        if (a_idx < b_idx) {
          return -1;
        } else if (a_idx > b_idx) {
          return 1;
        } else {
          return 0;
        }
      };
    })(this));
    return this;
  };

  XMLFormFieldDragWrapper.prototype.getSaveData = function(save_data) {
    var c, i, len, ref, ref1, sdata;
    if ((ref = this.conditions) != null ? ref.length : void 0) {
      save_data.conditions = [];
      ref1 = this.conditions;
      for (i = 0, len = ref1.length; i < len; i++) {
        c = ref1[i];
        sdata = c.getSaveData();
        if (!sdata) {
          continue;
        }
        save_data.conditions.push(sdata);
      }
      if (!save_data.conditions.length) {
        delete save_data.conditions;
      }
    }
    return save_data;
  };

  XMLFormFieldDragWrapper.prototype.destroy = function() {
    var ref;
    if ((ref = this.conditions) != null) {
      ref.length = 0;
    }
    delete this.__target;
    return delete this.data;
  };

  return XMLFormFieldDragWrapper;

})();

XMLFormFieldDragWrapperLoader = (function() {
  function XMLFormFieldDragWrapperLoader() {
    this.getInstanceFromSaveData = bind(this.getInstanceFromSaveData, this);
  }

  XMLFormFieldDragWrapperLoader.prototype.getInstanceFromSaveData = function(formWrapper, save_data) {
    return null;
  };

  return XMLFormFieldDragWrapperLoader;

})();
// Generated by CoffeeScript 1.12.7
var XMLFormFieldDragWrapperField, XMLFormFieldDragWrapperFieldLoader,
  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,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

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

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

  XMLFormFieldDragWrapperField.prototype.getName = function(useTableName) {
    if (useTableName == null) {
      useTableName = false;
    }
    return this.opts.field.getMappingSourceFullNameLocalized(useTableName);
  };

  XMLFormFieldDragWrapperField.prototype.contentSource = function() {
    return CUI.dom.text(this.getName());
  };

  XMLFormFieldDragWrapperField.prototype.contentTarget = function() {
    var content;
    content = CUI.dom.text(this.getName());
    new CUI.Tooltip({
      element: content,
      text: this.opts.treeNode.getFieldNamePath().join(" / ")
    });
    return content;
  };

  XMLFormFieldDragWrapperField.prototype.getID = function() {
    return this.opts.treeNode.fullFieldName();
  };

  XMLFormFieldDragWrapperField.prototype.getObjecttype = function() {
    return this.opts.treeNode.getObjecttype();
  };

  XMLFormFieldDragWrapperField.prototype.init = function() {
    return XMLFormFieldDragWrapperField.__super__.init.call(this);
  };

  XMLFormFieldDragWrapperField.prototype.getSaveData = function(save_data) {
    var f, i, k, len, ref, ref1, v;
    XMLFormFieldDragWrapperField.__super__.getSaveData.call(this, save_data);
    ref = this.opts.field.getXMLFormWrapperSaveData(this);
    for (k in ref) {
      v = ref[k];
      save_data[k] = v;
    }
    save_data.field = this.opts.treeNode.fullFieldName();
    ref1 = this.opts.field.getXMLFormWrapperFields(this) || [];
    for (i = 0, len = ref1.length; i < len; i++) {
      f = ref1[i];
      save_data[f.name] = this.data[f.name];
    }
  };

  return XMLFormFieldDragWrapperField;

})(XMLFormFieldDragWrapper);

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

  function XMLFormFieldDragWrapperFieldLoader() {
    this.getInstanceFromSaveData = bind(this.getInstanceFromSaveData, this);
    return XMLFormFieldDragWrapperFieldLoader.__super__.constructor.apply(this, arguments);
  }

  XMLFormFieldDragWrapperFieldLoader.prototype.getInstanceFromSaveData = function(formWrapper, save_data) {
    var dw, ref, ref1, ref2, type;
    if (!(save_data.field && save_data.type)) {
      return null;
    }
    dw = formWrapper.wrapperFields[save_data.field];
    if (!dw) {
      return null;
    }
    type = (ref = dw.opts) != null ? (ref1 = ref.field) != null ? typeof ref1.getXMLFormWrapperType === "function" ? ref1.getXMLFormWrapperType() : void 0 : void 0 : void 0;
    if (save_data.type !== type) {
      console.warn((CUI.util.getObjectClass(this)) + ".getInstanceFromSaveData: Loading problem, type mismatch: stored: " + save_data.type + " != field: " + type, {
        save_data: save_data,
        dragWrapper: dw,
        field: (ref2 = dw.opts) != null ? ref2.field : void 0
      });
    }
    dw = new window[CUI.util.getObjectClass(dw)](dw.opts, save_data);
    dw.init();
    return dw;
  };

  return XMLFormFieldDragWrapperFieldLoader;

})(XMLFormFieldDragWrapperLoader);
// Generated by CoffeeScript 1.12.7
var XMLFormFieldDragWrapperFixedValue, XMLFormFieldDragWrapperFixedValueLoader,
  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;

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

  XMLFormFieldDragWrapperFixedValue.PREFIX_ID = "__fixed_value_";

  function XMLFormFieldDragWrapperFixedValue(opts, data) {
    if (data == null) {
      data = {};
    }
    this.getSaveData = bind(this.getSaveData, this);
    this.contentTarget = bind(this.contentTarget, this);
    XMLFormFieldDragWrapperFixedValue.__super__.constructor.call(this, opts, data);
    this.__id = Math.floor(Math.random() * 10000) + 1;
    if (!CUI.util.isNull(data.text)) {
      this.data[this.__getDataName()] = data.text;
    }
    return;
  }

  XMLFormFieldDragWrapperFixedValue.prototype.contentSource = function() {
    return CUI.dom.text($$("xml.form.field.drag.wrapper.fixed.value.empty_text"));
  };

  XMLFormFieldDragWrapperFixedValue.prototype.contentTarget = function() {
    if (CUI.util.isEmpty(this.data[this.__getDataName()])) {
      return $$("xml.form.field.drag.wrapper.fixed.value.empty_text");
    } else {
      return this.data[this.__getDataName()];
    }
  };

  XMLFormFieldDragWrapperFixedValue.prototype.getSaveData = function(save_data) {
    XMLFormFieldDragWrapperFixedValue.__super__.getSaveData.call(this, save_data);
    save_data.type = "text_fixed";
    return save_data.text = this.data[this.__getDataName()];
  };

  XMLFormFieldDragWrapperFixedValue.prototype.getID = function() {
    return this.__id;
  };

  XMLFormFieldDragWrapperFixedValue.prototype.init = function() {
    XMLFormFieldDragWrapperFixedValue.__super__.init.call(this);
    this.__openValueModal();
    return this;
  };

  XMLFormFieldDragWrapperFixedValue.prototype.renderAsTarget = function(formField) {
    var target;
    target = XMLFormFieldDragWrapperFixedValue.__super__.renderAsTarget.call(this, formField);
    CUI.Events.listen({
      node: target,
      type: "click",
      call: (function(_this) {
        return function() {
          return _this.__openValueModal();
        };
      })(this)
    });
    return target;
  };

  XMLFormFieldDragWrapperFixedValue.prototype.__openValueModal = function() {
    var nameModal, originalValue;
    originalValue = this.data[this.__getDataName()];
    nameModal = new CUI.Modal({
      cancel: false,
      pane: {
        padded: true,
        header_left: new LocaLabel({
          loca_key: "xml.form.field.drag.wrapper.fixed.value.text"
        }),
        content: this.__getNameInput(),
        footer_right: [
          {
            text: $$("base.cancel"),
            onClick: (function(_this) {
              return function() {
                var f, i, len, ref;
                _this.data[_this.__getDataName()] = originalValue;
                ref = _this.isLinked.formFields;
                for (i = 0, len = ref.length; i < len; i++) {
                  f = ref[i];
                  f.update(false);
                }
                return nameModal.destroy();
              };
            })(this)
          }, {
            text: $$("base.ok"),
            primary: true,
            onClick: (function(_this) {
              return function() {
                CUI.Events.trigger({
                  type: "data-changed",
                  node: _this.__target
                });
                return nameModal.destroy();
              };
            })(this)
          }
        ]
      }
    });
    return nameModal.show();
  };

  XMLFormFieldDragWrapperFixedValue.prototype.__getDataName = function() {
    return XMLFormFieldDragWrapperFixedValue.PREFIX_ID + this.__id;
  };

  XMLFormFieldDragWrapperFixedValue.prototype.__getNameInput = function() {
    var form;
    form = new CUI.Form({
      fields: [
        {
          type: CUI.Input,
          name: this.__getDataName(),
          data: this.data,
          onDataChanged: (function(_this) {
            return function() {
              var f, i, len, ref;
              ref = _this.isLinked.formFields;
              for (i = 0, len = ref.length; i < len; i++) {
                f = ref[i];
                f.update(false);
              }
            };
          })(this)
        }
      ]
    });
    return form.start();
  };

  return XMLFormFieldDragWrapperFixedValue;

})(XMLFormFieldDragWrapper);

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

  function XMLFormFieldDragWrapperFixedValueLoader() {
    this.getInstanceFromSaveData = bind(this.getInstanceFromSaveData, this);
    return XMLFormFieldDragWrapperFixedValueLoader.__super__.constructor.apply(this, arguments);
  }

  XMLFormFieldDragWrapperFixedValueLoader.prototype.getInstanceFromSaveData = function(formWrapper, save_data) {
    if (save_data.type === "text_fixed") {
      return new XMLFormFieldDragWrapperFixedValue({
        formWrapper: formWrapper
      }, save_data);
    }
    return null;
  };

  return XMLFormFieldDragWrapperFixedValueLoader;

})(XMLFormFieldDragWrapperLoader);
// Generated by CoffeeScript 1.12.7
var XMLFormFieldDragDeepLink, XMLFormFieldDragDeepLinkLoader,
  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;

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

  function XMLFormFieldDragDeepLink() {
    this.getSaveData = bind(this.getSaveData, this);
    this.contentTarget = bind(this.contentTarget, this);
    return XMLFormFieldDragDeepLink.__super__.constructor.apply(this, arguments);
  }

  XMLFormFieldDragDeepLink.prototype.__getDataName = function() {
    return 'deep_link_url';
  };

  XMLFormFieldDragDeepLink.prototype.contentSource = function() {
    return CUI.dom.text($$("xml.form.field.drag.wrapper.fixed.value.deep_link"));
  };

  XMLFormFieldDragDeepLink.prototype.contentTarget = function() {
    return CUI.dom.text($$("xml.form.field.drag.wrapper.fixed.value.deep_link"));
  };

  XMLFormFieldDragDeepLink.prototype.getSaveData = function(save_data) {
    XMLFormFieldDragDeepLink.__super__.getSaveData.call(this, save_data);
    return save_data.type = "deep_link_url";
  };

  return XMLFormFieldDragDeepLink;

})(XMLFormFieldDragWrapper);

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

  function XMLFormFieldDragDeepLinkLoader() {
    this.getInstanceFromSaveData = bind(this.getInstanceFromSaveData, this);
    return XMLFormFieldDragDeepLinkLoader.__super__.constructor.apply(this, arguments);
  }

  XMLFormFieldDragDeepLinkLoader.prototype.getInstanceFromSaveData = function(formWrapper, save_data) {
    if (save_data.type === "deep_link_url") {
      return new XMLFormFieldDragDeepLink({
        formWrapper: formWrapper
      });
    }
    return null;
  };

  return XMLFormFieldDragDeepLinkLoader;

})(XMLFormFieldDragWrapperLoader);
// Generated by CoffeeScript 1.12.7
var XMLFormFieldGroup,
  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;

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

  function XMLFormFieldGroup(opts, data) {
    this.opts = opts;
    this.data = data;
    this.getSaveData = bind(this.getSaveData, this);
    this.update = bind(this.update, this);
    this.dump = bind(this.dump, this);
    this.renderContent = bind(this.renderContent, this);
    XMLFormFieldGroup.__super__.constructor.call(this, this.opts, this.data);
    this.grid = new XMLFormGrid({
      father_field: this,
      fields: this.opts.def.fields
    }, this.data);
  }

  XMLFormFieldGroup.prototype.renderContent = function() {
    return this.grid.render();
  };

  XMLFormFieldGroup.prototype.dump = function(s, spc) {
    XMLFormFieldGroup.__super__.dump.call(this, s, spc);
    this.grid.dump(s, spc + "  ");
    return s;
  };

  XMLFormFieldGroup.prototype.update = function() {
    XMLFormFieldGroup.__super__.update.call(this);
    return this.grid.update();
  };

  XMLFormFieldGroup.prototype.getSaveData = function(save_data) {
    var sdata;
    sdata = {
      type: "list",
      path: this.getBareKey(),
      fields: []
    };
    this.grid.getSaveData(sdata);
    if (sdata.fields.length) {
      save_data.fields.push(sdata);
    }
    return save_data;
  };

  return XMLFormFieldGroup;

})(XMLFormField);
// Generated by CoffeeScript 1.12.7
var XMLFormFieldForm,
  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;

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

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

  return XMLFormFieldForm;

})(XMLFormFieldGroup);
// Generated by CoffeeScript 1.12.7
var XMLFormFieldSkip,
  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;

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

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

  XMLFormFieldSkip.prototype.renderTd = function() {};

  XMLFormFieldSkip.prototype.update = function() {};

  return XMLFormFieldSkip;

})(XMLFormField);
// Generated by CoffeeScript 1.12.7
var XMLFormFieldHidden,
  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;

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

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

  XMLFormFieldHidden.prototype.getSaveData = function(save_data) {
    var def, f, i, len, ref, sdata;
    sdata = this.getBaseSaveData();
    def = this.getDef();
    if (def.easydb) {
      if (!sdata.easydb) {
        sdata.easydb = [];
      }
      ref = def.easydb;
      for (i = 0, len = ref.length; i < len; i++) {
        f = ref[i];
        sdata.easydb.push(f);
      }
    }
    save_data.fields.push(sdata);
    return save_data;
  };

  XMLFormFieldHidden.prototype.getPos = function() {};

  return XMLFormFieldHidden;

})(XMLFormFieldSkip);
// Generated by CoffeeScript 1.12.7
var XMLFormFieldInput,
  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;

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

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

  return XMLFormFieldInput;

})(XMLFormFieldMapping);
// Generated by CoffeeScript 1.12.7
var XMLFormFieldList,
  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;

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

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

  return XMLFormFieldList;

})(XMLFormFieldGroup);
// Generated by CoffeeScript 1.12.7
var XMLFormFieldOutput,
  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;

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

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

  XMLFormFieldOutput.prototype.renderContent = function() {
    var cls, span;
    cls = "xml-form-field-output";
    if (ez5.version("6") && !CUI.util.isEmpty(this.__def.elements_js)) {
      cls += " ez5-xml-form-has-js";
    }
    span = CUI.dom.span(cls);
    span.textContent = this.getText();
    return span;
  };

  XMLFormFieldOutput.prototype.dump = function() {};

  return XMLFormFieldOutput;

})(XMLFormField);
// Generated by CoffeeScript 1.12.7
var XMLFormFieldSelect,
  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;

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

  function XMLFormFieldSelect() {
    this.renderContent = bind(this.renderContent, this);
    return XMLFormFieldSelect.__super__.constructor.apply(this, arguments);
  }

  XMLFormFieldSelect.prototype.renderContent = function() {
    var i, idx, len, opt, options, ref;
    options = [];
    ref = this.opts.def.options;
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      opt = ref[idx];
      options.push({
        text: opt.text[ez5.loca.culture],
        value: idx,
        selected: idx === 0
      });
    }
    return this.renderDropWrapper(new CUI.Select({
      name: "dummy",
      options: options,
      data: {}
    }).start().DOM);
  };

  return XMLFormFieldSelect;

})(XMLFormField);
// Generated by CoffeeScript 1.12.7
var XMLFormFieldSplitter,
  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;

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

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

  XMLFormFieldSplitter.prototype.renderContent = function() {
    var span;
    span = CUI.dom.span("xml-form-field-splitter");
    span.textContent = this.getText();
    return span;
  };

  XMLFormFieldSplitter.prototype.dump = function() {};

  return XMLFormFieldSplitter;

})(XMLFormField);
// Generated by CoffeeScript 1.12.7
var XMLFormFieldTextarea,
  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;

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

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

  return XMLFormFieldTextarea;

})(XMLFormFieldMapping);
// Generated by CoffeeScript 1.12.7
var XMLFormForm;

XMLFormForm = (function() {
  function XMLFormForm(opts, data) {
    var block, i, len, ref;
    this.opts = opts;
    this.data = data;
    this.__injectedBlocks = this.opts.blocks;
    this.__blocks = [];
    ref = this.opts.profile.tabs;
    for (i = 0, len = ref.length; i < len; i++) {
      block = ref[i];
      this.__addBlock(block);
    }
    return;
  }

  XMLFormForm.prototype.loadCustomFields = function(fields) {
    var entry, field, i, j, len, len1, ref, ref1;
    if (!fields) {
      return;
    }
    for (i = 0, len = fields.length; i < len; i++) {
      field = fields[i];
      if (ez5.version("6") && ((ref = field.xml_export) != null ? ref.length : void 0) > 0) {
        ref1 = field.xml_export;
        for (j = 0, len1 = ref1.length; j < len1; j++) {
          entry = ref1[j];
          if (entry.elements_js) {
            field.elements_js = entry.elements_js;
            break;
          }
        }
      }
      if (field.custom && field.text) {
        this.addCustomField(field);
      } else if (ez5.version("6") && field.elements_js) {
        this.__applyElementsJsToField(field);
      }
    }
  };

  XMLFormForm.prototype.__applyElementsJsToField = function(savedField) {
    var block, fieldId, fieldPair, i, inputDef, inputField, len, outputDef, outputField, ref, ref1;
    fieldId = savedField._id || savedField.name;
    if (!fieldId || !savedField.elements_js) {
      return;
    }
    ref = this.__blocks;
    for (i = 0, len = ref.length; i < len; i++) {
      block = ref[i];
      fieldPair = (ref1 = block.grid) != null ? ref1.findFieldById(fieldId) : void 0;
      if (fieldPair) {
        outputField = fieldPair[0], inputField = fieldPair[1];
        if (outputField && inputField) {
          outputDef = outputField.getDef();
          inputDef = inputField.getDef();
          outputDef.elements_js = savedField.elements_js;
          inputDef.elements_js = savedField.elements_js;
          outputField.reload();
          inputField.reload();
        }
        break;
      }
    }
  };

  XMLFormForm.prototype.addCustomField = function(fieldInputDef) {
    var fieldOutputDef;
    if (!this.isCustomFieldsEnabled()) {
      return;
    }
    fieldInputDef.type = "Input";
    fieldInputDef["class"] = "ez5-xml-form-entry-custom";
    fieldInputDef.custom = true;
    fieldOutputDef = {
      type: "Output",
      text: fieldInputDef.text,
      "class": "ez5-xml-form-entry-custom",
      custom: true,
      _id: fieldInputDef._id
    };
    if (ez5.version("6") && fieldInputDef.elements_js) {
      fieldOutputDef.elements_js = fieldInputDef.elements_js;
    }
    this.__customBlock.addCustomField(fieldOutputDef, fieldInputDef);
  };

  XMLFormForm.prototype.updateField = function(field, newDef) {
    field.setDef(newDef);
    field.reload();
  };

  XMLFormForm.prototype.removeCustomField = function(outputField, inputField) {
    if (!this.isCustomFieldsEnabled()) {
      return;
    }
    this.__customBlock.removeCustomField(outputField, inputField);
  };

  XMLFormForm.prototype.getField = function(pos, indexBlock) {
    var ref;
    return (ref = this.__blocks[indexBlock]) != null ? ref.getField(pos) : void 0;
  };

  XMLFormForm.prototype.dump = function() {
    var block, i, len, ref, s;
    s = ["Form"];
    ref = this.__blocks;
    for (i = 0, len = ref.length; i < len; i++) {
      block = ref[i];
      block.dump(s, "  ");
    }
    return s.join("\n");
  };

  XMLFormForm.prototype.render = function(__container) {
    var block, blockContent, blockElement, i, injectedBlocks, len;
    this.__container = __container;
    injectedBlocks = this.__injectedBlocks || [];
    CUI.dom.empty(this.__container);
    for (i = 0, len = injectedBlocks.length; i < len; i++) {
      block = injectedBlocks[i];
      blockElement = new CUI.Block({
        "class": "ez5-metadata-mapping-settings",
        content: block.content
      });
      CUI.dom.append(this.__container, blockElement);
    }
    blockContent = this.getBlocks().map((function(_this) {
      return function(block) {
        return block.content;
      };
    })(this));
    blockElement = new CUI.Block({
      content: new CUI.VerticalList({
        content: blockContent
      }),
      padded: false
    });
    CUI.dom.append(this.__container, blockElement);
  };

  XMLFormForm.prototype.getBlocks = function() {
    var i, len, ref, results, t;
    ref = this.__blocks;
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      t = ref[i];
      results.push(t.getBlock());
    }
    return results;
  };

  XMLFormForm.prototype.update = function(triggerUpdate) {
    var i, len, ref, t;
    if (triggerUpdate == null) {
      triggerUpdate = true;
    }
    ref = this.__blocks;
    for (i = 0, len = ref.length; i < len; i++) {
      t = ref[i];
      t.update();
    }
    if (this.__container && triggerUpdate) {
      CUI.Events.trigger({
        node: this.__container,
        type: 'data-changed'
      });
    }
  };

  XMLFormForm.prototype.removeDragWrapper = function(dragWrapper, update) {
    if (update == null) {
      update = true;
    }
    CUI.util.removeFromArray(dragWrapper, dragWrapper.isLinked.dragWrappers);
    if (update) {
      return this.update();
    }
  };

  XMLFormForm.prototype.addDragWrapper = function(dragWrapper, fieldKey, update) {
    if (update == null) {
      update = true;
    }
    CUI.util.assert(dragWrapper instanceof XMLFormFieldDragWrapper, "XMLFormForm.addDragWrapper", "dragWrapper must be instance of XMLFormFieldDragWrapper", {
      dragWrapper: dragWrapper
    });
    if (!(fieldKey && this.data[fieldKey])) {
      return false;
    }
    if (dragWrapper.isLinked) {
      this.removeDragWrapper(dragWrapper, false);
    }
    this.data[fieldKey].dragWrappers.push(dragWrapper);
    dragWrapper.isLinked = this.data[fieldKey];
    if (update) {
      this.update();
    }
    return true;
  };

  XMLFormForm.prototype.removeDragWrappersNotOfObjecttype = function(objecttypeName) {
    var _, dragWrapper, dragWrappersToRemove, i, len, ref, value;
    ref = this.data;
    for (_ in ref) {
      value = ref[_];
      dragWrappersToRemove = value.dragWrappers.filter(function(dragWrapper) {
        if (!(dragWrapper instanceof XMLFormFieldDragWrapperField)) {
          return false;
        }
        return dragWrapper.getObjecttype() !== objecttypeName;
      });
      for (i = 0, len = dragWrappersToRemove.length; i < len; i++) {
        dragWrapper = dragWrappersToRemove[i];
        this.removeDragWrapper(dragWrapper, false);
      }
    }
  };

  XMLFormForm.prototype.getBaseKey = function() {
    return this.opts.profile.xml_base || "/";
  };

  XMLFormForm.prototype.getSaveData = function(save_data) {
    var i, len, ref, ref1, t;
    save_data.fields = [];
    ref = this.__blocks;
    for (i = 0, len = ref.length; i < len; i++) {
      t = ref[i];
      if (t !== this.__customBlock) {
        t.getSaveData(save_data);
      }
    }
    if ((ref1 = this.__customBlock) != null) {
      ref1.getSaveData(save_data);
    }
    return save_data;
  };

  XMLFormForm.prototype.__addBlock = function(blockConfig) {
    var block;
    block = new XMLFormBlock({
      form: this,
      block: blockConfig
    }, this.data);
    if (blockConfig.custom) {
      this.__customBlock = block;
      this.__blocks.unshift(block);
    } else {
      this.__blocks.push(block);
    }
    return block;
  };

  XMLFormForm.prototype.isCustomFieldsEnabled = function() {
    return !!this.__customBlock;
  };

  return XMLFormForm;

})();
// Generated by CoffeeScript 1.12.7
var XMLFormGrid;

XMLFormGrid = (function() {
  function XMLFormGrid(opts, data) {
    this.opts = opts;
    this.data = data;
    this.grid = [];
    this.max = {
      x: -1,
      y: -1
    };
    this.__fields = this.opts.fields;
    this.generateGrid();
  }

  XMLFormGrid.prototype.generateGrid = function() {
    var f_def, i, idx, len, ref, results;
    this.formFields = [];
    ref = this.__fields;
    results = [];
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      f_def = ref[idx];
      results.push(this.__addField(f_def, idx));
    }
    return results;
  };

  XMLFormGrid.prototype.addCustomField = function(fieldOutputDef, fieldInputDef) {
    this.max.y++;
    fieldOutputDef.x = 0;
    fieldOutputDef.y = this.max.y;
    fieldInputDef.x = 1;
    fieldInputDef.y = this.max.y;
    this.__fields.push(fieldOutputDef);
    this.__addField(fieldOutputDef, this.__fields.length - 1);
    this.__renderField(fieldOutputDef.x, fieldOutputDef.y);
    this.__fields.push(fieldInputDef);
    this.__addField(fieldInputDef, this.__fields.length - 1);
    this.__renderField(fieldInputDef.x, fieldInputDef.y);
    this.update();
  };

  XMLFormGrid.prototype.getField = function(pos) {
    var inputField, outputField;
    if (pos.x === 0) {
      outputField = this.grid[pos.x][pos.y];
      inputField = this.grid[pos.x + 1][pos.y];
    } else {
      outputField = this.grid[pos.x - 1][pos.y];
      inputField = this.grid[pos.x][pos.y];
    }
    return [outputField, inputField];
  };

  XMLFormGrid.prototype.findFieldById = function(fieldId) {
    var i, inputField, outputField, ref, ref1, ref2, y;
    for (y = i = 0, ref = this.max.y; 0 <= ref ? i <= ref : i >= ref; y = 0 <= ref ? ++i : --i) {
      outputField = (ref1 = this.grid[0]) != null ? ref1[y] : void 0;
      inputField = (ref2 = this.grid[1]) != null ? ref2[y] : void 0;
      if ((outputField != null ? outputField.getID() : void 0) === fieldId || (inputField != null ? inputField.getID() : void 0) === fieldId) {
        return [outputField, inputField];
      }
    }
    return null;
  };

  XMLFormGrid.prototype.removeCustomField = function(fieldOutput, fieldInput) {
    var field, i, index, j, k, len, newKey, previousKey, ref, ref1, ref2, ref3, row, x, y;
    row = fieldOutput.getRow();
    this.__removeField(fieldOutput.getPos());
    this.__removeField(fieldInput.getPos());
    CUI.dom.remove(row);
    this.max.y--;
    for (y = i = 0, ref = this.max.y; i <= ref; y = i += 1) {
      for (x = j = 0, ref1 = this.max.x; j <= ref1; x = j += 1) {
        if ((ref2 = this.grid[x][y]) != null) {
          ref2.setPos(x, y);
        }
      }
    }
    ref3 = this.formFields;
    for (index = k = 0, len = ref3.length; k < len; index = ++k) {
      field = ref3[index];
      previousKey = field.getID();
      field.setIdx(index);
      newKey = field.getID();
      if (this.data[previousKey] && previousKey !== newKey) {
        this.data[newKey] = this.data[previousKey];
        delete this.data[previousKey];
      }
    }
  };

  XMLFormGrid.prototype.__removeField = function(pos) {
    var dragWrapper, field, i, key, len, ref;
    field = this.grid[pos.x][pos.y];
    CUI.util.removeFromArray(field, this.formFields);
    CUI.util.removeFromArray(field.getDef(), this.__fields);
    key = field.getID();
    if (this.data[key]) {
      ref = this.data[key].dragWrappers;
      for (i = 0, len = ref.length; i < len; i++) {
        dragWrapper = ref[i];
        dragWrapper.destroy();
      }
      this.data[key].dragWrappers.length = 0;
      this.data[key].formFields.length = 0;
      delete this.data[key];
    }
    field.destroy();
    this.grid[pos.x].splice(pos.y, 1);
  };

  XMLFormGrid.prototype.__addField = function(f_def, idx) {
    var classname, ef, f, i, key, pos, ref, ref1, results, x, y;
    if (!f_def.type) {
      console.error("XMLFormGrid.generateGrid: Definition has not 'type' attribute, skipping.", {
        definition: f_def
      });
      return;
    }
    classname = "XMLFormField" + (CUI.util.toCamel(f_def.type, true));
    CUI.util.assert(window[classname] instanceof Function, "XMLFormWrapper.showForm", classname + " not found", {
      definition: f_def,
      classname: classname
    });
    f_def.form = this;
    f = new window[classname]({
      def: f_def,
      idx: idx,
      grid: this
    }, this.data);
    this.formFields[idx] = f;
    key = f.getDataKey();
    if (f.getSaveData) {
      if (!this.data[key]) {
        this.data[key] = {
          formFields: [],
          key: key,
          dragWrappers: []
        };
      }
      this.data[key].formFields.push(f);
    }
    pos = f.getPos();
    if (!pos) {
      return;
    }
    results = [];
    for (y = i = ref = pos.y, ref1 = pos.rowspan + pos.y; i < ref1; y = i += 1) {
      results.push((function() {
        var j, ref2, ref3, results1;
        results1 = [];
        for (x = j = ref2 = pos.x, ref3 = pos.colspan + pos.x; j < ref3; x = j += 1) {
          if (pos.x === x && pos.y === y) {
            results1.push(this.setCell(pos.x, pos.y, f));
          } else {
            ef = new XMLFormFieldSkip({
              def: {
                x: x,
                y: y
              },
              idx: this,
              grid: this,
              father_field: f
            });
            results1.push(this.setCell(x, y, ef));
          }
        }
        return results1;
      }).call(this));
    }
    return results;
  };

  XMLFormGrid.prototype.dump = function(s, spc) {
    var ff, i, len, ref;
    ref = this.formFields;
    for (i = 0, len = ref.length; i < len; i++) {
      ff = ref[i];
      ff.dump(s, spc + "  ");
    }
    return s;
  };

  XMLFormGrid.prototype.setCell = function(x, y, f) {
    if (!this.grid[x]) {
      this.grid[x] = [];
    }
    CUI.util.assert(!this.grid[x][y], "XMLFormWrapper.showForm", "Position " + x + "/" + y + " is already taken", {
      existingField: this.grid[x][y],
      offendingField: f,
      blocks: this.blocks
    });
    this.grid[x][y] = f;
    if (x > this.max.x) {
      this.max.x = x;
    }
    if (y > this.max.y) {
      this.max.y = y;
    }
  };

  XMLFormGrid.prototype.render = function() {
    var i, j, ref, ref1, x, y;
    this.__table = CUI.dom.$element("table", "xml-form-wrapper-main");
    for (y = i = 0, ref = this.max.y; 0 <= ref ? i <= ref : i >= ref; y = 0 <= ref ? ++i : --i) {
      for (x = j = 0, ref1 = this.max.x; 0 <= ref1 ? j <= ref1 : j >= ref1; x = 0 <= ref1 ? ++j : --j) {
        this.__renderField(x, y);
      }
    }
    delete this.__tr;
    return this.__table;
  };

  XMLFormGrid.prototype.__renderField = function(x, y) {
    var f, ref;
    if (x === 0) {
      this.__tr = CUI.dom.$element("tr");
      CUI.dom.append(this.__table, this.__tr);
    }
    f = (ref = this.grid[x]) != null ? ref[y] : void 0;
    if (!f) {
      CUI.dom.append(this.__tr, CUI.dom.$element("td"));
    } else {
      CUI.dom.append(this.__tr, f.renderTd());
    }
  };

  XMLFormGrid.prototype.update = function() {
    var i, j, ref, ref1, ref2, ref3, x, y;
    for (y = i = 0, ref = this.max.y; 0 <= ref ? i <= ref : i >= ref; y = 0 <= ref ? ++i : --i) {
      for (x = j = 0, ref1 = this.max.x; 0 <= ref1 ? j <= ref1 : j >= ref1; x = 0 <= ref1 ? ++j : --j) {
        if ((ref2 = this.grid[x]) != null) {
          if ((ref3 = ref2[y]) != null) {
            ref3.update();
          }
        }
      }
    }
    return this;
  };

  XMLFormGrid.prototype.getID = function() {
    if (!this.opts.father_field) {
      return this.opts.block.getID();
    } else {
      return this.opts.father_field.getID();
    }
  };

  XMLFormGrid.prototype.getForm = function() {
    if (this.opts.father_field) {
      return this.opts.father_field.getForm();
    } else {
      return this.opts.block.getForm();
    }
  };

  XMLFormGrid.prototype.getBlock = function() {
    if (this.opts.father_field) {
      return this.opts.father_field.getBlock();
    } else {
      return this.opts.block;
    }
  };

  XMLFormGrid.prototype.getKey = function() {
    if (this.opts.father_field) {
      return this.opts.father_field.getKey();
    } else {
      return this.getBlock().getBaseKey();
    }
  };

  XMLFormGrid.prototype.getSaveData = function(save_data) {
    var ff, i, len, ref;
    ref = this.formFields;
    for (i = 0, len = ref.length; i < len; i++) {
      ff = ref[i];
      if (typeof ff.getSaveData === "function") {
        ff.getSaveData(save_data);
      }
    }
    return save_data;
  };

  return XMLFormGrid;

})();
// Generated by CoffeeScript 1.12.7
var XMLFormBlock;

XMLFormBlock = (function() {
  function XMLFormBlock(opts, data) {
    var ref;
    this.opts = opts != null ? opts : {};
    this.data = data;
    CUI.util.assert(CUI.util.isArray((ref = this.opts.block) != null ? ref.fields : void 0), 'new XMLFormBlock', 'block.fields must be an Array', {
      block: this.block
    });
    this.grid = new XMLFormGrid({
      block: this,
      fields: this.opts.block.fields
    }, this.data);
  }

  XMLFormBlock.prototype.addCustomField = function(fieldOutputDef, fieldInputDef) {
    return this.grid.addCustomField(fieldOutputDef, fieldInputDef);
  };

  XMLFormBlock.prototype.getField = function(pos) {
    return this.grid.getField(pos);
  };

  XMLFormBlock.prototype.removeCustomField = function(outputField, inputField) {
    this.grid.removeCustomField(outputField, inputField);
  };

  XMLFormBlock.prototype.dump = function(s, spc) {
    s.push(spc + this.getName());
    this.grid.dump(s, spc + '  ');
    return s;
  };

  XMLFormBlock.prototype.getForm = function() {
    return this.opts.form;
  };

  XMLFormBlock.prototype.getBlock = function() {
    var ref;
    return {
      name: this.getName(),
      text: ((ref = this.opts.block.text) != null ? ref[ez5.loca.culture] : void 0) || this.getName(),
      content: (function(_this) {
        return function() {
          var d;
          d = CUI.dom.div('ez5-xml-form-tab-tab');
          CUI.dom.append(d, _this.grid.render());
          return d;
        };
      })(this)
    };
  };

  XMLFormBlock.prototype.getName = function() {
    return this.opts.block.tab || '<no name>';
  };

  XMLFormBlock.prototype.getID = function() {
    return this.opts.block.tab || '<no id>';
  };

  XMLFormBlock.prototype.getBaseKey = function() {
    return this.opts.form.getBaseKey();
  };

  XMLFormBlock.prototype.update = function() {
    return this.grid.update();
  };

  XMLFormBlock.prototype.getSaveData = function(save_data) {
    return this.grid.getSaveData(save_data);
  };

  return XMLFormBlock;

})();
// Generated by CoffeeScript 1.12.7
var XMLFormWrapper,
  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;

XMLFormWrapper = (function(superClass) {
  extend(XMLFormWrapper, superClass);

  function XMLFormWrapper() {
    return XMLFormWrapper.__super__.constructor.apply(this, arguments);
  }

  XMLFormWrapper.prototype.initOpts = function() {
    XMLFormWrapper.__super__.initOpts.call(this);
    return this.addOpts({
      pane: {
        mandatory: true,
        check: CUI.BorderLayout
      },
      blocks: {
        mandatory: true,
        check: Array
      },
      mapping: {
        mandatory: true,
        check: "PlainObject"
      },
      profile: {
        mandatory: true,
        check: String
      }
    });
  };

  XMLFormWrapper.prototype.readOpts = function() {
    var fields_pane, mapping_pane;
    XMLFormWrapper.__super__.readOpts.call(this);
    this.pane = this._pane;
    this.__blocks = this._blocks;
    this.loaders = [new XMLFormFieldDragWrapperFieldLoader(), new XMLFormFieldDragWrapperFixedValueLoader()];
    if (ez5.version("6")) {
      this.loaders.push(new XMLFormFieldDragDeepLinkLoader());
    }
    this.data = {};
    fields_pane = new CUI.SimplePane({
      "class": "cui-pane--window",
      title: $$("xml.form.wrapper.pane.fields")
    });
    mapping_pane = new CUI.SimplePane({
      "class": "cui-pane--window",
      title: $$("xml.form.wrapper.pane.mapping"),
      content: (function(_this) {
        return function() {
          var vl;
          vl = new CUI.VerticalLayout({
            top: {
              content: function() {
                return new CUI.Toolbar({
                  center: {
                    content: function() {
                      var data, input, triggerEventSearch;
                      data = {};
                      triggerEventSearch = function() {
                        return CUI.Events.trigger({
                          node: mapping_pane,
                          type: "xml-mapping-search",
                          info: data
                        });
                      };
                      input = new CUI.Input({
                        data: data,
                        "class": "ez5-quicksearch-input ez5-quicksearch-input--size-normal",
                        name: "search",
                        placeholder: $$("admin.metadata.form.mapping.search.placeholder"),
                        onDataChanged: function() {
                          return CUI.scheduleCallback({
                            ms: 150,
                            call: triggerEventSearch
                          });
                        }
                      });
                      return input.start();
                    }
                  }
                });
              }
            }
          });
          _this.content = vl.center();
          return vl;
        };
      })(this)
    });
    this.pane.replace(fields_pane, "east");
    this.pane.replace(mapping_pane, "center");
    this.fields = fields_pane.center();
    new CUI.Droppable({
      element: this.content,
      drop: (function(_this) {
        return function(ev, info) {
          return _this.form.removeDragWrapper(info.globalDrag.dragWrapper);
        };
      })(this),
      accept: (function(_this) {
        return function(ev, info) {
          var ref;
          if ((ref = info.globalDrag.dragWrapper) != null ? ref.isLinked : void 0) {
            return true;
          } else {
            return false;
          }
        };
      })(this)
    });
  };

  XMLFormWrapper.prototype.init = function() {
    var dfr;
    dfr = new CUI.Deferred();
    ez5.api.xmlmapping({
      api: "/profile/" + this._profile,
      dataType: "json"
    }).fail(dfr.reject).done((function(_this) {
      return function(profile_data) {
        var ref, ref1, ref2;
        _this.profile_data = profile_data;
        _this.__required_field_type = {};
        if ((ref = _this.profile_data.profile_type) != null ? ref.exiftool_import : void 0) {
          _this.__required_field_type["import"] = true;
        }
        if ((ref1 = _this.profile_data.profile_type) != null ? ref1.exiftool_export : void 0) {
          _this.__required_field_type["export"] = true;
        }
        if ((ref2 = _this.profile_data.profile_type) != null ? ref2.xml_export : void 0) {
          _this.__required_field_type["export"] = true;
        }
        return _this.__showFields().fail(dfr.reject).done(function() {
          _this.showForm();
          return dfr.resolve();
        });
      };
    })(this));
    return dfr.promise();
  };

  XMLFormWrapper.prototype.__loadFieldsData = function(fields) {
    var field, i, len;
    if (!fields) {
      return;
    }
    for (i = 0, len = fields.length; i < len; i++) {
      field = fields[i];
      this.__loadFieldData(field);
    }
  };

  XMLFormWrapper.prototype.__loadFieldData = function(field) {
    var i, instance, j, key, len, len1, loader, ref, ref1, ref2, save_data;
    CUI.util.assert(!field.easydb || CUI.util.isArray(field.easydb), "XMLFormWrapper.__loadFieldsData", "Cannot load old style easydb String value", {
      field: field
    });
    if (((ref = field.easydb) != null ? ref.length : void 0) > 0) {
      ref1 = field.easydb;
      for (i = 0, len = ref1.length; i < len; i++) {
        save_data = ref1[i];
        ref2 = this.loaders;
        for (j = 0, len1 = ref2.length; j < len1; j++) {
          loader = ref2[j];
          instance = loader.getInstanceFromSaveData(this, save_data);
          if (instance) {
            if (ez5.version("6.14") && !field._id && field.name) {
              key = field.name;
            } else {
              key = field._id;
            }
            this.form.addDragWrapper(instance, key, false);
            break;
          }
        }
      }
    }
    if (field.fields) {
      this.__loadFieldsData(field.fields);
    }
  };

  XMLFormWrapper.prototype.getSaveData = function(save_data) {
    if (save_data == null) {
      save_data = {};
    }
    if (!(this.form && this.profile_data)) {
      return;
    }
    save_data.xml_base = this.profile_data.xml_base;
    return this.form.getSaveData(save_data);
  };

  XMLFormWrapper.prototype.registerWrapperField = function(wrapperField) {
    var key;
    key = wrapperField.opts.treeNode.fullFieldName();
    CUI.util.assert(!this.wrapperFields[key], "XMLFormWrapper.registerWrapperField", "Cannot register " + (CUI.util.getObjectClass(wrapperField)) + "." + key + " more than once", {
      key: key,
      wrapperField: wrapperField,
      wrapperTreeNodes: this.wrapperFields
    });
    return this.wrapperFields[key] = wrapperField;
  };

  XMLFormWrapper.prototype.refreshFields = function() {
    return this.__showFields().done((function(_this) {
      return function() {
        _this.form.update(false);
        return CUI.Events.trigger({
          node: _this.content,
          type: 'data-changed'
        });
      };
    })(this));
  };

  XMLFormWrapper.prototype.__showFields = function() {
    var _, _ot, addMasksToObjectTypeManager, form, i, j, len, len1, onlyObjectsWithEAS, ot, otm, profileType, profilesTypes, ref, ref1, ref2, ref3, value, wrapperField;
    if (this.wrapperFields) {
      ref = this.wrapperFields;
      for (wrapperField = i = 0, len = ref.length; i < len; wrapperField = ++i) {
        _ = ref[wrapperField];
        wrapperField.destroy();
      }
    }
    this.wrapperFields = {};
    otm = new ObjecttypeManager();
    onlyObjectsWithEAS = false;
    profilesTypes = [];
    ref1 = this.profile_data;
    for (profileType in ref1) {
      value = ref1[profileType];
      if (value) {
        profilesTypes.push(profileType);
      }
    }
    if (((ref2 = this.profile_data.profile_type) != null ? ref2.exiftool_export : void 0) && profilesTypes.length === 1) {
      onlyObjectsWithEAS = true;
    }
    addMasksToObjectTypeManager = (function(_this) {
      return function(idTable) {
        var j, len1, m, ref3, results;
        ref3 = ez5.mask.CURRENT._masks_by_table_id[idTable];
        results = [];
        for (j = 0, len1 = ref3.length; j < len1; j++) {
          m = ref3[j];
          if (ez5.version("6.12") && onlyObjectsWithEAS) {
            if (ez5.mask.CURRENT._mask_instance_by_name[m.name].getEASFields("all").length === 0) {
              continue;
            }
          }
          results.push(otm.addMask(ez5.mask.CURRENT._mask_instance_by_name[m.name]));
        }
        return results;
      };
    })(this);
    if (this._mapping.idTable) {
      addMasksToObjectTypeManager(this._mapping.idTable);
    } else {
      ref3 = ez5.schema.CURRENT._objecttypes;
      for (j = 0, len1 = ref3.length; j < len1; j++) {
        ot = ref3[j];
        _ot = new Objecttype(new Table("CURRENT", ot.table_id));
        if (!_ot.inMainSearch() && !ez5.version("6.12")) {
          continue;
        }
        addMasksToObjectTypeManager(ot.table_id);
      }
    }
    otm.initCommonFields("all", true, (function(_this) {
      return function(f) {
        return f.isSourceForMapping(_this.__required_field_type);
      };
    })(this));
    this.fields.empty();
    this.fields.append(new CUI.Label({
      text: $$("admin.metadata.form.mapping.field.tags.hint"),
      multiline: true,
      appearance: "secondary"
    }));
    if (!this.__required_field_type["import"]) {
      this.fields.append(new XMLFormFieldDragWrapperFixedValue({
        formWrapper: this
      }).renderAsSource());
      if (ez5.version("6")) {
        this.fields.append(new XMLFormFieldDragDeepLink({
          formWrapper: this
        }).renderAsSource());
      }
    }
    form = new FieldsForm({
      otm: otm,
      data: {},
      acceptField: (function(_this) {
        return function(field) {
          return field.isSourceForMapping(_this.__required_field_type);
        };
      })(this),
      treeOpts: {
        cols: ["auto", "maximize"],
        maximize: true,
        rowMove: false
      },
      treeNodeClass: XMLFormWrapperTreeNode,
      formWrapper: this
    });
    this.fields.append(form.renderForm());
    return form.open();
  };

  XMLFormWrapper.prototype.usedForExport = function() {
    if (this.__required_field_type["export"]) {
      return true;
    } else {
      return false;
    }
  };

  XMLFormWrapper.prototype.usedForImport = function() {
    if (this.__required_field_type["import"]) {
      return true;
    } else {
      return false;
    }
  };

  XMLFormWrapper.prototype.dump = function() {
    if (this.form) {
      return console.debug(this.form.dump());
    }
  };

  XMLFormWrapper.prototype.showForm = function() {
    this.form = new XMLFormForm({
      profile: this.profile_data,
      wrapper: this,
      blocks: this.__blocks
    }, this.data);
    this.form.render(this.content);
    this.form.loadCustomFields(this._mapping.fields);
    if (this.isCustomFieldsEnabled()) {
      this.__loadFieldsData(this._mapping.fields);
    }
    return this.form.update(false);
  };

  XMLFormWrapper.prototype.destroy = function() {
    delete this.pane;
    delete this.form;
    return XMLFormWrapper.__super__.destroy.call(this);
  };

  XMLFormWrapper.getOutputSpan = function(key) {
    var span;
    span = CUI.dom.span("xml-form-field-key");
    if (key) {
      CUI.dom.setAttributeMap(span, {
        title: key
      });
      span.textContent = key.replace(/\[.*?\]/g, "");
    }
    return span;
  };

  XMLFormWrapper.prototype.addCustomField = function(fieldDef) {
    this.form.addCustomField(fieldDef);
    CUI.Events.trigger({
      node: this.content,
      type: 'data-changed'
    });
  };

  XMLFormWrapper.prototype.updateField = function(field, newDef) {
    this.form.updateField(field, newDef);
    CUI.Events.trigger({
      node: this.content,
      type: 'data-changed'
    });
  };

  XMLFormWrapper.prototype.removeCustomField = function(outputField, inputField) {
    this.form.removeCustomField(outputField, inputField);
    CUI.Events.trigger({
      node: this.content,
      type: 'data-changed'
    });
  };

  XMLFormWrapper.prototype.isCustomFieldsEnabled = function() {
    return this.form.isCustomFieldsEnabled();
  };

  XMLFormWrapper.prototype.getField = function(pos, indexBlock) {
    return this.form.getField(pos, indexBlock);
  };

  XMLFormWrapper.prototype.getForm = function() {
    return this.form;
  };

  return XMLFormWrapper;

})(CUI.Element);

CUI.ready(function() {
  return CUI.Events.registerEvent({
    type: "xml-mapping-search",
    sink: true
  });
});
// Generated by CoffeeScript 1.12.7
var XMLFormWrapperCondition, XMLFormWrapperConditionItem,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

XMLFormWrapperCondition = (function() {
  function XMLFormWrapperCondition() {
    this.getSaveData = bind(this.getSaveData, this);
    this.addConditionItem = bind(this.addConditionItem, this);
    this.removeConditionItem = bind(this.removeConditionItem, this);
    this.renderDropArea = bind(this.renderDropArea, this);
    this.getType = bind(this.getType, this);
    this.type = null;
    this.list = [];
  }

  XMLFormWrapperCondition.prototype.getType = function() {
    return this.type;
  };

  XMLFormWrapperCondition.prototype.loadCondition = function(dragWrapperTarget, condition) {
    var data, dragWrapper, dw, j, len, ref, ref1, save_data;
    console.debug("XMLFormWrapperCondition loading", condition);
    this.type = condition.type;
    if (!((ref = condition.list) != null ? ref.length : void 0)) {
      return this;
    }
    ref1 = condition.list;
    for (j = 0, len = ref1.length; j < len; j++) {
      save_data = ref1[j];
      dragWrapper = dragWrapperTarget.opts.formWrapper.wrapperFields[save_data.field];
      dw = new window[CUI.util.getObjectClass(dragWrapper)](dragWrapper);
      console.debug(save_data, dw);
      data = CUI.util.copyObject(save_data);
      delete data.field;
      this.addConditionItem(new XMLFormWrapperConditionItem({
        condition: this,
        dragWrapper: dw
      }, data));
    }
    console.debug("loading done", this.list);
    return this;
  };

  XMLFormWrapperCondition.prototype.renderDropArea = function() {
    var i, j, len, ref;
    this.dropArea = CUI.dom.div("xml-form-wrapper-condition-drop-area");
    this.dropArea.append(CUI.dom.text(this.type));
    new CUI.Droppable({
      element: this.dropArea,
      drop: (function(_this) {
        return function(ev, info) {
          console.debug("dropped element", ev, info);
          if (info.globalDrag.conditionItem) {
            if (CUI.util.inArray(info.globalDrag.conditionItem, _this.list) > -1) {
              return;
            } else {
              _this.addConditionItem(info.globalDrag.conditionItem.remove());
            }
            return;
          }
          return _this.addConditionItem(new XMLFormWrapperConditionItem({
            dragWrapper: info.globalDrag.dragWrapper
          }));
        };
      })(this),
      accept: (function(_this) {
        return function(ev, info) {
          if (info.globalDrag.dragWrapper instanceof XMLFormFieldDragWrapperField) {
            return true;
          } else if (info.globalDrag.conditionItem) {
            return true;
          } else {
            return false;
          }
        };
      })(this)
    });
    ref = this.list;
    for (j = 0, len = ref.length; j < len; j++) {
      i = ref[j];
      this.dropArea.append(i.render());
    }
    return this.dropArea;
  };

  XMLFormWrapperCondition.prototype.removeConditionItem = function(conditionItem) {
    var c;
    c = CUI.util.removeFromArray(conditionItem, this.list);
    CUI.util.assert(c === 0, (CUI.util.getObjectClass(this)) + ".removeConditionItem", "conditionItem not found in list", {
      list: this.list,
      conditionItem: conditionItem
    });
    return idx;
  };

  XMLFormWrapperCondition.prototype.addConditionItem = function(conditionItem) {
    CUI.util.assert(conditionItem instanceof XMLFormWrapperConditionItem, (CUI.util.getObjectClass(this)) + ".addCondition", "conditionItem needs to be instance of XMLFormWrapperConditionItem", {
      conditionIten: conditionItem
    });
    this.list.push(conditionItem);
    conditionItem.setCondition(this);
    if (this.dropArea) {
      return this.dropArea.append(conditionItem.render());
    }
  };

  XMLFormWrapperCondition.prototype.getSaveData = function() {
    var i, j, len, ref, sdata;
    if (!this.list.length) {
      return;
    }
    sdata = {
      type: this.type,
      list: []
    };
    ref = this.list;
    for (j = 0, len = ref.length; j < len; j++) {
      i = ref[j];
      sdata.list.push(i.getSaveData());
    }
    return sdata;
  };

  return XMLFormWrapperCondition;

})();

XMLFormWrapperConditionItem = (function() {
  function XMLFormWrapperConditionItem(opts, data1) {
    this.opts = opts != null ? opts : {};
    this.data = data1 != null ? data1 : {};
    this.getSaveData = bind(this.getSaveData, this);
    this.remove = bind(this.remove, this);
    this.setCondition = bind(this.setCondition, this);
    console.debug("XMLFormWrapperConditionItem", this.opts);
  }

  XMLFormWrapperConditionItem.prototype.setCondition = function(condition1) {
    this.condition = condition1;
  };

  XMLFormWrapperConditionItem.prototype.render = function() {
    this.t = CUI.dom.table_one_row(this.opts.dragWrapper.renderAsCondition(), new CUI.Select({
      name: "type",
      options: [
        {
          text: "eq_no_case",
          value: "eq_no_case"
        }, {
          text: "eq",
          value: "eq"
        }
      ],
      data: this.data
    }).start(), new CUI.Input({
      name: "value",
      data: this.data
    }).start());
    new CUI.Draggable({
      element: this.t,
      create: (function(_this) {
        return function() {
          return {
            conditionItem: _this
          };
        };
      })(this)
    });
    return this.t;
  };

  XMLFormWrapperConditionItem.prototype.remove = function() {
    this.condition.removeConditionItem(this);
    this.t.remove();
    return this;
  };

  XMLFormWrapperConditionItem.prototype.getSaveData = function() {
    var sdata;
    sdata = {
      field: this.opts.dragWrapper.getID(),
      type: this.data.type,
      value: this.data.value
    };
    return sdata;
  };

  return XMLFormWrapperConditionItem;

})();
// Generated by CoffeeScript 1.12.7
var XMLFormWrapperTreeNode,
  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;

XMLFormWrapperTreeNode = (function(superClass) {
  extend(XMLFormWrapperTreeNode, superClass);

  function XMLFormWrapperTreeNode() {
    return XMLFormWrapperTreeNode.__super__.constructor.apply(this, arguments);
  }

  XMLFormWrapperTreeNode.prototype.nodeAdded = function(level) {
    if (level == null) {
      level = 0;
    }
    XMLFormWrapperTreeNode.__super__.nodeAdded.call(this, level);
    if (this.field instanceof NestedTable || this.field instanceof LinkedObject || this.field instanceof PoolField) {
      return;
    }
    if (!ez5.version("6") && this.field instanceof CustomDataType) {
      return;
    }
    this.dragWrapperField = new XMLFormFieldDragWrapperField({
      formWrapper: this._formWrapper,
      treeNode: this,
      field: this.field
    });
    this._formWrapper.registerWrapperField(this.dragWrapperField);
  };

  XMLFormWrapperTreeNode.prototype.getModeForNested = function() {
    return "all";
  };

  XMLFormWrapperTreeNode.prototype.renderContent = function() {
    var source_div;
    if (this.dragWrapperField) {
      source_div = this.dragWrapperField.renderAsSource();
      this.addColumn(new CUI.ListViewColumn({
        element: source_div
      }));
    }
    return new CUI.Label({
      text: this.field.nameLocalized(),
      multiline: true,
      tooltip: {
        text: this.fullFieldName() + " [" + CUI.util.getObjectClass(this.field) + "]"
      }
    });
  };

  XMLFormWrapperTreeNode.prototype.isSelectable = function() {
    return false;
  };

  XMLFormWrapperTreeNode.prototype.getFieldNamePath = function() {
    if (this.father && this.father.getFieldNamePath) {
      return this.father.getFieldNamePath().concat([this.field.nameLocalized()]);
    }
    return [this.field.fullNameLocalized(!this.field.isTopLevelField(), true)];
  };

  XMLFormWrapperTreeNode.prototype.getObjecttype = function() {
    if (this.father && this.father.getObjecttype) {
      return this.father.getObjecttype();
    }
    if (this.field instanceof NestedTable) {
      return this.field.fatherMask.table.name();
    }
    return this.field.table.name();
  };

  XMLFormWrapperTreeNode.prototype.getFormWrapper = function() {
    return this._formWrapper;
  };

  XMLFormWrapperTreeNode.prototype.getProfileType = function() {
    var ref, ref1;
    return (ref = this.getFormWrapper()) != null ? (ref1 = ref.profile_data) != null ? ref1.profile_type : void 0 : void 0;
  };

  return XMLFormWrapperTreeNode;

})(FieldsFormNode);
// Generated by CoffeeScript 1.12.7
var XMLFormWrapperCondition, XMLFormWrapperConditionItem,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

XMLFormWrapperCondition = (function() {
  function XMLFormWrapperCondition() {
    this.getSaveData = bind(this.getSaveData, this);
    this.addConditionItem = bind(this.addConditionItem, this);
    this.removeConditionItem = bind(this.removeConditionItem, this);
    this.renderDropArea = bind(this.renderDropArea, this);
    this.getType = bind(this.getType, this);
    this.type = null;
    this.list = [];
  }

  XMLFormWrapperCondition.prototype.getType = function() {
    return this.type;
  };

  XMLFormWrapperCondition.prototype.loadCondition = function(dragWrapperTarget, condition) {
    var data, dragWrapper, dw, j, len, ref, ref1, save_data;
    console.debug("XMLFormWrapperCondition loading", condition);
    this.type = condition.type;
    if (!((ref = condition.list) != null ? ref.length : void 0)) {
      return this;
    }
    ref1 = condition.list;
    for (j = 0, len = ref1.length; j < len; j++) {
      save_data = ref1[j];
      dragWrapper = dragWrapperTarget.opts.formWrapper.wrapperFields[save_data.field];
      dw = new window[CUI.util.getObjectClass(dragWrapper)](dragWrapper);
      console.debug(save_data, dw);
      data = CUI.util.copyObject(save_data);
      delete data.field;
      this.addConditionItem(new XMLFormWrapperConditionItem({
        condition: this,
        dragWrapper: dw
      }, data));
    }
    console.debug("loading done", this.list);
    return this;
  };

  XMLFormWrapperCondition.prototype.renderDropArea = function() {
    var i, j, len, ref;
    this.dropArea = CUI.dom.div("xml-form-wrapper-condition-drop-area");
    this.dropArea.append(CUI.dom.text(this.type));
    new CUI.Droppable({
      element: this.dropArea,
      drop: (function(_this) {
        return function(ev, info) {
          console.debug("dropped element", ev, info);
          if (info.globalDrag.conditionItem) {
            if (CUI.util.inArray(info.globalDrag.conditionItem, _this.list) > -1) {
              return;
            } else {
              _this.addConditionItem(info.globalDrag.conditionItem.remove());
            }
            return;
          }
          return _this.addConditionItem(new XMLFormWrapperConditionItem({
            dragWrapper: info.globalDrag.dragWrapper
          }));
        };
      })(this),
      accept: (function(_this) {
        return function(ev, info) {
          if (info.globalDrag.dragWrapper instanceof XMLFormFieldDragWrapperField) {
            return true;
          } else if (info.globalDrag.conditionItem) {
            return true;
          } else {
            return false;
          }
        };
      })(this)
    });
    ref = this.list;
    for (j = 0, len = ref.length; j < len; j++) {
      i = ref[j];
      this.dropArea.append(i.render());
    }
    return this.dropArea;
  };

  XMLFormWrapperCondition.prototype.removeConditionItem = function(conditionItem) {
    var c;
    c = CUI.util.removeFromArray(conditionItem, this.list);
    CUI.util.assert(c === 0, (CUI.util.getObjectClass(this)) + ".removeConditionItem", "conditionItem not found in list", {
      list: this.list,
      conditionItem: conditionItem
    });
    return idx;
  };

  XMLFormWrapperCondition.prototype.addConditionItem = function(conditionItem) {
    CUI.util.assert(conditionItem instanceof XMLFormWrapperConditionItem, (CUI.util.getObjectClass(this)) + ".addCondition", "conditionItem needs to be instance of XMLFormWrapperConditionItem", {
      conditionIten: conditionItem
    });
    this.list.push(conditionItem);
    conditionItem.setCondition(this);
    if (this.dropArea) {
      return this.dropArea.append(conditionItem.render());
    }
  };

  XMLFormWrapperCondition.prototype.getSaveData = function() {
    var i, j, len, ref, sdata;
    if (!this.list.length) {
      return;
    }
    sdata = {
      type: this.type,
      list: []
    };
    ref = this.list;
    for (j = 0, len = ref.length; j < len; j++) {
      i = ref[j];
      sdata.list.push(i.getSaveData());
    }
    return sdata;
  };

  return XMLFormWrapperCondition;

})();

XMLFormWrapperConditionItem = (function() {
  function XMLFormWrapperConditionItem(opts, data1) {
    this.opts = opts != null ? opts : {};
    this.data = data1 != null ? data1 : {};
    this.getSaveData = bind(this.getSaveData, this);
    this.remove = bind(this.remove, this);
    this.setCondition = bind(this.setCondition, this);
    console.debug("XMLFormWrapperConditionItem", this.opts);
  }

  XMLFormWrapperConditionItem.prototype.setCondition = function(condition1) {
    this.condition = condition1;
  };

  XMLFormWrapperConditionItem.prototype.render = function() {
    this.t = CUI.dom.table_one_row(this.opts.dragWrapper.renderAsCondition(), new CUI.Select({
      name: "type",
      options: [
        {
          text: "eq_no_case",
          value: "eq_no_case"
        }, {
          text: "eq",
          value: "eq"
        }
      ],
      data: this.data
    }).start(), new CUI.Input({
      name: "value",
      data: this.data
    }).start());
    new CUI.Draggable({
      element: this.t,
      create: (function(_this) {
        return function() {
          return {
            conditionItem: _this
          };
        };
      })(this)
    });
    return this.t;
  };

  XMLFormWrapperConditionItem.prototype.remove = function() {
    this.condition.removeConditionItem(this);
    this.t.remove();
    return this;
  };

  XMLFormWrapperConditionItem.prototype.getSaveData = function() {
    var sdata;
    sdata = {
      field: this.opts.dragWrapper.getID(),
      type: this.data.type,
      value: this.data.value
    };
    return sdata;
  };

  return XMLFormWrapperConditionItem;

})();
// Generated by CoffeeScript 1.12.7
var MetadataApp,
  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;

MetadataApp = (function(superClass) {
  extend(MetadataApp, superClass);

  function MetadataApp() {
    return MetadataApp.__super__.constructor.apply(this, arguments);
  }

  MetadataApp.label = function() {
    return "admin.menu.metadata.mappings";
  };

  MetadataApp.path = function() {
    return ["metadata"];
  };

  MetadataApp.group = function() {
    return "zzc_administration";
  };

  MetadataApp.submenu = function() {
    return "administration";
  };

  MetadataApp.is_allowed = function() {
    return ez5.session.hasSystemRight("root", "profile");
  };

  MetadataApp.prototype.load = function() {
    var wb;
    MetadataApp.__super__.load.call(this);
    this.__namespaces = [];
    this.__getTagsPromise = MetadataTagSelector.getTags().done((function(_this) {
      return function(_, namespaces) {
        return _this.__namespaces = namespaces;
      };
    })(this));
    this.metadata_menu = {
      items: []
    };
    this.tree = new CUI.ListViewTree({
      cols: ["maximize"],
      selectableRows: true,
      footer_left: [
        {
          ui: "metadata-plus-button",
          icon: "plus",
          group: "plus-minus",
          menu: this.metadata_menu
        }, {
          ui: "metadata-minus-button",
          icon: "minus",
          group: "plus-minus",
          onClick: (function(_this) {
            return function() {
              var ref;
              return (ref = _this.tree.getSelectedNode()) != null ? ref.remove(true) : void 0;
            };
          })(this)
        }
      ],
      footer_right: [
        {
          loca_key: "admin.metadata.menu.button",
          menu: {
            items: [
              {
                loca_key: "admin.metadata.menu.download.button",
                onClick: (function(_this) {
                  return function() {
                    return _this.__download();
                  };
                })(this)
              }, new CUI.FileUploadButton({
                fileUpload: this.__getUploadFileReader(),
                text: $$("admin.metadata.menu.upload.button|text"),
                icon: $$("admin.metadata.menu.upload.button|icon"),
                multiple: false
              })
            ]
          }
        }
      ]
    });
    this.pane = new CUI.BorderLayout({
      west: {
        flexHandle: {
          "class": "ez5-main-left-flex-handle",
          hidden: false,
          state_name: "metadata-list",
          label: {
            text: $$("metadata.app.pane.title"),
            icon: "right",
            tooltip: {
              text: $$("metadata.app.pane.title")
            }
          }
        },
        content: new CUI.SimplePane({
          "class": "cui-pane--window",
          header_left: new CUI.Button({
            text: $$("metadata.app.pane.title"),
            tooltip: {
              text: $$("base.help.flex_handle.close|tooltip")
            },
            ui: "metadata.app.flex_handle_close.button",
            "class": "cui-pane-title-button",
            onClick: (function(_this) {
              return function() {
                return _this.getPaneFlexHandle().close();
              };
            })(this)
          }),
          header_right: new LocaButton({
            loca_key: "base.help.flex_handle.close",
            ui: "metadata.app.flex_handle_close.button",
            icon: "west",
            "class": "cui-pane-close-button",
            onClick: (function(_this) {
              return function() {
                return _this.getPaneFlexHandle().close();
              };
            })(this)
          }),
          content: this.tree.render()
        })
      }
    });
    ez5.rootLayout.replace(this.pane, "center");
    wb = new CUI.WaitBlock({
      element: this.pane
    }).show();
    this.empty();
    return this.loadList().done((function(_this) {
      return function() {
        return wb.destroy();
      };
    })(this));
  };

  MetadataApp.prototype.allow_unload = function() {
    var node;
    node = this.tree.getSelectedNode();
    if (node) {
      return node.check_deselect();
    } else {
      return CUI.resolvedPromise();
    }
  };

  MetadataApp.prototype.unload = function() {
    MetadataApp.__super__.unload.call(this);
    this.pane.destroy();
    return CUI.resolvedPromise();
  };

  MetadataApp.prototype.empty = function() {
    return this.pane.replace(new CUI.SimplePane({
      "class": "cui-pane--window",
      title: $$("xml.form.wrapper.pane.mapping"),
      content: new CUI.EmptyLabel({
        centered: true,
        text: $$("metadata.app.no_profile_selected")
      })
    }), "center");
  };

  MetadataApp.prototype.loadList = function() {
    var dfr;
    this.__list = new MetadataProfileList();
    dfr = new CUI.Deferred();
    this.__list.load().done((function(_this) {
      return function() {
        var i, len, p, prof, ref;
        _this.metadata_menu.items.splice(0);
        _this.tree.root.removeFromDOM(false);
        _this.tree.root.children = [];
        ref = _this.__list.getProfiles();
        for (i = 0, len = ref.length; i < len; i++) {
          p = ref[i];
          prof = new MetadataProfile({
            profile: p,
            metadata: _this
          });
          _this.metadata_menu.items.push(prof.getMenuItem());
          _this.tree.root.addChild(prof);
        }
        return _this.tree.root.open().done(dfr.resolve).fail(dfr.reject);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  MetadataApp.prototype.__download = function() {
    var showSplash;
    showSplash = (function(_this) {
      return function() {
        return ez5.splash.show("admin.metadata.menu.download.splash");
      };
    })(this);
    CUI.scheduleCallback({
      call: showSplash,
      ms: 1000
    });
    return this.__list.load().done((function(_this) {
      return function() {
        var i, j, len, len1, mapping, mappingPromises, mappings, profile, promise, ref, ref1;
        mappingPromises = [];
        mappings = [];
        ref = _this.__list.getProfiles();
        for (i = 0, len = ref.length; i < len; i++) {
          profile = ref[i];
          ref1 = profile.mappings;
          for (j = 0, len1 = ref1.length; j < len1; j++) {
            mapping = ref1[j];
            promise = ez5.api.xmlmapping({
              api: "/mapping/" + mapping.id,
              handle_error: function() {
                CUI.scheduleCallbackCancel({
                  call: showSplash
                });
                return false;
              }
            }).done(function(mapping) {
              return mappings.push(mapping);
            });
            mappingPromises.push(promise);
          }
        }
        return CUI.whenAll(mappingPromises).done(function() {
          if (mappings.length > 0) {
            return CUI.FileReader.save(ez5.session.getEasydbName() + "_MetadataMappings_" + CUI.util.moment().format('YYYY-MM-DD') + ".json", JSON.stringify({
              mappings: mappings
            }, null, "   "));
          }
        }).always(function() {
          CUI.scheduleCallbackCancel({
            call: showSplash
          });
          return ez5.splash.hide();
        });
      };
    })(this));
  };

  MetadataApp.prototype.__getUploadFileReader = function() {
    return new CUI.FileReader({
      onDone: (function(_this) {
        return function(fileReader) {
          var data, mappings;
          try {
            data = JSON.parse(fileReader.getResult());
          } catch (error) {
            CUI.problem({
              text: $$("admin.metadata.menu.upload.format-error")
            });
            return;
          }
          mappings = data.mappings;
          if (CUI.util.isEmpty(mappings)) {
            CUI.problem({
              text: $$("admin.metadata.menu.upload.no-mappings-found")
            });
            return;
          }
          return _this.__showUploadConfirmation(mappings);
        };
      })(this)
    });
  };

  MetadataApp.prototype.__showUploadConfirmation = function(mappings) {
    var checkboxData, confirmationDialog, done, upload;
    checkboxData = {};
    done = (function(_this) {
      return function() {
        ez5.splash.done("admin.metadata.menu.upload.splash.done");
        _this.empty();
        return _this.loadList();
      };
    })(this);
    upload = (function(_this) {
      return function(replace) {
        var mappingPromises;
        ez5.splash.show("admin.metadata.menu.upload.splash");
        mappingPromises = [];
        return CUI.chunkWork.call(_this, {
          items: mappings,
          chunk_size: 1,
          call: function(items, index) {
            var mapping;
            if (!checkboxData[index]) {
              return CUI.resolvedPromise();
            }
            mapping = items[0];
            delete mapping.id;
            return ez5.api.xmlmapping({
              type: "PUT",
              api: '/mapping',
              json_data: mapping
            });
          }
        }).done(function() {
          var i, j, len, len1, mapping, profile, promise, ref, ref1, removePromises;
          if (!replace) {
            done();
            return;
          }
          removePromises = [];
          ref = _this.__list.getProfiles();
          for (i = 0, len = ref.length; i < len; i++) {
            profile = ref[i];
            ref1 = profile.mappings;
            for (j = 0, len1 = ref1.length; j < len1; j++) {
              mapping = ref1[j];
              promise = ez5.api.xmlmapping({
                type: "DELETE",
                api: "/mapping/" + mapping.id
              });
              removePromises.push(promise);
            }
          }
          return CUI.whenAll(removePromises).done(done).fail(function() {
            return ez5.splash.hide();
          });
        }).fail(function() {
          return ez5.splash.hide();
        });
      };
    })(this);
    confirmationDialog = new CUI.ConfirmationDialog({
      title: $$("admin.metadata.menu.upload.confirmation.title"),
      content: (function(_this) {
        return function() {
          var checkbox, checkboxes, form, index, label, mapping;
          checkboxes = [];
          for (index in mappings) {
            mapping = mappings[index];
            checkbox = new CUI.Checkbox({
              name: index,
              text: ez5.loca.getBestFrontendValue(mapping.displayname),
              active: true,
              group: "mapping"
            });
            checkboxes.push(checkbox);
          }
          form = new CUI.Form({
            fields: checkboxes,
            data: checkboxData
          });
          form.start();
          label = new LocaLabel({
            loca_key: "admin.metadata.menu.upload.confirmation.text",
            multiline: true,
            markdown: true
          });
          return new CUI.VerticalList({
            content: [label, form]
          });
        };
      })(this),
      buttons: [
        {
          text: $$("admin.metadata.menu.upload.confirmation.cancel"),
          onClick: (function(_this) {
            return function() {
              return confirmationDialog.destroy();
            };
          })(this)
        }, {
          text: $$("admin.metadata.menu.upload.confirmation.replace"),
          onClick: (function(_this) {
            return function() {
              var replaceConfirmationDialog;
              replaceConfirmationDialog = new CUI.ConfirmationDialog({
                title: $$("admin.metadata.menu.upload.confirmation.replace.confirm.title"),
                content: new LocaLabel({
                  loca_key: "admin.metadata.menu.upload.confirmation.replace.confirm"
                }),
                buttons: [
                  {
                    text: $$("base.cancel"),
                    onClick: function() {
                      replaceConfirmationDialog.destroy();
                    }
                  }, {
                    text: $$("base.ok"),
                    onClick: function() {
                      replaceConfirmationDialog.destroy();
                      confirmationDialog.destroy();
                      upload(true);
                    }
                  }
                ]
              });
              replaceConfirmationDialog.show();
            };
          })(this)
        }, {
          text: $$("admin.metadata.menu.upload.confirmation.add"),
          onClick: (function(_this) {
            return function() {
              confirmationDialog.destroy();
              upload(false);
            };
          })(this)
        }
      ]
    });
    confirmationDialog.show();
  };

  MetadataApp.prototype.getTagsPromise = function() {
    return this.__getTagsPromise;
  };

  MetadataApp.prototype.getNamespaces = function() {
    return this.__namespaces;
  };

  MetadataApp.prototype.getPaneFlexHandle = function() {
    return CUI.dom.data(this.pane.west(), "flexHandle");
  };

  return MetadataApp;

})(RootMenuApp);

ez5.session_ready(function() {
  return ez5.rootMenu.registerApp(MetadataApp);
});
// Generated by CoffeeScript 1.12.7
var MetadataProfileList,
  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;

MetadataProfileList = (function(superClass) {
  extend(MetadataProfileList, superClass);

  function MetadataProfileList() {
    return MetadataProfileList.__super__.constructor.apply(this, arguments);
  }

  MetadataProfileList.prototype.readOpts = function() {
    MetadataProfileList.__super__.readOpts.call(this);
    return this.__profiles = null;
  };

  MetadataProfileList.prototype.load = function(opts) {
    var data;
    if (opts == null) {
      opts = {};
    }
    data = opts.skip_cache ? {} : ez5.session.fylrCacheParams();
    return ez5.api.xmlmapping({
      data: data,
      api: "/list"
    }).done((function(_this) {
      return function(__profiles) {
        _this.__profiles = __profiles;
      };
    })(this));
  };

  MetadataProfileList.prototype.getProfiles = function() {
    CUI.util.assert(CUI.util.isArray(this.__profiles), this.__cls + ".getProfiles", "Profiles not loaded yet. Use .load() first.");
    return this.__profiles;
  };

  MetadataProfileList.prototype.getMapping = function(mapping_id) {
    var i, j, len, len1, map, prof, ref, ref1;
    CUI.util.assert(CUI.util.isArray(this.__profiles), this.__cls + ".getMapping", "Profiles not loaded yet. Use .load() first.");
    ref = this.__profiles;
    for (i = 0, len = ref.length; i < len; i++) {
      prof = ref[i];
      ref1 = prof.mappings;
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        map = ref1[j];
        if (map.id === mapping_id) {
          return map;
        }
      }
    }
    return null;
  };

  MetadataProfileList.prototype.getProfileForMapping = function(mapping_id) {
    var i, j, len, len1, map, prof, ref, ref1;
    CUI.util.assert(CUI.util.isArray(this.__profiles), this.__cls + ".getProfileForMapping", "Profiles not loaded yet. Use .load() first.");
    ref = this.__profiles;
    for (i = 0, len = ref.length; i < len; i++) {
      prof = ref[i];
      ref1 = prof.mappings;
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        map = ref1[j];
        if (map.id === mapping_id) {
          return prof;
        }
      }
    }
    return null;
  };

  MetadataProfileList.prototype.getMappingOpts = function(injectOpts, filter_profile_type, filter_profile, filter) {
    var i, j, k, l, len, len1, map, ok, opt, opts, prof, ref, ref1, t, v;
    if (injectOpts == null) {
      injectOpts = null;
    }
    CUI.util.assert(CUI.util.isArray(this.__profiles), this.__cls + ".getMetadataMappings", "Profiles not loaded yet. Use .load() first.");
    opts = [];
    ref = this.__profiles;
    for (i = 0, len = ref.length; i < len; i++) {
      prof = ref[i];
      if (filter_profile && prof.profile !== filter_profile) {
        continue;
      }
      if (filter_profile_type && prof.profile_type) {
        if (CUI.util.isEmptyObject(filter_profile_type)) {
          ok = false;
        } else {
          ok = true;
        }
        for (k in filter_profile_type) {
          v = filter_profile_type[k];
          if (prof.profile_type[k] !== v) {
            ok = false;
            break;
          }
        }
      } else {
        ok = !!prof.profile_type;
      }
      if (!ok) {
        continue;
      }
      ref1 = prof.mappings;
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        map = ref1[j];
        if (filter && !filter(map)) {
          continue;
        }
        t = ez5.loca.getBestFrontendValue(map.displayname);
        if (CUI.util.isEmpty(t)) {
          t = "Mapping " + map.id;
        }
        opts.push({
          text: t,
          value: map.id
        });
      }
    }
    opts.sort(function(a, b) {
      return a.text.localeCompare(b.text);
    });
    if (injectOpts) {
      if (injectOpts.length) {
        if (opts.length && injectOpts.length > 1) {
          opts.splice(0, 0, {
            divider: true
          });
        }
        for (l = injectOpts.length - 1; l >= 0; l += -1) {
          opt = injectOpts[l];
          opts.splice(0, 0, opt);
        }
      }
    } else if (opts.length === 0) {
      opts.push({
        text: $$("metadata.profile.list.no_profiles"),
        disabled: true,
        value: null
      });
    }
    return opts;
  };

  MetadataProfileList.prototype.getMappingField = function(filter_profile_type, opts) {
    var default_opts, field_opts, getOptions;
    if (opts == null) {
      opts = {};
    }
    getOptions = (function(_this) {
      return function() {
        var extraMappingOpts, mappingOpts, options;
        if (opts.show_only_standard) {
          options = [
            {
              text: $$("metadata.profile.mapping.standard_mapping"),
              value: "standard"
            }
          ];
          return options;
        }
        mappingOpts = ez5.metadata.getMappingOpts(null, filter_profile_type, null, opts.mapping_filter);
        if (mappingOpts.length === 0) {
          return;
        }
        extraMappingOpts = [
          {
            text: $$("metadata.profile.mapping.no_mapping"),
            value: null
          }, {
            divider: true
          }
        ];
        if (opts.show_standard_option) {
          extraMappingOpts.unshift({
            text: $$("metadata.profile.mapping.standard_mapping"),
            value: "standard"
          });
        }
        return extraMappingOpts.concat(mappingOpts);
      };
    })(this);
    if (!getOptions()) {
      return;
    }
    field_opts = opts.field_opts || {};
    default_opts = {
      form: {
        label: $$("metadata.profile.mapping.label")
      },
      name: "mapping",
      maximize_horizontal: true,
      mark_changed: false,
      check_changed: false,
      undo_support: false,
      options: getOptions,
      onDataInit: (function(_this) {
        return function(_, data) {
          if (!getOptions().some(function(option) {
            return CUI.util.isEqual(option.value, data[field_opts.name]);
          })) {
            data[field_opts.name] = opts.show_standard_option ? "standard" : null;
          }
        };
      })(this)
    };
    CUI.util.mergeMap(field_opts, default_opts);
    return new CUI.Select(field_opts);
  };

  MetadataProfileList.prototype.getRecipesFromProfileRecipes = function(recipes, only_usereditable) {
    var _, hasUserEditable, paramDef, recipe, recipeName, ref, result;
    if (only_usereditable == null) {
      only_usereditable = false;
    }
    if (!recipes) {
      return [];
    }
    result = [];
    for (recipeName in recipes) {
      recipe = recipes[recipeName];
      FASProduceConfigBaseConfig.__normalizeRecipe(recipe);
      if (CUI.util.isEmpty(recipe.Params)) {
        continue;
      }
      if (only_usereditable) {
        hasUserEditable = false;
        ref = recipe.Params;
        for (_ in ref) {
          paramDef = ref[_];
          if (paramDef.usereditable) {
            hasUserEditable = true;
            break;
          }
        }
        if (!hasUserEditable) {
          continue;
        }
      }
      result.push(recipe);
    }
    return result;
  };

  MetadataProfileList.prototype.__filterRecipesByRequired = function(compiledRecipes, requiredRecipes) {
    var filtered, i, len, recipeName;
    if (!compiledRecipes) {
      return null;
    }
    if (!requiredRecipes || requiredRecipes.length === 0) {
      return compiledRecipes;
    }
    filtered = {};
    for (i = 0, len = requiredRecipes.length; i < len; i++) {
      recipeName = requiredRecipes[i];
      if (compiledRecipes[recipeName]) {
        filtered[recipeName] = compiledRecipes[recipeName];
      }
    }
    return filtered;
  };

  MetadataProfileList.prototype.__resolveProfileRecipes = function(opts) {
    var mapping, mapping_id, profile;
    if (opts.profile_recipes) {
      return opts.profile_recipes;
    }
    if (opts.getMappingId) {
      mapping_id = opts.getMappingId();
      if (mapping_id && CUI.util.isInteger(parseInt(mapping_id))) {
        mapping_id = parseInt(mapping_id);
        profile = this.getProfileForMapping(mapping_id);
        mapping = this.getMapping(mapping_id);
        return this.__filterRecipesByRequired(profile != null ? profile._compiled_recipes : void 0, mapping != null ? mapping._recipes_required : void 0);
      }
    }
    return null;
  };

  MetadataProfileList.prototype.getMappingRecipeConfigButton = function(data, opts) {
    var button, filteredRecipes, hasRecipes, name, only_usereditable, profileRecipes, recipes;
    if (opts == null) {
      opts = {};
    }
    name = opts.name || "mapping_recipe_configs";
    only_usereditable = opts.only_usereditable || false;
    recipes = this.getMetadataRecipesWithParams(only_usereditable);
    hasRecipes = recipes.length > 0;
    if (opts.hide_if_no_recipes) {
      profileRecipes = this.__resolveProfileRecipes(opts);
      filteredRecipes = this.getRecipesFromProfileRecipes(profileRecipes, only_usereditable);
      if (filteredRecipes.length === 0) {
        return null;
      }
    }
    button = new CUI.Button({
      icon: "fa-cog",
      text: opts.button_text || null,
      disabled: !hasRecipes,
      group: "mapping_recipe_config",
      tooltip: {
        text: $$("metadata.profile.mapping.recipe_config.tooltip")
      },
      onClick: (function(_this) {
        return function(ev, btn) {
          profileRecipes = _this.__resolveProfileRecipes(opts);
          filteredRecipes = _this.getRecipesFromProfileRecipes(profileRecipes, only_usereditable);
          if (filteredRecipes.length === 0) {
            return;
          }
          _this.__showRecipeConfigPopover(btn, data, name, filteredRecipes, opts.popover_placement, only_usereditable, opts.onDataChanged);
        };
      })(this)
    });
    this.__updateRecipeConfigActiveState(button, data, name);
    return button;
  };

  MetadataProfileList.prototype.updateRecipeConfigButtonState = function(button, mapping, only_usereditable) {
    var filteredRecipes, isSpecificMapping, mappingObj, mapping_id, profile, profileRecipes;
    if (only_usereditable == null) {
      only_usereditable = false;
    }
    if (!button) {
      return;
    }
    isSpecificMapping = mapping && CUI.util.isInteger(parseInt(mapping));
    if (!isSpecificMapping) {
      button.disable();
      return;
    }
    mapping_id = parseInt(mapping);
    profile = this.getProfileForMapping(mapping_id);
    mappingObj = this.getMapping(mapping_id);
    filteredRecipes = this.__filterRecipesByRequired(profile != null ? profile._compiled_recipes : void 0, mappingObj != null ? mappingObj._recipes_required : void 0);
    profileRecipes = this.getRecipesFromProfileRecipes(filteredRecipes, only_usereditable);
    if (profileRecipes.length === 0) {
      button.disable();
    } else {
      button.enable();
    }
  };

  MetadataProfileList.prototype.getMetadataRecipesWithParams = function(only_usereditable) {
    var _, hasUserEditable, i, len, paramDef, recipe, recipes, ref, ref1, ref2, result;
    if (only_usereditable == null) {
      only_usereditable = false;
    }
    recipes = ((ref = ez5.session.data.config.eas) != null ? (ref1 = ref._metadata) != null ? ref1.recipes : void 0 : void 0) || [];
    result = [];
    for (i = 0, len = recipes.length; i < len; i++) {
      recipe = recipes[i];
      FASProduceConfigBaseConfig.__normalizeRecipe(recipe);
      if (CUI.util.isEmpty(recipe.Params)) {
        continue;
      }
      if (only_usereditable) {
        hasUserEditable = false;
        ref2 = recipe.Params;
        for (_ in ref2) {
          paramDef = ref2[_];
          if (paramDef.usereditable) {
            hasUserEditable = true;
            break;
          }
        }
        if (!hasUserEditable) {
          continue;
        }
      }
      result.push(recipe);
    }
    return result;
  };

  MetadataProfileList.prototype.__recipeHasValues = function(recipeData) {
    var _, ref, value;
    if (!(recipeData != null ? recipeData.params : void 0)) {
      return false;
    }
    ref = recipeData.params;
    for (_ in ref) {
      value = ref[_];
      if (!CUI.util.isEmpty(value)) {
        return true;
      }
    }
    return false;
  };

  MetadataProfileList.prototype.__updateRecipeConfigActiveState = function(button, data, name) {
    var hasData, recipeData, recipeName, ref;
    hasData = false;
    if (data[name]) {
      ref = data[name];
      for (recipeName in ref) {
        recipeData = ref[recipeName];
        if (this.__recipeHasValues(recipeData)) {
          hasData = true;
          break;
        }
      }
    }
    if (hasData) {
      button.activate();
    } else {
      button.deactivate();
    }
  };

  MetadataProfileList.prototype.__cleanRecipeConfigData = function(data, name) {
    var paramName, recipeData, recipeName, ref, ref1, value;
    if (!data[name]) {
      return;
    }
    ref = data[name];
    for (recipeName in ref) {
      recipeData = ref[recipeName];
      if (recipeData != null ? recipeData.params : void 0) {
        ref1 = recipeData.params;
        for (paramName in ref1) {
          value = ref1[paramName];
          if (CUI.util.isEmpty(value)) {
            delete recipeData.params[paramName];
          }
        }
      }
      if (!this.__recipeHasValues(recipeData)) {
        delete data[name][recipeName];
      }
    }
    if (CUI.util.isEmptyObject(data[name])) {
      delete data[name];
    }
  };

  MetadataProfileList.prototype.__showRecipeConfigPopover = function(button, data, name, recipes, placement, only_usereditable, onDataChanged) {
    var displayName, form, i, initialData, len, panel, panels, paramDef, paramFields, paramName, popover, recipe, recipeName, ref;
    if (only_usereditable == null) {
      only_usereditable = false;
    }
    if (!data[name]) {
      data[name] = {};
    }
    initialData = CUI.util.copyObject(data[name], true);
    panels = [];
    for (i = 0, len = recipes.length; i < len; i++) {
      recipe = recipes[i];
      recipeName = recipe.RecipeName;
      displayName = ez5.loca.getBestFrontendValue(recipe.Displayname) || recipe.Name || recipeName;
      if (!data[name][recipeName]) {
        data[name][recipeName] = {
          params: {}
        };
      }
      if (!data[name][recipeName].params) {
        data[name][recipeName].params = {};
      }
      paramFields = [];
      ref = recipe.Params;
      for (paramName in ref) {
        paramDef = ref[paramName];
        if (only_usereditable && !paramDef.usereditable) {
          continue;
        }
        paramFields.push(this.__createRecipeParamField(paramName, paramDef));
      }
      form = new CUI.Form({
        data: data[name][recipeName],
        name: "params",
        fields: paramFields
      });
      form.start();
      panel = new CUI.Panel({
        text: displayName,
        closed: recipes.length > 1,
        content: form,
        radio: displayName
      });
      panels.push(panel);
    }
    popover = new CUI.Popover({
      element: button,
      placement: placement || "se",
      "class": "ez5-mapping-recipe-config-popover",
      pane: {
        padded: true,
        header_left: new CUI.Label({
          text: $$("metadata.profile.mapping.recipe_config.title")
        }),
        content: panels
      },
      onHide: (function(_this) {
        return function() {
          _this.__cleanRecipeConfigData(data, name);
          _this.__updateRecipeConfigActiveState(button, data, name);
          if (!CUI.util.isEqual(initialData, data[name] || {})) {
            if (typeof onDataChanged === "function") {
              onDataChanged();
            }
          }
        };
      })(this)
    });
    popover.show();
  };

  MetadataProfileList.prototype.__createRecipeParamField = function(paramName, paramDef) {
    var emptyValueFound, field, i, len, locaKeyFn, option, ref;
    locaKeyFn = function(type, parent_def) {
      return "fylr.produce.config.form.version.recipe";
    };
    field = BaseConfig.getFieldDefinitionFromParameter(paramName, paramDef, null, locaKeyFn);
    field.form.label = field.name;
    switch (paramDef.type) {
      case "bool":
        field.form.label = null;
        field.text = paramName;
        break;
      case "int":
        if (paramDef.defaultint) {
          field.placeholder = "" + paramDef.defaultint;
        }
        break;
      case "text":
        if (paramDef.multiline) {
          field.textarea = true;
        }
        if (paramDef.defaultstring) {
          field.placeholder = paramDef.defaultstring;
        }
    }
    field.form.hint = paramDef.description;
    if (field.options) {
      emptyValueFound = false;
      ref = field.options;
      for (i = 0, len = ref.length; i < len; i++) {
        option = ref[i];
        if (option.value === "") {
          if (!emptyValueFound) {
            emptyValueFound = true;
          } else {
            option.divider = true;
          }
        }
        if (ez5.loca.has(option.text)) {
          option.text = $$(option.text);
        } else if (ez5.loca.has("fylr.produce.config.form.version.recipe.params." + paramName + "." + option.value)) {
          option.text = $$("fylr.produce.config.form.version.recipe.params." + paramName + "." + option.value);
        } else {
          option.text = option.value;
        }
      }
    }
    return field;
  };

  return MetadataProfileList;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var MetadataProfile,
  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;

MetadataProfile = (function(superClass) {
  extend(MetadataProfile, superClass);

  function MetadataProfile() {
    return MetadataProfile.__super__.constructor.apply(this, arguments);
  }

  MetadataProfile.prototype.initOpts = function() {
    MetadataProfile.__super__.initOpts.call(this);
    return this.addOpts({
      metadata: {
        mandatory: true,
        check: MetadataApp
      },
      profile: {
        mandatory: true,
        check: "PlainObject"
      }
    });
  };

  MetadataProfile.prototype.readOpts = function() {
    var i, len, mapping_short, ref;
    MetadataProfile.__super__.readOpts.call(this);
    this.profile = this._profile;
    if (!this.profile.profile_type) {
      this.profile.profile_type = {};
    }
    this.metadata = this._metadata;
    this.children = [];
    ref = this.profile.mappings;
    for (i = 0, len = ref.length; i < len; i++) {
      mapping_short = ref[i];
      this.children.push(new MetadataProfileMapping({
        mapping_short: mapping_short,
        metadata: this.metadata
      }));
    }
    return this.children.sort(function(a, b) {
      return a.getDisplayName().localeCompare(b.getDisplayName());
    });
  };

  MetadataProfile.prototype.getName = function() {
    return ez5.loca.getBestFrontendValue(this.profile.displayname) || this.profile.profile;
  };

  MetadataProfile.prototype.renderContent = function() {
    return new CUI.Label({
      text: this.getName()
    });
  };

  MetadataProfile.prototype.getProfileTypes = function() {
    var on_off, ref, type, types;
    types = [];
    ref = this.profile.profile_type;
    for (type in ref) {
      on_off = ref[type];
      if (on_off) {
        types.push(type);
      }
    }
    return types;
  };

  MetadataProfile.prototype.getMenuItem = function() {
    return {
      ui: "metadata-profile-" + this.profile.profile + "-item",
      value: this.profile.profile,
      text: this.getName(),
      onClick: (function(_this) {
        return function() {
          var mapping;
          mapping = new MetadataProfileMapping({
            metadata: _this.metadata
          });
          _this.profile.mappings.push(mapping);
          _this.addNode(mapping);
          return mapping.select();
        };
      })(this)
    };
  };

  MetadataProfile.prototype.isSelectable = function() {
    return false;
  };

  return MetadataProfile;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var MetadataProfileMapping,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

MetadataProfileMapping = (function(superClass) {
  extend(MetadataProfileMapping, superClass);

  function MetadataProfileMapping() {
    return MetadataProfileMapping.__super__.constructor.apply(this, arguments);
  }

  MetadataProfileMapping.prototype.initOpts = function() {
    MetadataProfileMapping.__super__.initOpts.call(this);
    return this.addOpts({
      metadata: {
        mandatory: true,
        check: MetadataApp
      },
      mapping_short: {
        check: "PlainObject"
      }
    });
  };

  MetadataProfileMapping.prototype.readOpts = function() {
    var ref;
    MetadataProfileMapping.__super__.readOpts.call(this);
    this.metadata = this._metadata;
    return this.__id = (ref = this.opts.mapping_short) != null ? ref.id : void 0;
  };

  MetadataProfileMapping.prototype.renderContent = function() {
    var dn;
    dn = this.getDisplayName();
    if (dn !== null) {
      return new CUI.Label({
        text: dn
      });
    } else {
      return new CUI.EmptyLabel({
        text: $$("admin.metadata.list.mapping.new")
      });
    }
  };

  MetadataProfileMapping.prototype.getDisplayName = function() {
    var dn, ref, ref1;
    dn = ez5.loca.getBestFrontendValue((ref = this.mapping) != null ? ref.displayname : void 0);
    if (!CUI.util.isEmpty(dn)) {
      return dn;
    }
    dn = ez5.loca.getBestFrontendValue((ref1 = this._mapping_short) != null ? ref1.displayname : void 0);
    if (!CUI.util.isEmpty(dn)) {
      return dn;
    }
    if (this.__id) {
      return this.__id + "";
    }
    return null;
  };

  MetadataProfileMapping.prototype.isSelectable = function() {
    return CUI.ListViewTreeNode.prototype.isSelectable.call(this);
  };

  MetadataProfileMapping.prototype.select = function() {
    return MetadataProfileMapping.__super__.select.call(this).done((function(_this) {
      return function() {
        return _this.load();
      };
    })(this));
  };

  MetadataProfileMapping.prototype.deselect = function() {
    return MetadataProfileMapping.__super__.deselect.call(this).done((function(_this) {
      return function() {
        var ref, ref1;
        if ((ref = _this.metadata) != null) {
          ref.empty();
        }
        if ((ref1 = _this.xmlForm) != null) {
          ref1.destroy();
        }
        delete _this.xmlForm;
        delete _this.mapping;
        return delete _this.__saveButton;
      };
    })(this));
  };

  MetadataProfileMapping.prototype.load = function() {
    if (this.__id) {
      return ez5.api.xmlmapping({
        api: "/mapping/" + this.__id
      }).done((function(_this) {
        return function(mapping) {
          _this.mapping = mapping;
          return _this.show();
        };
      })(this));
    } else {
      this.mapping = {};
      return this.show();
    }
  };

  MetadataProfileMapping.prototype.remove = function(keep) {
    var key;
    if (keep == null) {
      keep = false;
    }
    if (this.__id) {
      key = "metadata.profile.mapping.confirm.remove";
    } else {
      key = "metadata.profile.mapping.confirm.remove.new";
    }
    CUI.confirm({
      text: $$(key, {
        name: this.getDisplayName()
      }),
      button_text_ok: $$("metadata.profile.mapping.confirm.remove.button.ok")
    }).done((function(_this) {
      return function() {
        if (!_this.__id) {
          return MetadataProfileMapping.__super__.remove.call(_this, keep);
        } else {
          return ez5.api.xmlmapping({
            type: 'DELETE',
            api: '/mapping/' + _this.__id
          }).done(function() {
            ez5.metadata.load({
              skip_cache: true
            });
            return CUI.ListViewTreeNode.prototype.remove.call(_this, keep);
          });
        }
      };
    })(this));
    return this;
  };

  MetadataProfileMapping.prototype.show = function() {
    var initSaveData, pane, requiredWrapper;
    initSaveData = null;
    requiredWrapper = CUI.dom.div("ez5-required-message");
    this.__errorLabel = new CUI.Label({
      text: "",
      "class": "ez5-editor-required-message",
      icon: "warning"
    });
    CUI.dom.append(requiredWrapper, this.__errorLabel);
    this.__errorLabel.hide();
    this.__saveButton = new LocaButton({
      ui: "metadata-profile-mapping-save-button",
      loca_key: "metadata.profile.mapping.button.save",
      primary: true,
      disabled: true,
      onClick: (function(_this) {
        return function(ev) {
          _this.__saveButton.disable();
          return _this.save(ev).done(function() {
            return _this.load();
          }).fail(function() {
            return _this.__saveButton.enable();
          });
        };
      })(this)
    });
    this.__plusButton = new CUI.Button({
      icon: "plus",
      group: "customFields",
      disabled: true,
      onClick: (function(_this) {
        return function() {
          _this.__showNewFieldModal();
        };
      })(this)
    });
    this.__minusButton = new CUI.Button({
      icon: "minus",
      group: "customFields",
      disabled: true,
      onClick: (function(_this) {
        return function() {
          _this.__removeField();
        };
      })(this)
    });
    this.__editButton = new CUI.Button({
      icon: "edit",
      group: "customFields",
      disabled: true,
      onClick: (function(_this) {
        return function() {
          _this.__showEditFieldModal();
        };
      })(this)
    });
    if (indexOf.call(this.father.getProfileTypes(), "exiftool_import") >= 0) {
      this.__copyButton = new CUI.Button({
        icon: "fa-files-o",
        group: "customFields",
        disabled: true,
        onClick: (function(_this) {
          return function() {
            _this.__showCopyFieldModal();
          };
        })(this)
      });
    }
    if (ez5.version("6") && this.__isExportMapping()) {
      this.__jsButton = new CUI.Button({
        icon: "fa-code",
        group: "jsEditor",
        disabled: true,
        tooltip: {
          text: $$("admin.metadata.mapping.js.button.tooltip")
        },
        onClick: (function(_this) {
          return function() {
            _this.__showJsEditorForSelectedField();
          };
        })(this)
      });
    }
    pane = new CUI.BorderLayout({
      center: {},
      east: {
        flexHandle: {
          state_name: "metadata-profile-east"
        },
        "class": "ez5-metadata-profile-mapping-east"
      },
      south: {
        content: new CUI.PaneToolbar({
          right: {
            content: [requiredWrapper, this.__saveButton]
          },
          left: {
            content: (function(_this) {
              return function() {
                var buttons;
                buttons = [_this.__plusButton, _this.__minusButton, _this.__editButton, _this.__copyButton, _this.__jsButton];
                return new CUI.Buttonbar({
                  buttons: buttons
                });
              };
            })(this)
          }
        })
      }
    });
    this.metadata.pane.replace(pane, "center");
    CUI.Events.listen({
      node: pane,
      type: "data-changed",
      call: (function(_this) {
        return function() {
          var e;
          _this.__errorLabel.setText("");
          _this.__saveButton.disable();
          _this.__errorLabel.hide();
          _this.__clearFieldValidationErrors();
          CUI.util.isEqual;
          try {
            if (!CUI.util.isEqual(initSaveData, _this.getSaveData())) {
              _this.__saveButton.enable();
            }
          } catch (error) {
            e = error;
            _this.__saveButton.disable();
            console.error(e);
            _this.__errorLabel.show();
            _this.__errorLabel.setText((typeof e.getError === "function" ? e.getError() : void 0) || e);
          }
        };
      })(this)
    });
    this.xmlForm = new XMLFormWrapper({
      pane: pane,
      profile: this.father.profile.profile,
      mapping: this.mapping,
      blocks: this.getBlocks()
    });
    this.xmlForm.init().done((function(_this) {
      return function() {
        if (!_this.xmlForm) {
          return;
        }
        try {
          initSaveData = _this.getSaveData();
        } catch (error) {}
        CUI.Events.listen({
          type: "metadata-mapping-field-click",
          node: pane,
          call: function(_, info) {
            if (CUI.dom.hasClass(info.field.getRow(), XMLFormField.SELECTED_CLASS)) {
              _this.__selectedCustomFieldPos = info.field.getPos();
              _this.__selectedIndexBlock = info.indexBlock;
              _this.__selectedField = info.field;
            } else {
              _this.__selectedCustomFieldPos = null;
              _this.__selectedIndexBlock = null;
              _this.__selectedField = null;
            }
            _this.__updateActionButtons(info.field);
          }
        });
        if (_this.xmlForm.isCustomFieldsEnabled()) {
          return _this.__plusButton.enable();
        }
      };
    })(this));
    this.update();
  };

  MetadataProfileMapping.prototype.__updateActionButtons = function(field) {
    var ref, ref1, ref2, ref3;
    if (!field || !field.getDef() || field instanceof XMLFormFieldSplitter) {
      if ((ref = this.__copyButton) != null) {
        ref.disable();
      }
      this.__minusButton.disable();
      this.__editButton.disable();
      if ((ref1 = this.__jsButton) != null) {
        ref1.disable();
      }
      return;
    }
    if (field.getDef().custom) {
      this.__minusButton.enable();
      this.__editButton.enable();
      if ((ref2 = this.__copyButton) != null) {
        ref2.enable();
      }
    } else {
      this.__minusButton.disable();
      this.__editButton.disable();
      if ((ref3 = this.__copyButton) != null) {
        ref3.disable();
      }
    }
    if (this.__jsButton) {
      if (CUI.dom.hasClass(field.getRow(), XMLFormField.SELECTED_CLASS)) {
        this.__jsButton.enable();
      } else {
        this.__jsButton.disable();
      }
    }
  };

  MetadataProfileMapping.prototype.__getFieldForm = function(data, addButton, messageLabel) {
    var dataFormFields, displayNameField, form, formFields, onDataChanged, strategyImportField, type, types, updateStrategyImportCheckbox;
    types = this.father.getProfileTypes();
    if (indexOf.call(types, "exiftool_import") >= 0) {
      type = "import";
    } else if (indexOf.call(types, "xml_export") >= 0) {
      type = "export";
    }
    updateStrategyImportCheckbox = (function(_this) {
      return function() {
        var hasListActive, ref, strategyField, strategyFields;
        if (type !== "import" || !form) {
          return;
        }
        strategyFields = form.getFieldsByName("strategy_import");
        if (!strategyFields.length) {
          return;
        }
        strategyField = strategyFields[0];
        hasListActive = (ref = data.xml_import) != null ? ref.some(function(tag) {
          return tag.list;
        }) : void 0;
        if (hasListActive) {
          data.strategy_import = true;
          strategyField.reload();
          return strategyField.disable();
        } else {
          return strategyField.enable();
        }
      };
    })(this);
    onDataChanged = (function(_this) {
      return function() {
        var f, field, j, k, l, len, len1, len2, path, ref, ref1, ref2, save_data, tag, uniquePathMap;
        messageLabel.hide();
        addButton.enable();
        updateStrategyImportCheckbox();
        if (!data.xml_export) {
          return;
        }
        if (!_this.father.profile.profile_type.xml_export) {
          return;
        }
        uniquePathMap = {};
        ref = data.xml_export;
        for (j = 0, len = ref.length; j < len; j++) {
          tag = ref[j];
          if (!tag.tag) {
            continue;
          }
          path = tag.tag.path;
          if (uniquePathMap[path]) {
            messageLabel.show();
            addButton.disable();
            return;
          }
          uniquePathMap[path] = true;
        }
        uniquePathMap = {};
        save_data = {};
        _this.xmlForm.getSaveData(save_data);
        ref1 = save_data.fields;
        for (k = 0, len1 = ref1.length; k < len1; k++) {
          field = ref1[k];
          if (!field.xml_export) {
            continue;
          }
          ref2 = field.xml_export;
          for (l = 0, len2 = ref2.length; l < len2; l++) {
            f = ref2[l];
            if (uniquePathMap[f.path]) {
              messageLabel.show();
              addButton.disable();
              return;
            }
            uniquePathMap[f.path] = true;
          }
        }
      };
    })(this);
    dataFormFields = [
      {
        type: MetadataTagSelector,
        form: {
          label: $$("admin.metadata.mapping.field.form.tags.tag.label")
        },
        metadata_type: type,
        name: "tag",
        getTags: (function(_this) {
          return function() {
            return _this.metadata.getTagsPromise();
          };
        })(this),
        allow_custom: type === "import"
      }, {
        type: CUI.Checkbox,
        form: {
          label: $$("admin.metadata.mapping.field.form.tags.list.label")
        },
        name: "list"
      }
    ];
    if (type === "import") {
      dataFormFields.push({
        type: CUI.Select,
        name: "printable",
        form: {
          label: $$("admin.metadata.mapping.field.form.tags.select.value-mode")
        },
        options: [
          {
            text: $$("admin.metadata.mapping.field.form.tags.select.value-mode-printable"),
            value: true
          }, {
            text: $$("admin.metadata.mapping.field.form.tags.select.value-mode-rawValue"),
            value: false
          }
        ]
      });
    }
    if (type === "import") {
      strategyImportField = {
        type: CUI.Checkbox,
        form: {
          label: $$("admin.metadata.mapping.field.form.strategy-import.label"),
          hint: $$("admin.metadata.mapping.field.form.strategy-import.hint")
        },
        name: "strategy_import"
      };
    }
    if (ez5.version("6")) {
      displayNameField = {
        type: CUI.MultiInput,
        control: ez5.loca.getLanguageControlAdmin(),
        user_selectable: ez5.session.getPref("languages_user_selection"),
        maximize_horizontal: true,
        form: {
          label: $$("admin.metadata.mapping.field.form.display-name")
        },
        name: "text"
      };
    } else {
      displayNameField = {
        type: CUI.Input,
        maximize_horizontal: true,
        form: {
          label: $$("admin.metadata.mapping.field.form.display-name")
        },
        name: "text"
      };
    }
    if (data.xml_import) {
      data.xml_import = data.xml_import.filter((function(_this) {
        return function(f) {
          var ref;
          return !((ref = f.originalPath) != null ? ref.includes("/rdf:RDF/rdf:Description/*[starts-with(name(),") : void 0);
        };
      })(this));
    }
    formFields = [displayNameField];
    if (strategyImportField) {
      formFields.push(strategyImportField);
    }
    formFields.push({
      type: CUI.DataForm,
      form: {
        label: $$("admin.metadata.mapping.field.form." + type + "-tags")
      },
      maximize_horizontal: true,
      name: "xml_" + type,
      fields: dataFormFields,
      has_add_button: true,
      enableAddButton: function(dataForm, rows) {
        var j, len, row;
        for (j = 0, len = rows.length; j < len; j++) {
          row = rows[j];
          if (!row.tag) {
            return false;
          }
        }
        return true;
      }
    });
    form = new CUI.Form({
      data: data,
      padded: true,
      onDataInit: onDataChanged,
      onDataChanged: onDataChanged,
      fields: formFields
    });
    form.start();
    updateStrategyImportCheckbox();
    return form;
  };

  MetadataProfileMapping.prototype.__getCustomImportTagsData = function(tags) {
    var j, len, search, tag, tagSearch, tagSearchList;
    search = [];
    for (j = 0, len = tags.length; j < len; j++) {
      tag = tags[j];
      tagSearch = "/rdf:RDF/rdf:Description/" + tag.path + "/rdf:Description/";
      if (tag.printable) {
        tagSearch += XMLFormField.SEARCH_IMPORT_PRINTABLE;
      } else {
        tagSearch += XMLFormField.SEARCH_IMPORT_RAW;
      }
      if (tag.list) {
        tagSearchList = tagSearch + XMLFormField.SEARCH_IMPORT_LIST;
        search.push({
          search: tagSearchList
        });
      }
      if (!search.some((function(_this) {
        return function(s) {
          return s.search === tagSearch;
        };
      })(this))) {
        search.push({
          search: tagSearch
        });
      }
      search.push({
        search: "/rdf:RDF/rdf:Description/*[starts-with(name(), '" + tag.path + "-')]/rdf:Description/et:prt",
        l10n_prefix: "/rdf:RDF/rdf:Description/" + tag.path
      });
    }
    return search;
  };

  MetadataProfileMapping.prototype.__getCustomDef = function(data) {
    var buildTags, field, tag, tags, types;
    types = this.father.getProfileTypes();
    field = {
      type: "Input",
      text: data.text
    };
    buildTags = function(tags) {
      if (!tags) {
        return;
      }
      tags = tags.filter(function(_tag) {
        var ref;
        return !CUI.util.isEmpty((ref = _tag.tag) != null ? ref.path : void 0);
      });
      return tags.map(function(_tag) {
        var tag;
        tag = _tag.tag;
        tag.list = _tag.list;
        tag.printable = _tag.printable;
        if (CUI.util.isFalse(tag.printable)) {
          tag.rawValue = true;
        }
        return tag;
      });
    };
    if (types.some((function(_this) {
      return function(type) {
        return type === "exiftool_export" || type === "xml_export" || type === "dc_export";
      };
    })(this))) {
      tags = buildTags(data.xml_export);
      if (CUI.util.isEmpty(tags)) {
        CUI.alert({
          text: $$("admin.metadata.mapping.field.form.empty-tags-message")
        });
        return;
      }
      field.xml_export = tags;
    }
    if (ez5.version("6") && data.elements_js) {
      field.elements_js = data.elements_js;
    }
    if (indexOf.call(types, "exiftool_import") >= 0) {
      tags = buildTags(data.xml_import);
      if (CUI.util.isEmpty(tags)) {
        CUI.alert({
          text: $$("admin.metadata.mapping.field.form.empty-tags-message")
        });
        return;
      }
      field.xml_import = this.__getCustomImportTagsData(tags);
      if (data.strategy_import || field.xml_import.some((function(_this) {
        return function(e) {
          return e.search.includes("rdf:li");
        };
      })(this))) {
        field.strategy_import = "first";
      }
    }
    if (CUI.util.isEmpty(field.text)) {
      tag = tags.filter(function(_tag) {
        return !CUI.util.isEmpty(_tag.description);
      })[0];
      if (!tag) {
        CUI.alert({
          text: $$("admin.metadata.mapping.field.form.empty-display-name-message")
        });
        return;
      }
      field.text = ez5.loca.getBestFrontendValue(tag.description);
    }
    return field;
  };

  MetadataProfileMapping.prototype.__showCopyFieldModal = function() {
    var data, inputField, outputField, ref;
    if (!this.__selectedCustomFieldPos) {
      return;
    }
    ref = this.xmlForm.getField(this.__selectedCustomFieldPos, this.__selectedIndexBlock), outputField = ref[0], inputField = ref[1];
    data = this.__getDataFromField(outputField, inputField);
    this.__showNewFieldModal(data);
  };

  MetadataProfileMapping.prototype.__showNewFieldModal = function(data) {
    var addButton, footerButtons, form, jsButton, messageLabel, modal;
    if (data == null) {
      data = {};
    }
    addButton = new LocaButton({
      loca_key: "admin.metadata.mapping.new-field.modal.footer.button",
      primary: true,
      onClick: (function(_this) {
        return function() {
          var fieldDef;
          fieldDef = _this.__getCustomDef(data);
          if (!fieldDef) {
            return;
          }
          _this.xmlForm.addCustomField(fieldDef);
          return modal.destroy();
        };
      })(this)
    });
    messageLabel = new CUI.Label({
      text: $$("admin.metadata.mapping.error.duplicate-tag-path")
    });
    messageLabel.hide();
    form = this.__getFieldForm(data, addButton, messageLabel);
    footerButtons = [messageLabel, addButton];
    if (ez5.version("6") && this.__isExportMapping()) {
      jsButton = new LocaButton({
        loca_key: "admin.metadata.mapping.edit-field.modal.js.button",
        icon: "fa-code",
        tooltip: {
          text: $$("admin.metadata.mapping.js.button.tooltip")
        },
        onClick: (function(_this) {
          return function() {
            return _this.__showElementsJsModal(null, data);
          };
        })(this)
      });
      footerButtons.unshift(jsButton);
    }
    modal = new CUI.Modal({
      "class": "ez5-metadata-profile-modal",
      cancel: true,
      onCancel: (function(_this) {
        return function() {
          form.destroy();
          return modal.destroy();
        };
      })(this),
      pane: {
        header_left: new LocaLabel({
          loca_key: "admin.metadata.mapping.new-field.modal.header"
        }),
        content: form,
        footer_right: footerButtons
      }
    });
    modal.show();
  };

  MetadataProfileMapping.prototype.__getDataFromField = function(outputField, inputField) {
    var data, outputFieldDef, types;
    types = this.father.getProfileTypes();
    outputFieldDef = outputField.getDef();
    data = {
      text: outputFieldDef.text
    };
    if (data.text && CUI.util.isPlainObject(data.text) && !outputFieldDef.custom) {
      data.text = ez5.loca.getBestFrontendValue(data.text);
    }
    if (types.some((function(_this) {
      return function(type) {
        return type === "exiftool_export" || type === "xml_export" || type === "dc_export";
      };
    })(this))) {
      data.xml_export = inputField.getCustomDataTags();
      if (ez5.version("6") && inputField.getDef().elements_js) {
        data.elements_js = inputField.getDef().elements_js;
      }
    }
    if (indexOf.call(types, "exiftool_import") >= 0) {
      data.xml_import = inputField.getCustomDataTags();
      data.strategy_import = inputField.getDef().strategy_import === "first";
    }
    return data;
  };

  MetadataProfileMapping.prototype.__showEditFieldModal = function() {
    var addButton, data, footerButtons, form, inputDef, inputField, jsButton, messageLabel, modal, outputDef, outputField, ref;
    if (!this.__selectedCustomFieldPos) {
      return;
    }
    ref = this.xmlForm.getField(this.__selectedCustomFieldPos, this.__selectedIndexBlock), outputField = ref[0], inputField = ref[1];
    inputDef = inputField.getDef();
    outputDef = outputField.getDef();
    data = this.__getDataFromField(outputField, inputField);
    addButton = new LocaButton({
      loca_key: "admin.metadata.mapping.edit-field.modal.footer.button",
      primary: true,
      onClick: (function(_this) {
        return function() {
          var fieldDef;
          fieldDef = _this.__getCustomDef(data);
          if (!fieldDef) {
            return;
          }
          inputDef.xml_export = fieldDef.xml_export;
          inputDef.xml_import = fieldDef.xml_import;
          inputDef.text = fieldDef.text;
          outputDef.text = fieldDef.text;
          inputDef.strategy_import = fieldDef.strategy_import;
          _this.xmlForm.updateField(inputField, inputDef);
          _this.xmlForm.updateField(outputField, outputDef);
          return modal.destroy();
        };
      })(this)
    });
    messageLabel = new CUI.Label({
      text: $$("admin.metadata.mapping.error.duplicate-tag-path")
    });
    messageLabel.hide();
    form = this.__getFieldForm(data, addButton, messageLabel);
    footerButtons = [messageLabel, addButton];
    if (ez5.version("6") && this.__isExportMapping()) {
      jsButton = new LocaButton({
        loca_key: "admin.metadata.mapping.edit-field.modal.js.button",
        icon: "fa-code",
        tooltip: {
          text: $$("admin.metadata.mapping.js.button.tooltip")
        },
        onClick: (function(_this) {
          return function() {
            return _this.__showElementsJsModal(inputField, inputDef, outputField, outputDef);
          };
        })(this)
      });
      if (!CUI.util.isEmpty(inputDef.elements_js)) {
        jsButton.activate();
      }
      footerButtons.unshift(jsButton);
    }
    modal = new CUI.Modal({
      "class": "ez5-metadata-profile-modal",
      cancel: true,
      onCancel: (function(_this) {
        return function() {
          form.destroy();
          return modal.destroy();
        };
      })(this),
      pane: {
        header_left: new LocaLabel({
          loca_key: "admin.metadata.mapping.edit-field.modal.header"
        }),
        content: form,
        footer_right: footerButtons
      }
    });
    modal.show();
  };

  MetadataProfileMapping.prototype.__showJsEditorForSelectedField = function() {
    var inputDef, inputField, outputDef, outputField, ref;
    if (!this.__selectedField) {
      return;
    }
    ref = this.xmlForm.getField(this.__selectedCustomFieldPos, this.__selectedIndexBlock), outputField = ref[0], inputField = ref[1];
    if (!inputField) {
      return;
    }
    inputDef = inputField.getDef();
    outputDef = outputField != null ? outputField.getDef() : void 0;
    this.__showElementsJsModal(inputField, inputDef, outputField, outputDef);
  };

  MetadataProfileMapping.prototype.__showElementsJsModal = function(inputField, inputDef, outputField, outputDef) {
    var form, hl, info_label, jsData, jsModal, saveButton;
    if (outputField == null) {
      outputField = null;
    }
    if (outputDef == null) {
      outputDef = null;
    }
    jsData = {};
    if (inputDef.elements_js) {
      jsData.elements_js = inputDef.elements_js;
    } else {
      jsData.elements_js = "";
    }
    saveButton = new LocaButton({
      loca_key: "admin.metadata.mapping.edit-field.modal.js.save",
      text: $$("base.apply"),
      primary: true,
      onClick: (function(_this) {
        return function() {
          if (CUI.util.isEmpty(jsData.elements_js)) {
            delete inputDef.elements_js;
            if (outputDef) {
              delete outputDef.elements_js;
            }
          } else {
            inputDef.elements_js = jsData.elements_js;
            if (outputDef) {
              outputDef.elements_js = jsData.elements_js;
            }
          }
          if (inputField) {
            _this.xmlForm.updateField(inputField, inputDef);
            if (outputField && outputDef) {
              _this.xmlForm.updateField(outputField, outputDef);
            }
            CUI.Events.trigger({
              type: "data-changed",
              node: _this.xmlForm.pane
            });
          }
          return jsModal.destroy();
        };
      })(this)
    });
    form = new CUI.Form({
      data: jsData,
      padded: true,
      maximize_vertical: true,
      fields: [
        {
          type: CUI.CodeInput,
          mode: "javascript",
          name: "elements_js",
          maximize_horizontal: true
        }
      ],
      onDataChanged: (function(_this) {
        return function() {
          var e;
          try {
            eval("(function(){" + jsData.elements_js + "})");
            return saveButton.enable();
          } catch (error) {
            e = error;
            return saveButton.disable();
          }
        };
      })(this)
    });
    form.start();
    info_label = new CUI.Label({
      text: $$("admin.metadata.mapping.edit-field.modal.js.info"),
      markdown: true,
      centered: false,
      multiline: true
    });
    hl = new CUI.HorizontalLayout({
      maximize_horizontal: true,
      maximize_vertical: true,
      center: {
        "class": "ez5-metadata-js-editor-modal-js",
        content: form
      },
      right: {
        "class": "ez5-metadata-js-editor-modal-info",
        content: info_label
      }
    });
    jsModal = new CUI.Modal({
      "class": "ez5-metadata-js-editor-modal",
      cancel: true,
      onCancel: (function(_this) {
        return function() {
          form.destroy();
          return jsModal.destroy();
        };
      })(this),
      pane: {
        header_left: new LocaLabel({
          loca_key: "admin.metadata.mapping.edit-field.modal.js.header"
        }),
        content: hl,
        footer_right: [saveButton]
      }
    });
    jsModal.show();
  };

  MetadataProfileMapping.prototype.__removeField = function() {
    var inputField, outputField, ref, removeConfirmation;
    if (!this.__selectedCustomFieldPos) {
      return;
    }
    ref = this.xmlForm.getField(this.__selectedCustomFieldPos, this.__selectedIndexBlock), outputField = ref[0], inputField = ref[1];
    removeConfirmation = new CUI.ConfirmationDialog({
      title: $$("admin.metadata.mapping.remove.confirmation.header"),
      content: new LocaLabel({
        loca_key: "admin.metadata.mapping.remove.confirmation"
      }),
      buttons: [
        {
          text: $$("base.cancel"),
          onClick: (function(_this) {
            return function() {
              return removeConfirmation.destroy();
            };
          })(this)
        }, {
          text: $$("base.ok"),
          onClick: (function(_this) {
            return function() {
              _this.xmlForm.removeCustomField(outputField, inputField);
              _this.__updateActionButtons();
              return removeConfirmation.destroy();
            };
          })(this)
        }
      ]
    });
    removeConfirmation.show();
  };

  MetadataProfileMapping.prototype.check_deselect = function(ev) {
    var dfr, ref;
    dfr = new CUI.Deferred();
    if ((ref = this.__saveButton) != null ? ref.isEnabled() : void 0) {
      new CUI.ConfirmationChoice({
        text: $$("metadata.profile.mapping.unsaved_changes.text"),
        choices: [
          {
            _value: "discard",
            text: $$("metadata.profile.mapping.unsaved_changes.button.discard")
          }, {
            _value: "cancel",
            text: $$("base.cancel")
          }, {
            _value: "save",
            primary: true,
            text: $$("metadata.profile.mapping.unsaved_changes.button.save")
          }
        ]
      }).open().done((function(_this) {
        return function(choice, btn, ev) {
          switch (choice._value) {
            case "discard":
              _this.__saveButton.disable();
              return dfr.resolve();
            case "cancel":
              return dfr.reject();
            case "save":
              return _this.save().done(dfr.resolve).fail(dfr.reject);
          }
        };
      })(this));
    } else {
      dfr.resolve();
    }
    return dfr.promise();
  };

  MetadataProfileMapping.prototype.__clearFieldValidationErrors = function() {
    var fieldData, formData, formField, j, key, len, ref;
    if (!this.xmlForm) {
      return;
    }
    formData = this.xmlForm.data;
    for (key in formData) {
      fieldData = formData[key];
      ref = fieldData.formFields || [];
      for (j = 0, len = ref.length; j < len; j++) {
        formField = ref[j];
        if (formField.drop) {
          CUI.dom.removeClass(formField.drop, "ez5-xml-form-field-invalid");
        }
        if (formField.__validationErrorLabel) {
          CUI.dom.remove(formField.__validationErrorLabel.DOM);
          formField.__validationErrorLabel = null;
        }
      }
    }
  };

  MetadataProfileMapping.prototype.__addFieldValidationError = function(formField, locaKey) {
    var errorLabel;
    if (!formField.drop) {
      return;
    }
    CUI.dom.addClass(formField.drop, "ez5-xml-form-field-invalid");
    errorLabel = new CUI.Label({
      text: $$(locaKey),
      "class": "ez5-xml-form-field-error-label cui-label-danger",
      icon: "fa-exclamation-triangle",
      multiline: true
    });
    formField.__validationErrorLabel = errorLabel;
    CUI.dom.append(formField.drop.parentNode, errorLabel.DOM);
    CUI.Events.trigger({
      type: "content-resize",
      node: formField.drop
    });
  };

  MetadataProfileMapping.prototype.__validateDragWrapperPositions = function() {
    var dragWrappers, dw, fieldData, fieldHasError, formData, formField, hasError, hasRegularAfter, hasRegularBefore, i, idx, isSpecial, j, k, key, l, len, len1, n, ref, ref1, ref2, ref3;
    if (!ez5.version("6")) {
      return;
    }
    formData = this.xmlForm.data;
    hasError = false;
    for (key in formData) {
      fieldData = formData[key];
      dragWrappers = fieldData.dragWrappers || [];
      if (dragWrappers.length < 2) {
        continue;
      }
      isSpecial = function(dw) {
        return dw instanceof XMLFormFieldDragWrapperFixedValue || dw instanceof XMLFormFieldDragDeepLink;
      };
      fieldHasError = false;
      for (idx = j = 0, len = dragWrappers.length; j < len; idx = ++j) {
        dw = dragWrappers[idx];
        if (!isSpecial(dw)) {
          continue;
        }
        hasRegularBefore = false;
        hasRegularAfter = false;
        for (i = k = 0, ref = idx; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
          if (!isSpecial(dragWrappers[i])) {
            hasRegularBefore = true;
            break;
          }
        }
        for (i = l = ref1 = idx + 1, ref2 = dragWrappers.length; ref1 <= ref2 ? l < ref2 : l > ref2; i = ref1 <= ref2 ? ++l : --l) {
          if (!isSpecial(dragWrappers[i])) {
            hasRegularAfter = true;
            break;
          }
        }
        if (hasRegularBefore && hasRegularAfter) {
          fieldHasError = true;
          break;
        }
      }
      if (fieldHasError) {
        hasError = true;
        ref3 = fieldData.formFields || [];
        for (n = 0, len1 = ref3.length; n < len1; n++) {
          formField = ref3[n];
          this.__addFieldValidationError(formField, "admin.metadata.mapping.error.special-tag-position");
        }
      }
    }
    if (hasError) {
      throw new InvalidSaveDataException({
        label: "admin.metadata.mapping.error.form-has-errors"
      });
    }
  };

  MetadataProfileMapping.prototype.__getRecipeConfigField = function(types) {
    var configButton, container;
    if (!ez5.version("6") || indexOf.call(types, "exiftool_import") < 0 || ez5.metadata.getMetadataRecipesWithParams().length === 0) {
      return void 0;
    }
    configButton = ez5.metadata.getMappingRecipeConfigButton(this.mapping, {
      name: "recipe_configs",
      button_text: $$("metadata.profile.mapping.recipe_config.button.text"),
      popover_placement: "e",
      profile_recipes: this.father.profile._compiled_recipes,
      hide_if_no_recipes: true,
      onDataChanged: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            type: "data-changed",
            node: configButton
          });
        };
      })(this)
    });
    if (!configButton) {
      return null;
    }
    container = CUI.dom.div("ez5-mapping-field-with-config");
    container.appendChild(configButton.DOM);
    return new CUI.DataFieldProxy({
      form: {
        label: $$("metadata.profile.mapping.recipe_config.form.label")
      },
      element: container
    });
  };

  MetadataProfileMapping.prototype.getSaveData = function() {
    var availableNamespaces, f, field, group, j, k, len, len1, metadataAttributesField, namespaces, prefixGroup, ref, ref1, ref2, save_data, uniquePathMap;
    if (!this.mapping || !this.xmlForm) {
      return null;
    }
    save_data = {
      id: this.mapping.id,
      displayname: this.mapping.displayname,
      idTable: this.mapping.idTable,
      profile: this.father.profile.profile,
      profile_type: CUI.util.copyObject(this.father.profile.profile_type, true)
    };
    if (ez5.version("6")) {
      save_data.recipe_configs = this.mapping.recipe_configs ? CUI.util.copyObject(this.mapping.recipe_configs, true) : null;
    }
    this.xmlForm.getSaveData(save_data);
    if (!save_data.profile_type.xml_export) {
      return save_data;
    }
    this.__validateDragWrapperPositions();
    availableNamespaces = this.metadata.getNamespaces();
    metadataAttributesField = null;
    namespaces = {};
    uniquePathMap = {};
    ref = save_data.fields;
    for (j = 0, len = ref.length; j < len; j++) {
      field = ref[j];
      if (!field.xml_export) {
        continue;
      }
      ref1 = field.xml_export;
      for (k = 0, len1 = ref1.length; k < len1; k++) {
        f = ref1[k];
        if (uniquePathMap[f.path]) {
          throw new InvalidSaveDataException({
            label: "admin.metadata.mapping.error.duplicate-tag-path"
          });
        }
        uniquePathMap[f.path] = true;
        group = f.group || ((ref2 = f.path.split(":")) != null ? ref2[0] : void 0);
        if (group && availableNamespaces[group]) {
          namespaces["xmlns:" + group] = availableNamespaces[group];
          prefixGroup = group.split("-")[0];
          if (prefixGroup !== group) {
            namespaces["xmlns:" + prefixGroup] = availableNamespaces[prefixGroup];
          }
        }
        if (!metadataAttributesField && CUI.util.isPlainObject(f.attributes)) {
          metadataAttributesField = f;
        }
      }
    }
    if (metadataAttributesField) {
      CUI.util.mergeMap(metadataAttributesField.attributes, namespaces);
    }
    return save_data;
  };

  MetadataProfileMapping.prototype.save = function(ev) {
    var req, save_data;
    save_data = this.getSaveData();
    if (ev != null ? ev.hasModifierKey() : void 0) {
      this.xmlForm.dump();
      console.debug(CUI.util.dump(save_data));
      return CUI.rejectedPromise();
    }
    ez5.splash.show('system.list.manager.item.saving');
    req = {
      api: "/xmlmapping/mapping",
      json_data: save_data
    };
    if (!this.__id) {
      req.type = "PUT";
    } else {
      req.type = "POST";
      req.api += "/" + this.__id;
    }
    return ez5.server(req).done((function(_this) {
      return function(data) {
        _this.__id = data.id;
        return ez5.metadata.load({
          skip_cache: true
        }).done(function() {
          return ez5.splash.done('system.list.manager.item.saved');
        }).fail(function() {
          return ez5.splash.hide();
        });
      };
    })(this)).fail((function(_this) {
      return function() {
        return ez5.splash.hide();
      };
    })(this));
  };

  MetadataProfileMapping.prototype.getBlocks = function() {
    var onlyObjectsWithEAS, profileType, profilesTypes, ref, ref1, types, value;
    types = this.father.getProfileTypes();
    onlyObjectsWithEAS = false;
    profilesTypes = [];
    ref = this.father.profile.profile_type;
    for (profileType in ref) {
      value = ref[profileType];
      if (value) {
        profilesTypes.push(profileType);
      }
    }
    if (((ref1 = this.father.profile.profile_type) != null ? ref1.exiftool_export : void 0) && profilesTypes.length === 1) {
      onlyObjectsWithEAS = true;
    }
    return [
      {
        ui: "metadata-profile-mapping-general-tab",
        name: "general",
        text: $$("admin.metadata.tab.general"),
        content: (function(_this) {
          return function() {
            return new CUI.Form({
              onDataChanged: function() {
                return _this.update();
              },
              fields: [
                {
                  type: CUI.Select,
                  form: {
                    label: $$("admin.metadata.mapping.object_type")
                  },
                  name: "idTable",
                  options: function() {
                    var _ot, hasEASFields, j, k, len, len1, m, options, ot, ref2, ref3;
                    options = [
                      {
                        text: $$("admin.metadata.mapping.object_type.all"),
                        value: null
                      }
                    ];
                    ref2 = ez5.schema.CURRENT._objecttypes;
                    for (j = 0, len = ref2.length; j < len; j++) {
                      ot = ref2[j];
                      _ot = new Objecttype(new Table("CURRENT", ot.table_id));
                      if (!_ot.inMainSearch() && !ez5.version("6.12")) {
                        continue;
                      }
                      if (ez5.version("6.12") && onlyObjectsWithEAS) {
                        hasEASFields = false;
                        ref3 = ez5.mask.CURRENT._masks_by_table_id[ot.table_id];
                        for (k = 0, len1 = ref3.length; k < len1; k++) {
                          m = ref3[k];
                          if (ez5.mask.CURRENT._mask_instance_by_name[m.name].getEASFields("all").length > 0) {
                            hasEASFields = true;
                            break;
                          }
                        }
                        if (!hasEASFields) {
                          continue;
                        }
                      }
                      options.push({
                        text: _ot.nameLocalized(),
                        value: ot.table_id
                      });
                    }
                    return options;
                  },
                  onDataInit: function(_, data) {
                    return _this.__lastIdTableSelected = data.idTable;
                  },
                  onDataChanged: function(data, field) {
                    var removeDragWrappers;
                    removeDragWrappers = function() {
                      var objecttypeName, xmlFormForm;
                      if (data.idTable) {
                        objecttypeName = ez5.schema.CURRENT._table_by_id[data.idTable].name;
                        xmlFormForm = _this.xmlForm.getForm();
                        xmlFormForm.removeDragWrappersNotOfObjecttype(objecttypeName);
                      }
                      _this.xmlForm.refreshFields();
                      _this.__lastIdTableSelected = data.idTable;
                    };
                    if (!data.idTable) {
                      return removeDragWrappers();
                    }
                    CUI.confirm({
                      text: $$("admin.metadata.mapping.object_type.confirm.label")
                    }).done(function() {
                      return removeDragWrappers();
                    }).fail(function() {
                      data.idTable = _this.__lastIdTableSelected;
                      return field.reload();
                    });
                  }
                }, {
                  ui: "metadata-profile-mapping-general-name-input",
                  type: CUI.MultiInput,
                  control: ez5.loca.getLanguageControlAdmin(),
                  user_selectable: ez5.session.getPref("languages_user_selection"),
                  form: {
                    label: $$("admin.metadata.mapping.name")
                  },
                  name: "displayname"
                }, _this.__getRecipeConfigField(types), {
                  ui: "metadata-profile-mapping-general-type-input",
                  type: CUI.Output,
                  form: {
                    label: $$("metadata.profile.mapping.profile_type.label")
                  },
                  text: types.join(", "),
                  placeholder: $$("metadata.profile.mapping.profile_type.placeholder")
                }
              ],
              data: _this.mapping
            }).start();
          };
        })(this)
      }
    ];
  };

  MetadataProfileMapping.prototype.__isExportMapping = function() {
    var types;
    types = this.father.getProfileTypes();
    return types.some((function(_this) {
      return function(type) {
        return type === "exiftool_export" || type === "xml_export" || type === "dc_export";
      };
    })(this));
  };

  return MetadataProfileMapping;

})(CUI.ListViewTreeNode);

CUI.ready((function(_this) {
  return function() {
    return CUI.Events.registerEvent({
      type: "metadata-mapping-field-click",
      bubble: true
    });
  };
})(this));
// Generated by CoffeeScript 1.12.7
var MetadataTagSelector,
  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;

MetadataTagSelector = (function(superClass) {
  extend(MetadataTagSelector, superClass);

  MetadataTagSelector.AUTOCOMPLETE_LIMIT = 100;

  MetadataTagSelector.prototype.initOpts = function() {
    MetadataTagSelector.__super__.initOpts.call(this);
    return this.addOpts({
      getTags: {
        "default": MetadataTagSelector.getTags,
        check: Function
      },
      metadata_type: {
        mandatory: true,
        check: (function(_this) {
          return function(value) {
            return value === "export" || value === "import";
          };
        })(this)
      },
      allow_custom: {
        "default": false,
        check: Boolean
      }
    });
  };

  function MetadataTagSelector(opts) {
    MetadataTagSelector.__super__.constructor.call(this, opts);
    this.__tagOptionsLabel = new CUI.Label({
      content: ""
    });
    return;
  }

  MetadataTagSelector.prototype.render = function() {
    var tags;
    MetadataTagSelector.__super__.render.call(this);
    this.__autocompletion.addContainer("all");
    tags = this._getTags();
    if (CUI.util.isPromise(tags)) {
      this.__getTagsPromise = tags;
    } else {
      this.__getTagsPromise = CUI.resolvedPromise(tags);
    }
    this.append(this.__tagOptionsLabel);
    return this;
  };

  MetadataTagSelector.prototype.__search = function() {
    var inputValue;
    inputValue = this.__input.value;
    return this.__getTagsPromise.done((function(_this) {
      return function(tags, namespaces) {
        if (namespaces == null) {
          namespaces = {};
        }
        tags = tags.filter(function(tag) {
          var _, ref, string, value;
          if (_this._metadata_type === "export") {
            if (CUI.util.isFalse(tag.writable) || !namespaces[tag.group]) {
              return false;
            }
          }
          string = tag.path.toUpperCase();
          ref = tag.description;
          for (_ in ref) {
            value = ref[_];
            string += "|" + (value.toUpperCase());
          }
          if (string.indexOf(inputValue.toUpperCase()) > -1) {
            return true;
          }
          if (inputValue.split(/\s+/).every(function(word) {
            return string.indexOf(word.toUpperCase()) > -1;
          })) {
            return true;
          }
          return false;
        });
        tags = tags.slice(0, MetadataTagSelector.AUTOCOMPLETE_LIMIT);
        _this.__show(tags);
        if (_this._allow_custom && inputValue.length > 0) {
          if (_this.__validateTag(inputValue)) {
            return _this.setValue({
              path: inputValue
            });
          }
        }
      };
    })(this));
  };

  MetadataTagSelector.prototype.__show = function(tags) {
    var fn, i, len, tag;
    this.__autocompletion.emptyContainer();
    if (!(tags != null ? tags.length : void 0) > 0) {
      this.__autocompletion.hide();
      return;
    }
    fn = (function(_this) {
      return function(tag) {
        var description, item, path;
        path = new CUI.Label({
          text: tag.path
        });
        description = new CUI.Label({
          text: ez5.loca.getBestFrontendValue(tag.description),
          appearance: "secondary",
          size: "mini"
        });
        item = _this.__autocompletion.appendItem("all", new CUI.VerticalList({
          content: [path, description]
        }));
        return CUI.Events.listen({
          type: "click",
          node: item,
          call: function() {
            _this.setValue(tag);
            _this.__autocompletion.hide();
          }
        });
      };
    })(this);
    for (i = 0, len = tags.length; i < len; i++) {
      tag = tags[i];
      fn(tag);
    }
    this.__autocompletion.show();
  };

  MetadataTagSelector.prototype.__validateTag = function(string) {
    return string.match(/^[a-zA-Z0-9_-]+:[a-zA-Z0-9_-]+$/);
  };

  MetadataTagSelector.prototype.displayValue = function() {
    var data, tagOptions;
    MetadataTagSelector.__super__.displayValue.call(this);
    CUI.dom.hideElement(this.__tagOptionsLabel);
    data = this.getValue();
    if (!data) {
      return;
    }
    tagOptions = MetadataTagSelector.getTagOptions(data);
    if (tagOptions.length === 0) {
      return;
    }
    this.__tagOptionsLabel.setContent(tagOptions);
    CUI.dom.showElement(this.__tagOptionsLabel);
    return this;
  };

  MetadataTagSelector.prototype.__getButtonLocaKey = function() {
    return "admin.metadata.mapping.tag.field.button";
  };

  MetadataTagSelector.prototype.__getInputPlaceholder = function() {
    return $$("admin.metadata.mapping.tag.field.button.placeholder");
  };

  MetadataTagSelector.prototype.__getDisplayText = function() {
    var ref;
    return (ref = this.getValue()) != null ? ref.path : void 0;
  };

  MetadataTagSelector.getTags = function() {
    var deferred;
    deferred = new CUI.Deferred();
    ez5.api.xmlmapping({
      api: '/tags',
      type: 'GET',
      withCredentials: ez5.version("6")
    }).done((function(_this) {
      return function(data) {
        var timestamp;
        timestamp = CUI.util.moment(data.timestamp).format('DD/MM/YYYY HH:mm:ss');
        console.debug("MetadataTagSelector :: Metadata mapping tags loaded. Timestamp: " + timestamp + ". Exiftool version: " + data.exiftool_version);
        return deferred.resolve(data.tags, data.xmlns);
      };
    })(this)).fail(deferred.reject);
    return deferred.promise();
  };

  MetadataTagSelector.getTagOptions = function(tag) {
    var attribute, i, len, ref, span, tagsOptions;
    tagsOptions = [];
    ref = ["printable", "rawValue", "list", "time", "date", "l10n"];
    for (i = 0, len = ref.length; i < len; i++) {
      attribute = ref[i];
      if (!tag[attribute]) {
        continue;
      }
      span = CUI.dom.span("ez5-tag");
      span.textContent = $$("admin.metadata.mapping.field.tag." + attribute);
      tagsOptions.push(span);
    }
    return tagsOptions;
  };

  return MetadataTagSelector;

})(SearchSelector);
// Generated by CoffeeScript 1.12.7
var MainList,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

MainList = (function(superClass) {
  extend(MainList, superClass);

  function MainList() {
    return MainList.__super__.constructor.apply(this, arguments);
  }

  MainList.is_allowed = function() {
    return ez5.session.hasSystemRight("root", "objectadmineditor");
  };

  MainList.label = function() {
    return "admin.menu.main_list";
  };

  MainList.path = function() {
    return ["lists"];
  };

  MainList.prototype.getAggregationSearchOpts = function(search) {
    return {
      data: {
        debug: "MainList.count_aggregation"
      },
      skip_connector: true,
      handle_error: (function(_this) {
        return function(xhr) {
          return true;
        };
      })(this),
      json_data: {
        aggregations: {
          _objecttype: {
            type: "term",
            limit: 10000,
            field: "_objecttype",
            sort: "term"
          }
        },
        search: search,
        limit: 0
      }
    };
  };

  MainList.prototype.getNodeClass = function() {
    return MainListNode;
  };

  MainList.prototype.loadLayout = function() {
    var dbInfo, tables, waitBlock;
    this.__loadLayout = new CUI.Deferred();
    this.mainLayout = new CUI.HorizontalLayout({
      "class": "ez5-main-layout ez5-event-poller",
      absolute: false,
      left: {
        "class": "ez5-main-left ez5-main-list-objecttypes",
        flexHandle: {
          "class": "ez5-main-left-flex-handle",
          label: {
            loca_key: "main.list.objecttypes.title",
            icon: "right",
            tooltip: {
              text: $$("main.list.objecttypes.title")
            }
          },
          state_name: "lists-left",
          hidden: false
        }
      },
      right: {
        "class": "ez5-main-right",
        flexHandle: {
          state_name: "lists-right",
          label: {
            text: ""
          },
          hidden: false,
          closed: true
        }
      }
    });
    ez5.rootLayout.replace(this.mainLayout, "center");
    this.empty();
    this.__pane = new CUI.Pane({
      "class": "ez5-main-list-pane cui-pane--window",
      absolute: true,
      top: {
        content: [
          new CUI.PaneHeader({
            left: {
              content: new CUI.Button({
                text: $$("main.list.objecttypes.title"),
                tooltip: {
                  text: $$("base.help.flex_handle.close|tooltip")
                },
                ui: "main.list.flex_handle_close.button",
                "class": "cui-pane-title-button",
                onClick: (function(_this) {
                  return function() {
                    return _this.getPaneFlexHandle().close();
                  };
                })(this)
              })
            },
            right: {
              content: {
                loca_key: "base.help.flex_handle.close",
                ui: "main.list.flex_handle_close.button",
                icon: "west",
                "class": "cui-pane-close-button",
                onClick: (function(_this) {
                  return function() {
                    return _this.getPaneFlexHandle().close();
                  };
                })(this)
              }
            }
          })
        ]
      }
    });
    this.mainLayout.replace(this.__pane, "left");
    this.sidebar = new Sidebar({
      mainLayout: this.mainLayout,
      getSearch: (function(_this) {
        return function() {
          return _this.search;
        };
      })(this)
    });
    this.__loadLayout.done((function(_this) {
      return function() {
        return waitBlock.destroy();
      };
    })(this));
    this.tree = new ListViewEditTree({
      ui: "main.list.list_view",
      cols: ["maximize", "auto"],
      "class": "ez5-main-list-tree",
      colClasses: ["ez5-main-list-tree-column-main", "ez5-main-list-tree-column-count ez5-list-view-column-count"],
      absolute: true,
      no_header: true,
      no_hierarchy: true,
      rowMove: false,
      selectableRows: true,
      focusable: true,
      onSelect: (function(_this) {
        return function(ev, info) {
          return _this.pushState();
        };
      })(this)
    });
    this.__pane.replace(this.tree.render(), "center");
    waitBlock = new CUI.WaitBlock({
      element: this.__pane.center()
    }).show();
    tables = ez5.schema.CURRENT.tables.filter(function(table) {
      return !table._instance;
    });
    if (tables.length === 0) {
      this.__nodes = [];
      this.tree.load_data(this.__nodes);
      this.__loadLayout.resolve();
      return this.__loadLayout;
    }
    dbInfo = new DbInfo();
    dbInfo.load().done((function(_this) {
      return function() {
        var makeAggregationSearch, ot, ot_counts, ot_id, ot_names_create, ot_names_read, search;
        ot_names_create = (function() {
          var ref, results;
          ref = dbInfo.getAvailableObjecttypes();
          results = [];
          for (ot_id in ref) {
            ot = ref[ot_id];
            results.push(ot.name);
          }
          return results;
        })();
        search = [];
        _this.__nodes = [];
        ot_names_read = [];
        ot_counts = {};
        makeAggregationSearch = function() {
          var search_opts;
          search_opts = _this.getAggregationSearchOpts(search);
          return ez5.api.search(search_opts).done(function(data) {
            var i, j, len, len1, ref, ref1, ref2, ref3, term;
            ot_names_read = [];
            ref = data.aggregations._objecttype.terms;
            for (i = 0, len = ref.length; i < len; i++) {
              term = ref[i];
              ot_names_read.push(term.term);
              ot_counts[term.term] = term.count;
            }
            ref1 = ez5.schema.CURRENT._objecttypes;
            for (j = 0, len1 = ref1.length; j < len1; j++) {
              ot = ref1[j];
              if ((ref2 = ot.name, indexOf.call(ot_names_read, ref2) >= 0) || (ref3 = ot.name, indexOf.call(ot_names_create, ref3) >= 0)) {
                (function(ot) {
                  var node, nodeClass;
                  nodeClass = _this.getNodeClass();
                  node = new nodeClass({
                    mainList: _this,
                    ui: "main.list.list_view.node:" + ot.name,
                    count: 0,
                    objecttype: ot,
                    text: ot._name_localized,
                    count: ot_counts[ot.name] || 0
                  });
                  _this.__nodes.push(node);
                  if (!_this.__startNode) {
                    return _this.__startNode = node;
                  } else if (_this.__startObjecttype === ot.name) {
                    return _this.__startNode = node;
                  }
                })(ot);
              }
            }
            _this.__nodes.sort(function(a, b) {
              return a.getSort().localeCompare(b.getSort());
            });
            _this.tree.load_data(_this.__nodes);
            _this.__loadLayout.resolve();
          });
        };
        return makeAggregationSearch();
      };
    })(this));
    return this.__loadLayout;
  };

  MainList.prototype.empty = function() {
    if (!this.mainLayout.isDestroyed()) {
      this.mainLayout.replace(new CUI.EmptyLabel({
        centered: true,
        text: $$("main.list.empty")
      }), "center");
    }
    return this.__empty = true;
  };

  MainList.prototype.pushState = function() {
    var ref, sel_node;
    sel_node = (ref = this.tree) != null ? ref.getSelectedNode() : void 0;
    if (!sel_node) {
      return MainList.__super__.pushState.call(this);
    } else if (this.__load_sid) {
      MainList.__super__.pushState.call(this, [sel_node.getObjecttype().name, this.__load_sid]);
      return this.__load_sid = null;
    } else {
      return MainList.__super__.pushState.call(this, [sel_node.getObjecttype().name]);
    }
  };

  MainList.prototype.update_path = function(path) {
    var i, len, load_gid, node, ref;
    load_gid = (function(_this) {
      return function() {
        var gid;
        gid = Main.getGlobalObjectIdFromLocation(document.location);
        if (!gid) {
          return;
        }
        return _this.collection.loadInSidebar({
          global_object_id: gid,
          push_state: false
        });
      };
    })(this);
    ref = this.tree.root.children;
    for (i = 0, len = ref.length; i < len; i++) {
      node = ref[i];
      if (path[1] !== node.getObjecttype().name) {
        continue;
      }
      if (node.isSelected()) {
        load_gid();
      } else {
        node.select().done(load_gid).fail((function(_this) {
          return function() {
            return _this.pushState();
          };
        })(this));
      }
      return;
    }
  };

  MainList.prototype.load = function(path) {
    if (path[1]) {
      this.__startObjecttype = path[1];
    }
    this.__startNode = null;
    return MainList.__super__.load.call(this, path).done((function(_this) {
      return function() {
        var ref;
        _this.__load_sid = document.location.pathname.split("/")[3];
        return (ref = _this.__startNode) != null ? ref.select().done(function() {
          return _this.loadDeepLink(_this.collection);
        }) : void 0;
      };
    })(this));
  };

  MainList.prototype.unload = function() {
    this.unloadSearch();
    return MainList.__super__.unload.call(this);
  };

  MainList.prototype.unloadSearch = function() {
    if (this.collection) {
      this.collection.destroy();
      this.collection = null;
    }
    if (this.search) {
      this.search.destroy();
      this.search = null;
    }
    this.sidebar.empty().hideSidebar();
    return this.empty();
  };

  MainList.prototype.loadSearch = function(node) {
    if (!this.mainLayout || this.mainLayout.isDestroyed()) {
      return CUI.rejectedPromise();
    }
    this.__objecttype = new Objecttype(node.getObjecttype());
    this.unloadSearch();
    this.collection = new CollectionMemory({
      sidebar: this.sidebar
    });
    this.search = new SearchList({
      objecttype: this.getObjecttype().name(),
      container: this.mainLayout.center(),
      collection: this.collection,
      sidebar: this.sidebar
    });
    this.collection.setSearch(this.search);
    return this.search.init().done((function(_this) {
      return function() {
        if (!_this.search) {
          return;
        }
        _this.search.execute();
        return _this.__empty = false;
      };
    })(this));
  };

  MainList.prototype.getObjecttype = function() {
    return this.__objecttype;
  };

  MainList.prototype.getPaneFlexHandle = function() {
    return CUI.dom.data(CUI.dom.closest(this.__pane.DOM, "[flex-handled-pane]"), "flexHandle");
  };

  return MainList;

})(Main);

ez5.session_ready(function() {
  return ez5.rootMenu.registerApp(MainList);
});
// Generated by CoffeeScript 1.12.7
var MainListNode,
  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;

MainListNode = (function(superClass) {
  extend(MainListNode, superClass);

  function MainListNode(opts) {
    this.opts = opts != null ? opts : {};
    MainListNode.__super__.constructor.call(this, this.opts);
    this.__countLabel = new CUI.Label();
    this.setupEventPoller();
  }

  MainListNode.prototype.setupEventPoller = function() {
    return EventPoller.listen({
      instance: this,
      filter: (function(_this) {
        return function(event) {
          return event.objecttype === _this._objecttype.name;
        };
      })(this),
      call: (function(_this) {
        return function(events) {
          var event, i, len;
          for (i = 0, len = events.length; i < len; i++) {
            event = events[i];
            if (event.type === "OBJECT_DELETE") {
              _this._count--;
            } else if (event.type === "OBJECT_INSERT" || event.type === "OBJECT_UNDELETE") {
              _this._count++;
            }
          }
          return _this.__updateCountLabel();
        };
      })(this)
    });
  };

  MainListNode.prototype.initOpts = function() {
    MainListNode.__super__.initOpts.call(this);
    return this.addOpts({
      mainList: {
        mandatory: true,
        check: MainList
      },
      count: {
        check: function(v) {
          return v >= 0;
        }
      },
      text: {
        check: String
      },
      objecttype: {
        check: "PlainObject"
      }
    });
  };

  MainListNode.prototype.getText = function() {
    return this._text;
  };

  MainListNode.prototype.getSort = function() {
    return this._text.toUpperCase();
  };

  MainListNode.prototype.getObjecttype = function() {
    return this._objecttype;
  };

  MainListNode.prototype.renderContent = function() {
    this.__updateCountLabel();
    this.addColumn(new CUI.ListViewColumn({
      element: this.__countLabel
    }));
    return new CUI.Label({
      text: this.getText()
    });
  };

  MainListNode.prototype.deselect = function(ev, row) {
    if (ev && row === this) {
      return CUI.rejectedPromise();
    }
    return MainListNode.__super__.deselect.call(this, ev);
  };

  MainListNode.prototype.select = function(ev) {
    return CUI.chainedCall(MainListNode.__super__.select.call(this, ev), (function(_this) {
      return function() {
        return _this._mainList.loadSearch(_this);
      };
    })(this));
  };

  MainListNode.prototype.__updateCountLabel = function() {
    if (this._count < 0) {
      this._count = 0;
    }
    return this.__countLabel.setText(ez5.format_number(this._count));
  };

  MainListNode.prototype.setCount = function(newCount) {
    this._count = newCount;
    return this.__updateCountLabel();
  };

  return MainListNode;

})(ListViewEditTreeNode);
// 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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

ez5.ObjecttypeMainList = (function(superClass) {
  extend(ObjecttypeMainList, superClass);

  ObjecttypeMainList.is_allowed = function() {
    return true;
  };

  ObjecttypeMainList.label = function() {
    return this.objecttype || this.constructor.objecttype;
  };

  ObjecttypeMainList.documentTitle = function() {
    var objecttype;
    objecttype = ez5.schema.CURRENT._table_by_name[this.label()]._name_localized;
    return $$("root.menu.list.objecttype", {
      objecttype: objecttype
    });
  };

  ObjecttypeMainList.group = function() {
    return "aa_main_" + this.icon;
  };

  ObjecttypeMainList.path = function() {
    return ["lists/" + (this.label())];
  };

  ObjecttypeMainList.submenu = function() {
    if (this.hasSubmenu) {
      return this.group();
    } else {
      return "root";
    }
  };

  ObjecttypeMainList.getSubmenuKey = function() {};

  ObjecttypeMainList.getSubmenuText = function() {
    return $$("root.menu.list.objecttype.submenu");
  };

  ObjecttypeMainList.getSubmenuTooltip = function() {
    return this.getSubmenuText();
  };

  ObjecttypeMainList.getSubmenuIcon = function() {
    return this.icon;
  };

  ObjecttypeMainList.getMenuButton = function() {
    var button;
    button = ObjecttypeMainList.__super__.constructor.getMenuButton.call(this);
    delete button.loca_key;
    button.text = this.documentTitle();
    button.tooltip = {
      text: button.text
    };
    if (!this.hasSubmenu) {
      button.icon = this.icon;
    }
    return button;
  };

  function ObjecttypeMainList(opts) {
    this.opts = opts;
    ObjecttypeMainList.__super__.constructor.call(this, this.opts);
    this.__cls = this.getObjectClass();
    return this;
  }

  ObjecttypeMainList.prototype.getObjectClass = function() {
    return "ObjecttypeMainList" + (this.getObjecttypeName());
  };

  ObjecttypeMainList.prototype.setTitle = function() {
    var objecttype;
    ObjecttypeMainList.__super__.setTitle.call(this);
    objecttype = ez5.schema.CURRENT._table_by_name[this.getObjecttypeName()]._name_localized;
    return ObjecttypeMainList.__super__.setTitle.call(this, "root.menu.list.objecttype", {
      objecttype: objecttype
    });
  };

  ObjecttypeMainList.prototype.getObjecttypeName = function() {
    return this.constructor.objecttype;
  };

  ObjecttypeMainList.prototype.loadLayout = function() {
    this.mainLayout = new CUI.HorizontalLayout({
      "class": "ez5-main-layout ez5-event-poller",
      absolute: false,
      right: {
        "class": "ez5-main-right",
        flexHandle: {
          state_name: "lists-right",
          label: {
            text: ""
          },
          hidden: false,
          closed: true
        }
      }
    });
    ez5.rootLayout.replace(this.mainLayout, "center");
    this.sidebar = new Sidebar({
      mainLayout: this.mainLayout,
      getSearch: (function(_this) {
        return function() {
          return _this.search;
        };
      })(this)
    });
    this.collection = new CollectionMemory({
      sidebar: this.sidebar
    });
    this.search = new SearchList({
      objecttype: this.getObjecttypeName(),
      container: this.mainLayout.center(),
      collection: this.collection,
      sidebar: this.sidebar
    });
    this.collection.setSearch(this.search);
    this.search.init().done((function(_this) {
      return function() {
        if (!_this.search) {
          return;
        }
        return _this.search.execute();
      };
    })(this));
    return CUI.resolvedPromise();
  };

  ObjecttypeMainList.reloadIcons = function(promptUserReload) {
    var btn, i, icon, len, objecttype, ref, reloadPrompt;
    if (promptUserReload == null) {
      promptUserReload = false;
    }
    if (promptUserReload) {
      reloadPrompt = new CUI.Alert({
        title: $$("admin.objecttype.update_main_menu.title"),
        text: $$("admin.objecttype.update_main_menu.text"),
        cancel: true,
        button_text_ok: $$("admin.objecttype.update_main_menu.button")
      });
      reloadPrompt.open().done((function(_this) {
        return function() {
          return document.location.reload();
        };
      })(this));
      return;
    }
    ref = ez5.objecttypes.getObjecttypes();
    for (i = 0, len = ref.length; i < len; i++) {
      objecttype = ref[i];
      icon = objecttype.objecttype.show_in_main_menu_with_icon;
      if (icon) {
        btn = ez5.rootMenu.__app_button_by_unique_id[objecttype.objecttype.name];
        if (btn.hasClass("ez5-root-menu-submenu-button")) {
          continue;
        }
        if (btn != null) {
          btn.setIcon(icon);
        }
      }
    }
  };

  return ObjecttypeMainList;

})(MainList);

ez5.defaults_done(function() {
  var checkAvailableObjecttypes, enabledInMainMenuObjecttypes, groupQuantity, i, icon, len, loadMainListObjectsApps, objectsWithRecords, objecttype, ref;
  enabledInMainMenuObjecttypes = {};
  groupQuantity = {};
  objectsWithRecords = [];
  checkAvailableObjecttypes = (function(_this) {
    return function() {
      var dfr, fn, icon, objectsChecksPromises, objecttypeName;
      dfr = new CUI.Deferred;
      objectsChecksPromises = [];
      fn = function(objecttypeName) {};
      for (objecttypeName in enabledInMainMenuObjecttypes) {
        icon = enabledInMainMenuObjecttypes[objecttypeName];
        fn(objecttypeName);
        objectsChecksPromises.push(ez5.api.search({
          json_data: {
            limit: 1,
            format: "short",
            objecttypes: [objecttypeName],
            generate_rights: false
          },
          data: {
            debug: "ObjecttypeMainListCheck"
          }
        }).done(function(result) {
          if ((result != null ? result.count : void 0) > 0) {
            return objectsWithRecords.push(result.objecttypes[0]);
          }
        }));
      }
      CUI.whenAll(objectsChecksPromises).always(function() {
        return dfr.resolve();
      });
      return dfr;
    };
  })(this);
  ref = ez5.objecttypes.getObjecttypes();
  for (i = 0, len = ref.length; i < len; i++) {
    objecttype = ref[i];
    icon = objecttype.objecttype.show_in_main_menu_with_icon;
    if (icon) {
      enabledInMainMenuObjecttypes[objecttype.objecttype.name] = objecttype;
      if (!groupQuantity[icon]) {
        groupQuantity[icon] = 0;
      }
      groupQuantity[icon]++;
    }
  }
  loadMainListObjectsApps = (function(_this) {
    return function() {
      var _class, _objecttype, fn, j, len1, objecttypeMainListClasses, objecttypeName, ref1;
      objecttypeMainListClasses = [];
      fn = function(objecttypeName) {
        var _class;
        icon = _objecttype.objecttype.show_in_main_menu_with_icon;
        _class = (function(superClass) {
          extend(_Class, superClass);

          function _Class() {
            return _Class.__super__.constructor.apply(this, arguments);
          }

          return _Class;

        })(ez5.ObjecttypeMainList);
        _class.objecttype = objecttypeName;
        _class.icon = icon;
        _class.hasSubmenu = groupQuantity[icon] > 1;
        _class.locaName = ez5.schema.CURRENT._table_by_name[objecttypeName]._name_localized;
        window["ObjecttypeMainList" + objecttypeName] = _class;
        return objecttypeMainListClasses.push(_class);
      };
      for (objecttypeName in enabledInMainMenuObjecttypes) {
        _objecttype = enabledInMainMenuObjecttypes[objecttypeName];
        if (indexOf.call(objectsWithRecords, objecttypeName) < 0) {
          continue;
        }
        if (!ez5.version("6") && ((ref1 = ez5.rootMenu.getApps()) != null ? ref1.some(function(app) {
          return app.objecttype === objecttypeName;
        }) : void 0)) {
          continue;
        }
        fn(objecttypeName);
      }
      if (objecttypeMainListClasses.length > 0) {
        objecttypeMainListClasses.sort(function(a, b) {
          return a.locaName.localeCompare(b.locaName);
        });
        for (j = 0, len1 = objecttypeMainListClasses.length; j < len1; j++) {
          _class = objecttypeMainListClasses[j];
          ez5.rootMenu.registerApp(_class);
        }
        ez5.rootMenu.loadApps();
      }
    };
  })(this);
  if (!CUI.util.isEmpty(enabledInMainMenuObjecttypes)) {
    checkAvailableObjecttypes().done((function(_this) {
      return function() {
        return loadMainListObjectsApps();
      };
    })(this));
  }
});
// Generated by CoffeeScript 1.12.7
var ResultList,
  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;

ResultList = (function(superClass) {
  extend(ResultList, superClass);

  function ResultList() {
    return ResultList.__super__.constructor.apply(this, arguments);
  }

  ResultList.prototype.__page_size = 50;

  ResultList.prototype.__page_sizes = [10, 25, 50, 100, 1000];

  ResultList.prototype.getName = function() {
    return "result-list";
  };

  ResultList.prototype.__getColsAndHeaders = function(data, standard_only) {
    if (standard_only == null) {
      standard_only = false;
    }
    return ResultList.__super__.__getColsAndHeaders.call(this, data, true);
  };

  ResultList.prototype.renderResultObject = function(result_object, group) {
    var element, ref, ref1;
    if (group === "standard") {
      element = result_object.renderCardResultList();
    } else {
      element = ResultList.__super__.renderResultObject.call(this, result_object, group);
    }
    CUI.dom.setAttribute(element, "ui", "result.list.object");
    if (((ref = this._selectable_opts) != null ? ref.isSelectable : void 0) && !((ref1 = this._selectable_opts) != null ? ref1.isSelectable(result_object != null ? result_object.data : void 0) : void 0)) {
      CUI.dom.addClass(element, "is-not-selectable");
    }
    return element;
  };

  ResultList.prototype.getAdditionalViewFields = function() {
    return [];
  };

  ResultList.prototype.getObjectFormatNeeded = function() {
    return "standard";
  };

  ResultList.prototype.filterTopLevel = function() {
    return true;
  };

  ResultList.prototype.__addTopLevelPlaceholder = function(nodes) {
    var top_level_node;
    if (this._allowTopLevelPlaceholder) {
      top_level_node = new ResultTableNode({
        resultTable: this,
        object: {
          _global_object_id: "0",
          _system_object_id: 0
        },
        cols: this.__info.cols,
        field_per_column: this.__info.field_per_column,
        offset: 0
      });
      if (nodes.length > 0) {
        return nodes.unshift(top_level_node);
      }
    }
  };

  ResultList.prototype.getNodesFromData = function(data) {
    var nodes, ref;
    this._open_nodes = this.hasSearchInput();
    if (this._open_nodes && (!(this.getSearch().getSearchHierarchyManager) || !((ref = this.getSearch().getSearchHierarchyManager()) != null ? ref.isFlatHierarchy() : void 0))) {
      nodes = this.getNodesFromDataTree(data);
    } else if (this.getSearch().isTrashModeActive()) {
      nodes = this.getNodesFromDataFlatNoHierarchy(data);
    } else {
      nodes = this.getNodesFromDataFlat(data);
    }
    this.__addTopLevelPlaceholder(nodes);
    return nodes;
  };

  ResultList.prototype.addToRequest = function(request) {
    ResultList.__super__.addToRequest.call(this, request);
    return this;
  };

  ResultList.prototype.__searchHasObjecttypes = function() {
    return !(this.getSearch() instanceof SearchCollection);
  };

  return ResultList;

})(ResultTable);
// Generated by CoffeeScript 1.12.7
var SearchList,
  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;

SearchList = (function(superClass) {
  extend(SearchList, superClass);

  function SearchList() {
    return SearchList.__super__.constructor.apply(this, arguments);
  }

  SearchList.prototype.initOpts = function() {
    SearchList.__super__.initOpts.call(this);
    return this.addOpts({
      collection: {
        mandatory: true,
        check: Collection
      },
      container: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isElement(v);
        }
      },
      sidebar: {
        check: Sidebar
      },
      objecttype: {
        mandatory: true,
        check: String
      },
      create_button: {
        "default": true,
        check: Boolean
      },
      show_deleted: {
        "default": false,
        check: Boolean
      },
      getSharePath: {
        check: Function,
        mandatory: false
      },
      header: {
        check: function(v) {
          return CUI.util.isElement(v);
        }
      }
    });
  };

  SearchList.prototype.readOpts = function() {
    SearchList.__super__.readOpts.call(this);
    this.otm = new ObjecttypeManager();
    return this.otm.addObjecttypes((function(_this) {
      return function(table) {
        return table.name() === _this._objecttype;
      };
    })(this));
  };

  SearchList.prototype.execute = function(request) {
    var objecttype;
    objecttype = this.getObjecttype();
    if (!objecttype) {
      return CUI.resolvedPromise();
    }
    return SearchList.__super__.execute.call(this, request);
  };

  SearchList.prototype.init = function() {
    var i, len, managers, objecttype, ot, ot_names, paneHeader, plusButton, ref, resultManager, sts, vl;
    objecttype = this.getObjecttype();
    if (!objecttype) {
      CUI.dom.replace(this._container, new CUI.EmptyLabel({
        text: $$("search.list.objecttype_no_masks"),
        centered: true
      }));
      return CUI.resolvedPromise();
    }
    if (this._header) {
      paneHeader = this._header;
    } else {
      paneHeader = new CUI.PaneHeader({
        left: {
          content: new CUI.Label({
            text: $$("search.list.title", {
              objecttype: objecttype.nameLocalized()
            })
          })
        }
      });
    }
    this.__buttonToolbar = new CUI.PaneToolbar({
      "class": "ez5-search-list-main-button-toolbar"
    });
    ot_names = [];
    ref = this.getSearchObjecttypes();
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      if (ot.poolLink()) {
        ot_names.push(ot.name());
      }
    }
    if (ot_names.length) {
      this.__searchTypeSelector = sts = new SearchTypeSelector({
        pref_name: "search_type_selector_" + ot_names.join("_"),
        objecttypes: this.getSearchObjecttypes(),
        show_connector: false
      });
      this.addSearchManager(sts);
    } else {
      sts = null;
    }
    this.__searchInput = new SearchInput({
      expert: this,
      searchTypeSelector: sts,
      input_opts: {
        "aria-labelledby": "list-search-button"
      }
    });
    if (this._create_button && this._sidebar) {
      plusButton = new LocaButton({
        "class": "ez5-search-list-button-new-objects",
        loca_key: "search.list.button.new_objects",
        group: "add_records",
        ui: "search.list.add_object.button",
        disabled: true,
        onClick: (function(_this) {
          return function() {
            var ref1;
            return (ref1 = _this._sidebar.loadEditor({
              table_id: _this.getSearchObjecttypes()[0].id(),
              search: _this
            })) != null ? ref1.done(function() {
              return _this._sidebar.showSidebar();
            }) : void 0;
          };
        })(this)
      });
    }
    vl = new CUI.VerticalLayout({
      top: {
        content: null
      }
    });
    this.__mainSearch = new CUI.HorizontalLayout({
      "class": "ez5-tmp-mainSearch",
      absolute: true,
      left: {
        "class": "ez5-facet-manager",
        flexHandle: {
          hidden: true,
          state_name: "search-main-facets",
          closed: true
        }
      },
      center: {
        content: vl
      }
    });
    this.__pane = new CUI.Pane({
      "class": "ez5-search-list-pane cui-pane--window",
      absolute: true,
      top: {
        content: [paneHeader, this.__searchInput.getInputLayout(), this.__buttonToolbar]
      },
      center: {
        content: this.__mainSearch
      },
      bottom: false
    });
    CUI.dom.replace(this._container, this.__pane);
    this.rc = vl.center();
    this.addSearchManager(this.__searchInput);
    this.__searchInput.addPlaceholder();
    this.__searchInput.getInputLayout().append(this.getSearchButton(), "right", false);
    CUI.Events.listen({
      node: this.rc,
      type: "toolbox",
      call: (function(_this) {
        return function(ev, info) {
          return info.tools.push.apply(info.tools, _this.getCurrentTools());
        };
      })(this)
    });
    this.__facetManager = new FacetManager();
    this.facetBtns = [];
    this.facetButton = this.__initFacetButton("list");
    this.facetSettingsBtn = new LocaButton({
      ui: "result.manager.view.options.button",
      "class": "ez5-result-manager-button-options",
      loca_key: "result.manager.button.options",
      group: "facet",
      onClick: (function(_this) {
        return function() {
          return _this.showFacetSettingsPopover();
        };
      })(this)
    });
    this.facetBtns.push(this.facetButton, this.facetSettingsBtn);
    this.__buttonToolbar.append(this.facetBtns, "left");
    this.addSearchManager(this.__facetManager);
    this.registerResultContainer(this.rc);
    this._collection.on({
      type: ["remove", "insert", "select"],
      instance: this,
      call: (function(_this) {
        return function(ev, info) {
          if (info.skip_update) {
            return;
          }
          return _this.updateFlyoutButtonbar();
        };
      })(this)
    });
    managers = [];
    if (ez5.version("6") && ez5.schema.CURRENT._table_by_name[this._objecttype].in_main_search) {
      managers.push(new ResultStandard({
        ui: "search.list.result.standard",
        container: this.rc,
        navigation_buttons_left: [plusButton],
        selectable_opts: {
          collection: this._collection
        }
      }));
      managers.push(new ResultText({
        ui: "search.list.result.text",
        container: this.rc,
        navigation_buttons_left: [plusButton],
        selectable_opts: {
          collection: this._collection
        }
      }));
    }
    managers.push(new ResultList({
      ui: "search.list.result.list",
      container: this.rc,
      navigation_buttons_left: [plusButton],
      selectable_opts: {
        draggable: false,
        collection: this._collection
      }
    }));
    if (!!!this._show_deleted) {
      managers.push(new ez5.ResultTableV2({
        ui: "search.list.result.table",
        container: this.rc,
        navigation_buttons_left: [plusButton],
        selectable_opts: {
          collection: this._collection
        }
      }));
    }
    resultManager = new ResultManager({
      pref: "search_list_view_data",
      managers: managers
    });
    this.addSearchManager(resultManager);
    this.addSearchManager(new CollectionSearchManager({
      getPageSize: function() {
        return resultManager.getCurrentViewData().page_size;
      },
      collection: this._collection
    }));
    this.__searchHierarchyManager = new SearchListHierarchyManager({
      container: vl.top(),
      searchInput: this.getSearchInput(),
      savePrefName: "search_list_hierarchy_manager"
    });
    this.addSearchManager(this.__searchHierarchyManager);
    this.addSearchManager(new SortManager({
      pref: "search_list_sort_data"
    }));
    if (this._show_deleted && TrashSearchManager.canSeeDeleted()) {
      this.addSearchManager(new TrashSearchManager({
        active: true
      }));
    }
    this.registerKeyboardShortcuts(this._container);
    return Search.prototype.init.call(this).done((function(_this) {
      return function() {
        CUI.Events.trigger({
          type: "content-resize",
          node: _this.__pane.top()
        });
        if (!plusButton) {
          return;
        }
        _this.canCreateSearchObjecttypes().done(function() {
          return plusButton.enable();
        });
        if (ez5.session.getPref("search.list.filter")) {
          return _this.facetButton.activate({
            initial_activate: true
          });
        }
      };
    })(this));
  };

  SearchList.prototype.getCurrentTools = function() {
    var tools;
    tools = SearchList.__super__.getCurrentTools.call(this);
    if (this._show_deleted) {
      return this.getTrashModeTools(tools);
    }
    return tools;
  };

  SearchList.prototype.getTrashModeTools = function(original_tools) {
    var i, len, tool, tool_name, trash_tools;
    trash_tools = [];
    for (i = 0, len = original_tools.length; i < len; i++) {
      tool = original_tools[i];
      tool_name = tool.getName();
      if (tool_name.includes("show.fullscreen") || tool_name.includes("refresh") || tool_name.includes("present_share_url")) {
        trash_tools.push(tool);
      } else if (tool_name.includes("selection.all") || tool_name.includes("selection.page") || tool_name.includes("selection.clear")) {
        trash_tools.push(tool);
      }
    }
    return trash_tools;
  };

  SearchList.prototype.getFacetsContainer = function() {
    return this.__mainSearch.left();
  };

  SearchList.prototype.runFirstSearch = function() {
    return this.execute();
  };

  SearchList.prototype.getSharePath = function() {
    if (this._getSharePath != null) {
      return this._getSharePath();
    }
    return window.easydb_base_prefix + "#lists/" + encodeURI(this.getObjecttype().name());
  };

  SearchList.prototype.getDetailShareUrl = function(id) {
    return this.getSharePath() + "/" + id;
  };

  SearchList.prototype.addToRequest = function(request) {
    return SearchList.__super__.addToRequest.call(this, request);
  };

  SearchList.prototype.getSearchObjecttypes = function() {
    return this.otm.objecttypes;
  };

  SearchList.prototype.getObjecttype = function() {
    return this.getSearchObjecttypes()[0];
  };

  SearchList.prototype.getPane = function() {
    return this.__pane;
  };

  SearchList.prototype.getSearchInput = function() {
    return this.__searchInput;
  };

  SearchList.prototype.getButtonToolbar = function() {
    return this.__buttonToolbar;
  };

  SearchList.prototype.hasUserInput = function(request, excludedSearchManager) {
    if (excludedSearchManager == null) {
      excludedSearchManager = [];
    }
    return SearchList.__super__.hasUserInput.call(this, request, excludedSearchManager);
  };

  SearchList.prototype.getDefaultSortFilter = function() {
    return [
      {
        "field": "_standard.1.text",
        "order": "ASC",
        "_level": 0
      }
    ];
  };

  SearchList.prototype.getDefaultSortKey = function() {
    return "main.search.sort.standard";
  };

  SearchList.prototype.getShareUrl = function() {};

  SearchList.prototype.getSearchButtonOpts = function() {
    var opts;
    opts = SearchList.__super__.getSearchButtonOpts.call(this);
    opts.id = "list-search-button";
    return opts;
  };

  SearchList.prototype.getAvailableMaskNames = function() {
    if (this.getSearchTypeSelector()) {
      return this.getSearchTypeSelector().getMaskNames();
    } else {
      return this.getSearchBasics().getMaskNames();
    }
  };

  return SearchList;

})(SearchMain);
// Generated by CoffeeScript 1.12.7
var TrashMainList,
  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;

TrashMainList = (function(superClass) {
  extend(TrashMainList, superClass);

  function TrashMainList() {
    return TrashMainList.__super__.constructor.apply(this, arguments);
  }

  TrashMainList.is_allowed = function() {
    return TrashSearchManager.canSeeDeleted();
  };

  TrashMainList.label = function() {
    return "admin.menu.trash_list";
  };

  TrashMainList.group = function() {
    return "zzz_trash";
  };

  TrashMainList.isBottomApp = function() {
    return true;
  };

  TrashMainList.path = function() {
    return ["trash"];
  };

  TrashMainList.prototype.getAggregationSearchOpts = function(search) {
    var opts;
    opts = TrashMainList.__super__.getAggregationSearchOpts.call(this, search);
    opts.json_data.include_deleted = true;
    opts.json_data.search.push({
      type: "in",
      bool: "must_not",
      fields: ["_latest_version_deleted_at"],
      "in": [null]
    });
    return opts;
  };

  TrashMainList.prototype.loadSearch = function(node) {
    if (!this.mainLayout || this.mainLayout.isDestroyed()) {
      return CUI.rejectedPromise();
    }
    this.__objecttype = new Objecttype(node.getObjecttype());
    this.unloadSearch();
    this.collection = new CollectionMemory({
      sidebar: this.sidebar
    });
    this.search = new SearchList({
      objecttype: this.getObjecttype().name(),
      container: this.mainLayout.center(),
      collection: this.collection,
      sidebar: this.sidebar,
      create_button: false,
      show_deleted: true,
      getSharePath: (function(_this) {
        return function() {
          return _this.getSharePath();
        };
      })(this),
      header: this.__getSearchHeader()
    });
    this.collection.setSearch(this.search);
    return this.search.init().done((function(_this) {
      return function() {
        if (!_this.search) {
          return;
        }
        _this.enableTrashMode();
        _this.search.execute();
        return _this.__empty = false;
      };
    })(this));
  };

  TrashMainList.prototype.__getSearchHeader = function() {
    return new CUI.PaneHeader({
      left: {
        content: new LocaLabel({
          loca_key: "main.trash.search.header"
        })
      }
    }).DOM;
  };

  TrashMainList.prototype.enableTrashMode = function() {
    var i, len, ref, results, sm;
    ref = this.search.getSearchManagers();
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      sm = ref[i];
      if (sm instanceof TrashSearchManager) {
        sm.setActive(true);
        break;
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  TrashMainList.prototype.getNodeClass = function() {
    return TrashMainListNode;
  };

  TrashMainList.prototype.loadLayout = function() {
    return TrashMainList.__super__.loadLayout.call(this).done((function(_this) {
      return function() {
        var paneHeader;
        if (_this.__pane) {
          paneHeader = new CUI.PaneHeader({
            left: {
              content: new CUI.Button({
                text: $$("main.trash.objecttypes.title"),
                tooltip: {
                  text: $$("base.help.flex_handle.close|tooltip")
                },
                ui: "main.list.flex_handle_close.button",
                "class": "cui-pane-title-button",
                onClick: function() {
                  return _this.getPaneFlexHandle().close();
                }
              })
            },
            right: {
              content: {
                loca_key: "base.help.flex_handle.close",
                ui: "main.list.flex_handle_close.button",
                icon: "west",
                "class": "cui-pane-close-button",
                onClick: function() {
                  return _this.getPaneFlexHandle().close();
                }
              }
            }
          });
          return _this.__pane.replace(paneHeader, "top");
        }
      };
    })(this));
  };

  TrashMainList.prototype.empty = function() {
    if (!this.mainLayout.isDestroyed()) {
      this.mainLayout.replace(new CUI.EmptyLabel({
        centered: true,
        text: $$("main.trash.empty")
      }), "center");
    }
    return this.__empty = true;
  };

  TrashMainList.prototype.getSharePath = function() {
    return window.easydb_base_prefix + "#trash/" + encodeURI(this.getObjecttype().name());
  };

  TrashMainList.prototype.getDetailShareUrl = function(id) {
    return this.getSharePath() + "/" + id;
  };

  TrashMainList.prototype.getPaneFlexHandle = function() {
    return CUI.dom.data(CUI.dom.closest(this.__pane.DOM, "[flex-handled-pane]"), "flexHandle");
  };

  return TrashMainList;

})(MainList);

ez5.session_ready(function() {
  return ez5.rootMenu.registerApp(TrashMainList);
});
// Generated by CoffeeScript 1.12.7
var TrashMainListNode,
  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;

TrashMainListNode = (function(superClass) {
  extend(TrashMainListNode, superClass);

  function TrashMainListNode() {
    return TrashMainListNode.__super__.constructor.apply(this, arguments);
  }

  TrashMainListNode.prototype.setupEventPoller = function() {
    return EventPoller.listen({
      instance: this,
      filter: (function(_this) {
        return function(event) {
          return event.objecttype === _this._objecttype.name;
        };
      })(this),
      call: (function(_this) {
        return function(events) {
          var event, i, len;
          for (i = 0, len = events.length; i < len; i++) {
            event = events[i];
            if (event.type === "OBJECT_DELETE") {
              _this._count++;
            } else if (event.type === "OBJECT_UNDELETE" || event.type === "OBJECT_PURGE") {
              _this._count--;
            }
          }
          return _this.__updateCountLabel();
        };
      })(this)
    });
  };

  return TrashMainListNode;

})(MainListNode);
// Generated by CoffeeScript 1.12.7
var PluginManagerApp,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

PluginManagerApp = (function(superClass) {
  extend(PluginManagerApp, superClass);

  function PluginManagerApp() {
    return PluginManagerApp.__super__.constructor.apply(this, arguments);
  }

  PluginManagerApp.label = function() {
    return "admin.menu.pluginmanager";
  };

  PluginManagerApp.group = function() {
    return "zzg_administration";
  };

  PluginManagerApp.submenu = function() {
    return "administration";
  };

  PluginManagerApp.path = function() {
    return ["pluginmanager"];
  };

  PluginManagerApp.is_allowed = function() {
    return ez5.session.hasSystemRight("root", "plugin");
  };

  PluginManagerApp.prototype.readOpts = function() {
    PluginManagerApp.__super__.readOpts.call(this);
    return this.config = [];
  };

  PluginManagerApp.prototype.getPlusButton = function() {
    return {
      icon: "plus",
      group: "plus-minus",
      onClick: (function(_this) {
        return function() {
          return _this.showPluginUpload();
        };
      })(this)
    };
  };

  PluginManagerApp.prototype.addRow = function(item) {
    return this.tree.addNode(item).done((function(_this) {
      return function() {
        return item.select();
      };
    })(this));
  };

  PluginManagerApp.prototype.showPluginUpload = function() {
    var data, item, mod;
    data = {};
    item = new PluginManagerAppItem({
      manager: this,
      plugin: data
    });
    mod = new CUI.Modal({
      pane: {
        title: $$("plugin.manager.app.list.upload.title"),
        padded: true,
        content: item.getTypeForm(true),
        footer_right: new CUI.Button({
          text: "Save",
          primary: true,
          onClick: (function(_this) {
            return function(ev) {
              return item.save(ev).done(function() {
                return _this.addRow(item).done(function() {
                  return document.location.reload();
                });
              }).fail(function() {
                console.error("Failed to save plugin");
                return mod.destroy();
              });
            };
          })(this)
        })
      },
      cancel: true
    });
    mod.show();
    return item.setStatus();
  };

  PluginManagerApp.prototype.getMissingLabel = function() {
    return new CUI.EmptyLabel({
      centered: true,
      text: $$("plugin.manager.app.no_plugin")
    });
  };

  PluginManagerApp.prototype.getCenterTitle = function() {
    var displayname, ref, ref1, ref2, ref3, ref4, ref5, ref6;
    displayname = ez5.loca.getBestFrontendValue((ref = this.tree) != null ? (ref1 = ref.getSelectedNode()) != null ? (ref2 = ref1._plugin) != null ? (ref3 = ref2.manifest) != null ? ref3.displayname : void 0 : void 0 : void 0 : void 0) || ((ref4 = this.tree) != null ? (ref5 = ref4.getSelectedNode()) != null ? (ref6 = ref5._plugin) != null ? ref6.name : void 0 : void 0 : void 0);
    if (!CUI.util.isEmpty(displayname)) {
      return displayname;
    }
    return $$("plugin.manager.app.pane.plugin");
  };

  PluginManagerApp.prototype.getLeftTitle = function() {
    return $$("plugin.manager.app.pane.title");
  };

  PluginManagerApp.prototype.getTreeOpts = function() {
    var opts;
    opts = PluginManagerApp.__super__.getTreeOpts.call(this);
    opts.onSort = (function(_this) {
      return function(key, order) {
        var field;
        field = key.replace("plugin.", "");
        _this.__sortField = field;
        _this.__sortOrder = order;
        _this.loadTree(true);
      };
    })(this);
    opts.filterManager = (function(_this) {
      return function() {
        var filter_form, input, lay;
        input = ListViewEditTree.getFilterManager(function(filter) {
          _this.__filter_data.search = filter;
          return _this.loadFilter();
        });
        filter_form = new CUI.FormPopover({
          data: _this.__filter_data,
          fields: function() {
            var c, columnOptions, columnsField, fields, i, len, ref;
            fields = [
              {
                type: CUI.Checkbox,
                form: {
                  label: $$("plugin.manager.filter.show_enabled")
                },
                name: "show_enabled"
              }, {
                type: CUI.Checkbox,
                form: {
                  label: $$("plugin.manager.filter.show_disabled")
                },
                name: "show_disabled"
              }
            ];
            columnOptions = [];
            ref = _this._valid_columns;
            for (i = 0, len = ref.length; i < len; i++) {
              c = ref[i];
              columnOptions.push({
                text: $$("plugin.manager.app.list." + c + "|text"),
                value: c
              });
            }
            columnsField = {
              type: CUI.Options,
              form: {
                label: $$("plugin.manager.filter.columns")
              },
              name: "columns",
              horizontal: false,
              sortable: true,
              options: columnOptions,
              onDataChanged: function(data) {
                if (data["columns"].length === 0) {
                  data["columns"] = ["name"];
                }
                CUI.Events.trigger({
                  type: "viewport-resize",
                  node: filter_form.DOM
                });
                ez5.session.savePref("pluginmanager-columns", _this.__filter_data.columns);
                _this.load();
              }
            };
            fields.push(columnsField);
            return fields;
          },
          trigger_data_changed_while_open: true,
          button: {
            "class": "ez5-plugin-manager-filter-button",
            loca_key: "plugin.manager.filter.button"
          },
          onDataChanged: function() {
            return _this.loadFilter();
          }
        });
        lay = new CUI.HorizontalLayout({
          "class": "ez5-filter-manager",
          center: {
            content: [input]
          },
          right: {
            content: filter_form.start()
          }
        });
        return lay;
      };
    })(this);
    return opts;
  };

  PluginManagerApp.prototype.initFilterData = function() {
    var column, columns, i, len;
    this._valid_columns = ["name", "displayname", "type", "enabled", "updated_at"];
    if (this.__filter_data) {
      this.__filter_data.search = "";
      return;
    }
    columns = ez5.session.getPref("pluginmanager-columns") || [];
    for (i = 0, len = columns.length; i < len; i++) {
      column = columns[i];
      if (indexOf.call(this._valid_columns, column) < 0) {
        columns.splice(columns.indexOf(column), 1);
      }
    }
    if (CUI.util.isEmpty(columns)) {
      columns = ["name", "type", "enabled"];
    }
    this.__filter_data = {
      search: "",
      show_enabled: true,
      show_disabled: true,
      columns: columns
    };
  };

  PluginManagerApp.prototype.loadFilter = function(__filter, opts) {
    this.__filter = __filter;
    if (opts == null) {
      opts = {};
    }
    return this.loadList(this.__filter_data.search, opts).done((function(_this) {
      return function(nodes, data1) {
        _this.nodes = nodes;
        _this.data = data1;
        _this.loadNodes();
        _this.__data_nodes = _this.tree.root.children.length;
        return _this.setStatus();
      };
    })(this));
  };

  PluginManagerApp.prototype.load = function() {
    var defaultSortField, defaultSortOrder;
    if (!this.__sortableFieldsMap) {
      this.__sortableFieldsMap = {
        name: "name",
        displayname: "manifest.displayname",
        type: "type",
        enabled: "enabled",
        updated_at: "updated_at"
      };
    }
    if (indexOf.call(this.__filter_data.columns, "enabled") >= 0) {
      defaultSortField = "enabled";
      defaultSortOrder = "DESC";
    } else {
      defaultSortField = "name";
      defaultSortOrder = "ASC";
    }
    if (this.__sortableFieldsMap[defaultSortField]) {
      defaultSortField = this.__sortableFieldsMap[defaultSortField];
    }
    this.__sortField = defaultSortField;
    this.__sortOrder = defaultSortOrder;
    return PluginManagerApp.__super__.load.call(this);
  };

  PluginManagerApp.prototype.loadList = function(filter, opts) {
    var dfr;
    if (opts == null) {
      opts = {};
    }
    dfr = new CUI.Deferred();
    ez5.api.plugin({
      api: "/manage"
    }).fail(dfr.reject).done((function(_this) {
      return function(data) {
        var displayname, i, len, plugin, plugins, ref, ref1;
        plugins = [];
        ref = data.plugins;
        for (i = 0, len = ref.length; i < len; i++) {
          plugin = ref[i];
          if ((plugin.enabled && !_this.__filter_data.show_enabled) || (!plugin.enabled && !_this.__filter_data.show_disabled)) {
            continue;
          }
          if (filter) {
            displayname = ez5.loca.getBestFrontendValue((ref1 = plugin.manifest) != null ? ref1.displayname : void 0) || "";
            if (!(_this.checkFilter(plugin.name, filter) || _this.checkFilter(displayname, filter) || _this.checkFilter(plugin.type, filter))) {
              continue;
            }
          }
          plugins.push(new PluginManagerAppItem({
            plugin: plugin,
            manager: _this
          }));
        }
        plugins = _this.sortPlugins(plugins, _this.__sortField, _this.__sortOrder);
        return dfr.resolve(plugins);
      };
    })(this));
    return dfr.promise();
  };

  PluginManagerApp.prototype.sortPlugins = function(plugins, field, order) {
    var getDisplayName, getNestedValue, getSecondaryField;
    getNestedValue = function(obj, path) {
      var current, i, len, part, parts;
      parts = path.split('.');
      current = obj;
      for (i = 0, len = parts.length; i < len; i++) {
        part = parts[i];
        if ((current != null ? current[part] : void 0) == null) {
          return null;
        }
        current = current[part];
      }
      return current;
    };
    getDisplayName = function(plugin) {
      var displayname, ref;
      displayname = ez5.loca.getBestFrontendValue((ref = plugin.manifest) != null ? ref.displayname : void 0);
      return displayname || plugin.name || "";
    };
    getSecondaryField = (function(_this) {
      return function() {
        var hasDisplayName, hasName;
        hasDisplayName = indexOf.call(_this.__filter_data.columns, "displayname") >= 0;
        hasName = indexOf.call(_this.__filter_data.columns, "name") >= 0;
        if (hasDisplayName) {
          return "displayname";
        } else if (hasName) {
          return "name";
        } else {
          return "displayname";
        }
      };
    })(this);
    return plugins.sort((function(_this) {
      return function(a, b) {
        var aSecondaryValue, aValue, bSecondaryValue, bValue, result, secondaryField;
        aValue = getNestedValue(a._plugin, field);
        bValue = getNestedValue(b._plugin, field);
        if (field === "manifest.displayname") {
          aValue = getDisplayName(a._plugin);
          bValue = getDisplayName(b._plugin);
        }
        if (aValue === null && bValue === null) {
          return 0;
        }
        if (aValue === null) {
          if (order === "ASC") {
            return -1;
          } else {
            return 1;
          }
        }
        if (bValue === null) {
          if (order === "ASC") {
            return 1;
          } else {
            return -1;
          }
        }
        if (typeof aValue === "boolean") {
          result = aValue === bValue ? 0 : (aValue ? 1 : -1);
        } else if (typeof aValue === "number") {
          result = aValue - bValue;
        } else {
          result = String(aValue).localeCompare(String(bValue));
        }
        if (order === "DESC") {
          result = -result;
        }
        if (result === 0 && field === "enabled") {
          secondaryField = getSecondaryField();
          if (secondaryField === "displayname") {
            aSecondaryValue = getDisplayName(a._plugin);
            bSecondaryValue = getDisplayName(b._plugin);
          } else {
            aSecondaryValue = a._plugin.name || "";
            bSecondaryValue = b._plugin.name || "";
          }
          result = aSecondaryValue.localeCompare(bSecondaryValue);
        }
        return result;
      };
    })(this));
  };

  PluginManagerApp.prototype.checkFilter = function(string, filter) {
    return string != null ? string.toLowerCase().includes(filter.toLowerCase()) : void 0;
  };

  PluginManagerApp.prototype.getColumns = function() {
    return this.__filter_data.columns.concat();
  };

  PluginManagerApp.prototype.getListFields = function() {
    var column, field, i, len, listFields, ref, sortFieldKey;
    listFields = [];
    ref = this.__filter_data.columns;
    for (i = 0, len = ref.length; i < len; i++) {
      column = ref[i];
      field = {
        th_label: "plugin.manager.app.list." + column + "|text",
        sortable: {
          key: "plugin." + (this.__sortableFieldsMap[column] || column)
        }
      };
      sortFieldKey = this.__sortableFieldsMap[column] || column;
      if (sortFieldKey === this.__sortField) {
        field.sortable.order = this.__sortOrder;
      }
      listFields.push(field);
    }
    return listFields;
  };

  PluginManagerApp.prototype.destroy = function() {
    PluginManagerApp.__super__.destroy.call(this);
    return delete this.pane;
  };

  return PluginManagerApp;

})(SystemListManager);

ez5.session_ready(function() {
  if (ez5.version("6")) {
    return ez5.rootMenu.registerApp(PluginManagerApp);
  }
});
// Generated by CoffeeScript 1.12.7
var PluginManagerAppItem,
  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;

PluginManagerAppItem = (function(superClass) {
  extend(PluginManagerAppItem, superClass);

  function PluginManagerAppItem() {
    this._save = bind(this._save, this);
    return PluginManagerAppItem.__super__.constructor.apply(this, arguments);
  }

  PluginManagerAppItem.prototype.initOpts = function() {
    PluginManagerAppItem.__super__.initOpts.call(this, this.opts);
    return this.addOpts({
      plugin: {
        check: "PlainObject"
      }
    });
  };

  PluginManagerAppItem.prototype.readOpts = function() {
    return PluginManagerAppItem.__super__.readOpts.call(this);
  };

  PluginManagerAppItem.prototype.getContent = function() {
    return this._plugin.name;
  };

  PluginManagerAppItem.prototype.getId = function() {
    return this._plugin.id;
  };

  PluginManagerAppItem.prototype.getDeleteConfirmLocaKey = function() {
    if (this._plugin.type === "disk") {
      return "plugin.manager.app.item.delete_confirm_disk";
    }
    return "system.list.manager.item.delete_confirm";
  };

  PluginManagerAppItem.prototype.getDeleteConfirmOpts = function() {
    var opts;
    opts = PluginManagerAppItem.__super__.getDeleteConfirmOpts.call(this);
    opts.button_text_ok = $$("plugin.manager.app.item.delete.confirm");
    opts.button_text_cancel = $$("plugin.manager.app.item.delete.cancel");
    return opts;
  };

  PluginManagerAppItem.prototype.load = function(ignore_400) {
    var ref;
    if (ignore_400 == null) {
      ignore_400 = false;
    }
    if ((ref = this._plugin.manifest) != null ? ref.url : void 0) {
      this._plugin.external_url = this._plugin.manifest.url;
    }
    this.update();
    return CUI.resolvedPromise();
  };

  PluginManagerAppItem.prototype._loadData = function(data) {
    return this.loadData(data);
  };

  PluginManagerAppItem.prototype.loadData = function(_plugin) {
    this._plugin = _plugin;
    this.__origData = CUI.util.copyObject(this._plugin, true);
    return this;
  };

  PluginManagerAppItem.prototype.deleteOnServer = function() {
    var promise;
    promise = ez5.api.plugin({
      api: "/manage/" + this.getId(),
      type: "DELETE"
    });
    promise.done((function(_this) {
      return function() {
        return _this.__showReloadDialog();
      };
    })(this));
    return promise;
  };

  PluginManagerAppItem.prototype._save = function(ev, save_data) {
    var config_save_data, dfr, promise, send_config, shouldReloadAfterSave;
    if (ev != null ? ev.hasModifierKey() : void 0) {
      console.debug(CUI.util.getObjectClass(this), CUI.util.dump(save_data));
      return new CUI.rejectedPromise();
    }
    send_config = false;
    if (save_data.config && (this.__pluginBaseConfigInstance != null)) {
      config_save_data = this.__getPluginConfigSaveData();
      delete save_data.config;
      if (!CUI.util.isEqual(this.__initialConfigData, config_save_data)) {
        send_config = true;
      }
    }
    shouldReloadAfterSave = false;
    if (this.getId()) {
      promise = ez5.api.plugin({
        api: "/manage/" + this.getId(),
        type: "POST",
        json_data: save_data
      });
    } else {
      shouldReloadAfterSave = true;
      promise = ez5.api.plugin({
        api: "/manage",
        type: "PUT",
        json_data: save_data
      });
    }
    if (!shouldReloadAfterSave) {
      if (this._plugin.type === "url" && this.initialData.url !== save_data.url) {
        shouldReloadAfterSave = true;
      }
      if (this._plugin.type === "zip" && !CUI.util.isEqual(this.initialData.zip_file, save_data.zip_file)) {
        shouldReloadAfterSave = true;
      }
      if (this.initialData.enabled !== save_data.enabled) {
        shouldReloadAfterSave = true;
      }
    }
    dfr = new CUI.Deferred();
    promise.done((function(_this) {
      return function(data) {
        var finish;
        finish = function() {
          return dfr.resolve(data);
        };
        if (send_config) {
          return _this.__savePluginConfig(config_save_data).done(finish).fail(dfr.reject);
        } else if (shouldReloadAfterSave) {
          _this.__showReloadDialog();
          return finish();
        } else {
          return finish();
        }
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  PluginManagerAppItem.prototype.__getPluginConfigSaveData = function(forDwonload) {
    var bc, i, len, ref, save_data;
    if (forDwonload == null) {
      forDwonload = false;
    }
    save_data = {};
    ref = this.__pluginBaseConfigInstance.baseConfigs;
    for (i = 0, len = ref.length; i < len; i++) {
      bc = ref[i];
      bc.getSaveData(save_data, forDwonload);
    }
    return save_data;
  };

  PluginManagerAppItem.prototype.__savePluginConfig = function(config_data) {
    var data, dfr;
    dfr = new CUI.Deferred();
    data = {
      plugin: {}
    };
    data.plugin[this._plugin.name] = {
      config: config_data
    };
    ez5.server({
      api: "/config",
      type: "POST",
      json_data: data
    }).done(dfr.resolve).fail(dfr.reject);
    return dfr.promise();
  };

  PluginManagerAppItem.prototype.renderContent = function() {
    var _c, column, displayname, enabled_columns, first_column, i, len, ref, updated_at;
    first_column = null;
    enabled_columns = this._manager.getColumns();
    for (i = 0, len = enabled_columns.length; i < len; i++) {
      column = enabled_columns[i];
      switch (column) {
        case "name":
          _c = new CUI.Label({
            text: this._plugin.name
          });
          break;
        case "type":
          _c = new CUI.Label({
            text: this._plugin.type
          });
          break;
        case "enabled":
          _c = new CUI.Icon({
            icon: this._plugin.enabled ? "fa-check" : "fa-minus"
          });
          break;
        case "displayname":
          displayname = ez5.loca.getBestFrontendValue((ref = this._plugin.manifest) != null ? ref.displayname : void 0) || "";
          _c = new CUI.Label({
            text: displayname
          });
          break;
        case "updated_at":
          updated_at = this._plugin.updated_at ? ez5.format_date_and_time(this._plugin.updated_at, true) : "-";
          _c = new CUI.Label({
            text: updated_at
          });
      }
      if (first_column == null) {
        first_column = _c;
      } else {
        this.addColumn(new CUI.ListViewColumn({
          element: _c
        }));
      }
    }
    return first_column;
  };

  PluginManagerAppItem.prototype.__supportSchedules = function() {
    var ref, schedulerData;
    schedulerData = (ref = this._plugin.manifest) != null ? ref.scheduler : void 0;
    return !!schedulerData && !CUI.util.isEmpty(schedulerData);
  };

  PluginManagerAppItem.prototype.getPluginDescription = function() {
    var description, ref;
    if (!((ref = this._plugin.manifest) != null ? ref.info : void 0)) {
      return null;
    }
    description = ez5.loca.getBestFrontendValue(this._plugin.manifest.info);
    if (!CUI.util.isEmpty(description) && description !== "-") {
      return description;
    }
    return null;
  };

  PluginManagerAppItem.prototype.getPaneContent = function() {
    var descriptionLabel, descriptionText, vl;
    this.__tabs = PluginManagerAppItem.__super__.getPaneContent.call(this);
    descriptionText = this.getPluginDescription();
    if (!descriptionText) {
      return this.__tabs;
    }
    descriptionLabel = new CUI.Label({
      text: descriptionText,
      multiline: true,
      markdown: true,
      "class": "ez5-plugin-manager-app-item-description cui-label-description"
    });
    vl = new CUI.VerticalList({
      content: [descriptionLabel, this.__tabs],
      maximize_horizontal: true,
      maximize_vertical: true
    });
    return vl;
  };

  PluginManagerAppItem.prototype.getTabs = function() {
    var tabs;
    tabs = [
      {
        name: "general",
        text: $$("plugin.manager.app.item.tab.general"),
        content: (function(_this) {
          return function() {
            return new CUI.Form({
              data: _this._plugin,
              fields: _this.getGeneralFields()
            }).start();
          };
        })(this)
      }, {
        name: "type",
        text: $$("plugin.manager.app.item.tab.type"),
        content: this.getTypeForm()
      }
    ];
    if (this.__supportSchedules()) {
      tabs.push({
        name: "schedules",
        text: "Schedules",
        content: this.getSchedulesForm()
      });
    }
    if (this.canShowConfig()) {
      tabs.push({
        name: "config",
        text: $$("plugin.manager.app.item.tab.config"),
        load_on_show: true,
        content: (function(_this) {
          return function() {
            return _this.getConfigForm();
          };
        })(this),
        onActivate: (function(_this) {
          return function() {
            return _this._config_tools_btn.show();
          };
        })(this),
        onDeactivate: (function(_this) {
          return function() {
            return _this._config_tools_btn.hide();
          };
        })(this)
      });
    }
    if (this.__hasReadme()) {
      tabs.push({
        name: "readme",
        text: $$("plugin.manager.app.item.tab.readme"),
        load_on_show: true,
        content: (function(_this) {
          return function() {
            return _this.getReadmeContent();
          };
        })(this)
      });
    }
    return tabs;
  };

  PluginManagerAppItem.prototype.__hasReadme = function() {
    var ref, ref1;
    return !!((ref = this._plugin.manifest) != null ? (ref1 = ref.webfrontend) != null ? ref1.readme : void 0 : void 0);
  };

  PluginManagerAppItem.prototype.__getReadmeUrl = function() {
    var readmeFile, ref, ref1;
    readmeFile = (ref = this._plugin.manifest) != null ? (ref1 = ref.webfrontend) != null ? ref1.readme : void 0 : void 0;
    if (!readmeFile) {
      return null;
    }
    return ez5.getAbsoluteURL("/api/v1/plugin/static/" + this._plugin.name + "/" + readmeFile);
  };

  PluginManagerAppItem.prototype.getReadmeContent = function() {
    var dfr, readmeUrl;
    dfr = new CUI.Deferred();
    readmeUrl = this.__getReadmeUrl();
    if (!readmeUrl) {
      dfr.resolve(new CUI.EmptyLabel({
        text: $$("plugin.manager.app.item.tab.readme.not_available")
      }));
      return dfr.promise();
    }
    new CUI.XHR({
      url: readmeUrl,
      method: "GET",
      responseType: "text"
    }).start().done((function(_this) {
      return function(markdownContent) {
        var label, pane;
        label = new CUI.Label({
          text: markdownContent,
          multiline: true,
          markdown: true,
          "class": "ez5-plugin-manager-readme-content"
        });
        pane = new CUI.SimplePane({
          "class": "cui-pane--window ez5-plugin-manager-readme-pane",
          content: label
        });
        CUI.Events.listen({
          node: pane,
          type: "click",
          call: function(ev) {
            var anchorElement, anchorId, href, target;
            target = ev.getTarget();
            if (target.tagName === "A") {
              href = target.getAttribute("href");
              if (href != null ? href.startsWith("#") : void 0) {
                ev.stop();
                anchorId = href.substring(1);
                anchorElement = pane.DOM.querySelector("[id='" + anchorId + "']");
                if (anchorElement) {
                  return anchorElement.scrollIntoView({
                    behavior: "smooth"
                  });
                }
              }
            }
          }
        });
        return dfr.resolve(pane);
      };
    })(this)).fail((function(_this) {
      return function(xhr) {
        return dfr.resolve(new CUI.EmptyLabel({
          text: $$("plugin.manager.app.item.tab.readme.load_error")
        }));
      };
    })(this));
    return dfr.promise();
  };

  PluginManagerAppItem.prototype.canShowConfig = function() {
    return this._plugin.enabled && ez5.session.hasSystemRight("root", "config");
  };

  PluginManagerAppItem.prototype.getExtraButtons = function() {
    var downloadButton, fileReader, uploadButton;
    fileReader = new CUI.FileReader({
      onDone: (function(_this) {
        return function(file) {
          _this.__uploadedConfig = JSON.parse(file.getResult());
          _this.__tabs.getTab("config").loadContent();
          _this.setStatus();
          return CUI.alert({
            text: $$("base.config.manager.success.loading")
          });
        };
      })(this)
    });
    downloadButton = new LocaButton({
      loca_key: "base.config.manager.button.download",
      onClick: (function(_this) {
        return function(ev) {
          var download_data;
          download_data = _this.__getPluginConfigSaveData(true);
          return CUI.FileReader.save(ez5.session.getEasydbName() + "_BaseConfig_" + _this._plugin.name + "_" + CUI.util.moment().format('YYYY-MM-DD') + ".json", JSON.stringify(download_data, null, "    "));
        };
      })(this)
    });
    uploadButton = new CUI.FileUploadButton({
      text: $$("base.config.manager.button.upload|text"),
      icon: $$("base.config.manager.button.upload|icon"),
      multiple: false,
      fileUpload: fileReader
    });
    this._config_tools_btn = new LocaButton({
      loca_key: "base.config.manager.menu",
      menu: {
        items: [downloadButton, uploadButton]
      }
    });
    this._config_tools_btn.hide();
    return [this._config_tools_btn];
  };

  PluginManagerAppItem.prototype.getTypeForm = function(forNewPlugin) {
    var eas_field, fields, upload_btn, uploader;
    if (forNewPlugin == null) {
      forNewPlugin = false;
    }
    uploader = new CUI.FileUpload({
      url: ez5.eas.getUploadUrl(),
      onAdd: (function(_this) {
        return function(file) {
          return console.debug("onAdd", file);
        };
      })(this),
      onUpdate: (function(_this) {
        return function() {
          return console.debug("onUpdate", file);
        };
      })(this)
    });
    upload_btn = new CUI.FileUploadButton({
      fileUpload: uploader,
      text: "Upload Button",
      icon: "upload",
      accept: ".zip",
      multiple: false
    });
    eas_field = new EASField({
      name: "zip_file",
      "class": "ez5-plugin-manager-app-eas-field"
    });
    fields = [
      {
        type: CUI.Select,
        name: "type",
        form: {
          label: $$("plugin.manager.app.item.tab.type.type")
        },
        options: [
          {
            value: "zip"
          }, {
            disabled: true,
            value: "disk"
          }, {
            value: "url"
          }
        ]
      }, {
        type: CUI.Input,
        name: "url",
        form: {
          label: "url"
        }
      }, {
        type: CUI.Output,
        name: "path",
        form: {
          label: $$("plugin.manager.app.item.tab.type.path")
        }
      }, {
        name: "zip_file",
        form: {
          label: $$("plugin.manager.app.list.upload")
        },
        type: CUI.DataFieldProxy,
        element: (function(_this) {
          return function(df) {
            return eas_field.renderEditorInput(df.getData());
          };
        })(this)
      }
    ];
    if (forNewPlugin) {
      fields.splice(0, 0, {
        type: CUI.Checkbox,
        name: "enabled",
        form: {
          label: $$("plugin.manager.app.pane.enabled")
        }
      });
    }
    this.typeForm = new CUI.Form({
      data: this._plugin,
      fields: fields,
      onDataChanged: (function(_this) {
        return function() {
          if (_this._plugin.type === "zip") {
            _this.typeForm.getFieldsByName("zip_file")[0].show(true);
            _this.typeForm.getFieldsByName("url")[0].hide(true);
          } else {
            _this.typeForm.getFieldsByName("zip_file")[0].hide(true);
            _this.typeForm.getFieldsByName("url")[0].show(true);
          }
          return _this.setStatus();
        };
      })(this)
    });
    return this.typeForm.start();
  };

  PluginManagerAppItem.prototype.getSchedulesForm = function() {
    var fields, name, ref, ref1, ref2, schedule;
    fields = [];
    ref1 = (ref = this._plugin.manifest) != null ? ref.scheduler : void 0;
    for (name in ref1) {
      schedule = ref1[name];
      fields.push({
        type: CUI.Form,
        form: {
          label: name
        },
        name: name,
        fields: [
          {
            type: CUI.Output,
            name: "next_run_at",
            form: {
              label: $$("plugin.manager.app.item.tab.schedules.form.next_run_at")
            },
            getValue: (function(_this) {
              return function(v) {
                return ez5.format_date_and_time(v, true);
              };
            })(this)
          }, {
            type: CUI.Output,
            name: "run_started_at",
            form: {
              label: $$("plugin.manager.app.item.tab.schedules.form.run_started_at")
            },
            getValue: (function(_this) {
              return function(v) {
                return ez5.format_date_and_time(v, true);
              };
            })(this)
          }, {
            type: CUI.Output,
            name: "run_finished_at",
            form: {
              label: $$("plugin.manager.app.item.tab.schedules.form.run_finished_at")
            },
            getValue: (function(_this) {
              return function(v) {
                return ez5.format_date_and_time(v, true);
              };
            })(this)
          }, {
            type: CUI.Output,
            form: {
              label: $$("plugin.manager.app.item.tab.schedules.form.run_status")
            },
            name: "run_status"
          }, ((ref2 = schedule.plugin_user) != null ? ref2.require : void 0) ? {
            type: UserGroupSelector,
            form: {
              label: $$("plugin.manager.app.item.tab.schedules.form.user")
            },
            undo_and_changed_support: false,
            aclWhoManager: new AclWhoManager({
              who_filter: ["user"]
            }),
            name: "user"
          } : void 0, {
            type: CUI.Form,
            name: "schedule",
            form: {
              label: $$("plugin.manager.app.item.tab.schedules.form.schedule")
            },
            fields: ScheduleEditor.getFields()
          }, {
            type: CUI.Checkbox,
            form: {
              label: $$("plugin.manager.app.item.tab.schedules.form.start_now")
            },
            name: "start_now"
          }
        ]
      });
    }
    return new CUI.Form({
      data: this._plugin,
      name: "schedules",
      fields: fields
    }).start();
  };

  PluginManagerAppItem.prototype.getConfigForm = function() {
    var dfr;
    dfr = new CUI.Deferred();
    ez5.server({
      api: "/config/list"
    }).done((function(_this) {
      return function(data) {
        var ref;
        _this.__plugin_config_defs = data != null ? data.plugin[_this._plugin.name] : void 0;
        if (CUI.util.isEmpty((ref = _this.__plugin_config_defs) != null ? ref.defs : void 0)) {
          dfr.resolve(new CUI.EmptyLabel({
            text: $$("plugin.manager.app.item.tab.config.no_config")
          }));
          return;
        }
        return ez5.api.config().done(function(config_data) {
          var content, ref1, ref2, ref3;
          if (!CUI.util.isEmpty(_this.__uploadedConfig)) {
            _this._plugin.config = _this.__uploadedConfig;
          } else {
            _this._plugin.config = (config_data != null ? (ref1 = config_data.plugin[_this._plugin.name]) != null ? ref1.config : void 0 : void 0) || {};
          }
          _this.__pluginBaseConfigInstance = BaseConfig.initialize({
            data: _this._plugin.config,
            config: data != null ? (ref2 = data.plugin[_this._plugin.name]) != null ? ref2.defs : void 0 : void 0,
            l10n_prefix: "server.config.group",
            BaseConfigClass: PluginBaseConfig,
            show_introduction: false
          });
          content = new CUI.SimplePane({
            "class": "cui-pane--window",
            content: (ref3 = _this.__pluginBaseConfigInstance.plugin_rows[0]) != null ? ref3.content : void 0
          });
          if (CUI.util.isEmpty(_this.__uploadedConfig)) {
            _this.__initialConfigData = CUI.util.copyObjectV2(_this.__getPluginConfigSaveData(), true);
          } else {
            delete _this.__uploadedConfig;
          }
          return dfr.resolve(content);
        });
      };
    })(this));
    return dfr.promise();
  };

  PluginManagerAppItem.prototype.registerDataChangedListener = function(div) {
    PluginManagerAppItem.__super__.registerDataChangedListener.call(this, div);
    this.setStatus();
  };

  PluginManagerAppItem.prototype.__showReloadDialog = function() {
    return new CUI.ConfirmationChoice({
      ui: "plugin.manager.app.item.reload_dialog",
      title: $$("plugin.manager.app.reload_modal.title"),
      text: $$("plugin.manager.app.reload_modal.content"),
      cancel: true,
      choices: [
        {
          text: $$("plugin.manager.app.reload_modal.button"),
          primary: true,
          onClick: (function(_this) {
            return function() {
              return document.location.reload();
            };
          })(this)
        }
      ]
    }).open();
  };

  PluginManagerAppItem.prototype.setStatus = function() {
    this.typeForm.getFieldByIdx(3).hide(true);
    this.typeForm.getFieldsByName("url")[0].hide(true);
    this.typeForm.getFieldsByName("path")[0].hide(true);
    if (this.getId()) {
      this.typeForm.getFieldsByName("type")[0].disable();
    } else {
      this.typeForm.getFieldsByName("type")[0].enable();
    }
    switch (this._plugin.type) {
      case "zip":
        this.typeForm.getFieldByIdx(3).show(true);
        break;
      case "disk":
        this.typeForm.getFieldsByName("path")[0].show(true);
        break;
      case "url":
        this.typeForm.getFieldsByName("url")[0].show(true);
    }
    return PluginManagerAppItem.__super__.setStatus.call(this);
  };

  PluginManagerAppItem.prototype.getGeneralFields = function() {
    var buildInfoFields, build_info, field, fields, ref, validFields;
    fields = [
      {
        type: CUI.Checkbox,
        name: "enabled",
        text: $$("plugin.manager.app.pane.enabled")
      }, {
        type: CUI.Output,
        text: this._plugin.name,
        form: {
          label: $$("plugin.manager.app.item.tab.general.name")
        }
      }, {
        type: CUI.Checkbox,
        name: "auto_added",
        disabled: true,
        form: {
          label: $$("plugin.manager.app.list.auto_added|text")
        }
      }, this._plugin.external_url ? {
        type: CUI.Output,
        name: "external_url",
        markdown: true,
        form: {
          label: $$("plugin.manager.app.item.tab.general.external_url")
        }
      } : void 0, {
        type: CUI.Select,
        options: this.getUpdateOptions(),
        disabled: this._plugin.type === "zip",
        form: {
          label: $$("plugin.manager.app.item.tab.general.updates")
        },
        name: "update_policy",
        text: "update policy"
      }, {
        type: CUI.Output,
        name: "created_at",
        form: {
          label: $$("plugin.manager.app.item.tab.general.created_at")
        },
        getValue: (function(_this) {
          return function(v) {
            return ez5.format_date_and_time(v, true);
          };
        })(this)
      }, {
        type: CUI.Output,
        name: "updated_at",
        form: {
          label: $$("plugin.manager.app.item.tab.general.updated_at")
        },
        getValue: (function(_this) {
          return function(v) {
            return ez5.format_date_and_time(v, true);
          };
        })(this)
      }, {
        type: CUI.Output,
        name: "last_checked_at",
        form: {
          label: $$("plugin.manager.app.item.tab.general.last_checked_at")
        },
        placeholder: "-",
        getValue: (function(_this) {
          return function(v) {
            return ez5.format_date_and_time(v, true);
          };
        })(this)
      }
    ];
    if ((ref = this._plugin.manifest) != null ? ref.build_info : void 0) {
      build_info = this._plugin.manifest.build_info;
      buildInfoFields = [
        build_info.repository ? {
          type: CUI.Output,
          text: build_info.repository,
          form: {
            label: $$("plugin.manager.app.item.tab.general.build_info.repository")
          }
        } : void 0, build_info.release ? {
          type: CUI.Output,
          text: build_info.release,
          form: {
            label: $$("plugin.manager.app.item.tab.general.build_info.release")
          }
        } : void 0, build_info.rev ? {
          type: CUI.Output,
          text: build_info.rev,
          form: {
            label: $$("plugin.manager.app.item.tab.general.build_info.rev")
          }
        } : void 0, build_info.lastchanged ? {
          type: CUI.Output,
          text: ez5.format_date_and_time(build_info.lastchanged, true),
          form: {
            label: $$("plugin.manager.app.item.tab.general.build_info.lastchanged")
          }
        } : void 0, build_info.builddate ? {
          type: CUI.Output,
          text: ez5.format_date_and_time(build_info.builddate, true),
          form: {
            label: $$("plugin.manager.app.item.tab.general.build_info.builddate")
          }
        } : void 0
      ];
      validFields = (function() {
        var i, len, results;
        results = [];
        for (i = 0, len = buildInfoFields.length; i < len; i++) {
          field = buildInfoFields[i];
          if (field) {
            results.push(field);
          }
        }
        return results;
      })();
      if (validFields.length > 0) {
        fields.push({
          type: CUI.Form,
          form: {
            label: $$("plugin.manager.app.item.tab.general.build_info")
          },
          fields: validFields
        });
      }
    }
    return fields;
  };

  PluginManagerAppItem.prototype.getUpdateOptions = function() {
    if (this._plugin.type === "zip") {
      return [
        {
          text: "never",
          value: "never"
        }
      ];
    } else {
      return [
        {
          text: "automatic (daily)",
          value: "automatic"
        }, {
          text: "always (development)",
          value: "always"
        }, {
          text: "never",
          value: "never"
        }
      ];
    }
  };

  PluginManagerAppItem.prototype.hasChanges = function() {
    var initialDataWithoutConfig, saveDataWithoutConfig;
    if (!this.initialData) {
      return false;
    }
    initialDataWithoutConfig = CUI.util.copyObject(this.initialData, true);
    delete initialDataWithoutConfig.config;
    saveDataWithoutConfig = CUI.util.copyObject(this.getSaveData(), true);
    delete saveDataWithoutConfig.config;
    if (CUI.util.isEqual(initialDataWithoutConfig, saveDataWithoutConfig)) {
      if (this.__initialConfigData != null) {
        return !CUI.util.isEqual(this.__initialConfigData, this.__getPluginConfigSaveData());
      }
      return false;
    } else {
      return true;
    }
  };

  PluginManagerAppItem.prototype.getSaveData = function() {
    var allEmpty, field, i, len, name, ref, ref1, save_data, schedule;
    save_data = CUI.util.copyObject(this._plugin, true);
    if (save_data.type === "zip") {
      delete save_data.url;
    } else if (save_data.type === "url") {
      delete save_data.zip_file;
    }
    if (!CUI.util.isEmpty(save_data.schedules)) {
      ref = save_data.schedules;
      for (name in ref) {
        schedule = ref[name];
        allEmpty = true;
        if (!CUI.util.isEmpty(schedule.schedule)) {
          ref1 = ["days_of_month", "weekdays", "hours"];
          for (i = 0, len = ref1.length; i < len; i++) {
            field = ref1[i];
            if (!CUI.util.isEmpty(schedule.schedule[field])) {
              allEmpty = false;
              break;
            }
          }
        }
        if (allEmpty) {
          delete save_data.schedules[name];
        }
      }
    }
    return save_data;
  };

  PluginManagerAppItem.prototype.isDeletable = function() {
    if (this._plugin.type === "disk") {
      return true;
    }
    return !this._plugin.auto_added;
  };

  PluginManagerAppItem.prototype.isWritable = function() {
    return true;
  };

  return PluginManagerAppItem;

})(SystemListManagerItem);
// Generated by CoffeeScript 1.12.7
var BackupManagerApp,
  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;

BackupManagerApp = (function(superClass) {
  extend(BackupManagerApp, superClass);

  function BackupManagerApp() {
    return BackupManagerApp.__super__.constructor.apply(this, arguments);
  }

  BackupManagerApp.label = function() {
    return "admin.menu.backup_manager";
  };

  BackupManagerApp.group = function() {
    return "zzh_administration";
  };

  BackupManagerApp.submenu = function() {
    return "administration";
  };

  BackupManagerApp.path = function() {
    return ["backupmanager"];
  };

  BackupManagerApp.is_allowed = function() {
    return ez5.session.hasSystemRight("root", "backup");
  };

  BackupManagerApp.prototype.load = function(path) {
    var result;
    this.__eventPoller = EventPoller.listen({
      filter: {
        type: ["BACKUP_DONE", "BACKUP_FAILED"]
      },
      instance: this,
      call: (function(_this) {
        return function(events) {
          var selectedRowIdx;
          selectedRowIdx = _this.tree.nodes.indexOf(_this.tree.getSelectedNode());
          return _this.loadTree().done(function() {
            return _this.tree.nodes[selectedRowIdx].select();
          });
        };
      })(this)
    });
    result = BackupManagerApp.__super__.load.call(this, path);
    this.__addExtraTreeInfo();
    return result;
  };

  BackupManagerApp.prototype.unload = function() {
    var ref;
    if ((ref = this.__eventPoller) != null) {
      ref.destroy();
    }
    return BackupManagerApp.__super__.unload.call(this);
  };

  BackupManagerApp.prototype.loadList = function() {
    var dfr;
    dfr = new CUI.Deferred();
    ez5.api.system({
      api: "/backup/list"
    }).done((function(_this) {
      return function(data) {
        var backup, backups, i, len;
        backups = [];
        for (i = 0, len = data.length; i < len; i++) {
          backup = data[i];
          backups.push(new BackupManagerAppItem({
            backup: backup,
            manager: _this
          }));
        }
        dfr.resolve(backups);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  BackupManagerApp.prototype.getListFields = function() {
    return [
      {
        th_label: "backup.manager.app.list.id"
      }, {
        th_label: "backup.manager.app.list.created_at"
      }, {
        th_label: "backup.manager.app.list.size"
      }, {
        th_label: "backup.manager.app.list.format"
      }, {
        th_label: "backup.manager.app.list.include_events"
      }, {
        th_label: "backup.manager.app.list.status"
      }
    ];
  };

  BackupManagerApp.prototype.getCenterTitle = function() {
    return $$("backup.manager.app.pane.backup");
  };

  BackupManagerApp.prototype.getLeftTitle = function() {
    return $$("backup.manager.app.pane.title");
  };

  BackupManagerApp.prototype.getMissingLabel = function() {
    return new CUI.EmptyLabel({
      centered: true,
      text: $$("backup.manager.app.no_backup")
    });
  };

  BackupManagerApp.prototype.getPlusButton = function() {
    return {
      icon: "plus",
      group: "plus-minus",
      onClick: (function(_this) {
        return function() {
          return _this.showNewBackupModal();
        };
      })(this)
    };
  };

  BackupManagerApp.prototype.showNewBackupModal = function() {
    var item, mod;
    item = new BackupManagerAppItem({
      manager: this
    });
    mod = new CUI.Modal({
      pane: {
        title: $$("backup.manager.app.new_popup.title"),
        padded: true,
        content: new CUI.VerticalList({
          content: [
            new CUI.Label({
              text: $$("backup.manager.app.new_popup.text"),
              multiline: true
            }), item.getNewForm()
          ]
        }),
        footer_right: new CUI.Button({
          text: $$("backup.manager.app.new_popup.create_button"),
          primary: true,
          onClick: (function(_this) {
            return function(ev) {
              return item.save(ev).done(function() {
                return _this.addRow(item).done(function() {
                  return mod.destroy();
                });
              });
            };
          })(this)
        })
      },
      cancel: true
    });
    mod.show();
    return item.setStatus();
  };

  BackupManagerApp.prototype.addRow = function(item) {
    this.tree.addNode(item).done((function(_this) {
      return function() {};
    })(this));
    return item.select();
  };

  BackupManagerApp.prototype.loadFilter = false;

  BackupManagerApp.prototype.getTreeOpts = function() {
    var opts;
    return opts = {
      no_hierarchy: true,
      cols: ["auto", "maximize", "auto", "auto", "auto", "auto"]
    };
  };

  BackupManagerApp.prototype.getFlexHandle = function() {
    var flexHandle;
    flexHandle = {
      label: this.getMenuTitle(),
      state_name: "admin-manager-left",
      hidden: false
    };
    return flexHandle;
  };

  BackupManagerApp.prototype.__addExtraTreeInfo = function() {
    var footer, footerWrapper;
    footer = CUI.dom.matchSelector(this.__layout.DOM, ".ez5-backup-manager-app-layout .cui-pane-footer");
    if (footer && footer.length > 0) {
      footerWrapper = CUI.dom.parent(footer[0]);
      return CUI.dom.prepend(footerWrapper, new LocaLabel({
        loca_key: "backup.manager.app.footer.text",
        multiline: true,
        markdown: true,
        "class": "ez5-backup-manager-hint-text"
      }));
    }
  };

  return BackupManagerApp;

})(SystemListManager);

ez5.session_ready(function() {
  if (ez5.version("6")) {
    return ez5.rootMenu.registerApp(BackupManagerApp);
  }
});
// Generated by CoffeeScript 1.12.7
var BackupManagerAppItem,
  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;

BackupManagerAppItem = (function(superClass) {
  extend(BackupManagerAppItem, superClass);

  function BackupManagerAppItem() {
    this._save = bind(this._save, this);
    this._loadData = bind(this._loadData, this);
    return BackupManagerAppItem.__super__.constructor.apply(this, arguments);
  }

  BackupManagerAppItem.prototype.initOpts = function() {
    BackupManagerAppItem.__super__.initOpts.call(this, this.opts);
    return this.addOpts({
      backup: {
        "default": {},
        check: "PlainObject"
      }
    });
  };

  BackupManagerAppItem.prototype.getId = function() {
    return this._backup.id;
  };

  BackupManagerAppItem.prototype.getContent = function() {
    return this._backup.id + " ";
  };

  BackupManagerAppItem.prototype.renderContent = function() {
    var includeEventsIcon, ref;
    this.addColumn(new CUI.ListViewColumn({
      element: new CUI.Label({
        text: ez5.format_date_and_time(this._backup.created_at)
      })
    }));
    this.addColumn(new CUI.ListViewColumn({
      element: new CUI.Label({
        text: ez5.format_filesize((ref = this._backup.stats) != null ? ref.filesize : void 0)
      })
    }));
    this.addColumn(new CUI.ListViewColumn({
      element: new CUI.Label({
        text: this._backup.opts.format
      })
    }));
    includeEventsIcon = this._backup.opts.include_events ? "fa-check" : "fa-times";
    this.addColumn(new CUI.ListViewColumn({
      element: new CUI.Icon({
        icon: includeEventsIcon
      })
    }));
    this.addColumn(new CUI.ListViewColumn({
      element: new CUI.Label({
        text: this._backup.status
      })
    }));
    return BackupManagerAppItem.__super__.renderContent.call(this);
  };

  BackupManagerAppItem.prototype.isDeletable = function() {
    return true;
  };

  BackupManagerAppItem.prototype.isWritable = function() {
    return false;
  };

  BackupManagerAppItem.prototype.getApi = function() {
    return "system";
  };

  BackupManagerAppItem.prototype.getEndpoint = function() {
    return "/backup" + BackupManagerAppItem.__super__.getEndpoint.call(this);
  };

  BackupManagerAppItem.prototype._loadData = function(_backup) {
    this._backup = _backup;
    return this;
  };

  BackupManagerAppItem.prototype.show = function() {
    BackupManagerAppItem.__super__.show.call(this);
    this.__tabs.getTab("log")._onActivate = (function(_this) {
      return function() {
        _this.__pollingLog = true;
        return _this.updateLog();
      };
    })(this);
    this.__tabs.getTab("log")._onDeactivate = (function(_this) {
      return function() {
        return _this.__pollingLog = false;
      };
    })(this);
    return this;
  };

  BackupManagerAppItem.prototype.deselect = function(ev) {
    return BackupManagerAppItem.__super__.deselect.call(this, ev).done((function(_this) {
      return function() {
        return _this.__pollingLog = false;
      };
    })(this));
  };

  BackupManagerAppItem.prototype.getTabs = function() {
    var tabs;
    tabs = [
      {
        name: "detail",
        text: $$("backup.manager.app.tabs.details"),
        content: (function(_this) {
          return function() {
            return new CUI.Form({
              data: _this._backup,
              fields: _this.getGeneralFields()
            }).start();
          };
        })(this)
      }, {
        name: "log",
        text: $$("backup.manager.app.tabs.logs"),
        content: (function(_this) {
          return function() {
            return _this.getLogsTable();
          };
        })(this)
      }
    ];
    return tabs;
  };

  BackupManagerAppItem.prototype.getGeneralFields = function() {
    var fields, ref, ref1;
    fields = [
      {
        type: CUI.Output,
        text: "" + this._backup.id,
        form: {
          label: $$("backup.manager.app.list.id")
        }
      }, {
        type: CUI.Output,
        text: this._backup.status,
        form: {
          label: $$("backup.manager.app.list.status")
        }
      }, {
        type: CUI.Output,
        text: ez5.format_date_and_time(this._backup.created_at),
        form: {
          label: $$("backup.manager.app.list.created_at")
        }
      }, {
        type: CUI.Output,
        text: (ref = this._backup.create_user) != null ? ref.user._generated_displayname : void 0,
        form: {
          label: $$("backup.manager.app.list.created_by")
        }
      }, {
        type: CUI.Output,
        text: ez5.format_date_and_time(this._backup.finished_at),
        form: {
          label: $$("backup.manager.app.list.finished_at")
        }
      }, {
        type: CUI.Output,
        text: this._backup.opts.format,
        form: {
          label: $$("backup.manager.app.list.format")
        }
      }, {
        type: CUI.Output,
        text: this._backup.opts.include_events ? $$("boolean.column.detail.true") : $$("boolean.column.detail.false"),
        form: {
          label: $$("backup.manager.app.list.include_events")
        }
      }, {
        type: CUI.Output,
        text: ez5.format_filesize((ref1 = this._backup.stats) != null ? ref1.filesize : void 0),
        form: {
          label: $$("backup.manager.app.list.size")
        }
      }
    ];
    return fields;
  };

  BackupManagerAppItem.prototype.getLogsTable = function() {
    this.showLogData();
    return this.__logListView;
  };

  BackupManagerAppItem.prototype.updateLog = function() {
    if (this._backup.status === 'running' && this.__pollingLog) {
      CUI.setTimeout((function(_this) {
        return function() {
          return ez5.api[_this.getApi()]({
            api: _this.getEndpoint(),
            handle_error: function(xhr) {}
          }).done(function(data) {
            _this._backup.status = data.status;
            if (data.log.length > _this._backup.log.length) {
              _this._backup.log = data.log;
              _this.showLogData();
            }
            return _this.updateLog();
          });
        };
      })(this), 1000);
    }
  };

  BackupManagerAppItem.prototype.showLogData = function() {
    var headerRow, i, len, log, ref, row;
    if (!this.__logListView) {
      this.__logListView = new CUI.ListView({
        cols: ["auto", "auto"]
      });
      this.__logListView.render();
    } else {
      this.__logListView.removeAllRows();
    }
    headerRow = new CUI.ListViewHeaderRow();
    headerRow.addColumn(new CUI.ListViewHeaderColumn({
      element: new CUI.Label({
        text: $$('backup.manager.app.log_tab.created_at')
      })
    }));
    headerRow.addColumn(new CUI.ListViewHeaderColumn({
      element: new CUI.Label({
        text: $$('backup.manager.app.log_tab.message')
      })
    }));
    ref = this._backup.log || [];
    for (i = 0, len = ref.length; i < len; i++) {
      log = ref[i];
      row = new CUI.ListViewRow();
      row.addColumn(new CUI.ListViewColumn({
        element: new CUI.Label({
          text: ez5.format_date_and_time(log.created_at)
        })
      }));
      row.addColumn(new CUI.ListViewColumn({
        element: new CUI.Label({
          text: log.msg,
          multiline: true
        })
      }));
      this.__logListView.prependRow(row);
    }
    this.__logListView.prependRow(headerRow);
  };

  BackupManagerAppItem.prototype.getNewForm = function() {
    var fields, formatOpts;
    this.__newItemData = {};
    formatOpts = [
      {
        text: "pg_dump",
        value: "pg_dump"
      }, {
        text: "sqlite3",
        value: "sqlite3"
      }, {
        text: "sqlite3_db",
        value: "sqlite3_db"
      }, {
        text: "postgres",
        value: "postgres"
      }
    ];
    fields = [
      {
        type: CUI.Select,
        name: "format",
        options: formatOpts,
        form: {
          label: "Format"
        }
      }, {
        type: CUI.Checkbox,
        name: "include_events",
        form: {
          label: $$("backup.manager.app.list.include_events")
        }
      }
    ];
    this.newItemForm = new CUI.Form({
      data: this.__newItemData,
      fields: fields
    });
    this.newItemForm.start();
    return this.newItemForm;
  };

  BackupManagerAppItem.prototype.getSaveData = function() {
    return this.__newItemData;
  };

  BackupManagerAppItem.prototype._save = function(ev, save_data) {
    var promise;
    if (ev != null ? ev.hasModifierKey() : void 0) {
      console.debug(CUI.util.getObjectClass(this), CUI.util.dump(save_data));
      return new CUI.rejectedPromise();
    }
    promise = ez5.api.system({
      api: "/backup/new",
      type: "PUT",
      json_data: save_data
    });
    return promise;
  };

  BackupManagerAppItem.prototype.getExtraButtons = function() {
    return [this.getDownloadButton()];
  };

  BackupManagerAppItem.prototype.getCancelButton = function() {};

  BackupManagerAppItem.prototype.getDownloadButton = function() {
    var downloadUrl;
    if (this._backup.status !== "done") {
      return;
    }
    downloadUrl = Session.addToken(ez5.api.getFullBase() + "/system/backup/" + this.getId() + "/download");
    return new CUI.ButtonHref({
      text: $$("backup.manager.app.download_backup|text"),
      icon: $$("backup.manager.app.download_backup|icon"),
      download: true,
      href: downloadUrl,
      primary: true
    });
  };

  return BackupManagerAppItem;

})(SystemListManagerItem);
// Generated by CoffeeScript 1.12.7
var LocationSelector,
  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;

LocationSelector = (function(superClass) {
  extend(LocationSelector, superClass);

  function LocationSelector() {
    return LocationSelector.__super__.constructor.apply(this, arguments);
  }

  LocationSelector.prototype.initOpts = function() {
    LocationSelector.__super__.initOpts.call(this);
    this.addOpts({
      placeholder: {
        check: String,
        "default": $$("location.manager.selector.placeholder")
      },
      default_value: {
        check: function(v) {
          return CUI.util.isNumber(v) || CUI.util.isString(v);
        },
        "default": null
      }
    });
    return this.opts.options = [];
  };

  LocationSelector.prototype.readOpts = function() {
    LocationSelector.__super__.readOpts.call(this);
    if (this._default_value && CUI.util.isNumber(this._default_value)) {
      console.warn($$("location.manager.selector.placeholder.error"));
      this._default_value = null;
    }
    this._empty_text = this._empty_text || this._placeholder;
    return this.__getOptions().done((function(_this) {
      return function(options) {
        _this._options = options;
        _this.__options = options;
        _this.reload();
        return _this.setValue(_this._default_value);
      };
    })(this));
  };

  LocationSelector.prototype.__getOptions = function() {
    var dfr, options;
    dfr = new CUI.Deferred();
    options = [];
    ez5.api.system({
      api: "/location/list"
    }).done((function(_this) {
      return function(data) {
        var i, len, location, locations;
        locations = [];
        options.push({
          text: $$("location.manager.selector.empty_value"),
          value: ""
        });
        for (i = 0, len = data.length; i < len; i++) {
          location = data[i];
          options.push({
            text: location.name + " [" + location.kind + "]",
            value: location.name
          });
        }
        return dfr.resolve(options);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  return LocationSelector;

})(CUI.Select);
// Generated by CoffeeScript 1.12.7
var LocationManagerApp,
  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;

LocationManagerApp = (function(superClass) {
  extend(LocationManagerApp, superClass);

  function LocationManagerApp() {
    return LocationManagerApp.__super__.constructor.apply(this, arguments);
  }

  LocationManagerApp.label = function() {
    return "location.manager.app.title";
  };

  LocationManagerApp.group = function() {
    return "zzf_administration";
  };

  LocationManagerApp.submenu = function() {
    return "administration";
  };

  LocationManagerApp.path = function() {
    return ["locationmanager"];
  };

  LocationManagerApp.is_allowed = function() {
    return ez5.session.hasSystemRight("root", "location");
  };

  LocationManagerApp.prototype.loadList = function() {
    var dfr;
    dfr = new CUI.Deferred();
    ez5.api.system({
      api: "/location/list"
    }).done((function(_this) {
      return function(data) {
        var i, len, location, locations;
        locations = [];
        for (i = 0, len = data.length; i < len; i++) {
          location = data[i];
          locations.push(new LocationManagerAppItem({
            location: location,
            manager: _this
          }));
        }
        dfr.resolve(locations);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  LocationManagerApp.prototype.getListFields = function() {
    return [
      {
        th_label: "location.manager.app.list.id"
      }, {
        th_label: "location.manager.app.list.name"
      }, {
        th_label: "location.manager.app.list.type"
      }, {
        th_label: "location.manager.app.list.default"
      }, {
        th_label: "location.manager.app.list.status"
      }
    ];
  };

  LocationManagerApp.prototype.getCenterTitle = function() {
    return $$("location.manager.app.pane.location");
  };

  LocationManagerApp.prototype.getLeftTitle = function() {
    return $$("location.manager.app.list_title");
  };

  LocationManagerApp.prototype.getMissingLabel = function() {
    return new CUI.EmptyLabel({
      centered: true,
      text: "No Location"
    });
  };

  LocationManagerApp.prototype.addRow = function() {
    var new_node;
    new_node = new LocationManagerAppItem({
      manager: this
    });
    return this.tree.addNode(new_node).done((function(_this) {
      return function() {
        return new_node.select().fail(function() {
          return new_node["delete"]();
        }).done(function() {
          return new_node.scrollIntoView();
        });
      };
    })(this));
  };

  LocationManagerApp.prototype.loadFilter = false;

  LocationManagerApp.prototype.getTreeOpts = function() {
    var opts;
    return opts = {
      no_hierarchy: true,
      cols: ["fixed", "maximize", "auto", "auto", "auto"],
      footer_right: (function(_this) {
        return function() {
          return _this.getConfigDefaultLocationsMenu();
        };
      })(this)
    };
  };

  LocationManagerApp.prototype.getConfigDefaultLocationsMenu = function() {
    var menu;
    if (!ez5.session.hasSystemRight("root", "config")) {
      return [];
    }
    menu = [
      {
        loca_key: "admin.metadata.menu.button",
        menu: {
          items: [
            {
              loca_key: "location.manager.app.default_locations.button",
              onClick: (function(_this) {
                return function() {
                  return _this.openDefaultLocationModal();
                };
              })(this)
            }
          ]
        }
      }
    ];
    return menu;
  };

  LocationManagerApp.prototype.openDefaultLocationModal = function() {
    var formData, getConfigData, getLocationsFields, getLocationsForm, getSaveButton, modal, saveButton, showModal, targetDef, updateBaseConfig;
    formData = CUI.util.copyObject(ez5.session.getBaseConfig()["location_defaults"], true);
    saveButton = null;
    modal = null;
    targetDef = {};
    ez5.server({
      api: "/config/list"
    }).done((function(_this) {
      return function(baseConfig) {
        var ref;
        targetDef = (ref = baseConfig.system.defs.find(function(def) {
          return def.name === "location_defaults";
        })) != null ? ref.parameters : void 0;
        return showModal();
      };
    })(this));
    getConfigData = (function(_this) {
      return function() {
        var data;
        return data = {
          system: {
            config: {
              location_defaults: formData
            }
          }
        };
      };
    })(this);
    getSaveButton = (function(_this) {
      return function() {
        saveButton = new CUI.Button({
          text: $$("location.manager.app.default_locations.save"),
          disabled: true,
          primary: true,
          onClick: function(ev) {
            return ez5.server({
              api: "/config",
              type: "POST",
              json_data: getConfigData()
            }).done(function() {
              updateBaseConfig();
              return modal.destroy();
            }).fail(function() {});
          }
        });
        return saveButton;
      };
    })(this);
    updateBaseConfig = (function(_this) {
      return function() {
        return ez5.session.getBaseConfig()["location_defaults"] = formData;
      };
    })(this);
    getLocationsFields = (function(_this) {
      return function() {
        var fields, k, locationTargets, v;
        fields = [];
        locationTargets = ez5.session.getBaseConfig()["location_defaults"];
        for (k in targetDef) {
          v = targetDef[k];
          fields.push(new LocationSelector({
            default_value: locationTargets[k],
            name: k,
            form: {
              label: k
            }
          }));
        }
        fields.sort(function(a, b) {
          var ref, ref1;
          return ((ref = targetDef[a.getName()]) != null ? ref.position : void 0) - ((ref1 = targetDef[b.getName()]) != null ? ref1.position : void 0);
        });
        return fields;
      };
    })(this);
    getLocationsForm = (function(_this) {
      return function() {
        var form;
        form = new CUI.Form({
          data: formData,
          fields: getLocationsFields(),
          onDataChanged: function() {
            return saveButton.enable();
          }
        });
        return form.start();
      };
    })(this);
    return showModal = (function(_this) {
      return function() {
        modal = new CUI.Modal({
          pane: {
            title: $$("location.manager.app.default_locations.title"),
            padded: true,
            content: new CUI.VerticalList({
              content: [
                new CUI.Label({
                  text: $$("location.manager.app.default_locations.text"),
                  multiline: true,
                  "class": "cui-label-description"
                }), getLocationsForm()
              ]
            }),
            footer_right: getSaveButton()
          },
          cancel: true
        });
        return modal.show();
      };
    })(this);
  };

  LocationManagerApp.prototype.getFlexHandle = function() {
    var flexHandle;
    flexHandle = {
      label: this.getMenuTitle(),
      state_name: "admin-manager-left",
      hidden: false
    };
    return flexHandle;
  };

  return LocationManagerApp;

})(SystemListManager);

ez5.session_ready(function() {
  if (ez5.version("6")) {
    return ez5.rootMenu.registerApp(LocationManagerApp);
  }
});
// Generated by CoffeeScript 1.12.7
var LocationManagerAppItem,
  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;

LocationManagerAppItem = (function(superClass) {
  extend(LocationManagerAppItem, superClass);

  function LocationManagerAppItem() {
    this.save = bind(this.save, this);
    this._save = bind(this._save, this);
    this._loadData = bind(this._loadData, this);
    return LocationManagerAppItem.__super__.constructor.apply(this, arguments);
  }

  LocationManagerAppItem.prototype.initOpts = function() {
    LocationManagerAppItem.__super__.initOpts.call(this, this.opts);
    return this.addOpts({
      location: {
        check: "PlainObject"
      }
    });
  };

  LocationManagerAppItem.prototype.readOpts = function() {
    var emptyLocation;
    LocationManagerAppItem.__super__.readOpts.call(this);
    if (this._location) {
      return this._loadData(this._location);
    } else {
      emptyLocation = {
        id: void 0,
        kind: "file",
        config: {
          file: {}
        }
      };
      return this._loadData(emptyLocation);
    }
  };

  LocationManagerAppItem.prototype.getId = function() {
    return this._location.id;
  };

  LocationManagerAppItem.prototype.getIdDisplayText = function() {
    return this.getId() || $$("location.manager.app.no_id");
  };

  LocationManagerAppItem.prototype.newKey = "location.manager.app.new";

  LocationManagerAppItem.prototype.getContent = function() {
    return "" + this._location.id;
  };

  LocationManagerAppItem.prototype.renderContent = function() {
    this.addColumn(new CUI.ListViewColumn({
      element: new CUI.Label({
        text: this._location.name
      })
    }));
    this.addColumn(new CUI.ListViewColumn({
      element: new CUI.Label({
        text: this._location.kind
      })
    }));
    this.addColumn(new CUI.ListViewColumn({
      element: new CUI.Label({
        text: this.getDefaultTargetsText()
      })
    }));
    this.addColumn(new CUI.ListViewColumn({
      element: new CUI.Label({
        text: this._location.status
      })
    }));
    return LocationManagerAppItem.__super__.renderContent.call(this);
  };

  LocationManagerAppItem.prototype.isDeletable = function() {
    return true;
  };

  LocationManagerAppItem.prototype.isWritable = function() {
    return true;
  };

  LocationManagerAppItem.prototype.getApi = function() {
    return "system";
  };

  LocationManagerAppItem.prototype.getEndpoint = function() {
    return "/location" + LocationManagerAppItem.__super__.getEndpoint.call(this);
  };

  LocationManagerAppItem.prototype._loadData = function(_location) {
    this._location = _location;
    if (!this._location.kind) {
      this._location.kind = "file";
    }
    return this;
  };

  LocationManagerAppItem.prototype.getTabs = function() {
    var tabs;
    this.__configDiv = new CUI.dom.div();
    this.showLocationFormConfig();
    tabs = [
      {
        name: "detail",
        text: $$("location.manager.app.tab.general"),
        content: (function(_this) {
          return function() {
            return new CUI.VerticalList({
              maximize: true,
              content: [
                new CUI.Form({
                  data: _this._location,
                  fields: _this.getGeneralFields(),
                  onDataChanged: function() {}
                }).start(), _this.__configDiv
              ]
            });
          };
        })(this)
      }
    ];
    return tabs;
  };

  LocationManagerAppItem.prototype.showLocationFormConfig = function() {
    return CUI.dom.replace(this.__configDiv, this.getTypeForm());
  };

  LocationManagerAppItem.prototype.getStatus = function() {
    var status;
    status = this._location.status;
    if (this._location.status === "error") {
      status = this._location.status + " : " + this._location.status_msg;
    }
    return status;
  };

  LocationManagerAppItem.prototype.getDefaultTargetsText = function() {
    var defaults, idStr, k, matched, ref, v;
    defaults = ((ref = ez5.session.getBaseConfig()) != null ? ref['location_defaults'] : void 0) || {};
    matched = [];
    idStr = this._location.id != null ? "" + this._location.id : "";
    for (k in defaults) {
      v = defaults[k];
      if (v == null) {
        continue;
      }
      if (v === this._location.name || ("" + v) === idStr) {
        matched.push(k);
      }
    }
    if (matched.length) {
      return matched.join(', ');
    } else {
      return '-';
    }
  };

  LocationManagerAppItem.prototype.getGeneralFields = function() {
    var fields, type_opts, type_select;
    type_opts = [
      {
        text: "Filesystem",
        value: "file"
      }, {
        text: "S3",
        value: "s3"
      }
    ];
    if (ez5.version("6.10")) {
      type_opts.push({
        text: "Azure",
        value: "azure"
      });
    }
    type_select = {
      type: CUI.Select,
      name: "kind",
      options: type_opts,
      form: {
        label: $$("location.manager.app.list.type")
      },
      onDataChanged: (function(_this) {
        return function(_, dataField) {
          return _this.showLocationFormConfig();
        };
      })(this)
    };
    fields = [
      {
        type: CUI.Output,
        text: "" + (this.getIdDisplayText()),
        form: {
          label: $$("backup.manager.app.list.id")
        }
      }, {
        type: CUI.Output,
        text: this.getStatus(),
        form: {
          label: $$("location.manager.app.list.status")
        }
      }, {
        type: CUI.Input,
        name: "name",
        form: {
          label: $$("location.manager.app.list.name")
        }
      }, {
        type: CUI.Input,
        name: "prefix",
        form: {
          label: $$("location.manager.app.list.prefix")
        }
      }, {
        type: CUI.Checkbox,
        name: "allow_purge",
        form: {
          label: $$("location.manager.app.config.list.allow_purge")
        }
      }, {
        type: CUI.Checkbox,
        name: "allow_redirect",
        form: {
          label: $$("location.manager.app.config.s3.allow_redirect")
        }
      }, {
        type: CUI.Checkbox,
        name: "read_only",
        form: {
          label: $$("location.manager.app.config.list.read_only")
        }
      }, type_select
    ];
    return fields;
  };

  LocationManagerAppItem.prototype.getSecretKeyPlaceholder = function(type, key) {
    var placeholder, ref, ref1, ref2;
    if ((ref = (ref1 = this._location.config) != null ? (ref2 = ref1[type]) != null ? ref2[key] : void 0 : void 0) === "***" || ref === "*****") {
      placeholder = this._location.config[type][key];
      delete this._location.config[type][key];
      return placeholder;
    }
    return "";
  };

  LocationManagerAppItem.prototype.getTypeForm = function() {
    var form, panelTitle;
    form = {};
    if (this._location.kind === "file") {
      if (!this._location.config.file) {
        this._location.config.file = {};
      }
      panelTitle = $$("location.manager.app.config.panel.file");
      form = new CUI.Form({
        padded: false,
        data: this._location.config.file,
        fields: [
          {
            type: CUI.Input,
            name: "dir",
            form: {
              label: $$("location.manager.app.config.file.dir")
            }
          }, {
            type: CUI.Input,
            name: "remote_url_prefix",
            regexp: "^(https?:\/\/.+\/)?$",
            placeholder: "https://example.com/",
            form: {
              label: $$("location.manager.app.config.file.remote_url_prefix"),
              hint: $$("location.manager.app.config.file.remote_url_prefix.hint")
            }
          }
        ]
      });
    } else if (this._location.kind === "azure") {
      if (!this._location.config.azure) {
        this._location.config.azure = {};
      }
      panelTitle = $$("location.manager.app.config.panel.azure");
      form = new CUI.Form({
        data: this._location.config.azure,
        fields: [
          {
            type: CUI.Input,
            name: "account_name",
            form: {
              label: $$("location.manager.app.config.azure.account_name")
            }
          }, {
            type: CUI.Input,
            name: "account_key",
            placeholder: this.getSecretKeyPlaceholder("azure", "account_key"),
            form: {
              label: $$("location.manager.app.config.azure.account_key")
            }
          }, {
            type: CUI.Input,
            name: "endpoint_suffix",
            form: {
              label: $$("location.manager.app.config.azure.endpoint_suffix")
            }
          }, {
            type: CUI.Input,
            name: "connection_string",
            placeholder: this.getSecretKeyPlaceholder("azure", "connection_string"),
            form: {
              label: $$("location.manager.app.config.azure.connection_string")
            }
          }, {
            type: CUI.Input,
            name: "container",
            form: {
              label: $$("location.manager.app.config.azure.container")
            }
          }
        ]
      });
    } else if (this._location.kind === "s3") {
      if (!this._location.config.s3) {
        this._location.config.s3 = {};
      }
      panelTitle = $$("location.manager.app.config.panel.s3");
      form = new CUI.Form({
        data: this._location.config.s3,
        fields: [
          {
            type: CUI.Input,
            name: "accesskey",
            form: {
              label: $$("location.manager.app.config.s3.access_key")
            }
          }, {
            type: CUI.Input,
            name: "secretkey",
            placeholder: this.getSecretKeyPlaceholder("s3", "secretkey"),
            form: {
              label: $$("location.manager.app.config.s3.secret_key")
            }
          }, {
            type: CUI.Input,
            name: "bucket",
            form: {
              label: $$("location.manager.app.config.s3.bucket")
            }
          }, {
            type: CUI.Input,
            name: "endpoint",
            form: {
              label: $$("location.manager.app.config.s3.endpoint")
            }
          }, {
            type: CUI.Input,
            name: "region",
            form: {
              label: $$("location.manager.app.config.s3.region")
            }
          }, {
            type: CUI.Checkbox,
            name: "ssl",
            form: {
              label: $$("location.manager.app.config.s3.ssl")
            }
          }, {
            type: CUI.Checkbox,
            name: "pathstyle",
            form: {
              label: $$("location.manager.app.config.s3.pathstyle")
            }
          }
        ]
      });
    }
    return new CUI.Panel({
      text: panelTitle,
      radio: "config",
      closed: false,
      content: (function(_this) {
        return function() {
          return form.start();
        };
      })(this)
    });
  };

  LocationManagerAppItem.prototype.getSaveData = function() {
    var data, ref, remote_url;
    data = CUI.util.copyObject(this._location, true);
    if (!data.id) {
      delete data.id;
    }
    delete data.created_at;
    if (data.kind === "azure") {
      if (!CUI.util.isEmpty(data.config.azure.account_name) || !CUI.util.isEmpty(data.config.azure.account_key) || !CUI.util.isEmpty(data.config.azure.endpoint_suffix)) {
        if (!CUI.util.isEmpty(data.config.azure.connection_string)) {
          throw new InvalidSaveDataException();
        }
      }
    }
    if (data.kind === "file" && ((ref = data.config.file) != null ? ref.remote_url_prefix : void 0)) {
      remote_url = data.config.file.remote_url_prefix;
      if (!/^https?:\/\/.+\/$/.test(remote_url)) {
        throw new InvalidSaveDataException();
      }
    }
    return data;
  };

  LocationManagerAppItem.prototype._save = function(ev, save_data) {
    var promise;
    if (ev != null ? ev.hasModifierKey() : void 0) {
      console.debug(CUI.util.getObjectClass(this), CUI.util.dump(save_data));
      return new CUI.rejectedPromise();
    }
    if (!this.getId()) {
      promise = ez5.api.system({
        api: "/location/new",
        type: "POST",
        json_data: save_data
      });
    } else {
      promise = ez5.api.system({
        api: "/location/" + (this.getId()),
        type: "PUT",
        json_data: save_data
      });
    }
    return promise;
  };

  LocationManagerAppItem.prototype.showSuccessAlert = function() {
    return CUI.alert({
      text: $$("location.manager.app.success_msg")
    });
  };

  LocationManagerAppItem.prototype.showErrorAlert = function(error) {
    return CUI.alert({
      text: $$("location.manager.app.error_msg", {
        error: error
      })
    });
  };

  LocationManagerAppItem.prototype.save = function(ev) {
    var ref, save_data;
    if ((ref = this.saveButton) != null) {
      ref.disable();
    }
    save_data = this.getSaveData();
    ez5.splash.show('system.list.manager.item.saving');
    return this._save(ev, save_data).done((function(_this) {
      return function(data) {
        _this.moveNodeConfirm();
        _this._loadData(data);
        return _this.load().done(function(data) {
          _this.show();
          ez5.splash.hide();
          if (data.status === "connected") {
            _this.showSuccessAlert();
            return _this.updateConfig();
          } else {
            return _this.showErrorAlert(data.status_msg);
          }
        }).fail(function() {
          return ez5.splash.hide();
        });
      };
    })(this)).fail((function(_this) {
      return function() {
        var ref1;
        if ((ref1 = _this.saveButton) != null) {
          ref1.enable();
        }
        return ez5.splash.hide();
      };
    })(this));
  };

  LocationManagerAppItem.prototype.updateConfig = function() {
    var updatedSession;
    return updatedSession = ez5.session.get(ez5.session.token);
  };

  return LocationManagerAppItem;

})(SystemListManagerItem);
// Generated by CoffeeScript 1.12.7
var AdminEventManager,
  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;

AdminEventManager = (function(superClass) {
  extend(AdminEventManager, superClass);

  function AdminEventManager() {
    return AdminEventManager.__super__.constructor.apply(this, arguments);
  }

  AdminEventManager.is_allowed = function() {
    return ez5.session.hasSystemRight("root", "system.api.event[get]", "system.api.event.get");
  };

  AdminEventManager.group = function() {
    return "zze_administration";
  };

  AdminEventManager.submenu = function() {
    return "administration";
  };

  AdminEventManager.path = function() {
    return ["eventmanager"];
  };

  AdminEventManager.label = function() {
    return "admin.event.manager.menu.label";
  };

  AdminEventManager.prototype.initOpts = function(opts) {
    if (ez5.version("6")) {
      this.__newApi = true;
    } else {
      this.__newApi = false;
    }
    return AdminEventManager.__super__.initOpts.call(this, opts);
  };

  AdminEventManager.prototype.getTreeOpts = function() {
    var columnClasses, columnKeys, filter, i, key, len, opts;
    opts = AdminEventManager.__super__.getTreeOpts.call(this);
    opts.filterManager = function() {};
    filter = new CUI.ListViewHeaderRow();
    this.__sortColumns = [];
    columnClasses = [];
    columnKeys = ["_id", "timestamp", "user_generated_displayname", "type", "type_key"];
    for (i = 0, len = columnKeys.length; i < len; i++) {
      key = columnKeys[i];
      filter.addColumn(this.getHeaderColumn(key));
      columnClasses.push("ez5-admin-event-manager-column-" + key);
    }
    opts.colClasses = columnClasses;
    opts.extra_header = filter;
    this.__sort = "_id.DESC";
    this.__updateSortButtons();
    opts.cols = ["auto", "auto", "auto", "auto", "auto"];
    opts.selectableRows = "multiple";
    return opts;
  };

  AdminEventManager.prototype.loadInternal = function() {
    AdminEventManager.__super__.loadInternal.call(this);
    this.__layout.replace(new CUI.SimplePane({
      "class": "cui-pane--window",
      title: $$("admin.event.manager.title"),
      content: this.tree.render()
    }), "center");
    return this;
  };

  AdminEventManager.prototype.readOpts = function() {
    AdminEventManager.__super__.readOpts.call(this);
    return this.__filter_data = {};
  };

  AdminEventManager.prototype.getRightPane = function() {
    return {
      content: {},
      flexHandle: {
        label: this.getMenuTitle(),
        state_name: "admin-manager-right",
        hidden: false
      }
    };
  };

  AdminEventManager.prototype.getContainer = function() {
    return this.__layout.right();
  };

  AdminEventManager.prototype.getEvents = function() {
    var ref;
    return (ref = ez5.session.getDefaults().server.events) != null ? ref.searchable_events.map((function(_this) {
      return function(event) {
        return {
          value: event,
          text: AdminEventManager.locaType(event)
        };
      };
    })(this)) : void 0;
  };

  AdminEventManager.prototype.__basetypes = [];

  AdminEventManager.prototype.getTreePaneContent = function() {
    var groupData, groupOptions, i, len, ref, ref1, sp, tpc, userGroupSelector, userType, userTypesOptions, userTypesOptionsField, vl;
    groupOptions = [];
    groupData = {};
    this.__searchIdInput = new CUI.Input({
      maximize_horizontal: true,
      name: "id",
      placeholder: this.__newApi ? $$("admin.event.manager.form.id.placeholder") : void 0,
      form: {
        label: $$("admin.event.manager.form.id")
      }
    });
    userTypesOptions = [];
    this.__filter_form = new CUI.Form({
      data: this.__filter_data,
      padded: true,
      onDataChanged: this.__enableDisableFormFields,
      fields: [
        this.__searchIdInput, this.getSelectFilter("type", this.getEvents(), {
          getOptionLabel: (function(_this) {
            return function(arg) {
              var text, value;
              value = arg.value, text = arg.text;
              return new CUI.VerticalList({
                content: [
                  new CUI.Label({
                    "class": "ez5-event-option-label",
                    text: text
                  }), new CUI.Label({
                    text: value,
                    appearance: "secondary",
                    size: "mini"
                  })
                ]
              });
            };
          })(this),
          getTagLabel: (function(_this) {
            return function(eventType) {
              return new CUI.Label({
                "class": "ez5-tag",
                text: AdminEventManager.locaType(eventType) + (" [" + eventType + "]")
              });
            };
          })(this)
        }), {
          maximize_horizontal: true,
          type: CUI.DateTime,
          ui: "admin-event-manager-form-date-from-datetime",
          undo_and_changed_support: false,
          form: {
            label: $$("admin.event.manager.form.date_from")
          },
          name: "from",
          display_type: "short",
          input_types: ["date_time"]
        }, {
          maximize_horizontal: true,
          type: CUI.DateTime,
          ui: "admin-event-manager-form-date-to-datetime",
          undo_and_changed_support: false,
          form: {
            label: $$("admin.event.manager.form.date_to")
          },
          name: "to",
          display_type: "short",
          input_types: ["date_time"]
        }, ez5.version("6.7") ? {
          maximize_horizontal: true,
          type: CUI.Input,
          name: "system_object_id",
          form: {
            label: $$("admin.event.manager.form.system_object_id")
          },
          placeholder: $$("admin.event.manager.form.system_object_id.placeholder")
        } : void 0, ez5.version("6.22") ? this.getSelectFilter("basetypes", this.__basetypes.map((function(_this) {
          return function(type) {
            return {
              text: type
            };
          };
        })(this)), {
          getOptionLabel: (function(_this) {
            return function(arg) {
              var text;
              text = arg.text;
              return new CUI.Label({
                text: text
              });
            };
          })(this),
          getTagLabel: (function(_this) {
            return function(basetype) {
              return new CUI.Label({
                "class": "ez5-tag",
                text: basetype
              });
            };
          })(this)
        }) : void 0, ez5.version("6.7") ? {
          type: ez5.ObjecttypeSelector,
          form: {
            label: $$("admin.event.manager.form.objecttype")
          },
          name: "objecttype",
          show_name: true,
          store_value: "fullname"
        } : void 0, new CUI.Options({
          maximize_horizontal: true,
          placeholder: "",
          form: {
            label: $$("admin.event.manager.form.user_types")
          },
          name: "userTypes",
          options: userTypesOptions
        }), new UserGroupSelector({
          maximize_horizontal: true,
          form: {
            label: $$("admin.event.manager.form.id_user")
          },
          name: "user",
          aclWhoManager: new AclWhoManager({
            who_filter: ["user"]
          })
        }), userGroupSelector = new UserGroupSelector({
          maximize_horizontal: true,
          form: {
            label: $$("admin.event.manager.form.id_group")
          },
          aclWhoManager: new AclWhoManager({
            store_full_data: true,
            filter_groups: ["system"],
            who_filter: ["group"]
          }),
          name: "group",
          data: groupData,
          onDataChanged: (function(_this) {
            return function() {
              var group, idGroup;
              group = groupData.group;
              if (!group) {
                return;
              }
              group = Group.newInstance({
                group: group
              });
              idGroup = group.getId();
              if (CUI.util.idxInArray(null, groupOptions, (function(v) {
                return v.value === idGroup;
              })) === -1) {
                groupOptions.push({
                  value: idGroup,
                  text: group.getDisplayText()
                });
              }
              userGroupSelector.setValue();
              CUI.util.pushOntoArray(idGroup, _this.__filter_data.groups);
              return _this.__filter_form.getFieldsByName("groups")[0].show(true).reload();
            };
          })(this)
        }), new CUI.Options({
          maximize_horizontal: true,
          placeholder: "",
          name: "groups",
          options: groupOptions,
          hidden: true
        })
      ]
    }).start();
    ref1 = ((ref = ez5.session.getDefaults().server.events) != null ? ref.searchable_event_user_types : void 0) || [];
    for (i = 0, len = ref1.length; i < len; i++) {
      userType = ref1[i];
      userTypesOptions.push({
        text: userType
      });
    }
    userTypesOptionsField = this.__filter_form.getFieldsByName("userTypes")[0];
    userTypesOptionsField.reload();
    this.__empty_filter_data = CUI.util.copyObject(this.__filter_data, true);
    sp = new CUI.SimplePane({
      content: this.__filter_form,
      footer_right: (function(_this) {
        return function() {
          var buttons;
          buttons = [
            {
              ui: "admin-event-manager-form-reset-button",
              loca_key: "admin.event.manager.form.button.reset",
              onClick: function() {
                _this.__resetFilters();
              }
            }, {
              ui: "admin-event-manager-form-refresh-button",
              loca_key: "admin.event.manager.form.button.go",
              primary: true,
              onClick: function() {
                _this.__refresh();
              }
            }
          ];
          return buttons;
        };
      })(this)
    });
    return sp;
    tpc = AdminEventManager.__super__.getTreePaneContent.call(this);
    vl = new CUI.VerticalLayout({
      maximize: true,
      top: {
        content: sp
      },
      center: {
        content: tpc
      }
    });
    return vl;
  };

  AdminEventManager.prototype.__resetFilters = function() {
    this.__filter_data = CUI.util.copyObject(this.__empty_filter_data, true);
    this.data = null;
    this.load();
  };

  AdminEventManager.prototype.__refresh = function() {
    var wb;
    wb = new CUI.WaitBlock({
      element: this.getTree()
    }).show();
    return this.loadTree(true).always((function(_this) {
      return function() {
        return wb.destroy();
      };
    })(this));
  };

  AdminEventManager.prototype.__updateSortButtons = function() {
    var i, len, ref, ref1, sc, sort_sc;
    ref = this.__sortColumns;
    for (i = 0, len = ref.length; i < len; i++) {
      sc = ref[i];
      if ((ref1 = this.__sort) != null ? ref1.startsWith(sc.key) : void 0) {
        sort_sc = sc;
      } else {
        sc.button.replace(new CUI.Icon(), "right");
      }
    }
    if (!sort_sc) {
      return;
    }
    if (this.__sort.match(/DESC$/)) {
      sort_sc.button.replace(new CUI.Icon({
        icon: "south"
      }), "right");
    } else {
      sort_sc.button.replace(new CUI.Icon({
        icon: "north"
      }), "right");
    }
    return this;
  };

  AdminEventManager.prototype.getHeaderColumn = function(key) {
    var sb;
    if (key === "type") {
      return new CUI.ListViewHeaderColumn({
        element: new LocaLabel({
          loca_key: "admin.event.manager.column." + key,
          right: true
        })
      });
    }
    sb = new LocaButton({
      loca_key: "admin.event.manager.column." + key,
      appearance: "link",
      right: true,
      onClick: (function(_this) {
        return function() {
          if (!_this.__sort || !_this.__sort.startsWith(key)) {
            _this.__sort = key + ".DESC";
          } else if (_this.__sort.endsWith("DESC")) {
            _this.__sort = key + ".ASC";
          } else {
            _this.__sort = "_id.DESC";
          }
          _this.__updateSortButtons();
          return _this.loadTree(true);
        };
      })(this)
    });
    if (key === "type_key") {
      key = "type";
    }
    this.__sortColumns.push({
      button: sb,
      key: key
    });
    return new CUI.ListViewHeaderColumn({
      element: sb
    });
  };

  AdminEventManager.locaType = function(k) {
    if (!k) {
      k = "Unknown";
    }
    return ez5.loca.str_default('admin.event.manager.event.' + k.toLowerCase(), k);
  };

  AdminEventManager.prototype.getSelectFilter = function(key, options, arg) {
    var getOptionLabel, getTagLabel;
    getOptionLabel = arg.getOptionLabel, getTagLabel = arg.getTagLabel;
    options.sort(function(optionOne, optionTwo) {
      return optionOne.text.localeCompare(optionTwo.text);
    });
    return {
      type: CUI.FormPopover,
      maximize_horizontal: true,
      ui: "admin-event-manager-type-form-select",
      popover: {
        "class": "ez5-admin-event-manager-select",
        use_element_width_as_min_width: true,
        pointer: null,
        placements: ["se"],
        pane: {
          padded: true
        },
        placement: "se"
      },
      form: {
        label: $$("admin.event.manager.form." + key)
      },
      button: {
        "class": "ez5-admin-event-manager-select cui-button--has-caret",
        text: $$("admin.event.manager.select.button." + key),
        icon_right: "fa-angle-down"
      },
      renderDisplayContent: (function(_this) {
        return function() {
          var div, i, len, ref, ref1, type;
          if (!((ref = _this.__filter_data[key]) != null ? ref.length : void 0)) {
            return;
          }
          div = CUI.dom.element("DIV", {
            "class": "ez5-tag-holder"
          });
          ref1 = _this.__filter_data[key];
          for (i = 0, len = ref1.length; i < len; i++) {
            type = ref1[i];
            div.appendChild(getTagLabel(type).DOM);
          }
          return div;
        };
      })(this),
      fields: [
        {
          type: CUI.Options,
          horizontal: false,
          name: key,
          options: options.map((function(_this) {
            return function(arg1) {
              var text, value;
              value = arg1.value, text = arg1.text;
              return {
                ui: "admin-event-manager-" + (value || text) + "-select-option",
                value: value || text,
                content: getOptionLabel({
                  value: value,
                  text: text
                })
              };
            };
          })(this))
        }
      ]
    };
  };

  AdminEventManager.prototype.getMissingName = function() {
    return $$("admin.event.manager.missing_name");
  };

  AdminEventManager.prototype.getLeftTitle = function() {
    return $$("admin.event.manager.search.title");
  };

  AdminEventManager.prototype.getCenterTitle = function() {
    return $$("admin.event.manager.pane_title");
  };

  AdminEventManager.prototype.getMenuTitle = function() {
    return new CUI.Label({
      text: $$("admin.event.manager.title")
    });
  };

  AdminEventManager.prototype.getListFields = function() {};

  AdminEventManager.prototype.getTitle = function() {
    return new CUI.Label({
      text: $$("admin.event.manager.pane_title")
    });
  };

  AdminEventManager.prototype.loadList = function(filter, opts) {
    var dfr, searchCallback, searchOpts;
    if (opts == null) {
      opts = {};
    }
    if (opts.searchOpts) {
      searchOpts = opts.searchOpts;
    } else {
      searchOpts = {};
    }
    searchOpts = this.__getSearchOpts(searchOpts);
    dfr = new CUI.Deferred();
    searchCallback = (function(_this) {
      return function(data) {
        var _data, event, events, i, len, ref, ref1, ref2;
        if (CUI.util.isEmpty(data)) {
          dfr.reject();
          return;
        }
        if (data.offset == null) {
          data.offset = 0;
        }
        events = [];
        ref = data.objects;
        for (i = 0, len = ref.length; i < len; i++) {
          event = ref[i];
          events.push(new AdminEventManagerEvent({
            event: event,
            manager: _this
          }));
        }
        if (events.length > 0) {
          _this.__csvButton.enable();
          if ((ref1 = _this.__deleteButton) != null) {
            ref1.enable();
          }
        } else {
          _this.__csvButton.disable();
          if ((ref2 = _this.__deleteButton) != null) {
            ref2.disable();
          }
        }
        _data = {
          count: data.count,
          offset: data.offset,
          limit: data.limit,
          objects: data
        };
        _this.__count = data.count;
        return dfr.resolve(events, _data);
      };
    })(this);
    ez5.splash.show("admin.event.manager.splash.loading-events");
    if (this.__newApi || CUI.util.isEmpty(this.__filter_data.id)) {
      ez5.api.event({
        api: "/list",
        data: searchOpts
      }).done(searchCallback).fail(dfr.reject);
    } else {
      ez5.api.event({
        api: "/" + this.__filter_data.id
      }).done((function(_this) {
        return function(data) {
          var ref;
          data = {
            objects: [data],
            count: 1,
            limit: 1
          };
          searchCallback(data);
          _this.__csvButton.disable();
          return (ref = _this.__deleteButton) != null ? ref.disable() : void 0;
        };
      })(this)).fail((function(_this) {
        return function() {
          var data;
          data = {
            objects: [],
            count: 0,
            limit: 1
          };
          return searchCallback(data);
        };
      })(this));
    }
    dfr.always((function(_this) {
      return function() {
        return ez5.splash.hide();
      };
    })(this));
    return dfr.promise();
  };

  AdminEventManager.prototype.__getSearchOpts = function(searchOpts) {
    var ref;
    if (searchOpts == null) {
      searchOpts = {};
    }
    if (!searchOpts.limit) {
      searchOpts.limit = 100;
    }
    if (!searchOpts.offset) {
      searchOpts.offset = 0;
    }
    if (this.__newApi && !CUI.util.isEmpty(this.__filter_data.id)) {
      searchOpts.id = this.__filter_data.id;
    }
    if (((ref = this.__filter_data.type) != null ? ref.length : void 0) > 0) {
      searchOpts.type = this.__filter_data.type.join(",");
    }
    if (!CUI.util.isEmpty(this.__filter_data.from)) {
      searchOpts.date_from = this.__filter_data.from;
    }
    if (!CUI.util.isEmpty(this.__filter_data.to)) {
      searchOpts.date_to = this.__filter_data.to;
    }
    if (!CUI.util.isEmpty(this.__filter_data.user)) {
      searchOpts.user_id = this.__filter_data.user.user._id;
    }
    if (!CUI.util.isEmpty(this.__filter_data.groups)) {
      searchOpts.group_id = this.__filter_data.groups.join(",");
    }
    if (!CUI.util.isEmpty(this.__filter_data.basetypes)) {
      searchOpts.basetype = this.__filter_data.basetypes.join(",");
    }
    if (!CUI.util.isEmpty(this.__filter_data.userTypes)) {
      searchOpts.user_type = this.__filter_data.userTypes.join(",");
    }
    if (ez5.version("6.7") && !CUI.util.isEmpty(this.__filter_data.objecttype)) {
      searchOpts.objecttype = this.__filter_data.objecttype;
    }
    if (ez5.version("6.7") && !CUI.util.isEmpty(this.__filter_data.system_object_id)) {
      searchOpts.system_object_id = this.__filter_data.system_object_id;
    }
    if (this.__sort) {
      if (this.__sort.indexOf("_id.") === -1) {
        searchOpts.sort = this.__sort + ",_id.DESC";
      } else {
        searchOpts.sort = this.__sort;
      }
    }
    return searchOpts;
  };

  AdminEventManager.prototype.loadTree = function(refresh) {
    if (refresh == null) {
      refresh = false;
    }
    if (refresh) {
      return AdminEventManager.__super__.loadTree.call(this);
    } else {
      this.setStatus();
      return CUI.resolvedPromise();
    }
  };

  AdminEventManager.prototype.__getCSVDownloadURL = function(_searchOpts) {
    var searchOpts, url;
    searchOpts = this.__getSearchOpts();
    delete searchOpts.limit;
    CUI.util.mergeMap(searchOpts, _searchOpts);
    searchOpts.format = "csv";
    searchOpts.csv_use_bom = "true";
    searchOpts.csv_explode_array_concat = ",";
    searchOpts.csv_delimiter = ";";
    searchOpts.offset = 0;
    url = ez5.api.getFullBase() + "/event/list?" + ez5.tokenParam + "=" + ez5.session.token + "&";
    url += CUI.encodeUrlData(searchOpts);
    return url;
  };

  AdminEventManager.prototype.__deleteAll = function() {
    var alert, deleteApiInvocation, deletedCount, doDelete, showSuccess;
    deleteApiInvocation = null;
    deletedCount = 0;
    alert = new CUI.Alert({
      text: $$("admin.event.manager.remove_loading.text"),
      text_icon: "spinner",
      button_text_ok: $$("admin.event.manager.remove_loading.abort-button")
    });
    alert.open().done((function(_this) {
      return function() {
        if (deleteApiInvocation != null) {
          deleteApiInvocation.abort();
        }
        alert.destroy();
        return showSuccess(deletedCount);
      };
    })(this));
    showSuccess = (function(_this) {
      return function(count) {
        return CUI.alert({
          text: $$("admin.event.manager.remove_from_server_confirm.done", {
            count: count
          })
        }).done(function() {
          return _this.__refresh();
        });
      };
    })(this);
    doDelete = (function(_this) {
      return function() {
        var api;
        if (_this.__newApi) {
          api = "/list";
        } else {
          api = "";
        }
        return deleteApiInvocation = ez5.api.event({
          type: "DELETE",
          api: api,
          data: _this.__getDeleteUrlData()
        }).done(function(data) {
          if (ez5.version("6")) {
            if (alert != null) {
              alert.destroy();
            }
            showSuccess(_this.__count);
            return;
          }
          if (deletedCount >= _this.__count) {
            if (alert != null) {
              alert.destroy();
            }
            return showSuccess(deletedCount);
          } else {
            deletedCount += data.count;
            return doDelete();
          }
        }).fail(function() {
          if (alert != null) {
            alert.destroy();
          }
          return showSuccess(deletedCount);
        });
      };
    })(this);
    return doDelete();
  };

  AdminEventManager.prototype.__getDeleteUrlData = function() {
    var searchOpts;
    searchOpts = this.__getSearchOpts();
    delete searchOpts.limit;
    searchOpts.offset = 0;
    return searchOpts;
  };

  AdminEventManager.prototype.deleteRows = function(rows) {
    var i, ids, len, row;
    ids = [];
    for (i = 0, len = rows.length; i < len; i++) {
      row = rows[i];
      ids.push(row.getID());
    }
    return this.__deleteMultipleById(ids);
  };

  AdminEventManager.prototype.load = function() {
    var gridBody, label, loadPromise;
    if (ez5.session.hasSystemRight("root", "system.api.event.get", "system.api.event[get]")) {
      loadPromise = ez5.version("6.22") ? ez5.api.search({
        json_data: {
          type: "event",
          limit: 0,
          aggregations: {
            basetypes: {
              field: "event.basetype",
              type: "term"
            }
          }
        }
      }).done((function(_this) {
        return function(data) {
          _this.__basetypes = data.aggregations.basetypes.terms.map(function(arg) {
            var term;
            term = arg.term;
            return term;
          });
          return AdminEventManager.__super__.load.call(_this);
        };
      })(this)) : AdminEventManager.__super__.load.call(this);
      gridBody = this.__getTreeGridBody();
      if (gridBody) {
        new CUI.Lasso({
          element: gridBody,
          create: (function(_this) {
            return function(ev) {
              return ev.hasModifierKey(true);
            };
          })(this),
          dragstart: (function(_this) {
            return function() {
              var i, len, results, selectedRow, selectedRows;
              selectedRows = _this.tree.getSelectedRows();
              if (selectedRows.length > 0) {
                results = [];
                for (i = 0, len = selectedRows.length; i < len; i++) {
                  selectedRow = selectedRows[i];
                  results.push(selectedRow != null ? selectedRow.deselect(null) : void 0);
                }
                return results;
              }
            };
          })(this),
          selected: (function(_this) {
            return function(ev, info) {
              var element, i, len, listViewRow, ref;
              ref = info.elements;
              for (i = 0, len = ref.length; i < len; i++) {
                element = ref[i];
                listViewRow = CUI.dom.data(element, "listViewRow");
                if (listViewRow != null) {
                  listViewRow.select(ev);
                }
              }
              return true;
            };
          })(this)
        });
      }
      return loadPromise;
    } else {
      label = new CUI.Label({
        text: $$("admin.event.manager.no_rights"),
        multiline: true,
        centered: true,
        appearance: 'secondary'
      });
      ez5.rootLayout.replace(label, "center");
    }
    return CUI.resolvedPromise();
  };

  AdminEventManager.prototype.unload = function() {
    var gridBody;
    gridBody = this.__getTreeGridBody();
    if (gridBody) {
      CUI.Lasso.destroy(gridBody);
    }
    return AdminEventManager.__super__.unload.call(this);
  };

  AdminEventManager.prototype.__getTreeGridBody = function() {
    var grid, ref;
    grid = (ref = this.tree) != null ? ref.getBottom() : void 0;
    if (!grid) {
      return;
    }
    return CUI.dom.children(grid)[0];
  };

  AdminEventManager.prototype.__deleteMultipleById = function(ids) {
    var alertKey, call, textKey, titleKey;
    if (ids == null) {
      ids = [];
    }
    if (this.__newApi) {
      call = {
        type: "DELETE",
        api: "/list",
        data: {
          id: ids.join(",")
        }
      };
    } else {
      call = {
        type: "DELETE",
        json_data: ids
      };
    }
    if (ids.length > 1) {
      titleKey = $$("admin.event.manager.remove_from_server_confirm.title");
      textKey = $$("admin.event.manager.remove_from_server_confirm.text", {
        count: ids.length
      });
      alertKey = $$("admin.event.manager.remove_from_server_confirm.done", {
        count: ids.length
      });
    } else {
      titleKey = $$("admin.event.manager.remove_from_server_confirm.title.one");
      textKey = $$("admin.event.manager.remove_from_server_confirm.text.one");
      alertKey = $$("admin.event.manager.remove_from_server_confirm.done.one");
    }
    return CUI.confirm({
      title: titleKey,
      text: textKey
    }).done((function(_this) {
      return function() {
        return ez5.api.event(call).done(function() {
          return CUI.alert({
            text: alertKey
          }).done(function() {
            if (!_this.__newApi && _this.__filter_data.id) {
              _this.__searchIdInput.setValue("");
              _this.__enableDisableFormFields(_this.__filter_data, _this.__searchIdInput);
            }
            return _this.__refresh();
          });
        });
      };
    })(this));
  };

  AdminEventManager.prototype.__enableDisableFormFields = function(data, input) {
    var field, i, len, ref, results;
    if (this.__newApi) {
      return;
    }
    ref = input.getForm().getFields();
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      field = ref[i];
      if (field !== input) {
        if (data.id) {
          results.push(field.disable());
        } else {
          results.push(field.enable());
        }
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  AdminEventManager.prototype.getPlusButton = function() {};

  AdminEventManager.prototype.getExtraButton = function() {
    return [
      ez5.session.hasSystemRight("root", "system.api.event.delete", "system.api.event[delete]") ? this.__deleteButton = new LocaButton({
        ui: "admin.event.manager-remove-from-server-button",
        loca_key: "admin.event.manager.remove_from_server",
        disabled: true,
        onClick: (function(_this) {
          return function() {
            return CUI.confirm({
              title: $$("admin.event.manager.remove_from_server_confirm.title"),
              button_text_ok: $$("admin.event.manager.remove_from_server_confirm.ok"),
              button_text_cancel: $$("admin.event.manager.remove_from_server_confirm.cancel"),
              text: $$("admin.event.manager.remove_from_server_confirm.text", {
                count: _this.__count
              })
            }).done(function() {
              return _this.__deleteAll();
            });
          };
        })(this)
      }) : void 0, this.__csvButton = new LocaButtonHref({
        loca_key: "admin.event.manager.csv_download",
        disabled: true,
        onClick: (function(_this) {
          return function() {
            var data, form, modal;
            data = {
              csv_max_length: true,
              csv_explode_info: true
            };
            form = new CUI.Form({
              data: data,
              fields: [
                {
                  type: CUI.Checkbox,
                  name: "csv_explode_info",
                  form: {
                    label: $$("admin.event.manager.csv-download.form.explode_info.label")
                  }
                }, {
                  type: CUI.Checkbox,
                  name: "csv_max_length",
                  form: {
                    label: $$("admin.event.manager.csv-download.form.max_length.label")
                  }
                }
              ]
            });
            form.start();
            modal = new CUI.Modal({
              cancel: true,
              onCancel: function() {
                modal.destroy();
              },
              pane: {
                padded: true,
                header_left: new CUI.Label({
                  text: $$("admin.event.manager.csv-download.modal.header.label")
                }),
                content: form,
                footer_right: new LocaButton({
                  loca_key: "admin.event.manager.csv-download.modal.button",
                  onClick: function() {
                    var downloadUrl, opts;
                    opts = {
                      csv_max_length: data.csv_max_length ? 100 : 0,
                      csv_explode: data.csv_explode_info ? "true" : void 0
                    };
                    downloadUrl = _this.__getCSVDownloadURL(opts);
                    ez5.download_file({
                      href: downloadUrl,
                      name: CUI.util.moment().format('YYYY-MM-DD') + "_events.csv"
                    });
                    return modal.doCancel();
                  }
                })
              }
            });
            return modal.show();
          };
        })(this)
      })
    ];
  };

  AdminEventManager.prototype.getMinusButton = function() {
    if (ez5.session.hasSystemRight("root", "system.api.event.delete", "system.api.event[delete]")) {
      return AdminEventManager.__super__.getMinusButton.call(this);
    }
    return null;
  };

  return AdminEventManager;

})(SystemListManager);

ez5.session_ready(function() {
  return ez5.rootMenu.registerApp(AdminEventManager);
});
// Generated by CoffeeScript 1.12.7
var AdminEventManagerEvent,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

AdminEventManagerEvent = (function(superClass) {
  extend(AdminEventManagerEvent, superClass);

  function AdminEventManagerEvent() {
    return AdminEventManagerEvent.__super__.constructor.apply(this, arguments);
  }

  AdminEventManagerEvent.prototype.initOpts = function() {
    AdminEventManagerEvent.__super__.initOpts.call(this);
    return this.addOpts({
      event: {
        check: "PlainObject"
      }
    });
  };

  AdminEventManagerEvent.prototype.readOpts = function() {
    AdminEventManagerEvent.__super__.readOpts.call(this);
    return this.__event = this._event;
  };

  AdminEventManagerEvent.prototype.renderContent = function() {
    this.addColumn(new CUI.ListViewColumn({
      text: this.getTimestamp()
    }));
    this.addColumn(new CUI.ListViewColumn({
      text: this.getUserGeneratedDisplayname()
    }));
    this.addColumn(new CUI.ListViewColumn({
      text: AdminEventManager.locaType(this.getType())
    }));
    this.addColumn(new CUI.ListViewColumn({
      text: this.getType()
    }));
    return new CUI.Label({
      text: this.getID()
    });
  };

  AdminEventManagerEvent.prototype.isDeletable = function() {
    return true;
  };

  AdminEventManagerEvent.prototype.getEvent = function() {
    return this.__event.event;
  };

  AdminEventManagerEvent.prototype.getType = function() {
    return this.getEvent().type;
  };

  AdminEventManagerEvent.prototype.getID = function() {
    return this.getEvent()._id;
  };

  AdminEventManagerEvent.prototype.getUserGeneratedDisplayname = function() {
    if (this.__event.user) {
      return this.__event.user._generated_displayname || ("" + this.__event.user._id);
    } else {
      return $$("admin.event.manager.user_generated_displayname.system");
    }
  };

  AdminEventManagerEvent.prototype.registerDataChangedListener = function() {};

  AdminEventManagerEvent.prototype.load = function() {
    var ref;
    if (((ref = this.manager.getTree().getSelectedRows()) != null ? ref.length : void 0) > 1) {
      return CUI.resolvedPromise();
    }
    return ez5.api.event({
      api: "/" + this.getID()
    }).done((function(_this) {
      return function(__event) {
        _this.__event = __event;
      };
    })(this));
  };

  AdminEventManagerEvent.prototype.getTimestamp = function() {
    return ez5.format_date_and_time(this.getEvent().timestamp, true);
  };

  AdminEventManagerEvent.prototype.getPaneContent = function() {
    var assetId, data, ev, field, fields, getAssetId, getSystemObjectIdFromGlobalId, i, k, labelId, len, objectDumper, ref, ref1, ref2, ref3, ref4, ref5, ref6, value;
    ev = this.getEvent();
    fields = [];
    getAssetId = (function(_this) {
      return function() {
        var ref, value;
        value = (ref = ev.info) != null ? ref.asset_id : void 0;
        if (!value && ev.object_id && ev.basetype === "asset") {
          value = ev.object_id;
        }
        return value;
      };
    })(this);
    getSystemObjectIdFromGlobalId = (function(_this) {
      return function() {
        var gid, instance, ref, ref1, ref2, soId;
        gid = ev.global_object_id || ((ref = ev.info) != null ? ref.global_object_id : void 0);
        if (CUI.util.isEmpty(gid)) {
          return null;
        }
        ref1 = ("" + gid).split("@"), soId = ref1[0], instance = ref1[1];
        if (instance === ((ref2 = ez5.session.getInstance()) != null ? ref2.name : void 0)) {
          return parseInt(soId);
        } else {
          return null;
        }
      };
    })(this);
    ref = ["_id", "type", "timestamp", "remote_addr", "object_version", "schema", "user_generated_displayname", "basetype", "objecttype", "object_id", "global_object_id", "system_object_id", "objects_id", "asset_id", "assets_info", "info"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      switch (k) {
        case "timestamp":
          value = this.getTimestamp();
          break;
        case "user_generated_displayname":
          value = this.getUserGeneratedDisplayname();
          break;
        case "type":
          value = AdminEventManager.locaType(ev[k]) + ' [' + ev[k] + ']';
          break;
        case "global_object_id":
          value = ev.global_object_id || ((ref1 = ev.info) != null ? ref1.global_object_id : void 0);
          break;
        case "system_object_id":
          value = ((ref2 = ev.info) != null ? ref2.system_object_id : void 0) || getSystemObjectIdFromGlobalId();
          break;
        case "object_id":
          assetId = getAssetId();
          if (!assetId) {
            value = ev.object_id || ((ref3 = ev.info) != null ? ref3.object_id : void 0);
          }
          break;
        case "objects_id":
          value = this.__getObjectsIdList(ev);
          break;
        case "asset_id":
          value = getAssetId();
          break;
        case "assets_info":
          data = ((ref4 = ev.info) != null ? ref4.assets : void 0) ? ev.info.assets.map((function(_this) {
            return function(asset) {
              return {
                id: asset.id,
                text: $$("admin.event.manager.column.assets_id.link", {
                  id: "" + asset.id,
                  "class": "" + asset["class"]
                })
              };
            };
          })(this)) : (ref5 = ev.info) != null ? (ref6 = ref5.files) != null ? ref6.filter((function(_this) {
            return function(file) {
              return file._id !== void 0;
            };
          })(this)).map((function(_this) {
            return function(file) {
              return {
                id: file._id,
                text: "Asset #" + file._id,
                tooltip: {
                  text: file.path,
                  placement: "w"
                }
              };
            };
          })(this)) : void 0 : void 0;
          value = this.__getAssetsList(data);
          break;
        default:
          value = ev[k];
      }
      if (CUI.util.isEmpty(value)) {
        continue;
      }
      if (CUI.isPlainObject(value) || CUI.isArray(value)) {
        objectDumper = new CUI.ObjectDumper({
          object: value,
          parse_json: true
        });
        fields.push(this.__getOutputContentField(objectDumper, k));
      } else if (value instanceof CUI.DOMElement || value instanceof HTMLElement) {
        fields.push(this.__getOutputContentField(value, k));
      } else {
        labelId = ev.basetype === "file" && k === "object_id" ? "asset_id" : k;
        field = {
          form: {
            label: $$("admin.event.manager.column." + labelId + "|text")
          }
        };
        field.type = CUI.Output;
        field.text = value + "";
        fields.push(field);
      }
    }
    return new CUI.Form({
      fields: fields,
      "class": "ez5-admin-event-manager-event-details"
    }).start();
  };

  AdminEventManagerEvent.prototype.getEditorPane = function() {
    return new CUI.SimplePane({
      "class": "cui-pane--window",
      header_left: this.manager.getTitle(),
      padded: true,
      content: this.getPaneContent(),
      footer_right: (function(_this) {
        return function() {
          return [
            _this.__getObjectModalButton(), new LocaButton({
              loca_key: "admin.event.manager.event.button.close",
              primary: true,
              onClick: function() {
                return _this.deselect();
              }
            })
          ];
        };
      })(this)
    });
  };

  AdminEventManagerEvent.prototype.__getOutputContentField = function(content, key) {
    return {
      type: CUI.OutputContent,
      maximize_horizontal: true,
      content: content,
      form: {
        label: $$("admin.event.manager.column." + key + "|text")
      }
    };
  };

  AdminEventManagerEvent.prototype.__getObjectsIdList = function(ev) {
    var ref, ul;
    if (CUI.util.isEmpty((ref = ev.info) != null ? ref.global_object_ids : void 0)) {
      return null;
    }
    ul = new CUI.dom.ul();
    ev.info.global_object_ids.forEach((function(_this) {
      return function(objectId) {
        var li;
        li = new CUI.dom.li();
        CUI.dom.append(li, new CUI.ButtonHref({
          text: "" + objectId,
          onClick: function() {
            var loadPromise;
            ez5.splash.show("admin.event.manager.splash.loading-object");
            loadPromise = ResultObject.loadFromGlobalObjectId(objectId);
            return loadPromise.done(function(resultObject) {
              return resultObject.showModal();
            }).always(function() {
              return ez5.splash.hide();
            }).fail(function() {
              return CUI.alert({
                text: $$("admin.event.manager.alert.object_not_found")
              });
            });
          }
        }));
        return ul.appendChild(li);
      };
    })(this));
    return ul;
  };

  AdminEventManagerEvent.prototype.__getAssetsList = function(data) {
    var ul;
    if (data == null) {
      data = [];
    }
    if (CUI.util.isEmpty(data)) {
      return null;
    }
    ul = new CUI.dom.ul();
    data.forEach((function(_this) {
      return function(asset) {
        var li;
        li = new CUI.dom.li();
        CUI.dom.append(li, new CUI.ButtonHref({
          appearance: "link",
          text: asset.text,
          tooltip: asset.tooltip,
          onClick: function() {
            return ez5.api.eas({
              type: "GET",
              data: {
                ids: JSON.stringify([asset.id]),
                format: "long"
              }
            }).done(function(data) {
              var ref, ref1;
              _this.__eas = data[asset.id];
              if ((ref = _this.__eas.versions) != null ? ref.original : void 0) {
                return window.open(Session.addToken(_this.__eas.versions.original.url));
              } else if (((ref1 = Object.keys(_this.__eas.versions)) != null ? ref1.length : void 0) > 0) {
                return window.open(Session.addToken(_this.__eas.versions[Object.keys(_this.__eas.versions)[0]].url));
              } else {
                return CUI.alert({
                  text: $$("admin.event.manager.alert.file_not_found")
                });
              }
            });
          }
        }));
        return ul.appendChild(li);
      };
    })(this));
    return ul;
  };

  AdminEventManagerEvent.prototype.__getObjectModalButton = function() {
    var ev, ref, result, showFileEvents;
    result = [];
    ev = this.getEvent();
    if (ev.type === "OBJECT_DELETE" || ev.type === "OBJECT_PURGE") {
      return result;
    }
    if (ev != null ? ev.global_object_id : void 0) {
      result.push(new CUI.Button({
        text: $$("admin.event.manager.column.show_object.button"),
        onClick: (function(_this) {
          return function() {
            var loadPromise;
            ez5.splash.show("admin.event.manager.splash.loading-object");
            loadPromise = ResultObject.loadFromGlobalObjectId(ev.global_object_id);
            return loadPromise.done(function(resultObject) {
              return resultObject.showModal();
            }).always(function() {
              return ez5.splash.hide();
            }).fail(function() {
              return CUI.alert({
                text: $$("admin.event.manager.alert.object_not_found")
              });
            });
          };
        })(this)
      }));
    }
    showFileEvents = ["ASSET_DOWNLOAD", "ASSET_EXPORT_DOWNLOAD", "ASSET_EXPORT_TRANSPORT_COPY", "ASSET_EXPORT_TRANSPORT_COPY_SCHEDULED", "ASSET_EXPORT_TRANSPORT_DOWNLOAD", "EXPORT_ASSET", "COLLECTION_UPLOAD", "FILE_DOWNLOAD", "FILE_DOWNLOAD_ERROR", "FILE_METADATA", "FILE_METADATA_ERROR", "FILE_MOVE", "FILE_MOVE_ERROR", "FILE_PRODUCE", "FILE_UPLOAD", "FILE_UPLOAD_REMOTE"];
    if (ref = ev.type, indexOf.call(showFileEvents, ref) >= 0) {
      result.push(new CUI.Button({
        text: $$("admin.event.manager.column.show_file.button"),
        target: "_blank",
        onClick: (function(_this) {
          return function() {
            var fileId, ref1;
            fileId = ev.type === "COLLECTION_UPLOAD" ? ev.info.file_eas_id : (ref1 = ev.object_id) != null ? ref1 : ev.info.asset_id;
            return ez5.api.eas({
              type: "GET",
              data: {
                ids: JSON.stringify([fileId]),
                format: "long"
              }
            }).done(function(data) {
              var ref2, ref3;
              _this.__eas = data[fileId];
              if ((ref2 = _this.__eas.versions) != null ? ref2.original : void 0) {
                return window.open(Session.addToken(_this.__eas.versions.original.url));
              } else if (((ref3 = Object.keys(_this.__eas.versions)) != null ? ref3.length : void 0) > 0) {
                return window.open(Session.addToken(_this.__eas.versions[Object.keys(_this.__eas.versions)[0]].url));
              } else {
                return CUI.alert({
                  text: $$("admin.event.manager.alert.file_not_found")
                });
              }
            });
          };
        })(this)
      }));
    }
    return result;
  };

  AdminEventManagerEvent.prototype["delete"] = function() {
    return this.manager.__deleteMultipleById([this.getID()]);
  };

  AdminEventManagerEvent.prototype.select = function(ev) {
    if (this.manager.__loadedEvent !== this.getID()) {
      this.manager.__loadedEvent = this.getID();
    } else {
      this.manager.__loadedEvent = null;
      this.deselect();
      return CUI.rejectedPromise();
    }
    return AdminEventManagerEvent.__super__.select.call(this, ev);
  };

  return AdminEventManagerEvent;

})(SystemListManagerItem);
// Generated by CoffeeScript 1.12.7
var PoolManager,
  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;

PoolManager = (function(superClass) {
  extend(PoolManager, superClass);

  PoolManager.is_allowed = function() {
    return ez5.session.hasSystemRight("root", "poolmanager");
  };

  PoolManager.label = function() {
    return "admin.menu.pools";
  };

  PoolManager.group = function() {
    return "rightsmanagement";
  };

  PoolManager.submenu = function() {
    return "rightsmanagement";
  };

  PoolManager.path = function() {
    return ["poolmanager"];
  };

  function PoolManager(opts1) {
    this.opts = opts1 != null ? opts1 : {};
    this.loadList = bind(this.loadList, this);
    this.getNewNode = bind(this.getNewNode, this);
    PoolManager.__super__.constructor.call(this, this.opts);
    if (this._auto_reload) {
      EventPoller.listen({
        instance: this,
        filter: {
          type: ["OBJECT_INDEX", "OBJECT_DELETE"],
          basetype: "pool"
        },
        call: (function(_this) {
          return function(events) {
            return _this.loadList();
          };
        })(this)
      });
    }
  }

  PoolManager.prototype.initOpts = function() {
    PoolManager.__super__.initOpts.call(this);
    return this.addOpts({
      auto_reload: {
        "default": false,
        mandatory: true,
        check: Boolean
      },
      isPoolSelectable: {
        check: Function
      }
    });
  };

  PoolManager.prototype.getListFields = function() {
    return [
      {
        th_label: "admin.easydb.pool.list.name"
      }
    ];
  };

  PoolManager.prototype.getMissingName = function() {
    return $$("admin.easydb.pool.missing.name");
  };

  PoolManager.prototype.getLeftTitle = function() {
    return $$("admin.easydb.pool.pane.left.title");
  };

  PoolManager.prototype.getCenterTitle = function() {
    return $$("admin.easydb.pool.pane.center.title");
  };

  PoolManager.prototype.getNewRootText = function() {
    return $$("admin.easydb.pool.new");
  };

  PoolManager.prototype.getNewNode = function() {
    return new this.poolClass({
      manager: this
    });
  };

  PoolManager.prototype.getNavigationLocaKeyPrefix = function() {
    return "result.navigation.toolbar.pool";
  };

  PoolManager.prototype.getNoRecordLocaKey = function() {
    return $$("result.navigation.toolbar.pool.no_pools");
  };

  PoolManager.prototype.rootCanHaveChildren = function() {
    return false;
  };

  PoolManager.prototype.load = function() {
    this.__eventPoll = EventPoller.listen({
      instance: this,
      filter: {
        type: ["POOL_UPDATE"],
        basetype: "pool"
      },
      call: (function(_this) {
        return function(events) {
          var event, i, len, ref, selectedPoolId;
          selectedPoolId = ((ref = _this.tree.getSelectedNode()) != null ? ref.id : void 0) || null;
          if (!selectedPoolId) {
            _this.loadTree();
            return;
          }
          for (i = 0, len = events.length; i < len; i++) {
            event = events[i];
            if (event.object_id !== selectedPoolId) {
              _this.loadTreeAndReselectPool(selectedPoolId);
              return;
            }
          }
        };
      })(this)
    });
    return PoolManager.__super__.load.call(this);
  };

  PoolManager.prototype.unload = function() {
    var promise, ref;
    promise = PoolManager.__super__.unload.call(this);
    if ((ref = this.__eventPoll) != null) {
      ref.destroy();
    }
    return promise;
  };

  PoolManager.prototype.loadTreeAndReselectPool = function(selectedPoolId) {
    this.loadTree().done((function(_this) {
      return function() {
        var findNodePath, openAndSelectPath, path;
        findNodePath = function(parent, targetId, path) {
          var child, i, len, ref;
          if (parent.id === targetId) {
            path.unshift(parent);
            return true;
          }
          if (parent.children) {
            ref = parent.children;
            for (i = 0, len = ref.length; i < len; i++) {
              child = ref[i];
              if (findNodePath(child, targetId, path)) {
                path.unshift(parent);
                return true;
              }
            }
          }
        };
        openAndSelectPath = function(path) {
          var node;
          if (path.length === 1) {
            path[0].select();
            return;
          }
          node = path.shift();
          return node.open().done((function(_this) {
            return function() {
              return openAndSelectPath(path);
            };
          })(this));
        };
        path = [];
        findNodePath(_this.tree.nodes[0], selectedPoolId, path);
        return openAndSelectPath(path);
      };
    })(this));
  };

  PoolManager.prototype.loadList = function(filter, opts) {
    var dfr;
    if (opts == null) {
      opts = {};
    }
    CUI.mergeMap(opts, {
      objectKey: "pool",
      newInstanceFunc: (function(_this) {
        return function(pool) {
          pool = new _this.poolClass({
            pool: pool,
            manager: _this
          });
          if (_this._isPoolSelectable) {
            pool.setSelectable(_this._isPoolSelectable(pool));
          }
          return pool;
        };
      })(this),
      parentField: "pool._id_parent",
      doOpen: !!filter,
      searchOpts: {
        generate_rights: false
      }
    });
    if (opts.parentId === void 0) {
      opts.buildTree = true;
      delete opts.parentField;
    }
    CUI.mergeMap(opts.searchOpts, {
      type: "pool",
      format: void 0,
      limit: 100000,
      sort: [
        {
          field: "_level"
        }, {
          field: "pool.name"
        }
      ]
    });
    dfr = new CUI.Deferred();
    PoolManager.__super__.loadList.call(this, filter, opts).done((function(_this) {
      return function(objects, data) {
        var i, len, object, sort_loca;
        sort_loca = function(poolA, poolB) {
          var displayTextA, displayTextB, frontend_lang;
          frontend_lang = ez5.session.frontend_language || null;
          displayTextA = poolA.getDisplayText().toLocaleLowerCase();
          displayTextB = poolB.getDisplayText().toLocaleLowerCase();
          return displayTextA.localeCompare(displayTextB, frontend_lang);
        };
        if (!ez5.version("6.10")) {
          for (i = 0, len = objects.length; i < len; i++) {
            object = objects[i];
            object.sort(sort_loca);
          }
        }
        if (!filter && !opts.parentId && objects.length) {
          objects[0].do_open = true;
        }
        _this.data = data;
        return dfr.resolve(objects, data);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  PoolManager.prototype.__getObjectsFromData = function(data, opts) {
    if (!ez5.version("6")) {
      return PoolManager.__super__.__getObjectsFromData.call(this, data);
    }
    return data.objects.filter(function(pool) {
      var ref;
      return ((ref = pool.pool) != null ? ref.reference : void 0) !== "system:none";
    });
  };

  PoolManager.prototype.poolClass = Pool;

  return PoolManager;

})(SystemListHierarchyManager);

ez5.session_ready(function() {
  return ez5.rootMenu.registerApp(PoolManager);
});
// Generated by CoffeeScript 1.12.7
var PoolManagerList,
  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;

PoolManagerList = (function(superClass) {
  extend(PoolManagerList, superClass);

  function PoolManagerList() {
    return PoolManagerList.__super__.constructor.apply(this, arguments);
  }

  PoolManagerList.prototype.__root_pool = null;

  PoolManagerList.prototype.loadList = function() {
    return PoolManagerList.__super__.loadList.call(this, null, {
      parentField: null,
      buildTree: true
    }).done((function(_this) {
      return function(objects, data) {
        var _p, i, j, len, len1, p, ref;
        _this.__pools = [];
        for (i = 0, len = objects.length; i < len; i++) {
          p = objects[i];
          ref = p.find();
          for (j = 0, len1 = ref.length; j < len1; j++) {
            _p = ref[j];
            _this.__pools.push(_p);
            if (_p.isRootPool()) {
              _this.__root_pool = _p;
            }
          }
        }
      };
    })(this));
  };

  PoolManagerList.prototype.getList = function() {
    return this.__pools || [];
  };

  PoolManagerList.prototype.getRootPool = function() {
    return this.__root_pool;
  };

  PoolManagerList.prototype.findPoolByShortname = function(shortname) {
    var i, len, pool, ref;
    ref = this.__pools;
    for (i = 0, len = ref.length; i < len; i++) {
      pool = ref[i];
      if (pool.getShortname() === shortname) {
        return pool;
      }
    }
    return null;
  };

  PoolManagerList.prototype.findPoolById = function(pool_id) {
    var i, len, pool, ref;
    ref = this.__pools || [];
    for (i = 0, len = ref.length; i < len; i++) {
      pool = ref[i];
      if (pool.getId() === pool_id) {
        return pool;
      }
    }
    return null;
  };

  PoolManagerList.prototype.findPoolByDisplayname = function(display_name) {
    var i, len, pool, ref;
    ref = this.__pools;
    for (i = 0, len = ref.length; i < len; i++) {
      pool = ref[i];
      if (pool.getDisplayText() === display_name) {
        return pool;
      }
    }
    return null;
  };

  return PoolManagerList;

})(PoolManager);
// Generated by CoffeeScript 1.12.7
var PoolManagerPoolField,
  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;

PoolManagerPoolField = (function(superClass) {
  extend(PoolManagerPoolField, superClass);

  function PoolManagerPoolField() {
    this.loadList = bind(this.loadList, this);
    return PoolManagerPoolField.__super__.constructor.apply(this, arguments);
  }

  PoolManagerPoolField.prototype.initOpts = function() {
    PoolManagerPoolField.__super__.initOpts.call(this);
    return this.addOpts({
      "class": {
        check: String
      },
      onSelect: {
        check: Function
      }
    });
  };

  PoolManagerPoolField.prototype.readOpts = function() {
    PoolManagerPoolField.__super__.readOpts.call(this);
    return this.tree = new ListViewEditTree({
      fields: this.getListFields(),
      no_header: true,
      selectableRows: true,
      rowMove: false,
      onSelect: this._onSelect,
      "class": this._class,
      maximize: false,
      focusable: true,
      ignoreKeyEvents: true
    });
  };

  PoolManagerPoolField.prototype.empty = function() {};

  PoolManagerPoolField.prototype.getTree = function() {
    return this.tree;
  };

  PoolManagerPoolField.prototype.loadList = function(filter, opts) {
    if (opts == null) {
      opts = {};
    }
    CUI.Events.trigger({
      node: this.tree.DOM,
      type: "content-resize"
    });
    return PoolManagerPoolField.__super__.loadList.call(this, filter, opts);
  };

  PoolManagerPoolField.prototype.poolClass = PoolForPoolManagerPoolField;

  return PoolManagerPoolField;

})(PoolManager);
// Generated by CoffeeScript 1.12.7
var TagManager,
  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;

TagManager = (function(superClass) {
  extend(TagManager, superClass);

  function TagManager() {
    return TagManager.__super__.constructor.apply(this, arguments);
  }

  TagManager.is_allowed = function() {
    return ez5.session.hasSystemRight("root", "tagmanager");
  };

  TagManager.label = function() {
    return "admin.menu.tagmanager";
  };

  TagManager.group = function() {
    return "rightsmanagement";
  };

  TagManager.submenu = function() {
    return "rightsmanagement";
  };

  TagManager.path = function() {
    return ["tagmanager"];
  };

  TagManager.prototype.load = function() {
    var wb;
    TagManager.__super__.load.call(this);
    this.tagForm = new TagForm({
      context: this
    });
    this.transitionForm = new TransitionForm({
      tagForm: this.tagForm
    });
    this.saveButton = new CUI.Button({
      text: $$("base.save"),
      ui: "tag.manager.save.button",
      primary: true,
      disabled: true,
      onClick: (function(_this) {
        return function(ev) {
          return _this.save(ev).done(function() {
            return _this.resetDataChangedListener();
          });
        };
      })(this)
    });
    wb = new CUI.WaitBlock({
      element: ez5.rootLayout.center()
    }).show();
    return CUI.when(this.tagForm.load(), this.transitionForm.load()).done((function(_this) {
      return function() {
        var layout;
        _this.tabs = new CUI.Tabs({
          "class": "tag-manager-tabs",
          onActivate: function(tabs, tab) {
            return _this.setStatus();
          },
          tabs: [
            {
              name: "tags",
              text: $$("admin.tags.tab.tags"),
              content: function() {
                return _this.tagForm.getTree();
              }
            }, {
              name: "transitions",
              text: $$("admin.tags.tab.transitions"),
              content: function() {
                return _this.transitionForm.renderEditor();
              }
            }
          ],
          footer_right: new CUI.Buttonbar({
            buttons: [_this.saveButton]
          })
        });
        _this.registerDataChangedListener(_this.tabs.DOM);
        layout = new CUI.HorizontalLayout({
          center: {
            content: new CUI.SimplePane({
              "class": "cui-pane--window",
              title: $$("admin.tags.pane.title"),
              content: _this.tabs
            })
          }
        });
        ez5.rootLayout.replace(layout, "center");
        return wb.destroy();
      };
    })(this));
  };

  TagManager.prototype.unload = function() {
    var ref, ref1;
    ez5.rootLayout.empty("center");
    if ((ref = this.tagForm) != null) {
      ref.destroy();
    }
    if ((ref1 = this.transitionForm) != null) {
      ref1.destroy();
    }
    delete this.tabs;
    delete this.tagForm;
    delete this.transitionForm;
    return TagManager.__super__.unload.call(this);
  };

  TagManager.prototype.hasChanges = function() {
    return SystemListManagerItem.prototype.hasChanges.apply(this, arguments);
  };

  TagManager.prototype.setStatus = function() {
    return SystemListManagerItem.prototype.setStatus.apply(this, arguments);
  };

  TagManager.prototype.getInitialData = function() {
    return this.getSaveData();
  };

  TagManager.prototype.registerDataChangedListener = function(div) {
    return SystemListManagerItem.prototype.registerDataChangedListener.apply(this, arguments);
  };

  TagManager.prototype.resetDataChangedListener = function(div) {
    return SystemListManagerItem.prototype.resetDataChangedListener.apply(this, arguments);
  };

  TagManager.prototype.allow_unload = function() {
    var dfr;
    dfr = new CUI.Deferred();
    if (this.saveButton.isEnabled()) {
      new CUI.ConfirmationChoice({
        text: $$("tag.manager.unsaved_changes.text"),
        choices: [
          {
            _value: "discard",
            text: $$("tag.manager.unsaved_changes.button.discard")
          }, {
            _value: "cancel",
            text: $$("base.cancel")
          }, {
            _value: "save",
            primary: true,
            text: $$("tag.manager.unsaved_changes.button.save")
          }
        ]
      }).open().done((function(_this) {
        return function(choice, btn, ev) {
          switch (choice._value) {
            case "discard":
              return dfr.resolve();
            case "cancel":
              return dfr.reject();
            case "save":
              return _this.save().done(dfr.resolve).fail(dfr.reject);
          }
        };
      })(this));
    } else {
      dfr.resolve();
    }
    return dfr.promise();
  };

  TagManager.prototype.getSaveData = function() {
    return [this.tagForm.getSaveData(), this.transitionForm.getSaveData()];
  };

  TagManager.prototype.save = function(ev) {
    var acl_by_idx, dfr, i, idx_by_pseudo_id, j, len, len1, ref, save_data, tag, taggroup;
    this.saveButton.disable();
    ez5.splash.show('system.list.manager.item.saving');
    dfr = new CUI.Deferred();
    dfr.always((function(_this) {
      return function() {
        return _this.saveButton.enable();
      };
    })(this));
    dfr.fail((function(_this) {
      return function() {
        return ez5.splash.hide();
      };
    })(this));
    dfr.done((function(_this) {
      return function() {
        return ez5.splash.done('system.list.manager.item.saved');
      };
    })(this));
    save_data = this.tagForm.getSaveData();
    if (ev != null ? ev.hasModifierKey() : void 0) {
      console.debug("tags:", CUI.util.dump(save_data));
      console.debug("transitions:", CUI.util.dump(this.transitionForm.getSaveData()));
      return dfr.reject().promise();
    }
    acl_by_idx = [];
    idx_by_pseudo_id = {};
    for (i = 0, len = save_data.length; i < len; i++) {
      taggroup = save_data[i];
      ref = taggroup._tags;
      for (j = 0, len1 = ref.length; j < len1; j++) {
        tag = ref[j];
        acl_by_idx.push(tag._acl);
        idx_by_pseudo_id[tag._pseudo_id] = acl_by_idx.length - 1;
        delete tag._acl;
        delete tag._pseudo_id;
      }
    }
    ez5.api.tags({
      type: "POST",
      json_data: save_data
    }).done((function(_this) {
      return function(data) {
        var _acl, id_by_idx, idx, item, k, key, l, len2, len3, len4, len5, len6, len7, m, n, o, p, ref1, ref2, ref3, tag_idx, v, value;
        id_by_idx = [];
        for (k = 0, len2 = data.length; k < len2; k++) {
          taggroup = data[k];
          ref1 = taggroup._tags;
          for (l = 0, len3 = ref1.length; l < len3; l++) {
            tag = ref1[l];
            id_by_idx.push(tag.tag._id);
          }
        }
        tag_idx = 0;
        for (m = 0, len4 = data.length; m < len4; m++) {
          taggroup = data[m];
          ref2 = taggroup._tags;
          for (n = 0, len5 = ref2.length; n < len5; n++) {
            tag = ref2[n];
            _acl = acl_by_idx[tag_idx];
            for (o = 0, len6 = _acl.length; o < len6; o++) {
              item = _acl[o];
              if (item.tagfilter) {
                ref3 = item.tagfilter;
                for (key in ref3) {
                  value = ref3[key];
                  for (idx = p = 0, len7 = value.length; p < len7; idx = ++p) {
                    v = value[idx];
                    if (v < 0) {
                      value[idx] = id_by_idx[idx_by_pseudo_id[v]];
                    }
                  }
                }
              }
            }
            tag._acl = _acl;
            tag_idx++;
          }
        }
        return ez5.api.tags({
          type: "POST",
          json_data: data
        }).done(function() {
          return _this.tagForm.load().done(function() {
            var transition_data;
            transition_data = _this.transitionForm.getSaveData();
            return ez5.api.transitions({
              type: "POST",
              json_data: transition_data
            }).done(function(data) {
              return ez5.tagForm.load().done(function() {
                _this.tagForm.load();
                _this.transitionForm.load();
                return dfr.resolve();
              }).fail(dfr.reject);
            }).fail(dfr.reject);
          });
        }).fail(dfr.reject);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  return TagManager;

})(RootMenuApp);

ez5.session_ready(function() {
  return ez5.rootMenu.registerApp(TagManager);
});
// Generated by CoffeeScript 1.12.7
var SearchPopover,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

SearchPopover = (function(superClass) {
  extend(SearchPopover, superClass);

  function SearchPopover() {
    return SearchPopover.__super__.constructor.apply(this, arguments);
  }

  SearchPopover.prototype.initOpts = function() {
    SearchPopover.__super__.initOpts.call(this);
    this.addOpts({
      popover_element: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isElement(v) || CUI.util.isElement(v != null ? v.DOM : void 0);
        }
      },
      link_mask: {
        mandatory: false,
        check: Mask
      },
      onDone: {
        check: Function
      },
      onShow: {
        check: Function
      },
      onHide: {
        check: Function
      },
      collection: {
        mandatory: true,
        check: Collection
      },
      searchManagers: {
        check: Array,
        "default": []
      },
      isSelectable: {
        check: Function
      },
      searchInputOpts: {
        check: "PlainObject",
        mandatory: false,
        "default": {}
      },
      allowTopLevelPlaceholder: {
        check: Boolean,
        "default": false
      },
      allowSubsearch: {
        check: Boolean,
        "default": false
      },
      subsearch_validation: {
        check: Function,
        mandatory: false
      },
      allow_empty_result: {
        check: Boolean,
        "default": false
      },
      allowTrashRecords: {
        check: Boolean,
        "default": false
      },
      initialIncludeDeleted: {
        check: Boolean,
        "default": false
      },
      allObjecttypes: {
        check: Boolean,
        "default": false
      }
    });
    return this.removeOpt("container");
  };

  SearchPopover.prototype.readOpts = function() {
    SearchPopover.__super__.readOpts.call(this);
    this.__popover_element = this._popover_element;
    if (this._link_mask) {
      this.link_objecttype = new Objecttype(this._link_mask).addAllMasks();
    }
    if (this._allObjecttypes) {
      this.__allObjecttypesOTM = new ObjecttypeManager();
      return this.__allObjecttypesOTM.addObjecttypes();
    }
  };

  SearchPopover.prototype.runFirstSearch = function() {
    return this.execute();
  };

  SearchPopover.prototype.refresh = function() {
    this.__init = false;
    this.popover.destroy();
    return SearchPopover.__super__.refresh.call(this).done((function(_this) {
      return function() {
        return _this.popover.show();
      };
    })(this));
  };

  SearchPopover.prototype.getHeaderText = function() {
    if (this._link_mask) {
      return this._link_mask.table.nameLocalized();
    }
    return $$("search.popover.header");
  };

  SearchPopover.prototype.init = function() {
    var cls, footerLeftContent, hierarchyManagerClass, i, initialActive, len, managers, ref, ref1, ref2, ref3, ref4, reload_search, searchInputOpts, searchTypeOpts, selectable_opts, sm, tree_opts;
    if (this.__init) {
      return CUI.resolvedPromise();
    }
    this.__init = true;
    this.__header = new CUI.PaneHeader({
      left: {
        content: new CUI.Label({
          text: this.getHeaderText()
        })
      },
      right: {
        content: CUI.Pane.getToggleFillScreenButton({
          tooltip: {
            text: $$("base.fill_screen.tooltip")
          }
        })
      }
    });
    this.__buttonToolbar = new CUI.PaneToolbar();
    this.applyButton = new LocaButton({
      loca_key: "search.popover.button.apply",
      ui: "search.popover.apply.button",
      primary: true,
      onClick: (function(_this) {
        return function() {
          _this.closePopover();
          return typeof _this._onDone === "function" ? _this._onDone() : void 0;
        };
      })(this)
    });
    this.applySubSearchButton = null;
    if (this._allowSubsearch) {
      this.applySubSearchButton = new LocaButton({
        loca_key: "search.popover.button.apply_subsearch",
        ui: "search.popover.apply.button",
        hidden: true,
        primary: true,
        onClick: (function(_this) {
          return function() {
            var action;
            action = function() {
              var sd;
              sd = _this.getStoreData();
              _this.__subsearch_last_request_data.store_data = sd;
              _this._collection.addSubsearchData(_this.__subsearch_last_request_data);
              _this.closePopover();
              return typeof _this._onDone === "function" ? _this._onDone() : void 0;
            };
            if (_this._subsearch_validation != null) {
              return _this._subsearch_validation(_this.__subsearch_last_request_data).done(function() {
                return action();
              }).fail(function(reason) {
                if (!reason) {
                  return;
                }
                if (reason === "close") {
                  return _this.closePopover();
                }
              });
            } else {
              return action();
            }
          };
        })(this)
      });
    }
    this.applyButtonSetStatus();
    if (this._link_mask) {
      this.plusButton = new LocaButton({
        loca_key: "search.popover.button.plus",
        ui: "search.popover.plus.button",
        icon: "plus",
        disabled: true,
        onClick: (function(_this) {
          return function(ev) {
            if (ev.hasModifierKey()) {
              return _this.openEditor();
            } else {
              return _this.openEditor({
                popover_element: _this.__pane
              });
            }
          };
        })(this)
      });
      this.canCreateSearchObjecttypes().done((function(_this) {
        return function() {
          return _this.plusButton.enable();
        };
      })(this));
    }
    footerLeftContent = [];
    if (this._allowTrashRecords && TrashSearchManager.canSeeDeleted()) {
      initialActive = this._initialIncludeDeleted;
      this.__trashRecordsData = {
        show_trash: initialActive
      };
      this.__trashSearchManager = new TrashSearchManager({
        active: initialActive,
        only_deleted: true
      });
      this.__trashRecordsCheckbox = new CUI.Checkbox({
        data: this.__trashRecordsData,
        name: "show_trash",
        text: $$("search.popover.show_trash_records"),
        onDataChanged: (function(_this) {
          return function() {
            _this.__trashSearchManager.setActive(_this.__trashRecordsData.show_trash, false);
            if (_this.__searchTypeSelector) {
              return _this.__searchTypeSelector.updateContent(true).done(function() {
                return _this.execute();
              });
            } else {
              return _this.execute();
            }
          };
        })(this)
      });
      footerLeftContent.push(this.__trashRecordsCheckbox.start());
    }
    this.__footer = new CUI.PaneFooter({
      left: {
        content: footerLeftContent
      },
      right: {
        content: [this.applySubSearchButton, this.applyButton]
      }
    });
    if (!this._link_mask || ((ref = this.link_objecttype) != null ? ref.poolLink() : void 0)) {
      searchTypeOpts = {
        pref_name: "search_type_selector_" + (((ref1 = this.link_objecttype) != null ? ref1.name() : void 0) || "popover"),
        ignoreSelection: (function(_this) {
          return function() {
            var ref2;
            if (_this.__searchInput.ignoreSearchManager(_this.__searchTypeSelector)) {
              return true;
            }
            if ((ref2 = _this.hierarchyManager) != null ? ref2.isActive() : void 0) {
              return true;
            }
            return false;
          };
        })(this)
      };
      if (this.link_objecttype) {
        searchTypeOpts["objecttypes"] = [this.link_objecttype];
      } else if (this._allObjecttypes) {
        searchTypeOpts["objecttypes"] = this.__allObjecttypesOTM.getObjecttypes();
      }
      if (this._allowTrashRecords) {
        searchTypeOpts["show_all_objecttypes"] = true;
      }
      this.__searchTypeSelector = new SearchTypeSelector(searchTypeOpts);
      this.addSearchManager(this.__searchTypeSelector);
    } else {
      this.__searchTypeSelector = null;
    }
    if (this.__trashSearchManager) {
      this.addSearchManager(this.__trashSearchManager);
    }
    searchInputOpts = {
      expert: this,
      searchTypeSelector: this.__searchTypeSelector,
      scope_on_return: "fulltext"
    };
    CUI.util.mergeMap(searchInputOpts, this._searchInputOpts);
    this.__searchInput = new SearchInput(searchInputOpts);
    this.__pane = new CUI.Pane({
      "class": "ez5-search-popover-pane",
      ui: "search.popover",
      absolute: false,
      top: {
        content: [this.__header, this.__searchInput.getInputLayout(), this.__buttonToolbar]
      },
      bottom: {
        content: [this.__footer]
      }
    });
    this.__searchInput.addPlaceholder();
    this.rc = this.__pane.center();
    this.registerResultContainer(this.rc);
    CUI.Events.listen({
      type: "toolbox",
      node: this.rc,
      call: (function(_this) {
        return function(ev, info) {
          return info.tools.push.apply(info.tools, _this.getCurrentTools());
        };
      })(this)
    });
    selectable_opts = {
      collection: this._collection,
      draggable: false,
      lasso: !this._collection.isSingleMode(),
      select_with_modifier: true,
      fullscreen: false,
      isSelectable: this._isSelectable,
      onInit: (function(_this) {
        return function() {
          var domObject, domObjects, i, len, object, ref2, resultTableNode;
          if (!_this._isSelectable) {
            return;
          }
          domObjects = CUI.dom.matchSelector(_this.rc, "[global-object-id]");
          _this.getSearchInput().updateBackgroundHelp();
          for (i = 0, len = domObjects.length; i < len; i++) {
            domObject = domObjects[i];
            object = CUI.dom.data(domObject, "object");
            if (!object) {
              continue;
            }
            resultTableNode = CUI.dom.data((ref2 = domObject.children) != null ? ref2[0].parentElement : void 0, "listViewRow");
            if (resultTableNode) {
              resultTableNode.setSelectable(_this._isSelectable(object));
            }
          }
        };
      })(this)
    };
    if (!this.link_objecttype || (this.link_objecttype.inMainSearch() && ((ref2 = this.link_objecttype.getEASFields()) != null ? ref2.length : void 0) > 0)) {
      managers = [
        new ResultStandard({
          container: this.rc,
          pane_absolute: false,
          navigation_buttons_left: [this.plusButton],
          selectable_opts: selectable_opts,
          allowTopLevelPlaceholder: this._allowTopLevelPlaceholder
        }), new ResultText({
          container: this.rc,
          pane_absolute: false,
          navigation_buttons_left: [this.plusButton],
          selectable_opts: selectable_opts,
          allowTopLevelPlaceholder: this._allowTopLevelPlaceholder
        }), new ez5.ResultTableV2({
          container: this.rc,
          navigation_buttons_left: [this.plusButton],
          selectable_opts: selectable_opts,
          allowTopLevelPlaceholder: this._allowTopLevelPlaceholder
        })
      ];
      this.addSearchManager(new ResultManager({
        pref: "search_popover_view_data",
        managers: managers
      }));
    } else {
      this.__onlyResultList = true;
      tree_opts = {
        onOpen: (function(_this) {
          return function(ev, info) {
            var child, i, len, node, object, ref3;
            if (!_this._isSelectable) {
              return;
            }
            node = info.node;
            if (!(node != null ? node.children : void 0)) {
              return;
            }
            ref3 = node.children;
            for (i = 0, len = ref3.length; i < len; i++) {
              child = ref3[i];
              object = child.getTopLevelData();
              child.setSelectable(_this._isSelectable(object));
            }
          };
        })(this)
      };
      this.addSearchManager(new ResultManager({
        pref: "search_popover_list_view_data",
        managers: [
          new ResultList({
            ui: "search.popover.result.list",
            container: this.rc,
            pane_absolute: false,
            navigation_buttons_left: [this.plusButton],
            selectable_opts: selectable_opts,
            tree_opts: tree_opts,
            allowTopLevelPlaceholder: this._allowTopLevelPlaceholder
          })
        ]
      }));
    }
    reload_search = false;
    CUI.Events.listen({
      type: "event-poller",
      node: this.__pane,
      call: (function(_this) {
        return function(ev, info) {
          var event;
          if (info.batch_done && reload_search) {
            reload_search = false;
            _this.execute();
          }
          event = info.event;
          if (!event) {
            return;
          }
          if (event.type === "OBJECT_INDEX" && event.object_version === 1 && _this._collection.objectIdx(new CollectionObject({
            _global_object_id: event.global_object_id
          })) > -1) {
            reload_search = true;
          }
        };
      })(this)
    });
    this.addSearchManager(this.__searchInput);
    this.__searchInput.getInputLayout().append(this.getSearchButton(), "right", false);
    if (this._searchManagers) {
      ref3 = this._searchManagers;
      for (i = 0, len = ref3.length; i < len; i++) {
        sm = ref3[i];
        this.addSearchManager(sm);
      }
    }
    if (this._link_mask && (this._link_mask.isHierarchy() || this._link_mask.isPolyhierarchy())) {
      hierarchyManagerClass = this.__onlyResultList ? SearchListHierarchyManager : SearchHierarchyManager;
      this.hierarchyManager = new hierarchyManagerClass({
        container: this.__pane.top(),
        searchInput: this.__searchInput
      });
      this.addSearchManager(this.hierarchyManager);
    }
    this.addSearchManager(new SortManager({
      pref: "search_popover_sort_data"
    }));
    this._collection.off({
      instance: this
    });
    this._collection.on({
      type: ["insert", "remove", "select"],
      instance: this,
      call: (function(_this) {
        return function(ev, info) {
          if (!info.skip_update) {
            _this.updateFlyoutButtonbar();
          }
          _this.applyButtonSetStatus();
        };
      })(this)
    });
    cls = "ez5-search-popover ";
    this.addSearchManager(new CollectionSearchManager({
      collection: this._collection
    }));
    this.popover = new CUI.Popover({
      "class": cls + (((ref4 = this.link_objecttype) != null ? ref4.getCapabilityClasses("ez5-search-") : void 0) || ""),
      element: this.__popover_element,
      onShow: this._onShow,
      onHide: (function(_this) {
        return function() {
          _this.__cleanKeyboardListeners();
          return typeof _this._onHide === "function" ? _this._onHide() : void 0;
        };
      })(this),
      pane: this.__pane
    });
    return Search.prototype.init.call(this);
  };

  SearchPopover.prototype.execute = function(request) {
    var dfr;
    if (request == null) {
      request = new Request();
    }
    dfr = SearchPopover.__super__.execute.call(this, request);
    if (this._allowSubsearch) {
      dfr.done((function(_this) {
        return function() {
          if (_this.hasUserInput()) {
            _this.checkSubSearch();
          }
        };
      })(this));
    }
    return dfr;
  };

  SearchPopover.prototype.executeSearch = function(req_data) {
    var promise;
    promise = SearchPopover.__super__.executeSearch.call(this, req_data);
    if (this._allowSubsearch) {
      this.__subsearch_last_request_data = req_data;
    }
    return promise;
  };

  SearchPopover.prototype.checkSubSearch = function() {
    if ((!CUI.util.isEmpty(this.__subsearch_last_request_data) && this.lastData.count > 0) || this._allow_empty_result) {
      return this.applySubSearchButton.show(true);
    } else {
      return this.applySubSearchButton.hide(true);
    }
  };

  SearchPopover.prototype.applyButtonSetStatus = function() {
    var c;
    if ((c = this._collection.getCount()) > 0) {
      if (this._allowSubsearch) {
        this.applySubSearchButton.hide(true);
        this.applyButton.show(true);
      }
      this.applyButton.setText($$("search.popover.button.apply.count", {
        count: c
      }));
      this.applyButton.enable();
    } else {
      this.applyButton.setText($$("search.popover.button.apply.count.none"));
      this.applyButton.disable();
      if (this._allowSubsearch) {
        if ((!CUI.util.isEmpty(this.__subsearch_last_request_data) && this.lastData.count > 0) || this._allow_empty_result) {
          this.applySubSearchButton.show(true);
          this.applyButton.hide(true);
        }
      }
    }
    return this;
  };

  SearchPopover.prototype.getSearchHierarchyManager = function() {
    return this.hierarchyManager;
  };

  SearchPopover.prototype.openEditor = function(_opts) {
    var done_save, ed, global_object_id, link_mask, mode, object_list, onDone, opts, params, popover_element, result_object;
    if (_opts == null) {
      _opts = {};
    }
    ed = null;
    opts = CUI.Element.readOpts(_opts, "SearchPopover.openEditor", {
      result_object: {
        check: ResultObject
      },
      popover_element: {},
      onDone: {
        check: Function
      },
      collection: {
        mandatory: true,
        "default": this._collection,
        check: Collection
      },
      link_mask: {
        check: Mask
      }
    });
    if (opts.link_mask) {
      link_mask = opts.link_mask;
    } else {
      link_mask = this._link_mask;
    }
    result_object = opts.result_object;
    popover_element = opts.popover_element;
    onDone = opts.onDone;
    global_object_id = void 0;
    object_list = void 0;
    if (result_object) {
      if (result_object.id()) {
        mode = "single";
        global_object_id = result_object.id();
      } else {
        object_list = new ObjectList();
        object_list.push(result_object);
        mode = "new";
      }
    } else {
      mode = "new";
    }
    done_save = (function(_this) {
      return function(ed, received_data) {
        var i, idx, obj, ol, ref, ref1;
        if (_this.getSearchInput()) {
          _this.addCollectionAfterSave(received_data);
        }
        ol = ed.getObjectList();
        for (idx = i = 0, ref = ol.getCount(); 0 <= ref ? i < ref : i > ref; idx = 0 <= ref ? ++i : --i) {
          obj = ol.getObject(idx);
          if (obj instanceof TemplateObject) {
            continue;
          }
          if (obj.version() > 1) {
            continue;
          }
          if ((ed != null ? (ref1 = ed.editor_data) != null ? ref1.mode : void 0 : void 0) === "new") {
            obj.data._new_object = true;
          }
          opts.collection.insertObjects([obj.getCollectionObject()]);
        }
        return onDone != null ? onDone.call(_this) : void 0;
      };
    })(this);
    params = {
      table_id: link_mask.table.id(),
      popover_element: popover_element,
      global_object_id: global_object_id,
      object_list: object_list,
      mode: mode,
      format: "long",
      onSave: done_save,
      onSaveReadOnly: done_save,
      onCopy: (function(_this) {
        return function() {
          return result_object.getCopyFromSaveData().done(function(ro) {
            ed.getObjectList().setObject(ro, 0);
            ed.setMode("new");
            return ed.open();
          });
        };
      })(this)
    };
    ed = new EditorPopover(params);
    ed.open();
    return this;
  };

  SearchPopover.prototype.getButtonToolbar = function() {
    return this.__buttonToolbar;
  };

  SearchPopover.prototype.getSearchObjecttypes = function(user_selected, filter_by_pool) {
    var activeNames, activeOts, i, len, ot, ots, ref;
    if (user_selected == null) {
      user_selected = true;
    }
    if (filter_by_pool == null) {
      filter_by_pool = false;
    }
    if (this._link_mask) {
      return [this.link_objecttype];
    }
    if (this._allObjecttypes && filter_by_pool) {
      activeOts = SearchPopover.__super__.getSearchObjecttypes.call(this, user_selected, false);
      activeNames = (function() {
        var i, len, results;
        results = [];
        for (i = 0, len = activeOts.length; i < len; i++) {
          ot = activeOts[i];
          results.push(ot.name());
        }
        return results;
      })();
      ots = [];
      for (i = 0, len = activeOts.length; i < len; i++) {
        ot = activeOts[i];
        if (ot.poolLink() && (ref = ot.name(), indexOf.call(activeNames, ref) >= 0)) {
          ots.push(ot);
        }
      }
      return ots;
    }
    return SearchPopover.__super__.getSearchObjecttypes.call(this, user_selected, filter_by_pool);
  };

  SearchPopover.prototype.getObjecttype = function() {
    return this.link_objecttype;
  };

  SearchPopover.prototype.getDefaultSortFilter = function() {
    return SearchList.prototype.getDefaultSortFilter.call(this);
  };

  SearchPopover.prototype.getDefaultSortKey = function() {
    return SearchList.prototype.getDefaultSortKey.call(this);
  };

  SearchPopover.prototype.destroy = function() {
    SearchPopover.__super__.destroy.call(this);
    this.popover.destroy();
    this.popover = null;
    return this.__init = false;
  };

  SearchPopover.prototype.openPopover = function() {
    this.init().done((function(_this) {
      return function() {
        var ret;
        _this.registerKeyboardShortcuts(_this.popover.DOM);
        _this.popover.show();
        ret = _this.execute();
        return ret.done(function() {
          return _this.__searchInput.focusQueryContainer();
        });
      };
    })(this));
  };

  SearchPopover.prototype.closePopover = function() {
    var ref;
    if (typeof this._onHide === "function") {
      this._onHide();
    }
    return (ref = this.popover) != null ? ref.hide() : void 0;
  };

  SearchPopover.prototype.hasUserInput = function() {
    return !this.__searchInput.isEmpty();
  };

  SearchPopover.prototype.getShareUrl = function() {};

  SearchPopover.getBaseConfigButton = function(pname, getMask, inCollection, storeObj, getSearchFunc, allowTrashRecords, allObjecttypes) {
    var proxyField;
    if (inCollection == null) {
      inCollection = null;
    }
    if (storeObj == null) {
      storeObj = {};
    }
    if (getSearchFunc == null) {
      getSearchFunc = null;
    }
    if (allowTrashRecords == null) {
      allowTrashRecords = false;
    }
    if (allObjecttypes == null) {
      allObjecttypes = true;
    }
    proxyField = {
      type: CUI.DataFieldProxy,
      element: function(df) {
        var button, mask, output_text, qe, restoreData, search, setButtonStatus;
        if (inCollection) {
          if (inCollection instanceof CollectionWorkfolder) {
            qe = new QueryElementCollection({
              collection: inCollection
            });
            search = {
              best_mask_filter: true,
              search: [qe.getSearchFilter()]
            };
            output_text = "Collection " + qe.getBadge().value;
          } else if (inCollection instanceof CollectionStoredSearch) {
            inCollection.__initShowInSearch();
            qe = new QueryElementCollection({
              collection: inCollection
            });
            search = {
              best_mask_filter: true,
              search: [qe.getSearchFilter()]
            };
            output_text = "Collection " + qe.getBadge().value;
          } else {
            search = {
              best_mask_filter: true,
              search: [
                {
                  type: "in",
                  "in": inCollection.getObjects().map(function(co) {
                    return co.getGlobalObjectId();
                  }),
                  fields: ["_global_object_id"]
                }
              ]
            };
            output_text = $$("search.popover.selection.config.button", {
              count: inCollection.getObjects().length
            });
          }
          df.getData()[pname] = search;
          return new CUI.Label({
            text: output_text
          });
        }
        mask = typeof getMask === "function" ? getMask() : void 0;
        button = new CUI.Button({
          icon: "fa-search",
          text_inactive: $$("search.popover.base.config.button"),
          text_active: $$("search.popover.base.config.edit.button"),
          disabled: !mask && (getMask != null),
          onClick: (function(_this) {
            return function(ev, button) {
              var collection, first_request, ref, savedIncludeDeleted, searchPopover;
              first_request = true;
              collection = new CollectionMemory({
                preventBlurOnSelect: true
              });
              savedIncludeDeleted = allowTrashRecords && ((ref = df.getData()[pname]) != null ? ref.include_deleted : void 0);
              searchPopover = new SearchPopover({
                link_mask: typeof getMask === "function" ? getMask() : void 0,
                popover_element: button,
                collection: collection,
                request_format: "long",
                allow_empty_result: true,
                allowTrashRecords: allowTrashRecords,
                initialIncludeDeleted: !!savedIncludeDeleted,
                allObjecttypes: allObjecttypes,
                onRequestDone: function() {
                  if (first_request) {
                    restoreData(searchPopover, storeObj || null);
                    return first_request = false;
                  }
                },
                searchInputOpts: {
                  scope: ["fulltext", "token", "tokens"]
                },
                allowSubsearch: true,
                subsearch_validation: function(data) {
                  var dataCopy, dfr, userFilters;
                  dfr = new CUI.Deferred();
                  dataCopy = CUI.util.copyObject(data || {}, true);
                  userFilters = (dataCopy.search || []).filter(function(s) {
                    return (s != null ? s.__filter : void 0) !== "SearchTypeSelector" && (s != null ? s.__filter : void 0) !== "TrashSearchManager";
                  });
                  if (CUI.util.isEmpty(data != null ? data.search : void 0) || userFilters.length === 0) {
                    new CUI.ConfirmationChoice({
                      text: $$("search.popover.base.config.ask_continue.text"),
                      choices: [
                        {
                          loca_key: 'search.popover.base.config.ask_continue.button.cancel',
                          cancel: true
                        }, {
                          loca_key: 'search.popover.base.config.ask_continue.button.modify',
                          choice: 'modify'
                        }, {
                          loca_key: 'search.popover.base.config.ask_continue.button.continue',
                          choice: 'continue',
                          primary: true
                        }
                      ]
                    }).open().done(function(choice) {
                      switch (choice.choice) {
                        case 'modify':
                          return dfr.reject();
                        case 'continue':
                          return dfr.resolve();
                      }
                    }).fail(function() {
                      return dfr.reject("close");
                    });
                  } else {
                    return dfr.resolve();
                  }
                  return dfr.promise();
                },
                onDone: function() {
                  var base, objecttypes, ref1, sd, subsearch;
                  if (collection.hasSubsearchData()) {
                    subsearch = collection.getSubsearchData();
                    search = subsearch.search;
                    sd = subsearch.store_data;
                    Object.assign(storeObj, subsearch.store_data);
                    objecttypes = subsearch.objecttypes;
                  } else {
                    sd = null;
                    search = [
                      {
                        type: "in",
                        "in": collection.getObjects().map(function(co) {
                          return co.getGlobalObjectId();
                        }),
                        fields: ["_global_object_id"]
                      }
                    ];
                    objecttypes = Array.from(new Set(collection.getObjects().map(function(co) {
                      return co.getObjecttype();
                    })));
                  }
                  if ((base = df.getData())["webfrontend"] == null) {
                    base["webfrontend"] = {};
                  }
                  df.getData()["webfrontend"][pname] = {
                    store_data: sd
                  };
                  df.getData()[pname] = {
                    best_mask_filter: true,
                    include_deleted: allowTrashRecords && ((ref1 = searchPopover.__trashSearchManager) != null ? ref1.isActive() : void 0),
                    search: search,
                    objecttypes: objecttypes
                  };
                  if (getSearchFunc != null) {
                    df.getData()[pname] = getSearchFunc(df.getData()[pname]);
                  }
                  return setButtonStatus();
                }
              });
              return searchPopover.openPopover();
            };
          })(this)
        });
        restoreData = (function(_this) {
          return function(search, storedData) {
            var k, promises, sm, v;
            if (!storedData) {
              return;
            }
            promises = [];
            for (k in storedData) {
              v = storedData[k];
              if (!CUI.util.isFunction(window[k])) {
                continue;
              }
              try {
                sm = new window[k]({
                  init_from_data: v
                });
                sm.setSearch(search);
                if (sm instanceof SearchInput) {
                  promises.push(search.getSearchInput().restoreFromStored(sm));
                  continue;
                }
              } catch (error) {}
            }
            return CUI.when(promises).done(function() {
              return search.execute();
            });
          };
        })(this);
        setButtonStatus = (function(_this) {
          return function() {
            var ref;
            if (!CUI.util.isEmpty((ref = df.getData()) != null ? ref[pname] : void 0)) {
              button.setActive(true);
            } else {
              button.setActive(false);
            }
            CUI.Events.trigger({
              node: df,
              type: "data-changed",
              info: {
                element: df
              }
            });
            return button;
          };
        })(this);
        return setButtonStatus();
      }
    };
    return proxyField;
  };

  return SearchPopover;

})(SearchMain);
// Generated by CoffeeScript 1.12.7
var LinkedObjectFiltersSearchManager,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

LinkedObjectFiltersSearchManager = (function(superClass) {
  extend(LinkedObjectFiltersSearchManager, superClass);

  function LinkedObjectFiltersSearchManager() {
    return LinkedObjectFiltersSearchManager.__super__.constructor.apply(this, arguments);
  }

  LinkedObjectFiltersSearchManager.prototype.initOpts = function() {
    LinkedObjectFiltersSearchManager.__super__.initOpts.call(this);
    this.addOpts({
      getSearchFilters: {
        check: Function,
        mandatory: true
      }
    });
    return this;
  };

  LinkedObjectFiltersSearchManager.prototype.addToRequest = function(request) {
    var searchFilters;
    searchFilters = this.cleanFilter(CUI.util.copyObject(this._getSearchFilters(), true), request);
    if (!searchFilters) {
      return;
    }
    if (!request.search) {
      request.search = [];
    }
    request.search = request.search.concat(searchFilters);
    if (searchFilters.length > 0) {
      request.ignore_hierarchy = true;
    }
    return request;
  };

  LinkedObjectFiltersSearchManager.prototype.cleanFilter = function(filters, request) {
    var cleanFilters, field, filter, i, len, ot_name, ref;
    if (!filters || !filters.length) {
      return;
    }
    if (filters[0].type === "complex") {
      cleanFilters = [];
      ref = filters[0].search;
      for (i = 0, len = ref.length; i < len; i++) {
        filter = ref[i];
        if (filter.fields) {
          field = filter.fields[0].split(".");
          if (field.length > 1) {
            ot_name = field[0];
            if (indexOf.call(request.objecttypes, ot_name) >= 0 || !ez5.schema.CURRENT._objecttype_by_name[ot_name]) {
              cleanFilters.push(filter);
            }
          }
        } else {
          cleanFilters.push(filter);
        }
      }
      filters[0].search = cleanFilters;
    }
    return filters;
  };

  return LinkedObjectFiltersSearchManager;

})(SearchManager);
// Generated by CoffeeScript 1.12.7
var SearchMini,
  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;

SearchMini = (function(superClass) {
  extend(SearchMini, superClass);

  function SearchMini() {
    return SearchMini.__super__.constructor.apply(this, arguments);
  }

  SearchMini.prototype.initOpts = function() {
    SearchMini.__super__.initOpts.call(this);
    this.addOpts({
      element: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isElement(v);
        }
      },
      popover_element: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isElement(v) || CUI.util.isElement(v != null ? v.DOM : void 0);
        }
      },
      link_mask: {
        mandatory: true,
        check: Mask
      },
      link_mask_inline: {
        mandatory: true,
        check: ["standard", "short", "text"]
      },
      collection: {
        mandatory: true,
        check: Collection
      },
      onUpdate: {
        check: Function
      },
      searchManagers: {
        "default": [],
        check: Array
      },
      placeholder_text: {
        check: String
      },
      input_opts: {
        check: "PlainObject",
        "default": {}
      },
      search_managers_for_popover: {
        "default": true,
        check: Boolean
      },
      isSelectable: {
        check: Function
      },
      searchPopoverOpts: {
        check: "PlainObject",
        mandatory: false,
        "default": {}
      },
      preventOntheflySuggestion: {
        "default": false,
        check: Boolean
      }
    });
    return this.mergeOpts({
      request_format: {
        "default": "standard"
      }
    });
  };

  SearchMini.prototype.readOpts = function() {
    var element, i, idButton, input_opts, isClickedBusy, len, ref, sm;
    SearchMini.__super__.readOpts.call(this);
    this.collection = this._collection;
    this.__linkMask = this._link_mask;
    this.mini_container = new CUI.HorizontalLayout({
      center: {},
      right: {}
    });
    CUI.dom.replace(this._element, this.mini_container);
    this.link_objecttype = new Objecttype(this.__linkMask);
    idButton = "search_mini_button";
    this.mini_btn = new LocaButton({
      icon: "ellipsis_v",
      loca_key: "search.mini.button.open_search",
      ui: "search.mini.open_search.button",
      id: idButton,
      onClick: (function(_this) {
        return function() {
          return _this.openSearch();
        };
      })(this)
    });
    this.mini_container.append(this.mini_btn, "right");
    input_opts = {
      "aria-labelledby": idButton
    };
    CUI.util.mergeMap(this._input_opts, input_opts);
    this.queryElementInput = new QueryElementInputSearch({
      manager: this,
      placeholder_text: this._placeholder_text,
      input_opts: this._input_opts
    });
    this.mini_container.append(this.queryElementInput.render(), "center");
    element = this.queryElementInput.getElement();
    CUI.dom.setAttribute(element, "ui", "search.mini.autocompletion.input");
    this.autocompletion = new AutocompletionPopup({
      element: this.queryElementInput.getElement(),
      onHide: (function(_this) {
        return function() {
          return _this.queryElementInput.triggerFocus();
        };
      })(this)
    });
    this.__ignore_events = false;
    this.collection.on({
      type: ["insert", "remove"],
      call: (function(_this) {
        return function(ev, info) {
          if (_this.__ignore_events) {
            return;
          }
          return _this.update();
        };
      })(this)
    });
    this.autocompletion.addContainer("all");
    this.autocompletion.addContainer("status");
    this.autocompletion.onHide = (function(_this) {
      return function() {
        return _this.collection.removeObjects(_this.collection.getObjects());
      };
    })(this);
    isClickedBusy = false;
    CUI.Events.listen({
      type: "click",
      selector: "[global-object-id]",
      node: this.autocompletion,
      call: (function(_this) {
        return function(event) {
          var collectionObject, objectClicked;
          event.stopPropagation();
          if (isClickedBusy) {
            return;
          }
          objectClicked = CUI.dom.data(event.getCurrentTarget(), "object");
          if (_this._isSelectable && !_this._isSelectable(objectClicked)) {
            return;
          }
          isClickedBusy = true;
          collectionObject = new CollectionObject(objectClicked);
          _this.collection.insertObjects([collectionObject]).done(function() {
            return _this.autocompletion.hide();
          }).always(function() {
            return isClickedBusy = false;
          });
        };
      })(this)
    });
    this.addSearchManager(new SearchMiniResultManager({
      autocompletion: this.autocompletion,
      link_mask_inline: this._link_mask_inline,
      preventOntheflySuggestion: this._preventOntheflySuggestion,
      onShowResult: (function(_this) {
        return function() {
          var domObject, domObjects, i, len, object, ref;
          if (!_this._isSelectable) {
            return;
          }
          domObjects = CUI.dom.matchSelector(_this.autocompletion, "[global-object-id]");
          for (i = 0, len = domObjects.length; i < len; i++) {
            domObject = domObjects[i];
            object = CUI.dom.data(domObject, "object");
            if (!object) {
              continue;
            }
            if (!_this._isSelectable(object)) {
              CUI.dom.addClass(domObject, "ez5-item-not-selectable");
              CUI.dom.addClass((ref = domObject.children) != null ? ref[0] : void 0, "ez5-item-not-selectable");
            }
          }
        };
      })(this)
    }));
    ref = this._searchManagers;
    for (i = 0, len = ref.length; i < len; i++) {
      sm = ref[i];
      this.addSearchManager(sm);
    }
    return this.init().done((function(_this) {
      return function() {
        return _this.update({
          init: true
        });
      };
    })(this));
  };

  SearchMini.prototype.setInputValue = function(value) {
    return this.queryElementInput.value(value);
  };

  SearchMini.prototype.insertOnTheFly = function(opts) {
    var availableMasks, co, ro;
    if (opts.dbInfoData) {
      availableMasks = opts.dbInfoData._available_masks;
      if ((availableMasks != null ? availableMasks.length : void 0) > 0 && !availableMasks.some((function(_this) {
        return function(mask) {
          return mask._id === _this.__linkMask.id();
        };
      })(this))) {
        this.__linkMask = Mask.getMaskByMaskName(availableMasks[0].name);
      }
    }
    ro = this.getResultObjectFromCurrentValue(opts.value);
    ro.getData()._mapped_metadata_created = true;
    co = ro.getCollectionObject();
    this.autocompletion.hide();
    this.queryElementInput.triggerBlur();
    return this.collection.insertObjects([co]);
  };

  SearchMini.prototype.update = function(opts) {
    if (opts == null) {
      opts = {};
    }
    CUI.util.mergeMap(opts, {
      init: false,
      callback: true
    });
    this.setInputValue("");
    opts.searchMini = this;
    if (opts.callback) {
      return typeof this._onUpdate === "function" ? this._onUpdate(opts) : void 0;
    }
  };

  SearchMini.prototype.hasSearchBasics = function() {
    return false;
  };

  SearchMini.prototype.destroy = function() {
    var ref;
    if ((ref = this.popover_search) != null) {
      ref.destroy();
    }
    this.popover_search = null;
    return SearchMini.__super__.destroy.call(this);
  };

  SearchMini.prototype.__initSearchPopover = function() {
    var searchPopoverOpts;
    if (this.popover_search) {
      return;
    }
    this.__col_copy = this.collection.copy();
    this.__col_copy._preventBlurOnSelect = true;
    searchPopoverOpts = {
      link_mask: this.__linkMask,
      searchManagers: this._search_managers_for_popover ? this._searchManagers : null,
      popover_element: this._popover_element,
      isSelectable: this._isSelectable,
      collection: this.__col_copy,
      request_format: this._request_format,
      onAddToRequest: this._onAddToRequest,
      onRequestDone: this._onRequestDone,
      onShow: (function(_this) {
        return function() {
          var base;
          _this.mini_btn.addClass("cui-active");
          _this.__ignore_events = true;
          return typeof (base = _this._searchPopoverOpts).onShow === "function" ? base.onShow() : void 0;
        };
      })(this),
      onHide: (function(_this) {
        return function() {
          var base;
          _this.mini_btn.removeClass("cui-active");
          _this.__ignore_events = false;
          _this.popover_search.destroy();
          _this.popover_search = null;
          return typeof (base = _this._searchPopoverOpts).onHide === "function" ? base.onHide() : void 0;
        };
      })(this),
      onDone: (function(_this) {
        return function() {
          return _this.onDonePopoverSearch();
        };
      })(this)
    };
    CUI.util.mergeMap(searchPopoverOpts, this._searchPopoverOpts);
    this.popover_search = new SearchPopover(searchPopoverOpts);
  };

  SearchMini.prototype.onDonePopoverSearch = function() {
    this.__ignore_events = true;
    return this.collection.removeObjects(null, {
      skip_update: true
    }).done((function(_this) {
      return function() {
        var base;
        _this.collection.addSubsearchData(typeof (base = _this.__col_copy).getSubsearchData === "function" ? base.getSubsearchData() : void 0);
        return _this.collection.insertObjects(_this.__col_copy.getObjects()).done(function() {
          return _this.__col_copy = _this.collection.copy();
        }).always(function() {
          _this.update();
          return _this.__ignore_events = false;
        });
      };
    })(this)).fail((function(_this) {
      return function() {
        return _this.__ignore_events = false;
      };
    })(this));
  };

  SearchMini.prototype.openSearch = function(element) {
    this.__initSearchPopover();
    return this.popover_search.openPopover(element);
  };

  SearchMini.prototype.getResultObjectFromCurrentValue = function(value) {
    var data, f, ot_name, ref, ro, textFields;
    ro = new ResultObject();
    ot_name = this.__linkMask.table.name();
    data = {
      _mask: this.__linkMask.name(),
      _format: 'long'
    };
    ro.initData(ot_name, data);
    if (!CUI.util.isEmpty(value)) {
      textFields = this.__linkMask.getStandardTextFields([1]);
      f = (ref = textFields[0]) != null ? ref.field : void 0;
      if (f instanceof LocaTextColumn) {
        data[ot_name][f.name()] = {};
        data[ot_name][f.name()][ez5.loca.getDatabaseLanguages()[0]] = value;
      } else if (f) {
        data[ot_name][f.name()] = value;
      }
    }
    return ro;
  };

  SearchMini.prototype.openEditor = function(value) {
    this.__initSearchPopover();
    this.autocompletion.hide();
    this.queryElementInput.triggerBlur();
    return this.popover_search.openEditor({
      popover_element: this.mini_container,
      result_object: this.getResultObjectFromCurrentValue(value),
      onDone: (function(_this) {
        return function() {
          return _this.onDonePopoverSearch();
        };
      })(this)
    });
  };

  SearchMini.prototype.inputEmptied = function() {
    return this.collection.removeObjects();
  };

  SearchMini.prototype.addToRequest = function(request) {
    var sf;
    SearchMini.__super__.addToRequest.call(this, request);
    sf = this.queryElementInput.getSearchFilter();
    if (sf) {
      request.search = [sf];
    }
  };

  SearchMini.prototype.getSearchObjecttypes = function() {
    return [this.link_objecttype];
  };

  SearchMini.prototype.getCollection = function() {
    return null;
  };

  SearchMini.prototype.getAutocompletion = function() {
    return this.autocompletion;
  };

  SearchMini.prototype.getSearchPopover = function() {
    this.__initSearchPopover();
    return this.popover_search;
  };

  return SearchMini;

})(Search);
// Generated by CoffeeScript 1.12.7
var SearchMiniResultManager,
  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;

SearchMiniResultManager = (function(superClass) {
  extend(SearchMiniResultManager, superClass);

  function SearchMiniResultManager() {
    return SearchMiniResultManager.__super__.constructor.apply(this, arguments);
  }

  SearchMiniResultManager.prototype.initOpts = function() {
    SearchMiniResultManager.__super__.initOpts.call(this);
    return this.addOpts({
      autocompletion: {
        mandatory: true,
        check: AutocompletionPopup
      },
      link_mask_inline: {
        mandatory: true,
        check: ["standard", "short", "text"]
      },
      onShowResult: {
        check: Function
      },
      preventOntheflySuggestion: {
        "default": false,
        check: Boolean
      }
    });
  };

  SearchMiniResultManager.prototype.readOpts = function() {
    SearchMiniResultManager.__super__.readOpts.call(this);
    this.autocompletion = this._autocompletion;
    return this.__hasPlusButton = null;
  };

  SearchMiniResultManager.prototype.getName = function() {
    return "searchmini";
  };

  SearchMiniResultManager.prototype.addToRequest = function(request) {
    request.limit = 100;
    this.autocompletion.getContainer("status").replace(new LocaLabel({
      loca_key: "autocompletion.loading"
    }));
    return this.autocompletion.show();
  };

  SearchMiniResultManager.prototype.showResult = function(request, data) {
    var append_onthefly, i, item, len, o, plusButton, ref, ro, value;
    this.autocompletion.emptyContainer("all");
    if (data.count === 0) {
      this.autocompletion.getContainer("status").replace([
        new LocaLabel({
          loca_key: "autocompletion.nothing_found"
        })
      ]);
    } else {
      if (data.limit < data.count) {
        this.autocompletion.getContainer("status").replace(new LocaLabel({
          loca_key: "autocompletion.found_objects_limited",
          loca_key_attrs: {
            limit: data.limit,
            count: data.count
          }
        }));
      } else {
        this.autocompletion.getContainer("status").replace(new LocaLabel({
          loca_key: "autocompletion.found_objects",
          loca_key_attrs: {
            count: data.count
          }
        }));
      }
      ref = data.objects;
      for (i = 0, len = ref.length; i < len; i++) {
        o = ref[i];
        ro = new ResultObject().setData(o);
        item = this.autocompletion.appendItem("all", ro.renderCardSearchMini());
        CUI.dom.setAttribute(item.DOM, "global-object-id", o._global_object_id);
        CUI.dom.data(item.DOM, "object", o);
      }
    }
    value = this.getSearch().queryElementInput.value();
    plusButton = new LocaButton({
      loca_key: "search.mini.result.manager.new_object",
      ui: "search.mini.result.manager.new_object.button",
      size: "mini",
      hidden: true,
      onClick: (function(_this) {
        return function() {
          return _this.getSearch().openEditor(value);
        };
      })(this)
    });
    this.autocompletion.getContainer("status").append(plusButton);
    append_onthefly = (function(_this) {
      return function() {
        var table;
        if (data.count > 0) {
          return;
        }
        table = _this.getSearch().getSearchObjecttypes()[0].table;
        if (_this._preventOntheflySuggestion || table.isHierarchy() || table.poolLink() || table.isPolyhierarchy()) {
          return;
        }
        item = _this.autocompletion.appendItem("all", new CUI.Label({
          "class": "ez5-search-mini-result-manager-onthefly-create",
          text: $$("search.mini.result.manager.onthefly_object", {
            value: value
          })
        }));
        return CUI.Events.listen({
          type: "click",
          node: item,
          call: function(ev) {
            var opts;
            console.log(value);
            ev.stopPropagation();
            opts = {
              value: value,
              dbInfoData: _this.__dbInfoData
            };
            _this.getSearch().insertOnTheFly(opts);
          }
        });
      };
    })(this);
    if (this.__hasPlusButton === null) {
      this.getSearch().canCreateSearchObjecttypes().done((function(_this) {
        return function(dbInfoData) {
          _this.__dbInfoData = dbInfoData;
          _this.__hasPlusButton = true;
          plusButton.show();
          append_onthefly();
          return _this.autocompletion.autoSize();
        };
      })(this)).fail((function(_this) {
        return function() {
          return _this.__hasPlusButton = false;
        };
      })(this));
    } else if (this.__hasPlusButton) {
      plusButton.show();
      append_onthefly();
      this.autocompletion.autoSize();
    }
    this.autocompletion.autoSize();
    if (typeof this._onShowResult === "function") {
      this._onShowResult();
    }
    return this;
  };

  return SearchMiniResultManager;

})(SearchManager);
// Generated by CoffeeScript 1.12.7
var FacetManager,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

FacetManager = (function(superClass) {
  extend(FacetManager, superClass);

  function FacetManager() {
    return FacetManager.__super__.constructor.apply(this, arguments);
  }

  FacetManager.prototype.initOpts = function() {
    FacetManager.__super__.initOpts.call(this);
    return this.addOpts({
      init_from_data: {
        check: "PlainObject"
      }
    });
  };

  FacetManager.prototype.init = function() {
    var defaultSettings, facetKey, has_pool_ot, i, j, k, len, len1, ot, pinned_facet, ref, ref1, v;
    this.facet_container = this.getSearch().getFacetsContainer();
    CUI.dom.setAttribute(this.facet_container, "ui", "facet.manager.container");
    this.initPane();
    has_pool_ot = false;
    ref = this.getSearch().getSearchObjecttypes();
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      if (ot.poolLink()) {
        has_pool_ot = true;
      }
    }
    this.facets = this.getAvailableFacets();
    this.settings = ez5.session.getPref("search.main.filter.settings");
    defaultSettings = this.getDefaultSettings();
    if (!this.settings) {
      this.settings = defaultSettings;
    } else {
      for (k in defaultSettings) {
        v = defaultSettings[k];
        if (this.settings[k] === void 0 || this.settings[k] === null) {
          this.settings[k] = v;
        }
      }
    }
    if (this.settings.pinned_facet && CUI.util.isArray(this.settings.pinned_facet) && this.settings.pinned_facet.length > 0) {
      pinned_facet = {};
      ref1 = this.settings.pinned_facet;
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        facetKey = ref1[j];
        pinned_facet[facetKey] = {};
      }
      this.settings.pinned_facet = pinned_facet;
      this.saveSettings();
    }
  };

  FacetManager.prototype.isActiveFirst = function() {
    return true;
  };

  FacetManager.prototype.getSettings = function() {
    return this.settings;
  };

  FacetManager.prototype.getSettingsPopover = function(opts) {
    var pop;
    if (opts == null) {
      opts = {};
    }
    return pop = new CUI.Popover({
      element: opts.element,
      backdrop: {
        policy: "click"
      },
      "class": "view-select-popover",
      pane: {
        header_left: new LocaLabel({
          loca_key: "search.main.filter.settings.title"
        }),
        padded: true,
        content: (function(_this) {
          return function() {
            var data, form;
            data = _this.getSettings();
            form = new CUI.Form({
              data: data,
              fields: [
                {
                  type: CUI.Options,
                  name: "sort",
                  form: {
                    label: $$("search.main.filter.settings.sort")
                  },
                  radio: true,
                  horizontal: false,
                  options: [
                    {
                      value: "count",
                      text: $$("search.main.filter.settings.sort.count")
                    }, {
                      value: "term",
                      text: $$("search.main.filter.settings.sort.term")
                    }
                  ]
                }, {
                  type: CUI.Options,
                  name: "sort_order",
                  form: {
                    label: $$("search.main.filter.settings.sort_order")
                  },
                  radio: true,
                  horizontal: false,
                  options: [
                    {
                      value: "ASC",
                      text: $$("search.main.filter.settings.sort_order.asc")
                    }, {
                      value: "DESC",
                      text: $$("search.main.filter.settings.sort_order.desc")
                    }
                  ]
                }
              ],
              onDataChanged: function() {
                return pop.changes = true;
              }
            });
            return form.start();
          };
        })(this)
      },
      onHide: (function(_this) {
        return function() {
          if (pop.changes) {
            _this.saveSettings();
          }
          return typeof opts.onHide === "function" ? opts.onHide(pop.changes) : void 0;
        };
      })(this)
    });
  };

  FacetManager.prototype.getDefaultSettings = function() {
    return {
      "sort": "count",
      "sort_order": "desc"
    };
  };

  FacetManager.prototype.saveSettings = function() {
    return ez5.session.savePref("search.main.filter.settings", this.settings, true);
  };

  FacetManager.prototype.getRootPoolId = function() {
    var ref;
    return (ref = ez5.pools.getRootPool()) != null ? ref.getId() : void 0;
  };

  FacetManager.prototype.getAvailableFacets = function() {
    var addField, append_append_facets, append_facets, easField, eas_fields, f, facets, force, hasTags, has_pool_ot, i, j, l, len, len1, len2, len3, len4, len5, len6, len7, len8, len9, linkedObjectsFields, m, mask, maskNames, n, ot, otm, p, q, r, ref, ref1, ref10, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, s, searchObjecttypeIds, t, tagGroup, tags, u;
    facets = [];
    if (this.getSearch().getSearchObjecttypes(true).length > 1) {
      facets.push(new ObjecttypeFacet({
        facetManager: this
      }));
    }
    searchObjecttypeIds = [];
    maskNames = this.getSearch().getAvailableMaskNames();
    otm = new ObjecttypeManager();
    has_pool_ot = false;
    hasTags = false;
    ref = this.getSearch().getSearchObjecttypes();
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      searchObjecttypeIds.push(ot.id());
      if (ot.poolLink()) {
        has_pool_ot = true;
      }
      if (ot.hasTags()) {
        hasTags = true;
      }
      ref1 = ot.masks;
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        m = ref1[j];
        for (l = 0, len2 = maskNames.length; l < len2; l++) {
          mask = maskNames[l];
          if (mask === m.name()) {
            otm.addMask(m);
            break;
          }
        }
      }
    }
    if (has_pool_ot && this.getRootPoolId()) {
      facets.push(new PoolFacet({
        facetManager: this
      }));
    }
    if (hasTags && !CUI.util.isEmpty(ez5.tagForm.tagGroups)) {
      ref2 = ez5.tagForm.tagGroups;
      for (n = 0, len3 = ref2.length; n < len3; n++) {
        tagGroup = ref2[n];
        tags = tagGroup.getTagsWithDisplayType(["facet"]);
        if (CUI.util.isEmpty(tags)) {
          continue;
        }
        facets.push(new TagsFacet({
          facetManager: this,
          tagGroup: tagGroup
        }));
      }
    }
    if (ez5.version("6")) {
      facets.push(new SystemTagsFacet({
        facetManager: this
      }));
    }
    otm.initCommonFields("facet", true, (function(_field, objecttype) {
      return _field.isVisible("facet", {
        top_level_data: {
          _objecttype: objecttype.name()
        }
      });
    }));
    eas_fields = [];
    ref3 = otm.getEASFields("facet", function(o) {
      var ref3;
      return ref3 = o.id(), indexOf.call(searchObjecttypeIds, ref3) >= 0;
    });
    for (p = 0, len4 = ref3.length; p < len4; p++) {
      easField = ref3[p];
      if (!((ref4 = easField.FieldSchema.custom_settings) != null ? ref4.hide_field_in_search_facet : void 0)) {
        eas_fields.push(easField);
      }
    }
    if (eas_fields.length) {
      facets.push(new EASFacet({
        facetManager: this
      }));
    }
    this.link_otm = new ObjecttypeManager();
    linkedObjectsFields = this.getSearch().getLinkedObjectFields("facet", true).filter((function(_this) {
      return function(linkedObjectField) {
        var ref5;
        return ref5 = linkedObjectField.getMainMask().name(), indexOf.call(maskNames, ref5) >= 0;
      };
    })(this));
    this.link_otm.addLinkedObjectFields(linkedObjectsFields);
    append_facets = [];
    append_append_facets = (function(_this) {
      return function() {
        append_facets.sort(function(a, b) {
          return a.getHeaderText().getText().localeCompare(b.getHeaderText().getText());
        });
        return facets.push.apply(facets, append_facets);
      };
    })(this);
    force = ez5.session.isDebug();
    ref5 = this.link_otm.objecttypes;
    for (q = 0, len5 = ref5.length; q < len5; q++) {
      ot = ref5[q];
      if (!force) {
        if (!((ref6 = ot.table.schema._objecttype) != null ? ref6.objecttype.show_in_facet_grouping : void 0)) {
          continue;
        }
      }
      if (ot._linked_object_fields.length > 1 || force) {
        append_facets.push(new LinkedObjecttypeFacet({
          facetManager: this,
          objecttype: ot
        }));
      }
    }
    append_append_facets();
    addField = (function(_this) {
      return function(f) {
        var ref7;
        if (!f.supportsFacet()) {
          return;
        }
        if (!((ref7 = f.FieldSchema.custom_settings) != null ? ref7.hide_field_in_search_facet : void 0)) {
          return append_facets.push(f.getFacet({
            facetManager: _this
          }));
        }
      };
    })(this);
    ref7 = otm.objecttypes;
    for (r = 0, len6 = ref7.length; r < len6; r++) {
      ot = ref7[r];
      append_facets = [];
      ref8 = ot.commonFields;
      for (s = 0, len7 = ref8.length; s < len7; s++) {
        f = ref8[s];
        addField(f);
      }
      ref9 = ot.masks;
      for (t = 0, len8 = ref9.length; t < len8; t++) {
        mask = ref9[t];
        ref10 = mask.uniqueFields;
        for (u = 0, len9 = ref10.length; u < len9; u++) {
          f = ref10[u];
          addField(f);
        }
      }
      append_append_facets();
    }
    return facets;
  };

  FacetManager.prototype.executeSearch = function() {
    CUI.dom.addClass(this.facet_container, "ez5-loading");
    return this.getSearch().execute();
  };

  FacetManager.prototype.getFacets = function() {
    return this.facets;
  };

  FacetManager.prototype.hasUserInput = function() {
    var f, i, len, ref;
    if (!ez5.version("6")) {
      return false;
    }
    ref = this.facets;
    for (i = 0, len = ref.length; i < len; i++) {
      f = ref[i];
      if (f.hasFilter()) {
        return true;
      }
    }
    return false;
  };

  FacetManager.prototype.addToRequest = function(request) {
    var _f, current_facets, f, facet_by_key, i, j, l, len, len1, len2, ref, ref1;
    if (!this.getSearch().hasFacets()) {
      return;
    }
    current_facets = this.facets || [];
    facet_by_key = {};
    for (i = 0, len = current_facets.length; i < len; i++) {
      f = current_facets[i];
      facet_by_key[f.getFacetKey()] = f;
    }
    this.facets = [];
    ref = this.getAvailableFacets();
    for (j = 0, len1 = ref.length; j < len1; j++) {
      f = ref[j];
      if (_f = facet_by_key[f.getFacetKey()]) {
        f.setFacet(_f);
      }
      this.facets.push(f);
    }
    if (!request.aggregations) {
      request.aggregations = {};
    }
    ref1 = this.facets;
    for (l = 0, len2 = ref1.length; l < len2; l++) {
      f = ref1[l];
      f.addToRequest(request);
    }
    if (request.execute && !request.page_request) {
      this.__waitBlock = new CUI.WaitBlock({
        element: this.facet_container,
        ui: "facet.manager.wait_block"
      }).show();
    }
    return this;
  };

  FacetManager.prototype.resetFacets = function() {
    var f, i, len, ref;
    if (this.facets) {
      ref = this.facets;
      for (i = 0, len = ref.length; i < len; i++) {
        f = ref[i];
        f.setFilter();
      }
    }
    return this;
  };

  FacetManager.prototype.getPane = function() {
    return new CUI.SimplePane({
      content: new CUI.EmptyLabel({
        centered: true,
        text: $$("facet.manager.init_text")
      }),
      footer_right: CUI.dom.div()
    });
  };

  FacetManager.prototype.initPane = function() {
    this.__pane = this.getPane();
    return CUI.dom.replace(this.facet_container, this.__pane);
  };

  FacetManager.prototype.showEmptyLabel = function() {
    return CUI.dom.replace(this.facet_container, new CUI.EmptyLabel({
      centered: true,
      text: $$("facet.manager.no_filters")
    }));
  };

  FacetManager.prototype.rebuild = function() {
    if (!ez5.version("6")) {
      console.warn("FacetManager.rebuild is not supported in versions prior to Fylr");
      return;
    }
    return this.showResult(this.__cached_request, this.getSearch().getLastData());
  };

  FacetManager.prototype.showResult = function(request, data) {
    var f, fb, get_grouping, groupCount, i, idx, itemsActive, j, l, last_grouping_text, len, len1, len2, len3, n, pinned, pinnedNode, pinnedTree, pinnedTreeElem, pinned_blocks, pinned_facets, pinned_group, ref, ref1, ref2, ref3, req, shc, sms, sort_pinned, vl;
    CUI.dom.removeClass(this.facet_container, "ez5-loading");
    if (request.page_request) {
      return;
    }
    if (!request.aggregations) {
      this.showEmptyLabel();
      return;
    }
    if (ez5.version("6")) {
      if (!request.force_flat_hierarchy && this.shouldUseFlatHierarchy()) {
        req = new Request();
        req.exclusive_show = true;
        sms = this.getSearch().getSearchManagers().filter((function(_this) {
          return function(sm) {
            return !(sm instanceof ResultManagerResult);
          };
        })(this));
        req.searchManagers = sms;
        req.force_flat_hierarchy = true;
        req.limit = 1;
        if ((ref = this.getSearch()) != null) {
          ref.execute(req);
        }
        return;
      }
      this.__cached_request = CUI.util.copyObject(request, true);
    }
    if ((ref1 = this.__waitBlock) != null) {
      ref1.destroy();
    }
    delete this.__waitBlock;
    this.initPane();
    if (!this.getSearch().hasFacets()) {
      return;
    }
    last_grouping_text = null;
    get_grouping = (function(_this) {
      return function(facet) {
        var grouping_text, ref2;
        grouping_text = facet != null ? (ref2 = facet.getGroupingText()) != null ? ref2.trim() : void 0 : void 0;
        if (!CUI.util.isEmpty(grouping_text) && grouping_text !== last_grouping_text) {
          last_grouping_text = grouping_text;
          return new CUI.StickyHeader({
            "class": "ez5-facet-manager-sticky-header",
            control: shc,
            level: 0,
            content: new CUI.Label({
              text: grouping_text
            })
          });
        } else {
          return null;
        }
      };
    })(this);
    itemsActive = [];
    this.__pane.empty("center");
    shc = new CUI.StickyHeaderControl({
      element: this.__pane.center()
    });
    groupCount = 0;
    pinned_blocks = [];
    pinned_facets = [];
    ref2 = this.facets;
    for (idx = i = 0, len = ref2.length; i < len; idx = ++i) {
      f = ref2[idx];
      f.data(data.aggregations);
      if (this.isActiveFirst()) {
        pinned = this.isFacetPinned(f);
        if (pinned && !f.hasFilter()) {
          if (this.__pin_edit_mode) {
            if (pinned.sort) {
              f.__sort = pinned.sort;
            }
            pinned_facets.push(f);
            fb = f.blockHeader(false, true);
          } else {
            fb = f.getFacetBlock();
          }
          if (!fb) {
            continue;
          }
          if (pinned.sort) {
            fb.__sort = pinned.sort;
          }
          pinned_blocks.push(fb);
          continue;
        }
        if (!f.hasFilter()) {
          continue;
        }
        if (!vl) {
          vl = new CUI.VerticalList({
            "class": "ez5-facet-manager-active-container",
            maximize_horizontal: true,
            maximize_vertical: false
          });
          this.__pane.append(vl, "center");
        }
        vl.append(get_grouping(f), "center");
        vl.append(f.getFacetActiveBlock(), "center");
        groupCount++;
      } else {
        if (f.hasFilter()) {
          fb = f.getFacetActiveBlock();
        } else {
          fb = f.getFacetBlock();
        }
        if (!fb) {
          continue;
        }
        this.__pane.append(get_grouping(f), "center");
        this.__pane.append(fb, "center");
        groupCount++;
      }
    }
    if (pinned_blocks.length > 0) {
      pinned_group = new CUI.StickyHeader({
        "class": "ez5-facet-manager-sticky-header ez5-facet-manager-pinned-sticky-header",
        control: shc,
        level: 0,
        content: new CUI.HorizontalLayout({
          center: {
            content: new CUI.Buttonbar({
              buttons: [
                new CUI.Label({
                  text: $$("facet.manager.pinned_filters"),
                  icon: "fa-thumb-tack"
                }), new CUI.Button({
                  icon: "fa-cog",
                  active: this.__pin_edit_mode,
                  tooltip: {
                    text: $$("facet.manager.edit_pinned_filters")
                  },
                  onClick: (function(_this) {
                    return function() {
                      _this.__pin_edit_mode = !_this.__pin_edit_mode;
                      return _this.rebuild();
                    };
                  })(this)
                })
              ]
            })
          }
        })
      });
      this.__pane.append(pinned_group, "center");
      sort_pinned = (function(_this) {
        return function(arr) {
          var j, len1, with_sort, without_sort;
          with_sort = [];
          without_sort = [];
          for (j = 0, len1 = arr.length; j < len1; j++) {
            fb = arr[j];
            if (fb.__sort || fb.__sort === 0) {
              with_sort.push(fb);
            } else {
              without_sort.push(fb);
            }
          }
          with_sort.sort(function(a, b) {
            return a.__sort - b.__sort;
          });
          return with_sort.concat(without_sort);
        };
      })(this);
      pinned_blocks = sort_pinned(pinned_blocks);
      pinned_facets = sort_pinned(pinned_facets);
      if (this.__pin_edit_mode) {
        pinnedTree = new ListViewEditTree({
          "class": "ez5-facet-list-tree ez5-facet-list-tree-sort",
          cols: ["maximize"],
          maximize_horizontal: true,
          maximize_vertical: false,
          rowMove: true,
          rowMoveWithinNodesOnly: true,
          onRowMove: (function(_this) {
            return function(initialIdx, finalIdx, after) {
              _this.sortPinFacets(initialIdx, finalIdx, after, pinned_facets);
              return _this.saveSettings();
            };
          })(this)
        });
        pinnedTreeElem = pinnedTree.render();
        pinnedTree.root.open();
        for (j = 0, len1 = pinned_blocks.length; j < len1; j++) {
          fb = pinned_blocks[j];
          pinnedNode = new CUI.ListViewTreeNode({
            html: fb
          });
          pinnedTree.root.children.push(pinnedNode);
        }
        pinnedTree.root.update(true);
        this.__pane.append(pinnedTreeElem, "center");
        groupCount++;
      } else {
        for (l = 0, len2 = pinned_blocks.length; l < len2; l++) {
          fb = pinned_blocks[l];
          this.__pane.append(fb, "center");
          groupCount++;
        }
      }
    }
    if (this.isActiveFirst()) {
      ref3 = this.facets;
      for (idx = n = 0, len3 = ref3.length; n < len3; idx = ++n) {
        f = ref3[idx];
        if (this.isFacetPinned(f)) {
          continue;
        }
        fb = f.getFacetBlock();
        if (!fb) {
          continue;
        }
        this.__pane.append(get_grouping(f), "center");
        this.__pane.append(fb, "center");
        groupCount++;
      }
    }
    if (groupCount === 0) {
      this.showEmptyLabel();
    }
    return this;
  };

  FacetManager.prototype.getStoreData = function(saveData) {
    var facet, facetFilters, filters, i, len, ref;
    if (saveData == null) {
      saveData = {};
    }
    FacetManager.__super__.getStoreData.call(this, saveData);
    filters = {};
    ref = this.facets;
    for (i = 0, len = ref.length; i < len; i++) {
      facet = ref[i];
      facetFilters = facet.getFilter();
      if (CUI.util.isEmpty(facetFilters)) {
        continue;
      }
      filters[facet.getFacetKey()] = {
        filters: facetFilters,
        searchType: facet.getSearchType()
      };
    }
    saveData.FacetManager = filters;
    return saveData;
  };

  FacetManager.prototype.restoreFromStored = function(otherFacetManager) {
    var facet, facetByKey, facetFilter, facetKey, filters, i, len, ref;
    filters = otherFacetManager._init_from_data;
    facetByKey = {};
    ref = this.facets;
    for (i = 0, len = ref.length; i < len; i++) {
      facet = ref[i];
      facetByKey[facet.getFacetKey()] = facet;
    }
    for (facetKey in filters) {
      facetFilter = filters[facetKey];
      facet = facetByKey[facetKey];
      if (!facet) {
        continue;
      }
      facet.setSearchType(facetFilter.searchType);
      facet.setFilter(CUI.util.copyObject(facetFilter.filters, true), true);
    }
    return CUI.resolvedPromise();
  };

  FacetManager.prototype.isFacetPinned = function(facet) {
    if (!this.settings.pinned_facet) {
      return false;
    }
    return this.settings.pinned_facet[facet.getFacetKey()];
  };

  FacetManager.prototype.pinFacet = function(facet) {
    var base;
    if ((base = this.settings).pinned_facet == null) {
      base.pinned_facet = {};
    }
    this.settings.pinned_facet[facet.getFacetKey()] = {};
    this.saveSettings();
    return this.rebuild();
  };

  FacetManager.prototype.unpinFacet = function(facet) {
    if (!this.settings.pinned_facet) {
      return;
    }
    delete this.settings.pinned_facet[facet.getFacetKey()];
    this.saveSettings();
    return this.rebuild();
  };

  FacetManager.prototype.isFacetOpened = function(facet) {
    var panelSettings;
    panelSettings = CUI.getLocalStorage("filter_panel_settings");
    if (!panelSettings) {
      return false;
    }
    return panelSettings[facet.getFacetKey()];
  };

  FacetManager.prototype.addOpenedFacet = function(facet) {
    var panelSettings;
    panelSettings = CUI.getLocalStorage("filter_panel_settings") || {};
    panelSettings[facet.getFacetKey()] = true;
    return CUI.setLocalStorage("filter_panel_settings", panelSettings);
  };

  FacetManager.prototype.removeOpenedFacet = function(facet) {
    var panelSettings;
    panelSettings = CUI.getLocalStorage("filter_panel_settings") || {};
    delete panelSettings[facet.getFacetKey()];
    return CUI.setLocalStorage("filter_panel_settings", panelSettings);
  };

  FacetManager.prototype.sortPinFacets = function(from, to, after, facets) {
    var currentSort, facet, i, index, lastAssigned, len, pinned, ref;
    if (after && from > to) {
      to += 1;
    }
    facets.splice(to, 0, facets.splice(from, 1)[0]);
    lastAssigned = 0;
    for (index = i = 0, len = facets.length; i < len; index = ++i) {
      facet = facets[index];
      pinned = this.isFacetPinned(facet);
      currentSort = (ref = pinned.sort) != null ? ref : null;
      if ((currentSort != null) && currentSort > lastAssigned) {
        lastAssigned = currentSort;
      } else {
        lastAssigned += 1;
        pinned.sort = lastAssigned;
      }
    }
  };

  FacetManager.prototype.setFacetName = function(facet, name) {
    var pinned;
    pinned = this.isFacetPinned(facet);
    if (!pinned) {
      return;
    }
    if (CUI.util.isEmpty(name)) {
      delete pinned.name;
    } else {
      pinned.name = name;
    }
    this.saveSettings();
    return this.rebuild();
  };

  FacetManager.prototype.shouldUseFlatHierarchy = function() {
    var hasHierarchy, hm, i, len, ot, ref;
    if (!ez5.version("6")) {
      return false;
    }
    hasHierarchy = false;
    ref = this.getSearch().getSearchObjecttypes(true);
    for (i = 0, len = ref.length; i < len; i++) {
      ot = ref[i];
      if (ot.isHierarchy() || ot.isPolyhierarchy()) {
        hasHierarchy = true;
        break;
      }
    }
    if (!hasHierarchy) {
      return false;
    }
    hm = this.getSearch().getSearchHierarchyManager();
    return hasHierarchy && (hm != null) && hm.getExpandHierarchyMode() === "top_level_without_search";
  };

  return FacetManager;

})(SearchManager);
// Generated by CoffeeScript 1.12.7
var Facet,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

Facet = (function(superClass) {
  extend(Facet, superClass);

  function Facet() {
    this.__getMoreButton = bind(this.__getMoreButton, this);
    return Facet.__super__.constructor.apply(this, arguments);
  }

  Facet.prototype.initOpts = function() {
    Facet.__super__.initOpts.call(this);
    this.addOpts({
      facetManager: {
        mandatory: true,
        check: FacetManager
      }
    });
    return this.setFilter();
  };

  Facet.prototype.getLimit = function() {
    return 10;
  };

  Facet.prototype.name = function() {
    return "facet-name-missing";
  };

  Facet.prototype.data = function(data) {
    if (CUI.util.isUndef(data)) {
      return this._data;
    }
    return this._data = data;
  };

  Facet.prototype.setFacet = function(otherFacet) {
    this.setFilter(otherFacet.getFilter());
    return this.setSearchType(otherFacet.getSearchType());
  };

  Facet.prototype.getFacets = function() {
    return this._facetManager.getFacets();
  };

  Facet.prototype.getSearch = function() {
    return this._facetManager.getSearch();
  };

  Facet.prototype.getObjects = function(key, data) {
    var ref;
    if (key == null) {
      key = this.name();
    }
    if (data == null) {
      data = this.data();
    }
    return (ref = data[key]) != null ? ref.linked_objects : void 0;
  };

  Facet.prototype.getObjectsOnHierarchy = function(key, data) {
    var _key, items, linked_items, value;
    if (key == null) {
      key = this.name();
    }
    if (data == null) {
      data = this.data();
    }
    items = [];
    for (_key in data) {
      value = data[_key];
      if (_key.startsWith(key)) {
        linked_items = value.linked_objects;
        if (linked_items) {
          items.push.apply(items, linked_items);
        }
      }
    }
    return items;
  };

  Facet.prototype.getObjectsForPopover = function(key, data, offset) {
    if (key == null) {
      key = this.name();
    }
    if (data == null) {
      data = this.data();
    }
    if (offset == null) {
      offset = 0;
    }
    return this.getObjects(key, data);
  };

  Facet.prototype.getFacetKey = function(path) {
    var key;
    if (path == null) {
      path = [];
    }
    key = this.name();
    if ((path != null ? path.length : void 0) > 0) {
      key += ":" + path.join(".");
    }
    return key;
  };

  Facet.prototype.getObjectPath = function(obj) {
    var i, len, ref, results, s;
    if (this.isHierarchy() || this.isPolyhierarchy()) {
      ref = obj._path;
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        s = ref[i];
        results.push(s._id);
      }
      return results;
    } else {
      return [obj._id];
    }
  };

  Facet.prototype.getObjectPathString = function(obj) {
    return this.getObjectPath(obj).join(".") + ".";
  };

  Facet.prototype.getObjectsSorted = function(objects) {
    if (objects == null) {
      objects = null;
    }
    if (objects) {
      return objects;
    }
    return this.getObjects();
  };

  Facet.prototype.getPinButton = function() {
    var btn;
    if (this.hasFilter()) {
      return;
    }
    btn = new CUI.Button({
      icon: "fa-thumb-tack",
      appearance: "transparent-border",
      "class": "cui-button-pin facet-pin-button",
      tooltip: {
        text: (function(_this) {
          return function() {
            if (btn.isActive()) {
              return $$("facet.manager.button.unpin|tooltip");
            }
            return $$("facet.manager.button.pin|tooltip");
          };
        })(this)
      },
      "switch": true,
      active: !!this._facetManager.isFacetPinned(this),
      onActivate: (function(_this) {
        return function(btn, ev) {
          if (ev.initial_activate) {
            return;
          }
          return _this._facetManager.pinFacet(_this);
        };
      })(this),
      onDeactivate: (function(_this) {
        return function(btn, ev) {
          if (ev.initial_activate) {
            return;
          }
          return _this._facetManager.unpinFacet(_this);
        };
      })(this)
    });
    return btn;
  };

  Facet.prototype.getFacetBlock = function() {
    var btn, cbs, checkboxesList, data, facetBlockNode, facetHeaderNode, facetListTree, force_has_more, objects, ref, tree;
    if (!ez5.version("6")) {
      return this.getLegacyFacetBlock();
    }
    if (this.hasFilter()) {
      return;
    }
    data = this.data();
    objects = this.getObjectsSorted();
    if ((objects != null ? objects.length : void 0) > 0 && !this.hasFilter()) {
      if (objects.length > this.getLimit()) {
        objects = objects.slice(0, this.getLimit());
        force_has_more = true;
      }
      cbs = this.getCheckboxesFromItems(this.getItemsForObjects(objects));
      if (((ref = data[this.name()]) != null ? ref.has_more : void 0) || force_has_more) {
        btn = new LocaButton({
          loca_key: "facet.button.more",
          ui: "facet.more.button:" + (this.name()),
          onClick: (function(_this) {
            return function() {
              return _this.openPopover(btn);
            };
          })(this)
        });
        cbs.push(btn);
      }
      checkboxesList = new CUI.VerticalList({
        content: cbs,
        maximize_horizontal: true,
        maximize_vertical: true,
        auto_buttonbar: false
      });
      facetBlockNode = new CUI.ListViewTreeNode({
        html: checkboxesList.DOM
      });
      facetHeaderNode = new CUI.ListViewTreeNode({
        html: this.blockHeader(),
        children: [facetBlockNode]
      });
      tree = new CUI.ListViewTree({
        "class": "ez5-facet-list-tree",
        cols: ["maximize"],
        maximize_horizontal: true,
        maximize_vertical: false,
        focusable: true,
        onOpen: (function(_this) {
          return function() {
            return _this._facetManager.addOpenedFacet(_this);
          };
        })(this),
        onClose: (function(_this) {
          return function() {
            return _this._facetManager.removeOpenedFacet(_this);
          };
        })(this)
      });
      facetListTree = tree.render();
      tree.root.open();
      tree.root.children = [facetHeaderNode];
      tree.root.update(true);
      if (this._facetManager.isFacetOpened(this)) {
        facetHeaderNode.open();
      }
      if (this._facetManager.isFacetPinned(this)) {
        CUI.dom.addClass(tree, "ez5-facet-list-tree--pinned");
      }
      return facetListTree;
    } else {

    }
  };

  Facet.prototype.getLegacyFacetBlock = function() {
    var bl, btn, cbs, data, force_has_more, objects, ref;
    if (this.hasFilter()) {
      return;
    }
    data = this.data();
    objects = this.getObjectsSorted();
    if ((objects != null ? objects.length : void 0) > 0 && !this.hasFilter()) {
      bl = new CUI.Block({
        header: this.blockHeader(),
        "class": "ez5-facet-block",
        ui: "facet.block:" + (this.getFacetKey())
      });
      if (objects.length > this.getLimit()) {
        objects = objects.slice(0, this.getLimit());
        force_has_more = true;
      }
      cbs = this.getCheckboxesFromItems(this.getItemsForObjects(objects));
      if (((ref = data[this.name()]) != null ? ref.has_more : void 0) || force_has_more) {
        btn = new LocaButton({
          loca_key: "facet.button.more",
          ui: "facet.more.button:" + (this.name()),
          onClick: (function(_this) {
            return function() {
              return _this.openPopover(btn);
            };
          })(this)
        });
        cbs.push(btn);
      }
      bl.setContent(cbs);
      return bl;
    } else {

    }
  };

  Facet.prototype.nameLocalized = function() {
    return CUI.util.getObjectClass(this) + ".nameLocalized not implemented.";
  };

  Facet.prototype.fullNameLocalized = function() {
    return this.nameLocalized();
  };

  Facet.prototype.blockHeader = function(showButtonBar, showEditBtn) {
    var custom_name, editBtn, header, headerLabel, pinButton, pinned, rightContent, secondaryHeaderLabel, tooltipElement, tooltipText;
    if (showButtonBar == null) {
      showButtonBar = true;
    }
    if (showEditBtn == null) {
      showEditBtn = false;
    }
    if (showButtonBar && this.hasFilter()) {
      rightContent = new CUI.Buttonbar({
        buttons: [
          new CUI.Button({
            active: this.getSearchType() === "AND",
            text: $$("facet.manager.header.button.option-and"),
            radio: "search_option",
            group: "search_option",
            size: "mini",
            hidden: !this.__isAndButtonAvailable(),
            disabled: !this.__isAndButtonAvailable(),
            onClick: (function(_this) {
              return function(_, button) {
                if (_this.getSearchType() === "AND") {
                  return;
                }
                _this.setSearchType("AND");
                if (_this.hasFilter()) {
                  _this._facetManager.executeSearch();
                }
              };
            })(this)
          }), new CUI.Button({
            active: this.getSearchType() === "OR",
            text: $$("facet.manager.header.button.option-or"),
            radio: "search_option",
            group: "search_option",
            size: "mini",
            hidden: !this.__isAndButtonAvailable(),
            disabled: !this.__isOrButtonAvailable(),
            onClick: (function(_this) {
              return function() {
                if (_this.getSearchType() === "OR") {
                  return;
                }
                _this.setSearchType("OR");
                if (_this.hasFilter()) {
                  _this._facetManager.executeSearch();
                }
              };
            })(this)
          }), new CUI.Button({
            icon: $$("facet.manager.header.button.reset|icon"),
            size: "mini",
            onClick: (function(_this) {
              return function() {
                _this.clearFilter();
                _this._facetManager.executeSearch();
              };
            })(this)
          })
        ]
      });
    }
    headerLabel = this.getHeaderText();
    pinned = this._facetManager.isFacetPinned(this);
    if (ez5.version("6") && pinned) {
      if (pinned.name) {
        custom_name = true;
        headerLabel = new CUI.Label({
          text: pinned.name
        });
      } else {
        secondaryHeaderLabel = this.getSecondaryHeader();
      }
    }
    if (ez5.version("6") && showButtonBar) {
      pinButton = this.getPinButton();
      if (pinned) {
        tooltipText = this.fullNameLocalized() + (this.getSecondaryHeaderText() ? " " + (this.getSecondaryHeaderText()) : "");
      } else {
        tooltipText = this.fullNameLocalized();
      }
      header = new CUI.HorizontalLayout({
        center: {
          content: new CUI.Buttonbar({
            buttons: [headerLabel, secondaryHeaderLabel, pinButton]
          })
        },
        right: {
          content: rightContent
        }
      });
    } else {
      if (showEditBtn) {

        /*
        			 This is not used by now, but we keep it for future use this shows a button for let the user customize the facet see 70863
        				editBtn = new CUI.Button
        					icon: "fa-pencil"
        					appearance: "transparent-border"
        					class: "cui-button-pin facet-pin-button"
        					tooltip: text: $$("facet.manager.pin_edit.tooltip")
        					onClick: =>
        						new CUI.prompt
        							default: pinned.name or @fullNameLocalized() or ""
        							markdown: true
        							min_length: 0
        							placeholder: @fullNameLocalized()
        							text: $$("facet.manager.pin_edit.prompt", name: @fullNameLocalized())
        							"Customize name for filter " + @fullNameLocalized()
        						.done((name) =>
        							@_facetManager.setFacetName(@,name)
        						)
         */
        header = new CUI.HorizontalLayout({
          center: {
            content: new CUI.Buttonbar({
              buttons: [headerLabel, secondaryHeaderLabel, editBtn = null]
            })
          },
          right: {
            content: rightContent
          }
        });
        tooltipText = this.fullNameLocalized();
      } else {
        header = new CUI.HorizontalLayout({
          center: {
            content: headerLabel
          },
          right: {
            content: rightContent
          }
        });
        tooltipText = this.fullNameLocalized();
      }
    }
    tooltipElement = CUI.dom.findElement(headerLabel != null ? headerLabel.DOM : void 0, "span");
    if (!tooltipElement) {
      tooltipElement = headerLabel;
    }
    new CUI.Tooltip({
      element: tooltipElement,
      text: tooltipText
    });
    return header;
  };

  Facet.prototype._checkBooleanOperatorVisibility = function() {
    return this.__isAndButtonAvailable() && this.__isOrButtonAvailable();
  };

  Facet.prototype.getHeaderText = function() {
    return new CUI.Label({
      text: this.fullNameLocalized()
    });
  };

  Facet.prototype.getSecondaryHeader = function() {};

  Facet.prototype.getSecondaryHeaderText = function() {};

  Facet.prototype.setSearchType = function(type) {
    return this.__searchType = type;
  };

  Facet.prototype.getSearchType = function() {
    var defaultType;
    if (this.__isAndButtonAvailable()) {
      defaultType = "AND";
    } else {
      defaultType = "OR";
    }
    return this.__searchType || defaultType;
  };

  Facet.prototype.getGroupingText = function() {
    console.error(CUI.util.getObjectClass(this) + ".getGroupingText needs to be implemented.");
    return null;
  };

  Facet.prototype.renderObject = function(object) {
    return CUI.dom.text(this.renderObjectText(object));
  };

  Facet.prototype.renderItemContent = function(object) {
    var content;
    content = CUI.dom.element("DIV", {
      "class": " ez5-facet-content"
    });
    CUI.dom.append(content, this.renderObject(object));
    CUI.dom.append(content, CUI.dom.text(ez5.format_number(object.count)));
    CUI.dom.data(content, "facet-object", object);
    return content;
  };

  Facet.prototype.getItem = function(object) {
    var active, item;
    active = this.isFiltered(object);
    item = {
      content: this.renderItemContent(object),
      "class": "ez5-facet-item",
      active: active,
      ui: "facet.item.checkbox",
      onClick: (function(_this) {
        return function(ev) {
          if (ev.shiftKey()) {
            _this.setSearchType("OR");
          }
          if (active) {
            _this.removeFilter(object);
          } else {
            _this.addFilter(object);
          }
          _this.closePopover();
          return _this._facetManager.executeSearch();
        };
      })(this)
    };
    return item;
  };

  Facet.prototype.getFacetActiveBlock = function() {
    var activeBlock;
    activeBlock = new CUI.Block({
      header: this.blockHeader(),
      content: [],
      appearance: "normal",
      "class": "ez5-facet-block ez5-facet-active-block",
      ui: "facet.block.active:" + (this.getFacetKey())
    });
    this.__setActiveBlockContent(activeBlock);
    return activeBlock;
  };

  Facet.prototype.__setActiveBlockContent = function(block) {
    var items;
    items = [];
    this.__addActiveInnerItems(items);
    this.__addExtraInnerItems(items).done((function(_this) {
      return function() {
        var checkboxes;
        checkboxes = _this.getCheckboxesFromItems(items);
        return block.setContent(checkboxes);
      };
    })(this));
  };

  Facet.prototype.isActiveFirst = function() {
    return this._facetManager.isActiveFirst();
  };

  Facet.prototype.__getMoreButton = function(data, path) {
    var facetKey, moreButton, ref;
    if (path == null) {
      path = [];
    }
    facetKey = this.getFacetKey(path);
    if (!((ref = data[facetKey]) != null ? ref.has_more : void 0)) {
      return;
    }
    moreButton = new LocaButton({
      loca_key: "facet.button.more",
      ui: "facet.more.button:" + facetKey,
      onClick: (function(_this) {
        return function() {
          return _this.openPopover(moreButton, path);
        };
      })(this)
    });
    return moreButton;
  };

  Facet.prototype.__addActiveInnerItems = function(items, path) {
    var addActiveObject, added, facetKey, i, isHierarchy, j, len, len1, moreButton, obj, objects, objectsAdded, ref;
    if (path == null) {
      path = [];
    }
    facetKey = this.getFacetKey(path);
    isHierarchy = this.isHierarchy() || this.isPolyhierarchy();
    objects = this.getObjectsSorted(this.getObjects(facetKey) || []) || [];
    addActiveObject = (function(_this) {
      return function(obj) {
        var _parentPath, _path;
        if (!_this.isFiltered(obj)) {
          return false;
        }
        if (isHierarchy) {
          _path = _this.getObjectPath(obj);
          _parentPath = _path.slice(0, _path.length - 1);
          if (_parentPath.join(".") !== path.join(".")) {
            return false;
          }
        }
        (function(obj) {
          items.push({
            active: true,
            content: _this.renderItemContent(obj),
            "class": "ez5-facet-active ez5-facet-item ez5-facet-active-depth-" + _this.__getPathLength(path),
            ui: "facet.item.active",
            onClick: function() {
              _this.removeFilter(obj);
              return _this._facetManager.executeSearch();
            }
          });
          if (isHierarchy) {
            return _this.__addActiveInnerItems(items, _this.getObjectPath(obj));
          }
        })(obj);
        return true;
      };
    })(this);
    objectsAdded = [];
    for (i = 0, len = objects.length; i < len; i++) {
      obj = objects[i];
      added = addActiveObject(obj);
      if (added) {
        objectsAdded.push(this.getObjectPathString(obj));
      }
    }
    ref = CUI.util.copyObject(this.getFilter(), true);
    for (j = 0, len1 = ref.length; j < len1; j++) {
      obj = ref[j];
      if (objectsAdded.includes(this.getObjectPathString(obj))) {
        continue;
      }
      obj.count = 0;
      addActiveObject(obj);
    }
    if (this.isActiveFirst()) {
      items.push.apply(items, this.getItemsForObjects(objects, path));
    }
    moreButton = this.__getMoreButton(this.data(), path);
    if (moreButton) {
      items.push(moreButton);
    }
  };

  Facet.prototype.__addExtraInnerItems = function(items) {
    var deferred, f, i, j, len, len1, ref, ref1, request, requestData, searchManager, type;
    type = this.getSearchType();
    if (type !== "OR") {
      return CUI.resolvedPromise();
    }
    deferred = new CUI.Deferred();
    request = new Request();
    request.search = [];
    ref = this.getSearch().getSearchManagers();
    for (i = 0, len = ref.length; i < len; i++) {
      searchManager = ref[i];
      if (searchManager instanceof FacetManager) {
        continue;
      }
      searchManager.addToRequest(request);
    }
    ref1 = this.getFacets();
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      f = ref1[j];
      requestData = {
        aggregations: {},
        search: []
      };
      f.addToRequest(requestData);
      if (f === this) {
        request.aggregations = requestData.aggregations;
      } else {
        request.search = request.search.concat(requestData.search);
      }
    }
    ez5.api.search({
      data: {
        debug: "Facet.AggregationORItemsFor_" + (this.name())
      },
      json_data: {
        limit: 0,
        offset: 0,
        format: "standard",
        generate_rights: false,
        objecttypes: this.getSearch().getSearchObjecttypes().map((function(_this) {
          return function(ot) {
            return ot.name();
          };
        })(this)),
        search: request.search,
        aggregations: request.aggregations
      }
    }).done((function(_this) {
      return function(_data) {
        var bid, data, existingItemIds, facetKey, item, k, l, len2, len3, moreButton, newItems, newObjects, obj, objects, ref2;
        data = _data.aggregations;
        facetKey = _this.getFacetKey();
        if (_this.needToLoadHierarchyInnerItems()) {
          objects = _this.getObjectsOnHierarchy(facetKey, data);
        } else {
          objects = _this.getObjectsSorted(_this.getObjects(facetKey, data));
        }
        bid = items.findIndex(function(item) {
          return item instanceof LocaButton;
        });
        if (bid !== -1) {
          items.splice(bid, 1);
        }
        if (_this.isActiveFirst()) {
          if (_this.needToLoadHierarchyInnerItems()) {
            _this.getItemsForExtraObjectsWithHierarchy(items, objects, data);
          } else {
            newObjects = [];
            existingItemIds = [];
            for (k = 0, len2 = items.length; k < len2; k++) {
              item = items[k];
              obj = CUI.dom.data(item.content, "facet-object");
              if (obj) {
                existingItemIds.push(_this._getObjectId(obj));
              }
            }
            for (l = 0, len3 = objects.length; l < len3; l++) {
              obj = objects[l];
              if (ref2 = _this._getObjectId(obj), indexOf.call(existingItemIds, ref2) >= 0) {
                continue;
              }
              newObjects.push(obj);
            }
            newItems = _this.getItemsForObjects(newObjects);
            items.push.apply(items, newItems);
          }
        }
        if (!_this.needToLoadHierarchyInnerItems()) {
          moreButton = _this.__getMoreButton(data);
          if (moreButton) {
            items.push(moreButton);
          }
        }
        return deferred.resolve();
      };
    })(this)).fail(deferred.resolve);
    return deferred.promise();
  };

  Facet.prototype.needToLoadHierarchyInnerItems = function() {
    return this.isHierarchy() || this.isPolyhierarchy();
  };

  Facet.prototype.getPathLengthOffset = function() {
    return 0;
  };

  Facet.prototype._getObjectId = function(obj) {
    if (obj._id == null) {
      return obj.term + "-" + obj.count;
    }
    return obj._id;
  };

  Facet.prototype.__getPathLength = function(path) {
    return Math.max(0, path.length - this.getPathLengthOffset());
  };

  Facet.prototype.getItemForObject = function(obj, path) {
    var item;
    item = this.getItem(obj);
    if (path) {
      item["class"] += " ez5-facet-active-item-depth-" + this.__getPathLength(path);
    }
    return item;
  };

  Facet.prototype.getItemsForObjects = function(objects, path) {
    var i, items, len, obj, ref;
    if (path == null) {
      path = [];
    }
    items = [];
    ref = objects || [];
    for (i = 0, len = ref.length; i < len; i++) {
      obj = ref[i];
      if (this.isFiltered(obj)) {
        continue;
      }
      items.push(this.getItemForObject(obj, path));
    }
    return items;
  };

  Facet.prototype.__getExtraItemsPathClass = function(object, offset) {
    if (offset == null) {
      offset = 1;
    }
    return " ez5-facet-active-item-depth-" + (this.__getPathLength(object._path) - offset);
  };

  Facet.prototype.getItemsForExtraObjectsWithHierarchy = function(existingItems, objects, data) {
    var duplicate, existing_item, existing_item_object, flatHierarchy, flattenHierarchy, ho, hobj, i, insertObjectInHierarchy, isFiltered, item, j, k, len, len1, len2, newItem, newObjects, o, obj, objectHierarchy;
    if (existingItems == null) {
      existingItems = [];
    }
    newObjects = [];
    objectHierarchy = [];
    insertObjectInHierarchy = function(ho, hierarchy) {
      var el, i, len, ref, ref1, ref2;
      if (hierarchy.length === 0) {
        hierarchy.push(ho);
        return;
      }
      for (i = 0, len = hierarchy.length; i < len; i++) {
        el = hierarchy[i];
        if (!((ref = ho.object) != null ? ref._path : void 0) || !((ref1 = el.object) != null ? ref1._path : void 0)) {
          continue;
        }
        if (ref2 = el.object._id, indexOf.call(ho.object._path.map((function(_this) {
          return function(s) {
            return s._id;
          };
        })(this)), ref2) >= 0) {
          insertObjectInHierarchy(ho, el.children);
          return;
        }
      }
      hierarchy.push(ho);
    };
    for (i = 0, len = existingItems.length; i < len; i++) {
      item = existingItems[i];
      obj = CUI.dom.data(item.content, "facet-object");
      if (!obj) {
        continue;
      }
      ho = {
        object: obj,
        item: item,
        children: []
      };
      insertObjectInHierarchy(ho, objectHierarchy);
    }
    for (j = 0, len1 = objects.length; j < len1; j++) {
      o = objects[j];
      isFiltered = this.isFiltered(o);
      duplicate = false;
      for (k = 0, len2 = existingItems.length; k < len2; k++) {
        existing_item = existingItems[k];
        existing_item_object = CUI.dom.data(existing_item.content, "facet-object");
        if (!existing_item_object) {
          continue;
        }
        if (this._getObjectId(existing_item_object) === this._getObjectId(o)) {
          if (isFiltered) {
            if (existing_item_object.count !== o.count) {
              existing_item_object.count = o.count;
              newItem = this.getItem(existing_item_object);
              existing_item.content = newItem.content;
            }
          }
          duplicate = true;
          break;
        }
      }
      if (!duplicate && !isFiltered) {
        newObjects.push(o);
        item = this.getItem(o);
        item["class"] += this.__getExtraItemsPathClass(o);
        hobj = {
          object: o,
          item: item,
          children: []
        };
        insertObjectInHierarchy(hobj, objectHierarchy);
      }
    }
    flattenHierarchy = (function(_this) {
      return function(hierarchy, path) {
        var items, l, len3, moreButton, newPath;
        if (path == null) {
          path = [];
        }
        items = [];
        if (!hierarchy) {
          return items;
        }
        for (l = 0, len3 = hierarchy.length; l < len3; l++) {
          ho = hierarchy[l];
          items.push(ho.item);
          if (ho.children.length > 0) {
            newPath = path.concat([_this._getObjectId(ho.object)]);
            items.push.apply(items, flattenHierarchy(ho.children, newPath));
          }
        }
        moreButton = _this.__getMoreButton(data, path);
        if (moreButton) {
          items.push(moreButton);
        }
        return items;
      };
    })(this);
    flatHierarchy = flattenHierarchy(objectHierarchy);
    existingItems.splice(0, existingItems.length);
    return existingItems.push.apply(existingItems, flatHierarchy);
  };

  Facet.prototype.getCheckboxesFromItems = function(items) {
    var cbs, i, item, len;
    cbs = [];
    for (i = 0, len = items.length; i < len; i++) {
      item = items[i];
      if (CUI.util.isPlainObject(item)) {
        item.undo_and_changed_support = false;
        item.multiline = true;
        cbs.push((new CUI.Checkbox(item)).start());
      } else {
        cbs.push(item);
      }
    }
    return cbs;
  };

  Facet.prototype.addToRequest = function(request) {
    var _searchComplex, f, facet, filter, i, isOr, j, len, len1, obj, objFilters;
    _searchComplex = {
      __filter: "Facet",
      type: "complex",
      bool: "must",
      search: []
    };
    isOr = this.getSearchType() === "OR";
    objFilters = this.getFilter();
    if (this.isHierarchy() && objFilters.length > 1 && isOr) {
      objFilters = this.cleanHierarchyFilters(objFilters);
    }
    for (i = 0, len = objFilters.length; i < len; i++) {
      obj = objFilters[i];
      filter = this.requestSearchFilter(obj);
      filter.__filter = "Facet";
      if (isOr) {
        filter.bool = "should";
      }
      _searchComplex.search.push(filter);
    }
    if (_searchComplex.search.length > 0) {
      request.search.push(_searchComplex);
    }
    if (request.page_request) {
      return this;
    }
    facet = this.requestFacetWithLimit();
    if (facet) {
      if (this.hasMultipleAggregations()) {
        for (j = 0, len1 = facet.length; j < len1; j++) {
          f = facet[j];
          f._cls = CUI.util.getObjectClass(this);
          request.aggregations[f.field] = f;
        }
      } else {
        facet._cls = CUI.util.getObjectClass(this);
        request.aggregations[this.name()] = facet;
      }
    }
    if (this.isHierarchy() || this.isPolyhierarchy()) {
      this.addToRequestHierarchy(request);
    }
    return this;
  };

  Facet.prototype.requestFacetWithLimit = function(obj) {
    var add_props, i, len, r, rFacet;
    add_props = (function(_this) {
      return function(request) {
        if (!_this.__isBucketFacet()) {
          request.limit = _this.getLimit();
          request.sort = _this.getSortSetting();
          return request.order = _this.getSortOrderSetting();
        }
      };
    })(this);
    rFacet = this.requestFacet(obj);
    if (!rFacet) {
      return;
    }
    if (this.hasMultipleAggregations()) {
      for (i = 0, len = rFacet.length; i < len; i++) {
        r = rFacet[i];
        add_props(r);
      }
    } else {
      add_props(rFacet);
    }
    return rFacet;
  };

  Facet.prototype.getSortSetting = function() {
    var ref, ref1;
    return ((ref = this._facetManager) != null ? (ref1 = ref.getSettings()) != null ? ref1.sort : void 0 : void 0) || "count";
  };

  Facet.prototype.getSortOrderSetting = function() {
    var ref, ref1;
    return ((ref = this._facetManager) != null ? (ref1 = ref.getSettings()) != null ? ref1.sort_order : void 0 : void 0) || "DESC";
  };

  Facet.prototype.addToRequestHierarchy = function(request) {
    var fac_req, i, idx, j, len, len1, obj, objectFacetRequest, path, r, ref;
    fac_req = request.aggregations[this.name()];
    fac_req.filter_parent = null;
    if (!this.__isBucketFacet()) {
      fac_req.limit = this.getLimit() + this.getFilter().length;
    }
    ref = this.getFilter();
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      obj = ref[idx];
      path = this.getObjectPath(obj);
      objectFacetRequest = this.requestFacetWithLimit(obj);
      if (!objectFacetRequest) {
        continue;
      }
      if (this.hasMultipleAggregations()) {
        for (j = 0, len1 = objectFacetRequest.length; j < len1; j++) {
          r = objectFacetRequest[j];
          r.limit = r.limit + this.getFilter().length;
          request.aggregations[(r.field + ":") + path.join(".")] = r;
        }
      } else {
        objectFacetRequest.limit = objectFacetRequest.limit + this.getFilter().length;
        request.aggregations[((this.name()) + ":") + path.join(".")] = objectFacetRequest;
      }
    }
    return this;
  };

  Facet.prototype.requestFacet = function() {
    return CUI.util.assert(false, (CUI.util.getObjectClass(this)) + ".requestFacet", "Needs implementation");
  };

  Facet.prototype.renderObjectText = function(object, idx) {
    if (this.isHierarchy() || this.isPolyhierarchy()) {
      if (CUI.util.isNull(idx)) {
        idx = object._path.length - 1;
      }
      return object._path[idx].text;
    } else {
      return object.text;
    }
  };

  Facet.prototype.renderObjectTitle = function(obj) {
    var s;
    if (this.isHierarchy() || this.isPolyhierarchy()) {
      return ((function() {
        var i, len, ref, results;
        ref = obj._path;
        results = [];
        for (i = 0, len = ref.length; i < len; i++) {
          s = ref[i];
          results.push(s._id);
        }
        return results;
      })()).join(".");
    } else {
      return "" + obj._id;
    }
  };

  Facet.prototype.hasFilter = function() {
    return this.getFilter().length > 0;
  };

  Facet.prototype.clearFilter = function() {
    this.setFilter();
  };

  Facet.prototype.getFilter = function() {
    return this._filter;
  };

  Facet.prototype.setFilter = function(_filter, from_data) {
    this._filter = _filter != null ? _filter : [];
    if (from_data == null) {
      from_data = false;
    }
  };

  Facet.prototype.addFilter = function(obj) {
    return this._filter.push(obj);
  };

  Facet.prototype.isFiltered = function(obj) {
    var _obj, i, idx, len, ref;
    ref = this.getFilter();
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      _obj = ref[idx];
      if (this.isFilterOf(_obj, obj)) {
        return true;
      }
    }
    return false;
  };

  Facet.prototype.isFilterOf = function(obj1, obj2) {
    var path1, path2;
    path1 = this.getObjectPathString(obj1);
    path2 = this.getObjectPathString(obj2);
    return path2 === path1.substr(0, path2.length);
  };

  Facet.prototype.removeFilter = function(obj) {
    CUI.util.removeFromArray(null, this._filter, (function(_this) {
      return function(f) {
        return _this.isFilterOf(f, obj);
      };
    })(this));
  };

  Facet.prototype.closePopover = function() {
    if (this.popover) {
      this.popover.destroy();
      this.__popoverElement.enable();
      return this.popover = null;
    }
  };

  Facet.prototype.openPopover = function(__popoverElement, path) {
    var btn, buttons, do_search, facetPopoverHeaderLabel, order, pane, quicksearchInput, sort, toolbar;
    this.__popoverElement = __popoverElement;
    this.__inputSearchData = {
      filter: "",
      path: path,
      offset: 0,
      sort: "term"
    };
    if (ez5.version("6")) {
      this.__inputSearchData.order = "DESC";
    }
    do_search = (function(_this) {
      return function() {
        _this.__inputSearchData.offset = 0;
        return _this.__doPopoverSearch();
      };
    })(this);
    this.__popoverElement.disable();
    quicksearchInput = new CUI.Input({
      name: "filter",
      "class": "ez5-quicksearch-input",
      maximize_horizontal: true,
      data: this.__inputSearchData,
      onKeyup: (function(_this) {
        return function(df, ev) {
          if (ev.keyCode() === 13) {
            return do_search();
          }
        };
      })(this)
    }).start();
    sort = new CUI.Select({
      name: "sort",
      data: this.__inputSearchData,
      onDataChanged: (function(_this) {
        return function() {
          return do_search();
        };
      })(this),
      options: [
        {
          text: $$("facet.popover.sort_by.term"),
          value: "term"
        }, {
          text: $$("facet.popover.sort_by.count"),
          value: "count"
        }
      ]
    }).start();
    buttons = [sort];
    if (ez5.version("6")) {
      order = new CUI.Select({
        name: "order",
        data: this.__inputSearchData,
        onDataChanged: (function(_this) {
          return function() {
            return do_search();
          };
        })(this),
        options: [
          {
            text: $$("facet.popover.sort_order.asc"),
            value: "ASC"
          }, {
            text: $$("facet.popover.sort_order.desc"),
            value: "DESC"
          }
        ]
      }).start();
      buttons.push(order);
    }
    btn = new LocaButton({
      loca_key: "facet.more.button.search",
      primary: true,
      onClick: (function(_this) {
        return function() {
          return do_search();
        };
      })(this)
    });
    toolbar = new CUI.Toolbar({
      center: {
        content: [quicksearchInput, btn]
      },
      right: {
        content: new CUI.Buttonbar({
          buttons: buttons
        })
      }
    });
    facetPopoverHeaderLabel = this.blockHeader(false);
    CUI.dom.addClass(facetPopoverHeaderLabel, "cui-label");
    pane = new CUI.Pane({
      padded: true,
      maximize_horizontal: false,
      maximize_vertical: true,
      "class": "ez5-facet-popover-pane",
      top: {
        content: [
          new CUI.PaneHeader({
            left: {
              content: facetPopoverHeaderLabel
            }
          }), toolbar
        ]
      },
      bottom: {
        content: new CUI.PaneFooter({
          right: {
            content: this.__getNavigationButtons()
          }
        })
      }
    });
    this.popover = new CUI.Popover({
      "class": "ez5-facet-popover",
      element: this.__popoverElement,
      onHide: (function(_this) {
        return function() {
          return _this.__popoverElement.enable();
        };
      })(this),
      backdrop: {
        policy: "click"
      },
      placement: "e",
      pane: pane
    });
    this.popover.show();
    this.__resultContent = pane.center();
    return do_search();
  };

  Facet.prototype.popoverChunkSize = 20;

  Facet.prototype.__doPopoverSearch = function() {
    var _key, char, facet, facet_browse_request, i, key, len, lowerCase, ref, regexp, request, search_request, str, upperCase, waitBlock;
    search_request = new Request();
    if (this._facetManager.shouldUseFlatHierarchy()) {
      search_request.force_flat_hierarchy = true;
    }
    this.getSearch().addToRequest(search_request);
    request = {
      aggregations: {},
      search: []
    };
    key = this.getFacetKey(this.__inputSearchData.path);
    this.addToRequest(request);
    ref = request.aggregations;
    for (_key in ref) {
      facet = ref[_key];
      if (key !== _key) {
        delete request.aggregations[_key];
        continue;
      }
      if (!this.__isBucketFacet()) {
        facet.limit = this.popoverChunkSize;
        facet.offset = this.__inputSearchData.offset;
        facet.sort = this.__inputSearchData.sort;
        if (ez5.version("6")) {
          facet.order = this.__inputSearchData.order;
        }
      } else {
        delete facet.limit;
        delete facet.sort;
      }
    }
    if (this.getSearchType() === "OR") {
      CUI.util.removeFromArray(null, search_request.search, (function(_this) {
        return function(value) {
          return value.__filter === "Facet";
        };
      })(this));
    }
    facet_browse_request = {
      limit: 0,
      search: search_request.search,
      objecttypes: search_request.objecttypes,
      aggregations: request.aggregations
    };
    str = this.__inputSearchData.filter.trim();
    if (str.length > 0) {
      regexp = "";
      for (i = 0, len = str.length; i < len; i++) {
        char = str[i];
        if (char === "*") {
          regexp += ".*";
          continue;
        }
        char = CUI.util.escapeRegExp(char);
        upperCase = char.toUpperCase();
        lowerCase = char.toLowerCase();
        if (upperCase === lowerCase) {
          regexp += char;
        } else {
          regexp += "[" + upperCase + lowerCase + "]";
        }
      }
      facet_browse_request.aggregations[key].include = ".*" + regexp + ".*";
    }
    waitBlock = new CUI.WaitBlock({
      element: this.__resultContent
    }).show();
    return ez5.api.search({
      json_data: facet_browse_request
    }).always((function(_this) {
      return function() {
        return waitBlock.destroy();
      };
    })(this)).done((function(_this) {
      return function(data) {
        var checkboxes, content, foundObject, hasMore, items, j, len1, obj, objects, offset;
        offset = _this.__inputSearchData.offset || 0;
        objects = _this.getObjectsForPopover(key, data.aggregations, offset);
        hasMore = data.aggregations[key].has_more;
        if (_this.__inputSearchData.offset > 0) {
          _this.__previousButton.enable();
        } else {
          _this.__previousButton.disable();
        }
        if (hasMore) {
          _this.__nextButton.enable();
        } else {
          _this.__nextButton.disable();
        }
        items = [];
        if (objects.length > 0) {
          for (j = 0, len1 = objects.length; j < len1; j++) {
            obj = objects[j];
            if (_this.isFiltered(obj)) {
              foundObject = _this.getObjects(key).find(function(_obj) {
                return _this.getObjectPathString(obj) === _this.getObjectPathString(_obj);
              });
              obj.count = foundObject ? foundObject.count : 0;
            }
            items.push(_this.getItem(obj));
          }
          checkboxes = _this.getCheckboxesFromItems(items);
          content = new CUI.VerticalList({
            maximize_horizontal: true,
            maximize_vertical: false,
            content: checkboxes
          });
        } else {
          content = new CUI.Label({
            text: $$("facet.popover.no-objects-found", {
              search: str
            }),
            appearance: "secondary",
            multiline: true
          });
        }
        CUI.dom.empty(_this.__resultContent);
        CUI.dom.append(_this.__resultContent, content);
        return CUI.Events.trigger({
          type: "content-resize",
          node: _this.__resultContent
        });
      };
    })(this));
  };

  Facet.prototype.facetFilterFields = function() {
    console.error(this.__cls + ".facetFilterFields needs implemntation.");
    return [];
  };

  Facet.prototype.requestSearchFilter = function(obj) {
    return {
      bool: "must",
      fields: this.facetFilterFields(),
      type: "in",
      "in": [obj._id]
    };
  };

  Facet.prototype.isHierarchy = function() {
    return false;
  };

  Facet.prototype.isPolyhierarchy = function() {
    return false;
  };

  Facet.prototype.cleanHierarchyFilters = function(filters) {
    var parents;
    parents = new Set();
    filters.forEach((function(_this) {
      return function(obj) {
        var ref;
        return (ref = obj._path) != null ? ref.forEach(function(p) {
          if (p._id_parent !== null) {
            return parents.add(p._id_parent);
          }
        }) : void 0;
      };
    })(this));
    return filters.filter((function(_this) {
      return function(item) {
        return !parents.has(item._id);
      };
    })(this));
  };

  Facet.prototype.__getNavigationButtons = function() {
    this.__previousButton = new LocaButton({
      loca_key: "facet.more.button.prev",
      group: "navigation",
      disabled: true,
      onClick: (function(_this) {
        return function() {
          _this.__inputSearchData.offset = _this.__inputSearchData.offset - _this.popoverChunkSize;
          _this.__inputSearchData.offset = Math.max(0, _this.__inputSearchData.offset);
          return _this.__doPopoverSearch();
        };
      })(this)
    });
    this.__nextButton = new LocaButton({
      loca_key: "facet.more.button.next",
      group: "navigation",
      disabled: true,
      onClick: (function(_this) {
        return function() {
          _this.__inputSearchData.offset += _this.popoverChunkSize;
          return _this.__doPopoverSearch();
        };
      })(this)
    });
    return [this.__previousButton, this.__nextButton];
  };

  Facet.prototype.__isAndButtonAvailable = function() {
    return true;
  };

  Facet.prototype.__isOrButtonAvailable = function() {
    return true;
  };

  Facet.prototype.__isBucketFacet = function() {
    return false;
  };

  Facet.prototype.hasMultipleAggregations = function() {
    return false;
  };

  Facet.prototype.getNamesForMultipleAggregations = function() {
    return [];
  };

  return Facet;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var FieldFacet,
  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;

FieldFacet = (function(superClass) {
  extend(FieldFacet, superClass);

  function FieldFacet() {
    return FieldFacet.__super__.constructor.apply(this, arguments);
  }

  FieldFacet.prototype.initOpts = function() {
    FieldFacet.__super__.initOpts.call(this);
    return this.addOpts({
      field: {
        mandatory: true,
        check: Field
      }
    });
  };

  FieldFacet.prototype.name = function() {
    return this._field.fullName();
  };

  FieldFacet.prototype.nameLocalized = function() {
    return this._field.nameLocalized();
  };

  FieldFacet.prototype.fullNameLocalized = function() {
    return this._field.fullNameLocalized();
  };

  FieldFacet.prototype.getSecondaryHeader = function() {
    return new CUI.Label({
      "class": 'facet-manager-secondary-header',
      text: this.getSecondaryHeaderText()
    });
  };

  FieldFacet.prototype.getSecondaryHeaderText = function() {
    var objecttypeName;
    objecttypeName = this._field.getMainMask().table.nameLocalized();
    return '(' + $$('facet.manager.secondary_header', {
      objecttypeName: objecttypeName
    }) + ')';
  };

  FieldFacet.prototype.getGroupingText = function() {
    return this._field.getMainMask().table.nameLocalized();
  };

  FieldFacet.prototype.__isAndButtonAvailable = function() {
    if (this._field.insideNested()) {
      return true;
    }
    return false;
  };

  return FieldFacet;

})(Facet);
// Generated by CoffeeScript 1.12.7
var TermFacet,
  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;

TermFacet = (function(superClass) {
  extend(TermFacet, superClass);

  function TermFacet() {
    return TermFacet.__super__.constructor.apply(this, arguments);
  }

  TermFacet.prototype.getObjects = function(key, data) {
    var ref;
    if (key == null) {
      key = this.name();
    }
    if (data == null) {
      data = this.data();
    }
    return ((ref = data[key]) != null ? ref.terms : void 0) || [];
  };

  TermFacet.prototype.renderObjectText = function(object) {
    return object.term;
  };

  TermFacet.prototype.getObjectPath = function(obj) {
    return [obj.term];
  };

  return TermFacet;

})(Facet);
// Generated by CoffeeScript 1.12.7
var EASFacet,
  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;

EASFacet = (function(superClass) {
  extend(EASFacet, superClass);

  function EASFacet() {
    return EASFacet.__super__.constructor.apply(this, arguments);
  }

  EASFacet.prototype.isHierarchy = function() {
    return true;
  };

  EASFacet.prototype.name = function() {
    return "_eas";
  };

  EASFacet.prototype.nameLocalized = function() {
    return $$("eas.facet.name");
  };

  EASFacet.prototype.addToRequestHierarchy = function(request) {
    var i, idx, len, obj, ref;
    ref = this.getFilter();
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      obj = ref[idx];
      request.aggregations[(this.name()) + ":" + obj.term] = this.requestFacetWithLimit(obj);
    }
    return this;
  };

  EASFacet.prototype.getGroupingText = function() {
    return $$("facet.grouping.base_fields");
  };

  EASFacet.prototype.renderObjectText = function(obj) {
    var loca_key;
    if (obj._facet_key === "_eas") {
      loca_key = "server.eas.fileclass." + obj.term;
      if (ez5.loca.has(loca_key)) {
        return $$(loca_key);
      } else {
        return obj.term;
      }
    } else {
      return obj.term.substr(obj._facet_key.length - "_eas:".length + 1).toUpperCase();
    }
  };

  EASFacet.prototype.getObjectPath = function(obj) {
    if (obj._facet_key === "_eas") {
      return [obj.term];
    } else {
      return [obj._facet_key.substr("_eas".length + 1), obj.term];
    }
  };

  EASFacet.prototype.getObjects = function(key, data) {
    var i, len, obj, objs;
    if (key == null) {
      key = this.name();
    }
    if (data == null) {
      data = this.data();
    }
    objs = EASFacet.__super__.getObjects.call(this, key, data);
    for (i = 0, len = objs.length; i < len; i++) {
      obj = objs[i];
      obj._path = key.split(":").map(function(v) {
        return {
          _id: v
        };
      });
      obj._id = obj.term;
      obj._facet_key = key;
    }
    return objs;
  };

  EASFacet.prototype.getObjectsOnHierarchy = function(key, data) {
    var _key, hierarchy, i, items, len, term, terms, value;
    if (key == null) {
      key = this.name();
    }
    if (data == null) {
      data = this.data();
    }
    items = [];
    for (_key in data) {
      value = data[_key];
      if (_key.startsWith(key)) {
        hierarchy = _key.split(":").map(function(v) {
          return {
            _id: v
          };
        });
        terms = value.terms;
        if (terms) {
          for (i = 0, len = terms.length; i < len; i++) {
            term = terms[i];
            term._facet_key = _key;
            term._id = term.term;
            term._path = hierarchy;
            items.push(term);
          }
        }
      }
    }
    return items;
  };

  EASFacet.prototype.requestFacet = function(obj) {
    var facet, fieldPrefix, type;
    type = ez5.version("6") ? "term" : "asset";
    fieldPrefix = ez5.version("6") ? "_linked._asset." : "";
    if ((obj != null ? obj.term : void 0)) {
      facet = {
        type: type,
        field: fieldPrefix + "class_extension",
        include: obj.term + ".*"
      };
    } else {
      facet = {
        type: type,
        field: fieldPrefix + "class"
      };
    }
    return facet;
  };

  EASFacet.prototype.requestSearchFilter = function(obj) {
    var field_name, filter;
    field_name = obj._facet_key.startsWith("_eas:") ? "_linked._asset.class_extension" : "_linked._asset.class";
    filter = {
      bool: "must",
      fields: [field_name],
      type: "in",
      "in": [obj.term]
    };
    return filter;
  };

  EASFacet.prototype.renderObjectTitle = function(object) {
    return "empty";
  };

  EASFacet.prototype.cleanHierarchyFilters = function(objs) {
    var checkFacetKey, i, len, newObjs, obj;
    newObjs = [];
    for (i = 0, len = objs.length; i < len; i++) {
      obj = objs[i];
      checkFacetKey = obj._facet_key + ":" + obj.term;
      if (!objs.some(function(_obj) {
        return _obj._facet_key === checkFacetKey;
      })) {
        newObjs.push(obj);
      }
    }
    return newObjs;
  };

  EASFacet.prototype.__isAndButtonAvailable = function() {
    var easFields, i, len, objecttype, ref;
    ref = this.getSearch().getSearchObjecttypes();
    for (i = 0, len = ref.length; i < len; i++) {
      objecttype = ref[i];
      easFields = objecttype.getEASFields();
      if ((easFields != null ? easFields.length : void 0) > 1) {
        return true;
      }
    }
    return false;
  };

  EASFacet.prototype.needToLoadHierarchyInnerItems = function() {
    return true;
  };

  EASFacet.prototype._getObjectId = function(obj) {
    return obj._id;
  };

  return EASFacet;

})(TermFacet);
// Generated by CoffeeScript 1.12.7
var LinkedObjectFieldFacet,
  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;

LinkedObjectFieldFacet = (function(superClass) {
  extend(LinkedObjectFieldFacet, superClass);

  function LinkedObjectFieldFacet() {
    return LinkedObjectFieldFacet.__super__.constructor.apply(this, arguments);
  }

  LinkedObjectFieldFacet.prototype.name = function() {
    return this._field.fullName() + "/" + this._field.linkMask().table.name();
  };

  LinkedObjectFieldFacet.prototype.getGroupingText = function() {
    var f, j, len, ref, show;
    show = false;
    if (this.getSearch().getSearchObjecttypes().length > 0) {
      show = true;
    } else {
      ref = this.getFacets();
      for (j = 0, len = ref.length; j < len; j++) {
        f = ref[j];
        if (f instanceof LinkedObjecttypeFacet) {
          show = true;
          break;
        }
      }
    }
    if (show) {
      return this._field.getMainMask().table.nameLocalized();
    } else {
      return null;
    }
  };

  LinkedObjectFieldFacet.prototype.getHeaderText = function() {
    var checkNestedLocaName, fatherField, formattedText, fullNameLocalized, linkedObjectFields;
    fullNameLocalized = this._field.fullNameLocalized();
    if (this._field.insideNested()) {
      fatherField = this._field.getFatherField();
      linkedObjectFields = fatherField.getFields("all").filter(function(field) {
        return field instanceof LinkedObject;
      });
      if (linkedObjectFields.length === 1) {
        fullNameLocalized = fatherField.fullNameLocalized();
      }
    }
    checkNestedLocaName = function(fatherField, i) {
      var tableName;
      if (i == null) {
        i = 0;
      }
      if (!fatherField || i > 10) {
        return;
      }
      tableName = fatherField.table.name();
      if (fullNameLocalized.indexOf(tableName) >= 0) {
        if (fatherField.ColumnSchema) {
          fullNameLocalized = fullNameLocalized.replace(tableName, fatherField.ColumnSchema._name_localized);
        }
      }
      return checkNestedLocaName(fatherField.getFatherField());
    };
    checkNestedLocaName(this._field.getFatherField());
    formattedText = this._formatHeaderText(fullNameLocalized);
    return new CUI.Label({
      text: formattedText
    });
  };

  LinkedObjectFieldFacet.prototype._formatHeaderText = function(text) {
    var parts;
    if (text.indexOf(" / ") === -1) {
      return text;
    }
    parts = text.split(" / ");
    if (parts.length === 2) {
      return parts.join(": ");
    }
    if (parts.length > 2) {
      return parts[0] + ": " + parts[parts.length - 1];
    }
    return text;
  };

  LinkedObjectFieldFacet.prototype.requestFacet = function() {
    return {
      type: "linked_object",
      field: this._field.fullName()
    };
  };

  LinkedObjectFieldFacet.prototype.requestSearchFilter = function(obj) {
    var nestedField, request;
    request = {
      bool: "must",
      fields: this.facetFilterFields(),
      type: "in",
      "in": [obj._id]
    };
    if (!this._field.insideNested()) {
      return request;
    }
    nestedField = this._field.mask.nestedTableField;
    if (!nestedField.isNestedIndex()) {
      return request;
    }
    request = {
      type: "nested",
      path: nestedField.fullName(),
      search: [request]
    };
    return request;
  };

  LinkedObjectFieldFacet.prototype.facetFilterFields = function() {
    if (this.isHierarchy()) {
      return [this._field.fullName() + "._path." + this._field.linkMask().table.name() + "._id"];
    } else if (this.isPolyhierarchy()) {
      return [this._field.fullName() + "._paths." + this._field.linkMask().table.name() + "._id", this._field.fullName() + "." + this._field.linkMask().table.name() + "._id"];
    } else {
      return [this._field.fullName() + "." + this._field.linkMask().table.name() + "._id"];
    }
  };

  LinkedObjectFieldFacet.prototype.isHierarchy = function() {
    return this._field.linkMask().isHierarchy();
  };

  LinkedObjectFieldFacet.prototype.isPolyhierarchy = function() {
    return this._field.linkMask().isPolyhierarchy();
  };

  LinkedObjectFieldFacet.prototype.addToRequestHierarchy = function(request) {
    var idx, j, len, obj, path, ref, requestAggregation;
    LinkedObjectFieldFacet.__super__.addToRequestHierarchy.call(this, request);
    ref = this.getFilter();
    for (idx = j = 0, len = ref.length; j < len; idx = ++j) {
      obj = ref[idx];
      path = this.getObjectPath(obj);
      requestAggregation = request.aggregations[((this.name()) + ":") + path.join(".")];
      requestAggregation.filter_parent = path[path.length - 1];
    }
    return this;
  };

  return LinkedObjectFieldFacet;

})(FieldFacet);
// Generated by CoffeeScript 1.12.7
var LinkedObjecttypeFacet,
  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;

LinkedObjecttypeFacet = (function(superClass) {
  extend(LinkedObjecttypeFacet, superClass);

  function LinkedObjecttypeFacet() {
    return LinkedObjecttypeFacet.__super__.constructor.apply(this, arguments);
  }

  LinkedObjecttypeFacet.prototype.initOpts = function() {
    LinkedObjecttypeFacet.__super__.initOpts.call(this);
    return this.addOpts({
      objecttype: {
        mandatory: true,
        check: Objecttype
      }
    });
  };

  LinkedObjecttypeFacet.prototype.name = function() {
    return this._objecttype.table.name();
  };

  LinkedObjecttypeFacet.prototype.nameLocalized = function() {
    return this._objecttype.table.nameLocalized();
  };

  LinkedObjecttypeFacet.prototype.getGroupingText = function() {
    return $$("linked.objecttype.facet.grouping_text");
  };

  LinkedObjecttypeFacet.prototype.getHeaderText = function() {
    return new CUI.Label({
      text: this.nameLocalized()
    });
  };

  LinkedObjecttypeFacet.prototype.requestFacet = function() {
    return {
      type: "linked_object",
      objecttype: this.name()
    };
  };

  LinkedObjecttypeFacet.prototype.requestSearchFilter = function(obj) {
    return {
      bool: "must",
      type: "in",
      objecttype: this.name(),
      include_path: this.isHierarchy() || this.isPolyhierarchy(),
      "in": [obj._id]
    };
  };

  LinkedObjecttypeFacet.prototype.addToRequestHierarchy = function(request) {
    var i, idx, len, obj, path, ref, requestAggregation;
    LinkedObjecttypeFacet.__super__.addToRequestHierarchy.call(this, request);
    ref = this.getFilter();
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      obj = ref[idx];
      path = this.getObjectPath(obj);
      requestAggregation = request.aggregations[((this.name()) + ":") + path.join(".")];
      requestAggregation.filter_parent = path[path.length - 1];
    }
    return this;
  };

  LinkedObjecttypeFacet.prototype.isHierarchy = function() {
    return this._objecttype.isHierarchy();
  };

  LinkedObjecttypeFacet.prototype.isPolyhierarchy = function() {
    return this._objecttype.isPolyhierarchy();
  };

  LinkedObjecttypeFacet.prototype.__isAndButtonAvailable = function() {
    if (this.isHierarchy() || this.isPolyhierarchy()) {
      return true;
    }
    if (!CUI.util.isEmpty(this._objecttype._linked_object_fields_by_name) && Object.keys(this._objecttype._linked_object_fields_by_name).length <= 1) {
      return false;
    }
    return true;
  };

  return LinkedObjecttypeFacet;

})(Facet);
// Generated by CoffeeScript 1.12.7
var ObjecttypeFacet,
  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;

ObjecttypeFacet = (function(superClass) {
  extend(ObjecttypeFacet, superClass);

  function ObjecttypeFacet() {
    return ObjecttypeFacet.__super__.constructor.apply(this, arguments);
  }

  ObjecttypeFacet.prototype.requestFacet = function() {
    return {
      type: "term",
      field: "_objecttype"
    };
  };

  ObjecttypeFacet.prototype.facetFilterFields = function() {
    return ["_objecttype"];
  };

  ObjecttypeFacet.prototype.name = function() {
    return "_objecttype";
  };

  ObjecttypeFacet.prototype.getGroupingText = function() {
    return $$("facet.grouping.base_fields");
  };

  ObjecttypeFacet.prototype.renderObjectText = function(obj) {
    return new Objecttype(ez5.schema.CURRENT._objecttype_by_name[obj.term]).nameLocalized();
  };

  ObjecttypeFacet.prototype.requestSearchFilter = function(obj) {
    return {
      bool: "must",
      fields: this.facetFilterFields(),
      type: "in",
      "in": [obj.term]
    };
  };

  ObjecttypeFacet.prototype.getObjectsSorted = function(objects) {
    objects = ObjecttypeFacet.__super__.getObjectsSorted.call(this, objects);
    if (this.getSortSetting() === "term" && (objects != null ? objects.length : void 0) > 1) {
      objects.sort((function(_this) {
        return function(a, b) {
          var dataLang, ref;
          dataLang = ((ref = ez5.loca.getDatabaseLanguages()) != null ? ref[0] : void 0) || void 0;
          if (_this.getSortOrderSetting() === "ASC") {
            return _this.renderObjectText(a).localeCompare(_this.renderObjectText(b), dataLang);
          } else {
            return _this.renderObjectText(b).localeCompare(_this.renderObjectText(a), dataLang);
          }
        };
      })(this));
    }
    return objects;
  };

  ObjecttypeFacet.prototype.nameLocalized = function() {
    return $$("objecttype.facet.name");
  };

  ObjecttypeFacet.prototype.__isAndButtonAvailable = function() {
    return false;
  };

  return ObjecttypeFacet;

})(TermFacet);
// Generated by CoffeeScript 1.12.7
var PoolFacet,
  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;

PoolFacet = (function(superClass) {
  extend(PoolFacet, superClass);

  function PoolFacet() {
    this.requestSearchFilter = bind(this.requestSearchFilter, this);
    return PoolFacet.__super__.constructor.apply(this, arguments);
  }

  PoolFacet.prototype.name = function() {
    return "_pool";
  };

  PoolFacet.prototype.requestFacet = function(object) {
    var facetRequest, ref;
    facetRequest = {
      type: "linked_object",
      field: "_pool"
    };
    if (object && ((ref = object._path) != null ? ref.length : void 0) > 0) {
      facetRequest.filter_parent = object._path[object._path.length - 1]._id;
    }
    return facetRequest;
  };

  PoolFacet.prototype.getPathLengthOffset = function() {
    return 0;
  };

  PoolFacet.prototype.__getExtraItemsPathClass = function(object, offset) {
    if (offset == null) {
      offset = 2;
    }
    return PoolFacet.__super__.__getExtraItemsPathClass.call(this, object, offset);
  };

  PoolFacet.prototype.getGroupingText = function() {
    return $$("facet.grouping.base_fields");
  };

  PoolFacet.prototype.addToRequestHierarchy = function(request) {
    var fac_req;
    PoolFacet.__super__.addToRequestHierarchy.call(this, request);
    fac_req = request.aggregations[this.name()];
    return fac_req.filter_parent = this._facetManager.getRootPoolId();
  };

  PoolFacet.prototype.nameLocalized = function() {
    return $$("main.search.pool");
  };

  PoolFacet.prototype.requestSearchFilter = function(obj) {
    var ot;
    return {
      bool: "must",
      fields: (function() {
        var i, len, ref, results;
        ref = this._facetManager.getSearch().getSearchObjecttypes(true, true);
        results = [];
        for (i = 0, len = ref.length; i < len; i++) {
          ot = ref[i];
          results.push((ot.name()) + "._pool._path.pool._id");
        }
        return results;
      }).call(this),
      type: "in",
      "in": [obj._id]
    };
  };

  PoolFacet.prototype.isHierarchy = function() {
    return true;
  };

  PoolFacet.prototype.getObjectPath = function(obj) {
    var path;
    path = PoolFacet.__super__.getObjectPath.call(this, obj);
    path.shift();
    return path;
  };

  PoolFacet.prototype.getObjects = function(key, data) {
    var _, _pool, i, instance, j, len, len1, object, objects, ref, ref1;
    objects = PoolFacet.__super__.getObjects.call(this, key, data);
    if (!objects) {
      return;
    }
    objects = objects.filter(function(object) {
      return object._id !== 1;
    });
    for (i = 0, len = objects.length; i < len; i++) {
      object = objects[i];
      if (!object._path) {
        continue;
      }
      ref = object._path;
      for (j = 0, len1 = ref.length; j < len1; j++) {
        _pool = ref[j];
        if (!CUI.util.isString(_pool._id)) {
          continue;
        }
        ref1 = _pool._id.split("@"), _ = ref1[0], instance = ref1[1];
        if (!instance) {
          continue;
        }
        _pool.text += "@" + (ez5.connector.displaynameByInstance(instance));
      }
    }
    return objects;
  };

  PoolFacet.prototype.__isAndButtonAvailable = function() {
    return false;
  };

  return PoolFacet;

})(Facet);
// Generated by CoffeeScript 1.12.7
var DateFacet,
  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;

DateFacet = (function(superClass) {
  extend(DateFacet, superClass);

  function DateFacet() {
    return DateFacet.__super__.constructor.apply(this, arguments);
  }

  DateFacet.prototype.readOpts = function() {
    DateFacet.__super__.readOpts.call(this);
    this.__format_date = "YYYY-MM-DD";
    this.__ranges = {};
    this.__format_search = "date";
    if (!DateFacet.ranges) {
      DateFacet.ranges = this.__getRanges();
    }
    this.__closestDateRanges = this.__getClosestDateRanges();
    this.__ranges[this.name()] = DateFacet.ranges.concat(this.__closestDateRanges);
  };

  DateFacet.prototype.requestFacet = function(object) {
    var i, j, len, len1, map, offsetYears, range, ranges, rangesKey, ref, ref1;
    ranges = [];
    map = {
      days: true,
      months: true,
      years: true
    };
    if (object) {
      if (object.range.isUnknown) {
        return null;
      }
      rangesKey = (this.name()) + ":" + (this.getObjectPath(object).join('.'));
      if (object.range.isClosestDateRange) {
        if (!this.__ranges[rangesKey]) {
          this.__ranges[rangesKey] = this.__closestDateRanges;
        }
        ranges = [];
      } else {
        if (!object.range.toYear && object.range.month && !object.range.day) {
          this.__ranges[rangesKey] = this.__createDaysRanges(object.range.year, object.range.month);
          map.months = false;
          map.years = false;
        } else {
          map.days = false;
          offsetYears = Math.round((object.range.toYear - object.range.fromYear) / 10);
          if (!this.__ranges[rangesKey]) {
            if (object.range.toYear <= 0) {
              this.__ranges[rangesKey] = this.__createBCRanges(object.range.fromYear, object.range.toYear, offsetYears);
              map.months = false;
            } else {
              if (offsetYears === 0) {
                map.years = false;
                this.__ranges[rangesKey] = this.__createMonthsRanges(object.range.fromYear);
              } else {
                map.months = false;
                this.__ranges[rangesKey] = this.__createRanges(object.range.fromYear, object.range.toYear, offsetYears);
              }
            }
          }
        }
        if (this.__isAtMaxGranularity(object.range.fromYear, object.range.toYear)) {
          this.__ranges[rangesKey] = [];
        }
        ref = this.__ranges[rangesKey];
        for (i = 0, len = ref.length; i < len; i++) {
          range = ref[i];
          range.parent = object.range.name;
          ranges.push({
            from: range.from,
            to: range.to
          });
        }
      }
    } else {
      ref1 = this.__ranges[this.name()];
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        range = ref1[j];
        ranges.push({
          from: range.from,
          to: range.to
        });
      }
    }
    if (ranges.length === 0) {
      return null;
    }
    if (this.hasMultipleAggregations()) {
      return this.getNamesForMultipleAggregations(map).map((function(_this) {
        return function(name) {
          return {
            type: "date_range",
            field: name,
            format: _this.__format_search,
            ranges: ranges
          };
        };
      })(this));
    }
    return {
      type: "date_range",
      field: this.name(),
      format: this.__format_search,
      ranges: ranges
    };
  };

  DateFacet.prototype.getObjects = function(key, data) {
    var aggregationName, b, bucket, buckets, findRange, found, i, idx, j, k, len, len1, len2, name, names, object, objects, range, ref, ref1, ref2, ref3, unknownObject;
    if (key == null) {
      key = this.name();
    }
    if (data == null) {
      data = this.data();
    }
    buckets = ((ref = data[key]) != null ? ref.buckets : void 0) || [];
    if (this.hasMultipleAggregations()) {
      names = this.getNamesForMultipleAggregations();
      for (i = 0, len = names.length; i < len; i++) {
        name = names[i];
        if (key !== this.name()) {
          aggregationName = key.replace(this.name(), name);
        } else {
          aggregationName = name;
        }
        if (CUI.util.isEmpty(buckets)) {
          buckets = ((ref1 = data[aggregationName]) != null ? ref1.buckets : void 0) || [];
        }
        if (aggregationName !== key) {
          ref3 = ((ref2 = data[aggregationName]) != null ? ref2.buckets : void 0) || [];
          for (j = 0, len1 = ref3.length; j < len1; j++) {
            b = ref3[j];
            if (b.doc_count > 0) {
              found = buckets.find(function(bucket) {
                return bucket.key === b.key;
              });
              if (found && found.doc_count < b.doc_count) {
                found.doc_count = b.doc_count;
              }
            }
          }
        }
      }
    }
    if (buckets.length === 0) {
      return;
    }
    objects = [];
    findRange = (function(_this) {
      return function(keyToFind, ranges) {
        return CUI.util.findInArray(null, ranges, function(v) {
          return v.key === keyToFind;
        });
      };
    })(this);
    for (idx = k = 0, len2 = buckets.length; k < len2; idx = ++k) {
      bucket = buckets[idx];
      range = findRange(bucket.key, this.__ranges[key]);
      if (!range) {
        console.error("Bucket key not found. This should not happen - Skipping", bucket);
        continue;
      }
      if (bucket.doc_count === 0) {
        continue;
      }
      object = {
        range: range,
        bucket: bucket,
        count: bucket.doc_count
      };
      objects.push(object);
    }
    if (!ez5.version("6")) {
      objects.sort(function(a, b) {
        return CUI.util.compareIndex(a.range.idx, b.range.idx);
      });
    }
    if (this.hasMultipleAggregations() && key !== this.name()) {
      unknownObject = this.__buildUnknownObject(key, objects, data);
      if (unknownObject) {
        objects.push(unknownObject);
      }
    }
    return objects;
  };

  DateFacet.prototype.getObjectsForPopover = function(key, data, offset) {
    var objects;
    if (key == null) {
      key = this.name();
    }
    if (data == null) {
      data = this.data();
    }
    if (offset == null) {
      offset = 0;
    }
    objects = this.getObjectsSorted(null, this.__inputSearchData.sort, this.__inputSearchData.order);
    data[key].has_more = offset + this.popoverChunkSize < objects.length;
    return objects.slice(offset, offset + this.popoverChunkSize);
  };

  DateFacet.prototype.renderObjectText = function(object) {
    if (object.range.isUnknown) {
      return $$("date.facet.range.unknown");
    }
    if (object.range.displayName) {
      return object.range.displayName;
    } else {
      return $$("date.facet.range." + object.range.name);
    }
  };

  DateFacet.prototype.getObjectsSorted = function(objects, sort, order) {
    if (sort == null) {
      sort = null;
    }
    if (order == null) {
      order = null;
    }
    if (!sort) {
      sort = this.getSortSetting();
    }
    if (!order) {
      order = this.getSortOrderSetting();
    }
    objects = DateFacet.__super__.getObjectsSorted.call(this, objects);
    if (sort === "count" && (objects != null ? objects.length : void 0) > 1) {
      objects.sort((function(_this) {
        return function(a, b) {
          if (order === "ASC") {
            return a.count - b.count;
          } else {
            return b.count - a.count;
          }
        };
      })(this));
    }
    if (sort === "term" && order === "DESC" && (objects != null ? objects.length : void 0) > 1) {
      objects.reverse();
    }
    return objects;
  };

  DateFacet.prototype.requestSearchFilter = function(object) {
    var filters, map;
    if (this.hasMultipleAggregations()) {
      if (object.range.isUnknown) {
        return this.__requestUnknownSearchFilter(object);
      }
      map = this.__getFilterMap(object.range);
      filters = this.getNamesForMultipleAggregations(map).map((function(_this) {
        return function(name) {
          return {
            bool: "should",
            field: name,
            type: "range",
            from: object.bucket.from,
            to: object.bucket.to
          };
        };
      })(this));
      return {
        type: "complex",
        bool: "must",
        search: filters
      };
    } else {
      return {
        bool: "must",
        field: this.name(),
        type: "range",
        from: object.bucket.from,
        to: object.bucket.to
      };
    }
  };

  DateFacet.prototype.__requestUnknownSearchFilter = function(object) {
    var baseName, mustField, mustNotField, range;
    baseName = this.name();
    range = object.range;
    if (range.granularity === "month") {
      mustField = baseName + "_year";
      mustNotField = baseName + "_month";
    } else {
      mustField = baseName + "_month";
      mustNotField = "" + baseName;
    }
    return {
      type: "complex",
      bool: "must",
      search: [
        {
          bool: "must",
          field: mustField,
          type: "range",
          from: range.parentFrom,
          to: range.parentTo
        }, {
          bool: "must_not",
          field: mustNotField,
          type: "range",
          from: range.parentFrom,
          to: range.parentTo
        }
      ]
    };
  };

  DateFacet.prototype.__getFilterMap = function(range) {
    var map;
    map = {
      days: true,
      months: true,
      years: true
    };
    switch (range.granularity) {
      case "day":
        map.months = false;
        map.years = false;
        break;
      case "month":
        map.years = false;
    }
    return map;
  };

  DateFacet.prototype.__buildUnknownObject = function(key, childrenObjects, data) {
    var childrenGranularity, childrenTotal, existing, f, i, j, k, len, len1, len2, obj, parentCurrentCount, parentFilter, parentPath, ref, ref1, ref2, unknownCount, unknownIsFiltered, unknownRange, unknownRangeName;
    childrenGranularity = (ref = this.__ranges[key]) != null ? (ref1 = ref[0]) != null ? ref1.granularity : void 0 : void 0;
    if (childrenGranularity !== "month" && childrenGranularity !== "day") {
      return null;
    }
    parentPath = key.replace(this.name() + ":", "");
    parentFilter = null;
    ref2 = this.getFilter();
    for (i = 0, len = ref2.length; i < len; i++) {
      f = ref2[i];
      if (this.getObjectPath(f).join(".") === parentPath) {
        parentFilter = f;
        break;
      }
    }
    if (!parentFilter) {
      return null;
    }
    unknownRangeName = "unknown_" + parentFilter.range.name;
    unknownIsFiltered = this.getFilter().some((function(_this) {
      return function(f) {
        var ref3;
        return ((ref3 = f.range) != null ? ref3.name : void 0) === unknownRangeName;
      };
    })(this));
    if (!unknownIsFiltered) {
      for (j = 0, len1 = childrenObjects.length; j < len1; j++) {
        obj = childrenObjects[j];
        if (this.isFiltered(obj)) {
          return null;
        }
      }
    }
    parentCurrentCount = this.__getParentCurrentCount(parentFilter, data);
    childrenTotal = 0;
    for (k = 0, len2 = childrenObjects.length; k < len2; k++) {
      obj = childrenObjects[k];
      childrenTotal += obj.count;
    }
    unknownCount = parentCurrentCount - childrenTotal;
    if (unknownCount <= 0 && !unknownIsFiltered) {
      return null;
    }
    unknownRange = {
      name: "unknown_" + parentFilter.range.name,
      isUnknown: true,
      granularity: childrenGranularity,
      parentFrom: parentFilter.bucket.from,
      parentTo: parentFilter.bucket.to,
      parent: parentFilter.range.name,
      idx: -1
    };
    existing = this.__ranges[key].find(function(r) {
      return r.isUnknown;
    });
    if (!existing) {
      this.__ranges[key].push(unknownRange);
    }
    return {
      range: unknownRange,
      bucket: {
        from: parentFilter.bucket.from,
        to: parentFilter.bucket.to
      },
      count: unknownCount
    };
  };

  DateFacet.prototype.__getParentCurrentCount = function(parentFilter, data) {
    var aggKey, bucket, i, j, len, len1, name, names, parentAggKey, parentBucketKey, parentCount, parentParentPath, parentPath, ref, ref1;
    parentBucketKey = parentFilter.range.key;
    parentCount = 0;
    parentPath = this.getObjectPath(parentFilter);
    parentParentPath = parentPath.slice(0, parentPath.length - 1);
    if (parentParentPath.length > 0) {
      parentAggKey = this.name() + ":" + parentParentPath.join(".");
    } else {
      parentAggKey = this.name();
    }
    names = this.getNamesForMultipleAggregations();
    for (i = 0, len = names.length; i < len; i++) {
      name = names[i];
      aggKey = parentAggKey.replace(this.name(), name);
      ref1 = ((ref = data[aggKey]) != null ? ref.buckets : void 0) || [];
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        bucket = ref1[j];
        if (bucket.key === parentBucketKey && bucket.doc_count > parentCount) {
          parentCount = bucket.doc_count;
        }
      }
    }
    if (parentCount === 0) {
      parentCount = parentFilter.count;
    }
    return parentCount;
  };

  DateFacet.prototype.getObjectPath = function(object) {
    var i, key, len, parentPath, path, range, ranges, ref;
    path = [object.range.name];
    if (object.range.isUnknown && object.range.parent) {
      return this.__getUnknownObjectPath(object);
    }
    ref = this.__ranges;
    for (key in ref) {
      ranges = ref[key];
      for (i = 0, len = ranges.length; i < len; i++) {
        range = ranges[i];
        if (range.name === object.range.name) {
          parentPath = key.replace(this.name(), "").split(":")[1];
          if (parentPath) {
            path = parentPath.split(".").concat(path);
          }
          return path;
        }
      }
    }
    return path;
  };

  DateFacet.prototype.__getUnknownObjectPath = function(object) {
    var ancestorPath, i, key, len, parentName, parentPath, range, ranges, ref;
    parentName = object.range.parent;
    parentPath = [parentName];
    ref = this.__ranges;
    for (key in ref) {
      ranges = ref[key];
      for (i = 0, len = ranges.length; i < len; i++) {
        range = ranges[i];
        if (range.name === parentName) {
          ancestorPath = key.replace(this.name(), "").split(":")[1];
          if (ancestorPath) {
            parentPath = ancestorPath.split(".").concat(parentPath);
          }
          break;
        }
      }
    }
    return parentPath.concat([object.range.name]);
  };

  DateFacet.prototype.isHierarchy = function() {
    return true;
  };

  DateFacet.prototype.__getRanges = function() {
    var actualDecade, bcMainRange, currentMillennium, currentYearDecade, currentYearMinusTwo, firstMillenniumRange, futureYearsRanges, lastCentury, lastCenturyRanges, lastMillennium, lastMillenniumRanges, lastYearsRanges, mom, nextYearDecade, year;
    mom = CUI.util.moment();
    year = mom.year();
    nextYearDecade = Math.floor((year + 10) / 10) * 10;
    futureYearsRanges = this.__createRanges(nextYearDecade, 2100, 10, 1);
    actualDecade = this.__createRanges(year + 2, nextYearDecade - 1, 1, 2);
    currentYearDecade = Math.floor(year / 10) * 10;
    currentYearMinusTwo = year - 2;
    if (currentYearDecade <= currentYearMinusTwo) {
      lastYearsRanges = this.__createRanges(currentYearDecade, currentYearMinusTwo, 1, 6);
    }
    currentMillennium = Math.floor(year / 1000) * 1000;
    lastCentury = currentMillennium - 100;
    lastCenturyRanges = this.__createRanges(lastCentury, currentYearDecade - 1, 10, 7);
    lastMillennium = currentMillennium - 1000;
    lastMillenniumRanges = this.__createRanges(lastMillennium, lastCentury - 1, 100, 8);
    firstMillenniumRange = this.__createRanges(0, lastMillennium - 1, 1000, 9);
    bcMainRange = this.__createRanges(-10000000, 0, 10000000, 10);
    bcMainRange[0].displayName = CUI.DateTime.defaults.bc_appendix_output;
    return futureYearsRanges.concat(actualDecade || []).concat(lastYearsRanges).concat(lastCenturyRanges).concat(lastMillenniumRanges).concat(firstMillenniumRange).concat(bcMainRange);
  };

  DateFacet.DIGIT_REGEXP = /\d+/g;

  DateFacet.prototype.__createRanges = function(from, to, number, rangeIndex) {
    var _to, displayName, fromString, fromYear, fromYearString, index, padWithZero, ranges, toString, toYear, toYearString, yearOffset;
    if (rangeIndex == null) {
      rangeIndex = 1;
    }
    if ((-1 < number && number < 1) || from > to) {
      return [];
    }
    if (!ez5.version("6") && to < -1000000) {
      return [];
    }
    rangeIndex = rangeIndex * 1000;
    number = Math.ceil(number);
    yearOffset = number === 1 ? 0 : number;
    if (yearOffset) {
      _to = to - 1;
    } else {
      _to = to;
    }
    ranges = [];
    index = from;
    while (index <= _to) {
      fromYear = index;
      toYear = index + yearOffset;
      if (toYear > to) {
        toYear = to;
      }
      if (yearOffset && toYear !== to) {
        toYear--;
      }
      padWithZero = function(m) {
        return "000".substr(m.length - 1) + m;
      };
      fromYearString = ("" + fromYear).replace(DateFacet.DIGIT_REGEXP, padWithZero);
      toYearString = ("" + toYear).replace(DateFacet.DIGIT_REGEXP, padWithZero);
      if (ez5.version("6") && fromYear < -1000) {
        fromString = "" + fromYearString;
        toString = "" + toYearString;
      } else {
        fromString = fromYearString + "-01-01";
        toString = toYearString + "-12-31";
      }
      displayName = this.__getDisplayName(fromYear, toYear, yearOffset);
      ranges.push({
        name: "range_" + fromYear + "-" + toYear,
        displayName: displayName,
        key: fromString + "-" + toString,
        from: fromString,
        to: toString,
        fromYear: fromYear,
        toYear: toYear,
        granularity: "year",
        idx: rangeIndex
      });
      rangeIndex--;
      index = index + number;
    }
    return ranges;
  };

  DateFacet.prototype.__createMonthsRanges = function(year) {
    var dayStr, daysInMonth, displayName, fromDate, i, idx, moment, month, monthNames, monthStr, padWithZero, padYear, paddedYear, ranges, toDate;
    moment = CUI.util.moment;
    moment.locale(CUI.DateTime.getLocale());
    monthNames = monthNames = moment.months();
    padWithZero = function(n) {
      var nStr;
      nStr = n.toString();
      return (nStr.length < 2 ? "0" + nStr : nStr);
    };
    padYear = function(y) {
      return ("0000" + y).slice(-4);
    };
    paddedYear = padYear(year);
    ranges = [];
    idx = 12 * 1000;
    for (month = i = 1; i <= 12; month = ++i) {
      monthStr = padWithZero(month);
      fromDate = paddedYear + "-" + monthStr + "-01";
      daysInMonth = 31;
      if (month === 2) {
        if (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {
          daysInMonth = 29;
        } else {
          daysInMonth = 28;
        }
      } else if (month === 4 || month === 6 || month === 9 || month === 11) {
        daysInMonth = 30;
      }
      dayStr = padWithZero(daysInMonth);
      toDate = paddedYear + "-" + monthStr + "-" + dayStr;
      displayName = "" + monthNames[month - 1];
      ranges.push({
        name: "month_" + paddedYear + "_" + monthStr,
        displayName: displayName,
        key: fromDate + "-" + toDate,
        from: fromDate,
        to: toDate,
        year: year,
        month: month,
        granularity: "month",
        idx: idx
      });
      idx--;
    }
    return ranges;
  };

  DateFacet.prototype.__createDaysRanges = function(year, month) {
    var dateStr, day, dayStr, daysInMonth, displayName, i, idx, moment, padWithZero, padYear, paddedMonth, paddedYear, ranges, ref;
    moment = CUI.util.moment;
    moment.locale(CUI.DateTime.getLocale());
    padWithZero = function(n) {
      var nStr;
      nStr = n.toString();
      if (nStr.length < 2) {
        return "0" + nStr;
      } else {
        return nStr;
      }
    };
    padYear = function(y) {
      return ("0000" + y).slice(-4);
    };
    paddedYear = padYear(year);
    paddedMonth = padWithZero(month);
    daysInMonth = moment(paddedYear + "-" + paddedMonth + "-01", "YYYY-MM-DD").daysInMonth();
    ranges = [];
    idx = daysInMonth * 1000;
    for (day = i = 1, ref = daysInMonth; 1 <= ref ? i <= ref : i >= ref; day = 1 <= ref ? ++i : --i) {
      dayStr = padWithZero(day);
      dateStr = paddedYear + "-" + paddedMonth + "-" + dayStr;
      displayName = dayStr;
      ranges.push({
        name: "day_" + paddedYear + "_" + paddedMonth + "_" + dayStr,
        displayName: displayName,
        key: dateStr + "-" + dateStr,
        from: dateStr,
        to: dateStr,
        year: year,
        month: month,
        day: day,
        granularity: "day",
        idx: idx
      });
      idx--;
    }
    return ranges;
  };

  DateFacet.prototype.__getDisplayName = function(fromYear, toYear, offset) {
    var century, displayName, fromYearAbs, getPositionLabel, isBC, millennium, position, toYearAbs, yearArg;
    if (!offset) {
      return CUI.DateTime.format("" + fromYear);
    }
    isBC = fromYear < 0 && toYear <= 0;
    if (ez5.version("6") && isBC && fromYear < -1000) {
      fromYearAbs = Math.abs(fromYear) + 1;
      toYearAbs = Math.abs(toYear) + 1;
      return fromYearAbs + " - " + toYearAbs + " " + CUI.DateTime.defaults.bc_appendix_output;
    }
    if (isBC) {
      fromYear = Math.abs(fromYear) + 1;
      toYear = Math.abs(toYear) + 1;
    }
    getPositionLabel = (function(_this) {
      return function(position) {
        if (position === 1 || position === 2 || position === 3) {
          return $$("date.facet.range.year.position." + position + ".label");
        } else {
          return $$("date.facet.range.year.position.n.label", {
            position: position
          });
        }
      };
    })(this);
    switch (offset) {
      case 1000:
        millennium = Math.ceil(toYear / 1000);
        yearArg = Math.ceil(fromYear / 1000) * 1000;
        displayName = $$("date.facet.range.millennium.label", {
          number: getPositionLabel(millennium),
          year: yearArg
        });
        break;
      case 100:
        century = Math.ceil(toYear / 100);
        yearArg = Math.ceil(fromYear / 100) * 100;
        displayName = $$("date.facet.range.century.label", {
          number: getPositionLabel(century),
          year: yearArg
        });
        break;
      case 10:
        position = isBC ? toYear - 1 : fromYear;
        if (position === 0) {
          displayName = $$("date.facet.range.decade.zero.label");
        } else {
          displayName = $$("date.facet.range.decade.label", {
            number: position,
            year: fromYear
          });
        }
        break;
      default:
        displayName = fromYear + " - " + toYear;
    }
    if (isBC) {
      return displayName + (" " + CUI.DateTime.defaults.bc_appendix_output);
    }
    return displayName;
  };

  DateFacet.prototype.__createBCRanges = function(from, to, offsetYears) {
    var moreRanges, offset, ranges, startYear;
    if (ez5.version("6")) {
      return this.__createBCRangesFylr(from, to);
    }
    if (offsetYears <= 100000) {
      return this.__createRanges(from, to, offsetYears);
    }
    if (to === 0) {
      offset = 1000;
      startYear = -9999;
    } else if (to === -10000) {
      offset = 10000;
      startYear = -99999;
    } else if (to === -100000) {
      offset = 100000;
      startYear = -999999;
    } else if (to === -1000000) {
      offset = 1000000;
      startYear = -9999999;
    } else {
      return this.__createRanges(from, to, offsetYears);
    }
    ranges = this.__createRanges(startYear, to, offset, 1);
    moreRanges = this.__createRanges(from, startYear - 1, Math.abs(from - (startYear - 1)), 2);
    if (!moreRanges[0]) {
      return ranges;
    }
    moreRanges[0].displayName = $$("date.facet.range.more.bc", {
      year: CUI.DateTime.format("" + startYear)
    });
    return ranges.concat(moreRanges);
  };

  DateFacet.prototype.__createBCRangesFylr = function(from, to) {
    var nextGranularity, rangeSpan;
    rangeSpan = to - from;
    nextGranularity = Math.floor(rangeSpan / 10);
    if (nextGranularity < 1000) {
      nextGranularity = 1000;
    }
    return this.__createRanges(from, to, nextGranularity);
  };

  DateFacet.prototype.__getMinGranularityForYear = function(year) {
    var absYear;
    absYear = Math.abs(year);
    if (absYear < 10000) {
      return 1000;
    }
    if (absYear < 100000) {
      return 10000;
    }
    if (absYear < 1000000) {
      return 100000;
    }
    if (absYear < 10000000) {
      return 1000000;
    }
    if (absYear < 100000000) {
      return 10000000;
    }
    return 100000000;
  };

  DateFacet.prototype.__isAtMaxGranularity = function(fromYear, toYear) {
    var minGranularity, rangeSpan;
    if (!ez5.version("6")) {
      return false;
    }
    if (fromYear >= -1000) {
      return false;
    }
    rangeSpan = toYear - fromYear;
    minGranularity = this.__getMinGranularityForYear(fromYear);
    return rangeSpan < minGranularity;
  };

  DateFacet.prototype.__getClosestDateRanges = function() {
    var closestDateRanges, from, i, idx, lastYear, len, m, mom, nextYear, range, ranges, thisYear, to, year;
    ranges = [
      {
        name: "next_month",
        granularity: "month",
        from: (function(_this) {
          return function(m) {
            return m.add(1, "month").startOf("month");
          };
        })(this),
        to: (function(_this) {
          return function(m) {
            return m.add(1, "month").endOf("month");
          };
        })(this)
      }, {
        name: "week_after_next",
        granularity: "day",
        from: (function(_this) {
          return function(m) {
            return m.add(2, "week").startOf("week");
          };
        })(this),
        to: (function(_this) {
          return function(m) {
            return m.add(2, "week").endOf("week");
          };
        })(this)
      }, {
        name: "next_week",
        granularity: "day",
        from: (function(_this) {
          return function(m) {
            return m.add(1, "week").startOf("week");
          };
        })(this),
        to: (function(_this) {
          return function(m) {
            return m.add(1, "week").endOf("week");
          };
        })(this)
      }, {
        name: "tomorrow",
        granularity: "day",
        from: (function(_this) {
          return function(m) {
            return m.add(1, "day").startOf("day");
          };
        })(this),
        to: (function(_this) {
          return function(m) {
            return m.add(1, "day").endOf("day");
          };
        })(this)
      }, {
        name: "today",
        granularity: "day",
        from: (function(_this) {
          return function(m) {
            return m.startOf("day");
          };
        })(this),
        to: (function(_this) {
          return function(m) {
            return m.endOf("day");
          };
        })(this)
      }, {
        name: "yesterday",
        granularity: "day",
        from: (function(_this) {
          return function(m) {
            return m.subtract(1, "day").startOf("day");
          };
        })(this),
        to: (function(_this) {
          return function(m) {
            return m.subtract(1, "day").endOf("day");
          };
        })(this)
      }, {
        name: "this_week",
        granularity: "day",
        from: (function(_this) {
          return function(m) {
            return m.startOf("week");
          };
        })(this),
        to: (function(_this) {
          return function(m) {
            return m.endOf("week");
          };
        })(this)
      }, {
        name: "last_week",
        granularity: "day",
        from: (function(_this) {
          return function(m) {
            return m.subtract(1, "week").startOf("week");
          };
        })(this),
        to: (function(_this) {
          return function(m) {
            return m.subtract(1, "week").endOf("week");
          };
        })(this)
      }, {
        name: "this_month",
        granularity: "month",
        from: (function(_this) {
          return function(m) {
            return m.startOf("month");
          };
        })(this),
        to: (function(_this) {
          return function(m) {
            return m.endOf("month");
          };
        })(this)
      }, {
        name: "last_month",
        granularity: "month",
        from: (function(_this) {
          return function(m) {
            return m.subtract(1, "month").startOf("month");
          };
        })(this),
        to: (function(_this) {
          return function(m) {
            return m.subtract(1, "month").endOf("month");
          };
        })(this)
      }
    ];
    mom = CUI.util.moment();
    closestDateRanges = [];
    for (idx = i = 0, len = ranges.length; i < len; idx = ++i) {
      range = ranges[idx];
      m = mom.clone();
      from = range.from(m).format(this.__format_date);
      m = mom.clone();
      to = range.to(m).format(this.__format_date);
      closestDateRanges.push({
        idx: idx,
        name: range.name,
        key: from + "-" + to,
        from: from,
        to: to,
        granularity: range.granularity,
        isClosestDateRange: true
      });
    }
    year = mom.year();
    nextYear = this.__createRanges(year + 1, year + 1, 1, 3);
    delete nextYear[0].displayName;
    nextYear[0].name = "next_year";
    thisYear = this.__createRanges(year, year, 1, 4);
    delete thisYear[0].displayName;
    thisYear[0].name = "this_year";
    lastYear = this.__createRanges(year - 1, year - 1, 1, 5);
    delete lastYear[0].displayName;
    lastYear[0].name = "last_year";
    return nextYear.concat(thisYear).concat(lastYear).concat(closestDateRanges);
  };

  DateFacet.prototype.name = function() {
    return this._field.getSearchField();
  };

  DateFacet.prototype.__isAndButtonAvailable = function() {
    if (this._field.insideNested()) {
      return true;
    }
    return false;
  };

  DateFacet.prototype.needToLoadHierarchyInnerItems = function() {
    return true;
  };

  DateFacet.prototype._getObjectId = function(obj) {
    return obj.range.name;
  };

  DateFacet.prototype.__isBucketFacet = function() {
    return true;
  };

  DateFacet.prototype.cleanHierarchyFilters = function(filters) {
    var cleanedFilters, filter, i, len, name;
    cleanedFilters = [];
    for (i = 0, len = filters.length; i < len; i++) {
      filter = filters[i];
      name = filter.range.name;
      if (!filters.some(function(_filter) {
        return _filter.range.parent === name;
      })) {
        cleanedFilters.push(filter);
      }
    }
    return cleanedFilters;
  };

  DateFacet.prototype.hasMultipleAggregations = function() {
    return ez5.version("6");
  };

  DateFacet.prototype.getNamesForMultipleAggregations = function(map) {
    var baseName, names;
    if (!map) {
      map = {
        days: true,
        months: true,
        years: true
      };
    }
    baseName = this.name();
    names = [];
    if (map.days) {
      names.push("" + baseName);
    }
    if (map.months) {
      names.push(baseName + "_month");
    }
    if (map.years) {
      names.push(baseName + "_year");
    }
    return names;
  };

  return DateFacet;

})(FieldFacet);
// Generated by CoffeeScript 1.12.7
var DateRangeFacet,
  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;

DateRangeFacet = (function(superClass) {
  extend(DateRangeFacet, superClass);

  function DateRangeFacet() {
    return DateRangeFacet.__super__.constructor.apply(this, arguments);
  }

  DateRangeFacet.prototype.hasMultipleAggregations = function() {
    return ez5.version("6");
  };

  DateRangeFacet.prototype.getNamesForMultipleAggregations = function(map) {
    return DateRangeFacet.__super__.getNamesForMultipleAggregations.call(this, map);
  };

  return DateRangeFacet;

})(DateFacet);
// 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.BooleanFacet = (function(superClass) {
  extend(BooleanFacet, superClass);

  function BooleanFacet() {
    return BooleanFacet.__super__.constructor.apply(this, arguments);
  }

  BooleanFacet.prototype.isHierarchy = function() {
    return false;
  };

  BooleanFacet.prototype.getObjects = function(key, data) {
    var i, len, objects, ref, term, terms, value;
    if (key == null) {
      key = this.name();
    }
    if (data == null) {
      data = this.data();
    }
    terms = ((ref = data[key]) != null ? ref.terms : void 0) || [];
    objects = {};
    for (i = 0, len = terms.length; i < len; i++) {
      term = terms[i];
      value = term.term;
      if (!objects[value]) {
        objects[value] = {
          value: value === 1,
          count: 0
        };
      }
      objects[value].count += term.count;
    }
    return Object.values(objects);
  };

  BooleanFacet.prototype.renderObjectText = function(object) {
    return $$("boolean.facet." + object.value);
  };

  BooleanFacet.prototype.requestSearchFilter = function(object) {
    return {
      bool: "must",
      fields: [this.name()],
      type: "in",
      "in": [object.value]
    };
  };

  BooleanFacet.prototype.requestFacet = function() {
    return {
      type: "term",
      field: this.name()
    };
  };

  BooleanFacet.prototype.isFilterOf = function(objectOne, objectTwo) {
    return objectOne.value === objectTwo.value;
  };

  BooleanFacet.prototype.__isAndButtonAvailable = function() {
    return false;
  };

  return BooleanFacet;

})(FieldFacet);
// Generated by CoffeeScript 1.12.7
var TagsFacet,
  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;

TagsFacet = (function(superClass) {
  extend(TagsFacet, superClass);

  TagsFacet.prototype.initOpts = function() {
    TagsFacet.__super__.initOpts.call(this);
    return this.addOpts({
      tagGroup: {
        check: TagGroupSimple
      }
    });
  };

  function TagsFacet(opts) {
    this.opts = opts != null ? opts : {};
    this.requestSearchFilter = bind(this.requestSearchFilter, this);
    TagsFacet.__super__.constructor.call(this, this.opts);
    this.__tags = this._tagGroup.getTagsWithDisplayType(["facet"]);
  }

  TagsFacet.prototype.getLimit = function() {
    return 10000;
  };

  TagsFacet.prototype.name = function() {
    return "_tags";
  };

  TagsFacet.prototype.getFacetKey = function() {
    return "_tags_" + (this._tagGroup.getId());
  };

  TagsFacet.prototype.getObjects = function(_, data) {
    var i, key, len, objects, ref, tag, term, terms;
    if (data == null) {
      data = this.data();
    }
    key = this.name();
    terms = (ref = data[key]) != null ? ref.terms : void 0;
    if (CUI.util.isEmpty(terms)) {
      return;
    }
    objects = [];
    for (i = 0, len = terms.length; i < len; i++) {
      term = terms[i];
      if (term.count === 0) {
        continue;
      }
      tag = this.__getTagById(term.term);
      if (!tag) {
        continue;
      }
      objects.push({
        tag: tag,
        count: term.count
      });
    }
    return objects;
  };

  TagsFacet.prototype.getObjectsSorted = function(objects) {
    objects = TagsFacet.__super__.getObjectsSorted.call(this, objects);
    if (this.getSortSetting() === "term" && (objects != null ? objects.length : void 0) > 1) {
      objects.sort((function(_this) {
        return function(a, b) {
          var ref, ref1;
          if (_this.getSortOrderSetting() === "ASC") {
            return (ref = a.tag.getDisplayName()) != null ? ref.localeCompare(b.tag.getDisplayName()) : void 0;
          } else {
            return (ref1 = b.tag.getDisplayName()) != null ? ref1.localeCompare(a.tag.getDisplayName()) : void 0;
          }
        };
      })(this));
    }
    return objects;
  };

  TagsFacet.prototype.renderObject = function(object) {
    return [object.tag.getLabel(true, true)];
  };

  TagsFacet.prototype.requestFacet = function() {
    return {
      type: "term",
      field: "_tags._id"
    };
  };

  TagsFacet.prototype.requestSearchFilter = function(object) {
    return {
      bool: "must",
      fields: ["_tags._id"],
      type: "in",
      "in": [object.tag.getId()]
    };
  };

  TagsFacet.prototype.nameLocalized = function() {
    return this._tagGroup.getDisplayName();
  };

  TagsFacet.prototype.getGroupingText = function() {
    return $$("facet.grouping.base_fields");
  };

  TagsFacet.prototype.addFilter = function(obj) {
    obj.tag = obj.tag.getTagForFilter();
    return TagsFacet.__super__.addFilter.call(this, obj);
  };

  TagsFacet.prototype.getCheckboxesFromItems = function(items) {
    var i, item, len;
    if (this._tagGroup.isChoice()) {
      for (i = 0, len = items.length; i < len; i++) {
        item = items[i];
        if (CUI.util.isPlainObject(item)) {
          item.radio = "radio";
        }
      }
    }
    return TagsFacet.__super__.getCheckboxesFromItems.call(this, items);
  };

  TagsFacet.prototype.isFilterOf = function(objectOne, objectTwo) {
    return objectOne.tag.getId() === objectTwo.tag.getId();
  };

  TagsFacet.prototype.__getTagById = function(id) {
    return this.__tags.filter((function(_this) {
      return function(tag) {
        return tag.getId() === id;
      };
    })(this))[0];
  };

  TagsFacet.prototype.__isAndButtonAvailable = function() {
    return this._tagGroup.getType() !== "choice";
  };

  TagsFacet.prototype._getObjectId = function(obj) {
    return obj.tag.getId();
  };

  TagsFacet.prototype.setFilter = function(_filter, from_data) {
    var filter, i, len, ref, ref1, ref2, ref3, results, tag;
    this._filter = _filter != null ? _filter : [];
    if (from_data == null) {
      from_data = false;
    }
    if (from_data && this._filter.length > 0) {
      ref = this._filter;
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        filter = ref[i];
        tag = this.__getTagById((ref1 = filter.tag) != null ? (ref2 = ref1.data) != null ? (ref3 = ref2.tag) != null ? ref3._id : void 0 : void 0 : void 0);
        if (tag) {
          results.push(filter.tag = tag);
        } else {
          results.push(this._filter = []);
        }
      }
      return results;
    }
  };

  return TagsFacet;

})(Facet);
// Generated by CoffeeScript 1.12.7
var SystemTagsFacet,
  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;

SystemTagsFacet = (function(superClass) {
  extend(SystemTagsFacet, superClass);

  function SystemTagsFacet() {
    this.requestSearchFilter = bind(this.requestSearchFilter, this);
    return SystemTagsFacet.__super__.constructor.apply(this, arguments);
  }

  SystemTagsFacet.prototype.getLimit = function() {
    return 10000;
  };

  SystemTagsFacet.prototype.name = function() {
    return "_system_tags";
  };

  SystemTagsFacet.prototype.getFacetKey = function() {
    return "_system_tags";
  };

  SystemTagsFacet.prototype.getGroupingText = function() {
    return $$("facet.grouping.base_fields");
  };

  SystemTagsFacet.prototype.nameLocalized = function() {
    return $$("system.tags.facet.title");
  };

  SystemTagsFacet.prototype.getObjects = function(_, data) {
    var i, key, len, objects, ref, term, terms;
    if (data == null) {
      data = this.data();
    }
    key = this.name();
    terms = (ref = data[key]) != null ? ref.terms : void 0;
    if (CUI.util.isEmpty(terms)) {
      return;
    }
    objects = [];
    for (i = 0, len = terms.length; i < len; i++) {
      term = terms[i];
      if (term.count === 0) {
        continue;
      }
      objects.push({
        systemTag: new SystemTagSimple({
          data: {
            system_tag: term.term
          }
        }),
        count: term.count
      });
    }
    return objects;
  };

  SystemTagsFacet.prototype.renderObject = function(object) {
    return [object.systemTag.getLabel()];
  };

  SystemTagsFacet.prototype.getObjectsSorted = function(objects) {
    objects = SystemTagsFacet.__super__.getObjectsSorted.call(this, objects);
    if (objects && this.getSortSetting() === "term" && (objects != null ? objects.length : void 0) > 1) {
      objects.sort((function(_this) {
        return function(a, b) {
          if (_this.getSortOrderSetting() === "ASC") {
            return a.systemTag.getDisplayName().localeCompare(b.systemTag.getDisplayName());
          } else {
            return b.systemTag.getDisplayName().localeCompare(a.systemTag.getDisplayName());
          }
        };
      })(this));
    }
    return objects;
  };

  SystemTagsFacet.prototype.requestFacet = function() {
    return {
      type: "term",
      field: "_system_tags.system_tag"
    };
  };

  SystemTagsFacet.prototype.requestSearchFilter = function(object) {
    return {
      bool: "must",
      fields: ["_system_tags.system_tag"],
      type: "in",
      "in": [object.systemTag.getInternalName()]
    };
  };

  SystemTagsFacet.prototype.isFilterOf = function(objectOne, objectTwo) {
    return objectOne.systemTag.getDisplayName() === objectTwo.systemTag.getDisplayName();
  };

  return SystemTagsFacet;

})(Facet);
// Generated by CoffeeScript 1.12.7
var CollectionManager, CollectionManagerLoader,
  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;

CollectionManager = (function(superClass) {
  extend(CollectionManager, superClass);

  function CollectionManager() {
    return CollectionManager.__super__.constructor.apply(this, arguments);
  }

  CollectionManager.SHARED_COLLECTIONS_PAGE_SIZE = 200;

  CollectionManager.prototype.initOpts = function() {
    CollectionManager.__super__.initOpts.call(this);
    return this.addOpts({
      detailDiv: {
        check: function(v) {
          return CUI.util.isElement(v);
        }
      },
      mainLayout: {
        mandatory: true,
        check: CUI.Layout
      },
      sidebar: {
        check: Sidebar
      },
      onRender: {
        check: Function
      },
      preventBlurOnSelect: {
        check: Boolean,
        "default": false
      }
    });
  };

  CollectionManager.prototype.hasContent = function() {
    return !CUI.util.isEmpty(this.trees) || this.hasOwnCollections();
  };

  CollectionManager.prototype.hasFixedCollections = function() {
    return ez5.session.hasSystemRight("root", "search[show_fixed_searches]");
  };

  CollectionManager.prototype.hasEmptyStoredSearches = function() {
    return ez5.session.hasSystemRight("root", "frontend_features[stored_searches]");
  };

  CollectionManager.prototype.hasStoredSearches = function() {
    return true;
  };

  CollectionManager.prototype.hasOwnCollections = function() {
    return ez5.session.hasSystemRight("root", "search[has_own_collections]");
  };

  CollectionManager.prototype.hasButtons = function() {
    return true;
  };

  CollectionManager.prototype.hasCollectionSelection = function() {
    return true;
  };

  CollectionManager.prototype.allowsDeselect = function() {
    return false;
  };

  CollectionManager.prototype.hasSplitButton = function() {
    return true;
  };

  CollectionManager.prototype.hasFillScreenButton = function() {
    return true;
  };

  CollectionManager.prototype.hasSearchCollection = function() {
    if (ez5.session.hasSystemRight("root", "search")) {
      return true;
    }
    return false;
  };

  CollectionManager.prototype.getSidebar = function() {
    return this._sidebar;
  };

  CollectionManager.prototype.getCollectionWorkfolderClass = function() {
    return ez5.defaults["class"].CollectionWorkfolder;
  };

  CollectionManager.prototype.getDownloadManagerClass = function() {
    return this.getSearch().getDownloadManagerClass();
  };

  CollectionManager.prototype.getSearchCollection = function() {
    return this.__searchCollection;
  };

  CollectionManager.prototype.getSearchCollectionClass = function() {
    return ez5.defaults["class"].SearchCollection;
  };

  CollectionManager.prototype.getTreeFilter = function() {
    return (function(_this) {
      return function(filter) {
        return _this.loadCollections(filter);
      };
    })(this);
  };

  CollectionManager.prototype.__findInTrees = function(eq_func) {
    var nameOfTree, nodes, ref, tree;
    if (eq_func == null) {
      eq_func = null;
    }
    nodes = [];
    ref = this.trees;
    for (nameOfTree in ref) {
      tree = ref[nameOfTree];
      nodes.push.apply(nodes, tree.root.find(eq_func));
    }
    return nodes;
  };

  CollectionManager.prototype.destroy = function() {
    var i, len, nameOfTree, node, ref, ref1, ref2, tree;
    ref = this.__findInTrees();
    for (i = 0, len = ref.length; i < len; i++) {
      node = ref[i];
      node.destroy();
    }
    ref1 = this.trees;
    for (nameOfTree in ref1) {
      tree = ref1[nameOfTree];
      tree.destroy();
      delete this.trees[nameOfTree];
    }
    if ((ref2 = this.__collectionSelection) != null) {
      ref2.destroy();
    }
    CUI.Events.ignore({
      instance: this
    });
    return CollectionManager.__super__.destroy.call(this);
  };

  CollectionManager.prototype.getAddToCollectionMenuItems = function(opts) {
    var add_to_collection, fn, i, item, items, len, menu_items, ref, selCol;
    CUI.Element.readOpts(opts, "CollectionManager.getAddToCollectionTool", {
      collection: {
        mandatory: true,
        check: CollectionSelection
      }
    });
    add_to_collection = (function(_this) {
      return function(to_collection) {
        to_collection.insertObjects(opts.collection.getObjects());
      };
    })(this);
    items = this.getMenuItems();
    menu_items = [];
    ref = items || [];
    fn = (function(_this) {
      return function(item) {
        return menu_items.push({
          text: item.text,
          disabled: item.disabled,
          onClick: function(ev, btn) {
            return item.onClick(ev, btn).done(function(new_collection) {
              return add_to_collection(new_collection);
            });
          }
        });
      };
    })(this);
    for (i = 0, len = ref.length; i < len; i++) {
      item = ref[i];
      if (item.label) {
        menu_items.push(item);
        continue;
      }
      fn(item);
    }
    selCol = this.getSelectedCollection();
    if (selCol && selCol !== opts.collection && selCol !== opts.collection.getParentCollection()) {
      menu_items.push({
        divider: true
      });
      menu_items.push({
        label: $$("collection.manager.add_to_collection.existing_collection")
      });
      menu_items.push({
        text: selCol.renderNameAsText(),
        onClick: (function(_this) {
          return function() {
            return add_to_collection(selCol);
          };
        })(this)
      });
    }
    if (menu_items.length === 1) {
      return [];
    }
    return menu_items;
  };

  CollectionManager.prototype.render = function() {
    var event_types;
    this.__pane = this.getCollectionPane();
    this.registerDOMElement(this.__pane.DOM);
    if (this.hasCollectionSelection()) {
      this.__collectionSelection = new CollectionSelection({
        manager: this,
        sidebar: this._sidebar,
        preventBlurOnSelect: this._preventBlurOnSelect
      });
    }
    this.resetCollectionDetailDiv();
    if (this.hasButtons()) {
      if (this.hasOwnCollections()) {
        this.plusButton = new LocaButton({
          icon: "plus",
          loca_key: "collection.manager.button.add",
          ui: "collection.manager.add.button",
          group: "plus-minus",
          disabled: true,
          onClick: (function(_this) {
            return function() {
              var node;
              if (ez5.session.isReadOnly()) {
                CUI.alert({
                  text: $$("base.error.user.read_only_mode")
                });
                return;
              }
              node = _this.getTopCreateCollection();
              if (node) {
                return _this.newCollection(_this.getCollectionWorkfolderClass(), node.getPath(true)[0]);
              }
            };
          })(this)
        });
        this.minusButton = new LocaButton({
          icon: "minus",
          loca_key: "collection.manager.button.delete",
          ui: "collection.manager.minus.button",
          group: "plus-minus",
          disabled: true,
          onClick: (function(_this) {
            return function() {
              if (ez5.session.isReadOnly()) {
                CUI.alert({
                  text: $$("base.error.user.read_only_mode")
                });
                return;
              }
              return _this.getSelectedCollection()["delete"]().done(function() {
                return CUI.Events.trigger({
                  node: _this.tree,
                  type: "data-changed"
                });
              });
            };
          })(this)
        });
      }
      this.refreshButton = new LocaButton({
        loca_key: "collection.manager.button.refresh",
        ui: "collection.manager.refresh.button",
        onClick: (function(_this) {
          return function() {
            var ref;
            _this.refreshButton.disable();
            if ((ref = _this.getSelectedCollection()) != null) {
              ref.deselect();
            }
            return _this.loadCollections(null).done(function() {
              return _this.refreshButton.enable();
            });
          };
        })(this)
      });
    }
    event_types = ez5.version("6") ? ["COLLECTION_DELETE", "OBJECT_INDEX"] : ["OBJECT_DELETE", "OBJECT_INDEX"];
    EventPoller.listen({
      instance: this,
      filter: {
        type: event_types,
        basetype: "collection"
      },
      call: (function(_this) {
        return function(events) {
          var doRemoveNodes, event, i, j, len, len1, node, nodes, remove_nodes;
          remove_nodes = [];
          doRemoveNodes = function() {
            var i, len, node, ref, select_after, selectable_nodes;
            for (i = 0, len = remove_nodes.length; i < len; i++) {
              node = remove_nodes[i];
              if (node.isSelected()) {
                select_after = true;
              }
              node.remove(false, false);
            }
            if (select_after) {
              selectable_nodes = _this.__findInTrees(function(node) {
                return node.isSelectable();
              });
              return (ref = selectable_nodes[0]) != null ? ref.select() : void 0;
            }
          };
          for (i = 0, len = events.length; i < len; i++) {
            event = events[i];
            if (event.session_self) {
              continue;
            }
            nodes = _this.__findInTrees(function(node) {
              return node instanceof CollectionStorable && (node.getId() === event.object_id || node.getIdParent() === event.object_id);
            });
            if (nodes.length === 0) {
              continue;
            }
            for (j = 0, len1 = nodes.length; j < len1; j++) {
              node = nodes[j];
              if (event.type === "OBJECT_DELETE" || event.type === "COLLECTION_DELETE") {
                remove_nodes.push(node);
                CUI.toaster({
                  show_ms: 5000,
                  text: $$("collection.manager.collection_deleted_elsewhere", {
                    collection: node.renderNameAsText()
                  }),
                  markdown: true
                });
              } else if (event.type === "OBJECT_INDEX") {
                if (node.isRendered()) {
                  node.refresh(true);
                } else {
                  node.__markForUpdate = true;
                }
              }
            }
          }
          doRemoveNodes();
        };
      })(this)
    });
    this.initPanels();
    this.__hasSharedCollections = false;
    ez5.api.search({
      data: {
        debug: "CollectionManager-SharedCollectionCheck"
      },
      json_data: {
        type: "collection",
        limit: 0,
        search: this.getSharedCollectionSearch(),
        generate_rights: false
      }
    }).done((function(_this) {
      return function(data) {
        if (data.count > CollectionManager.SHARED_COLLECTIONS_PAGE_SIZE) {
          _this.__paginateSharedCollections = true;
        }
        _this.__hasSharedCollections = data.count > 0;
        return _this.loadCollections(null).done(function() {
          var ref;
          if ((ref = _this.plusButton) != null) {
            ref.enable();
          }
          _this.__selectOnLoad();
          return typeof _this._onRender === "function" ? _this._onRender() : void 0;
        });
      };
    })(this));
    return this.__pane;
  };

  CollectionManager.prototype.__selectOnLoad = function() {
    var node;
    if (this.getSelectedCollection()) {
      return;
    }
    node = this.findCollectionByLocation();
    if (node) {
      node.selectOnLoad();
      this.getPaneFlexHandle().open();
    }
  };

  CollectionManager.prototype.onSelect = function() {};

  CollectionManager.prototype.onDeselect = function() {};

  CollectionManager.prototype.objecttypesUpdated = function() {
    var ref;
    return (ref = this.__searchCollection) != null ? ref.updateCounter() : void 0;
  };

  CollectionManager.prototype.getCollectionLocation = function() {
    var m;
    m = document.location.pathname.match("^" + window.easydb_base_prefix + "/collection/(.*)$");
    return m != null ? m[1] : void 0;
  };

  CollectionManager.prototype.findCollectionByLocation = function() {
    var loc, node, nodes;
    loc = this.getCollectionLocation();
    if (loc) {
      node = this.findCollectionByLocator(loc);
    }
    if (!node && !this.hasSearchCollection()) {
      nodes = this.__findInTrees((function(_this) {
        return function(node) {
          return node.isSelectable();
        };
      })(this));
      node = nodes[0];
    }
    return node;
  };

  CollectionManager.prototype.findCollectionByLocator = function(locator) {
    var nodes;
    if (CUI.util.isEmpty(locator)) {
      return;
    }
    nodes = this.__findInTrees(function(node) {
      return typeof node.matchesLocator === "function" ? node.matchesLocator(locator) : void 0;
    });
    return nodes[0];
  };

  CollectionManager.prototype.findCollectionByName = function(name) {
    var nodes;
    nodes = this.__findInTrees(function(node) {
      if (!(node instanceof CollectionStorable)) {
        return;
      }
      return node.renderNameAsText() === name;
    });
    return nodes[0];
  };

  CollectionManager.prototype.getSelectedCollection = function() {
    var nameOfTree, node, ref, tree;
    ref = this.trees;
    for (nameOfTree in ref) {
      tree = ref[nameOfTree];
      node = tree.getSelectedNode();
      if (node) {
        return node;
      }
    }
    return null;
  };

  CollectionManager.prototype.getTopCreateCollection = function() {
    var ref, topCreate;
    topCreate = (ref = this.__findInTrees(function(node) {
      return typeof node.isCreateChildAllowed === "function" ? node.isCreateChildAllowed() : void 0;
    })) != null ? ref[0] : void 0;
    return topCreate;
  };

  CollectionManager.prototype.getMenuItems = function() {
    var c, fn, i, items, len, node, ref, ref1;
    if (!this.plusButton) {
      return null;
    }
    items = [];
    node = this.getSelectedCollection();
    if (!node && ((ref = this.trees["own_collection"]) != null ? ref.root.children : void 0)) {
      node = this.getTopCreateCollection();
    }
    if (!node) {
      this.plusButton.disable();
      return items;
    }
    ref1 = node.getPath(true);
    fn = (function(_this) {
      return function(c) {
        var text, uiValue;
        text = c.renderNameAsText();
        uiValue = (typeof c.getId === "function" ? c.getId() : void 0) || text.toLowerCase().replace(/s+/g, '_');
        return items.push({
          text: text,
          ui: "collection.manager.menu.item.button:" + uiValue,
          disabled: !node.isCreateChildAllowed(),
          onClick: function(ev, btn) {
            var root_btn;
            root_btn = btn.getMenuRootButton();
            if (!root_btn) {
              root_btn = btn;
            }
            root_btn.disable();
            return _this.newCollection(_this.getCollectionWorkfolderClass(), c).always(function() {
              return root_btn.enable();
            });
          }
        });
      };
    })(this);
    for (i = 0, len = ref1.length; i < len; i++) {
      c = ref1[i];
      if (!c.isCreateChildAllowed()) {
        continue;
      }
      fn(c);
    }
    if (items.length) {
      items.splice(0, 0, {
        label: $$("collection.manager.add_to_collection.new_collection")
      });
      this.plusButton.enable();
    } else {
      this.plusButton.disable();
    }
    return items;
  };

  CollectionManager.prototype.setStatus = function() {
    var node, ref;
    if ((ref = this.minusButton) != null) {
      ref.disable();
    }
    node = this.getSelectedCollection();
    if (!node) {
      this.getMenuItems();
      return this;
    }
    node.prepareCurrentTools().done((function(_this) {
      return function() {
        var ref1;
        _this.getMenuItems();
        if (node.isDeletable()) {
          return (ref1 = _this.minusButton) != null ? ref1.enable() : void 0;
        }
      };
    })(this));
    return this;
  };

  CollectionManager.prototype.__getClosePaneButton = function() {
    return new LocaButton({
      loca_key: "base.help.flex_handle.close",
      ui: "collection.manager.flex_handle_close.button",
      icon: "west",
      "class": "ez5-collection-manager-close-pane-button cui-pane-close-button",
      onClick: (function(_this) {
        return function() {
          return _this.getPaneFlexHandle().close();
        };
      })(this)
    });
  };

  CollectionManager.prototype.getClosePaneButtonCenter = function() {
    return this.__getClosePaneButton();
  };

  CollectionManager.prototype.getClosePaneButtonList = function() {
    return this.__getClosePaneButton();
  };

  CollectionManager.prototype.getPaneFlexHandle = function() {
    return CUI.dom.data(CUI.dom.closest(this.__pane.DOM, "[flex-handled-pane]"), "flexHandle");
  };

  CollectionManager.prototype.__triggerResizePaneEvents = function() {
    if (!this.__pane) {
      return;
    }
    CUI.Events.trigger({
      type: "viewport-resize"
    });
    return CUI.Events.trigger({
      node: this.__pane,
      type: "content-resize"
    });
  };

  CollectionManager.prototype.showSearch = function() {
    var ref;
    if (this.isSplitModeActive()) {
      return;
    }
    if ((ref = this.getSelectedCollection()) != null) {
      ref.deselect();
    }
  };

  CollectionManager.prototype.getSplitButton = function() {
    var splitBtn;
    if (!this.hasSearchCollection()) {
      return null;
    }
    return splitBtn = new LocaButton({
      "switch": true,
      active: this.lastSplitStateActive,
      loca_key: "collection.manager.finder.search.split_button",
      onActivate: (function(_this) {
        return function() {
          _this.lastSplitStateActive = true;
          return _this.setSplitMode(true);
        };
      })(this),
      onDeactivate: (function(_this) {
        return function() {
          _this.lastSplitStateActive = false;
          return _this.setSplitMode(false);
        };
      })(this)
    });
  };

  CollectionManager.prototype.isSplitModeActive = function() {
    return this._mainLayout.hasClass("ez5-finder--split-pane");
  };

  CollectionManager.prototype.setSplitMode = function(turn_on) {
    if (turn_on) {
      this._mainLayout.addClass("ez5-finder--split-pane");
      this._mainLayout.removeClass("ez5-finder--single-pane");
      this.__triggerResizePaneEvents();
    } else {
      this._mainLayout.removeClass("ez5-finder--split-pane");
      this._mainLayout.addClass("ez5-finder--single-pane");
      this.__triggerResizePaneEvents();
    }
  };

  CollectionManager.prototype.getTitleLocaKey = function() {
    return "collection.manager.title";
  };

  CollectionManager.prototype.getCollectionPane = function(tree) {
    this.__paneCollectionList = new CUI.SimplePane({
      "class": "cui-pane--window",
      header_left: [
        new CUI.Button({
          text: $$(this.getTitleLocaKey()),
          tooltip: {
            text: $$("base.help.flex_handle.close|tooltip")
          },
          ui: "collection.manager.flex_handle_close.button",
          "class": "cui-pane-title-button",
          onClick: (function(_this) {
            return function() {
              return _this.getPaneFlexHandle().close();
            };
          })(this)
        })
      ],
      header_right: [this.getClosePaneButtonList()]
    });
    if (!this._detailDiv) {
      return new CUI.HorizontalLayout({
        "class": "ez5-collection-manager-pane",
        left: {
          "class": "ez5-collection-manager-list",
          content: this.__paneCollectionList,
          flexHandle: {
            "class": "ez5-collection-manager-list-flex-handle",
            state_name: "collection-manager-left",
            closable: false,
            hidden: false
          }
        },
        center: {
          "class": "ez5-collection-manager-detail"
        }
      });
    } else {
      return this.__paneCollectionList;
    }
  };

  CollectionManager.prototype.addTreeToCollectionPane = function(tree) {
    return this.__paneCollectionList.replace(tree.render(), "center");
  };

  CollectionManager.prototype.getCollectionDetailDiv = function() {
    if (this._detailDiv) {
      return this._detailDiv;
    } else {
      return this.__pane.center();
    }
  };

  CollectionManager.prototype.resetCollectionDetailDiv = function(collection) {
    var key, sp;
    if (collection) {
      key = collection.getEmptyLabelLocaKey();
    } else {
      key = "collection.manager.no_collection.empty_label";
    }
    sp = new CUI.SimplePane({
      "class": "cui-pane--window",
      content: new LocaLabel({
        "class": "cui-empty-label",
        centered: true,
        multiline: true,
        loca_key: key
      })
    });
    CUI.dom.replace(this.getCollectionDetailDiv(), sp);
    return sp;
  };

  CollectionManager.prototype.setSearch = function(search1) {
    this.search = search1;
  };

  CollectionManager.prototype.loadSearch = function() {
    if (this.getCollectionLocation() || !this.hasSearchCollection()) {
      return;
    }
    if (!this.getSearch().getLastData()) {
      this.getSearch().executeOnLoad();
    }
  };

  CollectionManager.prototype.getSearch = function() {
    return this.search;
  };

  CollectionManager.prototype.getCollectionSearchFilter = function(include_has_acl) {
    var search;
    if (include_has_acl == null) {
      include_has_acl = false;
    }
    search = [
      {
        type: "complex",
        bool: "must",
        search: [
          {
            type: "in",
            bool: "should",
            fields: ["_owner.user._id"],
            "in": [ez5.session.getUser().getId()]
          }, {
            type: "in",
            bool: "should",
            fields: ["_owner.group._id"],
            "in": ez5.session.getGroupIds()
          }
        ]
      }
    ];
    if (include_has_acl) {
      search[0].search.push({
        type: "in",
        bool: "should",
        fields: ["_has_acl"],
        "in": [true]
      });
    } else {
      search[0].search.push({
        type: "complex",
        bool: "should",
        search: [
          {
            type: "in",
            bool: "must",
            fields: ["_has_acl"],
            "in": [true]
          }, {
            type: "in",
            bool: "must",
            fields: ["collection.type"],
            "in": ["search"]
          }
        ]
      });
    }
    return search;
  };

  CollectionManager.prototype.getSharedCollectionSearch = function() {
    var search;
    search = [
      {
        type: "complex",
        bool: "must",
        search: [
          {
            type: "in",
            bool: "must_not",
            fields: ["_owner.user._id"],
            "in": [ez5.session.getUser().getId()]
          }, {
            type: "in",
            bool: "must",
            fields: ["_has_acl"],
            "in": [true]
          }, {
            type: "in",
            bool: "must_not",
            fields: ["collection.type"],
            "in": ["search"]
          }
        ]
      }
    ];
    return search;
  };

  CollectionManager.prototype.getCollectionSortFilter = function() {
    return [
      {
        field: "_level"
      }, {
        field: "collection.displayname"
      }
    ];
  };

  CollectionManager.prototype.hasFilter = function() {
    return !CUI.util.isEmpty(this.__loadFilter);
  };

  CollectionManager.prototype.__load_counter = 0;

  CollectionManager.prototype.loadCollections = function(loadFilter) {
    var dfr, inputSearch, is_search, load_counter, load_objecttypes, phrase, read_search_response, ref, search, searchAttempt, searchDeferred, searchNoLimit, str, wb;
    load_counter = ++this.__load_counter;
    dfr = new CUI.Deferred();
    wb = new CUI.WaitBlock({
      element: this.__pane
    });
    wb.show();
    dfr.always((function(_this) {
      return function() {
        return wb.destroy();
      };
    })(this));
    if (loadFilter !== void 0) {
      this.__loadFilter = loadFilter;
    }
    if (this.hasSearchCollection()) {
      this.__searchCollection = new CollectionStructure({
        displayname: $$("collection.search.panel.title"),
        children: [],
        manager: this
      });
    }
    load_objecttypes = (function(_this) {
      return function() {
        var dfr2;
        dfr2 = new CUI.Deferred();
        _this.getSearch().getSearchInitializedPromise().fail(dfr2.reject).done(function() {
          var i, j, len, len1, linked_object_fields, linked_object_fields_facet, lof, lof_by_ot, objecttype_collections, ot, ot_inst, ot_name, ots_inst, ref;
          if (load_counter !== _this.__load_counter) {
            return;
          }
          if (_this.getSearch().isDestroyed()) {
            return;
          }
          linked_object_fields = _this.getSearch().getLinkedObjectFields("expert");
          linked_object_fields_facet = _this.getSearch().getLinkedObjectFields("facet") || [];
          if (linked_object_fields_facet.length > 0) {
            linked_object_fields = linked_object_fields.concat(linked_object_fields_facet);
          }
          lof_by_ot = {};
          for (i = 0, len = linked_object_fields.length; i < len; i++) {
            lof = linked_object_fields[i];
            ot_name = lof.linkMask().table.name();
            if (!lof_by_ot[ot_name]) {
              lof_by_ot[ot_name] = [];
            }
            lof_by_ot[ot_name].push(lof);
          }
          objecttype_collections = [];
          ref = ez5.objecttypes.getObjecttypes();
          for (j = 0, len1 = ref.length; j < len1; j++) {
            ot = ref[j];
            if (!lof_by_ot[ot.objecttype.name]) {
              continue;
            }
            if (!ot.objecttype.show_in_collections) {
              continue;
            }
            ot_inst = new Objecttype(ez5.schema.CURRENT._objecttype_by_name[ot.objecttype.name]);
            if (ot_inst.inMainSearch()) {
              continue;
            }
            ots_inst = new CollectionSearchObjecttype({
              objecttype: ot_inst,
              manager: _this,
              filter: _this.__loadFilter,
              info: ot
            });
            objecttype_collections.push(ots_inst);
          }
          objecttype_collections.sort(function(first, second) {
            return first.renderNameAsText().localeCompare(second.renderNameAsText());
          });
          return dfr2.resolve(objecttype_collections);
        });
        return dfr2.promise();
      };
    })(this);
    read_search_response = (function(_this) {
      return function(data, objecttype_collections) {
        var _own, _root, _searches, _shared, _shared_searches, colS, continue_after_shared, continue_after_shared_already_ran, group_nodes, i, idx, j, k, l, len, len1, len2, len3, loc, lost_and_found, obj, own_collection, own_collection2, own_collections, owner, p, ref, ref1, ref2, ref3, root_collections, shared_collection, shared_collections, sortCollections;
        if (data.count === 0 && _this.hasFilter()) {
          _this.inputFilter.addClass("ez5-collection-manager-nothing-found");
        }
        if (_this.isDestroyed()) {
          dfr.reject();
          return;
        }
        ref = data.objects;
        for (i = 0, len = ref.length; i < len; i++) {
          obj = ref[i];
          if (obj._owner.group) {
            owner = "group: " + obj._owner.group._id;
          } else {
            owner = "user: " + obj._owner.user._id;
          }
        }
        _root = [];
        _own = [];
        _searches = [];
        _shared_searches = [];
        _shared = [];
        ref1 = data.objects;
        for (idx = j = 0, len1 = ref1.length; j < len1; idx = ++j) {
          obj = ref1[idx];
          if (obj.collection.is_system_collection && !obj.collection._id_parent) {
            if (obj.collection.reference !== "system:root") {
              _root.push(obj);
            }
          } else if (obj.collection.type === "search") {
            if (obj._owner.user._id !== ez5.session.getUser().getId()) {
              _shared_searches.push(obj);
            } else {
              _searches.push(obj);
            }
          } else if (obj._owner.user._id === ez5.session.getUser().getId()) {
            _own.push(obj);
          } else {
            _shared.push(obj);
          }
        }
        root_collections = ez5.buildObjectTree({
          objects: _root,
          objectKey: "collection",
          doOpen: is_search,
          newInstanceFunc: function(collection) {
            return _this.getCollectionWorkfolderClass().newInstance({
              collection: collection,
              manager: _this
            });
          }
        });
        own_collections = ez5.buildObjectTree({
          objects: _own,
          objectKey: "collection",
          filter: false,
          doOpen: is_search,
          newInstanceFunc: function(collection) {
            return _this.getCollectionWorkfolderClass().newInstance({
              collection: collection,
              manager: _this
            });
          }
        });
        if (own_collections.length > 0) {
          own_collections = own_collections[0].children;
        }
        shared_collections = ez5.buildObjectTree({
          objects: _shared,
          objectKey: "collection",
          filter: true,
          doOpen: is_search,
          newInstanceFunc: function(collection) {
            return _this.getCollectionWorkfolderClass().newInstance({
              collection: collection,
              manager: _this
            });
          }
        });
        sortCollections = function(first, second) {
          var firstBestFrontendValue, secondBestFrontendValue;
          firstBestFrontendValue = ez5.loca.getBestDatabaseValue(first.getCollectionDisplayname()) || "";
          secondBestFrontendValue = ez5.loca.getBestDatabaseValue(second.getCollectionDisplayname()) || "";
          return firstBestFrontendValue.localeCompare(secondBestFrontendValue);
        };
        shared_collections.sort(sortCollections);
        for (k = 0, len2 = shared_collections.length; k < len2; k++) {
          shared_collection = shared_collections[k];
          shared_collection.sort(sortCollections);
        }
        if (own_collections.length > 1) {
          console.error("own_collection.length > 1, creating 'Shared' collection", own_collections);
        }
        lost_and_found = new CollectionStructure({
          children: [],
          displayname: $$(_this.getDisplayNameKeyForSharedCollections()),
          manager: _this
        });
        own_collections.sort(sortCollections);
        own_collection = null;
        ref2 = own_collections || [];
        for (l = 0, len3 = ref2.length; l < len3; l++) {
          own_collection2 = ref2[l];
          own_collection2.sort(sortCollections);
          if (own_collection2 instanceof CollectionSystemUser && !own_collection) {
            own_collection = own_collection2;
          } else {
            lost_and_found.children.push(own_collection2);
          }
        }
        _this.__ownCollection = own_collection;
        if (own_collection && lost_and_found.children.length > 0) {
          if (!own_collection.children) {
            own_collection.children = [];
          }
          own_collection.children.push(lost_and_found);
        }
        if ((own_collection != null ? (ref3 = own_collection.children) != null ? ref3.length : void 0 : void 0) > 100) {
          group_nodes = ez5.groupTreeNodes({
            nodes: own_collection.children,
            limit: 50,
            newInstanceFunc: function(first, last, nodes) {
              var cmp, cmp1, cmp2, displayname, firstName, get_split_compare, lastName, name_first, name_last;
              get_split_compare = function(name_first, name_last) {
                var cut_first, cut_last, len_first, len_last, n, ref4, txt_first, txt_last;
                txt_first = name_first.split("");
                txt_last = name_last.split("");
                len_first = txt_first.length;
                len_last = txt_last.length;
                cut_first = len_first - 1;
                cut_last = len_last - 1;
                for (idx = n = 0, ref4 = Math.min(len_first, len_last); 0 <= ref4 ? n < ref4 : n > ref4; idx = 0 <= ref4 ? ++n : --n) {
                  if (txt_first[idx].toLocaleLowerCase() !== txt_last[idx].toLocaleLowerCase()) {
                    cut_first = idx;
                    cut_last = idx;
                    break;
                  }
                }
                return [cut_first, cut_last];
              };
              cmp = get_split_compare(nodes[first].renderNameAsText(), nodes[last].renderNameAsText());
              name_first = nodes[first].renderNameAsText();
              name_last = nodes[last].renderNameAsText();
              if (nodes[first - 1]) {
                cmp1 = get_split_compare(nodes[first - 1].renderNameAsText(), name_first);
                if (cmp1[1] > cmp[0]) {
                  cmp[0] = cmp1[1];
                }
              }
              if (nodes[last + 1]) {
                cmp2 = get_split_compare(name_last, nodes[last + 1].renderNameAsText());
                if (cmp2[0] > cmp[1]) {
                  cmp[1] = cmp2[0];
                }
              }
              displayname = new CUI.Template({
                name: "collection-structure",
                map: {
                  collection_icon_first: true,
                  collection_icon_last: true,
                  collection_name_first: true,
                  collection_name_last: true
                }
              });
              firstName = name_first.split("").slice(0, cmp[0] + 1).join("");
              lastName = name_last.split("").slice(0, cmp[1] + 1).join("");
              displayname.append(new CUI.Icon({
                icon: 'folder'
              }), "collection_icon_first");
              displayname.append(new CUI.Icon({
                icon: 'folder'
              }), "collection_icon_last");
              displayname.append(firstName, "collection_name_first");
              displayname.append(lastName, "collection_name_last");
              return new CollectionStructure({
                icon: null,
                displayname: displayname,
                displaytext: firstName + " - " + lastName,
                manager: _this
              });
            }
          });
          own_collection.setChildren(group_nodes);
        }
        if (own_collection && _this.hasOwnCollections()) {
          if (!own_collection.children) {
            own_collection.children = [];
          }
          p = _this.addPanel(own_collection, "own_collection");
          own_collection.prepareCurrentTools().done(function() {
            return _this.setStatus();
          });
          p.open();
        }
        continue_after_shared_already_ran = false;
        continue_after_shared = function() {
          var _search, collectionSearch, collectionStoredSearch, len4, len5, len6, len7, len8, mf, mf1, mf2, mf3, n, o, ot_col, q, r, ref4, s, search_col, search_collections;
          if (continue_after_shared_already_ran) {
            return;
          }
          continue_after_shared_already_ran = true;
          if (!_this.hasSearchCollection()) {
            _this.setStatus();
            dfr.resolve();
            return;
          }
          if (_this.hasFixedCollections()) {
            mf1 = new CollectionFixedSearchAnyToday({
              manager: _this,
              getSearchObjecttypes: function() {
                return _this.getSearchObjectypes();
              }
            });
            mf2 = new CollectionFixedSearchInsertToday({
              manager: _this,
              getSearchObjecttypes: function() {
                return _this.getSearchObjectypes();
              }
            });
            mf3 = new CollectionFixedSearchUpdateToday({
              manager: _this,
              getSearchObjecttypes: function() {
                return _this.getSearchObjectypes();
              }
            });
            ref4 = [mf1, mf2, mf3];
            for (n = 0, len4 = ref4.length; n < len4; n++) {
              mf = ref4[n];
              mf.icon = function() {
                return "fa-calendar";
              };
              _this.__searchCollection.addChild(mf);
            }
          }
          search_collections = [];
          for (o = 0, len5 = _searches.length; o < len5; o++) {
            _search = _searches[o];
            collectionSearch = new CollectionStoredSearch({
              collection: _search,
              manager: _this
            });
            search_collections.push(collectionSearch);
          }
          for (q = 0, len6 = _shared_searches.length; q < len6; q++) {
            _search = _shared_searches[q];
            collectionStoredSearch = new CollectionStoredSearch({
              collection: _search,
              manager: _this
            });
            collectionStoredSearch.icon = function() {
              return "svg-search-shared";
            };
            search_collections.push(collectionStoredSearch);
          }
          if ((search_collections.length > 0 || _this.hasEmptyStoredSearches()) && _this.hasStoredSearches()) {
            search_collections.sort(sortCollections);
            for (r = 0, len7 = search_collections.length; r < len7; r++) {
              search_col = search_collections[r];
              _this.__searchCollection.addChild(search_col);
            }
          }
          if (_this.__searchCollection.children.length > 0 || _this.hasEmptyStoredSearches()) {
            p = _this.addPanel(_this.__searchCollection, "search_collection");
            if (is_search) {
              p.open();
            }
          }
          for (s = 0, len8 = objecttype_collections.length; s < len8; s++) {
            ot_col = objecttype_collections[s];
            p = _this.addPanel(ot_col, "ot_collection" + ot_col.renderNameAsText());
            if (is_search) {
              p.__load();
              p.open();
            }
          }
          CUI.chunkWork.call(_this, {
            chunk_size: 1,
            items: own_collections,
            call: function(items) {
              return items[0].prepareCurrentTools();
            }
          }).always(function() {
            return _this.setStatus();
          }).done(dfr.resolve).fail(dfr.reject);
        };
        if (_this.__hasSharedCollections) {
          if (_this.__paginateSharedCollections) {
            _this.__sharedCollectionsNavigationOffset = 0;
            _this.__sharedCollectionsNavigationToolbar = new NavigationToolbar({
              append_count_label: false,
              render_on_left: true,
              onLoadPage: function(page) {
                return _this.__sharedCollectionsLoadPage(page);
              }
            });
          }
          colS = new CollectionStructure({
            displayname: $$(_this.getDisplayNameKeyForSharedCollections()),
            "class": "ez5-folder-header",
            children: is_search || shared_collections.length > 0 ? shared_collections : void 0,
            manager: _this,
            navigation: _this.__sharedCollectionsNavigationToolbar,
            getChildren: function() {
              var dfrS;
              dfrS = new CUI.Deferred();
              if (_this.__paginateSharedCollections) {
                ez5.api.search({
                  data: {
                    debug: "CollectionManagerPaginatedSharedCollection"
                  },
                  json_data: {
                    type: "collection",
                    limit: CollectionManager.SHARED_COLLECTIONS_PAGE_SIZE,
                    offset: _this.__sharedCollectionsNavigationOffset,
                    search: _this.getSharedCollectionSearch(),
                    generate_rights: false,
                    sort: _this.getCollectionSortFilter()
                  }
                }).fail(dfrS.reject).done(function(data) {
                  var len4, n, node, nodes, ref4;
                  _this.__sharedCollectionsNavigationToolbar.update({
                    count: data.count,
                    offset: _this.__sharedCollectionsNavigationOffset,
                    limit: CollectionManager.SHARED_COLLECTIONS_PAGE_SIZE
                  });
                  nodes = ez5.buildObjectTree({
                    objects: data.objects,
                    objectKey: "collection",
                    filter: true,
                    newInstanceFunc: function(collection) {
                      return _this.getCollectionWorkfolderClass().newInstance({
                        collection: collection,
                        manager: _this
                      });
                    }
                  });
                  _this.__calculateSharedRecursiveCounts(nodes);
                  for (n = 0, len4 = nodes.length; n < len4; n++) {
                    node = nodes[n];
                    if (((ref4 = node.children) != null ? ref4.length : void 0) > 0) {
                      delete node.children;
                    }
                  }
                  return dfrS.resolve(nodes);
                });
              } else {
                ez5.api.search_no_limit({
                  data: {
                    debug: "CollectionManager"
                  },
                  json_data: {
                    type: "collection",
                    limit: 100000,
                    search: _this.getSharedCollectionSearch(),
                    generate_rights: false,
                    sort: _this.getCollectionSortFilter()
                  }
                }).fail(dfrS.reject).done(function(data) {
                  var nodes;
                  nodes = ez5.buildObjectTree({
                    objects: data.objects,
                    objectKey: "collection",
                    filter: true,
                    newInstanceFunc: function(collection) {
                      return _this.getCollectionWorkfolderClass().newInstance({
                        collection: collection,
                        manager: _this
                      });
                    }
                  });
                  _this.__calculateSharedRecursiveCounts(nodes);
                  return dfrS.resolve(nodes);
                });
              }
              return dfrS.promise();
            }
          });
          p = _this.addPanel(colS, "shared_collection", true);
          loc = _this.getCollectionLocation();
          if (is_search || (loc && !_this.findCollectionByLocator(loc)) || !(_this.hasOwnCollections() && own_collections.length > 0)) {
            return p.__load().always(function() {
              p.open();
              return continue_after_shared();
            });
          } else {
            return continue_after_shared();
          }
        } else {
          return continue_after_shared();
        }
      };
    })(this);
    if (!CUI.util.isEmpty(this.__loadFilter)) {
      is_search = true;
    }
    search = this.getCollectionSearchFilter(is_search || !this.hasOwnCollections());
    this.inputFilter.removeClass("ez5-collection-manager-nothing-found");
    if (is_search) {
      ref = Search.getPhrase(this.__loadFilter), str = ref[0], phrase = ref[1];
      if (ez5.version("6")) {
        inputSearch = {
          bool: "should",
          type: "match",
          mode: "wildcard",
          string: str + SearchUtil.ASTERISK
        };
      } else {
        inputSearch = {
          bool: "should",
          type: "match",
          mode: "fulltext",
          phrase: phrase,
          string: str
        };
      }
      search.push({
        type: "complex",
        bool: "must",
        search: [
          inputSearch, {
            type: "complex",
            bool: "should",
            search: [
              {
                type: "in",
                bool: "must",
                fields: ["_level"],
                "in": [2]
              }, {
                type: "in",
                bool: "must",
                fields: ["_owner.user._id"],
                "in": [ez5.session.user.getId()]
              }
            ]
          }
        ]
      });
    }
    searchDeferred = new CUI.Deferred();
    searchAttempt = 0;
    searchNoLimit = (function(_this) {
      return function() {
        var searchPromise;
        searchPromise = ez5.api.search_no_limit({
          handle_error: function(xhr) {
            if (xhr == null) {
              xhr = {};
            }
            if (xhr.status !== 404) {
              return false;
            }
            return true;
          },
          data: {
            debug: "CollectionManagerLoad"
          },
          json_data: {
            type: "collection",
            limit: 100000,
            search: search,
            generate_rights: false,
            sort: _this.getCollectionSortFilter()
          }
        });
        searchPromise.done(searchDeferred.resolve);
        return searchPromise.fail(function(xhr) {
          if (xhr.status === 404 && searchAttempt < 10) {
            searchAttempt++;
            return CUI.setTimeout({
              ms: 1000,
              call: function() {
                searchNoLimit();
              }
            });
          } else {
            return searchDeferred.reject(xhr);
          }
        });
      };
    })(this);
    searchNoLimit();
    searchDeferred.promise().always((function(_this) {
      return function() {
        return _this.inputFilter.enable();
      };
    })(this)).fail((function(_this) {
      return function(xhr) {
        _this.inputFilter.addClass("ez5-collection-manager-nothing-found");
        return dfr.reject(xhr);
      };
    })(this)).done((function(_this) {
      return function(data) {
        if (load_counter !== _this.__load_counter) {
          return;
        }
        return load_objecttypes().done(function(objecttype_collections) {
          return read_search_response(data, objecttype_collections);
        }).fail(dfr.reject);
      };
    })(this));
    return dfr.promise();
  };

  CollectionManager.prototype.initPanels = function() {
    this.trees = {};
    this.inputFilter = ListViewEditTree.getFilterManager(this.getTreeFilter());
    this.colPanels = null;
    this.searchPanels = null;
    this.__paneCollectionList.empty("center");
    this.paneForPanels = new CUI.SimplePane({
      "class": "ez5-collection-manager-pane-panels",
      content: this.inputFilter,
      footer_left: (function(_this) {
        return function() {
          if (!_this.hasButtons()) {
            return;
          }
          if (!_this.hasOwnCollections()) {
            return;
          }
          return [_this.plusButton, _this.minusButton];
        };
      })(this),
      footer_right: (function(_this) {
        return function() {
          if (!_this.hasButtons()) {
            return;
          }
          return [_this.refreshButton];
        };
      })(this)
    });
    return this.__paneCollectionList.append(this.paneForPanels, "center");
  };

  CollectionManager.prototype.getColPanels = function() {
    if (!this.colPanels) {
      this.colPanels = new CUI.Block({
        text: $$("collection.manager.block.collection"),
        "class": "ez5-collection-manager-col-panels",
        padded: false,
        level: 3,
        appearance: "muted"
      });
      this.paneForPanels.append(this.colPanels, "center");
    }
    return this.colPanels;
  };

  CollectionManager.prototype.getSearchPanels = function() {
    if (!this.searchPanels) {
      this.searchPanels = new CUI.Block({
        text: $$("collection.manager.block.search"),
        "class": "ez5-collection-manager-search-panels",
        padded: false,
        level: 3,
        appearance: "muted"
      });
      this.paneForPanels.append(this.searchPanels, "center");
    }
    return this.searchPanels;
  };

  CollectionManager.prototype.__sharedCollectionsLoadPage = function(page) {
    var col, panel, panelHeight;
    this.__sharedCollectionsNavigationToolbar.disable();
    this.__sharedCollectionsNavigationOffset = CollectionManager.SHARED_COLLECTIONS_PAGE_SIZE * page;
    col = this.trees["shared_collection"].root;
    panel = this.trees["shared_collection"].__panel;
    panelHeight = panel.DOM.offsetHeight;
    CUI.dom.setStyle(panel, {
      height: panelHeight
    });
    return col.getChildren().done((function(_this) {
      return function(nodes) {
        var i, len, node;
        for (i = 0, len = nodes.length; i < len; i++) {
          node = nodes[i];
          if (typeof node.setManager === "function") {
            node.setManager(col.getManager());
          }
        }
        _this.trees["shared_collection"].load_data(nodes).done(function() {
          CUI.dom.setStyle(panel, {
            height: ""
          });
          _this.__sharedCollectionsNavigationToolbar.enable();
          return _this.__sharedCollectionsNavigationToolbar.__update();
        });
      };
    })(this));
  };

  CollectionManager.prototype.addPanel = function(collection, name, updatePanel) {
    var container, load_panel, opts, p;
    if (updatePanel == null) {
      updatePanel = false;
    }
    CUI.util.assert(collection instanceof CUI.ListViewTreeNode, "CollectionManager.addPanel", "Collection must be ListViewTreeNode");
    switch (name) {
      case "own_collection":
      case "shared_collection":
        container = this.getColPanels();
        break;
      case "search_collection":
        container = this.getSearchPanels();
        break;
      default:
        container = this.getSearchPanels();
    }
    collection.setFather(null);
    if (this.trees[name] && !updatePanel) {
      p = this.trees[name].__panel;
      p.close();
      p.__activations = 0;
    } else {
      if (this.trees[name] && this.trees[name].__panel) {
        CUI.dom.remove(this.trees[name].__panel.DOM);
        delete this.trees[name];
      }
      load_panel = (function(_this) {
        return function(p2) {
          var col;
          col = _this.trees[name].root;
          if (col.children) {
            return CUI.resolvedPromise();
          }
          p2.button.setLoading(true);
          return col.getChildren().always(function() {
            return p2.button.setLoading(false);
          }).done(function(nodes) {
            var i, len, node;
            if (collection._navigation) {
              p2.prepend(collection._navigation, "content");
            }
            if (CUI.util.isEmpty(nodes)) {
              p2.setContent(new CUI.EmptyLabel({
                text: $$("collection.manager.objecttype_collection.empty")
              }));
              return;
            }
            for (i = 0, len = nodes.length; i < len; i++) {
              node = nodes[i];
              if (typeof node.setManager === "function") {
                node.setManager(col.getManager());
              }
            }
            return _this.trees[name].load_data(nodes);
          });
        };
      })(this);
      p = new CUI.Panel({
        text: collection.renderNameAsText(),
        radio: collection.renderNameAsText(),
        ui: "collection.manager.panel:" + ((typeof collection.getId === "function" ? collection.getId() : void 0) || name),
        icon_closed: 'fa-chevron-right',
        icon_opened: 'fa-chevron-down',
        onFirstActivate: (function(_this) {
          return function(p2, flags, event) {
            return load_panel(p2);
          };
        })(this)
      });
      if (name === "own_collection") {
        new CUI.Droppable({
          element: p.panel.get("header"),
          dropHelper: true,
          drop: (function(_this) {
            return function(ev, info) {
              var collectionStorable, rootNode;
              rootNode = _this.trees[name].root;
              collectionStorable = info.globalDrag.collectionStorable;
              if (!collectionStorable) {
                return CollectionManager.__super__.addPanel.call(_this, ev, info);
              }
              if (rootNode === collectionStorable.getFather()) {
                return;
              }
              collectionStorable.loadFromDb().done(function() {
                var sd;
                sd = collectionStorable.getSaveData();
                sd.collection._id_parent = typeof rootNode.getId === "function" ? rootNode.getId() : void 0;
                return collectionStorable.save(ev, sd).done(function() {
                  collectionStorable.remove(false, false);
                  return rootNode.addChild(collectionStorable);
                });
              });
            };
          })(this)
        });
      }
      p.__load = (function(_this) {
        return function() {
          return load_panel(p);
        };
      })(this);
      container.appendContent(p);
    }
    opts = {
      cols: ["maximize", "auto"],
      focusable: true,
      no_header: true,
      maximize_horizontal: true,
      maximize_vertical: false,
      rowMove: false,
      root: collection,
      colClasses: ["ez5-collection-manager-column-main", "ez5-collection-manager-column-utils ez5-list-view-column-count"],
      selectableRows: true,
      onBeforeSelect: (function(_this) {
        return function() {
          var ref;
          return (ref = _this.getSelectedCollection()) != null ? ref.deselect() : void 0;
        };
      })(this),
      onSelect: (function(_this) {
        return function() {
          _this.onSelect();
          _this.setStatus();
          _this._mainLayout.addClass("ez5-finder--folder-selected");
          p.open();
          return _this.__triggerResizePaneEvents();
        };
      })(this),
      onDeselect: (function(_this) {
        return function() {
          _this.onDeselect();
          _this.setStatus();
          _this._mainLayout.removeClass("ez5-finder--folder-selected");
          CUI.Events.trigger({
            type: "content-resize",
            node: _this._mainLayout
          });
          return _this.__triggerResizePaneEvents();
        };
      })(this)
    };
    this.trees[name] = new ListViewEditTree(opts);
    this.trees[name].__panel = p;
    p.setContent(this.trees[name].render());
    collection.getRoot().setTree(this.trees[name]);
    if (collection.children) {
      this.trees[name].load_data(collection.children);
    }
    if (collection.do_open) {
      p.open();
    }
    return p;
  };

  CollectionManager.prototype.getSearchObjectypes = function() {
    return this.getSearch().getSearchObjecttypes(false);
  };

  CollectionManager.prototype.getDisplayNameKeyForSharedCollections = function() {
    return "collection.manager.shared_collections";
  };

  CollectionManager.prototype.getDisplayNameKeyForOwnCollections = function() {
    return "collection.manager.own_collections";
  };

  CollectionManager.prototype.getCollectionSelection = function() {
    CUI.util.assert(this.__collectionSelection, "CollectionManager.getCollectionSelection", "There is no selection collection.", {
      opts: this.opts
    });
    return this.__collectionSelection;
  };

  CollectionManager.prototype.addCollection = function(c, father_node) {
    if (father_node == null) {
      father_node = this.getTopCreateCollection();
    }
    CUI.util.assert(father_node instanceof CollectionStorable, "CollectionManager.addCollection", "Father needs to be instance of CollectionStorable, and have an ID.", {
      father_node: father_node
    });
    CUI.util.assert(c instanceof CollectionStorable, "CollectionManager.addCollection", "Collection needs to be instance of CollectionStorable.", {
      collection: c
    });
    c.getData().collection._id_parent = father_node.getId();
    c.setManager(this);
    if (!father_node.getTree().__panel) {
      CUI.util.assert(false, "CollectionManager.addCollection", "This should not happen, the father_node should have a panel.", {
        father_node: father_node
      });
      return;
    }
    father_node.getTree().__panel.open();
    return this.__callFuncOnNode("openUpwards", father_node.addChild(c));
  };

  CollectionManager.prototype.__callFuncOnNode = function(func, promise) {
    var dfr;
    dfr = new CUI.Deferred();
    promise.fail(dfr.reject).done((function(_this) {
      return function(node) {
        return node[func]().fail(dfr.reject).done(function(node) {
          return dfr.resolve(node);
        });
      };
    })(this));
    return dfr.promise();
  };

  CollectionManager.prototype.newCollection = function(cls, father_node, data) {
    var c;
    if (data == null) {
      data = {};
    }
    c = new cls({
      manager: this
    });
    c.setData({
      collection: data
    });
    return this.__callFuncOnNode("edit", this.addCollection(c, father_node));
  };

  CollectionManager.prototype.__calculateSharedRecursiveCounts = function(collections) {
    var collection, i, len, recursiveCount;
    if (!collections || collections.length === 0) {
      return;
    }
    for (i = 0, len = collections.length; i < len; i++) {
      collection = collections[i];
      if (collection instanceof CollectionStorable) {
        recursiveCount = this.__calculateRecursiveCountForCollection(collection);
        collection.setSharedRecursiveCount(recursiveCount);
      }
      if (collection.children) {
        this.__calculateSharedRecursiveCounts(collection.children);
      }
    }
  };

  CollectionManager.prototype.__calculateRecursiveCountForCollection = function(collection) {
    var child, i, len, ref, totalCount;
    totalCount = collection.data._count || 0;
    if (collection.children) {
      ref = collection.children;
      for (i = 0, len = ref.length; i < len; i++) {
        child = ref[i];
        if (child instanceof CollectionStorable) {
          totalCount += this.__calculateRecursiveCountForCollection(child);
        }
      }
    }
    return totalCount;
  };

  CollectionManager.prototype.addStoredSearch = function(c) {
    var father_node, ref;
    father_node = this.getTopCreateCollection();
    if (!father_node && !this.hasOwnCollections() && ((ref = this.__ownCollection) != null ? typeof ref.isCreateChildAllowed === "function" ? ref.isCreateChildAllowed() : void 0 : void 0)) {
      father_node = this.__ownCollection;
    }
    CUI.util.assert(c instanceof CollectionStoredSearch, "CollectionManager.addStoredSearch", "Collection needs to be instance of CollectionStoredSearch, and have an ID.", {
      father_node: father_node
    });
    CUI.util.assert(father_node instanceof CollectionStorable, "CollectionManager.addCollection", "Father needs to be instance of CollectionStorable, and have an ID.", {
      father_node: father_node
    });
    c.getData().collection._id_parent = father_node.getId();
    c.setManager(this);
    this.__searchCollection.getTree().__panel.open();
    return this.__callFuncOnNode("edit", this.__searchCollection.addChild(c));
  };

  return CollectionManager;

})(CUI.DOMElement);

ez5.session_ready(function() {
  return ez5.rootMenu.registerAppLoader(new CollectionManagerLoader());
});

CollectionManagerLoader = (function(superClass) {
  extend(CollectionManagerLoader, superClass);

  function CollectionManagerLoader() {
    return CollectionManagerLoader.__super__.constructor.apply(this, arguments);
  }

  CollectionManagerLoader.prototype.findAppByLocation = function(location, apps) {
    var app, i, len;
    if (location.pathname.match("^/collection/(.*)")) {
      for (i = 0, len = apps.length; i < len; i++) {
        app = apps[i];
        if ((typeof app.getPathname === "function" ? app.getPathname() : void 0) === "/main") {
          return CUI.resolvedPromise(app);
        }
      }
    }
    return CUI.rejectedPromise();
  };

  return CollectionManagerLoader;

})(RootMenuAppLoader);
// Generated by CoffeeScript 1.12.7
var SearchCollection,
  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;

SearchCollection = (function(superClass) {
  extend(SearchCollection, superClass);

  function SearchCollection() {
    return SearchCollection.__super__.constructor.apply(this, arguments);
  }

  SearchCollection.prototype.initOpts = function() {
    SearchCollection.__super__.initOpts.call(this);
    return this.addOpts({
      collection: {
        mandatory: true,
        check: CollectionWithDetail
      },
      container: {
        check: function(v) {
          return CUI.util.isElement(v);
        }
      }
    });
  };

  SearchCollection.prototype.readOpts = function() {
    SearchCollection.__super__.readOpts.call(this);
    this.collection = this._collection;
    this.container = this._container;
    return this.tempCollection = this.getNewTempCollection();
  };

  SearchCollection.prototype.hasSearchBasics = function() {
    return false;
  };

  SearchCollection.prototype.updateInfo = function() {
    var btns;
    this.__infoBlock.setContent(this.collection.getInfo());
    this.__infoBlock.setText(this.collection.renderNameAsText());
    btns = Toolbox.mergeFlyoutButtons(this.tempCollection.getButtons(), this.collection.getButtons());
    this.getButtonToolbar().replace(btns, "right");
    return this;
  };

  SearchCollection.prototype.getSearchInput = function() {};

  SearchCollection.prototype.getNewTempCollection = function() {
    return new CollectionMemory({
      sidebar: this._collection.getManager().getSidebar(),
      search: this,
      manager: this._collection.getManager(),
      parent_collection: this._collection,
      preventBlurOnSelect: true
    });
  };

  SearchCollection.prototype.init = function() {
    var buttonbar;
    this.__infoBlock = new CUI.Block({
      text: "..."
    });
    buttonbar = new CUI.Buttonbar({
      buttons: [
        this.collection.getManager().getSplitButton(), new LocaButton({
          loca_key: "search.collection.collection.deselect",
          "class": "ez5-collection-manager-deselect-button",
          icon: "remove",
          onClick: (function(_this) {
            return function() {
              _this.collection.getManager().setSplitMode(false);
              return _this.collection.deselect();
            };
          })(this)
        })
      ]
    });
    this.__pane = new CUI.Pane({
      "class": "ez5-search-collection-pane cui-pane--window",
      top: {
        "class": "ez5-search-collection-pane-top",
        content: [
          new CUI.PaneHeader({
            auto_buttonbar: false,
            left: {
              content: new LocaLabel({
                loca_key: "search.collection.title",
                ui: "search.collection.title"
              })
            },
            right: {
              content: buttonbar
            }
          }), this.__infoBlock, this.__buttonToolbar = new CUI.PaneToolbar({
            "class": "ez5-search-collection-toolbar"
          })
        ]
      },
      center: {
        "class": "ez5-search-collection-center"
      }
    });
    this.rc = this.__pane.center();
    CUI.Events.listen({
      node: this.__pane,
      type: "toolbox",
      call: (function(_this) {
        return function(ev, info) {
          info.tools.push.apply(info.tools, _this._collection.getCurrentTools());
          return ev.stopPropagation();
        };
      })(this)
    });
    CUI.dom.append(this.container, this.__pane.DOM);
    this.registerResultContainer(this.rc);
    this.addResultSearchManager();
    this.addSearchManager(new CollectionSearchManager({
      toolbox_group: "collection",
      collection: this.tempCollection
    }));
    this.registerKeyboardShortcuts(this._container);
    return CUI.chainedCall(SearchCollection.__super__.init.call(this), (function(_this) {
      return function() {
        return _this.execute();
      };
    })(this), (function(_this) {
      return function() {
        _this.updateInfo();
        return _this.collection.on({
          type: ["insert", "remove", "update"],
          call: function(ev, info) {
            if (info.skip_update) {
              _this.updateInfo();
            }
          }
        });
      };
    })(this), (function(_this) {
      return function() {
        CUI.Events.trigger({
          node: _this.rc,
          type: "content-resize"
        });
        return _this.tempCollection.on({
          type: ["insert", "remove", "update"],
          call: function(ev, info) {
            _this.updateInfo();
          }
        });
      };
    })(this));
  };

  SearchCollection.prototype.CSSVariants = function() {
    return [
      {
        type: "choice",
        classes: [
          {
            label: "main.search.view.result.mini",
            "class": "result-standard-mini"
          }, {
            label: "main.search.view.result.midi",
            "class": "result-standard-midi"
          }
        ]
      }
    ];
  };

  SearchCollection.prototype.addResultSearchManager = function() {
    var managers, ref, ref1, ref2, sel_opts;
    if (this.tempCollection) {
      sel_opts = {
        collection: this.tempCollection
      };
    }
    managers = [
      new ResultStandard({
        ui: "search.collection.result.standard",
        container: this.getResultContainer(),
        page_size: 100,
        selectable_opts: sel_opts
      })
    ];
    if (ez5.version("6")) {
      managers.push(new ResultDetail({
        ui: "search.collection.result.detail",
        container: this.getResultContainer(),
        page_size: 5,
        selectable_opts: sel_opts
      }));
      managers.push(new ResultText({
        container: this.getResultContainer(),
        selectable_opts: sel_opts,
        page_size: 10
      }));
      managers.push(new ez5.ResultTableV2({
        filter_tree: true,
        container: this.getResultContainer(),
        selectable_opts: sel_opts
      }));
    }
    this.__resultManager = new ResultManager({
      default_view: (ref = this.collection) != null ? (ref1 = ref.data.collection) != null ? (ref2 = ref1.webfrontend_props) != null ? ref2.default_view : void 0 : void 0 : void 0,
      pref: "search_collection_view_data",
      managers: managers
    });
    this.addSearchManager(this.__resultManager);
    return this;
  };

  SearchCollection.prototype.getButtonToolbar = function() {
    return this.__buttonToolbar;
  };

  SearchCollection.prototype.getDetailShareUrl = function(id) {
    return window.easydb_base_prefix + ("#/detail/" + id);
  };

  SearchCollection.prototype.destroy = function() {
    if (this.__pane) {
      CUI.Events.ignore({
        node: this.__pane
      });
    }
    return SearchCollection.__super__.destroy.call(this);
  };

  SearchCollection.prototype.getSearchObjecttypes = function() {
    return CUI.util.assert(false, (CUI.util.getObjectClass(this)) + ".getSearchObjecttypes", "Unsupported by most Collections, thats why this is not implemented.");
  };

  SearchCollection.prototype.getSearchCollection = function() {
    return this._collection;
  };

  SearchCollection.prototype.getCollection = function() {
    return this.tempCollection;
  };

  SearchCollection.prototype.addToRequest = function(request) {
    request.objecttypes = void 0;
    this.collection.addToRequest(request);
    SearchCollection.__super__.addToRequest.call(this, request);
  };

  SearchCollection.prototype.executeSearch = function(req_data) {
    var fillDfr, promise, ref, rm;
    if (CUI.util.isFunction(this.collection.executeSearch)) {
      promise = this.collection.executeSearch(req_data);
      rm = (ref = this.__resultManager) != null ? ref.current_result_manager : void 0;
      if (rm instanceof ResultText || rm instanceof ez5.ResultTableV2) {
        fillDfr = new CUI.Deferred();
        promise.done((function(_this) {
          return function(data) {
            if (data.count > 0) {
              _this.__searchCollectionObjects(data, req_data).done(function(searchResult) {
                return fillDfr.resolve(searchResult);
              }).fail(function(err) {
                return fillDfr.reject(err);
              });
              return fillDfr.promise();
            } else {
              return fillDfr.resolve(data);
            }
          };
        })(this));
        return fillDfr.promise();
      } else {
        return promise;
      }
    } else {
      return SearchCollection.__super__.executeSearch.call(this, req_data);
    }
  };

  SearchCollection.prototype.__searchCollectionObjects = function(collection_objects, original_request_data) {
    var dfr, global_ids, req_data;
    dfr = new CUI.Deferred();
    global_ids = collection_objects.objects.map((function(_this) {
      return function(obj) {
        return obj._global_object_id;
      };
    })(this));
    req_data = {
      aggregations: original_request_data.aggregations,
      search: [
        {
          type: "in",
          fields: ["_global_object_id"],
          "in": global_ids
        }
      ],
      format: "long",
      generate_rights: ez5.version("6"),
      offset: 0,
      limit: global_ids.length
    };
    ez5.api.search({
      data: {
        debug: "searchCollectionObjects"
      },
      json_data: req_data
    }).done((function(_this) {
      return function(data) {
        var sorted_objects;
        sorted_objects = global_ids.map(function(id) {
          var i, len, obj, ref;
          ref = data.objects;
          for (i = 0, len = ref.length; i < len; i++) {
            obj = ref[i];
            if (obj._global_object_id === id) {
              return obj;
            }
          }
        });
        collection_objects.objects = sorted_objects;
        if (data.aggregations) {
          collection_objects.aggregations = data.aggregations;
        }
        return dfr.resolve(collection_objects);
      };
    })(this)).fail((function(_this) {
      return function(err) {
        return dfr.reject(err);
      };
    })(this));
    return dfr.promise();
  };

  return SearchCollection;

})(Search);
// Generated by CoffeeScript 1.12.7
var SearchCollectionHeadless,
  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;

SearchCollectionHeadless = (function(superClass) {
  extend(SearchCollectionHeadless, superClass);

  function SearchCollectionHeadless() {
    return SearchCollectionHeadless.__super__.constructor.apply(this, arguments);
  }

  SearchCollectionHeadless.prototype.readOpts = function() {
    SearchCollectionHeadless.__super__.readOpts.call(this);
    return this.init();
  };

  SearchCollectionHeadless.prototype.initOpts = function() {
    SearchCollectionHeadless.__super__.initOpts.call(this);
    return this.addOpts({
      request: {
        check: "PlainObject"
      }
    });
  };

  SearchCollectionHeadless.prototype.getNewTempCollection = function() {};

  SearchCollectionHeadless.prototype.init = function() {
    return Search.prototype.init.call(this);
  };

  SearchCollectionHeadless.prototype.executeSearch = function() {
    return Search.prototype.executeSearch.apply(this, arguments);
  };

  SearchCollectionHeadless.prototype.addToRequest = function(request) {
    var key, ref, value;
    SearchCollectionHeadless.__super__.addToRequest.call(this, request);
    ref = this._request;
    for (key in ref) {
      value = ref[key];
      if (request[key]) {
        CUI.util.mergeMap(request[key], value);
      } else {
        request[key] = value;
      }
    }
    return request;
  };

  return SearchCollectionHeadless;

})(SearchCollection);
// Generated by CoffeeScript 1.12.7
var DetailHierarchyList,
  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,
  slice = [].slice;

DetailHierarchyList = (function(superClass) {
  extend(DetailHierarchyList, superClass);

  function DetailHierarchyList() {
    return DetailHierarchyList.__super__.constructor.apply(this, arguments);
  }

  DetailHierarchyList.prototype.initOpts = function() {
    DetailHierarchyList.__super__.initOpts.call(this);
    return this.addOpts({
      sidebar: {
        check: Sidebar
      },
      container: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isElement(v);
        }
      },
      isSelectable: {
        check: Function
      }
    });
  };

  DetailHierarchyList.prototype.readOpts = function() {
    DetailHierarchyList.__super__.readOpts.call(this);
    return this.__collection = new DetailHierarchyListCollection({
      sidebar: this._sidebar,
      preventBlurOnSelect: true
    });
  };

  DetailHierarchyList.prototype.hasSearchBasics = function() {
    return false;
  };

  DetailHierarchyList.prototype.init = function() {
    var throttleActive;
    this.__resultList = new DetailHierarchyListResult({
      container: this._container,
      show_navigation: false,
      open_nodes: false,
      hierarchyList: this,
      tree_opts: {
        "class": "detail-hierarchy-list"
      },
      selectable_opts: {
        collection: this.__collection,
        draggable: false,
        lasso: false,
        toolbox: false,
        select: true,
        dblclick: false,
        deselect: false,
        isSelectable: this._isSelectable
      }
    });
    this.__resultList.setData(this.__resultList.getViewDataDefault());
    throttleActive = false;
    this.__keyboardListener = CUI.Events.listen({
      type: ["keydown"],
      node: this._container,
      call: (function(_this) {
        return function(event) {
          var active, activeIndex, key, ref, ref1, ref2, ref3, rows;
          if (!throttleActive) {
            throttleActive = true;
            key = event.key();
            if (key !== "ArrowLeft" && key !== "ArrowRight" && key !== "ArrowUp" && key !== "ArrowDown" && key !== "Home" && key !== "End") {
              return;
            }
            event.preventDefault();
            rows = slice.call(CUI.dom.matchSelector(_this._container, ".cui-list-view-row-selectable[tabindex]"));
            active = rows.find(function(row) {
              return document.hasFocus() && row === document.activeElement;
            }) || rows.find(function(row) {
              return row.classList.contains("cui-selected");
            });
            if (!active) {
              return;
            }
            activeIndex = rows.findIndex(function(row) {
              return row === active;
            });
            switch (key) {
              case "ArrowUp":
                if ((ref = rows[activeIndex - 1]) != null) {
                  ref.focus();
                }
                break;
              case "ArrowDown":
                if ((ref1 = rows[activeIndex + 1]) != null) {
                  ref1.focus();
                }
                break;
              case "Home":
                if ((ref2 = rows[0]) != null) {
                  ref2.focus();
                }
                break;
              case "End":
                if ((ref3 = rows.at(-1)) != null) {
                  ref3.focus();
                }
            }
            return setTimeout(function() {
              return throttleActive = false;
            }, 100);
          }
        };
      })(this)
    });
    this.registerResultContainer(this._container);
    this.addSearchManager(this.__resultList);
    if (!this.__sortManager) {
      this.addSearchManager(new SortManagerStandard());
    }
    return DetailHierarchyList.__super__.init.call(this);
  };

  DetailHierarchyList.prototype.getObject = function() {
    return this.__object;
  };

  DetailHierarchyList.prototype.loadObject = function(__object) {
    var co;
    this.__object = __object;
    co = this.__object.getCollectionObject();
    if (this.__collection.objectIdx(co) === -1) {
      this.__collection.insertObjects([co], null, {
        skip_update: true
      });
      this.otm = new ObjecttypeManager();
      this.otm.addObjecttypes((function(_this) {
        return function(table) {
          return table.name() === _this.__object.objecttype();
        };
      })(this));
      this.execute();
    }
  };

  DetailHierarchyList.prototype.getSearchObjecttypes = function() {
    return this.otm.objecttypes;
  };

  DetailHierarchyList.prototype.getObjecttype = function() {
    return this.getSearchObjecttypes()[0];
  };

  DetailHierarchyList.prototype.addToRequest = function(request) {
    var add_reverse_hierachy_sort, objecttype, path, searchField;
    objecttype = this.getObjecttype().name();
    path = this.__object.getPathData(false);
    if (this.__object.mask.isPolyhierarchy()) {
      path = path.reduce(((function(_this) {
        return function(a, b) {
          return a.concat(b);
        };
      })(this)), []);
    }
    if (path.length > 0) {
      if (this.__object.mask.isPolyhierarchy()) {
        searchField = objecttype + "._parents." + objecttype + "._id";
        path = path.map(function(parent) {
          return parent[objecttype]._id;
        });
      } else {
        searchField = objecttype + "._id_parent";
        path = [this.__object.getParentId()];
      }
      request.search = [
        {
          type: "in",
          bool: "must",
          fields: [searchField],
          "in": path
        }
      ];
    } else {
      request.search = [
        {
          type: "in",
          bool: "must",
          fields: [objecttype + "._id"],
          "in": [this.__object.id()]
        }
      ];
    }
    add_reverse_hierachy_sort = (function(_this) {
      return function(r) {
        var reverse_hierarchical;
        if (ez5.version("6")) {
          reverse_hierarchical = _this.__object.mask.getReverseLinkedTableFields("detail").some(function(f) {
            return f.isHierarchical();
          });
          if (reverse_hierarchical) {
            if (r.sort == null) {
              r.sort = [];
            }
            r.sort.splice(0, 0, {
              field: objecttype + "._parent_child_idx",
              order: "asc"
            });
          }
        }
        return r;
      };
    })(this);
    if (this.__sortManager) {
      request = this.__sortManager.addToRequest(request);
      this.opts["onAddToRequest"] = (function(_this) {
        return function(r) {
          r = _this.__sortManager.addToRequest(r);
          return add_reverse_hierachy_sort(r);
        };
      })(this);
    }
    request = add_reverse_hierachy_sort(request);
    return DetailHierarchyList.__super__.addToRequest.call(this, request);
  };

  DetailHierarchyList.prototype.showResult = function(request, data) {
    var _path, i, j, len, len1, object, pathsWithSelectedObject, ref, ref1, selectedObjectPaths;
    if (!this.__object.mask.isPolyhierarchy()) {
      return DetailHierarchyList.__super__.showResult.call(this, request, data);
    }
    selectedObjectPaths = this.__object.getPathData();
    if (selectedObjectPaths.length === 0) {
      return DetailHierarchyList.__super__.showResult.call(this, request, data);
    }
    ref = data.objects;
    for (i = 0, len = ref.length; i < len; i++) {
      object = ref[i];
      if (object._global_object_id === this.__object.getGlobalObjectId()) {
        continue;
      }
      if (!object._paths || object._paths.length === 0) {
        continue;
      }
      pathsWithSelectedObject = [];
      ref1 = object._paths;
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        _path = ref1[j];
        if (_path.some((function(_this) {
          return function(_object) {
            var k, len2, selectedObjectPath;
            for (k = 0, len2 = selectedObjectPaths.length; k < len2; k++) {
              selectedObjectPath = selectedObjectPaths[k];
              if (selectedObjectPath.some(function(o) {
                return o._global_object_id === _object._global_object_id;
              })) {
                return true;
              }
            }
            return false;
          };
        })(this))) {
          pathsWithSelectedObject.push(_path);
        }
      }
      object._paths = pathsWithSelectedObject;
    }
    return DetailHierarchyList.__super__.showResult.call(this, request, data);
  };

  DetailHierarchyList.prototype.destroy = function() {
    var ref, ref1;
    if ((ref = this.__collection) != null) {
      ref.destroy();
    }
    delete this.__collection;
    if ((ref1 = this.__keyboardListener) != null) {
      ref1.destroy();
    }
    return DetailHierarchyList.__super__.destroy.call(this);
  };

  return DetailHierarchyList;

})(Search);
// Generated by CoffeeScript 1.12.7
var DetailHierarchyListCollection,
  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;

DetailHierarchyListCollection = (function(superClass) {
  extend(DetailHierarchyListCollection, superClass);

  function DetailHierarchyListCollection() {
    return DetailHierarchyListCollection.__super__.constructor.apply(this, arguments);
  }

  DetailHierarchyListCollection.prototype.isSingleMode = function() {
    return true;
  };

  DetailHierarchyListCollection.prototype.__registerFullScreenEvents = function() {};

  DetailHierarchyListCollection.prototype.__loadSidebar = function(co, opts) {
    DetailHierarchyListCollection.__super__.__loadSidebar.call(this, co, opts);
    if (co) {
      return CUI.Events.trigger({
        type: "focus-sidebar-selection",
        node: window,
        info: {
          global_object_id: co.getGlobalObjectId()
        }
      });
    }
  };

  return DetailHierarchyListCollection;

})(CollectionMemory);
// Generated by CoffeeScript 1.12.7
var DetailHierarchyListResult,
  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;

DetailHierarchyListResult = (function(superClass) {
  extend(DetailHierarchyListResult, superClass);

  function DetailHierarchyListResult() {
    return DetailHierarchyListResult.__super__.constructor.apply(this, arguments);
  }

  DetailHierarchyListResult.prototype._page_size = 500;

  DetailHierarchyListResult.prototype.initOpts = function() {
    DetailHierarchyListResult.__super__.initOpts.call(this);
    return this.addOpts({
      hierarchyList: {
        mandatory: true,
        check: DetailHierarchyList
      }
    });
  };

  DetailHierarchyListResult.prototype.showResult = function(request, data) {
    var dfr, i, index, isPolyhierarchy, len, loadPath, object, objecttype, path, paths, promises, searchField, topLevelSet;
    promises = [];
    object = this._hierarchyList.getObject();
    isPolyhierarchy = object.mask.isPolyhierarchy();
    this.__level_count = {};
    loadPath = (function(_this) {
      return function(path, searchField) {
        var i, level, maxLevel, minLength, obj, ref, results;
        if (isPolyhierarchy) {
          minLength = 0;
          maxLevel = path.length - 1;
        } else {
          minLength = 1;
          maxLevel = path.length - 2;
        }
        if (path.length > minLength) {
          results = [];
          for (level = i = 0, ref = maxLevel; 0 <= ref ? i <= ref : i >= ref; level = 0 <= ref ? ++i : --i) {
            obj = path[level];
            if (isPolyhierarchy && !CUI.util.isNull(_this.__level_count[obj._global_object_id])) {
              continue;
            }
            results.push((function(obj, level) {
              var ancestors_request, promise;
              ancestors_request = {
                objecttypes: [obj._objecttype],
                format: "standard",
                offset: 0,
                limit: _this.getPageSize(),
                search: [
                  {
                    type: "in",
                    bool: "must",
                    fields: [searchField],
                    "in": [obj[obj._objecttype]._id]
                  }
                ]
              };
              if (ez5.version("6")) {
                ancestors_request.sort = request.sort;
              }
              promise = ez5.api.search({
                data: {
                  debug: "DetailHierarchyList.showResult.loadAncestors"
                },
                json_data: ancestors_request
              }).done(function(_data) {
                var _obj, j, len, ref1;
                level++;
                if (isPolyhierarchy) {
                  _this.__level_count[obj._global_object_id] = _data.count;
                } else {
                  ref1 = _data.objects;
                  for (j = 0, len = ref1.length; j < len; j++) {
                    _obj = ref1[j];
                    data.objects.push(_obj);
                  }
                  _this.__level_count[level] = _data.count;
                }
              });
              return promises.push(promise);
            })(obj, level));
          }
          return results;
        }
      };
    })(this);
    objecttype = object.getData()._objecttype;
    if (isPolyhierarchy) {
      paths = object.getPathData();
      searchField = objecttype + "._parents." + objecttype + "._id";
      topLevelSet = new Set();
      for (index = i = 0, len = paths.length; i < len; index = ++i) {
        path = paths[index];
        topLevelSet.add(path[0]._global_object_id);
        loadPath(path, searchField, index);
      }
      this.__level_count[0] = topLevelSet.size;
    } else {
      path = object.getPathData(false);
      this.__level_count[data.objects[0]._path.length - 1] = data.count;
      searchField = objecttype + "._id_parent";
      loadPath(path, searchField);
    }
    dfr = new CUI.Deferred();
    CUI.when(promises).fail(dfr.reject).done((function(_this) {
      return function() {
        var gid;
        gid = object.getGlobalObjectId();
        if (CUI.util.idxInArray(null, data.objects, function(obj) {
          return obj._global_object_id === gid;
        }) === -1) {
          data.objects.push(object.getData());
        }
        data.limit = Math.max(data.objects.length, data.limit);
        CUI.decide(DetailHierarchyListResult.__super__.showResult.call(_this, request, data)).fail(dfr.reject).done(dfr.resolve);
      };
    })(this));
    return dfr.promise();
  };

  DetailHierarchyListResult.prototype.getNodesFromDataTree = function(data) {
    var nodes;
    nodes = DetailHierarchyListResult.__super__.getNodesFromDataTree.call(this, data);
    this.sortNodesAndAddMoreButton(nodes);
    return nodes;
  };

  DetailHierarchyListResult.prototype.getNodesFromData = function(data) {
    var nodes;
    this._open_nodes = true;
    return nodes = this.getNodesFromDataTree(data);
  };

  DetailHierarchyListResult.prototype.sortNodesAndAddMoreButton = function(nodes, level, parentNode) {
    var i, len, levelCountKey, node;
    if (level == null) {
      level = 0;
    }
    if (parentNode == null) {
      parentNode = null;
    }
    if (!(nodes != null ? nodes.length : void 0)) {
      return;
    }
    if (!ez5.version("6")) {
      nodes.sort((function(_this) {
        return function(a, b) {
          var res_a, res_b;
          res_a = a.__resultObject;
          res_b = b.__resultObject;
          return res_a.renderText().localeCompare(res_b.renderText());
        };
      })(this));
    }
    if (level > 0 && this.__isPolyhierarchy()) {
      levelCountKey = parentNode.getTopLevelData()._global_object_id;
    } else {
      levelCountKey = level;
    }
    if (this.__level_count[levelCountKey] > nodes.length) {
      nodes.push(new ResultTableLoadMoreNode({
        offset: 0,
        limit: this.getPageSize(),
        count: this.__level_count[levelCountKey]
      }));
    }
    for (i = 0, len = nodes.length; i < len; i++) {
      node = nodes[i];
      if (node instanceof ResultTableLoadMoreNode) {
        continue;
      }
      this.sortNodesAndAddMoreButton(node.children, level + 1, node);
    }
  };

  DetailHierarchyListResult.prototype.getPageSize = function() {
    return this._page_size;
  };

  DetailHierarchyListResult.prototype.__isPolyhierarchy = function() {
    return this._hierarchyList.getObject().mask.isPolyhierarchy();
  };

  return DetailHierarchyListResult;

})(ResultList);
// Generated by CoffeeScript 1.12.7
var DetailSidebarPlugin,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

DetailSidebarPlugin = (function(superClass) {
  extend(DetailSidebarPlugin, superClass);

  function DetailSidebarPlugin() {
    return DetailSidebarPlugin.__super__.constructor.apply(this, arguments);
  }

  DetailSidebarPlugin.prototype.initOpts = function() {
    DetailSidebarPlugin.__super__.initOpts.call(this);
    return this.addOpts({
      detailSidebar: {
        mandatory: true,
        check: DetailSidebar
      }
    });
  };

  DetailSidebarPlugin.prototype.readOpts = function() {
    DetailSidebarPlugin.__super__.readOpts.call(this);
    this.__active = false;
    return this.registerListeners();
  };

  DetailSidebarPlugin.prototype.registerListeners = function() {
    return CUI.Events.listen({
      type: "detail-sidebar-render-object",
      instance: this._detailSidebar,
      call: (function(_this) {
        return function(ev, info) {
          if (info.detailSidebar !== _this._detailSidebar) {
            return;
          }
          return _this.renderObjectDetailSidebar();
        };
      })(this)
    });
  };

  DetailSidebarPlugin.prototype.render = function() {};

  DetailSidebarPlugin.prototype.renderObject = function() {};

  DetailSidebarPlugin.prototype.renderObjectDetailSidebar = function() {};

  DetailSidebarPlugin.prototype.callback = function(type, info) {};

  DetailSidebarPlugin.prototype.isAvailable = function() {};

  DetailSidebarPlugin.prototype.isFullscreenAvailable = function() {
    return true;
  };

  DetailSidebarPlugin.prototype.isDisabled = function() {
    return false;
  };

  DetailSidebarPlugin.prototype.showDetail = function() {};

  DetailSidebarPlugin.prototype.hideDetail = function() {};

  DetailSidebarPlugin.prototype.prefName = function() {};

  DetailSidebarPlugin.prototype.prefDefault = function() {
    return false;
  };

  DetailSidebarPlugin.prototype.getPane = function() {
    return "top";
  };

  DetailSidebarPlugin.prototype.setButton = function(button) {
    var ref;
    if ((ref = this.__button) != null) {
      ref.destroy();
    }
    this.__button = button;
    return this;
  };

  DetailSidebarPlugin.prototype.setActive = function() {
    var ref;
    this.__active = true;
    if ((ref = this.__getPane()) != null) {
      ref.setAttribute("detail-plugin", CUI.util.toClass(this.getElementClass()));
    }
    return this;
  };

  DetailSidebarPlugin.prototype.setInactive = function() {
    var ref;
    this.__active = false;
    if ((ref = this.__getPane()) != null) {
      ref.removeAttribute("detail-plugin");
    }
    return this;
  };

  DetailSidebarPlugin.prototype.__getPane = function() {
    var panes, ref;
    panes = this._detailSidebar.mainPane.getPanes();
    if (ref = this.getPane(), indexOf.call(panes, ref) >= 0) {
      return this._detailSidebar.mainPane.get(this.getPane());
    }
    return null;
  };

  DetailSidebarPlugin.prototype.isActive = function() {
    return this.__active;
  };

  DetailSidebarPlugin.prototype.getButton = function() {
    return this.__button;
  };

  DetailSidebarPlugin.prototype.getButtonLocaKey = function() {};

  DetailSidebarPlugin.prototype.getCenterContent = function() {};

  DetailSidebarPlugin.prototype.destroy = function() {
    var ref;
    if ((ref = this.__button) != null) {
      ref.destroy();
    }
    delete this.__button;
    return DetailSidebarPlugin.__super__.destroy.call(this);
  };

  return DetailSidebarPlugin;

})(CUI.Plugin);
// Generated by CoffeeScript 1.12.7
var DetailSidebar,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

DetailSidebar = (function(superClass) {
  extend(DetailSidebar, superClass);

  function DetailSidebar() {
    return DetailSidebar.__super__.constructor.apply(this, arguments);
  }

  DetailSidebar.prototype.initOpts = function() {
    DetailSidebar.__super__.initOpts.call(this);
    return this.addOpts({
      asset_browser_idx: {
        check: "Integer"
      },
      sidebar: {
        mandatory: true,
        check: Sidebar
      },
      search: {
        check: Search
      },
      offset: {
        check: function(v) {
          return v >= 0;
        }
      },
      global_object_id: {
        mandatory: true,
        check: String
      },
      next_previous_global_object_ids: {
        check: function(value) {
          return CUI.util.isArray(value) && value.every((function(_this) {
            return function(v) {
              return CUI.util.isString(v);
            };
          })(this));
        }
      },
      wait_for_index: {
        check: Boolean
      }
    });
  };

  DetailSidebar.prototype.readOpts = function() {
    var i, len, plugin, ref;
    DetailSidebar.__super__.readOpts.call(this);
    this.detail_data = {
      mask_name: null
    };
    this.__global_object_id = this._global_object_id;
    this.__asset_browser_idx = this._asset_browser_idx;
    this.__offset = this._offset;
    this.__search = this._search || this._sidebar.getSearch();
    this.__counter = 0;
    this.__plugins = DetailSidebar.plugins.newPlugins({
      detailSidebar: this
    });
    this.__next_previous_global_object_ids = this.__getNextPreviousGlobalObjectIds(this._next_previous_global_object_ids);
    ref = this.__plugins;
    for (i = 0, len = ref.length; i < len; i++) {
      plugin = ref[i];
      ez5.session.addCookieOnlyPref(plugin.prefName(), plugin.prefDefault());
    }
    return this;
  };

  DetailSidebar.prototype.triggerCallback = function(type, info) {
    if (info == null) {
      info = {};
    }
    info.detailSidebar = this;
    info.object = this.object;
    return CUI.Events.trigger({
      type: type,
      info: info
    });
  };

  DetailSidebar.prototype.getShareUrl = function() {
    return DetailSidebar.getDetailShareUrl(this.object, this.getSearch());
  };

  DetailSidebar.getDetailShareUrl = function(object, search) {
    var id, ref;
    if (!object) {
      return null;
    }
    if (!search) {
      return null;
    }
    if (object.getInstance()) {
      return search.getDetailShareUrl(object.getGlobalObjectId());
    }
    if ((ref = ez5.session.getBaseConfig().detail_deep_link) != null ? ref.use_system_object_id : void 0) {
      id = object.getSystemObjectId();
    } else {
      id = object.getUuid();
    }
    return search.getDetailShareUrl(id);
  };

  DetailSidebar.prototype.render = function() {
    var goToTopWrapper, i, len, plugin, ref;
    this.toolbar = new CUI.PaneToolbar({
      "class": "ez5-sidebar-toolbar ez5-detail-sidebar-toolbar"
    });
    this.paneHeader = new CUI.PaneHeader();
    this.mainPane = new CUI.Pane({
      "class": "ez5-detail-main-pane",
      top: {
        "class": "ez5-detail-asset-browser ez5-sidebar-asset-browser",
        flexHandle: {
          hidden: false,
          closed: true,
          state_name: "detail-sidebar"
        }
      }
    });
    this.browserLayout = new CUI.HorizontalLayout({
      "class": "ez5-detail-layout",
      left: {
        "class": "ez5-detail-layout-hierarchy",
        flexHandle: {
          hidden: false,
          closed: true,
          closable: false,
          state_name: "detail-sidebar-hierarchy",
          unit: "%"
        }
      },
      center: {
        content: this.mainPane
      }
    });
    if (ez5.version("6")) {
      this.__goToTopBtn = new LocaButton({
        "class": "cui-button-goto-top cui-disabled",
        loca_key: "general.frontend.gototop.button",
        onClick: (function(_this) {
          return function() {
            if (_this.__scrollDiv) {
              return _this.__scrollDiv.scrollTop = 0;
            }
          };
        })(this)
      });
      goToTopWrapper = new CUI.dom.div("ez5-goto-top");
      CUI.dom.append(goToTopWrapper, this.__goToTopBtn);
    }
    this.__paneFooter = new CUI.PaneFooter({
      "class": "ez5-detail-container-bottom"
    });
    this.container = new CUI.Pane({
      "class": "ez5-detail-container cui-pane--window",
      top: {
        content: [this.paneHeader, this.toolbar]
      },
      center: {
        content: [this.browserLayout, goToTopWrapper]
      },
      bottom: {
        content: this.__paneFooter
      }
    });
    this.__waitBlock = new CUI.WaitBlock({
      ui: "detail.sidebar.wait.block",
      element: this.mainPane.center(),
      text: $$("detail.sidebar.change-history.loading.label")
    });
    EventPoller.listen({
      instance: this,
      filter: (function(_this) {
        return function(event) {
          var currentGlobalObjectId, ref;
          currentGlobalObjectId = (ref = _this.getResultObject()) != null ? ref.getGlobalObjectId() : void 0;
          if (!currentGlobalObjectId) {
            return false;
          }
          return event.global_object_id === currentGlobalObjectId;
        };
      })(this),
      call: (function(_this) {
        return function(events) {
          var event, i, len;
          for (i = 0, len = events.length; i < len; i++) {
            event = events[i];
            switch (event.type) {
              case "OBJECT_DELETE" || "OBJECT_PURGE":
                _this._sidebar.empty();
                _this.__global_object_id = null;
                break;
              case "OBJECT_INDEX":
                _this.load(false);
                break;
              case "OBJECT_UNDELETE":
                return;
            }
          }
        };
      })(this)
    });
    ref = this.__plugins;
    for (i = 0, len = ref.length; i < len; i++) {
      plugin = ref[i];
      plugin.render();
    }
    return this.registerChangeHistoryEvent();
  };

  DetailSidebar.prototype.registerChangeHistoryEvent = function() {
    CUI.Events.listen({
      type: "show-change-history",
      node: this.DOM,
      call: (function(_this) {
        return function(ev, info) {
          var ref;
          if (((ref = _this.object) != null ? typeof ref.getId === "function" ? ref.getId() : void 0 : void 0) === (info != null ? info.object_id : void 0)) {
            return _this.renderChangeHistory();
          }
        };
      })(this)
    });
    return this.container;
  };

  DetailSidebar.prototype.load = function(present_error) {
    var dfr, format, loadCounter;
    if (present_error == null) {
      present_error = true;
    }
    if (!this.__global_object_id) {
      return CUI.resolvedPromise();
    }
    dfr = new CUI.Deferred();
    dfr.always((function(_this) {
      return function() {
        _this.__paneFooter.replace(_this.getNavigationPreviousNext(), "center");
        return _this.__updateNavigationPreviousNext();
      };
    })(this));
    loadCounter = ++this.__counter;
    if (this.container) {
      CUI.dom.removeAttribute(this.container.DOM, "ui");
    }
    if (ez5.version("6")) {
      format = "long_inheritance";
    } else {
      format = "long";
    }
    if (this._wait_for_index) {
      present_error = false;
    }
    ResultObject.loadFromData({
      _global_object_id: this.__global_object_id
    }, format, present_error, false, !!ez5.version("6"), !!ez5.version("6")).done((function(_this) {
      return function(object1) {
        var _mask, add_info, base, best, bestMask, ev_info, i, idx, info, j, k, len, len1, masks, p, pool, pool_info, pool_obj, ref, ref1, ref2, ref3, ref4, ref5, remote, standardMaskFound, v;
        _this.object = object1;
        if (ez5.version("6.4") && CUI.util.isEmptyObject((ref = _this.object) != null ? ref.getData()._generated_rights : void 0) && !((ref1 = _this.object) != null ? ref1.getData()._instance : void 0)) {
          _this._sidebar.hideSidebar();
          return dfr.reject({
            cancelled: true
          });
        }
        if (loadCounter !== _this.__counter) {
          return dfr.reject({
            cancelled: true
          });
        }
        if (!_this.container || _this.container.isDestroyed()) {
          dfr.reject();
          return;
        }
        best = ez5.maskMemoryManager.getBestMask(_this.object, "detail", _this.object.getAvailableMasks());
        bestMask = Mask.getMaskByMaskName(best);
        if (bestMask.hideInDetail() || indexOf.call(_this.object.getAvailableMasks(), bestMask) < 0) {
          masks = [];
          ref2 = _this.object.getAvailableMasks();
          for (i = 0, len = ref2.length; i < len; i++) {
            _mask = ref2[i];
            if (!_mask.hideInDetail()) {
              if (_mask.isStandard()) {
                best = _mask.name();
                standardMaskFound = true;
                break;
              }
              masks.push(_mask);
            }
          }
          if (!standardMaskFound) {
            best = (ref3 = masks[0]) != null ? ref3.name() : void 0;
          }
        }
        _this.detail_data.mask_name = _this.object.setDataByMaskName(best);
        if (_this.object.getAvailableMasks().length > 1) {
          ez5.maskMemoryManager.storeMask(_this.object.objecttype(), _this.detail_data.mask_name, "detail");
        }
        if ((base = _this.detail_data).mask_name_by_objecttype == null) {
          base.mask_name_by_objecttype = {};
        }
        _this.detail_data.mask_name_by_objecttype[_this.object.objecttype()] = _this.detail_data.mask_name;
        if (_this.object) {
          CUI.dom.setAttribute(_this.container, "ui", "detail.sidebar.container:" + (_this.object.getSystemObjectId()));
        }
        ev_info = {
          type: "DETAIL_VIEW",
          info: {
            global_object_id: _this.__global_object_id
          }
        };
        info = {
          object_id: _this.object.id() || void 0,
          objecttype: _this.object.objecttype() || void 0
        };
        remote = _this.object.getRemoteEasydb();
        if (remote) {
          add_info = ev_info.info;
          ref4 = {
            name: remote.getDisplayname(),
            url: remote.getServerUrl()
          };
          for (k in ref4) {
            v = ref4[k];
            info["connector_" + k] = v;
          }
        } else {
          add_info = ev_info;
        }
        for (k in info) {
          v = info[k];
          add_info[k] = v;
        }
        if (_this.object.pool()) {
          pool = _this.object.pool();
          p = new Pool({
            pool: pool
          });
          ev_info.info["pool"] = p.getEventInfo();
          ref5 = pool._path;
          for (idx = j = 0, len1 = ref5.length; j < len1; idx = j += 1) {
            pool_obj = ref5[idx];
            p = new Pool({
              pool: pool_obj
            });
            pool_info = p.getEventInfo();
            ev_info.info["pool." + (idx + 1)] = pool_info;
          }
        }
        EventPoller.saveEvent(ev_info);
        _this.renderObject().done(dfr.resolve).fail(dfr.reject);
        if (_this.__changeHistoryEnabled) {
          return _this.renderChangeHistory();
        }
      };
    })(this)).fail((function(_this) {
      return function() {
        var listener;
        if (_this._wait_for_index) {
          return listener = EventPoller.listen({
            filter: {
              type: ["OBJECT_INDEX", "OBJECT_INSERT"],
              global_object_id: _this.__global_object_id
            },
            instance: _this,
            call: function(events) {
              CUI.Events.ignore(listener);
              _this._wait_for_index = false;
              _this.load(true).done(dfr.resolve).fail(dfr.reject);
            }
          });
        } else {
          return dfr.reject();
        }
      };
    })(this));
    return dfr.promise();
  };

  DetailSidebar.prototype.empty = function() {
    CUI.dom.empty(this.container.DOM);
    CUI.dom.append(this.container.DOM, new CUI.EmptyLabel({
      centered: true,
      text: $$("main.detail.content.no_data.label")
    }).DOM);
    return this.container.DOM;
  };

  DetailSidebar.prototype.getMainSearch = function() {
    return this._sidebar.getSearch();
  };

  DetailSidebar.prototype.getSearch = function() {
    return this.__search;
  };

  DetailSidebar.prototype.getResultObject = function() {
    return this.object;
  };

  DetailSidebar.prototype.changeHistoryAvailable = function() {
    var ref;
    return ez5.session.hasSystemRight("root", "frontend_features[changelog]", "frontend_features[changelog_with_user]") && !((ref = this.object) != null ? typeof ref.getInstance === "function" ? ref.getInstance() : void 0 : void 0);
  };

  DetailSidebar.prototype.__renderDeletedObjectHeader = function() {
    if (this.__deletedObjectHeader) {
      CUI.dom.remove(this.__deletedObjectHeader);
      this.__deletedObjectHeader = null;
    }
    this.__deletedObjectHeader = this.object.renderDeletedHeader();
    return CUI.dom.insertAfter(this.paneHeader.DOM, this.__deletedObjectHeader);
  };

  DetailSidebar.prototype.__isObjectDeleted = function() {
    var ref;
    return (ref = this.object) != null ? ref.isDeleted() : void 0;
  };

  DetailSidebar.prototype.__undeleteObject = function() {
    var dfr, editor, ol;
    if (!ez5.version("6")) {
      return CUI.rejectedPromise();
    }
    ol = new ObjectList();
    ol.push(this.getResultObject());
    dfr = new CUI.Deferred();
    dfr.done((function(_this) {
      return function() {
        return _this.load();
      };
    })(this));
    dfr.always((function(_this) {
      return function() {
        return ez5.splash.hide();
      };
    })(this));
    ez5.splash.show("main.list.objecttypes.tool.prepare-delete");
    editor = new EditorHeadlessDelete({
      object_list: ol,
      require_comment: false
    });
    editor.undeleteObjects().done(function() {
      return dfr.resolve(this);
    }).fail(dfr.reject);
    return dfr.promise();
  };

  DetailSidebar.prototype.__purgeObject = function() {
    var dfr, editor, ol;
    if (!ez5.version("6")) {
      return CUI.rejectedPromise();
    }
    ol = new ObjectList();
    ol.push(this.getResultObject());
    dfr = new CUI.Deferred();
    dfr.done((function(_this) {
      return function() {
        return _this._sidebar.empty();
      };
    })(this));
    dfr.always((function(_this) {
      return function() {
        return ez5.splash.hide();
      };
    })(this));
    ez5.splash.show("main.list.objecttypes.tool.prepare-delete");
    editor = new EditorHeadlessDelete({
      object_list: ol,
      require_comment: false
    });
    editor.purgeObjects().done(function() {
      return dfr.resolve(this);
    }).fail(dfr.reject);
    return dfr.promise();
  };

  DetailSidebar.prototype.destroy = function() {
    var i, len, plugin, ref, ref1, ref2, ref3, ref4, ref5;
    if ((ref = this.container) != null) {
      ref.destroy();
    }
    delete this.container;
    if ((ref1 = this.browserLayout) != null) {
      ref1.destroy();
    }
    delete this.browserLayout;
    if ((ref2 = this.toolbar) != null) {
      ref2.destroy();
    }
    delete this.toolbar;
    if ((ref3 = this.paneHeader) != null) {
      ref3.destroy();
    }
    delete this.paneHeader;
    if ((ref4 = this.mainPane) != null) {
      ref4.destroy();
    }
    delete this.mainPane;
    ref5 = this.__plugins;
    for (i = 0, len = ref5.length; i < len; i++) {
      plugin = ref5[i];
      plugin.destroy();
    }
    delete this.__card_div;
    delete this.__detail_div;
    delete this.__plugins;
    delete this.__global_object_id;
    delete this.__offset;
    delete this.detail_data;
    delete this.object;
    delete this.__search;
    delete this.__deletedObjectHeader;
    CUI.Events.ignore({
      instance: this
    });
    return DetailSidebar.__super__.destroy.call(this);
  };

  DetailSidebar.prototype.canUpdate = function() {
    if (this.container && !this.container.isDestroyed() && CUI.dom.isInDOM(this.container.DOM)) {
      return true;
    } else {
      return false;
    }
  };

  DetailSidebar.prototype.update = function(_opts) {
    var i, k, len, opts, ref;
    opts = CUI.Element.readOpts(_opts, "DetailSidebar.update", {
      search: {
        check: Search
      },
      offset: {
        check: function(v) {
          return v >= 0;
        }
      },
      global_object_id: {
        mandatory: true,
        check: String
      },
      asset_browser_idx: {
        check: "Integer"
      },
      next_previous_global_object_ids: {
        check: function(value) {
          return CUI.util.isArray(value) && value.every((function(_this) {
            return function(v) {
              return CUI.util.isString(v);
            };
          })(this));
        }
      }
    });
    ref = ['search', 'offset'];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      if (opts[k] !== void 0) {
        this['__' + k] = opts[k];
      }
    }
    if (this.__global_object_id === opts.global_object_id) {
      return CUI.resolvedPromise();
    }
    this.__next_previous_global_object_ids = this.__getNextPreviousGlobalObjectIds(opts.next_previous_global_object_ids);
    this.__asset_browser_idx = opts.asset_browser_idx;
    this.__global_object_id = opts.global_object_id;
    return this.load();
  };

  DetailSidebar.prototype.getFieldsRendererSetStyle = function() {
    return false;
  };

  DetailSidebar.prototype.loadGlobalObjectId = function(gid) {
    return this._sidebar.allow_unload().done((function(_this) {
      return function() {
        CUI.Events.trigger({
          type: "focus-sidebar-selection",
          node: window,
          info: {
            global_object_id: gid
          }
        });
        return _this._sidebar.loadDetail({
          global_object_id: gid
        });
      };
    })(this));
  };

  DetailSidebar.prototype.__loadTools = function(ev, tools, tool) {
    var _tool, add_to_col, add_to_collection_tool, can_copy, collection, copy_tool, create_new_child_tool, edit_tool, gen_rights, i, len, manager, object, ot, promise, promises, ref, ref1, removeTools, remove_from_collection_tool;
    for (i = 0, len = tools.length; i < len; i++) {
      _tool = tools[i];
      switch (_tool.getName()) {
        case "object.edit.sidebar":
          edit_tool = _tool;
          break;
        case "object.copy.sidebar":
          copy_tool = _tool;
          break;
        case "object.create_new_child.sidebar":
          create_new_child_tool = _tool;
          break;
        case "object.remove_from_collection":
          remove_from_collection_tool = _tool;
          break;
        case "object.add_to_collection":
          add_to_collection_tool = _tool;
      }
    }
    promises = [];
    if (edit_tool && tool === "edit") {
      if (this.__isObjectDeleted()) {
        if (edit_tool != null) {
          edit_tool.setLoading(false);
        }
        if (edit_tool != null) {
          edit_tool.disable();
        }
      } else {
        gen_rights = this.getResultObject().getData()._generated_rights;
        if (gen_rights) {
          if (edit_tool != null) {
            edit_tool.setLoading(false);
          }
          if (gen_rights.write) {
            if (edit_tool != null) {
              edit_tool.enable();
            }
          }
        } else {
          ot = new Objecttype(ez5.schema.CURRENT._objecttype_by_name[this.getResultObject().objecttype()]);
          if (!ot.isLocal()) {
            this.getResultObject().getData()._generated_rights = {};
            if (edit_tool != null) {
              edit_tool.setLoading(false);
            }
          } else {
            promise = DbInfo.canWrite({
              object: this.getResultObject().getData()
            }).always((function(_this) {
              return function() {
                return edit_tool != null ? edit_tool.setLoading(false) : void 0;
              };
            })(this)).done((function(_this) {
              return function() {
                return edit_tool != null ? edit_tool.enable() : void 0;
              };
            })(this));
            promises.push(promise);
          }
        }
      }
    }
    if (copy_tool && tool === "copy") {
      can_copy = this.getResultObject().getData().__can_copy;
      if (can_copy !== void 0) {
        if (copy_tool != null) {
          copy_tool.setLoading(false);
        }
        if (create_new_child_tool != null) {
          create_new_child_tool.setLoading(false);
        }
        if (can_copy) {
          if (copy_tool != null) {
            copy_tool.enable();
          }
          if (create_new_child_tool != null) {
            create_new_child_tool.enable();
          }
        }
      } else {
        ot = new Objecttype(ez5.schema.CURRENT._objecttype_by_name[this.getResultObject().objecttype()]);
        if (!ot.isLocal()) {
          this.getResultObject().getData().__can_copy = false;
          if (copy_tool != null) {
            copy_tool.setLoading(false);
          }
          if (create_new_child_tool != null) {
            create_new_child_tool.setLoading(false);
          }
        } else {
          promise = DbInfo.canCreate({
            objecttypes: [ot]
          }).always((function(_this) {
            return function() {
              if (copy_tool != null) {
                copy_tool.setLoading(false);
              }
              return create_new_child_tool != null ? create_new_child_tool.setLoading(false) : void 0;
            };
          })(this)).fail((function(_this) {
            return function() {
              return _this.getResultObject().getData().__can_copy = false;
            };
          })(this)).done((function(_this) {
            return function() {
              _this.getResultObject().getData().__can_copy = true;
              if (copy_tool != null) {
                copy_tool.enable();
              }
              return create_new_child_tool != null ? create_new_child_tool.enable() : void 0;
            };
          })(this));
          promises.push(promise);
        }
      }
    }
    if (add_to_collection_tool && tool === "add") {
      manager = this.__getCollectionManager();
      add_to_col = manager.getAddToCollectionMenuItems({
        collection: this.__getCollectionSelection()
      });
      if (add_to_col.length > 0) {
        add_to_collection_tool._tools = [add_to_col][0];
      }
    }
    if (remove_from_collection_tool && tool === "remove") {
      object = this.getResultObject();
      removeTools = remove_from_collection_tool.getTools();
      if (((ref = object.__removeCollectionsTools) != null ? ref.length : void 0) > 1) {
        remove_from_collection_tool.enable();
        remove_from_collection_tool.setLoading(false);
      } else if (((ref1 = object.data._collections) != null ? ref1.length : void 0) > 0) {
        ez5.api.search_no_limit({
          json_data: {
            type: "collection",
            generate_rights: true,
            limit: 1000000,
            search: [
              {
                type: "in",
                bool: "must",
                fields: ["collection._id"],
                "in": (function() {
                  var j, len1, ref2, results;
                  ref2 = object.data._collections;
                  results = [];
                  for (j = 0, len1 = ref2.length; j < len1; j++) {
                    collection = ref2[j];
                    results.push(collection._id);
                  }
                  return results;
                })()
              }
            ]
          }
        }).done((function(_this) {
          return function(data) {
            var collectionObject, collections, fn, j, len1;
            object.__removeCollectionsTools = removeTools;
            removeTools.push({
              label: $$("collection.selection.remove_from_collection.title")
            });
            collections = data.objects.map(function(col) {
              return new CollectionStorable({
                collection: col
              });
            }).sort(function(col1, col2) {
              return col1.renderNameAsText().localeCompare(col2.renderNameAsText());
            });
            fn = function(collectionObject) {
              return removeTools.push(new ToolboxTool({
                group: "object",
                text: collectionObject.renderNameAsText(),
                name: "" + (collectionObject.getId()),
                disabled: !collectionObject.canUnlink(),
                run: function() {
                  return collectionObject.removeObjects([object.getCollectionObject()]).done(function() {
                    CUI.util.removeFromArray(null, removeTools, function(tool) {
                      return (typeof tool.getName === "function" ? tool.getName() : void 0) === ("" + (collectionObject.getId()));
                    });
                    return CUI.util.removeFromArray(null, object.data._collections, function(col) {
                      return col._id === collectionObject.getId();
                    });
                  });
                }
              }));
            };
            for (j = 0, len1 = collections.length; j < len1; j++) {
              collectionObject = collections[j];
              fn(collectionObject);
            }
            return remove_from_collection_tool.enable();
          };
        })(this)).always(function() {
          return remove_from_collection_tool.setLoading(false);
        });
      } else {
        remove_from_collection_tool.enable();
        remove_from_collection_tool.setLoading(false);
        removeTools.push(new ToolboxTool({
          group: "object",
          name: "object.remove_from_collection.empty_label",
          disabled: true
        }));
      }
    }
    return CUI.when(promises);
  };

  DetailSidebar.prototype.onClose = function() {};

  DetailSidebar.prototype.supportsFullscreen = function() {
    return !CUI.util.isEmpty(this.object.getAssetsForBrowser("detail"));
  };

  DetailSidebar.prototype.renderObject = function() {
    var _mask, _masks, bb, btn, btnClassname, buttons, dfr, fh_left, fh_top, fullscreenBtn, i, j, l, len, len1, len2, loading_promise, masks, mfs, mode, onActivate, onDeactivate, pane, pane_buttons, plugin, plugin_active, pref, ref, ref1, ref2, ref3, resultCardPinButton, tools;
    this.paneHeader.replace(new LocaLabel({
      ui: "detail.sidebar.title",
      loca_key: "detail.sidebar.title"
    }), "left");
    this.object.setCSSClasses(this.container);
    this.__renderDeletedObjectHeader();
    buttons = [];
    if (this.supportsFullscreen()) {
      fullscreenBtn = new CUI.Button({
        icon: "fa-expand",
        tooltip: {
          text: $$("detail.sidebar.button.fullscreen|favorite_tooltip")
        },
        onClick: (function(_this) {
          return function() {
            return _this.openFullscreen();
          };
        })(this)
      });
      buttons.push(fullscreenBtn);
    }
    buttons.push({
      icon: "close",
      loca_key: "detail.sidebar.button.close",
      ui: "detail.sidebar.close.button",
      onClick: (function(_this) {
        return function() {
          _this.onClose();
          return _this._sidebar.hideSidebar();
        };
      })(this)
    });
    this.paneHeader.replace(buttons, "right");
    pane_buttons = {
      left: [],
      top: []
    };
    fh_left = this.browserLayout.getFlexHandle("left");
    fh_top = this.mainPane.getFlexHandle("top");
    onActivate = (function(_this) {
      return function(btn, flags) {
        var plugin;
        plugin = btn.opts._plugin;
        plugin.showDetail();
        plugin.setActive();
        switch (plugin.getPane()) {
          case "top":
            fh_top.open().show();
            CUI.dom.showElement(_this.mainPane.top());
            break;
          case "left":
            fh_left.open().show();
        }
        if (plugin.prefName()) {
          ez5.session.saveCookiePref(plugin.prefName(), true);
        }
        _this.updateCenterContent();
      };
    })(this);
    onDeactivate = (function(_this) {
      return function(btn, flags) {
        var plugin;
        plugin = btn.opts._plugin;
        plugin.hideDetail();
        plugin.setInactive();
        switch (plugin.getPane()) {
          case "top":
            fh_top.close().hide();
            CUI.dom.hideElement(_this.mainPane.top());
            break;
          case "left":
            fh_left.close().hide();
        }
        if (plugin.prefName()) {
          ez5.session.saveCookiePref(plugin.prefName(), false);
        }
      };
    })(this);
    plugin_active = {
      left: null,
      top: null
    };
    ref = this.__plugins;
    for (i = 0, len = ref.length; i < len; i++) {
      plugin = ref[i];
      if (!this.__isPluginAvailable(plugin)) {
        plugin.hideDetail();
        continue;
      }
      plugin.renderObject();
      pane = plugin.getPane();
      pref = plugin.prefName();
      if (pref && ez5.session.getPref(pref) && !plugin.isDisabled()) {
        if ((ref1 = plugin_active[pane]) != null) {
          ref1.setInactive();
        }
        plugin.setActive();
        plugin_active[pane] = plugin;
      } else {
        plugin.setInactive();
      }
      btnClassname = pref.replaceAll('.', '-');
      btn = new LocaButton({
        ui: "detail.sidebar.plugin.button:" + pref,
        loca_key: plugin.getButtonLocaKey(),
        "class": "ez5-button-plugin ez5-button-plugin-" + btnClassname,
        radio: pane,
        group: pane,
        active: false,
        activate_initial: false,
        disabled: plugin.isDisabled(),
        radio_allow_null: true,
        _plugin: plugin,
        onActivate: onActivate,
        onDeactivate: onDeactivate
      });
      plugin.setButton(btn);
      pane_buttons[pane].push(btn);
    }
    buttons = [];
    buttons.push.apply(buttons, pane_buttons.left);
    buttons.push.apply(buttons, pane_buttons.top);
    if (pane_buttons.top.length === 0 || !plugin_active.top) {
      fh_top.close().hide();
      CUI.dom.hideElement(this.mainPane.top());
    }
    if (pane_buttons.left.length === 0 || !plugin_active.left) {
      fh_left.close().hide();
    }
    _masks = this.object.getAvailableMasks();
    masks = [];
    for (j = 0, len1 = _masks.length; j < len1; j++) {
      _mask = _masks[j];
      if (_mask.hideInDetail()) {
        continue;
      }
      masks.push(_mask);
    }
    if (masks.length === 0) {
      masks = [_masks[0]];
    }
    if (masks.length > 1) {
      mfs = new MaskFieldSelectorDetail({
        mask_name: this.detail_data.mask_name,
        masks: masks,
        onChanged: (function(_this) {
          return function(old_mask, new_mask) {
            _this.detail_data.mask_name = _this.object.setDataByMaskName(new_mask);
            ez5.maskMemoryManager.storeMask(_this.object.objecttype(), _this.detail_data.mask_name, "detail");
            _this.detail_data.mask_name_by_objecttype[_this.object.objecttype()] = _this.detail_data.mask_name;
            _this.renderObject();
            return CUI.resolvedPromise();
          };
        })(this)
      });
      this.__detailMaskSelector = mfs.getSelect().start();
      buttons.push.apply(buttons, [this.__detailMaskSelector]);
    }
    bb = new CUI.Buttonbar({
      buttons: buttons
    });
    tools = this.getCurrentTools();
    loading_promise = null;
    this.__toolboxFlyoutButtonBar = Toolbox.getFlyoutButtonbar(tools);
    this.__toolbarRightContent = this.getToolbarRightContent();
    this.toolbar.replace(bb, "left");
    this.toolbar.replace([this.__toolbarRightContent, this.__toolboxFlyoutButtonBar], "right");
    this.mainPane.empty("center");
    dfr = new CUI.Deferred();
    mode = "detail";
    this.__detail_div = this.object.renderDetail(mode, "detail-header", {
      detail: this,
      onDone: (function(_this) {
        return function() {
          if (ez5.version("6")) {
            _this.__configureGoToTopBtn();
          }
          _this.triggerCallback("detail-sidebar-render-object").done(dfr.resolve).fail(dfr.reject);
        };
      })(this),
      onFail: (function(_this) {
        return function() {
          return dfr.reject();
        };
      })(this),
      maximize: false
    });
    this.__card_div = this.object.renderCardDetail({
      mode: "result-card-info-detail",
      detail: this
    });
    if (ez5.version("6") && ((ref2 = ez5.cssLoader.getActiveCSS()) != null ? ref2.theme : void 0) === 'fylr') {
      resultCardPinButton = ResultObject.getResultCardPinButton(this.mainPane, "resultCard.unpin", (function(_this) {
        return function() {
          return _this.__configureGoToTopBtn();
        };
      })(this));
      CUI.dom.append(this.__card_div, resultCardPinButton);
    }
    ref3 = this.getActivePlugins();
    for (l = 0, len2 = ref3.length; l < len2; l++) {
      plugin = ref3[l];
      plugin.getButton().activate();
    }
    this.updateCenterContent();
    this.mainPane.show("center");
    this.updateAssetBrowserIdx();
    return dfr.promise();
  };

  DetailSidebar.prototype.__configureGoToTopBtn = function() {
    if (!this.__detail_div || !this.__goToTopBtn) {
      return;
    }
    if (this.__detailScrollListener) {
      CUI.Events.ignore(this.__detailScrollListener);
      this.__detailScrollListener = null;
    }
    if (CUI.dom.hasClass(this.mainPane, "is-fully-scrollable")) {
      this.__scrollDiv = this.mainPane.DOM;
    } else {
      this.__scrollDiv = this.__detail_div;
    }
    return this.__detailScrollListener = CUI.Events.listen({
      node: this.__scrollDiv,
      type: "scroll",
      call: (function(_this) {
        return function(ev) {
          if (_this.__scrollDiv.scrollTop > 0) {
            CUI.dom.removeClass(_this.__goToTopBtn, "cui-disabled");
          } else {
            CUI.dom.addClass(_this.__goToTopBtn, "cui-disabled");
          }
        };
      })(this)
    });
  };

  DetailSidebar.prototype.updateAssetBrowserIdx = function(assetBrowserIdx) {
    var assetBrowserPlugin;
    if (assetBrowserIdx == null) {
      assetBrowserIdx = this.__asset_browser_idx;
    }
    if (!assetBrowserIdx) {
      assetBrowserIdx = 0;
    }
    if (!CUI.util.isUndef(assetBrowserIdx)) {
      assetBrowserPlugin = this.getAssetBrowserPlugin();
      if (assetBrowserPlugin != null) {
        assetBrowserPlugin.setAssetBrowserIdx(assetBrowserIdx);
      }
    }
  };

  DetailSidebar.prototype.getActivePlugins = function() {
    var aplugins, i, len, plugin, ref;
    aplugins = [];
    ref = this.__plugins;
    for (i = 0, len = ref.length; i < len; i++) {
      plugin = ref[i];
      if (plugin.isActive()) {
        aplugins.push(plugin);
      }
    }
    return aplugins;
  };

  DetailSidebar.prototype.getPlugins = function() {
    return this.__plugins;
  };

  DetailSidebar.prototype.updateCenterContent = function() {
    var extra, i, len, plugin, ref;
    extra = [];
    ref = this.getActivePlugins();
    for (i = 0, len = ref.length; i < len; i++) {
      plugin = ref[i];
      extra.push(plugin.getCenterContent());
    }
    return this.mainPane.replace([extra, this.__card_div, this.__detail_div], "center");
  };

  DetailSidebar.prototype.getToolbarRightContent = function() {
    var ref;
    if (!((ref = this.getResultObject().getData()._generated_rights) != null ? ref.write : void 0)) {
      return;
    }
    if (this.__isObjectDeleted()) {
      return;
    }
    return new LocaButton({
      loca_key: "editor.button.pen",
      ui: "detail.sidebar.edit.button",
      onClick: (function(_this) {
        return function() {
          return _this._sidebar.loadEditor({
            global_object_id: _this.__global_object_id,
            search: _this.getSearch()
          });
        };
      })(this)
    });
  };

  DetailSidebar.prototype.openFullscreen = function() {
    var assetBrowserPlugin, detailFullscreen, search, videoPlayer, videoPlayerStart, videoPlayerTime;
    if (this.__offset >= 0) {
      search = this.getSearch();
      if (!(search instanceof SearchCollection)) {
        if (CUI.util.idxInArray(null, search.getSearchObjecttypes(), (function(_this) {
          return function(ot) {
            return ot.name() === _this.object.objecttype();
          };
        })(this)) === -1) {
          search = null;
        }
      }
    }
    assetBrowserPlugin = this.getAssetBrowserPlugin();
    videoPlayer = assetBrowserPlugin != null ? assetBrowserPlugin.getAssetBrowserVideoPlayer() : void 0;
    if (videoPlayer != null ? videoPlayer.isInDOM() : void 0) {
      videoPlayerTime = videoPlayer.getCurrentTime();
      if (!videoPlayer.isPaused()) {
        videoPlayerStart = true;
        videoPlayer.pause();
      }
    }
    return detailFullscreen = new DetailFullscreen({
      global_object_id: this.__global_object_id,
      search: search,
      offset: this.__offset,
      asset_browser_idx: assetBrowserPlugin != null ? assetBrowserPlugin.getAssetBrowserCurrentIdx() : void 0,
      video_player_start: videoPlayerStart,
      video_player_time: videoPlayerTime,
      onClose: (function(_this) {
        return function() {
          var assetBrowser, videoPlayerFullscreen;
          assetBrowser = detailFullscreen.getCurrentAssetBrowser();
          videoPlayerFullscreen = assetBrowser != null ? assetBrowser.getVideoPlayer() : void 0;
          if (videoPlayer != null ? videoPlayer.isInDOM() : void 0) {
            return videoPlayer.setCurrentTime(videoPlayerFullscreen.getCurrentTime());
          }
        };
      })(this)
    });
  };

  DetailSidebar.prototype.canShowAssetBrowser = function() {
    return !this.__changeHistoryEnabled;
  };

  DetailSidebar.prototype.getCurrentTools = function() {
    var addToCollectionTool, add_to_col_tools, add_to_collection_tool, collectionSelection, copyTool, copyToolOpts, count, dm, fn, manager, mask, menuItems, objecttype, onAddToCollection, onCopyToolRun, opts, parentInfo, ref, remove_from_collection_tool, tools, value;
    tools = [];
    if (!this.object) {
      return;
    }
    if (!this.__isObjectDeleted()) {
      tools.push(new ToolboxTool({
        loca_key: "tool.object.single-edit",
        name: "object.edit.sidebar",
        sort: "A:1",
        group: "object",
        disabled: (function(_this) {
          return function() {
            var ref;
            return !((ref = _this.getResultObject().getData()._generated_rights) != null ? ref.write : void 0);
          };
        })(this),
        loading: (function(_this) {
          return function() {
            return !_this.getResultObject().getData()._generated_rights;
          };
        })(this),
        onFlyoutMenuShow: (function(_this) {
          return function(ev, tools) {
            return _this.__loadTools(ev, tools, "edit");
          };
        })(this),
        run: (function(_this) {
          return function() {
            return _this._sidebar.loadEditor({
              global_object_id: _this.__global_object_id,
              search: _this.getSearch()
            });
          };
        })(this)
      }));
    }
    if (this.__isObjectDeleted()) {
      if (TrashSearchManager.canUndelete()) {
        tools.push(new ToolboxTool({
          loca_key: "tool.object.single-undelete",
          name: "object.undelete.sidebar",
          sort: "A:1",
          group: "object",
          run: (function(_this) {
            return function() {
              return _this.__undeleteObject();
            };
          })(this)
        }));
      }
      if (TrashSearchManager.canPurge()) {
        tools.push(new ToolboxTool({
          loca_key: "tool.object.single-purge",
          name: "object.purge.sidebar",
          sort: "A:2",
          group: "object",
          run: (function(_this) {
            return function() {
              return _this.__purgeObject();
            };
          })(this)
        }));
      }
    }
    copyToolOpts = {
      loca_key: "tool.object.single-copy",
      name: "object.copy.sidebar",
      sort: "A:2",
      group: "object",
      loading: true,
      disabled: true,
      onFlyoutMenuShow: (function(_this) {
        return function(ev, tools) {
          return _this.__loadTools(ev, tools, "copy");
        };
      })(this)
    };
    onCopyToolRun = (function(_this) {
      return function(opts) {
        var roPromise;
        if (opts.copyAsTemplate) {
          roPromise = ResultObject.loadFromGlobalObjectId(_this.__global_object_id, "full", null, true, false).done(function(resultObject) {
            return resultObject.copyAsTemplate();
          });
        } else {
          _this._sidebar.loadEditor({
            global_object_id: _this.__global_object_id,
            copy: true,
            search: _this.getSearch(),
            copyMask: _this.detail_data.mask_name,
            copySkipFields: opts.copySkipFields
          });
        }
      };
    })(this);
    if (!this.__isObjectDeleted()) {
      copyTool = Sidebar.getCopyTool(this.object, onCopyToolRun, copyToolOpts);
      tools.push(copyTool);
    }
    if (this.object.getMask().isHierarchy() && !this.__isObjectDeleted()) {
      mask = this.object.getMask();
      parentInfo = mask.schema.system_fields.parent;
      if (parentInfo && !TreeColumn.isReadOnly(parentInfo)) {
        tools.push(new ToolboxTool({
          loca_key: "detail.sidebar.button.create_new_child",
          name: "object.create_new_child.sidebar",
          sort: "A:3",
          group: "object",
          disabled: (function(_this) {
            return function() {
              var ref;
              return !((ref = _this.getResultObject().getData()._generated_rights) != null ? ref.write : void 0);
            };
          })(this),
          loading: (function(_this) {
            return function() {
              return !_this.getResultObject().getData()._generated_rights;
            };
          })(this),
          run: (function(_this) {
            return function() {
              return _this._sidebar.loadEditor({
                table_id: _this.object.getMask().getTable().id(),
                parent_id: _this.object.getId()
              });
            };
          })(this)
        }));
      }
    }
    if (ez5.session.hasSystemRight("root", "frontend_features[download]") && this.object.getSession().hasSystemRight("root", "frontend_features[download]") && !this.object.isDeleted()) {
      dm = new DownloadManager({
        result_object: this.object
      });
      if (dm.hasDownloadableVersion()) {
        tools.push(new ToolboxTool({
          name: "detail.download",
          favorite: true,
          loca_key: "detail.sidebar.download.button",
          sort: "C:1",
          group: "object",
          run: (function(_this) {
            return function() {
              return dm.startExport();
            };
          })(this)
        }));
      }
    }
    if (ez5.session.hasSystemRight("root", "frontend_features[export]") && !this.object.getInstance() && !this.object.isDeleted()) {
      tools.push(new ToolboxTool({
        loca_key: "detail.sidebar.export.button",
        name: "detail.export",
        sort: "C:2",
        group: "object",
        run: (function(_this) {
          return function() {
            var col;
            col = new CollectionMemory();
            return col.insertObjects([_this.object.getCollectionObject()]).done(function() {
              return new ExportManager({
                search: new SearchCollectionHeadless({
                  collection: col
                })
              }).prepareExport();
            });
          };
        })(this)
      }));
    }
    if (!CUI.util.isEmpty(this.object.getAssetsForBrowser("detail")) && !this.object.isDeleted()) {
      tools.push(new ToolboxTool({
        name: "detail.fullscreen",
        favorite: false,
        loca_key: "detail.sidebar.button.fullscreen",
        sort: "B:1",
        group: "object",
        run: (function(_this) {
          return function() {
            return _this.openFullscreen();
          };
        })(this)
      }));
    }
    if (ez5.session.hasSystemRight("root", "frontend_features[print]") && !this.object.isDeleted()) {
      tools.push(new ToolboxTool({
        name: "detail.print",
        loca_key: "detail.print.button",
        sort: "C:3",
        group: "object",
        run: (function(_this) {
          return function() {
            var printManager;
            printManager = new PrintManager({
              result_object: _this.object
            });
            return printManager.getOptionsModal().show();
          };
        })(this)
      }));
    }
    if (ez5.session.hasSystemRight("root", "frontend_features[collections]") && !this.object.isDeleted()) {
      manager = this.__getCollectionManager();
      collectionSelection = this.__getCollectionSelection();
      count = collectionSelection != null ? collectionSelection.getCount() : void 0;
      if (manager) {
        opts = {
          collection: collectionSelection
        };
        if (!ez5.version("6")) {
          add_to_col_tools = manager.getAddToCollectionMenuItems(opts);
          if (add_to_col_tools.length > 0) {
            add_to_collection_tool = new ToolboxTool({
              name: "object.add_to_collection",
              sort: "D:2",
              group: "object",
              disabled: count === 0,
              tools: add_to_col_tools,
              onFlyoutMenuShow: (function(_this) {
                return function(ev, tools) {
                  return _this.__loadTools(ev, tools, "add");
                };
              })(this)
            });
          }
        } else {
          onAddToCollection = (function(_this) {
            return function(targetCollection, filteredObjects) {
              var objectsToAdd;
              if (targetCollection) {
                objectsToAdd = filteredObjects || _this.getObjects();
                return targetCollection.insertObjects(objectsToAdd, null, false);
              }
            };
          })(this);
          addToCollectionTool = null;
          menuItems = AddToCollectionHelper.getAddToCollectionMenuItems({
            collection: collectionSelection,
            manager: manager,
            onAddToCollection: onAddToCollection,
            onRecentCollectionsValidated: (function(_this) {
              return function(validRecent) {
                var newItems;
                newItems = AddToCollectionHelper.updateMenuItemsWithValidatedRecent(add_to_collection_tool._tools, validRecent, collectionSelection, onAddToCollection);
                return add_to_collection_tool._tools = newItems;
              };
            })(this)
          });
          if (menuItems.length > 0) {
            add_to_collection_tool = new ToolboxTool({
              group: "object",
              disabled: count === 0,
              name: "object.collection_picker",
              sort: "D:2",
              tools: menuItems
            });
          }
        }
        remove_from_collection_tool = new ToolboxTool({
          name: "object.remove_from_collection",
          sort: "D:3",
          group: "object",
          disabled: count === 0,
          loca_key_attrs: {
            count: count
          },
          tools: [],
          onFlyoutMenuShow: (function(_this) {
            return function(ev, tools) {
              return _this.__loadTools(ev, tools, "remove");
            };
          })(this)
        });
        if (add_to_collection_tool) {
          tools.push(add_to_collection_tool);
        }
        if (remove_from_collection_tool) {
          tools.push(remove_from_collection_tool);
        }
      }
    }
    if (this.object.canBeShared()) {
      tools.push(new ToolboxTool({
        name: "detail.share",
        favorite: false,
        loca_key: "detail.sidebar.button.share",
        sort: "D:1",
        group: "object",
        run: (function(_this) {
          return function(ev) {
            return _this.object.presentShareUrls(ev.altKey() || ev.shiftKey());
          };
        })(this)
      }));
    }
    if (ez5.session.hasSystemRight("root", "frontend_features[changelog]", "frontend_features[changelog_with_user]") && !this.object.getInstance()) {
      tools.push(new ToolboxTool({
        name: "detail.change-history",
        loca_key: "detail.sidebar.change-history.button",
        sort: "B:3",
        group: "object",
        run: (function(_this) {
          return function() {
            return _this.renderChangeHistory();
          };
        })(this)
      }));
    }
    if (CUI.util.getObjectClass(this.__search) === "SearchMain" && !this.object.isDeleted()) {
      this.__searchLinkObjectsInsideNesteds();
      ref = this.__linkedNestedIdsPerObjecttype;
      fn = (function(_this) {
        return function(objecttype, tools) {
          return tools.push(new ToolboxTool({
            name: "detail.show-nested-with-linkobjects",
            loca_key: "detail.show-nested-linkeds-in-search",
            loca_key_attrs: {
              linkedname: ez5.schema.CURRENT._objecttype_by_name[objecttype]._name_localized
            },
            group: "object",
            run: function() {
              return _this.showLinkObjectsInsideNested(objecttype);
            }
          }));
        };
      })(this);
      for (objecttype in ref) {
        value = ref[objecttype];
        if (value.ids.length === 0) {
          continue;
        }
        fn(objecttype, tools);
      }
    }
    tools.push.apply(tools, this.object.getDetailTools({
      search: this.getMainSearch()
    }));
    return tools;
  };

  DetailSidebar.prototype.renderChangeHistory = function() {
    var i, len, plugin, ref, ref1;
    this.__changeHistoryEnabled = true;
    ref = this.__plugins;
    for (i = 0, len = ref.length; i < len; i++) {
      plugin = ref[i];
      if (!plugin.isDisabled()) {
        if ((ref1 = plugin.getButton()) != null) {
          ref1.disable();
        }
      }
    }
    if (this.object.changelog().length === 0) {
      this.mainPane.empty("center");
      this.__waitBlock.show();
      return this.object.loadFromDbWithFormat("full").done((function(_this) {
        return function() {
          _this.__waitBlock.hide();
          return _this.__renderHistoryBrowser();
        };
      })(this));
    } else {
      return this.__renderHistoryBrowser();
    }
  };

  DetailSidebar.prototype.getContainer = function() {
    return this.container;
  };

  DetailSidebar.prototype.__getCollectionManager = function() {
    var ref;
    return (ref = this._sidebar._getSearch()) != null ? ref._collectionManager : void 0;
  };

  DetailSidebar.prototype.__getCollectionSelection = function() {
    var ref;
    return (ref = this._sidebar._getSearch()) != null ? ref._collection : void 0;
  };

  DetailSidebar.prototype.__renderHistoryBrowser = function() {
    var activePlugins, closeButton, i, len, plugin, ref, ref1, ref2;
    activePlugins = this.getActivePlugins();
    for (i = 0, len = activePlugins.length; i < len; i++) {
      plugin = activePlugins[i];
      plugin.getButton().deactivate();
    }
    if ((ref = this.__toolboxFlyoutButtonBar) != null) {
      ref.disable();
    }
    if ((ref1 = this.__toolbarRightContent) != null) {
      ref1.disable();
    }
    if ((ref2 = this.__detailMaskSelector) != null) {
      ref2.disable();
    }
    closeButton = new LocaButton({
      ui: "detail.sidebar.change_history.close.button",
      loca_key: "detail.sidebar.change-history.close.button",
      onClick: (function(_this) {
        return function() {
          var j, l, len1, len2, ref3, ref4, ref5, ref6, ref7;
          for (j = 0, len1 = activePlugins.length; j < len1; j++) {
            plugin = activePlugins[j];
            plugin.getButton().activate();
          }
          ref3 = _this.__plugins;
          for (l = 0, len2 = ref3.length; l < len2; l++) {
            plugin = ref3[l];
            if (!plugin.isDisabled()) {
              if ((ref4 = plugin.getButton()) != null) {
                ref4.enable();
              }
              if ((ref5 = _this.__toolboxFlyoutButtonBar) != null) {
                ref5.enable();
              }
              if ((ref6 = _this.__toolbarRightContent) != null) {
                ref6.enable();
              }
              if ((ref7 = _this.__detailMaskSelector) != null) {
                ref7.enable();
              }
              _this.__changeHistoryEnabled = false;
            }
          }
          return _this.updateCenterContent();
        };
      })(this)
    });
    return this.mainPane.replace(this.object.renderHistoryBrowser(closeButton), "center");
  };

  DetailSidebar.prototype.getAssetBrowserPlugin = function() {
    var i, len, plugin, ref;
    ref = this.getActivePlugins();
    for (i = 0, len = ref.length; i < len; i++) {
      plugin = ref[i];
      if (plugin instanceof AssetBrowserDetailPlugin) {
        return plugin;
      }
    }
  };

  DetailSidebar.prototype.__updateByIndex = function(index) {
    var deferred, globalObjectId, includeDeleted, ref, ref1;
    globalObjectId = this.__next_previous_global_object_ids[index];
    if (!globalObjectId) {
      return CUI.rejectedPromise();
    }
    this.__navigationPreviousNext.disable();
    this.__waitBlock.show();
    if ((ref = this.__previousButton) != null) {
      ref.disable();
    }
    if ((ref1 = this.__nextButton) != null) {
      ref1.disable();
    }
    deferred = new CUI.Deferred();
    deferred.always((function(_this) {
      return function() {
        _this.__navigationPreviousNext.enable();
        return _this.__waitBlock.hide();
      };
    })(this));
    CUI.Events.trigger({
      type: "focus-sidebar-selection",
      node: window,
      info: {
        global_object_id: globalObjectId
      }
    });
    includeDeleted = TrashSearchManager.canSeeDeleted();
    ResultObject.loadFromGlobalObjectId(globalObjectId, "short", null, true, false, includeDeleted).done((function(_this) {
      return function(resultObject) {
        _this.__global_object_id = globalObjectId;
        delete _this.__asset_browser_idx;
        _this.load();
      };
    })(this)).fail(deferred.reject);
    return deferred.promise();
  };

  DetailSidebar.prototype.getNavigationPreviousNext = function() {
    if (!this.__next_previous_global_object_ids) {
      return;
    }
    this.__navigationPreviousNext = new NavigationToolbar({
      append_count_label: false,
      short: true,
      centered: true,
      onLoadPage: (function(_this) {
        return function(page) {
          return _this.__updateByIndex(page);
        };
      })(this)
    });
    return this.__navigationPreviousNext;
  };

  DetailSidebar.prototype.__updateNavigationPreviousNext = function() {
    var index, ref;
    if (!this.__navigationPreviousNext || !this.__next_previous_global_object_ids) {
      return;
    }
    index = CUI.util.idxInArray((ref = this.object) != null ? ref.getGlobalObjectId() : void 0, this.__next_previous_global_object_ids);
    this.__navigationPreviousNext.update({
      count: this.__next_previous_global_object_ids.length,
      offset: index,
      limit: 1
    });
  };

  DetailSidebar.prototype.__getNextPreviousGlobalObjectIds = function(next_previous_global_object_ids) {
    var nextPreviousGlobalObjectIds, ref;
    nextPreviousGlobalObjectIds = next_previous_global_object_ids;
    if (nextPreviousGlobalObjectIds && (ref = !this._global_object_id, indexOf.call(nextPreviousGlobalObjectIds, ref) >= 0)) {
      nextPreviousGlobalObjectIds.unshift(this._global_object_id);
    }
    return nextPreviousGlobalObjectIds;
  };

  DetailSidebar.prototype.__isPluginAvailable = function(plugin) {
    return plugin.isAvailable();
  };

  DetailSidebar.prototype.__searchLinkObjectsInsideNesteds = function() {
    this.__linkedNestedIdsPerObjecttype = {};
    this.object.mask.invokeOnFields("detail", true, ((function(_this) {
      return function(field, data, depth) {
        var base, fieldName, i, len, nestedObject, objectId, objectType, ref, ref1;
        if (!(field instanceof LinkedObject) || field instanceof TreeColumn || !field.insideNested() || !data) {
          return;
        }
        objectType = field.linkMask().table.name();
        if (!ez5.schema.CURRENT._objecttype_by_name[objectType].in_main_search) {
          return;
        }
        if ((base = _this.__linkedNestedIdsPerObjecttype)[objectType] == null) {
          base[objectType] = {
            ids: [],
            fields: []
          };
        }
        for (i = 0, len = data.length; i < len; i++) {
          nestedObject = data[i];
          fieldName = field.name();
          objectId = (ref = nestedObject[fieldName]) != null ? ref._system_object_id : void 0;
          if (objectId) {
            _this.__linkedNestedIdsPerObjecttype[objectType].ids.push(objectId);
          }
        }
        if (((ref1 = _this.__linkedNestedIdsPerObjecttype[objectType].ids) != null ? ref1.length : void 0) > 0) {
          return _this.__linkedNestedIdsPerObjecttype[objectType].fields.push(field);
        } else {
          return delete _this.__linkedNestedIdsPerObjecttype[objectType];
        }
      };
    })(this)), this.object.getData()[this.object.objecttype()]);
  };

  DetailSidebar.prototype.showLinkObjectsInsideNested = function(objecttype) {
    var _mask, query, search_data;
    _mask = this.__linkedNestedIdsPerObjecttype[objecttype].fields[0].linkMask();
    search_data = {
      _system_object_id: this.__linkedNestedIdsPerObjecttype[objecttype].ids.join(",")
    };
    query = new QueryElementField({
      data: search_data,
      field: new SystemObjectIdColumn(_mask)
    });
    this.__search.showInSearch(query);
  };

  return DetailSidebar;

})(CUI.Element);

ez5.session_ready(function() {
  return DetailSidebar.plugins = new CUI.PluginRegistry({
    "class": DetailSidebarPlugin
  });
});

CUI.ready(function() {
  CUI.Events.registerEvent({
    type: ["detail-sidebar-render-object"]
  });
  return CUI.Events.registerEvent({
    type: "focus-sidebar-selection"
  });
});
// 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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

ez5.FullscreenDetailSidebar = (function(superClass) {
  extend(FullscreenDetailSidebar, superClass);

  function FullscreenDetailSidebar() {
    return FullscreenDetailSidebar.__super__.constructor.apply(this, arguments);
  }

  FullscreenDetailSidebar.prototype.getCurrentTools = function() {
    var notAllowedTools, tools;
    tools = FullscreenDetailSidebar.__super__.getCurrentTools.call(this);
    notAllowedTools = ["object.edit.sidebar", "object.copy.sidebar", "detail.fullscreen"];
    tools = tools.filter(function(tool) {
      var ref;
      return ref = tool.getName(), indexOf.call(notAllowedTools, ref) < 0;
    });
    return tools;
  };

  FullscreenDetailSidebar.prototype.getToolbarRightContent = function() {
    var ref;
    if (!((ref = this.getResultObject().getData()._generated_rights) != null ? ref.write : void 0)) {
      return;
    }
    if (ez5.session.getPref("use_fullscreen") && (this._sidebar._collection != null)) {
      return new LocaButton({
        loca_key: "editor.button.pen",
        ui: "detail.sidebar.edit.button",
        onClick: (function(_this) {
          return function() {
            var ref1;
            _this._sidebar._collection.openModalEditor((ref1 = _this.object) != null ? ref1.data : void 0, false);
            return DetailFullscreen.triggerClose();
          };
        })(this)
      });
    }
  };

  FullscreenDetailSidebar.prototype.supportsFullscreen = function() {
    return false;
  };

  FullscreenDetailSidebar.prototype.render = function() {
    var content;
    content = FullscreenDetailSidebar.__super__.render.call(this);
    CUI.dom.setAttribute(this.container, "ui", "fullscreen.detail.sidebar.container");
    return content;
  };

  FullscreenDetailSidebar.prototype.onClose = function() {
    if (ez5.session.getPref("use_fullscreen")) {
      return DetailFullscreen.triggerClose();
    }
  };

  FullscreenDetailSidebar.prototype.__isPluginAvailable = function(plugin) {
    return FullscreenDetailSidebar.__super__.__isPluginAvailable.call(this, plugin) && plugin.isFullscreenAvailable();
  };

  FullscreenDetailSidebar.prototype.__getCollectionManager = function() {
    var ref, ref1;
    return (ref = this._sidebar._getSearch()) != null ? (ref1 = ref._collection) != null ? ref1._manager : void 0 : void 0;
  };

  FullscreenDetailSidebar.prototype.__getCollectionSelection = function() {
    var ref;
    return (ref = this.__getCollectionManager()) != null ? ref.getCollectionSelection() : void 0;
  };

  FullscreenDetailSidebar.prototype.changeHistoryAvailable = function() {
    return false;
  };

  return FullscreenDetailSidebar;

})(DetailSidebar);
// Generated by CoffeeScript 1.12.7
var HierarchyDetailPlugin,
  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;

HierarchyDetailPlugin = (function(superClass) {
  extend(HierarchyDetailPlugin, superClass);

  function HierarchyDetailPlugin() {
    return HierarchyDetailPlugin.__super__.constructor.apply(this, arguments);
  }

  HierarchyDetailPlugin.prototype.renderObject = function() {
    var object, ref;
    object = this._detailSidebar.object;
    if (!object.mask.isHierarchy() && !this._detailSidebar.object.mask.isPolyhierarchy()) {
      return;
    }
    if (this.__currentObjectRootId && this.__currentObjectRootId === object.getRootId()) {
      return;
    }
    this.__currentObjectRootId = object.getRootId();
    if ((ref = this.__hierarchyList) != null) {
      ref.destroy();
    }
    this.__hierarchyList = new DetailHierarchyList({
      sidebar: this._detailSidebar._sidebar,
      container: this._detailSidebar.browserLayout.left()
    });
    return this.__hierarchyList.init();
  };

  HierarchyDetailPlugin.prototype.isAvailable = function() {
    return this._detailSidebar.object.mask.isHierarchy() || this._detailSidebar.object.mask.isPolyhierarchy();
  };

  HierarchyDetailPlugin.prototype.isDisabled = function() {
    return !(this._detailSidebar.object.hasChildren() || this._detailSidebar.object.getParentId() || this._detailSidebar.object.getParents());
  };

  HierarchyDetailPlugin.prototype.getPane = function() {
    return "left";
  };

  HierarchyDetailPlugin.prototype.showDetail = function() {
    return this.__hierarchyList.loadObject(this._detailSidebar.object);
  };

  HierarchyDetailPlugin.prototype.prefName = function() {
    return "detail_sidebar_show_hierarchy";
  };

  HierarchyDetailPlugin.prototype.destroy = function() {
    var ref;
    delete this.__currentObjectRootId;
    if ((ref = this.__hierarchyList) != null) {
      ref.destroy();
    }
    this.__hierarchyList = null;
    return HierarchyDetailPlugin.__super__.destroy.call(this);
  };

  HierarchyDetailPlugin.prototype.getButtonLocaKey = function() {
    return "detail.sidebar.hierarchy.button";
  };

  return HierarchyDetailPlugin;

})(DetailSidebarPlugin);

ez5.session_ready(function() {
  return DetailSidebar.plugins.registerPlugin(HierarchyDetailPlugin);
});
// Generated by CoffeeScript 1.12.7
var AssetBrowserDetailPlugin,
  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;

AssetBrowserDetailPlugin = (function(superClass) {
  extend(AssetBrowserDetailPlugin, superClass);

  function AssetBrowserDetailPlugin() {
    return AssetBrowserDetailPlugin.__super__.constructor.apply(this, arguments);
  }

  AssetBrowserDetailPlugin.prototype.render = function() {
    CUI.Events.listen({
      type: "asset-browser-show-asset",
      node: this._detailSidebar.container,
      instance: this._detailSidebar,
      call: (function(_this) {
        return function(ev, info) {
          if (!_this.getButton().isActive()) {
            _this.getButton().activate();
          }
          return CUI.Events.trigger({
            node: _this.__assetBrowser,
            type: "show-asset",
            info: info
          });
        };
      })(this)
    });
    CUI.Events.listen({
      type: "flex-close",
      node: this._detailSidebar.container,
      instance: this._detailSidebar,
      call: (function(_this) {
        return function() {
          return _this.destroyActiveTool();
        };
      })(this)
    });
    CUI.Events.listen({
      type: "flex-open",
      node: this._detailSidebar.container,
      instance: this._detailSidebar,
      call: (function(_this) {
        return function() {
          return _this.startFirstTool();
        };
      })(this)
    });
    return this;
  };

  AssetBrowserDetailPlugin.prototype.getButtonLocaKey = function() {
    return "detail.sidebar.asset-browser.button";
  };

  AssetBrowserDetailPlugin.prototype.destroyActiveTool = function() {
    var ref, ref1;
    return (ref = this.__assetBrowser) != null ? (ref1 = ref.getActiveTool()) != null ? ref1.destroy() : void 0 : void 0;
  };

  AssetBrowserDetailPlugin.prototype.startFirstTool = function() {
    var ref;
    return (ref = this.__assetBrowser) != null ? ref.startFirstTool() : void 0;
  };

  AssetBrowserDetailPlugin.prototype.__destroyAssetBrowser = function() {
    var ref;
    if ((ref = this.__assetBrowser) != null) {
      ref.destroy();
    }
    this.__assetBrowser = null;
    if (this.__assetBrowserInfoControl) {
      this.__assetBrowserInfoControl.destroy();
      CUI.dom.remove(this.__assetBrowserInfoControl);
      this.__assetBrowserInfoControl = null;
    }
    return this;
  };

  AssetBrowserDetailPlugin.prototype.isAvailable = function() {
    var assets;
    assets = this._detailSidebar.object.getAssetsForBrowser(["detail", "standard"]);
    if (assets === false || assets.length === 0) {
      return false;
    } else {
      return true;
    }
  };

  AssetBrowserDetailPlugin.prototype.prefName = function() {
    return "show_asset_browser";
  };

  AssetBrowserDetailPlugin.prototype.prefDefault = function() {
    return true;
  };

  AssetBrowserDetailPlugin.prototype.hideDetail = function() {
    return this.__destroyAssetBrowser();
  };

  AssetBrowserDetailPlugin.prototype.showDetail = function() {
    var assets;
    this.__destroyAssetBrowser();
    assets = this._detailSidebar.object.getAssetsForBrowser(["detail", "standard"]);
    this.__assetBrowser = new AssetBrowser({
      ui: "asset.browser.detail",
      hires: true,
      img_alt: this._detailSidebar.object.renderAltText(),
      assets: assets,
      start_idx: this._asset_browser_idx
    });
    this._detailSidebar.mainPane.replace(this.__assetBrowser, "top");
    this.__assetBrowserInfoControl = new AssetBrowserInfoControl({
      assetBrowser: this.__assetBrowser,
      show_info_button: ez5.session.hasSystemRight("root", "frontend_features[asset_browser_metadata_tool]")
    });
    this._detailSidebar.mainPane.append(this.__assetBrowserInfoControl, "top");
    return this;
  };

  AssetBrowserDetailPlugin.prototype.getCenterContent = function() {};

  AssetBrowserDetailPlugin.prototype.getAssetBrowserCurrentIdx = function() {
    var ref;
    return (ref = this.__assetBrowser) != null ? ref.getCurrentIdx() : void 0;
  };

  AssetBrowserDetailPlugin.prototype.getAssetBrowserVideoPlayer = function() {
    var ref;
    return (ref = this.__assetBrowser) != null ? ref.getVideoPlayer() : void 0;
  };

  AssetBrowserDetailPlugin.prototype.getCurrentAsset = function() {
    var ref;
    return (ref = this.__assetBrowser) != null ? ref.getCurrentAsset() : void 0;
  };

  AssetBrowserDetailPlugin.prototype.setAssetBrowserIdx = function(idx) {
    var ref;
    if (!this.__assetBrowser) {
      return;
    }
    if (idx >= this.__assetBrowser.getAssets().length) {
      return;
    }
    return (ref = this.__assetBrowser) != null ? ref.setIdx(idx) : void 0;
  };

  AssetBrowserDetailPlugin.prototype.destroy = function() {
    this.__destroyAssetBrowser();
    return AssetBrowserDetailPlugin.__super__.destroy.call(this);
  };

  return AssetBrowserDetailPlugin;

})(DetailSidebarPlugin);

ez5.session_ready(function() {
  return DetailSidebar.plugins.registerPlugin(AssetBrowserDetailPlugin);
});
// 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.PublishDetailPlugin = (function(superClass) {
  extend(PublishDetailPlugin, superClass);

  function PublishDetailPlugin() {
    return PublishDetailPlugin.__super__.constructor.apply(this, arguments);
  }

  PublishDetailPlugin.prototype.renderObject = function() {};

  PublishDetailPlugin.prototype.isAvailable = function() {
    if (!ez5.session.isDebug()) {
      return false;
    }
    if (ez5.session.hasSystemRight("root", "system.api.publish.get", "system.api.publish[get]")) {
      return true;
    } else {
      return false;
    }
  };

  PublishDetailPlugin.prototype.isDisabled = function() {
    return false;
  };

  PublishDetailPlugin.prototype.getPane = function() {
    return "top";
  };

  PublishDetailPlugin.prototype.setInactive = function() {
    PublishDetailPlugin.__super__.setInactive.call(this);
    return CUI.Events.ignore({
      instance: this
    });
  };

  PublishDetailPlugin.prototype.showDetail = function() {
    var _delete, _post, addr, buttons, dt, lbl, load_data, new_rows, obj, published;
    obj = this._detailSidebar.object.getData();
    published = {
      publish: []
    };
    EventPoller.listen({
      filter: {
        type: "OBJECT_INDEX",
        objecttype: obj._objecttype,
        object_id: obj[obj._objecttype]._id
      },
      instance: this,
      call: (function(_this) {
        return function(events) {
          load_data();
          return dt.reload();
        };
      })(this)
    });
    addr = (function(_this) {
      return function(url) {
        return "[" + url + "](" + url + ")";
      };
    })(this);
    load_data = (function(_this) {
      return function() {
        var col, col_lbl, i, len, p, publish_url, ref;
        published.publish = [];
        ref = obj._published || [];
        for (i = 0, len = ref.length; i < len; i++) {
          p = ref[i];
          col = PublishColumn.getCollectorFromBaseConfig(p.collector);
          if (col) {
            col_lbl = ez5.loca.getBestFrontendValue(col.displayname);
          } else {
            col_lbl = null;
          }
          if (!col_lbl) {
            col_lbl = p.collector;
          }
          if (col != null ? col.url : void 0) {
            col_lbl = "[" + col_lbl + "](" + col.url + ")";
          }
          publish_url = p.publish_uri;
          if (col != null ? col.prefix : void 0) {
            publish_url = col.prefix + publish_url;
          }
          published.publish.push({
            _id: p._id,
            version: p.version,
            timestamp: ez5.format_date_and_time(p.timestamp_created),
            easydb_uri: addr(p.easydb_uri),
            publish_uri: addr(publish_url),
            collector: col_lbl
          });
        }
      };
    })(this);
    lbl = new LocaLabel({
      appearance: "title",
      "class": "ez5-publish-detail-title",
      loca_key: "publish.detail.plugin.title",
      padded: true
    });
    new_rows = "none";
    _post = false;
    _delete = false;
    if (ez5.session.hasSystemRight("root")) {
      _post = true;
      _delete = true;
    }
    if (ez5.session.hasSystemRight("system.api.publish.post", "system.api.publish[post]")) {
      _post = true;
    }
    if (ez5.session.hasSystemRight("system.api.publish.delete", "system.api.publish[delete]")) {
      _delete = true;
    }
    if (_delete) {
      new_rows = "remove_only";
    }
    if (_post) {
      buttons = [
        {
          loca_key: "publish.detail.plugin.plus_publish",
          group: "plus-minus",
          onClick: (function(_this) {
            return function() {
              return _this.openPublishDialog().done(function() {
                return dt.showWaitBlock();
              });
            };
          })(this)
        }
      ];
    } else {
      buttons = [];
    }
    load_data();
    dt = new CUI.DataTable({
      maximize: true,
      "class": "ez5-publish-detail-datatable",
      data: published,
      name: "publish",
      new_rows: new_rows,
      buttons: buttons,
      onBeforeRowRemove: (function(_this) {
        return function(data, ev) {
          return CUI.confirm({
            text: $$("publish.detail.plugin.confirm.delete.md"),
            markdown: true
          });
        };
      })(this),
      onRowRemove: (function(_this) {
        return function(data, ev) {
          return _this.unpublish(data).done(function() {
            return dt.showWaitBlock();
          });
        };
      })(this),
      fields: [
        {
          form: {
            label: $$("publish.detail.plugin.table.created")
          },
          type: CUI.Output,
          name: "timestamp"
        }, {
          form: {
            label: $$("publish.detail.plugin.table.collector")
          },
          type: CUI.Output,
          markdown: true,
          name: "collector"
        }, {
          form: {
            label: $$("publish.detail.plugin.table.publish_uri")
          },
          type: CUI.Output,
          markdown: true,
          name: "publish_uri"
        }, {
          form: {
            label: $$("publish.detail.plugin.table.easydb_uri")
          },
          type: CUI.Output,
          markdown: true,
          name: "easydb_uri"
        }
      ]
    });
    dt.start();
    this._detailSidebar.mainPane.replace([lbl, dt], "top");
  };

  PublishDetailPlugin.prototype.unpublish = function(data) {
    return ez5.api.publish({
      type: "DELETE",
      api: "/" + data._id
    });
  };

  PublishDetailPlugin.getCollectorSelect = function(opts) {
    var collector, collector_opts, i, len, ref, ref1, select;
    collector_opts = [];
    if (opts.placeholder) {
      collector_opts.push({
        text: opts.placeholder,
        value: null
      });
    }
    ref1 = ((ref = ez5.session.getBaseConfig().publish) != null ? ref.collectors : void 0) || [];
    for (i = 0, len = ref1.length; i < len; i++) {
      collector = ref1[i];
      collector_opts.push({
        text: ez5.loca.getBestFrontendValue(collector.displayname) || collector.internalname,
        value: collector
      });
    }
    select = {
      type: CUI.Select,
      options: collector_opts,
      name: "collector"
    };
    if (opts.label) {
      select.form = {
        label: opts.label
      };
    }
    return select;
  };

  PublishDetailPlugin.prototype.openPublishDialog = function() {
    var dfr, form, i, k, len, mod, obj, publish_data, ref, saveButton, set_form_status, type_opts;
    dfr = new CUI.Deferred();
    type_opts = [];
    ref = ["frontend", "object"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      type_opts.push({
        text: $$("publish.detail.plugin.dialog.form.type." + k),
        value: k
      });
    }
    publish_data = {};
    obj = this._detailSidebar.object.getData();
    form = new CUI.Form({
      data: publish_data,
      onDataChanged: (function(_this) {
        return function() {
          return set_form_status();
        };
      })(this),
      fields: [
        ez5.PublishDetailPlugin.getCollectorSelect({
          label: $$("publish.detail.plugin.dialog.form.collector")
        }), {
          type: CUI.Input,
          form: {
            label: $$("publish.detail.plugin.dialog.form.doi_urn")
          },
          required: true,
          name: "doi_urn"
        }, {
          type: CUI.Output,
          form: {
            label: $$("publish.detail.plugin.dialog.form.publish_uri")
          },
          name: "publish_uri"
        }, {
          type: CUI.Select,
          form: {
            label: $$("publish.detail.plugin.dialog.form.type")
          },
          options: type_opts,
          name: "type"
        }, {
          type: CUI.Checkbox,
          form: {
            label: $$("publish.detail.plugin.dialog.form.use_version")
          },
          name: "use_version"
        }, {
          type: CUI.Output,
          form: {
            label: $$("publish.detail.plugin.dialog.form.easydb_uri")
          },
          name: "easydb_uri"
        }
      ]
    });
    set_form_status = (function(_this) {
      return function() {
        var easydb_uri, j, len1, ref1, ref2, use_version;
        use_version = form.getFieldsByName("use_version")[0];
        if (publish_data.type === "object") {
          use_version.enable();
        } else {
          use_version.disable();
          use_version.deactivate();
        }
        if (publish_data.type === "html") {
          easydb_uri = window.easydb_base_prefix + "#/detail/" + obj._system_object_id;
        } else if (publish_data.use_version) {
          easydb_uri = "/api/objects/" + obj._system_object_id + "/version/" + obj[obj._objecttype]._version;
        } else {
          easydb_uri = "/api/objects/" + obj._system_object_id;
        }
        publish_data.easydb_uri = ez5.getAbsoluteURL(easydb_uri);
        publish_data.publish_uri = (((ref1 = publish_data.collector) != null ? ref1.prefix : void 0) || "") + publish_data.doi_urn.trim();
        if (CUI.util.isEmpty(publish_data.doi_urn.trim())) {
          saveButton.disable();
        } else {
          saveButton.enable();
        }
        ref2 = ["easydb_uri", "publish_uri"];
        for (j = 0, len1 = ref2.length; j < len1; j++) {
          k = ref2[j];
          form.getFieldsByName(k)[0].displayValue();
        }
      };
    })(this);
    saveButton = new LocaButton({
      loca_key: "publish.detail.plugin.dialog.save_button",
      onClick: (function(_this) {
        return function(ev, btn) {
          btn.disable();
          publish_data.publish_uri = publish_data.doi_urn.trim();
          return _this.publishObject(ev, publish_data).always(function() {
            return btn.enable();
          }).done(function() {
            mod.destroy();
            return dfr.resolve();
          });
        };
      })(this)
    });
    form.start();
    set_form_status();
    mod = new CUI.Modal({
      cancel: true,
      size: "xs",
      onCancel: (function(_this) {
        return function() {
          dfr.reject();
        };
      })(this),
      cancel_with_click_on_backdrop: false,
      pane: {
        footer_right: [saveButton],
        title: $$("publish.detail.plugin.dialog.title"),
        content: form,
        padded: true
      }
    });
    mod.show();
    return dfr.promise();
  };

  PublishDetailPlugin.prototype.publishObject = function(ev, publish_data) {
    var json_data, obj, ref;
    obj = this._detailSidebar.object.getData();
    json_data = [
      {
        publish: {
          system_object_id: obj._system_object_id,
          collector: ((ref = publish_data.collector) != null ? ref.internalname : void 0) || "",
          easydb_uri: publish_data.easydb_uri,
          publish_uri: publish_data.publish_uri
        }
      }
    ];
    if (publish_data.type === "object" && publish_data.use_version) {
      json_data[0].publish.version = obj[obj._objecttype]._version;
    }
    if (ev.hasModifierKey()) {
      console.debug(CUI.util.dump(json_data));
      return;
    }
    return ez5.api.publish({
      json_data: json_data
    });
  };

  PublishDetailPlugin.prototype.prefName = function() {
    return "detail_sidebar_show_publish";
  };

  PublishDetailPlugin.prototype.destroy = function() {
    return PublishDetailPlugin.__super__.destroy.call(this);
  };

  PublishDetailPlugin.prototype.getButtonLocaKey = function() {
    return "detail.sidebar.publish.button";
  };

  return PublishDetailPlugin;

})(DetailSidebarPlugin);

ez5.session_ready(function() {
  return DetailSidebar.plugins.registerPlugin(ez5.PublishDetailPlugin);
});
// Generated by CoffeeScript 1.12.7
var ResultDetailFullscreen,
  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;

ResultDetailFullscreen = (function(superClass) {
  extend(ResultDetailFullscreen, superClass);

  function ResultDetailFullscreen() {
    return ResultDetailFullscreen.__super__.constructor.apply(this, arguments);
  }

  ResultDetailFullscreen.prototype.readOpts = function() {
    ResultDetailFullscreen.__super__.readOpts.call(this);
    this.__containers = [this._container, this._container_thumbnails];
    this.__names = ["long", "thumbnail"];
    return this.__render_types = ["hires", "standard"];
  };

  ResultDetailFullscreen.prototype.initOpts = function() {
    ResultDetailFullscreen.__super__.initOpts.call(this);
    return this.addOpts({
      container: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isElement(v);
        }
      },
      container_thumbnails: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isElement(v);
        }
      },
      page_size: {
        mandatory: true,
        check: function(v) {
          return v >= 1;
        }
      },
      onElementsLoaded: {
        mandatory: false,
        check: Function
      },
      ui: {
        check: String
      }
    });
  };

  ResultDetailFullscreen.prototype.init = function() {
    var c, i, idx, len, ref;
    ref = this.__containers;
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      c = ref[idx];
      new ResultDynamicLoadingFullscreen({
        container: c,
        search: this.getSearch(),
        onElementLoaded: this._onElementsLoaded
      });
    }
    if (this._ui) {
      CUI.dom.setAttribute(this._container, "ui", this._ui + ":container");
      CUI.dom.setAttribute(this._container_thumbnails, "ui", this._ui + ":container_thumbnails");
    }
    return this;
  };

  ResultDetailFullscreen.prototype.addToRequest = function(request) {
    request.limit = this._page_size || 100;
    if (request.offset % request.limit !== 0) {
      request.offset = Math.floor(request.offset / request.limit) * request.limit;
    }
    request.format = "short";
    return request.ignore_hierarchy = true;
  };

  ResultDetailFullscreen.prototype.showResult = function(request, data) {
    var c_idx, cnt, d, i, idx, j, len, len1, loader, o, offset, ref, ref1;
    ref = this.__containers;
    for (c_idx = i = 0, len = ref.length; i < len; c_idx = ++i) {
      cnt = ref[c_idx];
      CUI.dom.empty(cnt);
      loader = CUI.dom.data(cnt, "loader");
      ref1 = data.objects;
      for (idx = j = 0, len1 = ref1.length; j < len1; idx = ++j) {
        o = ref1[idx];
        offset = request.offset + idx;
        d = loader.getPlaceholder({
          "class": "result-detail-fullscreen-" + this.__names[c_idx],
          offset: offset,
          idx: idx,
          request: request,
          object: o,
          render_type: this.__render_types[c_idx]
        });
        CUI.dom.setAttribute(d, "ui", "result.detail.fullscreen.object:" + this.__names[c_idx]);
        CUI.dom.append(cnt, d);
      }
      CUI.scheduleCallback({
        ms: 200,
        call: (function(_this) {
          return function() {
            return loader.markLoadMe();
          };
        })(this)
      });
    }
    return this;
  };

  return ResultDetailFullscreen;

})(SearchManager);
// Generated by CoffeeScript 1.12.7
var DetailFullscreen,
  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;

DetailFullscreen = (function(superClass) {
  extend(DetailFullscreen, superClass);

  function DetailFullscreen() {
    return DetailFullscreen.__super__.constructor.apply(this, arguments);
  }

  DetailFullscreen.prototype.initOpts = function() {
    DetailFullscreen.__super__.initOpts.call(this);
    return this.addOpts({
      global_object_id: {
        check: String
      },
      search: {
        check: Search
      },
      collection: {
        check: CollectionWithDetail
      },
      offset: {
        "default": 0,
        check: function(v) {
          return v >= 0;
        }
      },
      asset_browser_idx: {
        check: function(v) {
          return v >= 0;
        }
      },
      video_player_start: {
        check: Boolean,
        "default": false
      },
      video_player_time: {
        check: function(v) {
          return v >= 0;
        }
      },
      onClose: {
        check: Function
      }
    });
  };

  DetailFullscreen.prototype.readOpts = function() {
    var ref, ref1, ref2, ref3, ref4;
    DetailFullscreen.__super__.readOpts.call(this);
    this.__asset_browser_idx = parseInt(this._asset_browser_idx) || 0;
    this.__global_object_id = this._global_object_id;
    if (!this.__global_object_id) {
      if (this._search) {
        this.__global_object_id = (ref = this._search.getLastData()) != null ? (ref1 = ref.objects[0]) != null ? ref1._global_object_id : void 0 : void 0;
      } else if (this._collection) {
        this.__global_object_id = (ref2 = this._collection.getSearch()) != null ? (ref3 = ref2.getLastData()) != null ? (ref4 = ref3.objects[0]) != null ? ref4._global_object_id : void 0 : void 0 : void 0;
      }
    }
    this.render();
    this.__horizontalLayout = new CUI.HorizontalLayout({
      "class": "ez5-detail-fullscreen",
      right: {
        "class": "ez5-detail-fullscreen-right",
        content: true,
        flexHandle: {
          state_name: "fullscreen-right",
          hidden: false,
          closed: true
        }
      },
      center: {
        content: this.container.DOM
      }
    });
    this.__fullscreenDetailInfo = new FullscreenDetailInfo({
      layout: this.__horizontalLayout,
      side: "right",
      search: this._search,
      getGlobalObjectId: (function(_this) {
        return function() {
          return _this.__global_object_id;
        };
      })(this),
      collection: this._collection
    });
    document.body.appendChild(this.__horizontalLayout.DOM);
    this.load();
    if (ez5.session.getPref("use_fullscreen")) {
      return this.__fullscreenDetailInfo.loadObject();
    }
  };

  DetailFullscreen.prototype.close = function() {
    var assetBrowser, currentDiv, ref;
    currentDiv = this.getCurrent();
    if (!currentDiv) {
      if (typeof this._onClose === "function") {
        this._onClose();
      }
      this.destroy();
      return;
    }
    CUI.Events.trigger({
      type: "fullscreen-object-changed",
      node: window,
      info: {
        global_object_id: this.__global_object_id
      }
    });
    assetBrowser = this.__getAssetBrowser(currentDiv);
    if (assetBrowser != null ? (ref = assetBrowser.activeTool) != null ? ref.isActive() : void 0 : void 0) {
      assetBrowser.activeTool.destroy();
      return assetBrowser.activeTool = null;
    } else {
      if (typeof this._onClose === "function") {
        this._onClose();
      }
      return this.destroy();
    }
  };

  DetailFullscreen.prototype.destroy = function() {
    var ref, ref1;
    if ((ref = this.container) != null) {
      ref.destroy();
    }
    this.container = null;
    if ((ref1 = this.__horizontalLayout) != null) {
      ref1.destroy();
    }
    this.__horizontalLayout = null;
    CUI.Events.ignore({
      instance: this
    });
    return DetailFullscreen.__super__.destroy.call(this);
  };

  DetailFullscreen.prototype.render = function() {
    var clsBtn, fullscreenBtn;
    this.container = new CUI.Template({
      name: "ng-detail-fullscreen",
      map: {
        result: true,
        prev: true,
        next: true,
        info: true,
        object: true,
        header_left: true,
        header_center: true,
        header_right: true,
        bottom: true,
        bottom_left_scroll: true,
        bottom_right_scroll: true
      }
    });
    fullscreenBtn = new LocaButton({
      "switch": true,
      disabled: !CUI.dom.fullscreenEnabled(),
      ui: "detail.fullscreen.fullscreen.button",
      loca_key: "detail.fullscreen.button.fullscreen",
      appearance: "transparent-border",
      activate_initial: false,
      group: "fullscreen-upper-right-menu",
      onActivate: (function(_this) {
        return function(btn) {
          CUI.dom.requestFullscreen(_this.container.DOM).done(function() {
            return btn.deactivate({
              position_only: true
            });
          });
        };
      })(this),
      onDeactivate: (function(_this) {
        return function(btn, flags, ev) {
          if (!flags.position_only) {
            CUI.dom.exitFullscreen();
          }
        };
      })(this)
    });
    clsBtn = new LocaButton({
      ui: "detail.fullscreen.close.button",
      loca_key: "detail.fullscreen.closed-button",
      "class": "ez5-detail-fullscreen-close-button",
      group: "fullscreen-upper-right-menu",
      appearance: "transparent-border",
      onClick: (function(_this) {
        return function() {
          if (ez5.session.getPref("use_fullscreen")) {
            if (typeof _this._onClose === "function") {
              _this._onClose();
            }
            return _this.destroy();
          } else {
            return _this.close();
          }
        };
      })(this)
    });
    this.container.append(new CUI.Buttonbar({
      buttons: [fullscreenBtn, clsBtn]
    }), "header_right");
    CUI.dom.setClassOnMousemove({
      element: this.container.DOM,
      "class": "ez5-detail-fullscreen-mousemoved",
      instance: this,
      delayRemove: (function(_this) {
        return function() {
          return _this.__keep_mousemoved_class;
        };
      })(this)
    });
    CUI.Events.listen({
      type: "toolbox-before-show",
      instance: this,
      call: (function(_this) {
        return function(ev, info) {
          CUI.util.removeFromArray(null, info.tools, function(v) {
            var ref;
            return (ref = v.getName()) === "object.detail";
          });
        };
      })(this)
    });
    CUI.Events.listen({
      node: this.container.map.result,
      type: "click",
      instance: this,
      selector: ".result-dynamic[global-object-id]",
      call: (function(_this) {
        return function(ev) {
          var asset, div;
          div = ev.getCurrentTarget();
          asset = CUI.dom.closestUntil(ev.getTarget(), ".ez-asset", div);
          _this.__closeActiveTool(_this.getCurrent());
          return _this.scrollObjectIntoView(div.getAttribute("global-object-id"), parseInt(asset != null ? asset.getAttribute("asset-browser-idx") : void 0) || 0);
        };
      })(this)
    });
    CUI.Events.listen({
      type: "result-dynamic-loading-done",
      node: this.container.map.result,
      instance: this,
      call: (function(_this) {
        return function(ev) {
          if (_this.isDestroyed()) {
            return;
          }
          return _this.hideAndShowNaviButtons();
        };
      })(this)
    });
    CUI.Events.listen({
      node: this.container,
      type: "asset-detail",
      call: (function(_this) {
        return function(ev, info) {
          if (info.type === "destroy") {
            if (_this.isDestroyed()) {
              return;
            }
            if (_this.__avoid_close) {
              _this.__avoid_close = false;
              return;
            }
            if (typeof _this._onClose === "function") {
              _this._onClose();
            }
            return _this.destroy();
          }
        };
      })(this)
    });
    this.initResultScroll();
    this.initObjectNavi();
    return this.container;
  };

  DetailFullscreen.prototype.scrollObjectIntoView = function(gid, asset_browser_idx, direction) {
    var co, idx, o_el, selector;
    if (!this.container) {
      return;
    }
    this.__global_object_id = gid;
    this.__fullscreenDetailInfo.updateObject();
    o_el = this.container.map.object;
    selector = "div[global-object-id='" + gid + "']";
    this.__current_div = CUI.dom.matchSelector(o_el, selector)[0];
    if (!this.__current_div) {
      this.__asset_browser_idx = asset_browser_idx || 0;
      this._search = null;
      co = new CollectionObject({
        _global_object_id: gid
      });
      this._collection = new CollectionMemory();
      this._collection.insertObjects([co]).done((function(_this) {
        return function() {
          return _this.load();
        };
      })(this));
      return;
    }
    if (o_el.firstChild && this.__current_div) {
      idx = parseInt(CUI.dom.getAttribute(this.__current_div, "idx"));
      CUI.dom.setStyle(o_el.firstChild, {
        marginLeft: "-" + (idx * 100) + "%"
      });
      CUI.dom.data(o_el, "loader").showAsset(this.__current_div, asset_browser_idx || 0).done((function(_this) {
        return function() {
          var assetBrowser, detailInfoButton, fullscreenDetailInfoButton;
          assetBrowser = _this.__getAssetBrowser(_this.__current_div);
          if (asset_browser_idx === null) {
            if (!asset_browser_idx || asset_browser_idx < 0) {
              if (direction === "prev") {
                if (_this.__getAssetCount(_this.__current_div) > 0) {
                  asset_browser_idx = _this.__getAssetCount(_this.__current_div) - 1;
                } else {
                  asset_browser_idx = 0;
                }
              } else {
                asset_browser_idx = 0;
              }
            }
            if ((assetBrowser != null ? assetBrowser.getAssets().length : void 0) > 0) {
              if (assetBrowser != null) {
                assetBrowser.setIdx(asset_browser_idx);
              }
            }
            _this.__fullscreenDetailInfo.updateAssetBrowserIdx(asset_browser_idx);
          }
          if (assetBrowser != null ? assetBrowser.getResultObject() : void 0) {
            if (assetBrowser.tools) {
              CUI.util.removeFromArray(null, assetBrowser.tools, function(value) {
                return value instanceof DetailInfo;
              });
              assetBrowser.tools.push(_this.__fullscreenDetailInfo);
              assetBrowser.updateTools(assetBrowser.getCurrentAsset());
              _this.__initVideoPlayer(assetBrowser);
              _this.__fullscreenDetailInfo.setToggleButton();
            } else {
              detailInfoButton = CUI.dom.matchSelector(_this.__current_div, "[ez5-loca-key='detail.info.button']")[0];
              if (detailInfoButton) {
                fullscreenDetailInfoButton = new LocaButton({
                  appearance: "transparent-border",
                  loca_key: "detail.info.button",
                  "switch": true,
                  onClick: function() {
                    return _this.__fullscreenDetailInfo.toggle();
                  }
                });
                _this.__fullscreenDetailInfo.setToggleButton(fullscreenDetailInfoButton);
                CUI.dom.replace(detailInfoButton, fullscreenDetailInfoButton);
              }
            }
          }
          asset_browser_idx = asset_browser_idx || 0;
          CUI.dom.data(_this.container.map.result, "loader").showAsset(gid, asset_browser_idx, true).done(function() {
            var el;
            if (_this.isDestroyed()) {
              return;
            }
            el = CUI.dom.matchSelector(_this.container.map.result, selector)[0];
            if (el) {
              return CUI.dom.scrollIntoView(el);
            }
          });
          return _this.__asset_browser_idx = asset_browser_idx;
        };
      })(this));
    } else {
      this.__asset_browser_idx = 0;
    }
    this.hideAndShowNaviButtons();
  };

  DetailFullscreen.prototype.__initVideoPlayer = function(assetBrowser) {
    var asset, videoPlayer;
    if (CUI.util.isUndef(this._video_player_time)) {
      return;
    }
    videoPlayer = assetBrowser != null ? assetBrowser.getVideoPlayer() : void 0;
    asset = assetBrowser.getCurrentAsset();
    if (videoPlayer) {
      this._video_player_time = void 0;
      videoPlayer.start(asset);
      videoPlayer.setCurrentTime(this._video_player_time);
      if (this._video_player_start) {
        videoPlayer.play();
      }
    }
  };

  DetailFullscreen.prototype.getCurrentAssetBrowser = function() {
    var assetBrowser;
    assetBrowser = CUI.dom.findElement(this.container.map.object, ".ez5-asset-browser-hires");
    return CUI.dom.data(assetBrowser, "element");
  };

  DetailFullscreen.prototype.getCurrent = function() {
    return this.__current_div;
  };

  DetailFullscreen.prototype.load = function() {
    var chunk, co, col, dfr, ref, start_search;
    dfr = new CUI.Deferred();
    chunk = 100;
    start_search = (function(_this) {
      return function(search) {
        var scroll_to_object;
        scroll_to_object = function() {
          var ref;
          if (!_this.__global_object_id && _this._collection instanceof CollectionSelection) {
            _this.__global_object_id = (ref = _this._collection.getObjects()[_this._offset || 0]) != null ? ref.getGlobalObjectId() : void 0;
          }
          if (_this.__global_object_id) {
            return _this.scrollObjectIntoView(_this.__global_object_id, _this.__asset_browser_idx);
          }
        };
        return search.execute(new Request({
          offset: Math.floor(_this._offset / chunk) * chunk,
          exclusive_show: true,
          searchManagers: [
            new ResultDetailFullscreen({
              ui: "detail.fullscreen.result.detail",
              container: _this.container.map.object,
              container_thumbnails: _this.container.map.result,
              page_size: chunk,
              onElementsLoaded: function() {
                if (!_this.__userInteracted) {
                  return CUI.scheduleCallback({
                    ms: 500,
                    call: scroll_to_object
                  });
                }
              }
            })
          ]
        })).done(function() {
          return scroll_to_object();
        }).fail(dfr.reject);
      };
    })(this);
    if (this._search) {
      chunk = ((ref = this._search.getLastData()) != null ? ref.limit : void 0) || 100;
      start_search(this._search);
    } else if (this._collection) {
      start_search(new SearchCollectionHeadless({
        collection: this._collection
      }));
    } else if (this.__global_object_id) {
      co = new CollectionObject({
        _global_object_id: this.__global_object_id
      });
      col = new CollectionMemory();
      col.insertObjects([co]).done((function(_this) {
        return function() {
          return start_search(new SearchCollectionHeadless({
            collection: col
          }));
        };
      })(this));
    }
    return dfr.promise();
  };

  DetailFullscreen.prototype.hideAndShowNaviButtons = function() {
    var ab_count, ab_idx, dim, obj;
    dim = CUI.dom.getDimensions(this.container.map.result);
    if (dim.scrollLeft === 0) {
      CUI.dom.addClass(this.container.map.bottom, "ez5-detail-fullscreen-scroll-is-left");
    } else {
      CUI.dom.removeClass(this.container.map.bottom, "ez5-detail-fullscreen-scroll-is-left");
    }
    if (dim.scrollWidth - dim.scrollLeft - dim.clientWidth === 0) {
      CUI.dom.addClass(this.container.map.bottom, "ez5-detail-fullscreen-scroll-is-right");
    } else {
      CUI.dom.removeClass(this.container.map.bottom, "ez5-detail-fullscreen-scroll-is-right");
    }
    obj = this.getCurrent();
    if (obj) {
      ab_idx = this.__asset_browser_idx;
      ab_count = this.__getAssetCount(obj);
    }
    if ((obj != null ? obj.previousElementSibling : void 0) || ab_idx > 0) {
      CUI.dom.removeClass(this.container.DOM, "ez5-detail-fullscreen-hide-prev-button");
    } else {
      CUI.dom.addClass(this.container.DOM, "ez5-detail-fullscreen-hide-prev-button");
    }
    if ((obj != null ? obj.nextElementSibling : void 0) || ab_idx < ab_count - 1) {
      CUI.dom.removeClass(this.container.DOM, "ez5-detail-fullscreen-hide-next-button");
    } else {
      CUI.dom.addClass(this.container.DOM, "ez5-detail-fullscreen-hide-next-button");
    }
  };

  DetailFullscreen.prototype.initResultScroll = function() {
    var csTimeout, scrollContainer, stopScrollContainer, wheelTimeout;
    csTimeout = null;
    wheelTimeout = null;
    scrollContainer = (function(_this) {
      return function(diff, node, level) {
        if (level == null) {
          level = 0;
        }
        if (_this.isDestroyed()) {
          return;
        }
        _this.__keep_mousemoved_class = true;
        _this.container.map.result.scrollLeft += diff * (level + 1);
        _this.hideAndShowNaviButtons();
        return csTimeout = CUI.setTimeout(function() {
          if (!CUI.dom.isVisible(node)) {
            return;
          }
          return scrollContainer(diff, node, level + 1);
        }, 50);
      };
    })(this);
    this.hideAndShowNaviButtons();
    stopScrollContainer = (function(_this) {
      return function() {
        _this.__keep_mousemoved_class = false;
        CUI.clearTimeout(csTimeout);
        return csTimeout = null;
      };
    })(this);
    CUI.Events.listen({
      node: this.container.map.result,
      instance: this,
      type: "wheel",
      call: (function(_this) {
        return function(ev) {
          var deltaX, deltaY, scrollAmount;
          _this.__userInteracted = true;
          ev.preventDefault();
          deltaX = ev.getNativeEvent().deltaX;
          deltaY = ev.getNativeEvent().deltaY;
          scrollAmount = 0;
          if (Math.abs(deltaX) > Math.abs(deltaY)) {
            scrollAmount = deltaX;
          } else if (Math.abs(deltaY) > 3) {
            scrollAmount = deltaY;
          }
          if (Math.abs(scrollAmount) > 1) {
            _this.container.map.result.scrollLeft += scrollAmount;
            _this.hideAndShowNaviButtons();
            _this.__keep_mousemoved_class = true;
            CUI.clearTimeout(wheelTimeout);
            return wheelTimeout = CUI.setTimeout(function() {
              return _this.__keep_mousemoved_class = false;
            }, 1000);
          }
        };
      })(this)
    });
    CUI.Events.listen({
      node: this.container.map.bottom_left_scroll,
      instance: this,
      type: "mousedown",
      call: (function(_this) {
        return function(ev) {
          _this.__userInteracted = true;
          return scrollContainer(-1, _this.container.map.bottom_left_scroll);
        };
      })(this)
    });
    CUI.Events.listen({
      node: this.container.map.bottom_right_scroll,
      type: "mousedown",
      instance: this,
      call: (function(_this) {
        return function(ev) {
          _this.__userInteracted = true;
          return scrollContainer(1, _this.container.map.bottom_right_scroll);
        };
      })(this)
    });
    CUI.Events.listen({
      node: this.container.map.bottom_left_scroll,
      type: "mouseup",
      instance: this,
      call: function(ev) {
        return stopScrollContainer();
      }
    });
    return CUI.Events.listen({
      node: this.container.map.bottom_right_scroll,
      type: "mouseup",
      instance: this,
      call: function(ev) {
        return stopScrollContainer();
      }
    });
  };

  DetailFullscreen.prototype.initObjectNavi = function() {
    var loadObj;
    CUI.Events.listen({
      type: "click",
      instance: this,
      node: this.container.map.prev,
      call: (function(_this) {
        return function(ev) {
          _this.__userInteracted = true;
          if (ev.hasModifierKey()) {
            loadObj("next");
          } else {
            loadObj("prev");
          }
        };
      })(this)
    });
    CUI.Events.listen({
      type: "click",
      instance: this,
      node: this.container.map.next,
      call: (function(_this) {
        return function(ev) {
          _this.__userInteracted = true;
          if (ev.hasModifierKey()) {
            loadObj("prev");
          } else {
            loadObj("next");
          }
        };
      })(this)
    });
    CUI.Events.listen({
      type: "keydown",
      instance: this,
      capture: true,
      node: window,
      call: (function(_this) {
        return function(event) {
          var eventKeyboard;
          _this.__userInteracted = true;
          eventKeyboard = event.getKeyboard();
          if ((eventKeyboard === "Right") && CUI.dom.isVisible(_this.container.map.next)) {
            loadObj("next");
          }
          if ((eventKeyboard === "Left") && CUI.dom.isVisible(_this.container.map.prev)) {
            loadObj("prev");
          }
          if (eventKeyboard === "Esc") {
            _this.close();
          }
        };
      })(this)
    });
    CUI.Events.listen({
      type: "focus-outside-fullscreen",
      instance: this,
      capture: true,
      node: window,
      call: (function(_this) {
        return function() {
          return _this.close();
        };
      })(this)
    });
    CUI.Events.listen({
      type: "focus-sidebar-selection",
      instance: this,
      node: window,
      call: (function(_this) {
        return function(ev, info) {
          if (info.global_object_id && info.global_object_id !== _this.__global_object_id) {
            return _this.scrollObjectIntoView(info.global_object_id, 0);
          }
        };
      })(this)
    });
    return loadObj = (function(_this) {
      return function(dir) {
        var ab_count, ab_idx, asset_browser_index, gid, obj, obj_load;
        obj = _this.getCurrent();
        ab_idx = _this.__asset_browser_idx;
        _this.__closeActiveTool(obj);
        if (dir === "prev") {
          if (ab_idx > 0) {
            asset_browser_index = ab_idx - 1;
            obj_load = obj;
          } else {
            obj_load = obj.previousElementSibling;
            if (!obj_load) {
              return false;
            }
            ab_count = _this.__getAssetCount(obj_load);
            if (ab_count > 0) {
              asset_browser_index = ab_count - 1;
            } else {
              asset_browser_index = null;
            }
          }
        } else {
          ab_count = _this.__getAssetCount(obj);
          if (ab_idx < ab_count - 1) {
            asset_browser_index = ab_idx + 1;
            obj_load = obj;
          } else {
            obj_load = obj.nextElementSibling;
            if (!obj_load) {
              return false;
            }
            if (_this.__getAssetCount(obj_load) > 0) {
              asset_browser_index = 0;
            } else {
              asset_browser_index = null;
            }
          }
        }
        gid = CUI.dom.data(obj_load, "object")._global_object_id;
        return _this.scrollObjectIntoView(gid, asset_browser_index, dir);
      };
    })(this);
  };

  DetailFullscreen.prototype.__getAssetBrowser = function(obj) {
    if (!obj) {
      return null;
    }
    return CUI.dom.data(CUI.dom.matchSelector(obj, ".cui-asset-browser")[0], "element");
  };

  DetailFullscreen.prototype.__getAssetCount = function(obj) {
    var ref;
    return (ref = this.__getAssetBrowser(obj)) != null ? ref.getAssets().length : void 0;
  };

  DetailFullscreen.prototype.__closeActiveTool = function(obj) {
    var assetBrowser, ref, ref1;
    assetBrowser = this.__getAssetBrowser(obj);
    if (assetBrowser != null ? (ref = assetBrowser.activeTool) != null ? ref.isActive() : void 0 : void 0) {
      this.__avoid_close = true;
      if ((ref1 = assetBrowser.activeTool) != null) {
        ref1.destroy();
      }
      return assetBrowser.activeTool = null;
    }
  };

  DetailFullscreen.triggerClose = function() {
    return CUI.Events.trigger({
      node: window,
      type: "focus-outside-fullscreen"
    });
  };

  return DetailFullscreen;

})(CUI.Element);

CUI.ready((function(_this) {
  return function() {
    CUI.Events.registerEvent({
      type: "focus-outside-fullscreen",
      bubble: true
    });
    return CUI.Events.registerEvent({
      type: "fullscreen-object-changed",
      bubble: true
    });
  };
})(this));
// Generated by CoffeeScript 1.12.7
var CSSSwitcher,
  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;

CSSSwitcher = (function(superClass) {
  extend(CSSSwitcher, superClass);

  function CSSSwitcher() {
    return CSSSwitcher.__super__.constructor.apply(this, arguments);
  }

  CSSSwitcher.prototype.initOpts = function() {
    CSSSwitcher.__super__.initOpts.call(this);
    return this.addOpts({
      variants: {
        mandatory: true,
        check: "Array"
      },
      data: {
        mandatory: true,
        check: "PlainObject"
      },
      element: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isElement(v);
        }
      }
    });
  };

  CSSSwitcher.prototype.readOpts = function() {
    var i, len, ref, variant_group;
    CSSSwitcher.__super__.readOpts.call(this);
    ref = this._variants;
    for (i = 0, len = ref.length; i < len; i++) {
      variant_group = ref[i];
      CUI.Element.readOpts(variant_group, "new CSSSwitcher", {
        label: {
          mandatory: true,
          check: String
        },
        name: {
          mandatory: true,
          check: String
        },
        type: {
          mandatory: true,
          check: ["choice", "switch", "options"]
        },
        classes: {
          mandatory: false,
          check: function(v) {
            return CUI.util.isArray(v) && v.length > 0;
          }
        },
        options: {
          check: Array
        }
      });
    }
    return this.setCSS();
  };

  CSSSwitcher.prototype.getVariantName = function(variant_group) {
    return "variant_" + variant_group.name;
  };

  CSSSwitcher.prototype.setCSS = function() {
    var cls, i, idx, j, k, l, len, len1, len2, len3, name, option, ref, ref1, ref2, ref3, results, variant_group;
    ref = this._variants;
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      variant_group = ref[i];
      name = this.getVariantName(variant_group);
      if (variant_group.type === "options") {
        if (!this._data.hasOwnProperty(name)) {
          this._data[name] = [];
        }
        ref1 = variant_group.options;
        for (idx = j = 0, len1 = ref1.length; j < len1; idx = ++j) {
          option = ref1[idx];
          ref2 = option.classes;
          for (idx = k = 0, len2 = ref2.length; k < len2; idx = ++k) {
            cls = ref2[idx];
            CUI.dom.removeClass(this._element, cls["class"]);
          }
          if (this._data[name].includes(option.name)) {
            cls = option.classes[1]["class"];
          } else {
            cls = option.classes[0]["class"];
          }
          CUI.dom.addClass(this._element, cls);
        }
        continue;
      }
      ref3 = variant_group.classes;
      for (idx = l = 0, len3 = ref3.length; l < len3; idx = ++l) {
        cls = ref3[idx];
        CUI.dom.removeClass(this._element, cls["class"]);
        if (!this._data.hasOwnProperty(name) || this._data[name] >= variant_group.classes.length || !variant_group.classes[this._data[name]]) {
          this._data[name] = idx;
        }
      }
      cls = variant_group.classes[this._data[name]]["class"];
      results.push(CUI.dom.addClass(this._element, cls));
    }
    return results;
  };

  CSSSwitcher.prototype.getFields = function() {
    var cls, fields, i, idx, j, k, len, len1, len2, name, option, opts, ref, ref1, ref2, variant_group;
    fields = [];
    ref = this._variants;
    for (i = 0, len = ref.length; i < len; i++) {
      variant_group = ref[i];
      opts = [];
      name = this.getVariantName(variant_group);
      if (variant_group.type === "options") {
        ref1 = variant_group.options;
        for (idx = j = 0, len1 = ref1.length; j < len1; idx = ++j) {
          option = ref1[idx];
          opts.push({
            text: $$(option.label),
            value: option.name
          });
        }
      } else {
        ref2 = variant_group.classes;
        for (idx = k = 0, len2 = ref2.length; k < len2; idx = ++k) {
          cls = ref2[idx];
          opts.push({
            text: $$(cls.label),
            value: idx
          });
        }
      }
      switch (variant_group.type) {
        case "choice":
          fields.push({
            form: {
              label: $$(variant_group.label)
            },
            type: CUI.Options,
            horizontal: false,
            radio: true,
            options: opts,
            name: name
          });
          break;
        case "options":
          fields.push({
            form: {
              label: $$(variant_group.label)
            },
            type: CUI.Options,
            horizontal: false,
            radio: false,
            options: opts,
            name: name
          });
          break;
        case "switch":
          CUI.util.assert(variant_group.classes.length === 2, "CSSSwitcher.getFields", "variant of type 'switch' must have exactly 2 classes.", {
            variant: variant_group
          });
          fields.push({
            form: {
              label: $$(variant_group.label)
            },
            type: CUI.Checkbox,
            name: name,
            value_unchecked: opts[0].value,
            value: opts[1].value
          });
      }
    }
    return fields;
  };

  CSSSwitcher.prototype.render = function() {
    var btns, cls, fn, i, idx, j, len, len1, name, ref, ref1, variant_group;
    btns = [];
    ref = this._variants;
    for (i = 0, len = ref.length; i < len; i++) {
      variant_group = ref[i];
      name = this.getVariantName(variant_group);
      switch (variant_group.type) {
        case "choice":
          ref1 = variant_group.classes;
          fn = (function(_this) {
            return function(idx, name) {
              return btns.push(new CUI.Button({
                radio: name,
                group: name,
                active: parseInt(_this._data[name]) === idx,
                text: $$(cls.label) || idx + ":" + name,
                onClick: function() {
                  _this._data[name] = idx;
                  return _this.setCSS();
                }
              }));
            };
          })(this);
          for (idx = j = 0, len1 = ref1.length; j < len1; idx = ++j) {
            cls = ref1[idx];
            fn(idx, name);
          }
          break;
        case "switch":
          (function(_this) {
            return (function(variant_group, name) {
              return btns.push(new CUI.Button({
                "switch": true,
                group: name,
                active: parseInt(_this._data[name]) === 1,
                text: $$(variant_group.label),
                onDeactivate: function(btn, flags) {
                  if (flags.initial_activate) {
                    return;
                  }
                  _this._data[name] = 0;
                  return _this.setCSS();
                },
                onActivate: function(btn, flags) {
                  if (flags.initial_activate) {
                    return;
                  }
                  _this._data[name] = 1;
                  return _this.setCSS();
                }
              }));
            });
          })(this)(variant_group, name);
      }
    }
    this.setCSS();
    if (btns.length) {
      return new CUI.Buttonbar({
        buttons: btns
      });
    }
  };

  return CSSSwitcher;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var PoolDeepLink,
  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;

PoolDeepLink = (function(superClass) {
  extend(PoolDeepLink, superClass);

  function PoolDeepLink() {
    return PoolDeepLink.__super__.constructor.apply(this, arguments);
  }

  PoolDeepLink.prototype.findAppByLocation = function(location, apps) {
    var dfr, load_pool, m, shortname;
    m = location.pathname.match("^/pool/(.+)");
    if (!m) {
      return CUI.rejectedPromise();
    }
    shortname = m[1];
    dfr = new CUI.Deferred();
    load_pool = (function(_this) {
      return function() {
        var app, i, len, pool;
        pool = ez5.pools.findPoolByShortname(shortname);
        if (!pool) {
          DetailDeepLink.askLogin("pool.deep.link.needs_login").done(load_pool).fail(dfr.reject);
        } else {
          for (i = 0, len = apps.length; i < len; i++) {
            app = apps[i];
            if ((typeof app.getPathname === "function" ? app.getPathname() : void 0) === "/search") {
              dfr.resolve(app);
              return;
            }
          }
          CUI.problem({
            text: $$("pool.deep.link.search_app_not_found")
          }).done(dfr.reject);
        }
      };
    })(this);
    load_pool();
    return dfr.promise();
  };

  return PoolDeepLink;

})(RootMenuAppLoader);

ez5.session_ready(function() {
  return ez5.rootMenu.registerAppLoader(new PoolDeepLink());
});
// Generated by CoffeeScript 1.12.7
var SearchTypeSelector,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

SearchTypeSelector = (function(superClass) {
  extend(SearchTypeSelector, superClass);

  function SearchTypeSelector(opts1) {
    var onActivate, onDeactivate;
    this.opts = opts1 != null ? opts1 : {};
    SearchTypeSelector.__super__.constructor.call(this, this.opts);
    this.__update_pending = false;
    this.initOTM();
    onActivate = (function(_this) {
      return function(event, trigger) {
        if ((event != null ? event.getType() : void 0) === "click") {
          _this.__activateAll(trigger);
        }
      };
    })(this);
    onDeactivate = (function(_this) {
      return function(button, event, trigger) {
        var checkbox;
        if ((event != null ? event.getType() : void 0) === "click") {
          _this.__deactivateAll(trigger);
          checkbox = (typeof button.getCheckbox === "function" ? button.getCheckbox() : void 0) || button;
          CUI.dom.removeClass(checkbox.getButton(), "cui-indeterminate");
        }
      };
    })(this);
    this.button = new CUI.CheckboxButton({
      ui: "search.type.selector.open.button",
      "class": "ez5-search-type-selector-button",
      text: "",
      icon_right: "fa-angle-down",
      left: true,
      tooltip: {
        text: (function(_this) {
          return function() {
            return _this.getCountText("tooltip");
          };
        })(this)
      },
      checkbox_opts: {
        ui: "search.type.selector.checkbox",
        onActivate: (function(_this) {
          return function(_, __, event) {
            return onActivate(event);
          };
        })(this),
        onDeactivate: (function(_this) {
          return function(button, _, event) {
            return onDeactivate(button, event);
          };
        })(this)
      },
      onClick: (function(_this) {
        return function(ev, btn) {
          if (_this.__update_pending) {
            btn.startSpinner();
            return _this.updateContent().done(function() {
              return _this.popover.show();
            }).always(function() {
              btn.stopSpinner();
              return _this.__update_pending = false;
            }).done(function() {});
          } else {
            return _this.popover.show();
          }
        };
      })(this)
    });
    this.__checkboxHeader = new CUI.Checkbox({
      text: "",
      onActivate: (function(_this) {
        return function(_, __, event) {
          return onActivate(event, false);
        };
      })(this),
      onDeactivate: (function(_this) {
        return function(button, _, event) {
          return onDeactivate(button, event, false);
        };
      })(this)
    });
    this.__checkboxHeader.start();
    return;
  }

  SearchTypeSelector.prototype.initOTM = function() {
    this.otm = new ObjecttypeManager();
    this.otm.addObjecttypes((function(_this) {
      return function(table) {
        var j, len, ot, ref;
        if (_this._objecttypes) {
          ref = _this._objecttypes;
          for (j = 0, len = ref.length; j < len; j++) {
            ot = ref[j];
            if (ot.id() === table.id()) {
              return true;
            }
          }
          return false;
        } else {
          return table.inMainSearch();
        }
      };
    })(this));
    return this;
  };

  SearchTypeSelector.prototype.setButtonText = function() {
    var checkbox, locaKeyPrefix, objecttypeCount, poolCount, totalObjecttypeCount, totalPoolCount, txt;
    if (this.showObjecttypes()) {
      locaKeyPrefix = "search.type.selector.";
    } else {
      locaKeyPrefix = "search.type.selector.hidden_objecttype.";
    }
    txt = ez5.loca.str_default(locaKeyPrefix + "button|text", null);
    this.button.setText(txt);
    txt = ez5.loca.str_default(locaKeyPrefix + "title|text", null);
    this.__checkboxHeader.setText(txt);
    checkbox = this.button.getCheckbox();
    CUI.dom.removeClass(checkbox.getButton(), "cui-indeterminate");
    CUI.dom.removeClass(this.__checkboxHeader.getButton(), "cui-indeterminate");
    objecttypeCount = this.__last_stats.objecttype_count;
    poolCount = this.__last_stats.pool_count;
    totalObjecttypeCount = this.__last_stats.total_objecttype_count;
    totalPoolCount = this.__last_stats.total_pool_count;
    if ((objecttypeCount === 0 || (objecttypeCount === 1 && !this.showObjecttypes())) && poolCount === 0) {
      checkbox.deactivate();
      this.__checkboxHeader.deactivate();
    } else if (objecttypeCount === totalObjecttypeCount && poolCount === totalPoolCount) {
      checkbox.activate();
      this.__checkboxHeader.activate();
    } else {
      checkbox.deactivate();
      CUI.dom.addClass(checkbox.getButton(), "cui-indeterminate");
      this.__checkboxHeader.deactivate();
      CUI.dom.addClass(this.__checkboxHeader.getButton(), "cui-indeterminate");
    }
  };

  SearchTypeSelector.prototype.initOpts = function() {
    SearchTypeSelector.__super__.initOpts.call(this);
    return this.addOpts({
      ignoreSelection: {
        check: Function
      },
      pref_name: {
        check: String
      },
      init_from_data: {
        check: "PlainObject"
      },
      show_connector: {
        check: Boolean,
        "default": true
      },
      objecttypes: {
        check: function(arr) {
          var j, len, ot;
          if (!CUI.util.isArray(arr)) {
            return false;
          }
          for (j = 0, len = arr.length; j < len; j++) {
            ot = arr[j];
            if (!(ot instanceof Objecttype)) {
              return false;
            }
          }
          return true;
        }
      },
      show_all_objecttypes: {
        check: Boolean,
        "default": false
      }
    });
  };

  SearchTypeSelector.prototype.readOpts = function() {
    SearchTypeSelector.__super__.readOpts.call(this);
    CUI.util.assert(CUI.util.xor(this._pref_name, this._init_from_data), "new SearchTypeSelector", "One of opts.pref_name and opts.init_from_data must be set", {
      opts: this.opts
    });
    if (this._pref_name) {
      this.setState(ez5.session.getPref(this._pref_name));
    } else {
      this.setState(CUI.util.copyObject(this._init_from_data, true));
    }
    return this;
  };

  SearchTypeSelector.prototype.getCount = function(o) {
    var j, len, ot, ref, sb;
    sb = this.getSearch().getSearchBasics();
    if (!sb) {
      return 0;
    }
    ref = sb.getObjecttypes();
    for (j = 0, len = ref.length; j < len; j++) {
      ot = ref[j];
      if (ot.name === o.name()) {
        return ot.count;
      }
    }
    return 0;
  };

  SearchTypeSelector.prototype.showObjecttypes = function() {
    var objecttypesWithObjects, ref, ref1;
    if (this._show_all_objecttypes) {
      return this.otm.objecttypes.length >= 1;
    }
    objecttypesWithObjects = this.getObjecttypesWithObjects();
    if (objecttypesWithObjects.length === 1) {
      if (!objecttypesWithObjects[0].poolLink() && !!!(((ref = this.getState()) != null ? (ref1 = ref.pool_ids) != null ? ref1.length : void 0 : void 0) > 0)) {
        return true;
      }
    }
    return objecttypesWithObjects.length >= 2;
  };

  SearchTypeSelector.prototype.getObjecttypesWithObjects = function() {
    var j, len, o, objecttypes, ref;
    objecttypes = [];
    ref = this.otm.objecttypes;
    for (j = 0, len = ref.length; j < len; j++) {
      o = ref[j];
      if (this._show_all_objecttypes || this.getCount(o) > 0) {
        objecttypes.push(o);
      }
    }
    return objecttypes;
  };

  SearchTypeSelector.prototype.getObjecttypesWithoutObjects = function() {
    var j, len, o, objecttypes, ref;
    objecttypes = [];
    ref = this.otm.objecttypes;
    for (j = 0, len = ref.length; j < len; j++) {
      o = ref[j];
      if (this.getCount(o) === 0) {
        objecttypes.push(o);
      }
    }
    return objecttypes;
  };

  SearchTypeSelector.prototype.getButton = function() {
    CUI.Events.ignore({
      instance: this
    });
    EventPoller.listen({
      filter: {
        type: ["OBJECT_INDEX", "OBJECT_DELETE"]
      },
      instance: this,
      call: (function(_this) {
        return function() {
          _this.__update_pending = true;
        };
      })(this)
    });
    return this.button;
  };

  SearchTypeSelector.prototype.init = function() {
    var connectorButton, easydbs_count, icon, j, len, ot, ref, ref1, ref2, ref3, state, toolbar, toolbar_content, unreacheableInstances;
    if (this.popover) {
      this.popover.destroy();
      this.popover = null;
    }
    this.__initContent = false;
    this.selected_pools = null;
    this.pool_rows = [];
    this.pool_by_id = null;
    state = this.getState();
    ref = this.otm.objecttypes;
    for (j = 0, len = ref.length; j < len; j++) {
      ot = ref[j];
      if ((state != null ? (ref1 = state.objecttypes) != null ? ref1.length : void 0 : void 0) > 0 && this.showObjecttypes()) {
        ot._selected = (ref2 = ot.name(), indexOf.call(state.objecttypes, ref2) >= 0);
      } else {
        ot._selected = true;
      }
    }
    toolbar_content = [];
    if (((ref3 = ez5.connector) != null ? ref3.isAvailable() : void 0) && this._show_connector) {
      easydbs_count = ez5.connector.getActiveEasydbs().length;
      unreacheableInstances = !CUI.util.isEmpty(ez5.connector.__unreachableEasydbs);
      if (unreacheableInstances) {
        icon = $$("search.type.selector.button.connector.error|icon");
      } else {
        icon = $$("search.type.selector.button.connector|icon");
      }
      connectorButton = new CUI.Button({
        text: $$("search.type.selector.button.connector|text", {
          active: easydbs_count,
          available: ez5.connector.getAvailableEasydbs().length
        }),
        icon: icon,
        active: easydbs_count > 0,
        danger: unreacheableInstances,
        onClick: (function(_this) {
          return function() {
            return ez5.connector.showConfiguration().done(function() {
              return ez5.connector.logout().done(function() {
                return document.location.reload();
              });
            });
          };
        })(this)
      });
      toolbar_content.push(connectorButton);
    }
    toolbar = null;
    if (toolbar_content.length > 0) {
      toolbar = new CUI.Toolbar({
        left: {
          content: toolbar_content
        }
      });
    }
    this.__countText = new CUI.Label({
      "class": "ez5-search-type-selector-form",
      markdown: true,
      multiline: true,
      text: ""
    });
    this.popover = new CUI.Popover({
      "class": "popover-search-main-selector",
      element: this.button.DOM,
      placement: "se",
      backdrop: {
        policy: "click"
      },
      onHide: (function(_this) {
        return function() {
          _this.popover.disableAllButtons();
          return _this.__savePopover().done(function() {
            return _this.popover.enableAllButtons();
          });
        };
      })(this),
      pane: {
        maximize: true,
        footer_center: this.__countText,
        header_left: this.__checkboxHeader
      }
    });
    if (toolbar) {
      this.popover.append(toolbar, "top");
    }
    console.time("SearchTypeSelector");
    return this.updateContent().always((function(_this) {
      return function() {
        return console.timeEnd("SearchTypeSelector");
      };
    })(this));
  };

  SearchTypeSelector.prototype.__savePopover = function() {
    var dfr;
    dfr = new CUI.Deferred();
    if (this.__saveState()) {
      this.getSearch().objecttypesUpdated(this).fail(dfr.reject).done((function(_this) {
        return function() {
          return _this.getSearch().execute().always(function() {
            return dfr.resolve();
          });
        };
      })(this));
    } else {
      dfr.resolve();
    }
    return dfr.promise();
  };

  SearchTypeSelector.prototype.setState = function(__currentState) {
    this.__currentState = __currentState;
  };

  SearchTypeSelector.prototype.getState = function() {
    return this.__currentState;
  };

  SearchTypeSelector.prototype.destroy = function() {
    CUI.Events.ignore({
      instance: this
    });
    return SearchTypeSelector.__super__.destroy.call(this);
  };

  SearchTypeSelector.prototype.restoreFromStored = function(sts) {
    return this.restoreToState(sts.getState());
  };

  SearchTypeSelector.prototype.restoreToState = function(state) {
    var dfr;
    dfr = new CUI.Deferred();
    this.setState(state);
    this.init().done((function(_this) {
      return function() {
        return _this.getSearch().objecttypesUpdated(_this).done(dfr.resolve).fail(dfr.reject);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  SearchTypeSelector.prototype.initFromUrlData = function(url_data) {
    var _pool, j, l, len, len1, len2, m, objecttypes, ot, pool, pool_ids, ref, ref1, ref2, sd, str_to_arr;
    str_to_arr = function(str, parse_int) {
      var arr, el, i, j, len, ref;
      if (parse_int == null) {
        parse_int = false;
      }
      arr = [];
      if (!CUI.util.isString(str)) {
        return arr;
      }
      ref = str.split(",");
      for (j = 0, len = ref.length; j < len; j++) {
        el = ref[j];
        if (CUI.util.isEmpty(el)) {
          continue;
        }
        if (parse_int) {
          i = parseInt(el);
          if (isNaN(i) || i <= 0) {
            continue;
          }
          arr.push(i);
        } else {
          arr.push(el);
        }
      }
      return arr;
    };
    if (url_data.pool) {
      pool = ez5.pools.findPoolByShortname(url_data.pool);
      pool_ids = [];
      objecttypes = [];
      if (!pool) {
        console.error("Pool not found:", pool);
      } else {
        ref = pool.find();
        for (j = 0, len = ref.length; j < len; j++) {
          _pool = ref[j];
          pool_ids.push(_pool.getId());
        }
      }
      ref1 = this.otm.objecttypes;
      for (l = 0, len1 = ref1.length; l < len1; l++) {
        ot = ref1[l];
        if (ot.poolLink()) {
          objecttypes.push(ot.name());
        }
      }
      sd = {
        pool_ids: pool_ids,
        objecttypes: objecttypes
      };
    } else {
      sd = {
        objecttypes: [],
        pool_ids: []
      };
      if (url_data.p) {
        sd.pool_ids = str_to_arr(url_data.p[0], true);
      }
      if (url_data.ot) {
        sd.objecttypes = str_to_arr(url_data.ot[0]);
      } else if (url_data.p) {
        ref2 = this.otm.objecttypes;
        for (m = 0, len2 = ref2.length; m < len2; m++) {
          ot = ref2[m];
          if (ot.poolLink()) {
            sd.objecttypes.push(ot.name());
          }
        }
      }
    }
    if (sd.objecttypes.length || sd.pool_ids.length) {
      console.error("restore to state", sd);
      return this.restoreToState(sd);
    } else {

    }
  };

  SearchTypeSelector.prototype.getStoreAsUrlData = function(url_data) {
    var k, ref, sd, v;
    sd = this.getStoreData().SearchTypeSelector;
    ref = {
      ot: sd.objecttypes.join(","),
      p: sd.pool_ids.join(",")
    };
    for (k in ref) {
      v = ref[k];
      url_data[k] = v;
    }
    return url_data;
  };

  SearchTypeSelector.prototype.getStoreData = function(sd) {
    var j, len, ot, pool, pool_id, ref, ref1, state;
    if (sd == null) {
      sd = {};
    }
    SearchTypeSelector.__super__.getStoreData.call(this, sd);
    state = {
      objecttypes: [],
      pool_ids: []
    };
    ref = this.otm.objecttypes;
    for (j = 0, len = ref.length; j < len; j++) {
      ot = ref[j];
      if (ot._selected) {
        state.objecttypes.push(ot.name());
      }
    }
    ref1 = this.pool_by_id;
    for (pool_id in ref1) {
      pool = ref1[pool_id];
      if (pool._selected) {
        state.pool_ids.push(pool.pool._id);
      }
    }
    sd.SearchTypeSelector = state;
    return sd;
  };

  SearchTypeSelector.prototype.__saveState = function() {
    var state;
    state = this.getStoreData().SearchTypeSelector;
    if (JSON.stringify(state) !== JSON.stringify(this.getState())) {
      ez5.session.savePref(this._pref_name, state);
      this.setState(state);
      return true;
    } else {
      return false;
    }
  };

  SearchTypeSelector.prototype.countRequest = function(filter_active_checkboxes, updateBasics) {
    var dfr, has_pool_ot, include_deleted, j, l, len, len1, manager, nothing_found_response, only_deleted, ot, ot_names, ref, ref1, request, search, sf;
    if (filter_active_checkboxes == null) {
      filter_active_checkboxes = false;
    }
    if (updateBasics == null) {
      updateBasics = false;
    }
    has_pool_ot = false;
    search = [];
    ot_names = [];
    dfr = new CUI.Deferred();
    nothing_found_response = (function(_this) {
      return function() {
        return dfr.resolve({
          aggregations: {
            _pool: {
              linked_objects: []
            },
            _objecttype: {
              terms: []
            }
          },
          count: 0
        });
      };
    })(this);
    include_deleted = false;
    only_deleted = false;
    if (ez5.version("6")) {
      ref = this.getSearch().getSearchManagers();
      for (j = 0, len = ref.length; j < len; j++) {
        manager = ref[j];
        if (manager instanceof TrashSearchManager && manager.isActive()) {
          include_deleted = true;
          only_deleted = manager.isOnlyDeleted();
          break;
        }
      }
    }
    ref1 = this.getSearch().getSearchObjecttypes(filter_active_checkboxes);
    for (l = 0, len1 = ref1.length; l < len1; l++) {
      ot = ref1[l];
      if (ot.poolLink()) {
        has_pool_ot = true;
      }
      ot_names.push(ot.name());
    }
    if (ot_names.length === 0) {
      nothing_found_response();
      return dfr.promise();
    }
    request = {
      objecttypes: ot_names,
      search: search,
      generate_rights: false,
      limit: 0,
      aggregations: {
        _mask: {
          type: "term",
          limit: 100000,
          field: "_mask"
        },
        _objecttype: {
          type: "term",
          limit: 100000,
          field: "_objecttype"
        }
      }
    };
    if (include_deleted) {
      request.include_deleted = true;
      if (only_deleted) {
        request.search.push({
          type: "in",
          bool: "must_not",
          fields: ["_latest_version_deleted_at"],
          "in": [null]
        });
      }
    }
    if (has_pool_ot) {
      request.aggregations._pool = {
        type: "linked_object",
        field: "_pool",
        limit: 100000,
        sort: "term"
      };
    }
    if (filter_active_checkboxes) {
      sf = this.getSearchFilter();
      if (sf) {
        search.push(sf);
      }
    }
    dfr.done((function(_this) {
      return function(data) {
        var len2, m, ref2, t;
        _this.__mask_names = [];
        ref2 = data.aggregations._mask.terms;
        for (m = 0, len2 = ref2.length; m < len2; m++) {
          t = ref2[m];
          _this.__mask_names.push(t.term);
        }
      };
    })(this));
    ez5.api.search({
      data: {
        debug: "SearchTypeSelector.countRequest"
      },
      json_data: request,
      error: function(xhr) {
        if (xhr.status === 409) {
          return nothing_found_response();
        } else {
          return ez5.error_handler(xhr).done((function(_this) {
            return function() {
              return nothing_found_response();
            };
          })(this));
        }
      }
    }).done((function(_this) {
      return function(data) {
        if (updateBasics) {
          _this.getSearch().getSearchBasics().update(true).done(function() {
            dfr.resolve(data);
          });
        } else {
          dfr.resolve(data);
        }
      };
    })(this));
    return dfr.promise();
  };

  SearchTypeSelector.prototype.getMaskNames = function() {
    return this.__mask_names;
  };

  SearchTypeSelector.prototype.getObjecttypesForSearch = function(user_selected) {
    var j, len, o, ot, ref;
    if (user_selected == null) {
      user_selected = true;
    }
    ot = [];
    ref = this.otm.objecttypes;
    for (j = 0, len = ref.length; j < len; j++) {
      o = ref[j];
      if (!user_selected || ((o._selected || !this.showObjecttypes()) && (this._show_all_objecttypes || this.getCount(o) > 0))) {
        ot.push(o);
      }
    }
    return ot;
  };

  SearchTypeSelector.prototype.ignoreSelection = function() {
    if (typeof this._ignoreSelection === "function" ? this._ignoreSelection() : void 0) {
      return true;
    } else {
      return false;
    }
  };

  SearchTypeSelector.prototype.addToRequest = function(request) {
    var filter, ot;
    if (request == null) {
      request = {};
    }
    if (this.ignoreSelection() && !this._init_from_data) {
      request.objecttypes = (function() {
        var j, len, ref, results;
        ref = this.getSearch().getSearchObjecttypes(false);
        results = [];
        for (j = 0, len = ref.length; j < len; j++) {
          ot = ref[j];
          results.push(ot.name());
        }
        return results;
      }).call(this);
      return request;
    }
    if (!request.search) {
      request.search = [];
    }
    filter = this.getSearchFilter();
    if (filter) {
      request.search.push(filter);
    } else if (this.getObjecttypesForSearch().length === 0) {
      request.search.push(false);
    }
    return request;
  };

  SearchTypeSelector.prototype.getPoolIdsForSearch = function(include_remote) {
    var j, len, local_pool_ids, pool_id, pool_ids, ref;
    if (include_remote == null) {
      include_remote = false;
    }
    pool_ids = this.getSearchFilter({
      return_pool_ids: true
    }) || [];
    if (include_remote || !((ref = ez5.connector) != null ? ref.isAvailable() : void 0)) {
      return pool_ids;
    }
    local_pool_ids = [];
    for (j = 0, len = pool_ids.length; j < len; j++) {
      pool_id = pool_ids[j];
      if (CUI.util.isInteger(pool_id)) {
        local_pool_ids.push(pool_id);
      }
    }
    return local_pool_ids;
  };

  SearchTypeSelector.prototype.getSearchFilter = function(opts) {
    var filter, id, j, len, ot, ot_name, pool_fields, pool_ids, pool_ot_names, ref, state;
    if (opts == null) {
      opts = {};
    }
    if (this._init_from_data) {
      pool_ot_names = [];
      ref = this._init_from_data.objecttypes;
      for (j = 0, len = ref.length; j < len; j++) {
        ot_name = ref[j];
        if (ez5.schema.CURRENT._objecttype_by_name[ot_name].pool_link) {
          pool_ot_names.push(ot_name);
        }
      }
    } else {
      pool_ot_names = (function() {
        var l, len1, ref1, results;
        ref1 = this.getSearch().getSearchObjecttypes(true, true);
        results = [];
        for (l = 0, len1 = ref1.length; l < len1; l++) {
          ot = ref1[l];
          results.push(ot.name());
        }
        return results;
      }).call(this);
    }
    pool_fields = (function() {
      var l, len1, results;
      results = [];
      for (l = 0, len1 = pool_ot_names.length; l < len1; l++) {
        ot_name = pool_ot_names[l];
        results.push(ot_name + "._pool.pool._id");
      }
      return results;
    })();
    if (!this._init_from_data) {
      if (!pool_fields.length) {
        return null;
      }
      if (this.selected_pools === null) {
        state = this.getState();
        if (!state) {
          return null;
        }
        pool_ids = state.pool_ids;
      } else {
        pool_ids = (function() {
          var results;
          results = [];
          for (id in this.selected_pools) {
            results.push(CUI.util.getIntOrString(id));
          }
          return results;
        }).call(this);
      }
      if (!(pool_ids != null ? pool_ids.length : void 0)) {
        pool_ids = [-1];
      }
    } else {
      pool_ids = this._init_from_data.pool_ids;
    }
    if (opts.return_pool_ids) {
      return pool_ids;
    }
    filter = {
      __filter: "SearchTypeSelector",
      type: "complex",
      bool: "must",
      search: [
        {
          bool: "should",
          type: "in",
          fields: pool_fields,
          "in": pool_ids
        }, {
          type: "complex",
          bool: "should",
          search: [
            {
              bool: "must_not",
              type: "in",
              fields: ["_objecttype"],
              "in": (function() {
                var l, len1, results;
                results = [];
                for (l = 0, len1 = pool_ot_names.length; l < len1; l++) {
                  ot_name = pool_ot_names[l];
                  results.push(ot_name);
                }
                return results;
              })()
            }
          ]
        }
      ]
    };
    if (!this._init_from_data) {
      return filter;
    }
    filter = {
      type: "complex",
      search: [
        filter, {
          bool: "must",
          type: "in",
          fields: ["_objecttype"],
          "in": this._init_from_data.objecttypes
        }
      ]
    };
    return filter;
  };

  SearchTypeSelector.prototype.prepareData = function(data) {
    var has_remotes, j, len, pool, root, state;
    this.__last_stats = {
      object_count: 0
    };
    state = this.getState();
    this.pool_by_id = {};
    this.selected_pools = {};
    if (!data.aggregations._pool) {
      this.pool_rows = [];
    } else {
      has_remotes = false;
      root = ez5.buildObjectTree({
        objects: data.aggregations._pool.linked_objects,
        doOpen: false,
        newInstanceFunc: (function(_this) {
          return function(pool) {
            var p, ref;
            p = new PoolSelectorNode({
              pool: pool,
              manager: _this
            });
            if (pool._instance) {
              has_remotes = true;
            }
            _this.pool_by_id[p.id] = p;
            if ((state != null ? state.pool_ids.length : void 0) > 0) {
              if (ref = p.id, indexOf.call(state.pool_ids, ref) >= 0) {
                p.set_state(true);
              }
            } else {
              p.set_state(true);
            }
            return p;
          };
        })(this)
      });
      if (root.length === 1 && !has_remotes) {
        this.pool_rows = [];
        for (j = 0, len = root.length; j < len; j++) {
          pool = root[j];
          this.pool_rows.push.apply(this.pool_rows, pool.children);
        }
      } else {
        this.pool_rows = root;
      }
    }
    return this;
  };

  SearchTypeSelector.prototype.updateContent = function(updateBasics) {
    var dfr;
    if (updateBasics == null) {
      updateBasics = false;
    }
    dfr = new CUI.Deferred();
    this.__update_pending = false;
    this.countRequest(false, updateBasics).done((function(_this) {
      return function(data) {
        if (_this.isDestroyed()) {
          dfr.reject();
          return;
        }
        _this.prepareData(data);
        return _this.renderContent().done(function() {
          return _this.updateInfo().done(dfr.resolve).fail(dfr.reject);
        });
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  SearchTypeSelector.prototype.renderContent = function() {
    var container_parent, count, deferred, fn, j, l, len, len1, listviews, no_hierarchy, objecttypePanel, ot, p, poolPanel, ref, ref1, rootNode, show_objecttypes, sort_loca;
    listviews = [];
    sort_loca = function(a, b) {
      var ac, bc;
      ac = a.nameLocalized().toLocaleLowerCase();
      bc = b.nameLocalized().toLocaleLowerCase();
      return ac.localeCompare(bc);
    };
    show_objecttypes = this.showObjecttypes();
    if (show_objecttypes) {
      this.__objecttypeTree = new CUI.ListViewTree({
        no_hierarchy: true,
        "class": 'cui-lv--has-datafields',
        maximize_horizontal: true,
        maximize_vertical: false,
        cols: ["maximize", "auto", "auto"],
        colClasses: ["", "ez5-column-object-count", "ez5-column-info"]
      });
      ref = this.otm.objecttypes;
      fn = (function(_this) {
        return function(ot) {
          return _this.__objecttypeTree.root.addNode(new ObjecttypeSelectorNode({
            manager: _this,
            objecttype: ot,
            count: count
          }));
        };
      })(this);
      for (j = 0, len = ref.length; j < len; j++) {
        ot = ref[j];
        count = this.getCount(ot);
        if (count === 0 && !this._show_all_objecttypes) {
          continue;
        }
        fn(ot);
      }
      this.__objecttypeTree.root.sort(sort_loca);
      this.__objecttypeTree.render();
      this.__objecttypeTree.root.open().done((function(_this) {
        return function() {
          return _this.popover.autoSize();
        };
      })(this));
      objecttypePanel = new CUI.Panel({
        text: $$("main.search.selector.objecttype.title"),
        radio: "objecttype",
        closed: false,
        content: this.__objecttypeTree
      });
      listviews.push(objecttypePanel);
    }
    if (this.pool_rows.length) {
      deferred = new CUI.Deferred();
      rootNode = new PoolSelectorNode({
        children: this.pool_rows
      });
      rootNode.sort(sort_loca);
      no_hierarchy = true;
      ref1 = this.pool_rows;
      for (l = 0, len1 = ref1.length; l < len1; l++) {
        p = ref1[l];
        if (!p.isLeaf()) {
          no_hierarchy = false;
          break;
        }
      }
      this.__poolTree = new CUI.ListViewTree({
        root: rootNode,
        no_hierarchy: no_hierarchy,
        "class": 'cui-lv--has-datafields',
        maximize_horizontal: true,
        maximize_vertical: false,
        cols: ["maximize", "auto", "auto"],
        colClasses: ["", "ez5-column-object-count", "ez5-column-info"],
        selectableRows: false
      });
      this.__poolTree.render();
      if (show_objecttypes) {
        poolPanel = new CUI.Panel({
          text: $$("main.search.selector.pool.title"),
          closed: false,
          radio: "pool",
          content: this.__poolTree
        });
        listviews.push(poolPanel);
      } else {
        listviews.push(this.__poolTree);
      }
      this.__poolTree.root.open().done((function(_this) {
        return function() {
          _this.__poolTree.root.refresh();
          _this.popover.autoSize();
          deferred.resolve();
        };
      })(this));
    } else if (!show_objecttypes) {
      this.__poolTree = null;
      listviews.push(new CUI.SimplePane({
        title: $$("main.search.selector.pool.title"),
        padded: true,
        content: new CUI.EmptyLabel({
          "class": "ez5-main-search-selector-no-pools",
          text: $$("main.search.selector.pool.no_pools"),
          multiline: true,
          centered: true
        })
      }));
    }
    container_parent = new CUI.VerticalList({
      content: new CUI.VerticalList({
        maximize_horizontal: true,
        maximize_vertical: false,
        "class": "ez5-search-type-selector-ot-pools",
        content: listviews
      })
    });
    this.popover.replace(container_parent.DOM, "content");
    if (!this.__poolTree || !deferred) {
      return CUI.resolvedPromise();
    }
    return deferred.promise();
  };

  SearchTypeSelector.prototype.updateInfo = function() {
    return this.countRequest(true).done((function(_this) {
      return function(data) {
        _this.__last_stats.object_count = data.count;
        _this.__countText.setText(_this.getCountText());
        _this.setButtonText();
      };
    })(this));
  };

  SearchTypeSelector.prototype.getLastStats = function() {
    return this.__last_stats;
  };

  SearchTypeSelector.prototype.hasPoolFilter = function() {
    if (!this.__last_stats) {
      return false;
    }
    return this.__last_stats.pool_count < this.__last_stats.total_pool_count;
  };

  SearchTypeSelector.prototype.hasUserInput = function(request) {
    var currentManager, j, len, ref, sm;
    if (!this.hasPoolFilter()) {
      return false;
    }
    ref = this.getSearch().getSearchManagers();
    for (j = 0, len = ref.length; j < len; j++) {
      sm = ref[j];
      if (sm instanceof ResultManager) {
        currentManager = sm.current_result_manager;
        if (currentManager instanceof ResultTable || currentManager instanceof ez5.ResultTableV2) {
          return true;
        }
        break;
      }
    }
    return false;
  };

  SearchTypeSelector.prototype.getCountText = function(textType) {
    var connector, count, countLocaKey, countLocaKeyOpts, instances, instancesCount, j, len, locaKey, ref, ref1, showPools, text, type;
    if (textType == null) {
      textType = "";
    }
    this.__last_stats.objecttype_count = this.getSearch().getSearchObjecttypes(true).length;
    this.__last_stats.total_objecttype_count = this.getSearch().getSearchObjecttypes(false).filter((function(_this) {
      return function(ot) {
        return _this.getCount(ot) > 0;
      };
    })(this)).length;
    if (((ref = ez5.connector) != null ? ref.isAvailable() : void 0) && this._show_connector) {
      instancesCount = ez5.connector.getActiveEasydbs().length;
      if (instancesCount > 0) {
        connector = true;
      }
    }
    instances = new Set();
    this.__last_stats.pool_count = 0;
    this.__last_stats.total_pool_count = 0;
    if (this.__poolTree) {
      this.__poolTree.root.find((function(_this) {
        return function(node) {
          var instance, ref1;
          if (_this.__poolTree.root === node) {
            return;
          }
          if (connector && node.getFather() === _this.__poolTree.root) {
            return;
          }
          _this.__last_stats.total_pool_count++;
          if (node.isActive()) {
            _this.__last_stats.pool_count++;
            instance = ((ref1 = node.pool) != null ? ref1._instance : void 0) || "local";
            return instances.add(instance);
          }
        };
      })(this));
    }
    this.__last_stats.instance_count = instances.size;
    countLocaKeyOpts = {};
    ref1 = ["object", "pool", "objecttype", "instance"];
    for (j = 0, len = ref1.length; j < len; j++) {
      type = ref1[j];
      count = this.__last_stats[type + "_count"];
      locaKey = "main.search.selector.keys." + type;
      if (count !== 1) {
        locaKey += ".multiple";
      }
      countLocaKeyOpts[type + "_text"] = $$(locaKey);
      countLocaKeyOpts[type + "_count"] = ez5.format_number(count);
    }
    showPools = this.__last_stats.pool_count > 0;
    countLocaKey = this.__getCountLocaKey(this.showObjecttypes(), connector, showPools, textType);
    text = $$(countLocaKey, countLocaKeyOpts);
    return text;
  };

  SearchTypeSelector.prototype.__getCountLocaKey = function(objecttypes, connector, pools, type) {
    var key;
    if (objecttypes == null) {
      objecttypes = false;
    }
    if (connector == null) {
      connector = false;
    }
    if (pools == null) {
      pools = false;
    }
    key = "main.search.selector.status";
    if (connector) {
      key += ".with-connector";
    }
    if (objecttypes) {
      key += ".with-objecttypes";
    }
    if (!pools) {
      key += ".no-pools";
    }
    if (type) {
      key += "." + type;
    }
    return key;
  };

  SearchTypeSelector.prototype.__activateAll = function(trigger) {
    return this.__toggleNodes(true, trigger);
  };

  SearchTypeSelector.prototype.__deactivateAll = function(trigger) {
    return this.__toggleNodes(false, trigger);
  };

  SearchTypeSelector.prototype.__toggleNodes = function(activate, trigger) {
    var j, l, len, len1, node, ref, ref1;
    if (trigger == null) {
      trigger = true;
    }
    if (this.__objecttypeTree) {
      ref = this.__objecttypeTree.getRootChildren();
      for (j = 0, len = ref.length; j < len; j++) {
        node = ref[j];
        node.checkbox.setValue(activate);
      }
    }
    if (this.__poolTree) {
      ref1 = this.__poolTree.getRootChildren();
      for (l = 0, len1 = ref1.length; l < len1; l++) {
        node = ref1[l];
        node.set_state(activate, true);
      }
    }
    if (!trigger) {
      this.updateInfo();
      return;
    }
    this.button.startSpinner();
    this.updateInfo().done((function(_this) {
      return function() {
        return _this.__savePopover().always(function() {
          return _this.button.stopSpinner();
        });
      };
    })(this)).fail((function(_this) {
      return function() {
        return _this.button.stopSpinner();
      };
    })(this));
  };

  return SearchTypeSelector;

})(SearchManager);
// Generated by CoffeeScript 1.12.7
var SearchTypeSelectorNode,
  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;

SearchTypeSelectorNode = (function(superClass) {
  extend(SearchTypeSelectorNode, superClass);

  function SearchTypeSelectorNode(opts) {
    this.opts = opts != null ? opts : {};
    SearchTypeSelectorNode.__super__.constructor.call(this, this.opts);
    this._selected = false;
  }

  SearchTypeSelectorNode.prototype.renderContent = function() {
    var div, info_btn;
    this.countSpan = new CUI.Label({
      text: ez5.format_number(this.count)
    }).DOM;
    this.addColumn(new CUI.ListViewColumn({
      element: this.countSpan
    }));
    info_btn = this.getInfoButton();
    if (info_btn) {
      this.addColumn(new CUI.ListViewColumn({
        element: info_btn
      }));
    }
    div = CUI.dom.div("ez5-search-type-selector-node");
    return CUI.dom.append(div, this.getCheckbox());
  };

  SearchTypeSelectorNode.prototype.extraInfo = function() {};

  SearchTypeSelectorNode.prototype.infoButtonNeedsSpinner = function() {
    return false;
  };

  SearchTypeSelectorNode.prototype.getInfoButtonDisabled = function() {
    return false;
  };

  SearchTypeSelectorNode.prototype.getInfoButton = function() {
    var infoButton;
    return infoButton = new LocaButton({
      ui: "search.type.selector.node.info.button",
      loca_key: "search.type.selector.node.button.info",
      appearance: "flat",
      disabled: this.getInfoButtonDisabled(),
      onClick: (function(_this) {
        return function(ev, btn) {
          if (_this.infoButtonNeedsSpinner()) {
            btn.startSpinner();
          }
          return CUI.decide(_this.getInfoDiv()).done(function(content) {
            var pop;
            pop = new ez5.HintPopover({
              element: infoButton,
              content: content,
              padded: false
            });
            pop.show();
            if (_this.infoButtonNeedsSpinner()) {
              return btn.stopSpinner();
            }
          });
        };
      })(this)
    });
  };

  SearchTypeSelectorNode.prototype.getTooltipTitle = function() {};

  SearchTypeSelectorNode.prototype.getInfoDiv = function() {};

  return SearchTypeSelectorNode;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var ObjecttypeSelectorNode,
  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;

ObjecttypeSelectorNode = (function(superClass) {
  extend(ObjecttypeSelectorNode, superClass);

  function ObjecttypeSelectorNode() {
    return ObjecttypeSelectorNode.__super__.constructor.apply(this, arguments);
  }

  ObjecttypeSelectorNode.prototype.initOpts = function() {
    ObjecttypeSelectorNode.__super__.initOpts.call(this);
    return this.addOpts({
      objecttype: {
        check: Objecttype
      },
      count: {
        check: function(v) {
          return v >= 0;
        }
      },
      manager: {
        check: SearchTypeSelector
      }
    });
  };

  ObjecttypeSelectorNode.prototype.readOpts = function() {
    ObjecttypeSelectorNode.__super__.readOpts.call(this);
    this.objecttype = this._objecttype;
    this.manager = this._manager;
    return this.count = this._count;
  };

  ObjecttypeSelectorNode.prototype.nameLocalized = function() {
    return this.objecttype.nameLocalized();
  };

  ObjecttypeSelectorNode.prototype.infoButtonNeedsSpinner = function() {
    return true;
  };

  ObjecttypeSelectorNode.prototype.extraInfo = function() {
    var cap, caps;
    caps = [];
    if (this.objecttype.poolLink()) {
      caps.push("pool");
    }
    if (this.objecttype.isHierarchy()) {
      caps.push("hierarchy");
    }
    if (this.objecttype.isPolyhierarchy()) {
      caps.push("polyhierarchy");
    }
    if (caps.length === 0) {
      return;
    }
    return new CUI.Label({
      "class": "ez5-objecttype-selector-node-has-pool",
      appearance: "muted",
      size: "mini",
      text: ((function() {
        var i, len, results;
        results = [];
        for (i = 0, len = caps.length; i < len; i++) {
          cap = caps[i];
          results.push($$("table.capability." + cap));
        }
        return results;
      })()).join(', ')
    });
  };

  ObjecttypeSelectorNode.prototype.getTooltipTitle = function() {
    return $$("main.search.selector.info.objecttype.title", {
      name: this.objecttype.nameLocalized()
    });
  };

  ObjecttypeSelectorNode.prototype.getCheckbox = function() {
    var set_value;
    set_value = (function(_this) {
      return function(ev) {
        var altKey, ctrlKey, i, len, node, on_off, siblings;
        ctrlKey = (ev != null ? ev.ctrlKey() : void 0) || (ev != null ? ev.metaKey() : void 0);
        altKey = ev != null ? ev.altKey() : void 0;
        if (ctrlKey || altKey) {
          on_off = _this.checkbox.getValue();
          siblings = _this.getFather().children;
          if (altKey) {
            siblings = siblings.slice(siblings.indexOf(_this));
          }
          for (i = 0, len = siblings.length; i < len; i++) {
            node = siblings[i];
            if (node !== _this) {
              node.checkbox.setValue(on_off);
            }
          }
        }
        _this.manager.updateInfo();
      };
    })(this);
    return this.checkbox = new CUI.Checkbox({
      ui: "objecttype.selector.checkbox:" + (this.objecttype.name()),
      name: "_selected",
      text: this.nameLocalized(),
      data: this.objecttype,
      tooltip: {
        markdown: true,
        text: $$("objecttype.selector.checkbox.tooltip")
      },
      multiline: true,
      onActivate: (function(_this) {
        return function(df, flags, ev) {
          return set_value(ev);
        };
      })(this),
      onDeactivate: (function(_this) {
        return function(df, flags, ev) {
          return set_value(ev);
        };
      })(this)
    }).start();
  };

  ObjecttypeSelectorNode.prototype.getInfoDiv = function() {
    return this.objecttype.getInfoDiv();
  };

  return ObjecttypeSelectorNode;

})(SearchTypeSelectorNode);
// Generated by CoffeeScript 1.12.7
var PoolSelectorNode,
  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;

PoolSelectorNode = (function(superClass) {
  extend(PoolSelectorNode, superClass);

  function PoolSelectorNode() {
    return PoolSelectorNode.__super__.constructor.apply(this, arguments);
  }

  PoolSelectorNode.prototype.initOpts = function() {
    PoolSelectorNode.__super__.initOpts.call(this);
    return this.addOpts({
      pool: {
        check: "PlainObject"
      },
      manager: {
        check: SearchTypeSelector
      }
    });
  };

  PoolSelectorNode.prototype.readOpts = function() {
    PoolSelectorNode.__super__.readOpts.call(this);
    if (this._pool) {
      return this.setData(this._pool);
    }
  };

  PoolSelectorNode.prototype.getCheckbox = function() {
    return this.__checkbox = new CUI.Checkbox({
      ui: "pool.selector.checkbox:" + this.id,
      name: "_selected",
      tooltip: {
        markdown: true,
        text: $$("pool.selector.node.tooltip"),
        show_ms: 1500
      },
      text: this.nameLocalized(),
      multiline: true,
      onClick: (function(_this) {
        return function(event) {
          return _this.checkbox_changed(event);
        };
      })(this),
      data: this
    }).start();
  };

  PoolSelectorNode.prototype.getTooltipTitle = function() {
    return $$("main.search.selector.info.pool.title", {
      name: this.nameLocalized()
    });
  };

  PoolSelectorNode.prototype.nameLocalized = function() {
    if (this.pool._instance && this.pool._path.length === 1) {
      return this.pool._path[this.pool._path.length - 1].text + '@' + ez5.connector.displaynameByInstance(this.pool._instance);
    } else {
      return this.pool._path[this.pool._path.length - 1].text;
    }
  };

  PoolSelectorNode.prototype.getInfoContent = function() {
    return CUI.dom.append(CUI.dom.pre(), CUI.util.dump(this.pool));
  };

  PoolSelectorNode.prototype.setData = function(data) {
    this.pool = data;
    this.id = this.pool.id || this.pool._id;
    return this.count = this.pool.count;
  };

  PoolSelectorNode.prototype.getInfoButtonDisabled = function() {
    if (ez5.pools.findPoolById(this._pool._id)) {
      return false;
    } else {
      return true;
    }
  };

  PoolSelectorNode.prototype.getInfoDiv = function() {
    this.poolObject = ez5.pools.findPoolById(this._pool._id);
    return this.poolObject.getInfoDiv();
  };

  PoolSelectorNode.prototype.renderContent = function() {
    var content;
    content = PoolSelectorNode.__super__.renderContent.call(this);
    this.setPartial(content);
    this.setCount();
    return content;
  };

  PoolSelectorNode.prototype.setPartial = function(element) {
    var checkboxButton, nodes, nodesSelected;
    if (this.isRoot()) {
      return element;
    }
    checkboxButton = this.__checkbox.getButton();
    CUI.dom.removeClass(checkboxButton, "cui-indeterminate");
    if (!this.isOpen() && !this.isLeaf()) {
      nodes = this.find();
      nodesSelected = nodes.filter((function(_this) {
        return function(node) {
          return node._selected;
        };
      })(this));
      if (nodes.length !== nodesSelected.length && nodesSelected.length > 0) {
        CUI.dom.addClass(checkboxButton, "cui-indeterminate");
        if (this._selected) {
          checkboxButton.setIcon("");
        }
      }
    }
    if (this.father && this.father.checkbox) {
      this.father.setPartial(CUI.dom.parent(this.father.checkbox));
    }
    return element;
  };

  PoolSelectorNode.prototype.refresh = function() {
    var child, i, len, ref;
    if (this.__checkbox) {
      if (this.__checkbox.isDestroyed()) {
        return;
      }
      if (this._selected) {
        this.__checkbox.activate();
      } else {
        this.__checkbox.deactivate();
      }
    }
    if (this.children) {
      ref = this.children;
      for (i = 0, len = ref.length; i < len; i++) {
        child = ref[i];
        child.refresh();
      }
    }
  };

  PoolSelectorNode.prototype.setCount = function() {
    var ref;
    if (this.isRoot()) {
      return;
    }
    return (ref = this.countSpan) != null ? ref.textContent = ez5.format_number(this.getCount()) : void 0;
  };

  PoolSelectorNode.prototype.getCount = function() {
    var child, count, i, len, ref;
    count = this.count;
    if (!this.isOpen()) {
      return count;
    }
    if (this.children) {
      ref = this.children;
      for (i = 0, len = ref.length; i < len; i++) {
        child = ref[i];
        count -= child.count;
      }
    }
    return count;
  };

  PoolSelectorNode.prototype.set_state = function(selected, include_children) {
    var c, i, len, ref, ref1, ref2;
    if (include_children == null) {
      include_children = true;
    }
    this._selected = selected;
    if (this._selected) {
      this.opts.manager.selected_pools[this.id] = true;
      if ((ref = this.__checkbox) != null) {
        ref.activate();
      }
    } else {
      delete this.opts.manager.selected_pools[this.id];
      if ((ref1 = this.__checkbox) != null) {
        ref1.deactivate();
      }
    }
    if (include_children && this.children) {
      ref2 = this.children;
      for (i = 0, len = ref2.length; i < len; i++) {
        c = ref2[i];
        c.set_state(this._selected, true);
      }
    }
    if (this.__checkbox) {
      this.setPartial(CUI.dom.parent(this.__checkbox));
    }
  };

  PoolSelectorNode.prototype.all_children_selected = function() {
    var i, len, p, ref;
    if (!this.children) {
      return true;
    }
    ref = this.children;
    for (i = 0, len = ref.length; i < len; i++) {
      p = ref[i];
      if (!p._selected) {
        return false;
      }
      if (!p.all_children_selected()) {
        return false;
      }
    }
    return true;
  };

  PoolSelectorNode.prototype.checkbox_changed = function(event) {
    var altKey, ctrlKey, i, len, p, shiftKey, siblings;
    ctrlKey = event.ctrlKey() || event.metaKey();
    shiftKey = event.shiftKey();
    altKey = event.altKey();
    if (ctrlKey || altKey) {
      siblings = this.father.children;
      if (altKey) {
        siblings = siblings.slice(siblings.indexOf(this));
      }
      for (i = 0, len = siblings.length; i < len; i++) {
        p = siblings[i];
        p.set_state(this._selected, !shiftKey);
      }
    } else {
      this.set_state(this._selected, !shiftKey);
    }
    return this.opts.manager.updateInfo();
  };

  PoolSelectorNode.prototype.isActive = function() {
    return this._selected;
  };

  return PoolSelectorNode;

})(SearchTypeSelectorNode);
// Generated by CoffeeScript 1.12.7
var Editor,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

Editor = (function(superClass) {
  extend(Editor, superClass);

  function Editor(opts1) {
    this.opts = opts1;
    Editor.__super__.constructor.call(this, this.opts);
    if (this._mode === "copy") {
      this.setMode("new");
      this.__copy = true;
      this.__copySkipFields = this._copySkipFields || [];
    } else {
      this.setMode(this._mode);
    }
    this.__updateObject = (function(_this) {
      return function() {
        var cardInfo, ex, ref, resultCardPinButton;
        _this.triggerCallback("editor-update");
        _this.object_list.updateObjectInBrowser();
        try {
          _this.updateSaveButton();
          if (!_this.isTemplate()) {
            cardInfo = _this.object.renderCardEditor({
              mode: "result-card-info-detail",
              force_standard: true
            });
            if (ez5.version("6") && ((ref = ez5.cssLoader.getActiveCSS()) != null ? ref.theme : void 0) === 'fylr') {
              resultCardPinButton = ResultObject.getResultCardPinButton(_this.__mainPane, "resultCard.unpin", function() {
                return _this.__configureGoToTopBtn();
              });
              CUI.dom.append(cardInfo, resultCardPinButton);
            }
            return CUI.dom.replace(_this.__cardInfoContainer, cardInfo);
          }
        } catch (error1) {
          ex = error1;
          if (ex instanceof UserError) {
            return ex.presentError();
          } else {
            throw ex;
          }
        }
      };
    })(this);
    ez5.session.addCookieOnlyPref("show_asset_browser", true);
  }

  Editor.prototype.initOpts = function() {
    Editor.__super__.initOpts.call(this);
    return this.addOpts({
      global_object_id: {
        check: String
      },
      object_list: {
        check: ObjectList
      },
      mode: {
        mandatory: true,
        check: ["single", "bulk", "new", "copy"]
      },
      closeButtonNoConfirm: {
        "default": false,
        check: Boolean
      },
      onCancel: {
        check: Function
      },
      onCopy: {
        check: Function
      },
      onCreateNewChild: {
        check: Function
      },
      onSave: {
        check: Function
      },
      onApply: {
        check: Function
      },
      onSaveReadOnly: {
        check: Function
      },
      onDelete: {
        check: Function
      },
      table_id: {
        check: function(v) {
          return v >= 0;
        }
      },
      parent_id: {
        check: "Integer"
      },
      format: {
        check: ["short", "standard", "long", "full", "long_inheritance", "full_inheritance"]
      },
      asset_browser_idx: {
        check: "Integer"
      },
      copyMask: {
        check: String
      },
      next_previous_global_object_ids: {
        check: function(value) {
          return CUI.util.isArray(value) && value.every((function(_this) {
            return function(v) {
              return CUI.util.isString(v);
            };
          })(this));
        }
      },
      copySkipFields: {
        check: "Array",
        "default": []
      }
    });
  };

  Editor.prototype.readOpts = function() {
    var ref;
    Editor.__super__.readOpts.call(this);
    this.template_idx = null;
    this.__asset_browser_idx = this._asset_browser_idx;
    this.__is_rendered = false;
    this.__next_previous_global_object_ids = this._next_previous_global_object_ids;
    if (this.__next_previous_global_object_ids && (ref = !this._global_object_id, indexOf.call(this.__next_previous_global_object_ids, ref) >= 0)) {
      this.__next_previous_global_object_ids.unshift(this._global_object_id);
    }
    this.__maskSelectedByObjecttype = {};
    if (this._object_list) {
      this.object_list = this._object_list;
    }
    this.__plugins = Editor.plugins.newPlugins();
    this.__updateButtonsFirstDone = false;
    this.editor_data = {};
    this.__old_pool = null;
    if (this._table_id) {
      return this.editor_data.table = new Table("CURRENT", parseInt(this._table_id));
    }
  };

  Editor.prototype.setMode = function(mode) {
    CUI.util.assert(mode === "single" || mode === "bulk" || mode === "new", "new " + (CUI.util.getObjectClass(this)), "opts.mode must be 'single', 'bulk', or 'new' but is " + (CUI.util.isEmpty(mode) ? CUI.util.getObjectClass(mode) : mode) + ".", {
      opts: this.opts,
      mode: mode
    });
    this.editor_data.mode = mode;
    return this;
  };

  Editor.prototype.getMode = function() {
    var ref;
    return ((ref = this.editor_data) != null ? ref.mode : void 0) || null;
  };

  Editor.prototype.getSearch = function() {};

  Editor.prototype.modeIs = function(arr) {
    var ref;
    CUI.util.assert(CUI.util.isArray(arr), (CUI.util.getObjectClass(this)) + ".modeIs", "arr needs to be Array but is " + (CUI.util.getObjectClass(this)), {
      arr: arr
    });
    return ref = this.editor_data.mode, indexOf.call(arr, ref) >= 0;
  };

  Editor.prototype.modeIsNot = function(arr) {
    return !this.modeIs(arr);
  };

  Editor.prototype.destroy = function() {
    var j, len1, p, ref, ref1, ref2;
    CUI.Events.ignore({
      instance: this
    });
    this.dismissWaitModal();
    this.cleanPollListeners();
    this.__deactivateSidebar();
    this.__removeAssetBrowser();
    if ((ref = this.newObjects) != null) {
      ref.destroy();
    }
    if ((ref1 = this.__pane) != null) {
      ref1.destroy();
    }
    this.__pane = null;
    ref2 = this.__plugins || [];
    for (j = 0, len1 = ref2.length; j < len1; j++) {
      p = ref2[j];
      p.destroy();
    }
    delete this.__historyBrowserObject;
    return Editor.__super__.destroy.call(this);
  };

  Editor.prototype.getDbInfo = function(ignore_not_found, add_default_tags) {
    var compiled_tags, dbInfo, dfr, idx, load_db_info, oids, pool_id, ref, ref1, ref2, ref3, ref4, tag, tag_ids, tags;
    if (ignore_not_found == null) {
      ignore_not_found = false;
    }
    if (add_default_tags == null) {
      add_default_tags = true;
    }
    dbInfo = new DbInfo();
    dfr = new CUI.Deferred();
    if (this.editor_data.table.hasTags() && this.modeIsNot(["bulk"])) {
      tags = ((ref = this.object) != null ? ref.getData()._tags : void 0) || [];
      if (tags.length === 0) {
        tags = ((ref1 = this.object) != null ? (ref2 = ref1.getData()._template) != null ? ref2._tags : void 0 : void 0) || [];
      }
      tag_ids = (function() {
        var j, len1, results;
        results = [];
        for (j = 0, len1 = tags.length; j < len1; j++) {
          tag = tags[j];
          results.push(tag._id);
        }
        return results;
      })();
      if (this.modeIs(["new"]) && add_default_tags) {
        compiled_tags = (ref3 = this.editor_data._pool) != null ? ref3._compiled_tags : void 0;
        if (compiled_tags && compiled_tags.length > 0) {
          compiled_tags.forEach((function(_this) {
            return function(tag) {
              if (tag.is_default && !tag_ids.includes(tag._id)) {
                return tag_ids.push(tag._id);
              }
            };
          })(this));
        }
      }
      if (CUI.util.isEmpty(tag_ids)) {
        tag_ids = void 0;
      }
    } else {
      tag_ids = void 0;
    }
    if (this.modeIsNot(["bulk"])) {
      pool_id = (ref4 = this.editor_data._pool) != null ? ref4.pool._id : void 0;
    } else {
      pool_id = void 0;
    }
    load_db_info = (function(_this) {
      return function() {
        return dbInfo.load({
          table: _this.editor_data.table,
          pool_id: pool_id,
          tag_ids: tag_ids,
          object_ids: oids,
          ignore_not_found: !!(ignore_not_found && pool_id)
        }).done(function() {
          return dfr.resolve(dbInfo);
        }).fail(function(xhr) {
          var ref5;
          if (ignore_not_found && pool_id && (xhr != null ? (ref5 = xhr.responseJSON) != null ? ref5.code : void 0 : void 0) === "error.user.no_masks_for_create") {
            pool_id = null;
            return load_db_info();
          } else {
            return dfr.reject(xhr);
          }
        });
      };
    })(this);
    if (this.modeIs(["new"])) {
      oids = void 0;
      load_db_info();
    } else if (this.modeIs(["bulk"])) {
      oids = (function() {
        var j, ref5, results;
        results = [];
        for (idx = j = 1, ref5 = this.object_list.getCount(); 1 <= ref5 ? j < ref5 : j > ref5; idx = 1 <= ref5 ? ++j : --j) {
          results.push(this.object_list.getObject(idx).id());
        }
        return results;
      }).call(this);
      load_db_info();
    } else {
      oids = [this.object.id()];
      load_db_info();
    }
    return dfr.promise();
  };

  Editor.prototype.setPoolFromPoolId = function(pool_id) {
    var pool;
    pool = ez5.pools.findPoolById(pool_id);
    if (!pool) {
      delete this.editor_data._pool;
      return;
    }
    return this.setPoolFromObject(pool.getData());
  };

  Editor.prototype.getAssetBrowserButton = function() {
    return new LocaButton({
      loca_key: "editor.pullout.asset_browser",
      disabled: true,
      hidden: true,
      radio_allow_null: true,
      group: "pull-out",
      radio: "editor-pull-out",
      onDeactivate: (function(_this) {
        return function(btn, flags, event) {
          if (flags.initial_activate || flags.prior_activate) {
            return;
          }
          if (event) {
            ez5.session.saveCookiePref("show_asset_browser", false);
          }
          return _this.hidePullOut();
        };
      })(this),
      onActivate: (function(_this) {
        return function(btn, flags, event) {
          if (event) {
            ez5.session.saveCookiePref("show_asset_browser", true);
          }
          _this.showPullOut();
          return _this.renderAssetBrowser();
        };
      })(this)
    });
  };

  Editor.prototype.getHistoryBrowserButton = function() {
    var btn;
    btn = new LocaButton({
      loca_key: "editor.pullout.revision_history.history.button",
      "class": "ez5-button-history-browser",
      disabled: false,
      group: "pull-out",
      left: true,
      radio_allow_null: true,
      radio: "editor-pull-out",
      onDeactivate: (function(_this) {
        return function(btn, flags) {
          if (flags.initial_activate || flags.prior_activate) {
            return;
          }
          return _this.hidePullOut();
        };
      })(this),
      onActivate: (function(_this) {
        return function() {
          btn.startSpinner();
          _this.showPullOut();
          if (!_this.__historyBrowserObject) {
            _this.__historyBrowserObject = new ResultObject();
          }
          _this.__historyBrowserObject.setData(_this.object.getData());
          return _this.__historyBrowserObject.loadFromDbWithFormat("full").done(function() {
            return _this.renderHistoryBrowser();
          }).always(function() {
            return btn.stopSpinner();
          });
        };
      })(this)
    });
    return btn;
  };

  Editor.prototype.getPullOutSwitch = function() {
    var buttons, ref;
    buttons = [];
    buttons.push(this.assetBrowserButton);
    if (this.modeIs(["single"]) && ez5.session.hasSystemRight("root", "frontend_features[changelog]") && ((ref = this.object) != null ? ref.getRights().write : void 0)) {
      this.historyBrowserButton = this.getHistoryBrowserButton();
      if (this.historyBrowserButton) {
        buttons.push(this.historyBrowserButton);
      }
    } else {
      this.historyBrowserButton = null;
    }
    if (!this.__pullOutFlexHandle || !buttons) {
      this.__pullOutSwitch = null;
    } else {
      if (this.__horizontalLayout) {
        this.__sidebarButton = new CUI.Button({
          icon_inactive: "right",
          icon_active: "left",
          disabled: true,
          group: "pull-out",
          "switch": true,
          onActivate: (function(_this) {
            return function() {
              return _this.__activateSidebar();
            };
          })(this),
          onDeactivate: (function(_this) {
            return function() {
              return _this.__deactivateSidebar();
            };
          })(this)
        });
        buttons.push(this.__sidebarButton);
      }
      this.__pullOutSwitch = new CUI.Buttonbar({
        buttons: buttons
      });
    }
    return this.__pullOutSwitch;
  };

  Editor.prototype.__deactivateSidebar = function() {
    if (!this.__horizontalLayout) {
      return;
    }
    if (this.__modalFlexHandle) {
      this.__pullOutFlexHandle.resetSize();
      CUI.dom.remove(this.__pullOutFlexHandle.getElement());
      this.__pullOutFlexHandle = this.__modalFlexHandle;
      delete this.__modalFlexHandle;
    }
    CUI.dom.removeClass(document.body, "ez5-editor-pullout-active");
    CUI.dom.removeClass(this.__pullOutDiv, "cui-layer-sidebar--active");
    this.__pullOutFlexHandle.open().show();
    this.__horizontalLayout.append(this.__pullOutDiv, "right");
    CUI.Events.trigger({
      type: "viewport-resize",
      node: this.__pullOutDiv
    });
  };

  Editor.prototype.__activateSidebar = function() {
    var fh_el, opts;
    this.__pullOutFlexHandle.close().hide();
    CUI.dom.addClass(document.body, "ez5-editor-pullout-active");
    fh_el = CUI.dom.element("DIV");
    CUI.dom.append(document.body, fh_el);
    CUI.dom.append(document.body, this.__pullOutDiv);
    CUI.dom.addClass(this.__pullOutDiv, "cui-layer-sidebar--active");
    opts = {
      name: "pullout",
      direction: "row",
      element: fh_el,
      state_name: "editor-pullout",
      pane: ".ez5-editor-pullout",
      maxValue: window.innerWidth / 2,
      onResize: function(fh, size) {
        if (size) {
          document.body.style.setProperty("--pullout-width", size + "px");
        } else {
          document.body.style.setProperty("--pullout-width", "");
        }
      }
    };
    this.__modalFlexHandle = this.__pullOutFlexHandle;
    this.__pullOutFlexHandle = new CUI.FlexHandle(opts);
    this.__pullOutFlexHandle.init();
    CUI.Events.trigger({
      type: "viewport-resize",
      node: this.__pullOutDiv
    });
  };

  Editor.prototype.showPullOut = function() {
    var ref, ref1;
    if ((ref = this.__sidebarButton) != null) {
      ref.enable();
    }
    return (ref1 = this.__pullOutFlexHandle) != null ? ref1.open().show() : void 0;
  };

  Editor.prototype.__removeAssetBrowser = function() {
    if (this.assetBrowser) {
      this.assetBrowser.destroy();
      this.assetBrowser = null;
    }
    if (this.assetBrowserInfoControl) {
      this.assetBrowserInfoControl.destroy();
      CUI.dom.remove(this.assetBrowserInfoControl);
      this.assetBrowserInfoControl = null;
    }
    return this;
  };

  Editor.prototype.hidePullOut = function() {
    var ref;
    if (this.__sidebarButton) {
      this.__sidebarButton.deactivate();
      this.__sidebarButton.disable();
    }
    this.__removeAssetBrowser();
    return (ref = this.__pullOutFlexHandle) != null ? ref.close().hide() : void 0;
  };

  Editor.prototype.renderHistoryBrowser = function() {
    CUI.dom.empty(this.__pullOutDiv);
    CUI.dom.append(this.__pullOutDiv, this.__historyBrowserObject.renderHistoryBrowser(null, this));
    return this.__pullOutDiv;
  };

  Editor.prototype.renderAssetBrowser = function() {
    var assets, ref;
    if (!((ref = this.assetBrowserButton) != null ? ref.isActive() : void 0)) {
      return;
    }
    CUI.dom.empty(this.__pullOutDiv);
    if (this.object instanceof TemplateObject) {
      assets = this.object.getAssetsForBrowser("editor-template");
    } else {
      assets = this.object.getAssetsForBrowser("editor");
    }
    this.__removeAssetBrowser();
    if (this.__asset_browser_idx >= assets.length) {
      this.__asset_browser_idx = Math.max(assets.length - 1, 0);
    }
    this.assetBrowser = new AssetBrowser({
      ui: "asset.browser.editor",
      assets: assets,
      hires: true,
      start_idx: this.__asset_browser_idx || 0,
      editor_mode: true
    });
    this.assetBrowserInfoControl = this.getAssetBrowserInfoControl();
    this.appendAssetBrowser();
    return this;
  };

  Editor.prototype.closeHistoryBrowser = function() {
    var ref;
    return (ref = this.historyBrowserButton) != null ? ref.deactivate() : void 0;
  };

  Editor.prototype.restoreVersion = function(version_number) {
    var ref, render_mode, render_mode_header;
    ref = this.getRenderModes(this.object), render_mode_header = ref[0], render_mode = ref[1];
    return this.object.restoreDataFromVersion(version_number, render_mode_header, render_mode).done((function(_this) {
      return function() {
        _this.reloadEditor();
        return _this.triggerCallback("editor-update");
      };
    })(this));
  };

  Editor.prototype.getAssetBrowserInfoControl = function() {
    return new AssetBrowserInfoControl({
      assetBrowser: this.assetBrowser
    });
  };

  Editor.prototype.appendAssetBrowser = function() {
    CUI.dom.append(this.__pullOutDiv, this.assetBrowser);
    return CUI.dom.append(this.__pullOutDiv, this.assetBrowserInfoControl);
  };

  Editor.prototype.updateAssetBrowser = function(info) {
    if (!this.assetBrowserButton) {
      return;
    }
    if (info) {
      if (!this.assetBrowserButton.isActive()) {
        this.assetBrowserButton.activate();
      }
      return CUI.Events.trigger({
        type: "show-asset",
        node: this.__pullOutDiv,
        info: info
      });
    } else {
      return CUI.Events.trigger({
        type: "eas_update",
        node: this.__pullOutDiv
      });
    }
  };

  Editor.prototype.getMainPane = function() {
    return CUI.util.assert(false, (CUI.util.getObjectClass(this)) + ".getMainPane", "Needs implementation");
  };

  Editor.prototype.getEditorWrapper = function() {
    return this.__mainPane;
  };

  Editor.prototype.getScrollableWrapper = function() {
    return this.__mainPane;
  };

  Editor.prototype.rememberScrollPosition = function() {
    return false;
  };

  Editor.prototype.rememberMaskSplitterStates = function() {
    return false;
  };

  Editor.prototype.getChunkSize = function() {
    return null;
  };

  Editor.prototype.getChunkSizeSelect = function() {
    return null;
  };

  Editor.prototype.registerPollListener = function(fieldName, listener) {
    if (this.__fieldsPollListener == null) {
      this.__fieldsPollListener = {};
    }
    if (this.__fieldsPollListener[fieldName]) {
      this.__fieldsPollListener[fieldName].destroy();
    }
    return this.__fieldsPollListener[fieldName] = listener;
  };

  Editor.prototype.clearPollListener = function(fieldName) {
    if (!this.__fieldsPollListener) {
      return;
    }
    if (this.__fieldsPollListener[fieldName]) {
      this.__fieldsPollListener[fieldName].destroy();
      return delete this.__fieldsPollListener[fieldName];
    }
  };

  Editor.prototype.cleanPollListeners = function() {
    var fieldName, listener, ref;
    ref = this.__fieldsPollListener || {};
    for (fieldName in ref) {
      listener = ref[fieldName];
      listener.destroy();
    }
    return this.__fieldsPollListener = {};
  };

  Editor.prototype.render = function() {
    var mode, requiredWrapper;
    mode = CUI.util.toDash(CUI.util.getObjectClass(this));
    this.__mainPane = this.getMainPane();
    this.__paneHeader = new CUI.PaneHeader({
      left: {}
    });
    this.__toolbar = new CUI.PaneToolbar();
    this.assetBrowserButton = this.getAssetBrowserButton();
    this.askForCommentCheckbox = new CUI.Checkbox({
      text: $$("main.editor.require_comment"),
      mark_changed: false,
      name: "require_comment",
      data: this.editor_data,
      "class": "ez5-checkbox-require-comment",
      tooltip: {
        text: $$("main.editor.require_comment")
      }
    }).start();
    this.__requiredLabel = new LocaLabel({
      "class": "ez5-editor-required-message",
      loca_key: "editor.required_input_message",
      group: "required"
    });
    this.__serverValidationLabel = new LocaLabel({
      "class": "ez5-editor-required-message",
      loca_key: "editor.server_validation_message",
      group: "required"
    });
    this.__serverValidationLabelTemplate = new LocaLabel({
      "class": "ez5-editor-required-message",
      loca_key: "editor.server_validation_message_template",
      group: "required"
    });
    this.__warningLabel = new LocaLabel({
      "class": "ez5-editor-required-message",
      loca_key: "editor.warning_input_message",
      group: "required"
    });
    this.__bulkNoSelectedFieldsLabel = new LocaLabel({
      "class": "ez5-editor-required-message",
      loca_key: "editor.bulk_mode.no_selected_fields",
      group: "required"
    });
    this.__requiredDetailsBtn = new LocaButton({
      loca_key: "editor.required_details_btn",
      size: "mini",
      group: "required",
      onClick: (function(_this) {
        return function() {
          var j, len1, p, plbl, pop, problems, ref;
          if (_this.__currentProblems.length === 0) {
            return;
          }
          problems = [];
          ref = _this.__currentProblems;
          for (j = 0, len1 = ref.length; j < len1; j++) {
            p = ref[j];
            problems.push("* " + p.getProblemText());
          }
          plbl = new CUI.Label({
            text: problems.join("\n"),
            markdown: true,
            multiline: true
          });
          pop = new CUI.Popover({
            element: _this.__requiredDetailsBtn,
            backdrop: {
              policy: "click"
            },
            placement: "n",
            placements: ["n", "ne", "nw"],
            pane: {
              padded: true,
              title: $$("editor.required_details.popover.title"),
              content: plbl
            }
          });
          return pop.show();
        };
      })(this)
    });
    this.__serverValidationLabel.hide();
    this.__serverValidationLabelTemplate.hide();
    this.__requiredLabel.hide();
    this.__warningLabel.hide();
    this.__bulkNoSelectedFieldsLabel.hide();
    this.__requiredDetailsBtn.hide();
    requiredWrapper = CUI.dom.div("ez5-required-message");
    CUI.dom.append(requiredWrapper, [
      this.__requiredLabel, this.__warningLabel, this.__serverValidationLabel, this.__serverValidationLabelTemplate, this.__bulkNoSelectedFieldsLabel, new CUI.Buttonbar({
        buttons: [this.__requiredDetailsBtn]
      }).DOM
    ]);
    this.__toolbarBottom = new CUI.PaneToolbar({
      center: {
        content: requiredWrapper
      },
      right: {
        content: (function(_this) {
          return function() {
            var btns;
            btns = [];
            btns.push.apply(btns, _this.getChunkSizeSelect());
            if (btns.length === 0) {
              return;
            }
            return new CUI.Buttonbar({
              "class": "ez5-select-chunk-size",
              buttons: btns
            });
          };
        })(this)
      }
    });
    this.__paneFooter = new CUI.PaneFooter();
    this.__pane = new CUI.Pane({
      top: {
        content: [this.__paneHeader, this.__toolbar]
      },
      center: {
        content: [this.__mainPane]
      },
      bottom: {
        content: [this.__toolbarBottom, this.__paneFooter]
      }
    });
    this.__waitBlock = new CUI.WaitBlock({
      ui: "editor.wait.block",
      element: this.__pane.center()
    });
    EventPoller.listen({
      instance: this,
      filter: (function(_this) {
        return function(event) {
          var j, len1, obj, ref;
          if (!_this.object_list) {
            return false;
          }
          ref = _this.object_list.getObjects();
          for (j = 0, len1 = ref.length; j < len1; j++) {
            obj = ref[j];
            if (event.global_object_id && obj.getGlobalObjectId() === event.global_object_id) {
              return true;
            }
          }
          return false;
        };
      })(this),
      call: (function(_this) {
        return function(events) {
          var event, j, len1;
          if (_this.modeIs(["new"])) {
            return;
          }
          if (_this.ignoreEvents()) {
            return;
          }
          for (j = 0, len1 = events.length; j < len1; j++) {
            event = events[j];
            switch (event.type) {
              case "OBJECT_INSERT":
                _this.__saveInProgress = false;
                break;
              case "OBJECT_UPDATE":
                if (_this.__saveInProgress) {
                  _this.__saveInProgress = false;
                } else if (event.object_version > _this.object.version()) {
                  if (event.session_self) {
                    _this.object.loadFromDbWithMask(_this.editor_data.mask_name).done(function() {
                      return _this.load();
                    });
                  } else {
                    _this.askForVersionChanged();
                  }
                }
                break;
              case "OBJECT_DELETE":
                if (event.session_self) {
                  _this.callback("delete");
                } else {
                  _this.askForVersionDeleted();
                }
            }
          }
        };
      })(this)
    });
    CUI.Events.listen({
      node: this.__pane,
      instance: this,
      type: "asset-browser-idx-changed",
      call: (function(_this) {
        return function(ev, info) {
          return _this.__asset_browser_idx = info.current_idx;
        };
      })(this)
    });
    CUI.Events.listen({
      node: this.__pane,
      instance: this,
      type: "asset-browser-show-asset",
      call: (function(_this) {
        return function(ev, info) {
          if (CUI.dom.closest(ev.getTarget(), ".history-version")) {
            return;
          }
          return _this.updateAssetBrowser(info);
        };
      })(this)
    });
    CUI.Events.listen({
      node: this.__pane,
      instance: this,
      type: ["keydown"],
      call: (function(_this) {
        return function(event) {
          if (event.hasModifierKey() && event.code() === "KeyS") {
            event.stopPropagation();
            event.preventDefault();
            _this.handleSave(event);
          }
        };
      })(this)
    });
    CUI.dom.addClass(this.__pane.DOM, "ez5-editor ez5-editor-mode-" + mode);
    CUI.dom.setAttribute(this.__pane, "ui", "editor.container:" + mode);
    return this.__pane;
  };

  Editor.prototype.getToolbarRightContent = function() {};

  Editor.prototype.ignoreEvents = function() {
    return false;
  };

  Editor.prototype.getCurrentTools = function() {
    return CUI.resolvedPromise([]);
  };

  Editor.prototype.customizeTemplates = function() {
    var apply_selected_template_btn, check_status, data, deselect_all, dfr, dts, getOutputTemplateFields, getRowEditButton, group_id, group_templates, init_data, init_data_shared, j, len1, mask_id, mod, ref, saveButton, save_and_close, save_shared_templates, selected_template, shared_templates, template, templates;
    selected_template = null;
    dts = [];
    deselect_all = (function(_this) {
      return function(new_selected_row) {
        var dt, j, len1, results;
        results = [];
        for (j = 0, len1 = dts.length; j < len1; j++) {
          dt = dts[j];
          results.push(dt.listView.getSelectedRows().forEach(function(row) {
            if (row === new_selected_row) {
              return;
            }
            return row.deselect();
          }));
        }
        return results;
      };
    })(this);
    templates = ez5.session.getPref(this.__getTemplatesPrefKey()) || {};
    mask_id = this.object.getMask().id();
    shared_templates = this.__getSharedTemplates(true);
    data = {
      templates: []
    };
    ref = templates[mask_id] || [];
    for (j = 0, len1 = ref.length; j < len1; j++) {
      template = ref[j];
      data.templates.push({
        name: template.name,
        comment: template.comment,
        create_date: template.create_date,
        orig_name: template.name,
        data: template.data
      });
    }
    init_data = JSON.stringify(data);
    init_data_shared = {};
    for (group_id in shared_templates) {
      group_templates = shared_templates[group_id];
      init_data_shared[group_id] = JSON.stringify(group_templates);
    }
    dfr = new CUI.Deferred();
    apply_selected_template_btn = new LocaButton({
      loca_key: "editor.templates.customize.apply_selected",
      ui: "editor.templates.customize.apply_selected.button",
      disabled: true,
      onClick: (function(_this) {
        return function(ev) {
          if (!selected_template) {
            return;
          }
          if (check_status()) {
            return new CUI.ConfirmationChoice({
              text: $$("editor.template.save_and_apply.confirm.msg.md", {
                name: template.name
              }),
              ui: "editor.template.confirmation",
              markdown: true,
              choices: [
                {
                  cancel: true,
                  text: $$("editor.template.apply.confirm.cancel")
                }, {
                  _value: "save_and_apply",
                  text: $$("editor.template.apply.confirm.save_and_apply"),
                  primary: true
                }
              ]
            }).open().done(function(choice) {
              if (choice._value === "save_and_apply") {
                dfr.done(function() {
                  return _this.useTemplate(selected_template);
                });
                return save_and_close(ev);
              }
            });
          } else {
            _this.useTemplate(selected_template);
            dfr.resolve();
            return mod.destroy();
          }
        };
      })(this)
    });
    save_and_close = (function(_this) {
      return function(ev) {
        var l, len2, len3, m, mask_templates, promises, ref1, ref2, shared_promises, tmpl;
        saveButton.disable();
        mask_templates = [];
        ref1 = data.templates;
        for (l = 0, len2 = ref1.length; l < len2; l++) {
          tmpl = ref1[l];
          data = null;
          ref2 = templates[mask_id];
          for (m = 0, len3 = ref2.length; m < len3; m++) {
            template = ref2[m];
            if (template.name === tmpl.orig_name) {
              data = template.data;
              break;
            }
          }
          mask_templates.push({
            name: tmpl.name,
            data: data,
            comment: tmpl.comment,
            create_date: tmpl.create_date || new Date().toISOString()
          });
        }
        templates[mask_id] = mask_templates;
        promises = [];
        promises.push(ez5.session.savePref(_this.__getTemplatesPrefKey(), templates, true));
        shared_promises = save_shared_templates(ev) || [];
        promises = promises.concat(shared_promises);
        return CUI.whenAll(promises).done(function() {
          mod.destroy();
          return dfr.resolve();
        }).fail(function() {
          return saveButton.enable();
        });
      };
    })(this);
    saveButton = new LocaButton({
      loca_key: "editor.templates.customize.save",
      ui: "editor.templates.customize.save.button",
      disabled: true,
      primary: true,
      onClick: (function(_this) {
        return function(ev) {
          return save_and_close(ev);
        };
      })(this)
    });
    check_status = (function(_this) {
      return function() {
        var check_shared;
        check_shared = function() {
          for (group_id in shared_templates) {
            group_templates = shared_templates[group_id];
            if (init_data_shared[group_id] !== JSON.stringify(group_templates)) {
              return true;
            }
          }
        };
        if (init_data !== JSON.stringify(data) || check_shared()) {
          saveButton.enable();
          return true;
        } else {
          saveButton.disable();
        }
        return false;
      };
    })(this);
    save_shared_templates = (function(_this) {
      return function(ev) {
        var changed_groups, gdfr, group, promises;
        promises = [];
        changed_groups = {};
        for (group_id in shared_templates) {
          group_templates = shared_templates[group_id];
          if (init_data_shared[group_id] !== JSON.stringify(group_templates)) {
            changed_groups[group_id] = group_templates;
          }
        }
        for (group_id in changed_groups) {
          group_templates = changed_groups[group_id];
          gdfr = new CUI.Deferred();
          group = ez5.groupManager.getGroupById(parseInt(group_id));
          if (group.isWritable()) {
            group.load().done(function() {
              var groupData;
              groupData = group.getData();
              groupData.group.frontend_prefs.webfrontend.shared_templates[mask_id] = group_templates;
              return group.headlessSave(ev).done(gdfr.resolve).fail(gdfr.reject);
            }).fail(gdfr.reject);
          }
          promises.push(gdfr.promise());
        }
        return promises;
      };
    })(this);
    getRowEditButton = (function(_this) {
      return function(show_user) {
        if (show_user == null) {
          show_user = false;
        }
        return new LocaButton({
          icon: "fa-pencil",
          ui: "editor.templates.customize.edit.button",
          onClick: function(ev, btn) {
            var dt, editPopover, original_data, rows, selected_data;
            dt = btn._data_table;
            if (!dt) {
              return;
            }
            rows = dt.listView.getSelectedRows();
            if (rows.length === 0) {
              return;
            }
            selected_data = rows[0].getData();
            original_data = CUI.util.copyObject(selected_data, true);
            editPopover = new CUI.Modal({
              cancel: true,
              onCancel: function() {
                return CUI.confirm({
                  text: $$("editor.templates.customize.confirm_unsaved")
                }).done(function() {
                  Object.assign(selected_data, original_data);
                  return editPopover.destroy();
                });
              },
              pane: {
                title: $$("editor.templates.customize.edit.title"),
                padded: true,
                footer_right: [
                  new LocaButton({
                    loca_key: "editor.templates.customize.save",
                    primary: true,
                    onClick: function(ev) {
                      CUI.Events.trigger({
                        type: "data-changed",
                        node: dt.listView
                      });
                      check_status();
                      dt.loadPage();
                      return editPopover.destroy();
                    }
                  })
                ],
                content: function() {
                  return new CUI.Form({
                    data: selected_data,
                    fields: [
                      {
                        type: CUI.Input,
                        name: "name",
                        form: {
                          label: $$("editor.templates.customize.data_table.name")
                        },
                        ui: "editor.templates.customize.data_table.name.input"
                      }, {
                        type: CUI.Output,
                        name: "create_date",
                        form: {
                          label: $$("editor.templates.customize.data_table.create_date")
                        },
                        ui: "editor.templates.customize.data_table.create_date",
                        getValue: function(value) {
                          return ez5.format_date_and_time(value);
                        }
                      }, show_user ? {
                        type: CUI.Output,
                        name: "user",
                        form: {
                          label: $$("editor.templates.customize.data_table.user")
                        },
                        ui: "editor.templates.customize.data_table.user",
                        getValue: function(value) {
                          return value;
                        }
                      } : void 0, {
                        type: CUI.Input,
                        name: "comment",
                        form: {
                          label: $$("editor.templates.customize.data_table.comment")
                        },
                        ui: "editor.templates.customize.data_table.comment",
                        textarea: true
                      }
                    ]
                  }).start();
                }
              }
            });
            return editPopover.show();
          }
        });
      };
    })(this);
    getOutputTemplateFields = (function(_this) {
      return function() {
        return [
          {
            type: CUI.Output,
            name: "name",
            form: {
              label: $$("editor.templates.customize.data_table.name")
            },
            ui: "editor.templates.customize.data_table.name.input"
          }, {
            type: CUI.Output,
            name: "comment",
            form: {
              label: $$("editor.templates.customize.data_table.comment"),
              column: "maximize"
            },
            ui: "editor.templates.customize.data_table.comment"
          }, {
            type: CUI.Output,
            name: "create_date",
            form: {
              label: $$("editor.templates.customize.data_table.create_date")
            },
            ui: "editor.templates.customize.data_table.create_date",
            getValue: function(value) {
              return ez5.format_date_and_time(value);
            }
          }, {
            type: CUI.OutputContent,
            name: "data",
            getValue: function(templateData) {
              return new CUI.Button({
                icon: "fa-eye",
                onClick: (function(_this) {
                  return function(ev, btn) {
                    var pop, previewData, ro;
                    previewData = CUI.util.copyObject(templateData, true);
                    previewData._mapped_metadata_created = true;
                    ro = new ResultObject();
                    ro.setData(previewData);
                    pop = new CUI.Popover({
                      size: "m",
                      "class": "ez5-editor-templates-customize-preview-popover ez5-check-tab-height",
                      element: btn,
                      placement: "n",
                      pane: {
                        content: ro.renderDetail("detail", "detail-header", {}),
                        padded: true,
                        maximize_horizontal: true,
                        maximize_vertical: true
                      },
                      onShow: function() {
                        var tabs;
                        tabs = CUI.dom.findElements(pop.DOM, ".cui-tab-body");
                        tabs.forEach(function(tab) {
                          var tabDim;
                          tabDim = CUI.dom.getDimensions(tab);
                          return CUI.dom.setStyle(tab, {
                            height: tabDim.borderBoxHeight
                          });
                        });
                        return CUI.dom.removeClass(pop, "ez5-check-tab-height");
                      }
                    });
                    return pop.show();
                  };
                })(this)
              });
            },
            form: {
              label: "Preview"
            }
          }
        ];
      };
    })(this);
    mod = new CUI.Modal({
      ui: "editor.templates.customize.modal",
      "class": "ez5-editor-templates-customize-modal",
      size: "l",
      cancel: true,
      fill_screen_button: true,
      onCancel: (function(_this) {
        return function() {
          if (init_data === JSON.stringify(data)) {
            return;
          }
          return CUI.confirm({
            text: $$("editor.templates.customize.confirm_unsaved")
          }).done(function() {
            return dfr.reject();
          });
        };
      })(this),
      pane: {
        title: $$("editor.templates.customize.title"),
        footer_right: [apply_selected_template_btn, saveButton],
        ui: "editor.templates.customize.pane",
        content: (function(_this) {
          return function() {
            var tabs, tabsPanel, user_template_dt;
            user_template_dt = new CUI.DataTable({
              maximize: true,
              data: data,
              name: "templates",
              rowMove: true,
              new_rows: "remove_only",
              onRowRemove: function(data, ev) {
                var shared_template_dt;
                shared_template_dt = null;
                return apply_selected_template_btn.disable();
              },
              onRowDeselect: function() {
                var shared_template_dt;
                shared_template_dt = null;
                return apply_selected_template_btn.disable();
              },
              onRowSelect: function(ev, info) {
                deselect_all(info.row);
                selected_template = info.row.getData();
                return apply_selected_template_btn.enable();
              },
              buttons: [getRowEditButton()],
              ui: "editor.templates.customize.data_table",
              "class": "ez5-editor-templates-customize-data-table",
              onDataChanged: function() {
                return check_status();
              },
              fields: getOutputTemplateFields()
            });
            tabs = [];
            tabs.push({
              name: "user-templates",
              text: "User Templates",
              content: function() {
                dts.push(user_template_dt);
                return user_template_dt.start();
              },
              onActivate: function() {
                selected_template = null;
                return apply_selected_template_btn.disable();
              }
            });
            if (!CUI.util.isEmpty(shared_templates)) {
              tabs.push({
                name: "shared-templates",
                text: "Shared Templates",
                content: function() {
                  var panel, panels, shared_template_dt, vl;
                  panels = [];
                  for (group_id in shared_templates) {
                    group_templates = shared_templates[group_id];
                    shared_template_dt = new CUI.DataTable({
                      "class": "ez5-editor-templates-customize-data-table",
                      data: shared_templates,
                      name: group_id,
                      rowMove: true,
                      new_rows: "remove_only",
                      ui: "editor.templates.customize.data_table",
                      buttons: [getRowEditButton(true)],
                      onRowDeselect: function() {
                        shared_template_dt = null;
                        return apply_selected_template_btn.disable();
                      },
                      onRowSelect: function(ev, info) {
                        deselect_all(info.row);
                        selected_template = info.row.getData();
                        return apply_selected_template_btn.enable();
                      },
                      onBeforeRowRemove: function(data, ev) {
                        return CUI.confirm({
                          text: $$("editor.templates.customize.confirm_remove_shared"),
                          markdown: true
                        });
                      },
                      onRowRemove: function(data, ev) {
                        shared_template_dt = null;
                        return apply_selected_template_btn.disable();
                      },
                      onDataChanged: function() {
                        return check_status();
                      },
                      fields: getOutputTemplateFields()
                    });
                    dts.push(shared_template_dt);
                    panel = new CUI.Panel({
                      text: ez5.groupManager.getGroupById(parseInt(group_id)).getDisplayText(),
                      radio: true,
                      closed: true,
                      content: function() {
                        return shared_template_dt.start();
                      }
                    });
                    panels.push(panel);
                  }
                  return vl = new CUI.VerticalList({
                    content: panels,
                    maximize_horizontal: true,
                    maximize_vertical: true
                  });
                }
              });
            }
            tabsPanel = new CUI.Tabs({
              tabs: tabs,
              maximize_horizontal: true,
              maximize_vertical: true,
              onActivate: function() {
                deselect_all();
                selected_template = null;
                return apply_selected_template_btn.disable();
              }
            });
            return tabsPanel;
          };
        })(this)
      }
    }).show();
    return dfr.promise();
  };

  Editor.prototype.saveAsTemplate = function() {
    var canShareTemplates, data, dfr, e, existingUserTemplates, mask_id, saveButton, saveTemplate, saveTemplateModal, templateData;
    try {
      data = this.object.getSaveData({
        copy: true,
        copy_for_template: true
      });
    } catch (error1) {
      e = error1;
      CUI.problem({
        text: $$("editor.template.save_as_template.invalid|text")
      });
      return CUI.rejectedPromise();
    }
    dfr = new CUI.Deferred();
    dfr.always((function(_this) {
      return function() {
        return saveTemplateModal.destroy();
      };
    })(this));
    existingUserTemplates = ez5.session.getPref(this.__getTemplatesPrefKey()) || {};
    mask_id = this.object.getMask().id();
    saveTemplate = (function(_this) {
      return function(ev, overwrite) {
        var group, group_id, j, l, len1, len2, name, newUserTemplates, ref, ref1, ref2, template, userTemplate;
        if (overwrite == null) {
          overwrite = false;
        }
        if (!templateData.shared_template) {
          if (((ref = existingUserTemplates[mask_id]) != null ? ref.length : void 0) > 0 && !overwrite) {
            name = templateData.name.trim();
            ref1 = existingUserTemplates[mask_id];
            for (j = 0, len1 = ref1.length; j < len1; j++) {
              userTemplate = ref1[j];
              if (userTemplate.name === name) {
                CUI.confirm({
                  markdown: true,
                  button_primary: "cancel",
                  button_text_ok: $$("editor.template.save_as_template.overwrite"),
                  text: $$("editor.template.save_as_template.name.exists", {
                    name: name
                  })
                }).done(function() {
                  return saveTemplate(ev, true);
                });
                return;
              }
            }
          }
          newUserTemplates = CUI.util.copyObject(existingUserTemplates, true);
          if (!newUserTemplates[mask_id]) {
            newUserTemplates[mask_id] = [];
          }
          template = {
            name: templateData.name.trim(),
            data: data,
            comment: templateData.comment || "",
            create_date: new Date().toISOString()
          };
          if (!overwrite) {
            newUserTemplates[mask_id].push(template);
          } else {
            ref2 = newUserTemplates[mask_id];
            for (l = 0, len2 = ref2.length; l < len2; l++) {
              userTemplate = ref2[l];
              if (userTemplate.name === template.name) {
                userTemplate.data = template.data;
                userTemplate.comment = template.comment;
                userTemplate.create_date = template.create_date;
                break;
              }
            }
          }
          return ez5.session.savePref(_this.__getTemplatesPrefKey(), newUserTemplates).done(dfr.resolve).fail(dfr.reject);
        } else {
          group_id = templateData.shared_template_group.group._id;
          group = ez5.groupManager.getGroupById(group_id);
          if (group.isWritable()) {
            return group.load().done(function() {
              var base, base1, base2, base3, groupData;
              groupData = group.getData();
              if ((base = groupData.group).frontend_prefs == null) {
                base.frontend_prefs = {};
              }
              if ((base1 = groupData.group.frontend_prefs).webfrontend == null) {
                base1.webfrontend = {};
              }
              if ((base2 = groupData.group.frontend_prefs.webfrontend).shared_templates == null) {
                base2.shared_templates = {};
              }
              if ((base3 = groupData.group.frontend_prefs.webfrontend.shared_templates)[mask_id] == null) {
                base3[mask_id] = [];
              }
              groupData.group.frontend_prefs.webfrontend.shared_templates[mask_id].push({
                name: templateData.name.trim(),
                data: data,
                user: ez5.session.getUser().getId(),
                create_date: new Date().toISOString(),
                comment: templateData.comment || ""
              });
              return group.headlessSave(ev).done(dfr.resolve).fail(dfr.reject);
            }).fail(dfr.reject);
          } else {
            return dfr.reject();
          }
        }
      };
    })(this);
    saveButton = new LocaButton({
      loca_key: "editor.templates.customize.save",
      ui: "editor.templates.customize.save.button",
      disabled: true,
      primary: true,
      onClick: (function(_this) {
        return function(ev) {
          return saveTemplate(ev);
        };
      })(this)
    });
    templateData = {};
    canShareTemplates = ez5.groupManager.getGroups().some((function(_this) {
      return function(group) {
        if (group.isWritable()) {
          return true;
        }
      };
    })(this));
    saveTemplateModal = new CUI.Modal({
      cancel: true,
      "class": "ez5-editor-templates-save-modal",
      size: "s",
      onCancel: (function(_this) {
        return function() {
          dfr.reject();
        };
      })(this),
      pane: {
        title: $$("editor.template.save_as_template.title"),
        footer_right: saveButton,
        content: (function(_this) {
          return function() {
            return new CUI.Form({
              data: templateData,
              fields: [
                {
                  type: CUI.Input,
                  name: "name",
                  form: {
                    label: "Template Name"
                  },
                  placeholder: $$("editor.template.save_as_template.name.placeholder"),
                  checkInput: function(name) {
                    name = name.trim();
                    return !CUI.util.isEmpty(name);
                  }
                }, {
                  type: CUI.Input,
                  textarea: true,
                  form: {
                    label: $$("editor.templates.customize.data_table.comment")
                  },
                  name: "comment",
                  placeholder: $$("editor.template.save_as_template.comment.placeholder")
                }, canShareTemplates ? {
                  type: CUI.Checkbox,
                  name: "shared_template",
                  form: {
                    label: $$("editor.template.save_as_template.shared")
                  },
                  onDataChanged: function(data, field) {
                    var groupField, ref;
                    groupField = (ref = field.getForm().getFieldsByName("shared_template_group")) != null ? ref[0] : void 0;
                    if (data.shared_template && groupField) {
                      groupField.show(true);
                    } else {
                      groupField.hide(true);
                    }
                    return CUI.Events.trigger({
                      type: "content-resize",
                      node: saveTemplateModal
                    });
                  }
                } : void 0, canShareTemplates ? {
                  type: UserGroupSelector,
                  form: {
                    label: $$("editor.template.save_as_template.shared_group")
                  },
                  name: "shared_template_group",
                  generate_rights: true,
                  aclWhoManager: new AclWhoManager({
                    filter_system_groups: false,
                    who_filter: ["group"]
                  }),
                  filterData: function(group) {
                    var ref;
                    group = (ref = AclWho.newInstance(group)) != null ? ref.group : void 0;
                    if (group != null ? group.isWritable() : void 0) {
                      return true;
                    }
                    return false;
                  },
                  hidden: templateData.shared_template !== true
                } : void 0
              ],
              onDataChanged: function(data, input) {
                var nameInput, ref;
                nameInput = (ref = input.getForm()) != null ? ref.getFieldsByName("name")[0] : void 0;
                if (nameInput.getInputState() === "valid") {
                  return saveButton.enable();
                } else {
                  return saveButton.disable();
                }
              }
            }).start();
          };
        })(this)
      }
    });
    saveTemplateModal.show();
    return dfr.promise();
  };

  Editor.prototype.updateData = function(newData) {
    return this.object.setData(newData);
  };

  Editor.prototype.useTemplate = function(template) {
    return new CUI.ConfirmationChoice({
      text: $$("editor.template.apply.confirm.msg.md", {
        name: template.name
      }),
      ui: "editor.template.confirmation",
      markdown: true,
      choices: [
        {
          cancel: true,
          text: $$("editor.template.apply.confirm.cancel")
        }, {
          _value: "replace",
          text: $$("editor.template.apply.confirm.replace")
        }, {
          _value: "merge",
          text: $$("editor.template.apply.confirm.merge"),
          primary: true
        }
      ]
    }).open().done((function(_this) {
      return function(choice) {
        var copyObject, e, mergeOrReplace, ref, render_mode, render_mode_header;
        ref = _this.getRenderModes(_this.object), render_mode_header = ref[0], render_mode = ref[1];
        mergeOrReplace = function(object) {
          switch (choice._value) {
            case "merge":
              object.mergeData(template.data, render_mode_header, render_mode);
              break;
            case "replace":
              object.mergeData(template.data, render_mode_header, render_mode, true);
          }
        };
        copyObject = _this.object.copy();
        mergeOrReplace(copyObject);
        try {
          copyObject.getSaveData({
            copy: true,
            copy_for_template: true,
            create_objects: []
          });
        } catch (error1) {
          e = error1;
          CUI.problem({
            text: $$("editor.template.use_template.invalid|text")
          });
          return;
        }
        mergeOrReplace(_this.object);
        _this.reloadEditor();
      };
    })(this));
  };

  Editor.prototype.__getTemplatesPrefKey = function() {
    return "editor.templates";
  };

  Editor.prototype.__getSharedTemplates = function(onlyWritable) {
    var group, groupData, group_full_data, groups, j, l, len1, len2, name1, ref, ref1, result, template, templates;
    if (onlyWritable == null) {
      onlyWritable = false;
    }
    result = {};
    if (ez5.session.hasSystemRight("root")) {
      groups = ez5.groupManager.getGroups();
    } else {
      groups = ez5.session.getGroups() || [];
    }
    for (j = 0, len1 = groups.length; j < len1; j++) {
      group = groups[j];
      if (onlyWritable && !ez5.session.hasSystemRight("root")) {
        if (group instanceof SystemGroup) {
          group_full_data = ez5.groupManager.getGroupById(group.getId());
          if (!(group_full_data != null ? group_full_data.isWritable() : void 0)) {
            continue;
          }
        } else if (!group.isWritable()) {
          continue;
        }
      }
      groupData = group.getData();
      if ((ref = groupData.group.frontend_prefs) != null ? (ref1 = ref.webfrontend) != null ? ref1.shared_templates : void 0 : void 0) {
        templates = groupData.group.frontend_prefs.webfrontend.shared_templates[this.object.getMask().id()] || [];
        for (l = 0, len2 = templates.length; l < len2; l++) {
          template = templates[l];
          if (result[name1 = group.id] == null) {
            result[name1] = [];
          }
          result[group.id].push(template);
        }
      }
    }
    return result;
  };

  Editor.prototype.getStandardTools = function() {
    var adhocTemplateKey, adhocdisabled, all_user_templates, find_group_by_id, fn, fn1, getSharedTemplateTooltip, group_id, group_templates, j, len1, shared_templates, template, templates, tools;
    all_user_templates = ez5.session.getPref(this.__getTemplatesPrefKey()) || {};
    templates = all_user_templates[this.object.getMask().id()] || [];
    shared_templates = this.__getSharedTemplates();
    tools = [];
    if (CUI.util.isEmpty(window.adhoc_template) || window.adhoc_template.objecttype !== this.object.objecttype()) {
      adhocTemplateKey = $$("editor.template.no_adhoc_template.label");
      adhocdisabled = true;
    } else {
      adhocTemplateKey = $$("editor.template.adhoc_template.label");
      adhocdisabled = false;
    }
    tools.push({
      text: adhocTemplateKey,
      disabled: adhocdisabled,
      onClick: (function(_this) {
        return function() {
          return _this.useTemplate(window.adhoc_template);
        };
      })(this)
    });
    tools.push({
      divider: true
    });
    fn = (function(_this) {
      return function(template) {
        return tools.push({
          text: template.name,
          tooltip: {
            text: function() {
              var tooltipText;
              tooltipText = template.name;
              if (!CUI.util.isEmpty(template.comment)) {
                tooltipText += " - " + template.comment;
              }
              return tooltipText;
            }
          },
          ui: "editor.templates.tools.template.button:" + template.name,
          onClick: function() {
            return _this.useTemplate(template);
          }
        });
      };
    })(this);
    for (j = 0, len1 = templates.length; j < len1; j++) {
      template = templates[j];
      fn(template);
    }
    if (!CUI.util.isEmpty(templates)) {
      tools.push({
        divider: true
      });
    }
    find_group_by_id = (function(_this) {
      return function(group_id) {
        var group, groups, l, len2;
        if (ez5.session.hasSystemRight("root")) {
          groups = ez5.groupManager.getGroups();
        } else {
          groups = ez5.session.getGroups();
        }
        for (l = 0, len2 = groups.length; l < len2; l++) {
          group = groups[l];
          if (group.getId() === group_id) {
            return group;
          }
        }
        return null;
      };
    })(this);
    getSharedTemplateTooltip = (function(_this) {
      return function(group_id, template) {
        var tooltip;
        tooltip = (find_group_by_id(parseInt(group_id)).getDisplayText()) + " - " + template.name;
        if (!CUI.util.isEmpty(template.comment)) {
          tooltip += " - " + template.comment;
        }
        if (template.create_date) {
          tooltip += " - " + ez5.format_date_and_time(template.create_date, true);
        }
        return tooltip;
      };
    })(this);
    fn1 = (function(_this) {
      return function(group_id, group_templates) {
        var l, len2, results;
        results = [];
        for (l = 0, len2 = group_templates.length; l < len2; l++) {
          template = group_templates[l];
          results.push((function(template) {
            return tools.push({
              text: find_group_by_id(parseInt(group_id)).getDisplayText() + ": " + template.name,
              tooltip: {
                text: function() {
                  return getSharedTemplateTooltip(group_id, template);
                }
              },
              onClick: function() {
                return _this.useTemplate(template);
              }
            });
          })(template));
        }
        return results;
      };
    })(this);
    for (group_id in shared_templates) {
      group_templates = shared_templates[group_id];
      fn1(group_id, group_templates);
    }
    if (tools.length > 0) {
      tools.push({
        divider: true
      });
    }
    tools.push({
      loca_key: "editor.template.save_as_template",
      ui: "editor.templates.tools.save_as_template.button",
      onClick: (function(_this) {
        return function() {
          return _this.saveAsTemplate().done(function() {
            return _this.updateToolbarRight();
          });
        };
      })(this)
    });
    tools.push({
      loca_key: "editor.template.customize",
      ui: "editor.templates.tools.customize.button",
      disabled: (function(_this) {
        return function() {
          return templates.length < 1 && CUI.util.isEmpty(_this.__getSharedTemplates(true));
        };
      })(this),
      onClick: (function(_this) {
        return function() {
          return _this.customizeTemplates().done(function() {
            return _this.updateToolbarRight();
          });
        };
      })(this)
    });
    template = new ToolboxTool({
      name: "editor.template.menu",
      favorite: true,
      loca_key: "tool.editor.template.menu",
      sort: "B:4",
      tools: tools
    });
    return [template];
  };

  Editor.prototype.updateToolbarRight = function() {
    return this.getCurrentTools().always((function(_this) {
      return function(tools) {
        tools.push.apply(tools, _this.getStandardTools());
        _this.__toolsButton = Toolbox.getFlyoutButtonbar(tools || []);
        return _this.__toolbar.replace([_this.getToolbarRightContent(), _this.__toolsButton], "right");
      };
    })(this));
  };

  Editor.prototype.callback = function(status, arg1) {
    var name1;
    return typeof this[name1 = "_on" + CUI.util.toCamel(status, true)] === "function" ? this[name1](this, arg1) : void 0;
  };

  Editor.prototype.setPoolFromObject = function(pool_obj) {
    return this.editor_data._pool = pool_obj;
  };

  Editor.prototype.setPoolInObject = function(resultObject) {
    CUI.util.assert(resultObject instanceof ResultObject, "Editor.setPoolInObject", "resultObject needs to be instance of ResultObject", {
      resultObject: resultObject
    });
    resultObject.getData()[this.editor_data.table.name()]._pool = this.editor_data._pool;
  };

  Editor.prototype.checkAndSetPoolFromDbInfo = function() {
    var current_pool_id, errorLabel, pool_ids, ref;
    if (!this.editor_data.table.poolLink()) {
      return;
    }
    CUI.util.assert(this.editor_data.dbInfo instanceof DbInfo, "Editor.checkAndSetPoolFromDbInfo", "editor_data.dbInfo not set.", {
      editor_data: this.editor_data,
      editor: this
    });
    current_pool_id = (ref = this.editor_data._pool) != null ? ref.pool._id : void 0;
    pool_ids = this.editor_data.dbInfo.getPoolIds(null, false);
    if (this.modeIs(["bulk"])) {
      if (pool_ids === false) {
        throw new UserError({
          label: "editor.load.no_pool_for_bulk_found"
        });
      }
      if (pool_ids.length === 0) {
        return false;
      }
    }
    errorLabel = "editor.load.no_pool_found";
    if (this instanceof EditorHeadlessNew) {
      errorLabel += ".editor_headless";
    }
    if (pool_ids.length === 0) {
      throw new UserError({
        label: errorLabel
      });
    }
    if (!current_pool_id || indexOf.call(pool_ids, current_pool_id) < 0) {
      if (this.modeIs(["bulk"])) {
        return false;
      } else {
        if (!this.setPoolFromPoolId(pool_ids[0])) {
          throw new UserError({
            label: errorLabel
          });
        }
        return true;
      }
    } else {
      return false;
    }
  };

  Editor.prototype.load = function(dfr, level) {
    var data, deferred, load, ot, ref, ref1;
    if (dfr == null) {
      dfr = new CUI.Deferred();
    }
    if (level == null) {
      level = 0;
    }
    this.cleanPollListeners();
    CUI.util.assert((this.object_list && ((ref = this.getMode()) === "bulk" || ref === "new" || ref === "single")) || (this._global_object_id && !this.object_list && (((ref1 = this.getMode()) === "single") || this.__copy)) || (this.getMode() === "new" && this._table_id && !this.object_list), "Editor.load", "One of opts.global_object_id and opts.object_list must be set, or opts.table_id and opts.mode == 'new'.", {
      opts: this.opts,
      editor: this
    });
    if (this.object_list) {
      return this.__load(dfr, level);
    }
    if (this._global_object_id) {
      ResultObject.loadFromGlobalObjectId(this._global_object_id, "short", null, true, false).done((function(_this) {
        return function(result_object) {
          _this.object_list = new ObjectList({
            onRemove: function(object, idx) {
              return _this.__onObjectListRemove(object, idx);
            }
          });
          if (_this.__copy) {
            result_object.loadFromDb(null, _this._copyMask, "long").fail(dfr.reject).done(function() {
              var save_data;
              save_data = result_object.getSaveData({
                copy: true,
                skipFields: _this.__copySkipFields
              });
              _this.editor_data.table = result_object.table();
              if (_this.supportsTemplate()) {
                _this.addNewTemplateObject(save_data);
                _this.addNewResultObject();
              } else {
                _this.addNewResultObject(save_data);
              }
              return _this.__load(dfr, level);
            });
            return _this.__copy = false;
          } else {
            _this.object_list.push(result_object);
            return _this.__load(dfr, level);
          }
        };
      })(this)).fail(dfr.reject);
      return dfr.promise();
    }
    if (this.getMode() === "new") {
      ot = new Objecttype(ez5.schema.CURRENT._table_by_id[this._table_id]);
      data = {
        _mask: ot.getTable().preferredMask().name()
      };
      this.object_list = new ObjectList({
        onRemove: (function(_this) {
          return function(object, idx) {
            return _this.__onObjectListRemove(object, idx);
          };
        })(this)
      });
      load = (function(_this) {
        return function() {
          _this.addNewResultObject(data);
          return _this.__load(dfr, level);
        };
      })(this);
      if (!this._parent_id) {
        return load();
      }
      deferred = new CUI.Deferred();
      ResultObject.loadFromId(ot.name(), this._parent_id).done((function(_this) {
        return function(resultObject) {
          var path;
          path = resultObject.getData()._path;
          path.push(data);
          data._path = path;
          return data[ot.name()] = {
            _id_parent: _this._parent_id
          };
        };
      })(this)).always((function(_this) {
        return function() {
          return load().done(deferred.resolve).fail(deferred.reject);
        };
      })(this));
      return deferred.promise();
    }
    return CUI.util.assert("Editor.load", "Unsupported opts for load.", {
      opts: this.opts
    });
  };

  Editor.prototype.__load = function(dfr, level) {
    var promise, version;
    if (this.isDestroyed()) {
      return CUI.rejectedPromise();
    }
    CUI.util.assert(this.object_list.getCount(), "Editor.load", "Cannot load object, no objects in ObjectList", {
      opts: this.opts
    });
    CUI.util.assert(this.__pane, "Editor.load", "Cannot load, editor needs to be rendered first.");
    if (this.object_list.getCurrentIdx() === null) {
      this.object_list.setCurrentIdx(0);
    }
    this.object = this.object_list.getObject();
    CUI.util.assert(this.object instanceof ResultObject, (CUI.util.getObjectClass(this)) + ".load", "Cannot load object, object is not instance of ResultObject but \"" + (CUI.util.getObjectClass(this.object)) + "\".", {
      opts: this.opts,
      object: this.object
    });
    if (!this.editor_data.table) {
      this.editor_data.table = this.object.table();
      if (this.copyButton) {
        this.copyButton.hide();
        DbInfo.canCreate({
          objecttypes: [new Objecttype(this.editor_data.table)]
        }).done((function(_this) {
          return function() {
            return _this.copyButton.show();
          };
        })(this));
      }
    }
    dfr.always(((function(_this) {
      return function() {
        return _this.__updateNavigationPreviousNext();
      };
    })(this)));
    dfr.notify("rights");
    dfr.fail((function(_this) {
      return function(error) {
        return console.warn("Editor.load FAIL", _this.object_list.getCurrentIdx() + "/" + _this.object_list.getCount(), _this.object.getGlobalObjectId() || "new", error);
      };
    })(this));
    if (this.modeIs(["bulk"]) || !this.object.id()) {
      promise = CUI.resolvedPromise();
    } else {
      version = this.object.getVersion();
      this.__waitBlock.show();
      if (this.modeIs(["single"]) && ez5.version("6")) {
        promise = this.object.loadFromDb(null, this.editor_data.mask_name, "long_inheritance");
      } else {
        promise = this.object.loadFromDbWithMask(this.editor_data.mask_name);
      }
      promise.done((function(_this) {
        return function() {
          if (_this.editor_data.object_version && version !== _this.editor_data.object_version) {
            delete _this.editor_data._pool;
          }
          return _this.editor_data.object_version = version;
        };
      })(this));
    }
    promise.fail(dfr.reject);
    promise.done((function(_this) {
      return function() {
        var ignore_not_found, pool;
        if (!_this.editor_data._pool && _this.editor_data.table.poolLink()) {
          pool = _this.object.pool();
          if (_this.modeIsNot(["new", "bulk"])) {
            CUI.util.assert(pool, "Editor.load", "Unable to set pool for object, pool not found.", {
              object: _this.object,
              table: _this.editor_data.table
            });
          }
          _this.setPoolFromObject(pool);
        }
        if (_this.modeIs(["new"])) {
          ignore_not_found = true;
        } else {
          ignore_not_found = false;
        }
        return _this.getDbInfo(ignore_not_found).fail(dfr.reject).done(function(dbInfo) {
          var _mask, _masks, _standardMaskFound, dbReload, ex, j, len1, load_trigger, ref;
          _this.editor_data.dbInfo = dbInfo;
          try {
            if (_this.modeIsNot(["new"]) && !dbInfo.getGeneratedRights().write) {
              _this.throwNoRightsError();
            }
            if (_this.checkAndSetPoolFromDbInfo()) {
              CUI.util.assert(level === 0, "Editor.load", "Unable to set pool in new object.", {
                editor: _this
              });
              _this.load(dfr, level + 1);
              return;
            }
            if (_this.editor_data.mask_name && !dbInfo.maskNameAvailable(_this.editor_data.mask_name)) {
              _this.editor_data.mask_name = null;
            }
            if (!_this.editor_data.mask_name) {
              if (dbInfo.availableMasks().length === 0) {
                throw new UserError({
                  label: "editor.load.rightsmanagement.error.no_masks"
                });
              }
              _this.editor_data.mask_name = ez5.maskMemoryManager.getBestMask(_this.object, "editor", dbInfo.availableMasks());
              if (!dbInfo.maskNameAvailable(_this.editor_data.mask_name)) {
                _masks = [];
                ref = dbInfo.availableMasks();
                for (j = 0, len1 = ref.length; j < len1; j++) {
                  _mask = ref[j];
                  if (_mask.hideInEditor()) {
                    continue;
                  }
                  if (_mask.isStandard()) {
                    _this.editor_data.mask_name = _mask.name();
                    _standardMaskFound = true;
                    break;
                  }
                  _masks.push(_mask);
                }
                if (!_standardMaskFound) {
                  _this.editor_data.mask_name = dbInfo.availableMasks()[0].name();
                }
                if (level < 2) {
                  _this.__load(dfr, level + 1);
                  return;
                }
                console.error("Trying to reload mask, level >= 2", level, _this.editor_data.mask_name);
              }
              if (_this.object.mask.name() !== _this.editor_data.mask_name) {
                dbReload = true;
              } else {
                dbReload = false;
              }
            }
            load_trigger = _this.triggerCallback("editor-load");
            load_trigger.fail(dfr.reject);
            return load_trigger.done(function() {
              var render;
              dfr.notify("render");
              render = function() {
                _this.object.initSaveData({
                  bulk: _this.modeIs(["bulk"]),
                  new_mode: _this.modeIs(["new"]),
                  editor: _this
                });
                return _this.renderObject().done(dfr.resolve).fail(dfr.reject);
              };
              if (dbReload && _this.modeIs(["single"])) {
                return _this.object.loadFromDbWithMask(_this.editor_data.mask_name).done(function() {
                  return render();
                }).fail(dfr.reject);
              } else {
                _this.object.setMask(_this.editor_data.mask_name);
                return render();
              }
            });
          } catch (error1) {
            ex = error1;
            if (ex instanceof UserError) {
              ex.presentError().done(function() {});
              dfr.reject();
              return;
            }
            throw ex;
          }
        });
      };
    })(this));
    return dfr.promise();
  };

  Editor.prototype.triggerCallback = function(type, info) {
    if (info == null) {
      info = {};
    }
    info.editor = this;
    info.object = this.object;
    info.editor_data = this.editor_data;
    return CUI.Events.trigger({
      type: type,
      info: info
    });
  };

  Editor.prototype.throwNoRightsError = function() {
    if (this.modeIs(["bulk"])) {
      throw new UserError({
        label: "editor.load.rightsmanagement.error.no_rights_bulk"
      });
    } else {
      throw new UserError({
        label: "editor.load.rightsmanagement.error.no_rights"
      });
    }
  };

  Editor.prototype.getMaskSelectPlaceholder = function() {
    return this.maskSelectPlaceholder = CUI.dom.div("cui-buttonbar");
  };

  Editor.prototype.updateMaskSelect = function() {
    var mfs;
    CUI.dom.empty(this.maskSelectPlaceholder);
    mfs = new MaskFieldSelector({
      dbInfo: this.editor_data.dbInfo,
      show_all_fields_mask: true,
      mask_name: this.editor_data.mask_name,
      onChanged: (function(_this) {
        return function(old_name, new_name) {
          return _this.loadNewMask({
            loca_key: "main.editor.confirm_mask_change",
            new_mask_name: new_name
          });
        };
      })(this)
    });
    CUI.dom.append(this.maskSelectPlaceholder, mfs.getSelect().start().DOM);
    return this;
  };

  Editor.prototype.getPoolNameLocalized = function(pool) {
    if (pool == null) {
      pool = this.editor_data._pool;
    }
    return (new Pool({
      pool: pool
    })).getDisplayText();
  };

  Editor.prototype.getMaskNameLocalized = function(mask_name) {
    if (mask_name == null) {
      mask_name = this.editor_data.mask_name;
    }
    return Mask.getMaskByMaskName(mask_name, this.editor_data.table.id()).nameLocalized();
  };

  Editor.prototype.loadNewMask = function(_opts) {
    var confirm_text, dfr, load_new_mask, new_pool, opts;
    opts = CUI.Element.readOpts(_opts, "Editor.loadMasks", {
      loca_key: {
        mandatory: true,
        check: String
      },
      new_mask_name: {
        mandatory: true,
        check: String
      },
      confirm: {
        "default": this.hasChanges(),
        mandatory: true,
        check: Boolean
      }
    });
    if (this.editor_data._pool) {
      new_pool = this.getPoolNameLocalized();
    } else {
      new_pool = "";
    }
    confirm_text = $$(opts.loca_key, {
      current_mask: this.getMaskNameLocalized(),
      new_mask: this.getMaskNameLocalized(opts.new_mask_name),
      new_pool: new_pool
    });
    dfr = new CUI.Deferred();
    if (this.modeIs(["new", "bulk"])) {
      load_new_mask = (function(_this) {
        return function() {
          _this.editor_data.mask_name = opts.new_mask_name;
          if (_this.object) {
            ez5.maskMemoryManager.storeMask(_this.object.objecttype(), _this.editor_data.mask_name, "editor");
          }
          _this.reloadEditor();
          _this.triggerCallback("editor-update");
          _this.triggerCallback("editor-mask-changed");
          return dfr.resolve();
        };
      })(this);
    } else {
      load_new_mask = (function(_this) {
        return function() {
          var old_name;
          old_name = _this.editor_data.mask_name;
          _this.editor_data.mask_name = opts.new_mask_name;
          return _this.load().done(function() {
            if (_this.object) {
              ez5.maskMemoryManager.storeMask(_this.object.objecttype(), _this.editor_data.mask_name, "editor");
            }
            _this.object_list.updateObjectInBrowser();
            _this.updateButtons();
            return dfr.resolve();
          }).fail(function() {
            _this.editor_data.mask_name = old_name;
            return dfr.reject();
          });
        };
      })(this);
    }
    if (opts.confirm) {
      CUI.confirm({
        text: confirm_text,
        ui: "editor.load_new_mask.confirmation"
      }).done(load_new_mask).fail(dfr.reject);
    } else {
      load_new_mask();
    }
    return dfr.promise();
  };

  Editor.prototype.getDeleteButton = function() {
    return this.deleteButton = new LocaButton({
      loca_key: "editor.button.delete",
      ui: "editor.delete.button",
      text: $$("base.delete"),
      secondary: true,
      onClick: (function(_this) {
        return function() {
          return _this.deleteObjects();
        };
      })(this)
    });
  };

  Editor.prototype.deleteObjects = function(ask, allow_empty) {
    var deleteText, dfr, len;
    if (ask == null) {
      ask = this.editor_data.require_comment;
    }
    if (allow_empty == null) {
      allow_empty = false;
    }
    if (this.hasTemplate()) {
      len = this.object_list.getCount() - 1;
    } else {
      len = this.object_list.getCount();
    }
    if (len === 1) {
      deleteText = $$("admin.easydb.object.remove.confirm");
    } else {
      deleteText = $$("admin.easydb.object.remove.confirm.bulk", [len]);
    }
    dfr = new CUI.Deferred();
    CUI.confirm({
      title: $$("admin.easydb.object.remove.title"),
      icon: new CUI.Icon({
        icon: $$("admin.easydb.object.remove.icon")
      }),
      text: deleteText,
      button_text_ok: $$("base.delete"),
      button_icon_ok: new CUI.Icon({
        icon: $$("base.delete|icon")
      }),
      button_text_cancel: $$("base.cancel"),
      button_danger: "ok"
    }).fail(dfr.reject).done((function(_this) {
      return function(choice, btn, ev) {
        return _this.askForComment(ev, "delete", ask, allow_empty).fail(dfr.reject).done(function(ev) {
          return _this["delete"](ev).done(dfr.resolve).fail(dfr.reject);
        });
      };
    })(this));
    return dfr.promise();
  };

  Editor.prototype.undeleteObjects = function() {
    var deleteText, dfr, len;
    if (this.hasTemplate()) {
      len = this.object_list.getCount() - 1;
    } else {
      len = this.object_list.getCount();
    }
    if (len === 1) {
      deleteText = $$("admin.easydb.object.undelete.confirm");
    } else {
      deleteText = $$("admin.easydb.object.undelete.confirm.bulk", [len]);
    }
    dfr = new CUI.Deferred();
    CUI.confirm({
      title: $$("admin.easydb.object.undelete.title"),
      icon: new CUI.Icon({
        icon: $$("admin.easydb.object.remove.icon")
      }),
      text: deleteText,
      button_text_ok: $$("base.undelete"),
      button_icon_ok: new CUI.Icon({
        icon: $$("base.delete|icon")
      }),
      button_text_cancel: $$("base.cancel"),
      button_danger: "ok"
    }).fail(dfr.reject).done((function(_this) {
      return function(choice, btn, ev) {
        return _this.undelete(ev).done(dfr.resolve).fail(dfr.reject);
      };
    })(this));
    return dfr.promise();
  };

  Editor.prototype.purgeObjects = function() {
    var dfr, len, purgeText;
    if (this.hasTemplate()) {
      len = this.object_list.getCount() - 1;
    } else {
      len = this.object_list.getCount();
    }
    if (len === 1) {
      purgeText = $$("admin.easydb.object.purge.confirm");
    } else {
      purgeText = $$("admin.easydb.object.purge.confirm.bulk", {
        count: len
      });
    }
    dfr = new CUI.Deferred();
    CUI.confirm({
      title: $$("admin.easydb.object.purge.title"),
      icon: new CUI.Icon({
        icon: $$("admin.easydb.object.remove.icon")
      }),
      text: purgeText,
      button_text_ok: $$("base.purge"),
      button_icon_ok: new CUI.Icon({
        icon: $$("base.delete|icon")
      }),
      button_text_cancel: $$("base.cancel"),
      button_danger: "ok"
    }).fail(dfr.reject).done((function(_this) {
      return function(choice, btn, ev) {
        return _this.purge(ev).done(dfr.resolve).fail(dfr.reject);
      };
    })(this));
    return dfr.promise();
  };

  Editor.prototype.purge = function(ev) {
    var idx, j, obj, ot_names, ref, ref1, ref2, send_data, send_data_per_ot, start, tn;
    if (this.hasTemplate()) {
      start = 1;
    } else {
      start = 0;
    }
    send_data_per_ot = {};
    ot_names = [];
    for (idx = j = ref = start, ref1 = this.object_list.getCount(); ref <= ref1 ? j < ref1 : j > ref1; idx = ref <= ref1 ? ++j : --j) {
      obj = this.object_list.getObject(idx);
      if (!obj.id()) {
        continue;
      }
      tn = obj.objecttype();
      send_data = send_data_per_ot[tn];
      if (!send_data) {
        send_data = send_data_per_ot[tn] = [];
        ot_names.push(tn);
      }
      send_data.push([obj.id(), obj.version(), (ref2 = this.editor_data.comment) != null ? ref2.trim() : void 0]);
    }
    if (ev.ctrlKey() || ev.shiftKey() || ev.altKey()) {
      console.debug("PURGE", CUI.util.dump(send_data_per_ot));
      return CUI.rejectedPromise();
    }
    return CUI.chunkWork.call(this, {
      items: ot_names,
      chunk_size: 1,
      call: (function(_this) {
        return function(items) {
          var ot_name;
          ot_name = items[0];
          send_data = send_data_per_ot[ot_name];
          return ez5.api.db({
            type: "DELETE",
            api: '/' + ot_name + '?delete_policy=purge',
            json_data: send_data
          });
        };
      })(this)
    }).done((function(_this) {
      return function() {
        return _this.callback("purge");
      };
    })(this));
  };

  Editor.prototype.doSave = function(ev) {
    var dfr, idx, next_plugin, popts, ref, ref1;
    this.updateSaveButton();
    if ((ref = this.saveButton) != null ? ref.isDisabled() : void 0) {
      return CUI.rejectedPromise();
    }
    this.saveButton.disable();
    if ((ref1 = CUI.dom.find(":focus")[0]) != null) {
      ref1.blur();
    }
    dfr = new CUI.Deferred();
    dfr.fail((function(_this) {
      return function() {
        var ref2;
        return (ref2 = _this.saveButton) != null ? ref2.enable() : void 0;
      };
    })(this));
    popts = {
      bulk: this.modeIs(["bulk"]),
      "new": this.modeIs(["new"]),
      event: ev,
      editor: this,
      resultObject: this.object,
      objectList: this.object_list
    };
    idx = 0;
    next_plugin = (function(_this) {
      return function() {
        var p;
        if (idx === _this.__plugins.length) {
          _this.__doSave(ev).done(dfr.resolve).fail(dfr.reject);
          return;
        }
        p = _this.__plugins[idx];
        return CUI.decide(p.__onSave(popts)).fail(dfr.reject).done(function() {
          idx++;
          return next_plugin();
        });
      };
    })(this);
    next_plugin();
    return dfr.promise();
  };

  Editor.prototype.__doSave = function(ev) {
    var dfr;
    if (ev && (ev.altKey() || ev.shiftKey())) {
      return this.save(ev);
    }
    dfr = new CUI.Deferred();
    this.askForComment(ev, "save", this.editor_data.require_comment).fail(dfr.reject).done((function(_this) {
      return function(ev) {
        return _this.save(ev).fail(dfr.reject).done(function(received_data) {
          var read_only;
          if (_this.modeIsNot(["bulk"]) && received_data.length === 1 && !received_data[0]._generated_rights.write) {
            read_only = true;
          } else {
            read_only = false;
          }
          return dfr.resolve(received_data, read_only);
        });
      };
    })(this));
    return dfr.promise();
  };

  Editor.prototype.getCancelButton = function() {
    return new LocaButton({
      ui: "editor-cancel-button",
      loca_key: "editor.button.cancel",
      onClick: (function(_this) {
        return function(ev) {
          return _this.doCancel(ev);
        };
      })(this)
    });
  };

  Editor.prototype.handleSave = function(event) {
    this.__clearServerValidationErrors();
    if (this.rememberMaskSplitterStates()) {
      this.storeMaskSplitterStates();
    }
    return this.doSave(event).done((function(_this) {
      return function(received_data, read_only) {
        if (read_only) {
          return _this.callback("saveReadOnly", received_data);
        } else {
          return _this.callback("save", received_data);
        }
      };
    })(this)).fail((function(_this) {
      return function(error) {
        var ref, ref1, validation_problems;
        if (ez5.version("6.7") && (error != null ? (ref = error.response) != null ? ref.code : void 0 : void 0) === "validation.plugin.error") {
          validation_problems = (ref1 = error.response.parameters) != null ? ref1.problems : void 0;
          return _this.__processSeverValidationProblems(validation_problems);
        }
      };
    })(this));
  };

  Editor.prototype.getSaveButton = function() {
    var saveButtonGroup;
    saveButtonGroup = [];
    this.saveButton = new LocaButton({
      loca_key: "editor.button.save",
      ui: "editor.button.save",
      text: $$("base.save"),
      disabled: true,
      primary: true,
      onClick: (function(_this) {
        return function(ev) {
          return _this.handleSave(ev);
        };
      })(this)
    });
    saveButtonGroup.push(this.saveButton);
    if (this.askForCommentCheckbox) {
      saveButtonGroup.push(this.askForCommentCheckbox);
    }
    return saveButtonGroup;
  };

  Editor.prototype.__clearServerValidationErrors = function() {
    var j, len1, object, ref, results;
    ref = this.object_list.getObjects();
    results = [];
    for (j = 0, len1 = ref.length; j < len1; j++) {
      object = ref[j];
      results.push(object.clearValidationErrors());
    }
    return results;
  };

  Editor.prototype.__processSeverValidationProblems = function(validation_errors_for_objects) {
    var error, ex, idx, idxOffset, j, l, len1, len2, object, ref, validation_errors_list;
    try {
      idxOffset = ((ref = this.object_list) != null ? ref.getObject(0) : void 0) instanceof TemplateObject ? 1 : 0;
      for (idx = j = 0, len1 = validation_errors_for_objects.length; j < len1; idx = ++j) {
        validation_errors_list = validation_errors_for_objects[idx];
        object = this.object_list.getObject(idx + idxOffset);
        if (!object || !validation_errors_list || validation_errors_list.length === 0) {
          continue;
        }
        for (l = 0, len2 = validation_errors_list.length; l < len2; l++) {
          error = validation_errors_list[l];
          object.addServerValidationError(error);
        }
      }
    } catch (error1) {
      ex = error1;
      console.error("Error while processing server validation problems", ex);
    }
    return this.updateSaveButton();
  };

  Editor.prototype.askForComment = function(ev, type, ask, allow_empty) {
    var dfr, modal, save_button, update_save_button;
    if (ask == null) {
      ask = true;
    }
    if (allow_empty == null) {
      allow_empty = false;
    }
    dfr = new CUI.Deferred();
    if (!(ev != null ? ev.ctrlKey() : void 0) && !ask) {
      dfr.resolve(ev);
      return dfr.promise();
    }
    save_button = new CUI.Button({
      text: $$("base." + type),
      primary: true,
      onClick: (function(_this) {
        return function(ev) {
          modal.destroy();
          return dfr.resolve(ev);
        };
      })(this)
    });
    update_save_button = (function(_this) {
      return function() {
        if (_this.editor_data.comment.trim().length || allow_empty) {
          return save_button.enable();
        } else {
          return save_button.disable();
        }
      };
    })(this);
    modal = new CUI.Modal({
      "class": "ez5-editor-comment-modal",
      cancel: true,
      onCancel: function() {
        dfr.reject();
      },
      pane: {
        padded: true,
        header_left: new CUI.Label({
          text: $$("main.editor.comment." + type + ".title")
        }),
        content: (function(_this) {
          return function() {
            return [
              new CUI.MultilineLabel({
                text: $$("main.editor.comment." + type + ".hint")
              }), CUI.dom.space(), new CUI.Input({
                textarea: true,
                onDataChanged: update_save_button,
                name: "comment",
                maximize_horizontal: true,
                data: _this.editor_data
              }).start()
            ];
          };
        })(this),
        footer_right: (function(_this) {
          return function() {
            return [
              {
                text: $$("base.cancel"),
                onClick: function() {
                  modal.destroy();
                  return dfr.reject();
                }
              }, save_button
            ];
          };
        })(this)
      }
    });
    modal.show();
    update_save_button();
    return dfr.promise();
  };

  Editor.prototype.onChange = function(ev, data, info) {
    switch (ev.getType()) {
      case "pool-field-changed":
        this.poolChange(info);
        CUI.scheduleCallback({
          call: this.__updateObject,
          ms: 500
        });
        break;
      case "tags-field-changed":
        this.tagsChange(info).done((function(_this) {
          return function(resolve_info) {
            _this.triggerCallback("editor-tags-field-changed", resolve_info);
            return _this.__updateObject();
          };
        })(this));
        break;
      case "editor-changed":
      case "editor-reload-asset-browser":
      case "editor-update-asset-browser":
        CUI.scheduleCallback({
          call: this.__updateObject,
          ms: 500
        });
        switch (ev.getType()) {
          case "editor-reload-asset-browser":
            this.renderAssetBrowser();
            break;
          case "editor-update-asset-browser":
            this.updateAssetBrowser();
        }
    }
  };

  Editor.prototype.tagsChange = function(info) {
    return this.__checkDbInfoAndSwitchMask({
      loca_key_attrs: {
        current_pool: this.getPoolNameLocalized(info.old_pool),
        new_pool: this.getPoolNameLocalized()
      },
      confirm: info.editor_has_changes !== false,
      old_tags: info.old_tags,
      new_tags: info.new_tags,
      type: "tags"
    }).fail((function(_this) {
      return function() {
        console.debug("copying back old tags", CUI.util.dump(info.old_tags));
        _this.object.getData()._tags = info.old_tags;
        return _this.reloadEditor();
      };
    })(this));
  };

  Editor.prototype.poolChange = function(info) {
    var ref;
    if (!this.editor_data.table.poolLink()) {
      return;
    }
    if (!this.__old_pool) {
      this.__old_pool = info.old_pool;
    }
    this.editor_data._pool = info.new_pool;
    if (info.new_pool && ((ref = this.__old_pool) != null ? ref.pool._id : void 0) === info.new_pool.pool._id) {
      this.__old_pool = null;
      return;
    }
    if (!this.editor_data._pool) {
      return;
    }
    return this.__checkDbInfoAndSwitchMask({
      loca_key_attrs: {
        current_pool: this.getPoolNameLocalized(info.old_pool),
        new_pool: this.getPoolNameLocalized()
      },
      confirm: info.editor_has_changes !== false,
      type: "pool"
    }).done((function(_this) {
      return function() {
        return _this.__old_pool = null;
      };
    })(this)).fail((function(_this) {
      return function() {
        _this.editor_data._pool = _this.__old_pool;
        return _this.reloadEditor();
      };
    })(this));
  };

  Editor.prototype.__checkDbInfoAndSwitchMask = function(_opts) {
    var dfr, oldDbInfo, opts;
    opts = CUI.Element.readOpts(_opts, "Editor.__checkDbInfoAndSwitchMask", {
      loca_key_attrs: {
        mandatory: true,
        check: "PlainObject"
      },
      confirm: {
        mandatory: true,
        check: Boolean
      },
      type: {
        mandatory: true,
        check: ["tags", "pool"]
      },
      old_tags: {
        check: Array
      },
      new_tags: {
        check: Array
      }
    });
    dfr = new CUI.Deferred();
    oldDbInfo = this.editor_data.dbInfo;
    dfr.done((function(_this) {
      return function() {
        return _this.updateSaveButton();
      };
    })(this));
    dfr.fail((function(_this) {
      return function() {
        return _this.editor_data.dbInfo = oldDbInfo;
      };
    })(this));
    this.getDbInfo(false, false).done((function(_this) {
      return function(dbInfo) {
        var availableTagIdsAfter, availableTagIdsBefore, comment, confirm_mask_change, confirm_text, ex, fake_data, hasDifferentFields, load_new_mask, loca_key_attrs, masksAfter, masksBefore, new_fields, old_fields, ref, render_mode, render_mode_header, resolve_info, use_mask_name;
        _this.editor_data.dbInfo = dbInfo;
        try {
          if (_this.modeIsNot(["new"]) && !dbInfo.getGeneratedRights().write) {
            if (dbInfo.getGeneratedRights().unlink) {
              return dfr.resolve();
            }
            if (opts.type !== "tags") {
              _this.throwNoRightsError();
            }
            return dfr.resolve();
          }
          masksBefore = oldDbInfo.availableMasks();
          masksAfter = dbInfo.availableMasks();
          availableTagIdsBefore = JSON.stringify(oldDbInfo.availableTagIds());
          availableTagIdsAfter = JSON.stringify(dbInfo.availableTagIds());
          if (masksAfter.length === 0) {
            throw new UserError({
              label: "editor.load.rightsmanagement.error.no_masks"
            });
          }
          resolve_info = {
            old_tags: opts.old_tags,
            new_tags: opts.new_tags,
            available_tag_ids_before: oldDbInfo.availableTagIds(),
            available_tag_ids_after: dbInfo.availableTagIds()
          };
        } catch (error1) {
          ex = error1;
          if (ex instanceof UserError) {
            ex.presentError().done(function() {
              return dfr.reject();
            });
            return;
          }
          throw ex;
        }
        if (dbInfo.maskNameAvailable(_this.editor_data.mask_name)) {
          if (availableTagIdsBefore !== availableTagIdsAfter) {
            CUI.confirm({
              text: $$("editor.confirm_mask_change.tags_differ_warning")
            }).done(function() {
              var availableIdTags;
              availableIdTags = JSON.parse(availableTagIdsAfter);
              _this.object.getData()._tags = _this.object.getData()._tags.filter(function(tag) {
                var ref;
                return ref = tag._id, indexOf.call(availableIdTags, ref) >= 0;
              });
              return _this.reloadEditor().done(function() {
                return dfr.resolve(resolve_info);
              }).fail(dfr.reject);
            }).fail(dfr.reject);
          } else if (opts.old_tags && opts.new_tags) {
            ref = _this.getRenderModes(_this.object), render_mode_header = ref[0], render_mode = ref[1];
            if (_this.getTemplateIdx() !== null && !_this.isTemplate()) {
              fake_data = {
                _template: {
                  _tags: _this.object_list.getObject(_this.getTemplateIdx()).getData()._tags
                }
              };
              if (_this.modeIs(["new"])) {
                fake_data._owner = ez5.session.getUser().getData();
              } else {
                fake_data._owner = _this.object_list.getObject(_this.getTemplateIdx()).getData()._owner;
              }
            } else {
              fake_data = {};
            }
            fake_data._objecttype = _this.object.objecttype();
            old_fields = [];
            new_fields = [];
            _this.object.mask.invokeOnFields(render_mode, true, function(f) {
              fake_data._tags = opts.old_tags;
              if (f.isVisible(render_mode, {
                top_level_data: fake_data
              })) {
                old_fields.push(f);
              }
              fake_data._tags = opts.new_tags;
              if (f.isVisible(render_mode, {
                top_level_data: fake_data
              })) {
                return new_fields.push(f);
              }
            });
            hasDifferentFields = function() {
              var _field, j, len1;
              if (old_fields.length !== new_fields.length) {
                return true;
              }
              for (j = 0, len1 = new_fields.length; j < len1; j++) {
                _field = new_fields[j];
                if (indexOf.call(old_fields, _field) < 0) {
                  return true;
                }
              }
              return false;
            };
            if (hasDifferentFields()) {
              CUI.confirm({
                text: $$("editor.confirm_mask_change.fields_differ_warning")
              }).done(function() {
                return _this.reloadEditor().done(function() {
                  return dfr.resolve(resolve_info);
                }).fail(dfr.reject);
              }).fail(dfr.reject);
            } else {
              dfr.resolve(resolve_info);
            }
          } else {
            dfr.resolve(resolve_info);
          }
          return;
        }
        confirm_mask_change = opts.confirm;
        load_new_mask = function() {
          return _this.loadNewMask({
            loca_key: "editor.confirm_mask_change." + opts.type,
            new_mask_name: use_mask_name,
            confirm: confirm_mask_change
          }).done(dfr.resolve).fail(dfr.reject);
        };
        use_mask_name = masksAfter[0].name();
        if (_this.modeIsNot(["bulk", "new"])) {
          loca_key_attrs = CUI.util.copyObject(opts.loca_key_attrs);
          loca_key_attrs.current_mask = _this.getMaskNameLocalized();
          loca_key_attrs.new_mask = _this.getMaskNameLocalized(use_mask_name);
          confirm_text = $$("editor.confirm_mask_change." + opts.type + ".save", loca_key_attrs);
          comment = $$("editor.confirm_mask_change." + opts.type + ".save.comment", loca_key_attrs);
          return CUI.confirm({
            text: confirm_text
          }).done(function(choice, btn, ev) {
            return _this.savePoolAndTagsOnly(ev, comment).done(function() {
              confirm_mask_change = false;
              return load_new_mask();
            }).fail(dfr.reject);
          }).fail(dfr.reject);
        } else {
          return load_new_mask();
        }
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  Editor.prototype.savePoolAndTagsOnly = function(ev, comment) {
    var send_data;
    CUI.util.assert(this.modeIsNot(["new", "bulk"]), "Editor.savePoolAndTagsOnly", "Mode cannot be 'new' or 'bulk'.");
    send_data = {
      _objecttype: this.object.objecttype(),
      _comment: comment
    };
    send_data[send_data._objecttype] = {
      _id: this.object.id(),
      _version: this.object.version() + 1
    };
    if (this.editor_data.table.poolLink()) {
      CUI.util.assert(this.editor_data._pool, "Editor.savePoolAndTagsOnly", "editor_data._pool needs to be set.");
      send_data[send_data._objecttype]._pool = {
        pool: {
          _id: this.editor_data._pool.pool._id
        }
      };
    }
    send_data._mask = this.editor_data.mask_name;
    if (ez5.version("6")) {
      send_data[send_data._objecttype]._id = [this.object.id()];
    }
    if (this.editor_data.table.hasTags() && this.object) {
      send_data._tags = this.object.getData()._tags;
    }
    if (ev.hasModifierKey()) {
      console.debug(CUI.util.dump(send_data));
      return CUI.rejectedPromise();
    }
    return ez5.api.db({
      api: "/" + send_data._objecttype,
      data: {
        base_fields_only: 1
      },
      json_data: [send_data]
    });
  };

  Editor.prototype.reloadEditor = function(init_save_data) {
    if (init_save_data == null) {
      init_save_data = false;
    }
    if (init_save_data) {
      this.object.initSaveData({
        bulk: this.modeIs(["bulk"]),
        new_mode: this.modeIs(["new"]),
        editor: this
      });
    }
    this.cleanPollListeners();
    this.object_list.updateObjectInBrowser();
    return this.renderObject().done((function(_this) {
      return function() {
        _this.updateButtons();
        return _this.__updateNavigationPreviousNext();
      };
    })(this));
  };

  Editor.prototype["delete"] = function(ev) {
    var deleted_ids_per_ot, idx, j, obj, ot_names, ref, ref1, ref2, send_data, send_data_per_ot, soid, soid_to_ot_id, start, tn;
    if (this.hasTemplate()) {
      start = 1;
    } else {
      start = 0;
    }
    send_data_per_ot = {};
    ot_names = [];
    soid_to_ot_id = {};
    for (idx = j = ref = start, ref1 = this.object_list.getCount(); ref <= ref1 ? j < ref1 : j > ref1; idx = ref <= ref1 ? ++j : --j) {
      obj = this.object_list.getObject(idx);
      if (!obj.id()) {
        continue;
      }
      tn = obj.objecttype();
      send_data = send_data_per_ot[tn];
      if (!send_data) {
        send_data = send_data_per_ot[tn] = [];
        ot_names.push(tn);
      }
      send_data.push([obj.id(), obj.version(), (ref2 = this.editor_data.comment) != null ? ref2.trim() : void 0]);
      soid = obj.getSystemObjectId();
      if (soid) {
        soid_to_ot_id[soid] = {
          ot: tn,
          id: obj.id()
        };
      }
    }
    if (ev.ctrlKey() || ev.shiftKey() || ev.altKey()) {
      console.debug("DELETE", CUI.util.dump(send_data_per_ot));
      return CUI.rejectedPromise();
    }
    deleted_ids_per_ot = {};
    return CUI.chunkWork.call(this, {
      items: ot_names,
      chunk_size: 1,
      call: (function(_this) {
        return function(items) {
          var item, ot_name;
          ot_name = items[0];
          send_data = send_data_per_ot[ot_name];
          if (deleted_ids_per_ot[ot_name]) {
            send_data = (function() {
              var l, len1, results;
              results = [];
              for (l = 0, len1 = send_data.length; l < len1; l++) {
                item = send_data[l];
                if (!deleted_ids_per_ot[ot_name][item[0]]) {
                  results.push(item);
                }
              }
              return results;
            })();
          }
          if (send_data.length === 0) {
            return CUI.resolvedPromise();
          }
          return ez5.api.db({
            type: "DELETE",
            api: '/' + ot_name,
            json_data: send_data
          }).done(function(response_data) {
            var info, l, len1, removed;
            removed = response_data != null ? response_data.removed : void 0;
            if (!CUI.util.isArray(removed)) {
              return;
            }
            for (l = 0, len1 = removed.length; l < len1; l++) {
              soid = removed[l];
              info = soid_to_ot_id[soid];
              if (!info || info.ot === ot_name) {
                continue;
              }
              if (!deleted_ids_per_ot[info.ot]) {
                deleted_ids_per_ot[info.ot] = {};
              }
              deleted_ids_per_ot[info.ot][info.id] = true;
            }
          });
        };
      })(this)
    }).done((function(_this) {
      return function() {
        return _this.callback("delete");
      };
    })(this));
  };

  Editor.prototype.undelete = function(ev) {
    var idx, j, obj, ot_names, ref, ref1, ref2, send_data, send_data_per_ot, start, tn;
    if (this.hasTemplate()) {
      start = 1;
    } else {
      start = 0;
    }
    send_data_per_ot = {};
    ot_names = [];
    for (idx = j = ref = start, ref1 = this.object_list.getCount(); ref <= ref1 ? j < ref1 : j > ref1; idx = ref <= ref1 ? ++j : --j) {
      obj = this.object_list.getObject(idx);
      if (!obj.id()) {
        continue;
      }
      tn = obj.objecttype();
      send_data = send_data_per_ot[tn];
      if (!send_data) {
        send_data = send_data_per_ot[tn] = [];
        ot_names.push(tn);
      }
      send_data.push([obj.id(), obj.version(), (ref2 = this.editor_data.comment) != null ? ref2.trim() : void 0]);
    }
    if (ev.ctrlKey() || ev.shiftKey() || ev.altKey()) {
      console.debug("UNDELETE", CUI.util.dump(send_data_per_ot));
      return CUI.rejectedPromise();
    }
    return CUI.chunkWork.call(this, {
      items: ot_names,
      chunk_size: 1,
      call: (function(_this) {
        return function(items) {
          var ot_name;
          ot_name = items[0];
          send_data = send_data_per_ot[ot_name];
          return ez5.api.db({
            type: "DELETE",
            api: '/' + ot_name + '?delete_policy=undelete',
            json_data: send_data
          });
        };
      })(this)
    }).done((function(_this) {
      return function() {
        return _this.callback("undelete");
      };
    })(this));
  };

  Editor.prototype.showWaitModal = function(status, attrs, footer_right, show_spinner) {
    var c, labelOpts, pre;
    if (show_spinner == null) {
      show_spinner = false;
    }
    if (status.indexOf(".") === -1) {
      pre = this.getWaitModalTitleLocaKeyPrefix();
    } else {
      pre = "";
    }
    labelOpts = {
      loca_key: pre + status,
      loca_key_attrs: attrs,
      attr: {
        role: "status"
      }
    };
    if (show_spinner) {
      labelOpts.icon = "spinner";
    }
    c = new LocaLabel(labelOpts);
    if (!this.waitModal) {
      this.waitModal = new CUI.Modal({
        ui: "editor.saving_dialog",
        "class": "ez5-editor-wait-for-saving-dialog cui-progress-info-dialog",
        pane: {
          padded: true,
          header_left: new LocaLabel({
            loca_key: pre + "title",
            loca_key_attrs: attrs
          }),
          footer_right: footer_right,
          content: c
        }
      });
      this.waitModal.show();
    } else {
      this.waitModal.replace(c, "content");
    }
    return this.waitModal;
  };

  Editor.prototype.getWaitModalTitleLocaKeyPrefix = function() {
    return "main.editor.save.";
  };

  Editor.prototype.dismissWaitModalTimeout = function(received_data) {
    if (received_data == null) {
      received_data = [];
    }
    this.__dismissWaitModalInProgress = true;
    CUI.setTimeout({
      ms: 1500,
      call: (function(_this) {
        return function() {
          _this.__dismissWaitModalInProgress = false;
          return _this.dismissWaitModal();
        };
      })(this)
    });
    return this;
  };

  Editor.prototype.dismissWaitModal = function() {
    if (this.waitModal && !this.__dismissWaitModalInProgress) {
      this.waitModal.destroy();
      this.waitModal = null;
    }
    return this;
  };

  Editor.prototype.getSaveDataBulkMode = function(opts) {
    var bf, k, ref, tmpl, v;
    bf = this.getBulkFields();
    tmpl = this.object_list.getObject(0);
    CUI.util.assert(tmpl instanceof TemplateObject, (CUI.util.getObjectClass(this)) + ".save", "TemplateObject not found", {
      object_list: this.object_list
    });
    CUI.util.assert(bf.length, "Editor.save", "no bulk fields to save");
    ref = {
      bulk: true,
      render_mode_header: 'editor-header-bulk',
      render_mode: 'editor-bulk',
      editor: this
    };
    for (k in ref) {
      v = ref[k];
      opts[k] = v;
    }
    return tmpl.getSaveData(opts);
  };

  Editor.prototype.save = function(ev) {
    var acl, api_progress_poll, autoAddedComment, chunk_size, comment, create_object, create_objects, data, data2, data_json, dfr, ex, fn, found, ids, idx, j, l, len1, len2, len3, m, n, o, obj, opts, pa, processNext, produce_assets, progress_uuid, q, queue, r, ref, ref1, ref2, ref3, ref4, ref5, reloadEditor, reqs, save_url_appendix, send_data, send_data_object, send_data_objects, send_data_objects_dfr, so;
    this.__saveInProgress = true;
    dfr = new CUI.Deferred();
    dfr.done((function(_this) {
      return function(received_data) {
        _this.showWaitModal("saved");
        return _this.dismissWaitModalTimeout(received_data);
      };
    })(this));
    dfr.fail((function(_this) {
      return function() {
        _this.dismissWaitModal();
        if (reloadEditor) {
          return _this.reloadEditor();
        }
      };
    })(this));
    this.showWaitModal("preparing");
    send_data = [];
    create_objects = [];
    produce_assets = [];
    save_url_appendix = "";
    try {
      if (this.modeIsNot(["bulk"])) {
        for (idx = j = 0, ref = this.object_list.getCount(); 0 <= ref ? j < ref : j > ref; idx = 0 <= ref ? ++j : --j) {
          if (idx === this.getTemplateIdx()) {
            continue;
          }
          acl = [];
          obj = this.object_list.getObject(idx);
          obj.setMask(this.editor_data.mask_name);
          so = obj.getSaveData({
            "new": this.modeIs(["new"]),
            editor: this,
            render_mode_header: 'editor-header',
            render_mode: 'editor',
            create_objects: create_objects,
            produce_assets: produce_assets,
            for_server: true
          });
          so._idx_in_objects = idx;
          so._comment = (ref1 = this.editor_data.comment) != null ? ref1.trim() : void 0;
          send_data.push(so);
        }
      } else {
        opts = {
          create_objects: create_objects,
          for_server: true
        };
        data = this.getSaveDataBulkMode(opts);
        autoAddedComment = $$("main.editor.bulk.comment.auto_added_comment");
        comment = (ref2 = this.editor_data.comment) != null ? ref2.trim() : void 0;
        if (comment) {
          data._comment = comment + ("\n\n" + autoAddedComment);
        } else {
          data._comment = autoAddedComment;
        }
        if (opts.base_fields_only) {
          save_url_appendix = save_url_appendix + "&base_fields_only=1";
        }
        ids = [];
        for (idx = l = 1, ref3 = this.object_list.getCount(); 1 <= ref3 ? l < ref3 : l > ref3; idx = 1 <= ref3 ? ++l : --l) {
          o = this.object_list.getObject(idx);
          ids.push(o.id());
        }
        obj = data[data._objecttype];
        obj._id = [];
        chunk_size = this.getChunkSize() || ids.length;
        for (idx = m = 0, ref4 = ids.length, ref5 = chunk_size; ref5 > 0 ? m < ref4 : m > ref4; idx = m += ref5) {
          data2 = CUI.util.copyObject(data, false);
          data2[data._objecttype] = CUI.util.copyObject(data[data._objecttype], false);
          data2[data._objecttype]._id = ids.slice(idx, idx + chunk_size);
          send_data.push(data2);
        }
      }
    } catch (error1) {
      ex = error1;
      if (ex instanceof UserError) {
        ex.presentError({
          title: $$("main.editor.save.error.title")
        }).done((function(_this) {
          return function() {
            return dfr.reject();
          };
        })(this));
        return dfr.promise();
      }
      throw ex;
    }
    send_data_objects = [];
    for (n = 0, len1 = create_objects.length; n < len1; n++) {
      create_object = create_objects[n];
      data_json = JSON.stringify(create_object._save_data);
      found = null;
      for (q = 0, len2 = send_data_objects.length; q < len2; q++) {
        send_data_object = send_data_objects[q];
        if (send_data_object.data_json === data_json) {
          found = send_data_object;
        }
      }
      if (!found) {
        found = {
          objects: [],
          data_json: data_json
        };
        send_data_objects.push(found);
      }
      found.objects.push(create_object);
    }
    progress_uuid = ez5.generateUUID();
    save_url_appendix = save_url_appendix + "&progress_uuid=" + progress_uuid;
    if (ev && (ev.ctrlKey() || ev.altKey() || ev.shiftKey())) {
      console.debug("save data ****************");
      console.debug("object list: ------------", this.object_list);
      console.debug("url appendix: ------------", save_url_appendix);
      console.debug("send data objects: -----------", CUI.util.dump(send_data_objects), send_data_objects);
      console.debug("produce assets: -----------", CUI.util.dump(produce_assets), produce_assets);
      console.debug("send data: --------------", CUI.util.dump(send_data), send_data);
      return dfr.reject().promise();
    }
    api_progress_poll = EventPoller.listen({
      instance: this,
      filter: (function(_this) {
        return function(event) {
          return event.type === "API_PROGRESS" && event.info.uuid === progress_uuid;
        };
      })(this),
      call: (function(_this) {
        return function(events) {
          var latest_info;
          latest_info = events[events.length - 1].info;
          if (!_this.waitModal) {
            return;
          }
          return _this.showWaitModal(latest_info.progress_info, latest_info.progress_info_parameters);
        };
      })(this)
    });
    this.showWaitModal("sending");
    reloadEditor = false;
    reqs = [];
    send_data_objects_dfr = new CUI.Deferred();
    reqs.push(send_data_objects_dfr.promise());
    queue = send_data_objects.slice();
    processNext = function() {
      var dataObject, sendData;
      if (queue.length === 0) {
        send_data_objects_dfr.resolve();
        return;
      }
      dataObject = queue.shift();
      sendData = JSON.parse(dataObject.data_json);
      delete sendData.__in_memory;
      delete sendData._orig_mask;
      sendData[sendData._objecttype]._version = 1;
      return ez5.api.db({
        api: "/" + sendData._objecttype + "?format=standard",
        json_data: [sendData]
      }).done(function(response) {
        var createObject, d, field_name, key, len3, len4, len5, parent_ot, r, ref6, ref7, s, sdata, t, value;
        obj = response[0];
        ref6 = dataObject.objects;
        for (r = 0, len3 = ref6.length; r < len3; r++) {
          createObject = ref6[r];
          createObject._save_data[obj._objecttype]._id = obj[obj._objecttype]._id;
          if (createObject._parent_create_object) {
            parent_ot = createObject._parent_create_object._save_data["_objecttype"];
            field_name = createObject._parent_create_object._field_name;
            for (s = 0, len4 = queue.length; s < len4; s++) {
              sdata = queue[s];
              ref7 = sdata.objects;
              for (t = 0, len5 = ref7.length; t < len5; t++) {
                o = ref7[t];
                if (o === createObject._parent_create_object) {
                  d = JSON.parse(sdata.data_json);
                  d[parent_ot][field_name][obj._objecttype]._id = obj[obj._objecttype]._id;
                  sdata.data_json = JSON.stringify(d);
                }
              }
            }
            createObject._parent_create_object._save_data[parent_ot][field_name][obj._objecttype]._id = obj[obj._objecttype]._id;
            for (key in obj) {
              value = obj[key];
              createObject._parent_create_object._data_ref[parent_ot][field_name][key] = value;
            }
          }
          for (key in obj) {
            value = obj[key];
            createObject._data_ref[key] = value;
          }
        }
        reloadEditor = true;
        return processNext();
      }).fail(send_data_objects_dfr.reject);
    };
    processNext();
    fn = (function(_this) {
      return function(pa) {
        var _dfr, command;
        command = {
          eas_parent_id: pa.eas_parent_id,
          transform: pa.__transform
        };
        _dfr = EAS.postToProduce(command).done(function(new_value) {
          delete pa.__transform;
          return pa._id = new_value._id;
        });
        return reqs.push(_dfr);
      };
    })(this);
    for (r = 0, len3 = produce_assets.length; r < len3; r++) {
      pa = produce_assets[r];
      fn(pa);
    }
    CUI.when(reqs).done((function(_this) {
      return function() {
        return _this.sendData(send_data, save_url_appendix).always(function() {
          if (api_progress_poll) {
            return CUI.Events.ignore(api_progress_poll);
          }
        }).done(dfr.resolve).fail(dfr.reject);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  Editor.prototype.getApiDbPriority = function() {
    return 1;
  };

  Editor.prototype.getSendDataUrl = function() {
    var format;
    if (this._format) {
      format = this._format;
    } else if (this.modeIs(["new"])) {
      format = "long";
    } else {
      format = "short";
    }
    return "/" + this.editor_data.table.name() + "?priority=" + this.getApiDbPriority() + "&format=" + format;
  };

  Editor.prototype.sendData = function(send_data, save_url_appendix) {
    var chunk_size, dfr, objectsCount, received_data, ref, successful_chunks;
    if (save_url_appendix == null) {
      save_url_appendix = "";
    }
    dfr = new CUI.Deferred();
    successful_chunks = 0;
    if (this.modeIs(["bulk"])) {
      chunk_size = 1;
    } else {
      chunk_size = send_data.length;
    }
    received_data = [];
    objectsCount = (ref = this.object_list) != null ? ref.getCount() : void 0;
    if (this.hasTemplate()) {
      objectsCount--;
    }
    CUI.chunkWork.call(this, {
      items: send_data,
      timeout: 0,
      chunk_size: chunk_size,
      call: function(items, offset, len) {
        var fromP, toP;
        if (this.modeIs(["bulk"])) {
          fromP = offset * this.getChunkSize();
          toP = fromP + items.length * this.getChunkSize();
          if (toP > objectsCount) {
            toP = objectsCount;
          }
          this.showWaitModal("sending", {
            from: fromP + 1,
            to: toP,
            count: objectsCount
          });
        } else {
          this.showWaitModal("sending", {
            from: offset + 1,
            to: offset + items.length,
            count: len
          });
        }
        return ez5.api.db({
          api: this.getSendDataUrl() + save_url_appendix,
          json_data: items,
          error: function(xhr) {}
        }).done((function(_this) {
          return function(data) {
            var idx, j, len1, obj, resultObject, template_offset;
            if (_this.modeIsNot(["bulk"])) {
              if (_this.hasTemplate()) {
                template_offset = 1;
              } else {
                template_offset = 0;
              }
              for (idx = j = 0, len1 = data.length; j < len1; idx = ++j) {
                obj = data[idx];
                resultObject = _this.object_list.getObject(idx + template_offset + offset);
                resultObject.setData(obj);
              }
            }
            if (_this.hasTemplate()) {
              _this.object_list.getObjects().splice(1, items.length);
              successful_chunks++;
            }
            return received_data.push.apply(received_data, data);
          };
        })(this));
      }
    }).done((function(_this) {
      return function() {
        _this.initHasChanges();
        delete _this.editor_data.comment;
        return dfr.resolve(received_data);
      };
    })(this)).progress((function(_this) {
      return function(state, task_idx, len) {
        switch (state) {
          case "start":
            _this.dismissWaitModal();
            break;
          case "done":
            _this.showWaitModal("sending");
        }
      };
    })(this)).fail((function(_this) {
      return function(xhr) {
        var pending, success;
        if (_this.hasTemplate()) {
          pending = _this.object_list.getCountWithoutTemplate();
          success = successful_chunks * chunk_size;
          _this.object_list.updateBrowserWithNavigation(0);
          CUI.problem({
            text: $$("editor.send_data.failed_chunks", {
              success: success,
              pending: pending
            })
          });
        }
        _this.saveInProgress = false;
        if (xhr === "cancelled") {
          dfr.reject();
          return;
        }
        return ez5.error_handler(xhr).done(function() {
          return dfr.reject(xhr);
        });
      };
    })(this));
    return dfr.promise();
  };

  Editor.prototype.addNewTemplateObject = function(data) {
    var ref, ro;
    if (data == null) {
      data = {};
    }
    CUI.util.assert(((ref = this.editor_data) != null ? ref.table : void 0) instanceof Table, (CUI.util.getObjectClass(this)) + ".addNewTemplateObject", "@editor_data.table must be set");
    CUI.util.assert(this.object_list.getCount() === 0, (CUI.util.getObjectClass(this)) + ".addNewTemplateObject", "Unable to add TemplateObject to non-empty object_list", {
      object_list: this.object_list
    });
    ro = this.addNewResultObject(data, new TemplateObject());
    if (this.editor_data.table.poolLink()) {
      this.setPoolInObject(ro);
    }
    this.template_idx = 0;
    return ro;
  };

  Editor.prototype.addNewResultObject = function(data, ro) {
    var ref;
    if (data == null) {
      data = {};
    }
    if (ro == null) {
      ro = new ResultObject();
    }
    CUI.util.assert(((ref = this.editor_data) != null ? ref.table : void 0) instanceof Table, (CUI.util.getObjectClass(this)) + ".addNewResultObject", "@editor_data.table must be set");
    if (this.hasTemplate()) {
      data._template = this.object_list.getObject(this.getTemplateIdx()).data;
    }
    if (!data._mask) {
      data._mask = this.editor_data.mask_name;
    }
    ro.initData(this.editor_data.table.name(), data);
    this.object_list.push(ro);
    return ro;
  };

  Editor.prototype.supportsTemplate = function() {
    return false;
  };

  Editor.prototype.hasTemplate = function() {
    return !CUI.util.isNull(this.template_idx);
  };

  Editor.prototype.getTemplateIdx = function() {
    return this.template_idx;
  };

  Editor.prototype.hasActiveUploads = function() {
    if (!this.__pane) {
      return false;
    }
    return !!CUI.dom.findElement(this.__pane.DOM, ".ez5-file-upload-progress");
  };

  Editor.prototype.__abortUploads = function() {
    var el, j, len1, ref;
    if (!this.__pane) {
      return;
    }
    ref = CUI.dom.matchSelector(this.__pane.DOM, ".ez5-file-upload-progress");
    for (j = 0, len1 = ref.length; j < len1; j++) {
      el = ref[j];
      CUI.dom.data(el, "file-upload").abort();
    }
  };

  Editor.prototype.doCancel = function(ev) {
    return this.doClose(ev).done((function(_this) {
      return function(callback, received_data) {
        return _this.callback(callback, received_data);
      };
    })(this));
  };

  Editor.prototype.closeAllowed = function() {
    if (this.hasActiveUploads() || (this.__is_rendered && (this.saveAllowed() || this.hasChanges()))) {
      return false;
    } else {
      return true;
    }
  };

  Editor.prototype.doClose = function() {
    var dfr, ref, save_button;
    if (!this.closeAllowed()) {
      if (this.__cancelPromise) {
        return this.__cancelPromise;
      }
      this.updateSaveButton();
      dfr = new CUI.Deferred();
      if (((ref = this.saveButton) != null ? ref.isEnabled() : void 0) && this.modeIsNot(["bulk"])) {
        save_button = true;
      } else {
        save_button = false;
      }
      this.__getConfirmationChoice(save_button).open().done((function(_this) {
        return function(choice, btn, ev) {
          switch (choice._value) {
            case "cancel":
              return dfr.reject();
            case "discard":
              _this.__abortUploads();
              return dfr.resolve("cancel");
            case "save":
              return _this.doSave(ev).fail(function() {
                return dfr.reject();
              }).done(function(received_data, read_only) {
                if (read_only) {
                  return dfr.resolve("saveReadOnly", received_data);
                } else {
                  return dfr.resolve("save", received_data);
                }
              });
          }
        };
      })(this));
      this.__cancelPromise = dfr.promise();
      this.__cancelPromise.always((function(_this) {
        return function() {
          return _this.__cancelPromise = null;
        };
      })(this));
      return this.__cancelPromise;
    }
    return CUI.resolvedPromise("cancel");
  };

  Editor.prototype.__getConfirmationChoice = function(save_button) {
    if (save_button == null) {
      save_button = true;
    }
    return new CUI.ConfirmationChoice({
      ui: "editor.unsaved_changes.confirmation",
      text: $$("main.editor.unsaved_changes"),
      choices: [
        {
          _value: "discard",
          text: $$("editor.discard.changes"),
          secondary: true
        }, {
          _value: "cancel",
          primary: !save_button,
          secondary: save_button,
          text: $$("main.editor.unsaved_changes.cancel")
        }, save_button ? {
          _value: "save",
          primary: true,
          text: $$("base.save")
        } : void 0
      ]
    });
  };

  Editor.prototype.hasChanges = function() {
    var changed;
    if (!this.__is_rendered) {
      return false;
    }
    if (this.__waitBlock.isShown()) {
      return false;
    }
    changed = this.object.hasChangedSaveData();
    if (changed === -1) {
      return true;
    }
    return changed;
  };

  Editor.prototype.initHasChanges = function() {
    var j, len1, row, rows;
    if (!this.__pane) {
      return;
    }
    rows = CUI.dom.matchSelector(this.__pane.DOM, ".data-changed");
    for (j = 0, len1 = rows.length; j < len1; j++) {
      row = rows[j];
      CUI.dom.removeClass(row, "data-changed");
    }
    return this;
  };

  Editor.prototype.saveAllowed = function() {
    var has_changes;
    if (!this.__is_rendered) {
      return false;
    }
    if (this.modeIs(['bulk'])) {
      return this.getBulkFields().length > 0;
    }
    has_changes = this.hasChanges();
    if (has_changes === -1) {
      return false;
    }
    return has_changes || this.modeIs(['new']);
  };

  Editor.prototype.updateButtons = function() {
    var ac, assets, ref, ref1, ref2;
    if (!this.__pane) {
      return;
    }
    if (this.modeIs(["bulk"])) {
      this.__paneHeader.replace(new CUI.Label({
        ui: "editor.bulk.title",
        text: $$("main.editor.bulk")
      }), "left");
    } else {
      this.__paneHeader.replace(new CUI.Label({
        ui: "editor.title",
        text: $$("editor.title")
      }), "left");
    }
    if (this.historyBrowserButton) {
      if (this.object.id()) {
        this.historyBrowserButton.enable();
      } else {
        this.historyBrowserButton.disable();
      }
    }
    if (this.assetBrowserButton) {
      if (this.object instanceof TemplateObject) {
        assets = (ref = this.getObjectList().getObject(1)) != null ? ref.getAssetsForBrowser("editor") : void 0;
      } else {
        assets = this.object.getAssetsForBrowser("editor");
      }
      if ((assets != null ? assets.length : void 0) > 0 && this.__pullOutDiv) {
        this.assetBrowserButton.show();
        this.assetBrowserButton.enable();
        if (!this.__updateButtonsFirstDone) {
          if (ez5.session.getPref("show_asset_browser")) {
            if (this.assetBrowserButton.isActive()) {
              this.showPullOut();
            } else {
              this.assetBrowserButton.activate();
            }
          } else {
            if (!this.assetBrowserButton.isActive()) {
              this.hidePullOut();
            } else {
              this.assetBrowserButton.deactivate();
            }
          }
        }
      } else {
        this.assetBrowserButton.hide();
        this.assetBrowserButton.disable();
        this.hidePullOut();
      }
    }
    this.__updateButtonsFirstDone = true;
    ac = Mask.getMaskByMaskName(this.editor_data.mask_name, this.editor_data.table.id()).requireComment();
    if (this.modeIs(["bulk"]) && ac === "never") {
      ac = "default-disabled";
    }
    if (!this.__require_comment_type || this.__require_comment_type !== ac) {
      this.__require_comment_type = ac;
      switch (ac) {
        case "never":
          this.askForCommentCheckbox.hide();
          break;
        case "default-disabled":
          this.askForCommentCheckbox.setValue(false);
          this.askForCommentCheckbox.show();
          break;
        case "default-enabled":
          this.askForCommentCheckbox.setValue(true);
          this.askForCommentCheckbox.show();
          break;
        case "always":
          this.askForCommentCheckbox.setValue(true);
          this.askForCommentCheckbox.disable();
          this.askForCommentCheckbox.show();
          break;
        default:
          this.askForCommentCheckbox.hide();
      }
    }
    this.updateSaveButton();
    if (this.object.hasRight("delete") && (this.object.id() || (this.object instanceof TemplateObject && this.modeIs(["bulk"])))) {
      if ((ref1 = this.deleteButton) != null) {
        ref1.show();
      }
    } else {
      if ((ref2 = this.deleteButton) != null) {
        ref2.hide();
      }
    }
    return this;
  };

  Editor.prototype.updateSaveButton = function() {
    var anyServerProblem, cdp, data, div, e, el, enable, hasWarnings, idx, j, key, l, len1, len2, len3, len4, len5, len6, len7, len8, len9, m, n, nested_problem, obj, opts, p, path, popts, problem, problems, q, r, ref, ref1, ref10, ref11, ref12, ref13, ref14, ref15, ref16, ref17, ref18, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, s, t, top_level_data, u, validationOpts;
    if (!this.__pane) {
      return;
    }
    this.saveButton.disable();
    if ((ref = this.copyButton) != null) {
      ref.disable();
    }
    if ((ref1 = this.copyTool) != null) {
      ref1.disable();
    }
    if ((ref2 = this.__createNewChildTool) != null) {
      ref2.disable();
    }
    opts = {
      bulk: this.modeIs(['bulk']),
      "new": this.modeIs(['new']),
      editor: this
    };
    ref3 = ['ez5-check-failed-column', 'has-failed-content', 'ez5-check-failed-row'];
    for (j = 0, len1 = ref3.length; j < len1; j++) {
      key = ref3[j];
      ref4 = CUI.dom.matchSelector(this.__pane, '.' + key);
      for (l = 0, len2 = ref4.length; l < len2; l++) {
        el = ref4[l];
        el.classList.remove(key);
      }
    }
    this.__bulkNoSelectedFieldsLabel.hide();
    this.__requiredLabel.hide();
    this.__currentProblems = [];
    enable = true;
    if (opts.bulk) {
      anyServerProblem = false;
      this.__serverValidationLabelTemplate.hide();
    }
    ref5 = this.object_list.getObjects();
    for (idx = m = 0, len3 = ref5.length; m < len3; idx = ++m) {
      obj = ref5[idx];
      if (opts.bulk && this.getTemplateIdx() !== idx) {
        if (obj.hasUnhandledServerValidationError()) {
          div = this.object_list.findObjectInBrowser(idx);
          if (div) {
            if (!anyServerProblem && this.getTemplateIdx() === this.object_list.getCurrentIdx()) {
              anyServerProblem = true;
              this.__serverValidationLabelTemplate.show();
              this.__serverValidationLabel.hide();
            }
            CUI.dom.addClass(div, "ez5-check-failed");
          }
        }
        continue;
      }
      div = this.object_list.findObjectInBrowser(idx);
      CUI.dom.removeClass(div, "ez5-check-failed");
      ref6 = this.getRenderModes(obj), opts.render_mode_header = ref6[0], opts.render_mode = ref6[1];
      problems = obj.checkSaveData(opts);
      popts = {
        bulk: opts.bulk,
        "new": opts["new"],
        editor: opts.editor,
        resultObject: obj
      };
      ref7 = this.__plugins;
      for (n = 0, len4 = ref7.length; n < len4; n++) {
        p = ref7[n];
        ref8 = p.__checkForm(popts);
        for (q = 0, len5 = ref8.length; q < len5; q++) {
          cdp = ref8[q];
          problems.push(cdp);
        }
      }
      if (idx === this.object_list.getCurrentIdx()) {
        for (r = 0, len6 = problems.length; r < len6; r++) {
          p = problems[r];
          this.__currentProblems.push(p);
        }
      }
      if (problems.length === 0) {
        if (obj.hasUnhandledServerValidationError()) {
          CUI.dom.addClass(div, "ez5-check-failed");
        }
        continue;
      }
      for (s = 0, len7 = problems.length; s < len7; s++) {
        p = problems[s];
        p.setProblemClass('ez5-check-failed-column');
      }
      CUI.dom.addClass(div, "ez5-check-failed");
      if (!opts.bulk && this.getTemplateIdx() === idx) {
        continue;
      }
      enable = false;
    }
    if (!enable) {
      this.__requiredLabel.show();
    }
    if (((ref9 = this.__currentProblems) != null ? ref9.length : void 0) > 0) {
      this.__requiredDetailsBtn.show();
    } else {
      this.__requiredDetailsBtn.hide();
    }
    if (opts.bulk && this.getBulkFields().length === 0) {
      this.__requiredLabel.hide();
      this.__bulkNoSelectedFieldsLabel.show();
      enable = false;
    }
    if (enable && this.askForCommentCheckbox.isHidden() && this.modeIsNot(["bulk"]) && !this.getChunkSizeSelect()) {
      this.__toolbarBottom.hide();
    } else {
      this.__toolbarBottom.show();
    }
    if (enable && this.hasActiveUploads()) {
      enable = false;
    }
    if (!this.saveAllowed()) {
      enable = false;
    }
    if (enable) {
      hasWarnings = false;
      if (this.editor_data.dbInfo.availableMasks().length === 0) {
        this.__currentProblems.push(new CheckDataProblem({
          text: $$("editor.warning.no_masks_available")
        }));
        hasWarnings = true;
      }
      if (this.object.hasServerValidationError()) {
        try {
          this.object.updateServerValidationErrorsRenderedFields();
          ref10 = this.object.getServerValidationErrors();
          for (t = 0, len8 = ref10.length; t < len8; t++) {
            p = ref10[t];
            if (p.insideNestedPopup && p.field) {
              validationOpts = {
                rowIndex: p.row_index,
                field: p.field
              };
              data = this.object.getDataFromDataPath(p.dataPath);
              if (!p.field.checkServerValidationProblemHandled(data, top_level_data, p.message, validationOpts)) {
                ref11 = p.parsedFieldPath.path;
                for (u = 0, len9 = ref11.length; u < len9; u++) {
                  path = ref11[u];
                  if (path.nestedPopup && path.nestedRenderedField) {
                    nested_problem = new CheckDataProblem({
                      field: p.field,
                      text: p.message,
                      renderedField: path.nestedRenderedField,
                      rowIndex: path.index
                    });
                    nested_problem.setProblemClass('ez5-check-failed-column');
                    break;
                  }
                }
                problem = new CheckDataProblem({
                  field: p.field,
                  text: p.message,
                  rowIndex: p.rowIndex
                });
                data[p.field.name() + ":serverValidationProblem"] = {
                  problem: problem,
                  serverError: p
                };
                this.__currentProblems.push(problem);
                p.handled = false;
              } else {
                p.handled = true;
              }
              continue;
            }
            if (!p.field) {
              problem = new CheckDataProblem({
                text: p.message
              });
              this.__currentProblems.push(problem);
              continue;
            }
            data = this.object.getDataFromDataPath(p.dataPath);
            top_level_data = this.object.getData();
            validationOpts = {
              rowIndex: p.row_index,
              field: p.field
            };
            if (!p.field.checkServerValidationProblemHandled(data, top_level_data, p.message, validationOpts)) {
              problem = new CheckDataProblem({
                field: p.field,
                renderedField: p.renderedField,
                text: p.message,
                rowIndex: validationOpts.rowIndex
              });
              problem.setProblemClass('ez5-check-failed-column');
              this.__currentProblems.push(problem);
              p.handled = false;
            } else {
              p.handled = true;
            }
          }
        } catch (error1) {
          e = error1;
          console.error("Error while handling server validation problems", e);
        }
        hasWarnings = ((ref12 = this.__currentProblems) != null ? ref12.length : void 0) > 0;
      }
      if (hasWarnings) {
        if (this.object.hasUnhandledServerValidationError()) {
          CUI.dom.addClass(this.object_list.findObjectInBrowser(), "ez5-check-failed");
          this.__serverValidationLabel.show();
        } else {
          this.__warningLabel.show();
        }
        this.__requiredDetailsBtn.show();
        this.__toolbarBottom.show();
      } else {
        if (this.object.hasServerValidationError()) {
          CUI.dom.removeClass(this.object_list.findObjectInBrowser(), "ez5-check-failed");
        }
      }
    }
    if (enable) {
      this.saveButton.enable();
      if ((ref13 = this.copyButton) != null) {
        ref13.disable();
      }
      if ((ref14 = this.copyTool) != null) {
        ref14.disable();
      }
      if ((ref15 = this.__createNewChildTool) != null) {
        ref15.disable();
      }
    } else {
      this.__serverValidationLabel.hide();
      this.saveButton.disable();
      if ((ref16 = this.copyButton) != null) {
        ref16.enable();
      }
      if ((ref17 = this.copyTool) != null) {
        ref17.enable();
      }
      if ((ref18 = this.__createNewChildTool) != null) {
        ref18.enable();
      }
    }
    return this;
  };

  Editor.prototype.getBulkFields = function() {
    var fields, object;
    fields = [];
    object = this.object_list.getObject(this.getTemplateIdx());
    object.mask.invokeOnFields("all", false, (function(_this) {
      return function(f) {
        if (f.getOption(object.data[object.data._objecttype], "bulk")) {
          return fields.push(f);
        }
      };
    })(this));
    return fields;
  };

  Editor.prototype.getObjectList = function() {
    return this.object_list;
  };

  Editor.prototype.isTemplate = function() {
    return this.getTemplateIdx() === this.object_list.getCurrentIdx();
  };

  Editor.prototype.renderObject = function() {
    var dfr, pool_ids, ref, ref1, render_detail, render_mode, render_mode_header;
    this.updateToolbarRight();
    CUI.util.assert(this.editor_data.table instanceof Table, "Editor.renderObject", "table is not set");
    if (this.modeIsNot(["bulk"])) {
      CUI.util.assert(!this.editor_data.table.poolLink() || this.editor_data._pool, "Editor.renderObject", "pool is not set", {
        editor_data: this.editor_data
      });
    }
    this.__is_rendered = false;
    if (this.modeIs(["new"])) {
      CUI.util.assert(!this.object.id(), "Editor.renderObject", "id is set for 'new' editor.", {
        editor_data: this.editor_data,
        data: this.object.getData()
      });
    }
    CUI.util.assert(this.editor_data.mask_name, "Editor.renderObject", "editor_data.mask_name needs to be set.", {
      editor_data: this.editor_data,
      data: this.object.getData()
    });
    CUI.util.assert(this.object.objecttype(), "Editor.renderObject", "object.objecttype() is empty", {
      data: this.object.getData()
    });
    if (this.editor_data.table.poolLink()) {
      this.setPoolInObject(this.object);
    }
    this.object.setMask(this.editor_data.mask_name);
    dfr = new CUI.Deferred();
    if (!this.__pane) {
      return dfr.reject().promise();
    }
    this.object.setCSSClasses(this.__pane);
    dfr.always((function(_this) {
      return function() {
        var ref;
        _this.__waitBlock.hide();
        _this.__updateButtonsFirstDone = false;
        _this.__is_rendered = true;
        _this.initHasChanges();
        _this.updateButtons();
        if (((ref = _this.object.getAssetsForBrowser("editor")) != null ? ref.length : void 0) > 0) {
          return _this.renderAssetBrowser();
        } else {
          return _this.__removeAssetBrowser();
        }
      };
    })(this));
    if (this.modeIs(["bulk"]) && !this.isTemplate()) {
      this.getEditorWrapper().empty("center");
      render_detail = (function(_this) {
        return function() {
          _this.appendCardInfoContainer();
          return _this.getEditorWrapper().append(_this.object.renderDetail("detail", "detail-header", {
            onDone: function() {
              return dfr.resolve();
            },
            onFail: function() {
              return dfr.reject();
            }
          }), "center");
        };
      })(this);
      if ((ref = this.object.getFormat()) === "full" || ref === "long") {
        render_detail();
      } else {
        this.object.loadFromDbWithMask(this.editor_data.mask_name).done((function(_this) {
          return function() {
            _this.object.data._template = _this.object_list.getObject(_this.getTemplateIdx()).data;
            return render_detail();
          };
        })(this)).fail(dfr.reject);
      }
    } else {
      ref1 = this.getRenderModes(this.object), render_mode_header = ref1[0], render_mode = ref1[1];
      if (this.editor_data.table.poolLink()) {
        pool_ids = this.editor_data.dbInfo.getPoolIds();
        if (pool_ids === false) {
          pool_ids = [];
        }
      } else {
        pool_ids = null;
      }
      this.updateMaskSelect();
      this.getEditorWrapper().empty("center");
      if (!this.isTemplate()) {
        this.appendCardInfoContainer();
      }
      delete this.__rendered_mask_splitters;
      this.__editor_div = this.object.renderEditor(render_mode, render_mode_header, {
        onChange: (function(_this) {
          return function(ev, data, info) {
            return _this.onChange(ev, data, info);
          };
        })(this),
        editor: this,
        bulk: this.modeIs(["bulk"]),
        new_mode: this.modeIs(["new"]),
        pool_ids: pool_ids,
        maximize: false,
        onFieldRender: (function(_this) {
          return function(fieldRenderer, html) {
            return _this.__onFieldRendered(fieldRenderer, html);
          };
        })(this),
        onDone: (function(_this) {
          return function() {
            if (ez5.version("6")) {
              _this.__configureGoToTopBtn();
              if (_this.rememberMaskSplitterStates()) {
                _this.restoreMaskSplitterStates();
              }
              if (_this.rememberScrollPosition()) {
                _this.__scrollDiv.scrollTop = _this.__saved_scroll_position;
              }
            }
            return _this.triggerCallback("editor-render-object").fail(dfr.reject);
          };
        })(this),
        onFail: (function(_this) {
          return function() {
            return dfr.reject();
          };
        })(this)
      });
      this.getEditorWrapper().append(this.__editor_div, "center");
      dfr.resolve();
    }
    return dfr.promise();
  };

  Editor.prototype.__onFieldRendered = function(fieldRenderer, html) {
    if (this.rememberMaskSplitterStates() && fieldRenderer._field instanceof MaskSplitter) {
      if (!fieldRenderer.getState) {
        return;
      }
      if (this.__rendered_mask_splitters == null) {
        this.__rendered_mask_splitters = [];
      }
      return this.__rendered_mask_splitters.push({
        fieldRender: fieldRenderer,
        cls: fieldRenderer._field.getElementClass()
      });
    }
  };

  Editor.prototype.storeMaskSplitterStates = function() {
    var data, e, j, len1, ref;
    if (!ez5.version("6")) {
      return;
    }
    if (CUI.util.isEmpty(this.__rendered_mask_splitters)) {
      return;
    }
    this.__mask_splitter_states = [];
    try {
      ref = this.__rendered_mask_splitters;
      for (j = 0, len1 = ref.length; j < len1; j++) {
        data = ref[j];
        this.__mask_splitter_states.push({
          cls: data.fieldRender._field.getElementClass(),
          state: data.fieldRender.getState()
        });
      }
    } catch (error1) {
      e = error1;
      console.error("Error while storing mask splitter states", e);
    }
  };

  Editor.prototype.restoreMaskSplitterStates = function() {
    var data, e, i, j, len1, ref, ref1, results;
    try {
      if (!CUI.util.isEmpty(this.__mask_splitter_states) && !CUI.util.isEmpty(this.__rendered_mask_splitters)) {
        ref = this.__rendered_mask_splitters;
        results = [];
        for (i = j = 0, len1 = ref.length; j < len1; i = ++j) {
          data = ref[i];
          if (data.fieldRender._field.getElementClass() === ((ref1 = this.__mask_splitter_states[i]) != null ? ref1.cls : void 0)) {
            results.push(data.fieldRender.restoreState(this.__mask_splitter_states[i].state));
          } else {
            results.push(void 0);
          }
        }
        return results;
      }
    } catch (error1) {
      e = error1;
      return console.error("Error while restoring mask splitter states", e);
    }
  };

  Editor.prototype.appendCardInfoContainer = function() {
    var cardInfo, ref, resultCardPinButton;
    cardInfo = this.object.renderCardEditor({
      mode: "result-card-info-detail"
    });
    if (ez5.version("6") && ((ref = ez5.cssLoader.getActiveCSS()) != null ? ref.theme : void 0) === 'fylr') {
      resultCardPinButton = ResultObject.getResultCardPinButton(this.__mainPane, "resultCard.unpin", (function(_this) {
        return function() {
          return _this.__configureGoToTopBtn();
        };
      })(this));
      CUI.dom.append(cardInfo, resultCardPinButton);
    }
    this.__cardInfoContainer = CUI.dom.div();
    CUI.dom.append(this.__cardInfoContainer, cardInfo);
    return this.getEditorWrapper().append(this.__cardInfoContainer, "center");
  };

  Editor.prototype.getRenderModes = function(obj) {
    var header, mode;
    if (this.modeIs(["new"])) {
      if (obj instanceof TemplateObject) {
        header = "editor-header-template";
        mode = "editor-template";
      } else {
        header = "editor-header";
        mode = "editor";
      }
    } else if (this.modeIs(["bulk"])) {
      header = "editor-header-bulk";
      mode = "editor-bulk";
    } else {
      header = "editor-header";
      mode = "editor";
    }
    return [header, mode];
  };

  Editor.prototype.askForVersionChanged = function() {
    if (this.__askingForVersionChanged) {
      return;
    }
    return this.object.loadFromDb(null, null, "full").done((function(_this) {
      return function() {
        var comment, func, j, last_change, len1, mod, ref, ref1, replace;
        last_change = (ref = _this.object.data._changelog) != null ? ref.slice(-1)[0] : void 0;
        replace = {
          user: (last_change != null ? last_change.user.user._generated_displayname : void 0) || "unknown"
        };
        if (CUI.util.isEmpty(last_change != null ? last_change.comment : void 0)) {
          comment = new CUI.EmptyLabel({
            text: $$("main.editor.version_changed.no_comment")
          });
        } else {
          comment = new CUI.EmptyLabel({
            text: last_change.comment
          });
        }
        mod = new CUI.ConfirmationDialog({
          title: $$("main.editor.version_changed.title"),
          content: [
            new CUI.MultilineLabel({
              text: $$("main.editor.version_changed.explain", replace)
            }), comment
          ],
          buttons: [
            {
              text: $$("main.editor.version_changed.button.discard_changes"),
              primary: true,
              onClick: function(ev) {
                mod.destroy();
                _this.__askingForVersionChanged = false;
                return _this.object.loadFromDb(null, null, "full").done(function() {
                  return _this.reloadEditor(true);
                });
              }
            }
          ]
        });
        mod.show();
        _this.__askingForVersionChanged = true;
        ref1 = _this.__onAskForVersionChanged || [];
        for (j = 0, len1 = ref1.length; j < len1; j++) {
          func = ref1[j];
          func();
        }
        _this.__onAskForVersionChanged = [];
      };
    })(this));
  };

  Editor.prototype.onAskForVersionChanged = function(func) {
    if (this.__askingForVersionChanged) {
      func();
    }
    if (this.__onAskForVersionChanged == null) {
      this.__onAskForVersionChanged = [];
    }
    this.__onAskForVersionChanged.push(func);
  };

  Editor.prototype.askForVersionDeleted = function() {
    var mod;
    mod = new CUI.ConfirmationDialog({
      title: $$("main.editor.version_deleted.title"),
      content: new CUI.MultilineLabel({
        text: $$("main.editor.version_deleted.explain")
      }),
      buttons: [
        {
          text: $$("main.editor.version_deleted.button.close"),
          onClick: (function(_this) {
            return function(ev) {
              mod.destroy();
              return _this.callback("delete");
            };
          })(this)
        }
      ]
    });
    return mod.show();
  };

  Editor.prototype.getCopyButton = function() {
    if (this.modeIs(["new", "bulk"]) || !this._onCopy) {
      return;
    }
    return this.copyButton = new LocaButton({
      loca_key: "editor.copy",
      hidden: true,
      ui: "editor.copy.button",
      onClick: (function(_this) {
        return function() {
          return _this.callback("copy");
        };
      })(this)
    });
  };

  Editor.prototype.__updateByIndex = function(index) {
    var deferred, globalObjectId, ref, ref1;
    globalObjectId = this.__next_previous_global_object_ids[index];
    if (!globalObjectId) {
      return CUI.rejectedPromise();
    }
    this.__navigationPreviousNext.disable();
    this.__waitBlock.show();
    if ((ref = this.__previousButton) != null) {
      ref.disable();
    }
    if ((ref1 = this.__nextButton) != null) {
      ref1.disable();
    }
    deferred = new CUI.Deferred();
    deferred.always((function(_this) {
      return function() {
        _this.__navigationPreviousNext.enable();
        return _this.__waitBlock.hide();
      };
    })(this));
    ResultObject.loadFromGlobalObjectId(globalObjectId, "short", null, true, false).done((function(_this) {
      return function(resultObject) {
        var currentTable, idTable, objecttype;
        objecttype = resultObject.objecttype();
        idTable = ez5.schema.CURRENT._table_by_name[objecttype].table_id;
        currentTable = _this.editor_data.table;
        if (currentTable.id() !== idTable) {
          if (_this.object) {
            ez5.maskMemoryManager.storeMask(_this.object.objecttype(), _this.editor_data.mask_name, "editor");
          }
          _this.__maskSelectedByObjecttype[currentTable.name()] = _this.editor_data.mask_name;
          _this.editor_data.mask_name = _this.__maskSelectedByObjecttype[objecttype];
        }
        _this.editor_data = {
          mode: _this.editor_data.mode,
          require_comment: _this.editor_data.require_comment,
          mask_name: _this.editor_data.mask_name
        };
        delete _this.__asset_browser_idx;
        _this.object_list = new ObjectList({
          onRemove: function(object, idx) {
            return _this.__onObjectListRemove(object, idx);
          }
        });
        _this.object_list.push(resultObject);
        _this.__load(deferred, 0);
      };
    })(this)).fail(deferred.reject);
    return deferred.promise();
  };

  Editor.prototype.getNavigationPreviousNext = function() {
    if (this.modeIs(["new", "bulk"]) || !this.__next_previous_global_object_ids) {
      return;
    }
    this.__navigationPreviousNext = new NavigationToolbar({
      append_count_label: false,
      short: true,
      centered: true,
      onLoadPage: (function(_this) {
        return function(page) {
          return _this.__onPreviousNextUpdate(page);
        };
      })(this)
    });
    return this.__navigationPreviousNext;
  };

  Editor.prototype.__updateNavigationPreviousNext = function() {
    var index, ref;
    if (!this.__navigationPreviousNext) {
      return;
    }
    index = CUI.util.idxInArray((ref = this.object) != null ? ref.getGlobalObjectId() : void 0, this.__next_previous_global_object_ids);
    this.__navigationPreviousNext.update({
      count: this.__next_previous_global_object_ids.length,
      offset: index,
      limit: 1
    });
  };

  Editor.prototype.__onPreviousNextUpdate = function(index) {
    var ref, showSaveButton;
    if (this.hasChanges()) {
      this.updateSaveButton();
      showSaveButton = (ref = this.saveButton) != null ? ref.isEnabled() : void 0;
      this.__getConfirmationChoice(showSaveButton, false).open().done((function(_this) {
        return function(choice, _, ev) {
          if (choice._value === "save") {
            return _this.doSave(ev).done(function(data) {
              _this.callback("apply", data);
              return _this.__updateByIndex(index);
            });
          } else if (choice._value === "discard") {
            return _this.__updateByIndex(index);
          }
        };
      })(this));
    } else {
      this.__updateByIndex(index);
    }
  };

  Editor.prototype.__onObjectListRemove = function(object, idx) {};

  Editor.prototype.__getGoToTopButtonParent = function() {
    return this.__pane.center();
  };

  Editor.prototype.__addGoToTopButton = function() {
    var goToTopWrapper;
    if (ez5.version("6")) {
      this.__goToTopBtn = new LocaButton({
        "class": "cui-button-goto-top cui-disabled",
        loca_key: "general.frontend.gototop.button",
        onClick: (function(_this) {
          return function() {
            if (_this.__scrollDiv) {
              return _this.__scrollDiv.scrollTop = 0;
            }
          };
        })(this)
      });
      goToTopWrapper = new CUI.dom.div("ez5-goto-top");
      CUI.dom.append(goToTopWrapper, this.__goToTopBtn);
      CUI.dom.append(this.__getGoToTopButtonParent(), goToTopWrapper);
      return console.log(this.__goToTopBtn);
    }
  };

  Editor.prototype.__configureGoToTopBtn = function() {
    var elem;
    if (!this.__goToTopBtn) {
      this.__addGoToTopButton();
    }
    if (this.__EditorScrollListener) {
      CUI.Events.ignore(this.__EditorScrollListener);
      this.__EditorScrollListener = null;
    }
    if (CUI.dom.hasClass(this.__mainPane, "is-fully-scrollable")) {
      elem = this.getScrollableWrapper();
      if (!(elem instanceof HTMLElement)) {
        elem = elem.DOM;
      }
      this.__scrollDiv = elem;
    } else {
      this.__scrollDiv = this.__editor_div;
    }
    return this.__EditorScrollListener = CUI.Events.listen({
      node: this.__scrollDiv,
      type: "scroll",
      call: (function(_this) {
        return function(ev) {
          if (_this.__scrollDiv.scrollTop > 0) {
            CUI.dom.removeClass(_this.__goToTopBtn, "cui-disabled");
          } else {
            CUI.dom.addClass(_this.__goToTopBtn, "cui-disabled");
          }
          if (_this.rememberScrollPosition()) {
            _this.__saved_scroll_position = _this.__scrollDiv.scrollTop;
          }
        };
      })(this)
    });
  };

  return Editor;

})(CUI.Element);

CUI.ready(function() {
  CUI.Events.registerEvent({
    type: ["editor-changed", "editor-reload-asset-browser", "editor-update-asset-browser"],
    bubble: true
  });
  return CUI.Events.registerEvent({
    type: ["editor-update", "editor-load", "editor-render-object", "editor-add-new-result-object", "editor-tags-field-changed", "editor-mask-changed"]
  });
});

ez5.session_ready(function() {
  return Editor.plugins = new CUI.PluginRegistry({
    "class": ez5.EditorPlugin
  });
});
// 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.EditorPlugin = (function(superClass) {
  extend(EditorPlugin, superClass);

  function EditorPlugin() {
    return EditorPlugin.__super__.constructor.apply(this, arguments);
  }

  EditorPlugin.prototype.__checkForm = function(_opts) {
    var cdp, checkDataProblems, i, len, opts;
    opts = CUI.Element.readOpts(_opts, "ez5.EditorPlugin[checkForm]", {
      bulk: {
        mandatory: true,
        check: Boolean
      },
      "new": {
        mandatory: true,
        check: Boolean
      },
      editor: {
        mandatory: true,
        check: Editor
      },
      resultObject: {
        mandatory: true,
        check: ResultObject
      }
    });
    checkDataProblems = this.checkForm(opts);
    for (i = 0, len = checkDataProblems.length; i < len; i++) {
      cdp = checkDataProblems[i];
      CUI.util.assert(cdp instanceof CheckDataProblem, "ez5.EditorPlugin.__checkForm", "checkForm needs to return instances of CheckDataProblem.");
    }
    return checkDataProblems;
  };

  EditorPlugin.prototype.checkForm = function(opts) {
    return [];
  };

  EditorPlugin.prototype.__onSave = function(_opts) {
    var opts;
    opts = CUI.Element.readOpts(_opts, "ez5.EditorPlugin[onSave]", {
      bulk: {
        mandatory: true,
        check: Boolean
      },
      "new": {
        mandatory: true,
        check: Boolean
      },
      editor: {
        mandatory: true,
        check: Editor
      },
      resultObject: {
        mandatory: true,
        check: ResultObject
      },
      objectList: {
        mandatory: true,
        check: ObjectList
      },
      event: {
        mandatory: true,
        check: CUI.Event
      }
    });
    return CUI.decide(this.onSave(opts));
  };

  EditorPlugin.prototype.onSave = function(opts) {
    return [];
  };

  EditorPlugin.prototype.destroy = function() {
    return EditorPlugin.__super__.destroy.call(this);
  };

  return EditorPlugin;

})(CUI.Plugin);
// Generated by CoffeeScript 1.12.7
var EditorModal,
  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;

EditorModal = (function(superClass) {
  extend(EditorModal, superClass);

  function EditorModal() {
    this.removeObject = bind(this.removeObject, this);
    return EditorModal.__super__.constructor.apply(this, arguments);
  }

  EditorModal.prototype.getMainPane = function() {
    var left;
    left = {
      content: this.getMainPaneSidebar()
    };
    if (ez5.version("6")) {
      left.flexHandle = {
        state_name: "editor-modal-left",
        hidden: false
      };
    }
    this.__editorWrapper = new CUI.VerticalLayout({
      center: {
        content: []
      }
    });
    this.__horizontalLayout = new CUI.HorizontalLayout({
      "class": "ez5-editor-pane",
      left: left,
      center: {
        content: this.__editorWrapper
      },
      right: {
        flexHandle: {
          hidden: false,
          closed: true,
          state_name: "editor-modal-right"
        }
      }
    });
    this.__pullOutDiv = CUI.dom.element("div", {
      "class": "ez5-editor-pullout"
    });
    this.__horizontalLayout.append(this.__pullOutDiv, "right");
    this.__pullOutFlexHandle = this.__horizontalLayout.getFlexHandle("right");
    return this.__horizontalLayout;
  };

  EditorModal.prototype.getEditorWrapper = function() {
    return this.__editorWrapper;
  };

  EditorModal.prototype.getScrollableWrapper = function() {
    return this.getEditorWrapper().center();
  };

  EditorModal.prototype.getMainPaneSidebar = function() {
    return null;
  };

  EditorModal.prototype.__deactivateSidebar = function() {
    var ref;
    EditorModal.__super__.__deactivateSidebar.call(this);
    if ((ref = this.modal) != null) {
      ref.position();
    }
  };

  EditorModal.prototype.__activateSidebar = function() {
    var ref;
    EditorModal.__super__.__activateSidebar.call(this);
    if ((ref = this.modal) != null) {
      ref.position();
    }
  };

  EditorModal.prototype.getAssetBrowserInfoControl = function() {
    this.infoControlLayout = new CUI.VerticalLayout({
      center: {
        "class": "ez5-editor-pane-asset-browser"
      },
      bottom: {
        flexHandle: {
          hidden: true,
          closed: true,
          state_name: "editor-modal-asset-browser-divider"
        },
        "class": "ez5-editor-pane-asset-browser-info-control",
        content: this.infoControlDiv
      }
    });
    return new AssetBrowserInfoControl({
      assetBrowser: this.assetBrowser,
      contentContainer: this.infoControlLayout.bottom(),
      onUpdate: (function(_this) {
        return function(control) {
          if (control.getInfoState()) {
            return _this.infoControlLayout.getFlexHandle("bottom").show().open();
          } else {
            return _this.infoControlLayout.getFlexHandle("bottom").hide().close();
          }
        };
      })(this)
    });
  };

  EditorModal.prototype.appendAssetBrowser = function() {
    if (this.assetBrowserInfoControl) {
      this.infoControlLayout.append(this.assetBrowser, "center");
      this.infoControlLayout.append(this.assetBrowserInfoControl, "center");
      return CUI.dom.append(this.__pullOutDiv, this.infoControlLayout);
    } else {
      return CUI.dom.append(this.__pullOutDiv, this.assetBrowser);
    }
  };

  EditorModal.prototype.open = function() {
    this.__show();
    return this.load().done((function(_this) {
      return function() {
        return _this.modal.show();
      };
    })(this)).fail((function(_this) {
      return function() {
        return _this.modal.destroy();
      };
    })(this));
  };

  EditorModal.prototype.__show = function() {
    this.render();
    return this.modal = new CUI.Modal({
      "class": "ez5-editor-modal",
      fill_space: "both",
      pane: this.__pane
    });
  };

  EditorModal.prototype.show = function() {
    this.__show();
    return this.modal.show();
  };

  EditorModal.prototype.destroy = function() {
    var ref;
    EditorModal.__super__.destroy.call(this);
    delete this.infoControlLayout;
    if ((ref = this.modal) != null) {
      ref.destroy();
    }
    return this.modal = null;
  };

  EditorModal.prototype.getToolbarRightContent = function() {
    return this.getPullOutSwitch();
  };

  EditorModal.prototype.getCloseButtonLocaKey = function() {
    return "editor.modal.close";
  };

  EditorModal.prototype.getCurrentTools = function() {
    var dfr, tools;
    dfr = new CUI.Deferred();
    tools = [];
    if (this.object.hasRight("delete") && this.object.id()) {
      tools.push(new ToolboxTool({
        name: "editor.delete",
        sort: "B:5",
        loca_key: "tool.editor.delete",
        run: (function(_this) {
          return function() {
            return _this.deleteObjects();
          };
        })(this)
      }));
    }
    return dfr.resolve(tools);
  };

  EditorModal.prototype.render = function() {
    var leftFooterElements, ref;
    EditorModal.__super__.render.call(this);
    this.__toolbar.replace([this.getMaskSelectPlaceholder()], "left");
    this.__paneHeader.replace([
      new LocaButton({
        "class": "ez5-modal-close-button",
        loca_key: this.getCloseButtonLocaKey(),
        ui: "editor.modal.close.button",
        onClick: (function(_this) {
          return function(ev) {
            return _this.doCancel(ev);
          };
        })(this)
      })
    ], "right");
    leftFooterElements = [this.getPreferTemplateButton()];
    if (((ref = this.editor_data) != null ? ref["skip_new_modal_upload_step"] : void 0) && this.__getAvoidUploadButton) {
      leftFooterElements.push(this.__getAvoidUploadButton($$("editor.modal.new.avoid_upload_step_button.disable", true)));
    }
    this.__paneFooter.replace(leftFooterElements, "left");
    this.__paneFooter.replace(this.getNavigationPreviousNext(), "center");
    this.__paneFooter.replace([
      new CUI.Buttonbar({
        buttons: [this.getDeleteButton(), this.getCancelButton(), this.getCopyButton(), this.getApplyButton()]
      }), this.getSaveButton()
    ], "right");
    return this.__pane;
  };

  EditorModal.prototype.getPreferTemplateButton = function() {};

  EditorModal.prototype.getApplyButton = function() {};

  EditorModal.prototype.getCancelButton = function() {
    if (!this.modeIs(["bulk"])) {
      return null;
    }
    return new CUI.Button({
      text: $$("base.cancel"),
      onClick: (function(_this) {
        return function() {
          return _this.doCancel();
        };
      })(this)
    });
  };

  EditorModal.prototype.isOpen = function() {
    return !!this.modal;
  };

  EditorModal.prototype.__onObjectListRemove = function(object, idx) {
    if (this._object_list.getCurrentIdx() === idx) {
      this._object_list.setCurrentIdx(0);
      return this.load();
    } else {
      return this.updateButtons();
    }
  };

  EditorModal.prototype.removeObject = function(idx) {
    var load_first;
    console.debug("removeObject", this._object_list.getCurrentIdx(), idx);
    if (this._object_list.getCurrentIdx() === idx) {
      load_first = true;
      alert("load_first");
    }
    this._object_list.remove(idx);
    if (load_first) {
      this._object_list.setCurrentIdx(0);
      return this.load();
    } else {
      return this.updateButtons();
    }
  };

  EditorModal.prototype.__getGoToTopButtonParent = function() {
    return this.getEditorWrapper();
  };

  EditorModal.prototype.rememberScrollPosition = function() {
    return true;
  };

  EditorModal.prototype.rememberMaskSplitterStates = function() {
    return true;
  };

  return EditorModal;

})(Editor);
// Generated by CoffeeScript 1.12.7
var EditorModalBulk,
  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;

EditorModalBulk = (function(superClass) {
  extend(EditorModalBulk, superClass);

  function EditorModalBulk() {
    this.removeObject = bind(this.removeObject, this);
    return EditorModalBulk.__super__.constructor.apply(this, arguments);
  }

  EditorModalBulk.prototype.getMainPaneSidebar = function() {
    this.__sidebar = new CUI.VerticalLayout({
      "class": "ez5-editor-modal-bulk-left-vertical-layout",
      ui: "editor.modal.bulk.objects_container",
      bottom: {}
    });
    return this.__sidebar;
  };

  EditorModalBulk.prototype.rememberScrollPosition = function() {
    return false;
  };

  EditorModalBulk.prototype.rememberMaskSplitterStates = function() {
    return false;
  };

  EditorModalBulk.prototype.getSidebarButtons = function() {
    this.minusButton = new LocaButton({
      ui: "editor-modal-bulk-sidebar-minus-button",
      loca_key: "editor.modal.bulk.sidebar.minus-button",
      disabled: true,
      group: "plusminus",
      onClick: (function(_this) {
        return function() {
          _this.minusButton.disable();
          return _this.removeObject(_this.object_list.getCurrentIdx());
        };
      })(this)
    });
    this.copyToTemplateButton = new LocaButton({
      ui: "editor-modal-bulk-copy-to-template-button",
      loca_key: "editor.modal.bulk.copy_to_template",
      disabled: true,
      group: "plusminus",
      onClick: (function(_this) {
        return function() {
          return _this.copyToTemplate();
        };
      })(this)
    });
    return [this.minusButton, this.copyToTemplateButton];
  };

  EditorModalBulk.prototype.getWaitModalTitleLocaKeyPrefix = function() {
    if (this.getChunkSize()) {
      return "editor.modal.bulk.";
    } else {
      return EditorModalBulk.__super__.getWaitModalTitleLocaKeyPrefix.call(this);
    }
  };

  EditorModalBulk.prototype.getSidebar = function() {
    return this.__sidebar;
  };

  EditorModalBulk.prototype.render = function() {
    var browserDiv, get_object_idx, verticalList, verticalListContent;
    EditorModalBulk.__super__.render.call(this);
    this.__navigationToolbar = this.__renderNavigationToolbar();
    verticalListContent = [this.__navigationToolbar].concat(this.getSidebarButtons());
    browserDiv = this.object_list.renderBrowser();
    verticalList = new CUI.VerticalList({
      maximize_horizontal: true,
      maximize_vertical: true,
      "class": "ez5-editor-modal-bulk-vertical-list",
      content: verticalListContent
    });
    this.__sidebar.replace(browserDiv, "center");
    this.__sidebar.replace(verticalList, "bottom");
    get_object_idx = (function(_this) {
      return function(ev) {
        var idx, target;
        target = CUI.dom.closest(ev.getTarget(), "div[idx]");
        if (!target) {
          return null;
        }
        idx = parseInt(CUI.dom.getAttribute(target, "idx"));
        if (isNaN(idx)) {
          return null;
        } else {
          return idx;
        }
      };
    })(this);
    CUI.Events.listen({
      node: browserDiv,
      type: "toolbox",
      call: (function(_this) {
        return function(ev, info) {
          var idx, promise;
          if (!_this.hasTemplate()) {
            return;
          }
          idx = get_object_idx(ev);
          if (idx === null) {
            return;
          }
          if (idx === _this.getTemplateIdx()) {
            return;
          }
          if (idx !== _this.object_list.getCurrentIdx()) {
            _this.object_list.setCurrentIdx(idx);
            promise = _this.load();
          } else {
            promise = CUI.resolvedPromise();
          }
          promise.done(function() {
            if (_this.minusButton.isEnabled()) {
              info.tools.push(new ToolboxTool({
                group: "object",
                name: "object.remove_from_list",
                loca_key: "editor.modal.bulk.remove_from_list.tool",
                sort: "A:1",
                run: function() {
                  _this.minusButton.disable();
                  return _this.removeObject(_this.object_list.getCurrentIdx());
                }
              }));
            }
            if (_this.copyToTemplateButton.isEnabled()) {
              info.tools.push(new ToolboxTool({
                group: "object",
                name: "object.copy_to_template",
                loca_key: "editor.modal.bulk.copy_to_template.tool",
                sort: "A:2",
                run: function() {
                  _this.copyToTemplateButton.disable();
                  return _this.copyToTemplate();
                }
              }));
            }
          });
          return promise;
        };
      })(this)
    });
    CUI.Events.listen({
      node: browserDiv,
      type: "click",
      call: (function(_this) {
        return function(ev) {
          var idx, old_idx;
          ev.stopPropagation();
          idx = get_object_idx(ev);
          if (idx === null) {
            return;
          }
          old_idx = _this.object_list.getCurrentIdx();
          _this.object_list.setCurrentIdx(idx);
          _this.load().fail(function() {
            _this.object_list.setCurrentIdx(old_idx);
            return _this.load().fail(function() {});
          });
        };
      })(this)
    });
    this.__updateNavigationPage();
    this.__pane.addClass("ez5-editor-bulk");
    return this.__pane;
  };

  EditorModalBulk.prototype.copyToTemplate = function() {
    var idx, obj, tmpl;
    idx = this.object_list.getCurrentIdx();
    tmpl = this.object_list.getObject(this.getTemplateIdx());
    obj = this.object_list.getObject(idx);
    tmpl.setData(obj.getSaveData({
      copy: true
    }));
    this.object_list.setCurrentIdx(this.getTemplateIdx());
    return this.load();
  };

  EditorModalBulk.prototype.updateToolbarRight = function() {
    if (this.object_list.getCurrentIdx() === this.getTemplateIdx() || this.modeIs(["new"])) {
      return EditorModalBulk.__super__.updateToolbarRight.call(this);
    }
    return this.__toolbar.replace([this.getToolbarRightContent()], "right");
  };

  EditorModalBulk.prototype.dismissWaitModalTimeout = function(received_data) {
    var btn, not_saved_count, saved_count;
    if (received_data == null) {
      received_data = [];
    }
    if (this.editor_data.mode !== "bulk" || !ez5.version("6")) {
      return EditorModalBulk.__super__.dismissWaitModalTimeout.call(this, received_data);
    }
    if (received_data.length !== this.object_list.getCount()) {
      btn = new CUI.Button({
        text: $$("base.ok"),
        onClick: (function(_this) {
          return function() {
            _this.__dismissWaitModalInProgress = false;
            return _this.dismissWaitModal();
          };
        })(this)
      });
      this.dismissWaitModal();
      this.__dismissWaitModalInProgress = true;
      saved_count = received_data.length;
      not_saved_count = this.object_list.getCount() - received_data.length;
      if (received_data.length === 0) {
        this.showWaitModal("objects_not_saved", {}, btn);
        return;
      }
      this.showWaitModal("partially_saved", {
        not_saved: not_saved_count,
        saved: saved_count
      }, btn);
      return;
    } else {
      this.showWaitModal("objects_saved", {
        count: received_data.length
      });
    }
    this.__dismissWaitModalInProgress = true;
    CUI.setTimeout({
      ms: 1500,
      call: (function(_this) {
        return function() {
          _this.__dismissWaitModalInProgress = false;
          return _this.dismissWaitModal();
        };
      })(this)
    });
    return this;
  };

  EditorModalBulk.prototype.updateButtons = function() {
    var ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9;
    EditorModalBulk.__super__.updateButtons.call(this);
    if (((ref = this._object_list) != null ? ref.getCurrentIdx() : void 0) === this.getTemplateIdx() || ((ref1 = this._object_list) != null ? ref1.getCountWithoutTemplate() : void 0) <= this.getMinimumObjectCount()) {
      if ((ref2 = this.minusButton) != null) {
        ref2.disable();
      }
      if ((ref3 = this.copyToTemplateButton) != null) {
        ref3.disable();
      }
      if (((ref4 = this._object_list) != null ? ref4.getCountWithoutTemplate() : void 0) <= this.getMinimumObjectCount()) {
        if ((ref5 = this._object_list) != null) {
          ref5.toggleRemoveButtons(false);
        }
      }
    } else {
      if ((ref6 = this.minusButton) != null) {
        ref6.enable();
      }
      if ((ref7 = this.copyToTemplateButton) != null) {
        ref7.enable();
      }
      if ((ref8 = this._object_list) != null) {
        ref8.toggleRemoveButtons(true);
      }
    }
    if (!ez5.session.hasSystemRight("root", "frontend_features[editor_bulk_delete]")) {
      if ((ref9 = this.deleteButton) != null) {
        ref9.disable();
      }
    }
    return this;
  };

  EditorModalBulk.prototype.getMinimumObjectCount = function() {
    return 1;
  };

  EditorModalBulk.prototype.__onObjectListRemove = function(object, idx) {
    var tmpl_idx;
    tmpl_idx = this._object_list.getTemplateIdx();
    this.__updateNavigationPage();
    this.load();
    return this.updateButtons();
  };

  EditorModalBulk.prototype.removeObject = function(idx) {
    var tmpl_idx;
    idx = this._object_list.getCurrentIdx();
    this._object_list.remove(idx, false, false);
    tmpl_idx = this._object_list.getTemplateIdx();
    if (this._object_list.getCurrentIdx() === tmpl_idx) {
      this._object_list.setCurrentIdx(tmpl_idx + 1);
    }
    this.__updateNavigationPage();
    this.load();
    this.updateButtons();
    return this;
  };

  EditorModalBulk.prototype.getChunkSize = function() {
    return this.editor_data.chunk_size;
  };

  EditorModalBulk.prototype.getChunkSizeSelect = function() {
    var chunk_sizes, i, k, len, opts, sel;
    chunk_sizes = [1000, 100, 50, 10, 1];
    if (!this.editor_data.chunk_size) {
      this.editor_data.chunk_size = chunk_sizes[0];
    }
    opts = [];
    for (i = 0, len = chunk_sizes.length; i < len; i++) {
      k = chunk_sizes[i];
      opts.push({
        text: k + "",
        "default": k === this.editor_data.chunk_size,
        value: k
      });
    }
    sel = new CUI.Select({
      data: this.editor_data,
      name: "chunk_size",
      options: opts
    });
    return [
      new LocaLabel({
        loca_key: "editor.modal.bulk.chunk_size_select"
      }), sel.start()
    ];
  };

  EditorModalBulk.prototype.__renderNavigationToolbar = function() {
    var navigationToolbar;
    navigationToolbar = new NavigationToolbar({
      short: true,
      item_name: this.editor_data.table.nameLocalized(),
      onLoadPage: (function(_this) {
        return function(page) {
          _this.object_list.setCurrentIdx(page * ObjectList.chunkSize + 1);
          return _this.__updateNavigationPage(page);
        };
      })(this)
    });
    return navigationToolbar;
  };

  EditorModalBulk.prototype.addNewResultObject = function(data, ro) {
    if (data == null) {
      data = {};
    }
    if (ro == null) {
      ro = new ResultObject();
    }
    ro = EditorModalBulk.__super__.addNewResultObject.call(this, data, ro);
    this.updateButtons();
    this.__updateNavigationPage();
    return ro;
  };

  EditorModalBulk.prototype.__updateNavigationPage = function(page) {
    var count, idx, limit, offset;
    if (page == null) {
      page = null;
    }
    if (!this.__navigationToolbar) {
      return;
    }
    limit = ObjectList.chunkSize;
    if (page === null) {
      idx = this.object_list.getCurrentIdx() - 1;
      page = Math.max(0, Math.floor(idx / limit));
    }
    offset = limit * page;
    count = this.object_list.getCountWithoutTemplate();
    this.__navigationToolbar.update({
      count: count,
      offset: offset,
      limit: limit
    });
    if (this.object_list.getStartIdx() !== offset + 1) {
      this.object_list.updateBrowserWithNavigation(offset);
    }
  };

  return EditorModalBulk;

})(EditorModal);
// Generated by CoffeeScript 1.12.7
var EditorModalSingle,
  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;

EditorModalSingle = (function(superClass) {
  extend(EditorModalSingle, superClass);

  function EditorModalSingle() {
    return EditorModalSingle.__super__.constructor.apply(this, arguments);
  }

  EditorModalSingle.prototype.initOpts = function() {
    EditorModalSingle.__super__.initOpts.call(this);
    this.addOpts({
      editor_sidebar: {
        check: EditorSidebar
      },
      collection_selection: {
        mandatory: false
      }
    });
    this.mergeOpt("object_list", {
      mandatory: false,
      check: function(v) {
        return v instanceof ObjectList && v.getCount() === 1;
      }
    });
    return this.mergeOpt("mode", {
      "default": "single"
    });
  };

  EditorModalSingle.prototype.readOpts = function() {
    EditorModalSingle.__super__.readOpts.call(this);
    CUI.util.assert(CUI.util.xor(this._editor_sidebar, this._object_list || this._global_object_id), "new EditorModalSingle", "One of opts.editor_sidebar or opts.object_list must be set.", {
      opts: this.opts
    });
    if (this._editor_sidebar) {
      this.object_list = this._editor_sidebar.object_list;
      this.editor_data = this._editor_sidebar.editor_data;
      return this.object = this.object_list.getObject();
    }
  };

  EditorModalSingle.prototype.updateSaveButton = function() {
    EditorModalSingle.__super__.updateSaveButton.call(this);
    if (this.saveButton.isEnabled()) {
      this.applyButton.enable();
    } else {
      this.applyButton.disable();
    }
    return this;
  };

  EditorModalSingle.prototype.updateToolbarRight = function() {
    var dfr;
    dfr = EditorModalSingle.__super__.updateToolbarRight.call(this);
    dfr.done((function(_this) {
      return function() {
        var ref, ref1;
        if (_this.__sidebarButton && _this.assetBrowserButton.isActive()) {
          _this.__sidebarButton.enable();
          return (ref = _this.__pullOutFlexHandle) != null ? ref.show().open() : void 0;
        } else {
          return (ref1 = _this.__pullOutFlexHandle) != null ? ref1.close().hide() : void 0;
        }
      };
    })(this));
    return dfr;
  };

  EditorModalSingle.prototype.getCloseButtonLocaKey = function() {
    if (this._editor_sidebar) {
      return "editor.modal.from_sidebar.close";
    } else {
      return EditorModalSingle.__super__.getCloseButtonLocaKey.call(this);
    }
  };

  EditorModalSingle.prototype.getApplyButton = function() {
    return this.applyButton = new LocaButton({
      ui: "editor.modal.single.apply.button",
      loca_key: "editor.modal.single.button.apply",
      secondary: true,
      disabled: true,
      onClick: (function(_this) {
        return function(ev) {
          _this.__clearServerValidationErrors();
          if (_this.rememberMaskSplitterStates()) {
            _this.storeMaskSplitterStates();
          }
          return _this.doSave(ev).done(function(received_data, read_only) {
            if (read_only) {
              return CUI.problem({
                text: $$("editor.modal.single.read_only_after_apply")
              }).done(function() {
                return _this.callback("saveReadOnly", received_data);
              });
            } else {
              _this.callback("apply", received_data);
              return _this.load();
            }
          }).fail(function(error) {
            var ref, ref1, validation_problems;
            if (ez5.version("6.7") && (error != null ? (ref = error.response) != null ? ref.code : void 0 : void 0) === "validation.plugin.error") {
              validation_problems = (ref1 = error.response.parameters) != null ? ref1.problems : void 0;
              return _this.__processSeverValidationProblems(validation_problems);
            }
          });
        };
      })(this)
    });
  };

  EditorModalSingle.prototype.doClose = function(ev) {
    if (this._editor_sidebar) {
      return CUI.resolvedPromise("cancel");
    } else {
      return EditorModalSingle.__super__.doClose.call(this, ev);
    }
  };

  EditorModalSingle.prototype.open = function() {
    if (this._editor_sidebar) {
      this.show();
      if (this.copyButton) {
        DbInfo.canCreate({
          objecttypes: [new Objecttype(this.editor_data.table)]
        }).done((function(_this) {
          return function() {
            return _this.copyButton.show();
          };
        })(this));
      }
      return this.reloadEditor();
    } else {
      return EditorModalSingle.__super__.open.call(this);
    }
  };

  EditorModalSingle.prototype.getCurrentTools = function() {
    var dfr;
    dfr = new CUI.Deferred();
    EditorModalSingle.__super__.getCurrentTools.call(this).done((function(_this) {
      return function(tools) {
        var copyToolOpts, onCopyToolRun;
        copyToolOpts = {
          favorite: true,
          disabled: true,
          sort: "B:2"
        };
        onCopyToolRun = function(opts) {
          if (opts.copyAsTemplate) {
            return _this.object.copyAsTemplate();
          } else {
            return _this.callback("copy", opts);
          }
        };
        _this.copyTool = Sidebar.getCopyTool(_this.object, onCopyToolRun, copyToolOpts);
        if (_this.modeIsNot(["new"])) {
          return DbInfo.canCreate({
            objecttypes: [new Objecttype(_this.editor_data.table)]
          }).done(function() {
            return tools.push(_this.copyTool);
          }).always(function() {
            return dfr.resolve(tools);
          });
        } else {
          return dfr.resolve(tools);
        }
      };
    })(this));
    return dfr.promise();
  };

  EditorModalSingle.prototype.showFullscreenDetail = function() {
    var ref, ref1, showSaveButton;
    if (!this._collection_selection || (this.object == null)) {
      return;
    }
    if (this.hasChanges()) {
      this.updateSaveButton();
      showSaveButton = (ref = this.saveButton) != null ? ref.isEnabled() : void 0;
      return this.__getConfirmationChoice(showSaveButton).open().done((function(_this) {
        return function(choice, _, ev) {
          var ref1;
          switch (choice._value) {
            case "cancel":
              break;
            case "discard":
              _this._collection_selection.showFullscreen({
                global_object_id: _this.object.data._global_object_id
              });
              return (ref1 = _this.modal) != null ? ref1.destroy() : void 0;
            case "save":
              return _this.doSave(ev).done(function(received_data, read_only) {
                var ref2;
                _this._collection_selection.showFullscreen({
                  global_object_id: _this.object.data._global_object_id
                });
                return (ref2 = _this.modal) != null ? ref2.destroy() : void 0;
              }).fail(function() {});
          }
        };
      })(this));
    } else {
      this._collection_selection.showFullscreen({
        global_object_id: this.object.data._global_object_id
      });
      return (ref1 = this.modal) != null ? ref1.destroy() : void 0;
    }
  };

  EditorModalSingle.prototype.getToolbarRightContent = function() {
    var content, showDetailButton;
    content = EditorModalSingle.__super__.getToolbarRightContent.call(this);
    if (ez5.session.getPref("use_fullscreen")) {
      showDetailButton = new LocaButton({
        loca_key: "editor.modal.single.tool.show_detail",
        ui: "editor.modal.show_detail.button",
        onClick: (function(_this) {
          return function() {
            return _this.showFullscreenDetail();
          };
        })(this)
      });
      if (content) {
        return [showDetailButton, content];
      } else {
        return showDetailButton;
      }
    } else {
      return content;
    }
  };

  return EditorModalSingle;

})(EditorModal);
// Generated by CoffeeScript 1.12.7
var EditorModalNew,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

EditorModalNew = (function(superClass) {
  extend(EditorModalNew, superClass);

  function EditorModalNew() {
    return EditorModalNew.__super__.constructor.apply(this, arguments);
  }

  EditorModalNew.NAVIGATION_PAGE_SIZE = 100;

  EditorModalNew.OBJECTS_LIMIT = 1000;

  EditorModalNew.FILE_APPEND_TYPE_REPLACE = "replace";

  EditorModalNew.FILE_APPEND_TYPE_CREATE = "create_version";

  EditorModalNew.FILE_APPEND_TYPE_CREATE_PREFERRED = "create_version_preferred";

  EditorModalNew.FILE_APPEND_TYPE_REFUSE = "refuse";

  EditorModalNew.MATCH_FILENAME_REGEXP = /^(.*)[_\- ]+[0-9]+\.[a-zA-Z]+[a-zA-Z0-9]*$/;

  EditorModalNew.MATCH_SUBTITLES_REGEXP = /^(.+)\-{2}([a-zA-Z0-9]+)\.vtt$/;

  EditorModalNew.prototype.readOpts = function() {
    EditorModalNew.__super__.readOpts.call(this);
    this.initEditorDataFields();
    this.editor_data.prefer_template_over_mapping = true;
    this.__modalForm = null;
    this.__files = [];
    return this.__rPutFiles = [];
  };

  EditorModalNew.prototype.keyPrefix = "main.editor.modal.new.form";

  EditorModalNew.prototype.rememberScrollPosition = function() {
    return false;
  };

  EditorModalNew.prototype.rememberMaskSplitterStates = function() {
    return false;
  };

  EditorModalNew.prototype.getSidebarButtons = function() {
    var buttons, items, lastCount, openAddObjectsPrompt;
    items = [];
    if (this.editor_data.bulk_field) {
      this.__fileUploadButton = new CUI.FileUploadButton({
        ui: "editor-modal-new-upload-files-button",
        text: $$("editor.modal.new.button.files|text"),
        icon: $$("editor.modal.new.button.files|icon"),
        tooltip: {
          text: $$("editor.modal.new.button.files|tooltip")
        },
        multiple: true,
        fileUpload: this.__fileUpload
      });
      items.push(this.__fileUploadButton);
      if (window.bowser.webkit || window.bowser.blink || window.bowser.gecko || window.bowser.msedge) {
        this.__directoryUploadButton = new CUI.FileUploadButton({
          ui: "editor-modal-new-upload-directory-button",
          text: $$("editor.modal.new.button.directory|text"),
          icon: $$("editor.modal.new.button.directory|icon"),
          tooltip: {
            text: $$("editor.modal.new.button.directory|tooltip")
          },
          directory: true,
          fileUpload: this.__fileUpload
        });
        items.push(this.__directoryUploadButton);
      }
      items.push({
        divider: true
      });
    }
    lastCount = "";
    openAddObjectsPrompt = (function(_this) {
      return function() {
        return CUI.prompt({
          ui: "editor.modal.new.add_objects_prompt",
          text: $$('editor.modal.new.add_objects.prompt.text'),
          placeholder: $$('editor.modal.new.add_objects.prompt.placeholder'),
          min_length: 1,
          "default": lastCount
        }).done(function(count) {
          count = CUI.util.getInt(count);
          lastCount = count + "";
          if (!count || count <= 0 || count > 100) {
            openAddObjectsPrompt();
            return;
          }
          _this.addEmptyToEditor(count);
        });
      };
    })(this);
    items.push({
      loca_key: "editor.modal.new.add_object",
      ui: "editor.modal.new.add_object",
      onClick: (function(_this) {
        return function() {
          return _this.addEmptyToEditor();
        };
      })(this)
    });
    items.push({
      loca_key: "editor.modal.new.add_objects",
      ui: "editor.modal.new.add_objects",
      onClick: (function(_this) {
        return function() {
          return openAddObjectsPrompt();
        };
      })(this)
    });
    buttons = EditorModalNew.__super__.getSidebarButtons.call(this);
    buttons.splice(0, 0, {
      ui: "editor.modal.new.plus_button",
      loca_key: "editor.modal.new.sidebar.plus-button",
      group: "plusminus",
      menu: {
        items: items
      }
    });
    return buttons;
  };

  EditorModalNew.prototype.getChunkSizeSelect = function() {
    return null;
  };

  EditorModalNew.prototype.getChunkSize = function() {
    return null;
  };

  EditorModalNew.prototype.getUploadButtons = function() {
    var buttons, produce_checkbox;
    buttons = [];
    this.__fileUploadButton = new CUI.FileUploadButton({
      ui: "editor.modal.new.button:upload_file",
      fileUpload: this.__fileUpload,
      text: $$("editor.modal.new.button.files|text"),
      icon: $$("editor.modal.new.button.files|icon"),
      tooltip: {
        text: $$("editor.modal.new.button.files|tooltip")
      },
      multiple: true
    });
    buttons.push(this.__fileUploadButton);
    if (window.bowser.webkit || window.bowser.blink || window.bowser.gecko || window.bowser.msedge) {
      this.__directoryUploadButton = new CUI.FileUploadButton({
        fileUpload: this.__fileUpload,
        ui: "editor.modal.new.button:upload_directory",
        text: $$("editor.modal.new.button.directory|text"),
        icon: $$("editor.modal.new.button.directory|icon"),
        tooltip: {
          text: $$("editor.modal.new.button.directory|tooltip")
        },
        directory: true
      });
      buttons.push(this.__directoryUploadButton);
    }
    if (!ez5.version("6") || ez5.session.hasSystemRight("root", "frontend_features[upload_url]")) {
      this.__rputFileUploadButton = new LocaButton({
        ui: "editor.modal.new.button:upload_files_rput",
        loca_key: "editor.modal.new.button.rput.files",
        onClick: (function(_this) {
          return function() {
            return _this.__showUploadRPutFilesModal(_this.__rputFileUploadButton);
          };
        })(this)
      });
      buttons.push(this.__rputFileUploadButton);
    }
    if (ez5.version("6") && ez5.session.isDebug() && ez5.session.hasSystemRight("root", "frontend_features[upload_without_produce_versions]")) {
      produce_checkbox = new CUI.Checkbox({
        text: $$("editor.modal.new.upload_without_produce_versions"),
        data: this.editor_data,
        name: "upload_without_produce_versions",
        tooltip: {
          text: $$("editor.modal.new.upload_without_produce_versions|tooltip")
        },
        onDataChanged: (function(_this) {
          return function(d) {
            ez5.session.savePref("upload_without_produce_versions", _this.editor_data["upload_without_produce_versions"]);
            _this.__fileUpload.setUrl(ez5.eas.getUploadUrl({
              produce_versions: JSON.stringify([!_this.editor_data["upload_without_produce_versions"]])
            }));
          };
        })(this)
      });
      buttons.push(produce_checkbox.start());
    }
    return buttons;
  };

  EditorModalNew.prototype.getPreferTemplateButton = function() {
    var cb, mapping, mapping_name, text;
    mapping_name = $$("metadata.profile.mapping.no_mapping");
    if (this.editor_data.mapping && this.editor_data.mapping !== "standard") {
      mapping = ez5.metadata.getMapping(this.editor_data.mapping);
      if (mapping) {
        mapping_name = ez5.loca.getBestFrontendValue(mapping.displayname);
      }
    } else if (this.editor_data.mapping === "standard") {
      mapping_name = $$("metadata.profile.mapping.standard_mapping");
    }
    text = $$("editor.modal.new.prefer_template_over_mapping");
    if (mapping_name) {
      text += " (" + mapping_name + ")";
    }
    cb = new CUI.Checkbox({
      ui: "editor.modal.new.checkbox:prefer_template_over_mapping",
      disabled: !this.editor_data.mapping,
      data: this.editor_data,
      name: "prefer_template_over_mapping",
      text: text,
      onDataChanged: (function(_this) {
        return function() {
          return _this.reloadEditor();
        };
      })(this)
    });
    return cb.start();
  };

  EditorModalNew.prototype.__getAvoidUploadButton = function(label) {
    var cb;
    if (label == null) {
      label = $$("editor.modal.new.avoid_upload_step_button");
    }
    cb = new CUI.Checkbox({
      data: this.editor_data,
      name: "skip_new_modal_upload_step",
      text: label,
      onDataChanged: (function(_this) {
        return function() {
          ez5.session.setPref("skip_new_modal_upload_step", _this.editor_data["skip_new_modal_upload_step"]);
          return ez5.session.savePrefs();
        };
      })(this)
    });
    return cb.start();
  };

  EditorModalNew.prototype.getEASFields = function(include_nested) {
    var fields, mask;
    if (include_nested == null) {
      include_nested = true;
    }
    if (this.editor_data) {
      mask = Mask.getMaskByMaskName(this.editor_data.mask_name, this.editor_data.table.id());
    }
    CUI.util.assert(mask instanceof Mask, "EditorModalNew.getEASFields", "Mask not found.", {
      editor_data: this.editor_data
    });
    fields = [];
    mask.invokeOnFields('editor', include_nested, (function(_this) {
      return function(f) {
        var eas_column, new_eas_column;
        if (f instanceof ReverseLinkedTable && f.isHierarchical()) {
          return false;
        }
        if (f instanceof EASColumn && !f.isReadOnly('editor')) {
          fields.push(f);
        }
        if (f instanceof LinkedObject && include_nested) {
          eas_column = f.getFirstStandardEASColumn();
          if (eas_column) {
            new_eas_column = new EASColumnLinkedObject(eas_column.mask, eas_column.FieldSchema, f);
            return fields.push(new_eas_column);
          }
        }
      };
    })(this));
    return fields;
  };

  EditorModalNew.prototype.__getNavigation = function() {
    this.__currentPage = 0;
    this.__navigationFileToolbar = new NavigationToolbar({
      short: true,
      item_name: $$("editor.modal.new.navigation.item_name"),
      onLoadPage: (function(_this) {
        return function(page) {
          return _this.__updateNavigation(page);
        };
      })(this)
    });
    this.__updateNavigation();
    return this.__navigationFileToolbar;
  };

  EditorModalNew.prototype.__updateNavigation = function(page) {
    var file, filesInPage, j, len, limit, offset;
    if (page == null) {
      page = this.__currentPage;
    }
    if (!this.__navigationFileToolbar) {
      return;
    }
    limit = EditorModalNew.NAVIGATION_PAGE_SIZE;
    offset = page * limit;
    filesInPage = this.__files.slice(offset, offset + limit);
    if (page !== 0 && filesInPage.length === 0) {
      return this.__updateNavigation(--page);
    }
    this.__navigationFileToolbar.update({
      count: this.__files.length,
      offset: offset,
      limit: limit
    });
    this.__currentPage = page;
    CUI.dom.empty(this.__newPane.map.drop_zone);
    for (j = 0, len = filesInPage.length; j < len; j++) {
      file = filesInPage[j];
      this.__newPane.map.drop_zone.appendChild(file._template.DOM);
    }
  };

  EditorModalNew.prototype.onFileAdd = function(file) {
    var filename, lbl, remove_btn;
    if (this.newModal) {
      filename = file.getName();
      if (this.__files.length >= EditorModalNew.OBJECTS_LIMIT) {
        if (this.__fileLimitAlert) {
          return false;
        }
        this.__fileLimitAlert = CUI.alert({
          text: $$("editor.modal.new.file_limit", {
            file: filename,
            count: EditorModalNew.OBJECTS_LIMIT
          })
        }).done((function(_this) {
          return function() {
            return delete _this.__fileLimitAlert;
          };
        })(this));
        return false;
      }
      remove_btn = new LocaButton({
        loca_key: "editor.modal.new.remove-button",
        ui: "editor.modal.file.remove.button",
        appearance: "flat",
        size: "mini",
        tooltip: {
          text: $$("editor.modal.new.remove-button|tooltip"),
          placement: "e"
        },
        onClick: (function(_this) {
          return function() {
            return file.remove();
          };
        })(this)
      });
      file._template = new CUI.Template({
        name: "file-upload",
        map: {
          remove: true,
          info: true,
          thumb: true
        }
      });
      file._template.append(remove_btn, "remove");
      lbl = new CUI.Label({
        text: ez5.basename(filename),
        tooltip: {
          text: filename
        }
      });
      file._template.append(lbl, "info");
      file._template.replace(ez5.eas.getFileUploadMeter(file), "thumb");
      file.original_filename = file.getName();
      new CUI.Tooltip({
        element: file._template.DOM,
        text: (function(_this) {
          return function() {
            return file.getName() + ", " + ez5.format_filesize(file.getFile().size);
          };
        })(this)
      });
      this.__files.push(file);
      this.__updateNavigation();
      this.updateNextButton();
    } else {
      this.addFileToEditor(file);
    }
    return true;
  };

  EditorModalNew.prototype.onFileRemove = function(file) {
    if (this.newModal && file._template) {
      CUI.util.removeFromArray(file, this.__files);
      file._template.destroy();
      delete file._template;
      file.destroy();
      this.__updateNavigation();
      this.updateNextButton();
    }
  };

  EditorModalNew.prototype.onFileFail = function(file) {
    if (this.newModal) {
      return file.remove();
    } else {
      file._upload_field.uploadFail(file._file_data, file);
      return this.updateButtons();
    }
  };

  EditorModalNew.prototype.onFileDone = function(file) {
    var bulkField, data, file_always, pool;
    data = file.getData();
    if (!file._upload_field) {
      file._value = {
        _id: data[0]._id,
        original_filename: file.getName()
      };
      file_always = (function(_this) {
        return function(value) {
          var asset;
          file._value = value;
          if (file._template) {
            asset = new AssetPlain({
              value: value
            });
            file._template.replace(asset.getImgElement(), "thumb");
          }
        };
      })(this);
      ez5.eas.addToQueue({
        dequeue: (function(_this) {
          return function() {
            return _this.isDestroyed();
          };
        })(this),
        value: file._value,
        done: file_always,
        failed: file_always
      });
      return this.updateNextButton();
    } else {
      file._upload_field.uploadDone(file._file_data, file);
      if (this.editor_data.mapping) {
        bulkField = this.editor_data.bulk_field;
        if (bulkField instanceof EASColumnLinkedObject) {
          pool = this.editor_data["_pool_" + (bulkField.getLinkedObject().fullName())];
        } else {
          pool = this.editor_data._pool;
        }
        return EAS.mapMetadata({
          data: file._object_top_level_data,
          eas_id: file._value._id,
          mask_name: bulkField.getMainMask().name(),
          objecttype: bulkField.getMainMask().table.name(),
          pool_id: pool != null ? pool.pool._id : void 0,
          mapping: this.editor_data.mapping,
          mapping_recipe_configs: this.editor_data.mapping_recipe_configs
        }).done((function(_this) {
          return function() {
            var idx;
            idx = _this.object_list.idxByData(file._top_level_data);
            if (_this.isDestroyed()) {
              return;
            }
            if (_this.object_list.getCurrentIdx() === idx) {
              return _this.reloadEditor();
            } else {
              _this.object_list.updateObjectInBrowser(idx);
              return _this.updateButtons();
            }
          };
        })(this));
      } else {
        return this.updateButtons();
      }
    }
  };

  EditorModalNew.prototype.addEmptyToEditor = function(count) {
    var doFinish, i, j, ref, ref1;
    if (count == null) {
      count = 1;
    }
    doFinish = (function(_this) {
      return function() {
        _this.updateButtons();
        return _this.__updateNavigationPage();
      };
    })(this);
    this.addNewTemplateObject();
    for (i = j = 0, ref = count; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      if (((ref1 = this._object_list) != null ? ref1.getCount(true) : void 0) >= EditorModalNew.OBJECTS_LIMIT) {
        doFinish();
        CUI.alert({
          text: $$("editor.modal.new.max_quantity_objects_added", {
            count: i
          }),
          markdown: true
        });
        return;
      }
      Editor.prototype.addNewResultObject.call(this);
    }
    doFinish();
    return this;
  };

  EditorModalNew.prototype.getMinimumObjectCount = function() {
    return 1;
  };

  EditorModalNew.prototype.addNewTemplateObject = function(data) {
    var to;
    if (data == null) {
      data = {};
    }
    if (!CUI.util.isNull(this.template_idx)) {
      return;
    }
    to = EditorModalNew.__super__.addNewTemplateObject.call(this, data);
    this.updateButtons();
    return to;
  };

  EditorModalNew.prototype.initFileUpload = function() {
    var batches, progressAdd, progressDone, progressModal, progressRemove, progressShow, progress_dialog, thumbs_warned, urlParams;
    progressModal = null;
    batches = {};
    progressShow = (function(_this) {
      return function() {
        var _, batch, batchFile, file, filesDone, filesTotal, j, len, ref, ref1, sizeDone, sizeTotal, text;
        sizeTotal = 0;
        sizeDone = 0;
        filesTotal = 0;
        filesDone = 0;
        for (_ in batches) {
          batch = batches[_];
          for (j = 0, len = batch.length; j < len; j++) {
            batchFile = batch[j];
            file = batchFile.file;
            filesTotal++;
            sizeTotal += file.size;
            if (batchFile.done) {
              filesDone++;
              sizeDone += file.size;
            } else {
              sizeDone += (ref = batchFile.fileUpload) != null ? (ref1 = ref.getProgress()) != null ? ref1.loaded : void 0 : void 0;
            }
          }
        }
        text = $$("editor.modal.new.upload-progress-message", {
          filesDone: Math.min(filesDone + 1, filesTotal),
          filesTotal: filesTotal,
          sizeDone: (sizeDone / 1000000).toFixed(2),
          sizeTotal: (sizeTotal / 1000000).toFixed(2),
          percentage: (sizeDone * 100 / sizeTotal).toFixed(2)
        });
        if (!progressModal) {
          progressModal = new CUI.Alert({
            text: "-",
            "class": "ez5-modal-progress-alert",
            ui: "editor.modal.progress.alert",
            backdrop: false,
            button_text_ok: $$("editor.modal.new.upload-progress-abort-button"),
            onChoice: function() {
              var k, len1, ref2;
              _this.__fileUpload.stopQueuing();
              ref2 = _this.__fileUpload.getFiles();
              for (k = 0, len1 = ref2.length; k < len1; k++) {
                file = ref2[k];
                if (!file.isDone()) {
                  _this.__fileUpload.removeFile(file);
                  _this.onFileRemove(file);
                }
              }
            },
            onDestroy: function() {
              batches = {};
              return progressModal = null;
            }
          });
        }
        progressModal.setText(text);
        progressModal.open();
        if (filesDone === filesTotal && progressModal.isShown()) {
          progressModal.destroy();
        }
      };
    })(this);
    progressRemove = function(fileUpload) {
      var batch, batchIndex;
      batchIndex = fileUpload.getBatch();
      batch = batches[batchIndex];
      if (!batch) {
        return;
      }
      CUI.util.removeFromArray(null, batch, (function(_this) {
        return function(v) {
          return v.file === fileUpload.getFile();
        };
      })(this));
      progressShow();
    };
    progressAdd = function(fileUpload) {
      var batch, batchIndex, file;
      batchIndex = fileUpload.getBatch();
      batch = batches[batchIndex];
      if (!batch) {
        batch = [];
        batches[batchIndex] = batch;
      }
      file = fileUpload.getFile();
      batch.push({
        fileUpload: fileUpload,
        file: file,
        done: false
      });
      progressShow();
    };
    progressDone = function(fileUpload) {
      var batch, batchFile, batchIndex, file, j, len;
      batchIndex = fileUpload.getBatch();
      batch = batches[batchIndex];
      if (!batch) {
        return;
      }
      file = fileUpload.getFile();
      for (j = 0, len = batch.length; j < len; j++) {
        batchFile = batch[j];
        if (batchFile.file === file) {
          batchFile.done = true;
          break;
        }
      }
      progressShow();
    };
    this.__dupDialog = new DuplicatesDialog({
      ui: "editor.modal.new.duplicates.dialog"
    });
    thumbs_warned = false;
    progress_dialog = null;
    urlParams = {};
    if (ez5.version("6") && (this.editor_data != null)) {
      urlParams = {
        produce_versions: JSON.stringify([!this.editor_data["upload_without_produce_versions"]])
      };
    }
    this.__fileUpload = new CUI.FileUpload({
      url: ez5.eas.getUploadUrl(urlParams),
      shouldQueue: (function(_this) {
        return function(files) {
          if (files.length + _this.__files.length > EditorModalNew.OBJECTS_LIMIT) {
            CUI.alert({
              text: $$("editor.modal.new.file_limit_exceeded", {
                count: EditorModalNew.OBJECTS_LIMIT
              })
            });
            return false;
          }
          return true;
        };
      })(this),
      onAdd: (function(_this) {
        return function(file, idx, count) {
          var added, fn;
          fn = file.getFile().name;
          if (fn === "Thumbs.db" || fn === ".DS_Store") {
            if (!thumbs_warned) {
              CUI.alert({
                text: $$("editor.modal.new.file_ignored", {
                  file: fn
                })
              });
              thumbs_warned = true;
            }
            return false;
          }
          added = _this.onFileAdd(file);
          if (added) {
            progressAdd(file);
          }
        };
      })(this),
      onBatchStart: (function(_this) {
        return function() {
          return _this.updateNextButton();
        };
      })(this),
      onBatchQueued: (function(_this) {
        return function() {
          return _this.updateNextButton();
        };
      })(this),
      onBatchDone: (function(_this) {
        return function() {
          progressShow();
          _this.updateNextButton();
          if (progress_dialog != null) {
            progress_dialog.destroy();
          }
          return progress_dialog = null;
        };
      })(this),
      onRemove: (function(_this) {
        return function(file) {
          progressRemove(file);
          return _this.onFileRemove(file);
        };
      })(this),
      onBeforeDone: (function(_this) {
        return function(file) {
          return _this.__dupDialog.addFile(file).fail(function() {
            var index, j, len, object, objects;
            if (_this.newModal) {
              return;
            }
            objects = _this._object_list.getObjects();
            for (index = j = 0, len = objects.length; j < len; index = ++j) {
              object = objects[index];
              if (object.data === file._top_level_data) {
                _this._object_list.remove(index);
                break;
              }
            }
            if (objects.length <= 1) {
              _this.addEmptyToEditor();
            }
          });
        };
      })(this),
      onProgress: (function(_this) {
        return function() {
          return progressShow();
        };
      })(this),
      onDone: (function(_this) {
        return function(file) {
          progressDone(file);
          return _this.onFileDone(file);
        };
      })(this),
      onFail: (function(_this) {
        return function(file) {
          progressRemove(file);
          if (file.getStatus() !== "ABORT") {
            return EAS.presentUploadError(file).done(function() {
              return _this.onFileFail(file);
            });
          } else {
            return _this.onFileFail(file);
          }
        };
      })(this)
    });
    return this.__fileUpload;
  };

  EditorModalNew.prototype.queueFiles = function(files) {
    return this.__fileUpload.queueFiles(files);
  };

  EditorModalNew.prototype.saveAllowed = function() {
    return EditorModalNew.__super__.saveAllowed.call(this) && this.__fileUpload.isDone();
  };

  EditorModalNew.prototype.closeAllowed = function() {
    return EditorModalNew.__super__.closeAllowed.call(this) && this.__fileUpload.getFiles().length === 0;
  };

  EditorModalNew.prototype.destroy = function() {
    var ref, ref1, ref2;
    this.abortUploads();
    this.destroyNewModal();
    if ((ref = this.__form) != null) {
      ref.destroy();
    }
    this.__form = null;
    if ((ref1 = this.__fileUpload) != null) {
      ref1.destroy();
    }
    this.__fileUpload = null;
    if ((ref2 = this.__dupDialog) != null) {
      ref2.destroy();
    }
    this.__dupDialog = null;
    this.__directoryUploadButton = null;
    this.__fileUploadButton = null;
    this.__rputFileUploadButton = null;
    this.__mappingRecipeConfigButton = null;
    this.__mappingSelectField = null;
    return EditorModalNew.__super__.destroy.call(this);
  };

  EditorModalNew.prototype.destroyNewModal = function() {
    var ref, ref1;
    this.nextButton = null;
    if ((ref = this.newModal) != null) {
      ref.destroy();
    }
    this.newModal = null;
    if ((ref1 = this.__newPane) != null) {
      ref1.destroy();
    }
    return this.__newPane = null;
  };

  EditorModalNew.prototype.abortUploads = function() {
    var ref;
    this.upload_in_progress = false;
    return (ref = this.__fileUpload) != null ? ref.clear() : void 0;
  };

  EditorModalNew.prototype.initDbInfo = function(warn_if_no_objecttype_found) {
    var dfr;
    if (warn_if_no_objecttype_found == null) {
      warn_if_no_objecttype_found = true;
    }
    dfr = new CUI.Deferred();
    this.__allDbInfo = new DbInfo();
    this.__allDbInfo.load().done((function(_this) {
      return function() {
        var opts;
        _this.__available_objecttypes = _this.__allDbInfo.getAvailableObjecttypes();
        opts = _this.getObjecttypeFieldOptions();
        if (opts.length === 0 && warn_if_no_objecttype_found) {
          CUI.alert({
            title: $$("base.error"),
            text: $$("main.editor.modal.new.no_objecttype_found")
          }).done(function() {
            return dfr.reject("zero_objecttypes");
          });
          return;
        }
        _this.__initPool();
        return dfr.resolve(opts);
      };
    })(this));
    return dfr.promise();
  };

  EditorModalNew.prototype.__initPool = function() {
    var idPool, idPoolToLoad, poolIds, ref;
    if (((ref = this.editor_data.table) != null ? ref.poolLink() : void 0) && !this.editor_data._pool) {
      poolIds = this.__allDbInfo.getPoolIds(this.editor_data.table.name());
      idPool = ez5.session.getPref("pool_id");
      if (idPool && poolIds && indexOf.call(poolIds, idPool) >= 0) {
        idPoolToLoad = idPool;
      } else {
        idPoolToLoad = poolIds != null ? poolIds[0] : void 0;
      }
      if (idPoolToLoad) {
        this.setPoolFromPoolId(idPoolToLoad);
      }
    }
  };

  EditorModalNew.prototype.openEmpty = function() {
    var dfr, ref;
    if (ez5.session.isReadOnly()) {
      CUI.alert({
        text: $$("base.error.user.read_only_mode")
      });
      return CUI.rejectedPromise();
    }
    CUI.util.assert(((ref = this._object_list) != null ? ref.getCount() : void 0) === 0, "EditorModalNew.openEmpty", "opts.objects.getCount() must be 0", {
      opts: this.opts
    });
    this.initFileUpload();
    dfr = new CUI.Deferred();
    this.__dupDialog.resetBatchChoice();
    this.initDbInfo().done((function(_this) {
      return function() {
        var fill_space, ref1;
        _this.__showAllObjecttypes = false;
        _this.__newPane = new CUI.Template({
          name: "editor-modal-new-ng",
          map: {
            left: true,
            toolbar: true,
            drop_zone: true,
            backpane: true
          }
        });
        CUI.dom.setAttribute(_this.__newPane.DOM, "ui", "editor.modal.new.content");
        _this.__fileUpload.initDropZone({
          dropZone: _this.__newPane.map.drop_zone,
          allow_drop: function(ev) {
            if (_this.editor_data.bulk_field) {
              return true;
            } else {
              return false;
            }
          }
        });
        _this.__newPane.replace(new LocaLabel({
          "class": "cui-empty-label",
          centered: true,
          multiline: true,
          loca_key: "main.editor.new.drop_zone"
        }), "backpane");
        _this.nextButton = new LocaButton({
          loca_key: "main.editor.new.button.next",
          ui: "main.editor.new.button.next",
          primary: true,
          left: true,
          disabled: true,
          onClick: function() {
            return _this.openEditor();
          }
        });
        fill_space = "both";
        if (((ref1 = ez5.cssLoader.getActiveCSS()) != null ? ref1.theme : void 0) === "ng") {
          fill_space = void 0;
        }
        _this.newModal = new CUI.Modal({
          "class": "ez5-editor-modal-new ez5-event-poller",
          ui: "editor.modal.new.modal",
          fill_space: fill_space,
          cancel: true,
          onCancel: function(ev) {
            return _this.doClose(ev).done(function(callback) {
              _this.abortUploads();
              _this.destroyNewModal();
              return _this.callback(callback);
            });
          },
          pane: {
            header_left: new CUI.Label({
              text: $$("main.editor.objects.new_choice")
            }),
            content: _this.__newPane,
            footer_right: _this.nextButton,
            footer_left: _this.__getAvoidUploadButton()
          }
        });
        return _this.updateModalForm().done(function() {
          _this.newModal.show();
          return dfr.resolve(_this);
        }).fail(function() {
          return dfr.reject(_this);
        });
      };
    })(this)).fail((function(_this) {
      return function(xhr) {
        if (xhr === "zero_objecttypes") {
          _this.callback("cancel");
          dfr.reject(_this);
        } else {
          dfr.reject(xhr);
        }
      };
    })(this));
    dfr.done((function(_this) {
      return function() {
        if (_this.editor_data["skip_new_modal_upload_step"]) {
          return _this.openEditor();
        }
      };
    })(this));
    return dfr.promise();
  };

  EditorModalNew.prototype.openEditor = function() {
    var count, file, j, k, l, len, len1, len2, promises, ref, ref1, ref2, st;
    count = 0;
    promises = [];
    if (ez5.version("6") && this.editor_data.mapping) {
      ref = this.__fileUpload.getFiles();
      for (j = 0, len = ref.length; j < len; j++) {
        file = ref[j];
        st = file.getStatus();
        if (st === "FAILED" || st === "ABORT" || st === "DEQUEUED") {
          continue;
        }
        if (st !== "DONE") {
          this.__preparingMapping = true;
          this.showWaitModal("preparing-mapping");
          CUI.setTimeout({
            ms: 500,
            call: (function(_this) {
              return function() {
                _this.openEditor();
              };
            })(this)
          });
          return;
        }
      }
      this.__preparingMapping = false;
    }
    if (this.editor_data.bulk_field) {
      ref1 = this.__fileUpload.getFiles();
      for (k = 0, len1 = ref1.length; k < len1; k++) {
        file = ref1[k];
        st = file.getStatus();
        if (st === "FAILED" || st === "ABORT" || st === "DEQUEUED") {
          continue;
        }
        promises.push(this.addFileToEditor(file));
        count++;
      }
      ref2 = this.__rPutFiles;
      for (l = 0, len2 = ref2.length; l < len2; l++) {
        file = ref2[l];
        promises.push(this.addFileToEditor(file));
        count++;
      }
    }
    if (count === 0) {
      this.addEmptyToEditor();
      if (this.editor_data.skip_new_modal_upload_step) {
        this._object_list.getObjects()[1].data._can_be_overwritten = true;
        this.__empty_first_object_data = this._object_list.getObjects()[1].getSaveData();
      }
    }
    this.nextButton.startSpinner();
    this.newModal.disableAllButtons();
    promises.push(this.__dupDialog.getBatchPromise());
    this.__metadataMappingProblemsCount = 0;
    this.__metadataMappingProblems = [];
    this.__metadataMappingInProgress = {
      done: 0,
      count: count
    };
    this.showWaitModal("mapping", {
      done: 1,
      count: count
    }, null, true);
    return CUI.whenAll(promises).done((function(_this) {
      return function() {
        var len3, n, problem, problemText, ref3, show_editor;
        _this.__metadataMappingInProgress = null;
        show_editor = function() {
          _this.dismissWaitModal();
          _this.destroyNewModal();
          if (_this.object_list.getCountWithoutTemplate() > 1) {
            _this.object_list.setCurrentIdx(0);
          } else {
            _this.object_list.setCurrentIdx(1);
          }
          return _this.open().done(function() {
            if (_this.editor_data.bulk_field) {
              return _this.__fileUpload.initDropZone({
                dropZone: _this.getSidebar()
              });
            }
          });
        };
        if (_this.__metadataMappingProblemsCount > 0) {
          problemText = $$("editor.modal.new.mapping_problems", {
            count: _this.__metadataMappingProblemsCount
          });
          if (_this.__metadataMappingProblems.length > 0) {
            problemText += "\n\n";
            ref3 = _this.__metadataMappingProblems;
            for (n = 0, len3 = ref3.length; n < len3; n++) {
              problem = ref3[n];
              problemText += " - **EAS: " + problem.eas_id + "** - " + problem.code + ": " + problem.error + " \n";
            }
          }
          return CUI.alert({
            text: problemText,
            markdown: true
          }).done(show_editor);
        } else {
          return show_editor();
        }
      };
    })(this));
  };

  EditorModalNew.prototype.updateModalForm = function(dfr) {
    var wb;
    if (!dfr) {
      dfr = new CUI.Deferred();
      dfr.always((function(_this) {
        return function() {
          return _this.updateNextButton();
        };
      })(this));
    }
    if (this.__modalForm) {
      wb = new CUI.WaitBlock({
        element: this.__modalForm
      }).show();
      dfr.always((function(_this) {
        return function() {
          return wb.destroy();
        };
      })(this));
    }
    this.getDbInfo().done((function(_this) {
      return function(dbInfo) {
        var buttonBar, ex, fields, tags_field, toolbar;
        _this.editor_data.dbInfo = dbInfo;
        try {
          if (_this.checkAndSetPoolFromDbInfo()) {
            _this.updateModalForm(dfr);
            return;
          }
        } catch (error) {
          ex = error;
          if (ex instanceof UserError && !(_this instanceof EditorHeadlessNew)) {
            ex.presentError();
          }
          dfr.reject();
          return;
        }
        if (_this.editor_data.dbInfo.availableMasks().length === 0) {
          CUI.alert({
            title: $$("base.error"),
            text: $$("main.editor.modal.new.no_mask_found", {
              objecttype: _this.editor_data.table.nameLocalized()
            })
          }).done(function() {
            return dfr.reject();
          });
          return dfr.promise();
        }
        if (!_this.editor_data.mask_name) {
          _this.editor_data.mask_name = _this.editor_data.dbInfo.availableMasks()[0].name();
        }
        fields = _this.__getFormFields();
        if (tags_field = _this.getTagsField()) {
          fields.push(tags_field);
        }
        _this.__form = new CUI.Form({
          "class": "modal-editor-new",
          padded: true,
          fields: fields
        });
        _this.__updatePrefs();
        _this.__form.start();
        _this.__replaceModalForm(_this.__form);
        if (_this.__newPane) {
          buttonBar = new CUI.Buttonbar({
            buttons: _this.getUploadButtons()
          });
          toolbar = new CUI.Toolbar({
            left: {
              content: buttonBar
            },
            right: {
              content: _this.__getNavigation()
            }
          });
          _this.__newPane.replace(toolbar, "toolbar");
        }
        return dfr.resolve();
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  EditorModalNew.prototype.__getFormFields = function() {
    return [this.getObjecttypeField(), this.getPoolField(), this.getMaskField(), this.getEASField(), this.getEASFieldLinkedPoolSelector(), this.getLinkedPoolsCheckbox(), this.getLinkedPoolsSelector(), this.getMappingField(), this.getRecognizeVersionField(), this.getRecognizeSeriesField(), this.getIgnoreDuplicationField()];
  };

  EditorModalNew.prototype.__updatePrefs = function() {
    var field, fieldName, j, len, ref, ref1;
    ref = this.__getFieldNames();
    for (j = 0, len = ref.length; j < len; j++) {
      fieldName = ref[j];
      if (fieldName === "mapping") {
        field = this.__mappingSelectField;
        if (!field) {
          field = (ref1 = this.__form.getFieldsByName("_mapping")[0]) != null ? ref1._element() : void 0;
          if (!(field instanceof CUI.Select)) {
            field = null;
          }
        }
      } else {
        field = this.__form.getFieldsByName(fieldName)[0];
      }
      if (field) {
        ez5.session.setPref(fieldName, field.getValue());
      }
    }
    return ez5.session.savePrefs();
  };

  EditorModalNew.prototype.__getFieldNames = function() {
    return ["recognize_series", "recognize_version", "ignore_duplicate_dialog", "choice_table_id", "mask_name", "mapping"];
  };

  EditorModalNew.prototype.__replaceModalForm = function(form) {
    return this.__modalForm = this.replaceModalForm(form);
  };

  EditorModalNew.prototype.getRecognizeVersionField = function() {
    return {
      type: CUI.Checkbox,
      ui: "editor.modal.new.select:recognize_version",
      text: $$("editor.modal.new.recognize_version.label"),
      form: {
        hint: $$("editor.modal.new.recognize_version.label|hint")
      },
      data: this.editor_data,
      name: "recognize_version",
      onRender: (function(_this) {
        return function(field) {
          if (_this.editor_data.bulk_field) {
            return field.show(true);
          } else {
            return field.hide(true);
          }
        };
      })(this),
      onDataChanged: (function(_this) {
        return function() {
          return _this.__updatePrefs();
        };
      })(this)
    };
  };

  EditorModalNew.prototype.getRecognizeSeriesField = function() {
    return {
      type: CUI.Checkbox,
      ui: "editor.modal.new.select:recognize_series",
      text: $$("editor.modal.new.recognize_series.label"),
      form: {
        hint: $$("editor.modal.new.recognize_series.label|hint")
      },
      data: this.editor_data,
      name: "recognize_series",
      onRender: (function(_this) {
        return function(field) {
          if (_this.editor_data.bulk_field && _this.editor_data.bulk_field.supportsSeries()) {
            return field.show(true);
          } else {
            return field.hide(true);
          }
        };
      })(this),
      onDataChanged: (function(_this) {
        return function() {
          return _this.__updatePrefs();
        };
      })(this)
    };
  };

  EditorModalNew.prototype.getIgnoreDuplicationField = function() {
    return {
      type: CUI.Checkbox,
      ui: "editor.modal.new.select:ignore_duplicate_dialog",
      text: $$("editor.modal.new.ignore_duplication_check.label"),
      form: {
        hint: $$("editor.modal.new.ignore_duplication_check.label|hint")
      },
      data: this.editor_data,
      name: "ignore_duplicate_dialog",
      onRender: (function(_this) {
        return function(field) {
          if (_this.editor_data.bulk_field) {
            return field.show(true);
          } else {
            return field.hide(true);
          }
        };
      })(this),
      onDataChanged: (function(_this) {
        return function() {
          return _this.__updatePrefs();
        };
      })(this)
    };
  };

  EditorModalNew.prototype.replaceModalForm = function(form) {
    this.__newPane.replace(form, "left");
    return this.__newPane;
  };

  EditorModalNew.prototype.updateNextButton = function() {
    var bulkField, ref, ref1, ref2, ref3, ref4, ref5;
    if ((!this.editor_data.bulk_field) || this.__fileUpload.isQueuing()) {
      if ((ref = this.__fileUploadButton) != null) {
        ref.disable();
      }
      if ((ref1 = this.__directoryUploadButton) != null) {
        ref1.disable();
      }
      if ((ref2 = this.__rputFileUploadButton) != null) {
        ref2.disable();
      }
    } else {
      if ((ref3 = this.__fileUploadButton) != null) {
        ref3.enable();
      }
      if ((ref4 = this.__directoryUploadButton) != null) {
        ref4.enable();
      }
      if ((ref5 = this.__rputFileUploadButton) != null) {
        ref5.enable();
      }
    }
    if (this.nextButton) {
      this.nextButton.enable();
      if (!this.editor_data.bulk_field && this.__fileUpload.getFiles().length) {
        this.nextButton.disable();
      } else if (this.__fileUpload.getFiles(["FAILED", "ABORT", "CREATED"]).length > 0) {
        this.nextButton.disable();
      } else if (this.editor_data.table.poolLink() && !this.editor_data._pool) {
        this.nextButton.disable();
      } else if (this.editor_data.bulk_field) {
        bulkField = this.editor_data.bulk_field;
        if (!bulkField.isEASFieldEnabled()) {
          this.nextButton.disable();
        } else if (bulkField instanceof EASColumnLinkedObject && bulkField.getLinkedObject().linkMask().table.poolLink() && !this.editor_data["_pool_" + (bulkField.getLinkedObject().fullName())]) {
          this.nextButton.disable();
        }
      }
      this.__updateDropZoneCss();
    }
    return this;
  };

  EditorModalNew.prototype.__updateDropZoneCss = function() {
    if (this.__fileUpload.getFiles().length === 0 && this.__rPutFiles.length === 0) {
      return this.__newPane.removeClass("ez5-drop-zone-has-files");
    } else {
      return this.__newPane.addClass("ez5-drop-zone-has-files");
    }
  };

  EditorModalNew.prototype.getTagsField = function() {};

  EditorModalNew.prototype.getEASField = function() {
    var content, eas_opts, f, j, len, option, promises, ref, wrapperField;
    eas_opts = [];
    promises = [];
    ref = this.getEASFields();
    for (j = 0, len = ref.length; j < len; j++) {
      f = ref[j];
      option = f.getEASFieldOption();
      if (CUI.util.isPromise(option)) {
        promises.push(option);
        option.done((function(_this) {
          return function(easOption) {
            return eas_opts.push(easOption);
          };
        })(this));
      } else {
        eas_opts.push(option);
      }
    }
    content = CUI.dom.div();
    wrapperField = new CUI.DataFieldProxy({
      form: {
        label: $$(this.keyPrefix + ".field.label")
      },
      element: content,
      call_others: false
    });
    CUI.whenAll(promises).always((function(_this) {
      return function() {
        var dataField, fieldName, found, idx, k, l, len1, len2, noFieldsField, opt, ref1, ref2, ref3, ref4, ref5;
        if (eas_opts.length === 0) {
          if ((ref1 = _this.__newPane) != null) {
            ref1.addClass("ez5-disable-drop-zone");
          }
          _this.editor_data.bulk_field = null;
          noFieldsField = new CUI.DataFieldProxy({
            element: new CUI.Label({
              ui: "editor.modal.new.label:no_eas",
              content: $empty$(_this.keyPrefix + ".field.none")
            })
          });
          noFieldsField.start();
          return CUI.dom.replace(content, noFieldsField);
        } else {
          if ((ref2 = _this.__newPane) != null) {
            ref2.removeClass("ez5-disable-drop-zone");
          }
          found = 0;
          for (idx = k = 0, len1 = eas_opts.length; k < len1; idx = ++k) {
            opt = eas_opts[idx];
            if (((ref3 = _this.editor_data.bulk_field) != null ? ref3.nameForCollectionSave() : void 0) === opt.value.nameForCollectionSave()) {
              found = idx;
              break;
            }
          }
          _this.editor_data.bulk_field = eas_opts[found].value;
          eas_opts.sort(function(a, b) {
            return a.text.localeCompare(b.text);
          });
          dataField = CUI.Select.newSelectOrOutput({
            ui: "editor.modal.new.select:eas",
            tooltip: {
              text: eas_opts.length > 1 ? ez5.loca.str_default("editor.modal.new.eas_field.tooltip") : void 0
            },
            name: "bulk_field",
            maximize_horizontal: true,
            onDataChanged: function() {
              return _this.updateModalForm();
            },
            options: eas_opts,
            data: _this.editor_data
          });
          dataField.start();
          if (_this.__form) {
            ref4 = ["recognize_version", "ignore_duplicate_dialog", "recognize_series", "_pool_proxy", "_mapping"];
            for (l = 0, len2 = ref4.length; l < len2; l++) {
              fieldName = ref4[l];
              if ((ref5 = _this.__form.getFieldsByName(fieldName)[0]) != null) {
                ref5.reload();
              }
            }
          }
          _this.updateNextButton();
          return CUI.dom.replace(content, dataField);
        }
      };
    })(this));
    return wrapperField;
  };

  EditorModalNew.prototype.getFileData = function(_opts) {
    var bulk_field, check_type, create, file_data, file_data_match_type, get_match_names, mask, match_file, match_filename, object_top_level_data, opts, set_file_data, tn;
    if (_opts == null) {
      _opts = {};
    }
    opts = CUI.Element.readOpts(_opts, "EditorModalNew.getFileData", {
      top_level_data: {
        mandatory: true,
        check: 'PlainObject'
      },
      mask_name: {
        mandatory: true,
        check: String
      },
      filename: {
        mandatory: true,
        check: String
      },
      table: {
        mandatory: true,
        check: Table
      },
      bulk_field: {
        mandatory: true,
        check: EASColumn
      },
      mode: {
        mandatory: true,
        check: String
      },
      create: {
        mandatory: true,
        check: Boolean,
        "default": false
      }
    });
    mask = Mask.getMaskByMaskName(opts.mask_name, opts.table.id());
    bulk_field = opts.bulk_field;
    get_match_names = (function(_this) {
      return function(filename) {
        var match, ref, ref1;
        CUI.util.assert(CUI.util.isString(filename), "EditorModalNew.addFileToEditor[get_match_names]", "filename needs to be String.", {
          filename: filename
        });
        match = {
          filename: filename,
          dirname: ez5.dirname(filename),
          basename: ez5.basename(filename),
          bare_basename: ez5.bareBasename(filename).toLocaleLowerCase()
        };
        match.series_basename = (ref = match.basename.match(EditorModalNew.MATCH_FILENAME_REGEXP)) != null ? ref[1].toLocaleLowerCase() : void 0;
        match.subtitle_base = (ref1 = match.basename.match(EditorModalNew.MATCH_SUBTITLES_REGEXP)) != null ? ref1[1].toLocaleLowerCase() : void 0;
        return match;
      };
    })(this);
    match_filename = get_match_names(opts.filename);
    check_type = (function(_this) {
      return function(type) {
        switch (type) {
          case 'same':
          case 'version':
            if (_this.editor_data.recognize_version) {
              return type;
            }
            if (_this.editor_data.recognize_series && _this.editor_data.bulk_field.supportsSeries()) {
              return 'series';
            }
            break;
          case 'series':
            if (_this.editor_data.recognize_series && _this.editor_data.bulk_field.supportsSeries()) {
              return type;
            }
        }
      };
    })(this);
    match_file = (function(_this) {
      return function(eas_data) {
        var filename, j, len, match, value;
        if (!((eas_data != null ? eas_data.length : void 0) > 0)) {
          return;
        }
        for (j = 0, len = eas_data.length; j < len; j++) {
          value = eas_data[j];
          if (value._file_upload) {
            filename = value._file_upload.getName();
          } else {
            filename = value.original_filename;
          }
          match = get_match_names(filename);
          if (match_filename.subtitle_base && match.bare_basename.toLocaleLowerCase() === match_filename.subtitle_base) {
            return 'version';
          }
          if (match.dirname !== match_filename.dirname) {
            continue;
          }
          if (match.filename === match_filename.filename) {
            return check_type('same');
          }
          if (match.bare_basename === match_filename.bare_basename) {
            return check_type('version');
          }
          if (match.series_basename && match.series_basename === match_filename.series_basename) {
            return check_type('series');
          }
        }
      };
    })(this);
    tn = opts.table.name();
    file_data = null;
    file_data_match_type = null;
    object_top_level_data = null;
    create = opts.create;
    set_file_data = (function(_this) {
      return function(mask, mode, start_data) {
        CUI.util.assert(CUI.util.isPlainObject(start_data), "EditorModalNew.getFileData[set_file_data]", "start_data needs to be PlainObject.");
        object_top_level_data = start_data;
        return mask.invokeOnFields(mode, true, (function(f, data, depth) {
          var _data, _ro, create_new_entry, file_data_match, j, k, l, len, len1, len2, link_data, link_mask, link_tn, match_type, new_record, set_link_file_data, tf;
          if (file_data || file_data_match_type) {
            return;
          }
          if (f instanceof NestedTable) {
            if (CUI.util.isArray(data)) {
              if (data.length === 0) {
                _data = {};
                _data[f.name()] = [];
                data.push(_data);
              }
              return;
            }
            if (!data[f.name()]) {
              data[f.name()] = [];
            }
            return;
          }
          if (bulk_field instanceof EASColumnLinkedObject && f.fullName() === bulk_field.getLinkedObject().fullName()) {
            link_mask = f.linkMask();
            link_tn = link_mask.table.name();
            set_link_file_data = function(data) {
              if (!(data != null ? data[link_tn] : void 0)) {
                return;
              }
              return set_file_data(link_mask, 'standard', data[link_tn]);
            };
            if (CUI.util.isArray(data)) {
              for (j = 0, len = data.length; j < len; j++) {
                _data = data[j];
                set_link_file_data(_data[f.name()]);
                if (file_data) {
                  return;
                }
                if (file_data_match_type) {
                  create = true;
                  file_data_match_type = null;
                  break;
                }
              }
            } else {
              set_link_file_data(data[f.name()]);
              if (file_data) {
                return;
              }
            }
            if (create) {
              _ro = new ResultObject();
              link_data = {
                _mapped_metadata_created: true,
                _format: 'long',
                _mask: link_mask.name()
              };
              link_data[link_tn] = {};
              _ro.initData(link_tn, link_data);
              if (link_mask.table.poolLink()) {
                link_data[link_tn]._pool = _this.editor_data["_pool_" + (bulk_field.getLinkedObject().fullName())];
                if (!link_data[link_tn]._pool) {
                  link_data[link_tn]._pool = _this.editor_data.linked_pool;
                }
              }
              tf = link_mask.getTagsField('all');
              if (tf) {
                bulk_field.loadDbInfo().done(function() {
                  return tf.initData(link_data, {
                    mode: 'new',
                    dbInfo: bulk_field.getDbInfo()
                  });
                });
              }
              set_link_file_data(link_data);
              if (CUI.util.isArray(data)) {
                new_record = {};
                new_record[f.name()] = link_data;
                data.push(new_record);
              } else {
                data[f.name()] = link_data;
              }
            }
            return;
          }
          if (!(f instanceof EASColumn)) {
            return;
          }
          if (f.fullName() !== bulk_field.fullName()) {
            return;
          }
          if (CUI.util.isArray(data)) {
            create_new_entry = function() {
              new_record = {};
              new_record[f.name()] = [];
              file_data = new_record;
              data.push(new_record);
            };
            for (k = 0, len1 = data.length; k < len1; k++) {
              _data = data[k];
              match_type = match_file(_data[f.name()]);
              switch (match_type) {
                case 'same':
                case 'version':
                  file_data = _data;
                  file_data_match = match_type;
                  return;
              }
            }
            for (l = 0, len2 = data.length; l < len2; l++) {
              _data = data[l];
              match_type = match_file(_data[f.name()]);
              switch (match_type) {
                case 'series':
                  create_new_entry();
                  file_data_match = match_type;
                  return;
              }
            }
            if (create) {
              create_new_entry();
            }
            return;
          }
          match_type = match_file(data[f.name()]);
          switch (match_type) {
            case 'same':
            case 'version':
              file_data = data;
              file_data_match_type = match_type;
              return;
            case 'series':
              file_data_match_type = match_type;
          }
          if (create) {
            data[f.name()] = [];
            file_data = data;
          }
        }), start_data);
      };
    })(this);
    set_file_data(mask, opts.mode, opts.top_level_data);
    return [file_data, object_top_level_data];
  };

  EditorModalNew.prototype.addFileWithObjectToEditor = function(file, object, updatePolicy) {
    var bulkField, mapMetadataPromise, mask, pool, refuse, setEASData, table;
    if (object == null) {
      object = {};
    }
    table = this.editor_data.table;
    bulkField = this.editor_data.bulk_field;
    mask = Mask.getMaskByMaskName(this.editor_data.mask_name, table.id());
    file = file._value;
    file.preferred = true;
    refuse = false;
    setEASData = (function(_this) {
      return function(_mask, topData, level) {
        var found;
        if (level == null) {
          level = 0;
        }
        if (level > 20) {
          return;
        }
        found = false;
        _mask.invokeOnFields("editor", true, (function(f, data) {
          var _ro, easData, j, len, linkMask, newData, newLinkedData, newRecord, objecttypeName, ref, tagsField, version;
          if (found || refuse) {
            return;
          }
          if (f instanceof NestedTable) {
            if (!data[f.name()]) {
              data[f.name()] = [];
            }
            return;
          }
          if (f instanceof LinkedObject && bulkField instanceof EASColumnLinkedObject) {
            if (f.fullName() !== bulkField.getLinkedObject().fullName()) {
              return;
            }
            linkMask = f.linkMask();
            objecttypeName = linkMask.table.name();
            if (CUI.util.isArray(data)) {
              newLinkedData = {
                _format: 'long',
                _mask: linkMask.name()
              };
              newLinkedData[objecttypeName] = {};
              _ro = new ResultObject();
              _ro.initData(objecttypeName, newLinkedData);
              if (linkMask.table.poolLink()) {
                newLinkedData[objecttypeName]._pool = _this.editor_data["_pool_" + (bulkField.getLinkedObject().fullName())];
                if (!newLinkedData[objecttypeName]._pool) {
                  newLinkedData[objecttypeName]._pool = _this.editor_data.linked_pool;
                }
              }
              tagsField = linkMask.getTagsField('all');
              if (tagsField) {
                bulkField.loadDbInfo().done(function() {
                  return tagsField.initData(newLinkedData, {
                    mode: 'new',
                    dbInfo: bulkField.getDbInfo()
                  });
                });
              }
              setEASData(f.linkMask(), newLinkedData[objecttypeName], ++level);
              newData = {};
              newData[f.name()] = newLinkedData;
              data.push(newData);
            } else {
              if (!data[f.name()]) {
                data[f.name()] = {};
              }
              if (!data[f.name()][objecttypeName]) {
                data[f.name()][objecttypeName] = {};
              }
              delete data[f.name()]._path;
              delete data[f.name()][objecttypeName]._id;
              delete data[f.name()][objecttypeName]._version;
              setEASData(f.linkMask(), data[f.name()][objecttypeName], ++level);
            }
            return;
          }
          if (!(f instanceof EASColumn)) {
            return;
          }
          if (bulkField instanceof EASColumnLinkedObject && level === 0) {
            return;
          }
          if (f.fullName() !== bulkField.fullName()) {
            return;
          }
          if (CUI.util.isArray(data)) {
            newRecord = {
              _new: true
            };
            newRecord[f.name()] = [file];
            data.push(newRecord);
          } else {
            easData = data[f.name()];
            if (CUI.util.isEmpty(easData)) {
              data[f.name()] = [];
            }
            switch (updatePolicy) {
              case EditorModalNew.FILE_APPEND_TYPE_CREATE_PREFERRED:
                ref = data[f.name()];
                for (j = 0, len = ref.length; j < len; j++) {
                  version = ref[j];
                  version.preferred = false;
                }
                break;
              case EditorModalNew.FILE_APPEND_TYPE_REPLACE:
                data[f.name()] = [];
                break;
              case EditorModalNew.FILE_APPEND_TYPE_REFUSE:
                if (data[f.name()].length > 0) {
                  refuse = true;
                }
                break;
              default:
                if (data[f.name()].length > 0) {
                  file.preferred = false;
                }
            }
            if (refuse) {
              return;
            }
            data[f.name()].push(file);
          }
          return found = true;
        }), topData);
      };
    })(this);
    if (!object[table.name()]) {
      object[table.name()] = {};
    }
    setEASData(mask, object[table.name()]);
    if (refuse) {
      return CUI.rejectedPromise();
    }
    if (object._global_object_id) {
      if (!this.object_list.getObjects().some(function(_resultObject) {
        return _resultObject.data._global_object_id === object._global_object_id;
      })) {
        Editor.prototype.addNewResultObject.call(this, object);
      }
    } else {
      Editor.prototype.addNewResultObject.call(this, object);
    }
    if (!this.editor_data.mapping) {
      return CUI.resolvedPromise();
    }
    if (bulkField instanceof EASColumnLinkedObject) {
      pool = this.editor_data.linked_pool;
      if (!pool) {
        pool = this.editor_data["_pool_" + (bulkField.getLinkedObject().fullName())];
      }
    } else {
      pool = this.editor_data._pool;
    }
    mapMetadataPromise = EAS.mapMetadata({
      data: object[table.name()],
      eas_id: file._id,
      mask_name: bulkField.getMainMask().name(),
      objecttype: bulkField.getMainMask().table.name(),
      pool_id: pool != null ? pool.pool._id : void 0,
      mapping: this.editor_data.mapping,
      mapping_recipe_configs: this.editor_data.mapping_recipe_configs
    });
    return mapMetadataPromise;
  };

  EditorModalNew.prototype.getWaitModalTitleLocaKeyPrefix = function() {
    if (this.__metadataMappingInProgress || this.__preparingMapping) {
      return "main.editor.mapping.";
    } else {
      return EditorModalNew.__super__.getWaitModalTitleLocaKeyPrefix.call(this);
    }
  };

  EditorModalNew.prototype.addFileToEditor = function(file) {
    var add_result_object, attr, bulk_field, dfr, eas_field_name, file_data, first_object, j, len, linkedField, linkedPool, object_top_level_data, ot, pool, ref, ref1, ref2, ref3, reselect_first_item, resultObject, tn, top_level_data;
    dfr = new CUI.Deferred();
    tn = this.editor_data.table.name();
    bulk_field = this.editor_data.bulk_field;
    this.addNewTemplateObject();
    if (this.object_list.getObjects().length === 2 && this.__empty_first_object_data) {
      first_object = this.object_list.getObjects()[1];
      if (first_object.data._can_be_overwritten) {
        ot = first_object.data._objecttype;
        if (CUI.util.isEqual(first_object.getSaveData()[ot], this.__empty_first_object_data[ot])) {
          this.object_list.remove(1);
          reselect_first_item = true;
        } else {
          delete first_object.data._can_be_overwritten;
        }
        delete this.__empty_first_object_data;
      }
    }
    ref = this.object_list.getObjects();
    for (j = 0, len = ref.length; j < len; j++) {
      resultObject = ref[j];
      if (resultObject instanceof TemplateObject) {
        continue;
      }
      top_level_data = resultObject.getData();
      ref1 = this.getFileData({
        top_level_data: top_level_data[tn],
        filename: file.getName(),
        mask_name: this.editor_data.mask_name,
        table: this.editor_data.table,
        bulk_field: bulk_field,
        mode: 'editor'
      }), file_data = ref1[0], object_top_level_data = ref1[1];
      if (file_data) {
        break;
      }
    }
    if (!file_data) {
      top_level_data = {};
      top_level_data[tn] = {};
      add_result_object = true;
      ref2 = this.getFileData({
        top_level_data: top_level_data[tn],
        filename: file.getName(),
        mask_name: this.editor_data.mask_name,
        table: this.editor_data.table,
        bulk_field: bulk_field,
        mode: 'editor',
        create: true
      }), file_data = ref2[0], object_top_level_data = ref2[1];
    } else {
      add_result_object = false;
    }
    CUI.util.assert(file_data, "EditorModalNew.addFileToEditor", "Unable to find data to store file.");
    if (add_result_object) {
      resultObject = this.addNewResultObject(top_level_data);
      if (reselect_first_item) {
        this.object_list.setCurrentIdx(1);
        this.load();
      }
    }
    this.object_list.updateObjectInBrowser(this.object_list.getObjects().length - 1);
    if (file.getStatus() === "DONE") {
      eas_field_name = bulk_field.name();
      if (file_data[eas_field_name].length === 0) {
        file._value.preferred = true;
      }
      file_data[eas_field_name].push(file._value);
      if (this.editor_data.mapping) {
        if (bulk_field instanceof EASColumnLinkedObject) {
          pool = this.editor_data.linked_pool;
          if (!pool) {
            pool = this.editor_data["_pool_" + (bulk_field.getLinkedObject().fullName())];
          }
        } else {
          pool = this.editor_data._pool;
        }
        if (this.editor_data.linked_object_pools && pool) {
          ref3 = this.editor_data.linked_object_pools;
          for (linkedField in ref3) {
            linkedPool = ref3[linkedField];
            attr = "_pool_" + (this.editor_data.table.name()) + "." + linkedField;
            if (!this.editor_data[attr]) {
              this.editor_data[attr] = pool;
            }
          }
        }
        EAS.mapMetadata({
          data: object_top_level_data,
          eas_id: file._value._id,
          mask_name: bulk_field.getMainMask().name(),
          objecttype: bulk_field.getMainMask().table.name(),
          pool_id: pool != null ? pool.pool._id : void 0,
          mapping: this.editor_data.mapping,
          mapping_recipe_configs: this.editor_data.mapping_recipe_configs,
          editor: this
        }).done((function(_this) {
          return function(data) {
            var ref4;
            if (data != null ? (ref4 = data.result) != null ? ref4.mappingfail : void 0 : void 0) {
              if (_this.__metadataMappingProblemsCount == null) {
                _this.__metadataMappingProblemsCount = 0;
              }
              _this.__metadataMappingProblemsCount++;
              if (data.result.mappingErrors.length > 0) {
                if (_this.__metadataMappingProblems == null) {
                  _this.__metadataMappingProblems = [];
                }
                _this.__metadataMappingProblems = _this.__metadataMappingProblems.concat(data.result.mappingErrors);
              }
            }
            if (_this.__metadataMappingInProgress) {
              _this.__metadataMappingInProgress.done = Math.min(_this.__metadataMappingInProgress.done + 1, _this.__metadataMappingInProgress.count);
              _this.showWaitModal("mapping", {
                done: _this.__metadataMappingInProgress.done,
                count: _this.__metadataMappingInProgress.count
              }, null, true);
            }
            if (_this.isDestroyed()) {
              return;
            }
            _this.updateSaveButton();
            return dfr.resolve(resultObject);
          };
        })(this));
      } else {
        dfr.resolve(resultObject);
      }
    } else {
      bulk_field.uploadAdd(file_data, file);
      file._upload_field = bulk_field;
      file._top_level_data = top_level_data;
      file._object_top_level_data = object_top_level_data;
      file._file_data = file_data;
      dfr.resolve(resultObject);
    }
    this.updateSaveButton();
    return dfr.promise();
  };

  EditorModalNew.prototype.getMappingField = function() {
    var getEmptyLabel, metadataMappingProxyField, metadataUploadRight;
    if (ez5.session.hasSystemRight("root")) {
      metadataUploadRight = "standard";
    } else {
      metadataUploadRight = ez5.session.getSystemRight("frontend_features[metadata_upload]");
    }
    if (!metadataUploadRight) {
      return;
    }
    getEmptyLabel = (function(_this) {
      return function(msg) {
        delete _this.editor_data.mapping;
        return new CUI.Label({
          content: $empty$(msg),
          ui: "editor.modal.new.label:no_mapping"
        });
      };
    })(this);
    metadataMappingProxyField = new CUI.DataFieldProxy({
      maximize_horizontal: true,
      form: {
        label: $$("metadata.profile.mapping.label")
      },
      name: "_mapping",
      element: (function(_this) {
        return function() {
          var config_btn_opts, container, field, field_opts, opts;
          if (_this.editor_data.bulk_field === null) {
            return getEmptyLabel(_this.keyPrefix + ".field.none");
          }
          field_opts = {
            ui: "editor.modal.new.select:metadata_mapping",
            data: _this.editor_data,
            tooltip: {
              text: ez5.loca.str_default("editor.modal.new.mapping.tooltip")
            },
            onDataChanged: function() {
              _this.__updatePrefs();
              return _this.__updateMappingRecipeConfigButton();
            }
          };
          opts = {
            field_opts: field_opts,
            show_standard_option: true,
            show_only_standard: metadataUploadRight === "standard_only",
            mapping_filter: function(mapping) {
              if (!mapping.idTable) {
                return true;
              }
              return _this.editor_data.choice_table_id === mapping.idTable;
            }
          };
          field = ez5.metadata.getMappingField({
            exiftool_import: true
          }, opts);
          if (!field) {
            return getEmptyLabel(_this.keyPrefix + ".mapping.no_profile");
          }
          if (!_this.editor_data.hasOwnProperty("mapping")) {
            _this.editor_data.mapping = "standard";
          }
          _this.__mappingSelectField = field;
          if (!ez5.version("6") || ez5.metadata.getMetadataRecipesWithParams(true).length === 0) {
            return field.start();
          }
          config_btn_opts = {
            popover_placement: "w",
            only_usereditable: true,
            getMappingId: function() {
              return _this.editor_data.mapping;
            },
            onDataChanged: function() {
              return CUI.Events.trigger({
                type: "data-changed",
                node: _this.__mappingRecipeConfigButton
              });
            }
          };
          _this.__mappingRecipeConfigButton = ez5.metadata.getMappingRecipeConfigButton(_this.editor_data, config_btn_opts);
          _this.__updateMappingRecipeConfigButton();
          container = CUI.dom.div("ez5-mapping-field-with-config");
          container.appendChild(field.DOM);
          container.appendChild(_this.__mappingRecipeConfigButton.DOM);
          return container;
        };
      })(this)
    });
    return metadataMappingProxyField;
  };

  EditorModalNew.prototype.__updateMappingRecipeConfigButton = function() {
    if (!this.__mappingRecipeConfigButton) {
      return;
    }
    ez5.metadata.updateRecipeConfigButtonState(this.__mappingRecipeConfigButton, this.editor_data.mapping, true);
  };

  EditorModalNew.prototype.getPoolFieldHint = function() {
    return null;
  };

  EditorModalNew.prototype.getPoolField = function() {
    var idPool, opts, pool, poolField, poolSelector, pool_ids;
    if (this.editor_data.table.poolLink()) {
      poolField = new PoolFieldForEditor({
        hint: this.getPoolFieldHint()
      });
      pool_ids = this.editor_data.dbInfo.getPoolIds() || [];
      idPool = ez5.session.getPref("pool_id");
      if (!this.editor_data[poolField.name()] && idPool && CUI.util.inArray(idPool, pool_ids) && (pool = ez5.pools.findPoolById(idPool))) {
        this.editor_data[poolField.name()] = pool.getData();
      }
      opts = {
        ui: "editor.modal.new.select:pool",
        pool_ids: pool_ids,
        onDataChanged: (function(_this) {
          return function() {
            var poolId;
            if (!_this.editor_data[poolField.name()]) {
              _this.updateNextButton();
              return;
            }
            delete _this.editor_data.mask_name;
            poolId = _this.editor_data[poolField.name()].pool._id;
            ez5.session.setPref("pool_id", poolId);
            return _this.updateModalForm();
          };
        })(this)
      };
      poolSelector = poolField.renderEditorInput(this.editor_data, null, opts);
    } else {
      poolSelector = new CUI.DataFieldProxy({
        ui: "editor.modal.new.select:pool",
        "class": "ez5-pool-field-proxy",
        maximize_horizontal: true,
        form: {
          label: $$(this.keyPrefix + ".pool.label")
        },
        element: new CUI.Label({
          content: $empty$(this.keyPrefix + ".pool.none"),
          ui: "editor.modal.new.label:no_pool"
        })
      });
    }
    return poolSelector;
  };

  EditorModalNew.prototype.getLinkedPoolsCheckbox = function() {
    var ref;
    if (((ref = this.getLinkedObjectsWithPool()) != null ? ref.length : void 0) === 0) {
      return;
    }
    return {
      type: CUI.Checkbox,
      ui: "editor.modal.new.select:select_individual_pools",
      text: $$("editor.modal.new.select_individual_pools.label"),
      form: {
        hint: $$("editor.modal.new.select_individual_pools.label|hint")
      },
      data: this.editor_data,
      name: "select_individual_pools",
      onDataChanged: (function(_this) {
        return function() {
          var ref1;
          if (_this.editor_data.select_individual_pools && ((ref1 = _this.__linkedPoolsFields) != null ? ref1.isHidden() : void 0)) {
            _this.__linkedPoolsFields.show();
          } else {
            _this.__linkedPoolsFields.hide();
          }
        };
      })(this)
    };
  };

  EditorModalNew.prototype.getEASFieldLinkedPoolSelector = function() {
    var poolSelector;
    poolSelector = new CUI.DataFieldProxy({
      maximize_horizontal: true,
      form: {
        label: $$(this.keyPrefix + ".pool-linked-object.label")
      },
      name: "_pool_proxy",
      onRender: (function(_this) {
        return function(_field) {
          var field;
          field = _this.editor_data.bulk_field;
          if (!(field && field instanceof EASColumnLinkedObject && field.getLinkedObject().linkMask().table.poolLink())) {
            _field.hide(true);
            _this.editor_data["linked_pool_id"] = null;
            return;
          }
          _field.show(true);
        };
      })(this),
      element: (function(_this) {
        return function() {
          var dbInfo, element, field, linkTable, linkedObject;
          field = _this.editor_data.bulk_field;
          if (field && field instanceof EASColumnLinkedObject && field.getLinkedObject().linkMask().table.poolLink()) {
            linkedObject = field.getLinkedObject();
            linkTable = linkedObject.linkMask().table;
            dbInfo = field.getDbInfo();
            dbInfo.load({
              table: linkTable,
              ignore_not_found: true
            }).fail(function() {
              element.setContent($empty$(_this.keyPrefix + ".pool.none"));
              return element.setIcon(null);
            }).done(function() {
              var _linkedPoolSelector, fieldName, idPool, opts, pool, poolField, pool_ids, ref, ref1, standard_pool;
              pool_ids = dbInfo.getPoolIds() || [];
              fieldName = "_pool_" + (linkedObject.fullName());
              poolField = new PoolFieldForEditor({
                name: fieldName
              });
              idPool = ez5.session.getPref(fieldName);
              if (idPool && CUI.util.inArray(idPool, pool_ids) !== -1 && (pool = ez5.pools.findPoolById(idPool))) {
                _this.editor_data[poolField.name()] = pool.getData();
                _this.editor_data["linked_pool_id"] = (ref = pool.getData().pool) != null ? ref._id : void 0;
              }
              if (ez5.version("6") && !_this.editor_data[poolField.name()]) {
                standard_pool = _this.editor_data[fieldName] = ez5.pools.findPoolById(2);
                if (standard_pool) {
                  _this.editor_data[fieldName] = standard_pool.getData();
                  _this.editor_data["linked_pool_id"] = 2;
                } else {
                  if ((ref1 = _this.editor_data._pool) != null ? ref1.pool._id : void 0) {
                    _this.editor_data[fieldName] = _this.editor_data._pool;
                    _this.editor_data["linked_pool_id"] = _this.editor_data._pool.pool._id;
                  }
                }
              }
              opts = {
                pool_ids: pool_ids,
                onDataChanged: function() {
                  var poolId;
                  if (_this.editor_data[fieldName]) {
                    poolId = _this.editor_data[fieldName].pool._id;
                    ez5.session.savePref(fieldName, poolId);
                  }
                  return _this.updateNextButton();
                }
              };
              _linkedPoolSelector = poolField.renderEditorInput(_this.editor_data, null, opts);
              _linkedPoolSelector.start();
              CUI.dom.replace(element, _linkedPoolSelector);
              _this.updateNextButton();
            });
          }
          element = new LocaLabel({
            loca_key: _this.keyPrefix + ".pool.loading.label"
          });
          return element;
        };
      })(this)
    });
    return poolSelector;
  };

  EditorModalNew.prototype.getLinkedPoolsSelector = function() {
    var ref;
    delete this.editor_data.linked_object_pools;
    if (!((ref = this.getLinkedObjectsWithPool()) != null ? ref.length : void 0) > 0) {
      return;
    }
    this.__linkedPoolsFields = this.getPoolLinkedObjectFields();
    return this.__linkedPoolsFields;
  };

  EditorModalNew.prototype.getLinkedObjectsWithPool = function() {
    var _objecttype;
    if (!this.editor_data.table || !this.editor_data.mask_name) {
      return;
    }
    _objecttype = new Objecttype(this.editor_data.table);
    if (!this.editor_data.mask_name === '_all_fields') {
      _objecttype.addMask(Mask.getMaskByMaskName(this.editor_data.mask_name));
    } else {
      _objecttype.addMask(Mask.getMaskByMaskName("_all_fields", this.editor_data.table.schema.table_id));
    }
    return _objecttype.getAllFields("editor").filter((function(_this) {
      return function(field) {
        return field instanceof LinkedObject && field.linkMask().table.poolLink() && !(field instanceof TreeColumn);
      };
    })(this));
  };

  EditorModalNew.prototype.getPoolLinkedObjectFields = function() {
    var getPoolSelectors, linkedPoolsForm, updateLinkedPools;
    updateLinkedPools = (function(_this) {
      return function(fieldName, linkedObjectWithPool) {
        var poolData, pool_id, ref;
        if ((ref = _this.editor_data[fieldName]) != null ? ref.pool : void 0) {
          pool_id = _this.editor_data[fieldName].pool._id;
          poolData = {
            pool: {
              _id: pool_id
            }
          };
        } else {
          poolData = null;
        }
        return _this.editor_data.linked_object_pools[linkedObjectWithPool.fullName(false)] = poolData;
      };
    })(this);
    getPoolSelectors = (function(_this) {
      return function() {
        var fn1, j, len, linkedObjectWithPool, linkedObjectsWithPool, poolPromises, poolSelectors;
        linkedObjectsWithPool = _this.getLinkedObjectsWithPool();
        poolSelectors = [];
        poolPromises = [];
        _this.editor_data.linked_object_pools = {};
        if (!linkedObjectsWithPool) {
          return poolSelectors;
        }
        fn1 = function(linkedObjectWithPool) {
          var poolPromise, poolSelector;
          poolPromise = new CUI.Deferred();
          poolSelector = {
            type: CUI.DataFieldProxy,
            maximize_horizontal: true,
            form: {
              label: $$("editor.modal.new.linkedPools.label", {
                fieldName: linkedObjectWithPool.fullNameLocalized()
              })
            },
            name: linkedObjectWithPool.name(),
            element: function(df_proxy) {
              var dbInfo, element, linkTable;
              linkTable = linkedObjectWithPool.linkMask().table;
              dbInfo = new DbInfo();
              dbInfo.load({
                table: linkTable,
                ignore_not_found: true
              }).fail(function() {
                poolPromise.reject();
                element.setContent($empty$(_this.keyPrefix + ".pool.none"));
                return element.setIcon(null);
              }).done(function() {
                var _linkedPoolSelector, fieldName, opts, parentElement, poolField, pool_ids;
                pool_ids = dbInfo.getPoolIds() || [];
                if (pool_ids.length === 0) {
                  poolPromise.resolve();
                  df_proxy.hide(true);
                  df_proxy._hidden = true;
                  return;
                }
                fieldName = "_pool_" + (linkedObjectWithPool.fullName());
                _this.editor_data.linked_object_pools[linkedObjectWithPool.fullName(false)] = null;
                poolField = new PoolFieldForEditor({
                  name: fieldName
                });
                opts = {
                  placeholder: $$("pool.field.placeholder.linkedobjects.new"),
                  pool_ids: pool_ids,
                  onDataChanged: function() {
                    updateLinkedPools(fieldName, linkedObjectWithPool);
                    return _this.updateNextButton();
                  }
                };
                _linkedPoolSelector = poolField.renderEditorInput(_this.editor_data, null, opts);
                _linkedPoolSelector.start();
                updateLinkedPools(fieldName, linkedObjectWithPool);
                parentElement = CUI.dom.parent(element);
                if (!parentElement) {
                  return;
                }
                CUI.dom.replace(parentElement, _linkedPoolSelector);
                poolPromise.resolve();
                _this.updateNextButton();
              });
              element = new LocaLabel({
                loca_key: _this.keyPrefix + ".pool.loading.label"
              });
              return element;
            }
          };
          poolSelectors.push(poolSelector);
          return poolPromises.push(poolPromise.promise());
        };
        for (j = 0, len = linkedObjectsWithPool.length; j < len; j++) {
          linkedObjectWithPool = linkedObjectsWithPool[j];
          fn1(linkedObjectWithPool);
        }
        CUI.whenAll(poolPromises).done(function() {
          var ref;
          if (!_this.editor_data.select_individual_pools) {
            return (ref = _this.__linkedPoolsFields) != null ? ref.hide() : void 0;
          }
        });
        return poolSelectors;
      };
    })(this);
    linkedPoolsForm = new CUI.Form({
      name: "linked_object_pools",
      fields: getPoolSelectors()
    });
    return linkedPoolsForm;
  };

  EditorModalNew.prototype.getObjecttypeFieldOptions = function() {
    var correct, idx, j, len, opt, opts, ref, tb;
    opts = [];
    correct = false;
    ref = ez5.schema.CURRENT._objecttypes;
    for (idx = j = 0, len = ref.length; j < len; idx = ++j) {
      tb = ref[idx];
      if (!tb.in_main_search && !this.__showAllObjecttypes) {
        continue;
      }
      if (!this.__available_objecttypes[tb.table_id]) {
        continue;
      }
      opt = {
        value: tb.table_id,
        text: tb._name_localized
      };
      if (this.editor_data.choice_table_id && this.editor_data.choice_table_id === tb.table_id) {
        correct = true;
      }
      if (this.__showAllObjecttypes) {
        opt.right = new CUI.Label({
          text: (new Objecttype(tb)).getDisplayType(),
          appearance: "secondary"
        });
        if (tb.in_main_search) {
          opt.appearance = "important";
        }
      }
      opts.push(opt);
    }
    if (opts.length && (!this.editor_data.choice_table_id || !correct)) {
      this.editor_data.choice_table_id = opts[0].value;
      this.editor_data.table = null;
    }
    if (!this.editor_data.table && this.editor_data.choice_table_id) {
      this.editor_data.table = new Table("CURRENT", this.editor_data.choice_table_id);
    }
    return opts;
  };

  EditorModalNew.prototype.getObjecttypeField = function() {
    var df;
    df = new CUI.Select({
      ui: "editor.modal.new.select.objecttype",
      name: "choice_table_id",
      maximize_horizontal: true,
      form: {
        label: $$(this.keyPrefix + ".objecttype.label")
      },
      tooltip: {
        text: ez5.loca.str_default("editor.modal.new.objecttype.tooltip")
      },
      mark_changed: false,
      options: (function(_this) {
        return function(df, ev) {
          if (ev != null ? ev.altKey() : void 0) {
            _this.__showAllObjecttypes = true;
          }
          return _this.getObjecttypeFieldOptions();
        };
      })(this),
      onDataChanged: (function(_this) {
        return function() {
          delete _this.editor_data.mask_name;
          delete _this.editor_data._pool;
          delete _this.editor_data.bulk_field;
          _this.editor_data.table = new Table("CURRENT", _this.editor_data.choice_table_id);
          _this.__initPool();
          return _this.updateModalForm();
        };
      })(this),
      data: this.editor_data
    });
    return df;
  };

  EditorModalNew.prototype.getShowAllFieldsMask = function() {
    return true;
  };

  EditorModalNew.prototype.getMaskField = function() {
    var __selectDefaultMask, e, m, mfs;
    __selectDefaultMask = (function(_this) {
      return function() {
        return _this.editor_data.mask_name = _this.editor_data.dbInfo.availableMasks()[0].name();
      };
    })(this);
    try {
      m = Mask.getMaskByMaskName(this.editor_data.mask_name, this.editor_data.table.id());
      if (!CUI.util.isEmpty(this.editor_data.mask_name) && this.editor_data.mask_name !== "_all_fields") {
        if (m.getTable().id() !== this.editor_data.table.id()) {
          console.debug("Mask saved in prefs does not belong to the current table. Mask name '" + this.editor_data.mask_name + "', table id: " + (m.getTable().id()) + ", selecting default mask.");
          __selectDefaultMask();
        }
      }
    } catch (error) {
      e = error;
      console.debug("Mask saved in prefs is no longer available. Mask name '" + this.editor_data.mask_name + "'", e);
      __selectDefaultMask();
    }
    mfs = new MaskFieldSelector({
      ui: "editor.modal.new.select:mask",
      dbInfo: this.editor_data.dbInfo,
      select_opts: {
        maximize_horizontal: true
      },
      form: {
        label: $$(this.keyPrefix + ".mask.label")
      },
      mask_name: this.editor_data.mask_name,
      show_all_fields_mask: this.getShowAllFieldsMask(),
      onChanged: (function(_this) {
        return function(old_name, new_name) {
          _this.editor_data.mask_name = new_name;
          return _this.updateModalForm().fail(function() {
            return _this.editor_data.mask_name = old_name;
          });
        };
      })(this)
    });
    return mfs.getSelect();
  };

  EditorModalNew.prototype.getApiDbPriority = function() {
    return 2;
  };

  EditorModalNew.prototype.initEditorDataFields = function() {
    var fieldName, j, len, ref;
    ref = this.__getFieldNames();
    for (j = 0, len = ref.length; j < len; j++) {
      fieldName = ref[j];
      if (this.editor_data[fieldName] === void 0) {
        this.editor_data[fieldName] = ez5.session.getPref(fieldName);
      }
    }
    if (ez5.version("6")) {
      if (ez5.session.isDebug()) {
        this.editor_data["upload_without_produce_versions"] = ez5.session.getPref("upload_without_produce_versions");
      } else {
        this.editor_data["upload_without_produce_versions"] = false;
      }
    }
    if (this.editor_data["recognize_series"] === void 0) {
      this.editor_data["recognize_series"] = true;
    }
    this.editor_data["skip_new_modal_upload_step"] = ez5.session.getPref("skip_new_modal_upload_step");
  };

  EditorModalNew.prototype.__showUploadRPutFilesModal = function() {
    var applyButton, cancelButton, checkboxData, content, data, form, hintLabel, leaveCheckbox, modal, removeEmptyUrls, updateApplyButton;
    data = {};
    checkboxData = {
      leave: false
    };
    hintLabel = new CUI.Label({
      text: $$("editor.modal.new.rput.modal.form.hint"),
      "class": "cui-label-description",
      multiline: true
    });
    removeEmptyUrls = (function(_this) {
      return function() {
        var activeEl, changed, focusOnNewRow, focusedUrl, i, idx, input, inputs, j, len, ref, ref1, ref2, ref3, url;
        if (!((ref = data.urls) != null ? ref.length : void 0)) {
          return;
        }
        activeEl = document.activeElement;
        focusedUrl = null;
        focusOnNewRow = false;
        if (activeEl && form.DOM.contains(activeEl)) {
          inputs = form.DOM.querySelectorAll("[cui-data-field-name='url'] input");
          for (i = j = 0, len = inputs.length; j < len; i = ++j) {
            input = inputs[i];
            if (input === activeEl) {
              if ((ref1 = data.urls[i]) != null ? (ref2 = ref1.url) != null ? ref2.replace(/^\s+|\s+$/g, "") : void 0 : void 0) {
                focusedUrl = data.urls[i].url;
              } else {
                focusOnNewRow = true;
              }
              break;
            }
          }
        }
        changed = false;
        idx = data.urls.length - 1;
        while (idx >= 0) {
          url = (ref3 = data.urls[idx].url) != null ? ref3.replace(/^\s+|\s+$/g, "") : void 0;
          if (!url) {
            data.urls.splice(idx, 1);
            changed = true;
          }
          idx--;
        }
        if (changed) {
          form.reload();
          CUI.Events.trigger({
            type: "content-resize",
            node: form
          });
          return CUI.scheduleCallback({
            ms: 0,
            call: function() {
              var k, len1, ref4, results;
              inputs = form.DOM.querySelectorAll("[cui-data-field-name='url'] input");
              if (focusedUrl) {
                results = [];
                for (i = k = 0, len1 = inputs.length; k < len1; i = ++k) {
                  input = inputs[i];
                  if (((ref4 = data.urls[i]) != null ? ref4.url : void 0) === focusedUrl) {
                    input.focus();
                    break;
                  } else {
                    results.push(void 0);
                  }
                }
                return results;
              } else if (focusOnNewRow && inputs.length > 0) {
                return inputs[inputs.length - 1].focus();
              }
            }
          });
        }
      };
    })(this);
    updateApplyButton = (function(_this) {
      return function() {
        var _data, allValid, j, len, ref, ref1, ref2, url;
        if (!((ref = data.urls) != null ? ref.length : void 0)) {
          if (typeof applyButton !== "undefined" && applyButton !== null) {
            applyButton.disable();
          }
          return;
        }
        allValid = true;
        ref1 = data.urls;
        for (j = 0, len = ref1.length; j < len; j++) {
          _data = ref1[j];
          url = (ref2 = _data.url) != null ? ref2.replace(/^\s+|\s+$/g, "") : void 0;
          if (!url || !_this.__isValidUrl(url)) {
            allValid = false;
            break;
          }
        }
        if (allValid) {
          return typeof applyButton !== "undefined" && applyButton !== null ? applyButton.enable() : void 0;
        } else {
          return typeof applyButton !== "undefined" && applyButton !== null ? applyButton.disable() : void 0;
        }
      };
    })(this);
    form = new CUI.Form({
      data: data,
      onDataChanged: function() {
        CUI.Events.trigger({
          type: "content-resize",
          node: form
        });
        return updateApplyButton();
      },
      fields: [
        {
          type: CUI.DataForm,
          name: "urls",
          maximize_horizontal: true,
          fields: [
            {
              type: CUI.Input,
              name: "url",
              ui: "editor.modal.new.rput.form.url.input",
              placeholder: $$("editor.modal.new.rput.modal.form.url.placeholder"),
              checkInput: (function(_this) {
                return function(value) {
                  var trimmed;
                  trimmed = value != null ? value.replace(/^\s+|\s+$/g, "") : void 0;
                  if (!trimmed) {
                    return false;
                  }
                  return _this.__isValidUrl(trimmed);
                };
              })(this)
            }
          ]
        }
      ]
    });
    form.start();
    form.DOM.addEventListener("focusout", (function(_this) {
      return function() {
        return CUI.scheduleCallback({
          ms: 100,
          call: function() {
            removeEmptyUrls();
            return updateApplyButton();
          }
        });
      };
    })(this));
    content = CUI.dom.div();
    CUI.dom.append(content, hintLabel);
    CUI.dom.append(content, form);
    cancelButton = new CUI.Button({
      ui: "editor.modal.new.modal.button:rput_cancel",
      text: $$("base.cancel"),
      onClick: function() {
        return modal.destroy();
      }
    });
    leaveCheckbox = new CUI.Checkbox({
      data: checkboxData,
      name: "leave",
      text: $$("editor.modal.new.rput.modal.form.leave_original"),
      tooltip: {
        text: $$("editor.modal.new.rput.modal.form.leave_original.tooltip")
      }
    });
    leaveCheckbox.start();
    modal = new CUI.Modal({
      "class": "ez5-modal-new-rput",
      pane: {
        padded: true,
        header_left: new CUI.Label({
          text: $$("editor.modal.new.rput.modal.form.title"),
          ui: "editor.modal.new.modal.title:rput_eas"
        }),
        content: content,
        footer_left: leaveCheckbox,
        footer_right: [
          cancelButton, applyButton = new CUI.Button({
            text: $$("editor.modal.new.rput.modal.form.button.apply"),
            ui: "editor.modal.new.modal.button:rput_apply",
            left: true,
            primary: true,
            disabled: true,
            onClick: (function(_this) {
              return function(_, button) {
                var _data, alertMessage, filename, filesAdded, fn1, j, k, len, len1, parameters, promises, ref, ref1, url, urlsWithError, validUrls;
                validUrls = [];
                urlsWithError = [];
                ref = data.urls;
                for (j = 0, len = ref.length; j < len; j++) {
                  _data = ref[j];
                  url = (ref1 = _data.url) != null ? ref1.replace(/^\s+|\s+$/g, "") : void 0;
                  if (!url) {
                    continue;
                  }
                  if (!_this.__isValidUrl(url)) {
                    urlsWithError.push(url);
                    continue;
                  }
                  validUrls.push(url);
                }
                if (validUrls.length === 0 && urlsWithError.length === 0) {
                  modal.destroy();
                  return;
                }
                if (validUrls.length === 0 && urlsWithError.length > 0) {
                  alertMessage = $$("editor.modal.new.rput.modal.form.error-message", {
                    urls: urlsWithError
                  });
                  CUI.alert({
                    text: alertMessage
                  });
                  return;
                }
                cancelButton.disable();
                button.disable();
                button.startSpinner();
                promises = [];
                filesAdded = [];
                fn1 = function(url, parameters) {
                  var deferred, rputRequest;
                  rputRequest = function(params) {
                    return ez5.api.eas({
                      type: "POST",
                      api: "/rput?" + (CUI.encodeUrlData(params)),
                      handle_error: function() {
                        return true;
                      }
                    });
                  };
                  deferred = new CUI.Deferred();
                  rputRequest(parameters).done(function(files) {
                    if (!files) {
                      urlsWithError.push(url);
                    } else {
                      data = files[0];
                      data.__url = url;
                      filesAdded.push(data);
                    }
                    return deferred.resolve();
                  }).fail(function(response) {
                    var errorCode, ref2, retryParams;
                    errorCode = response != null ? (ref2 = response.responseJSON) != null ? ref2.code : void 0 : void 0;
                    if (errorCode === "EasRputErrorContentLength") {
                      retryParams = CUI.util.copyObject(parameters);
                      retryParams.skip_head_request = 1;
                      retryParams.filename = _this.__getFilename(url, true, ".png");
                      return rputRequest(retryParams).done(function(files) {
                        if (!files) {
                          urlsWithError.push(url);
                        } else {
                          data = files[0];
                          data.__url = url;
                          filesAdded.push(data);
                        }
                        return deferred.resolve();
                      }).fail(function() {
                        urlsWithError.push(url);
                        return deferred.resolve();
                      });
                    } else {
                      urlsWithError.push(url);
                      return deferred.resolve();
                    }
                  });
                  return promises.push(deferred.promise());
                };
                for (k = 0, len1 = validUrls.length; k < len1; k++) {
                  url = validUrls[k];
                  filename = _this.__getFilename(url);
                  parameters = {
                    url: url,
                    filename: ez5.version("6") ? null : filename,
                    token: ez5.session.token
                  };
                  if (checkboxData.leave) {
                    parameters.leave = 1;
                  }
                  fn1(url, parameters);
                }
                CUI.whenAll(promises).done(function() {
                  button.stopSpinner();
                  button.enable();
                  cancelButton.enable();
                  if (urlsWithError.length > 0) {
                    alertMessage = $$("editor.modal.new.rput.modal.form.error-message", {
                      urls: urlsWithError
                    });
                    CUI.alert({
                      text: alertMessage
                    });
                  }
                  if (filesAdded.length > 0) {
                    _this.__addRPutFiles(filesAdded);
                    return modal.destroy();
                  }
                });
              };
            })(this)
          })
        ]
      }
    });
    modal.show();
    CUI.Events.listen({
      type: "paste",
      node: CUI.dom.parent(modal),
      call: (function(_this) {
        return function(ev) {
          var j, len, pastedText, ref, trimmedUrl, url, urls;
          pastedText = (ref = ev.getNativeEvent().clipboardData) != null ? ref.getData("text/plain") : void 0;
          urls = pastedText != null ? pastedText.split(/\r?\n/g) : void 0;
          for (j = 0, len = urls.length; j < len; j++) {
            url = urls[j];
            trimmedUrl = url != null ? url.replace(/^\s+|\s+$/g, "") : void 0;
            if (!trimmedUrl || !_this.__isValidUrl(trimmedUrl)) {
              continue;
            }
            data.urls.push({
              url: CUI.parseLocation(trimmedUrl).href
            });
          }
          form.reload();
          updateApplyButton();
          CUI.Events.trigger({
            type: "content-resize",
            node: form
          });
        };
      })(this)
    });
  };

  EditorModalNew.prototype.__addRPutFiles = function(filesAdded) {
    var fileData, fn1, j, len;
    fn1 = (function(_this) {
      return function(fileData) {
        var asset, file, filename, lbl, removeButton, url;
        url = fileData.__url;
        file = {};
        file._value = fileData;
        file._template = new CUI.Template({
          name: "file-upload",
          map: {
            remove: true,
            info: true,
            thumb: true
          }
        });
        removeButton = new LocaButton({
          loca_key: "editor.modal.new.remove-button",
          ui: "editor.modal.file.remove.button",
          appearance: "flat",
          size: "mini",
          tooltip: {
            text: $$("editor.modal.new.remove-button|tooltip"),
            placement: "e"
          },
          onClick: function() {
            CUI.util.removeFromArray(file, _this.__files);
            CUI.util.removeFromArray(file, _this.__rPutFiles);
            _this.__updateNavigation();
            return _this.updateNextButton();
          }
        });
        file._template.append(removeButton, "remove");
        filename = _this.__getFilename(url, false);
        lbl = new CUI.Label({
          text: ez5.basename(filename),
          tooltip: {
            text: filename
          }
        });
        file._template.append(lbl, "info");
        asset = new AssetPlain({
          value: file._value
        });
        file._template.replace(asset.getImgElement(), "thumb");
        file.original_filename = filename;
        file.getStatus = function() {
          return "DONE";
        };
        file.getName = function() {
          return filename;
        };
        new CUI.Tooltip({
          element: file._template.DOM,
          text: function() {
            return filename;
          }
        });
        _this.__files.push(file);
        return _this.__rPutFiles.push(file);
      };
    })(this);
    for (j = 0, len = filesAdded.length; j < len; j++) {
      fileData = filesAdded[j];
      fn1(fileData);
    }
    this.__updateNavigation();
    this.updateNextButton();
  };

  EditorModalNew.prototype.__isValidUrl = function(url) {
    var parsedUrl, ref;
    try {
      parsedUrl = new URL(url);
      return (ref = parsedUrl.protocol) === "http:" || ref === "https:";
    } catch (error) {
      return false;
    }
  };

  EditorModalNew.prototype.__getFilename = function(url, decode, extension) {
    var addExtension, filename, getExtensionFromUrl, imageExtensions;
    if (decode == null) {
      decode = true;
    }
    if (extension == null) {
      extension = "";
    }
    imageExtensions = [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".tif", ".webp", ".svg"];
    getExtensionFromUrl = function(url) {
      var i, j, matches, ref, ref1, urlPath;
      urlPath = url.split("?")[0];
      matches = urlPath.match(/\.[a-zA-Z]{2,4}/g);
      if (matches) {
        for (i = j = ref = matches.length - 1; j >= 0; i = j += -1) {
          if (ref1 = matches[i].toLowerCase(), indexOf.call(imageExtensions, ref1) >= 0) {
            return matches[i].toLowerCase();
          }
        }
      }
      return null;
    };
    addExtension = function(filename) {
      var currentExt, urlExt;
      if (!extension) {
        return filename;
      }
      currentExt = filename.substring(filename.lastIndexOf(".")).toLowerCase();
      if (indexOf.call(imageExtensions, currentExt) >= 0) {
        return filename;
      }
      urlExt = getExtensionFromUrl(url);
      if (urlExt) {
        return filename + urlExt;
      }
      return filename + extension;
    };
    filename = url.substring(url.lastIndexOf("/") + 1);
    if (decode) {
      return addExtension(decodeURI(filename));
    } else {
      return addExtension(decodeURI(filename));
    }
    return filename;
  };

  return EditorModalNew;

})(EditorModalBulk);
// Generated by CoffeeScript 1.12.7
var DuplicatesDialog,
  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;

DuplicatesDialog = (function(superClass) {
  extend(DuplicatesDialog, superClass);

  function DuplicatesDialog() {
    return DuplicatesDialog.__super__.constructor.apply(this, arguments);
  }

  DuplicatesDialog.prototype.initOpts = function() {
    DuplicatesDialog.__super__.initOpts.call(this);
    this.removeOpt("text");
    this.removeOpt("title");
    this.removeOpt("markdown");
    this.removeOpt("html");
    return this.removeOpt("content");
  };

  DuplicatesDialog.prototype.readOpts = function() {
    this._text = " ";
    DuplicatesDialog.__super__.readOpts.call(this);
    this.__queue = [];
    return this.resetBatchChoice();
  };

  DuplicatesDialog.prototype.resetBatchChoice = function() {
    CUI.util.assert(this.__queue.length === 0, "DuplicatesDialog.startBatch", "Unable to start batch, queue not empty.");
    this.__batch_solution = null;
    this.__approved_in_batch = [];
    return this;
  };

  DuplicatesDialog.prototype.getBatchPromise = function() {
    if (this.__batch_dfr) {
      return this.__batch_dfr.promise();
    } else {
      return CUI.resolvedPromise();
    }
  };

  DuplicatesDialog.prototype.getQueue = function() {
    return this.__queue;
  };

  DuplicatesDialog.prototype.addFile = function(file) {
    var dfr, ignoreDuplication, ref;
    CUI.util.assert(file instanceof CUI.FileUploadFile && ((ref = file.getData()) != null ? ref[0]._id : void 0) > 0, "DuplicatesDialog.addFile", "file needs to be valid", {
      file: file
    });
    ignoreDuplication = ez5.session.getPref("ignore_duplicate_dialog");
    if (ignoreDuplication) {
      return CUI.resolvedPromise();
    }
    if (this.__queue.length === 0) {
      this.__batch_dfr = new CUI.Deferred();
    }
    dfr = new CUI.Deferred();
    dfr.always((function(_this) {
      return function(solution) {
        var item;
        item = _this.__queue.splice(0, 1)[0];
        if (solution !== "skip") {
          CUI.util.pushOntoArray(item.file.getData()[0]._id, _this.__approved_in_batch);
        }
        if (_this.__queue.length > 0) {
          return _this.processItem(_this.__queue[0]);
        } else {
          _this.__batch_dfr.resolve();
          return _this.__batch_dfr = null;
        }
      };
    })(this));
    this.__queue.push({
      deferred: dfr,
      file: file
    });
    if (this.__queue.length === 1) {
      this.processItem(this.__queue[0]);
    }
    return dfr.promise();
  };

  DuplicatesDialog.prototype.processItem = function(item) {
    var asset, buttons, cb, content, done, dup, dup_count, duplicate_label_links, duplicate_objects, duplicates_label_text, hl, i, idx, j, k, key, len, len1, len2, linked_obj, objLinkCallback, obj_id, pane, ref, ref1, ref2, value, vl;
    done = (function(_this) {
      return function(solution) {
        _this.hide();
        item.file._duplicates_solution = solution;
        if (DuplicatesDialog.form_data.apply_to_batch && !_this.__batch_solution) {
          _this.__batch_solution = solution;
        }
        switch (solution) {
          case "skip":
            item.deferred.reject(solution);
            break;
          default:
            item.deferred.resolve(solution);
        }
      };
    })(this);
    value = item.file.getData()[0];
    asset = new AssetPlain({
      value: value
    });
    dup_count = 0;
    duplicate_objects = [];
    if (value._duplicates) {
      ref = value._duplicates;
      for (i = 0, len = ref.length; i < len; i++) {
        dup = ref[i];
        if (CUI.util.idxInArray(dup._id, this.__approved_in_batch) > -1) {
          dup_count = dup_count + 1;
        } else if (dup.linked_system_objects.length > 0) {
          dup_count = dup_count + 1;
          if (ez5.version("6")) {
            ref1 = dup.linked_system_objects;
            for (j = 0, len1 = ref1.length; j < len1; j++) {
              linked_obj = ref1[j];
              duplicate_objects.push(linked_obj._system_object_id);
            }
          }
        }
      }
    }
    if (dup_count === 0) {
      done("import");
      return this;
    }
    if (this.__batch_solution) {
      done(this.__batch_solution);
      return this;
    }
    buttons = [
      {
        "class": 'ez5-duplicates-dialog-button-skip',
        text: $$("duplicates.dialog.button.skip"),
        ui: "duplicates.dialog.skip.button",
        secondary: true,
        onClick: (function(_this) {
          return function() {
            return done("skip");
          };
        })(this)
      }, {
        "class": 'ez5-duplicates-dialog-button-import',
        text: $$("duplicates.dialog.button.import"),
        ui: "duplicates.dialog.import.button",
        primary: true,
        onClick: (function(_this) {
          return function() {
            return done("import");
          };
        })(this)
      }
    ];
    hl = new CUI.HorizontalList({
      "class": "ez5-duplicates-dialog-duplicates",
      content: [asset.getImgElement()]
    });
    duplicate_label_links = null;
    if (duplicate_objects.length > 0) {
      duplicates_label_text = duplicate_objects.length > 1 ? $$("duplicates.dialog.object_links") : $$("duplicates.dialog.object_link");
      for (idx = k = 0, len2 = duplicate_objects.length; k < len2; idx = ++k) {
        obj_id = duplicate_objects[idx];
        if (idx > 0) {
          duplicates_label_text += ", ";
        }
        duplicates_label_text += " #" + obj_id;
      }
      objLinkCallback = function(matchedText, matchIndex, fullText) {
        var a, id;
        id = parseInt(matchedText.match(/#(\d+)/)[1], 10);
        a = CUI.dom.element("a");
        a.textContent = matchedText;
        a.onclick = (function(_this) {
          return function(e) {
            var pop, ro;
            e.preventDefault();
            ro = new ResultObject();
            return pop = ro.loadFromSystemObjectId(parseInt(id), "long").done(function() {
              return ro.showPopover({
                popover: {
                  element: a
                }
              });
            });
          };
        })(this);
        return a;
      };
      duplicate_label_links = new CUI.Label({
        "class": "ez5-duplicates-dialog-object-links",
        text: duplicates_label_text,
        multiline: true,
        text_node_func: (function(_this) {
          return function(text) {
            return CUI.Label.parseWithRegex(text, /#(\d+)/g, objLinkCallback);
          };
        })(this)
      });
    }
    vl = new CUI.VerticalList({
      content: [
        new CUI.Label({
          multiline: true,
          markdown: true,
          text: $$("duplicates.dialog.text" + (dup_count === 1 ? ".one" : ""), {
            count: dup_count,
            filename: CUI.MarkdownInput.escape(item.file.getFile().name)
          })
        }), hl, duplicate_label_links
      ]
    });
    cb = new CUI.Checkbox({
      text: $$("duplicates.dialog.checkbox.apply_to_batch"),
      name: "apply_to_batch",
      data: DuplicatesDialog.form_data
    }).start();
    pane = this.getPane();
    ref2 = {
      header_left: new LocaLabel({
        loca_key: "duplicates.dialog.title"
      }),
      content: vl,
      footer_right: buttons,
      footer_left: cb
    };
    for (key in ref2) {
      content = ref2[key];
      pane.replace(content, key);
    }
    this.show();
    return this;
  };

  DuplicatesDialog.form_data = {
    apply_to_batch: false
  };

  return DuplicatesDialog;

})(CUI.ConfirmationDialog);
// Generated by CoffeeScript 1.12.7
var EditorHeadlessNew,
  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;

EditorHeadlessNew = (function(superClass) {
  extend(EditorHeadlessNew, superClass);

  function EditorHeadlessNew() {
    return EditorHeadlessNew.__super__.constructor.apply(this, arguments);
  }

  EditorHeadlessNew.prototype.initOpts = function() {
    CUI.Element.prototype.initOpts.call(this);
    this.addOpts({
      collection: {
        check: Collection
      },
      data: {
        "default": {},
        check: "PlainObject"
      },
      hide_ignore_duplication_field: {
        check: Boolean,
        "default": false
      },
      show_update_object_fields: {
        check: Boolean,
        "default": false
      },
      filterObjecttypeOption: {
        check: Function
      }
    });
    return this.mergeOpt("mode", {
      "default": "new"
    });
  };

  EditorHeadlessNew.prototype.readOpts = function() {
    CUI.Element.prototype.readOpts.call(this);
    this.editor_data = this._data;
    if (this.editor_data.choice_table_id) {
      this.editor_data.table = new Table("CURRENT", this.editor_data.choice_table_id);
    }
    this.__collectionMode = "new";
    this.object_list = new ObjectList();
    return this.collection = this._collection;
  };

  EditorHeadlessNew.prototype.setCollectionMode = function(mode) {
    if (mode !== "new" && mode !== "update") {
      return;
    }
    return this.__collectionMode = mode;
  };

  EditorHeadlessNew.prototype.replaceModalForm = function(form) {
    CUI.dom.replace(this.__container, form.DOM);
    return this.__container;
  };

  EditorHeadlessNew.prototype.getSendDataUrl = function() {
    var url;
    url = EditorHeadlessNew.__super__.getSendDataUrl.call(this);
    if (this.collection && this.__collectionMode === "new") {
      url += "&collection=" + this.collection.getId();
    }
    return url;
  };

  EditorHeadlessNew.prototype.setModalFormContainer = function(__container) {
    this.__container = __container;
  };

  EditorHeadlessNew.prototype.reloadEditor = function() {};

  EditorHeadlessNew.prototype.setTableByName = function(tn) {
    this.editor_data.table = new Table("CURRENT", ez5.schema.CURRENT._table_by_name[tn].table_id);
    return this;
  };

  EditorHeadlessNew.prototype.setTags = function(tags) {
    return this.editor_data._tags = tags;
  };

  EditorHeadlessNew.prototype.setEASFieldByCollectionStoreName = function(eas_field_name) {
    this.editor_data.bulk_field = (function(_this) {
      return function() {
        var easFields, f, i, j, len, len1;
        if (CUI.util.isEmpty(eas_field_name)) {
          return null;
        }
        easFields = _this.getEASFields();
        for (i = 0, len = easFields.length; i < len; i++) {
          f = easFields[i];
          if (f.nameForCollectionSave() === eas_field_name) {
            return f;
          }
        }
        for (j = 0, len1 = easFields.length; j < len1; j++) {
          f = easFields[j];
          if (eas_field_name.indexOf('.') === -1 && f.name() === eas_field_name) {
            return f;
          }
        }
        return null;
      };
    })(this)();
    return this.editor_data.bulk_field;
  };

  EditorHeadlessNew.prototype.setMapping = function(mapping) {
    return this.editor_data.mapping = mapping;
  };

  EditorHeadlessNew.prototype.discardHasChanges = function() {};

  EditorHeadlessNew.prototype.updateNextButton = function() {};

  EditorHeadlessNew.prototype.addNewTemplateObject = function() {};

  EditorHeadlessNew.prototype.addNewResultObject = function(data, ro) {
    if (data == null) {
      data = {};
    }
    if (ro == null) {
      ro = new ResultObject();
    }
    ro = EditorHeadlessNew.__super__.addNewResultObject.call(this, data, ro);
    if (this.editor_data.table.poolLink()) {
      this.setPoolInObject(ro);
    }
    if (this.editor_data._tags) {
      ro.getData()._tags = this.editor_data._tags;
    }
    return ro;
  };

  EditorHeadlessNew.prototype.getWaitModalTitleLocaKeyPrefix = function() {
    if (this.__saveInProgress) {
      return EditorHeadlessNew.__super__.getWaitModalTitleLocaKeyPrefix.call(this);
    } else {
      return "main.editor.upload.";
    }
  };

  EditorHeadlessNew.prototype.initFileUpload = function() {};

  EditorHeadlessNew.prototype.getUploadButtons = function() {};

  EditorHeadlessNew.prototype.getShowAllFieldsMask = function() {
    return false;
  };

  EditorHeadlessNew.prototype.getTagsField = function() {
    var df, tsel;
    if (this.editor_data.table.hasTags()) {
      tsel = (new TagsFieldForEditor()).renderEditorInput(this.editor_data, this.editor_data, {
        editor: this
      });
      CUI.Events.listen({
        node: tsel,
        type: "editor-changed",
        call: function(ev) {
          return console.debug("data changed on tags");
        }
      });
      df = new CUI.DataFieldProxy({
        form: {
          label: $$(this.keyPrefix + ".tags.label")
        },
        element: tsel
      });
    } else {
      this.editor_data._tags = [];
      df = new CUI.DataFieldProxy({
        form: {
          label: $$(this.keyPrefix + ".tags.label")
        },
        element: $empty$(this.keyPrefix + ".tags.none")
      });
    }
    console.debug("getTagsField", df.DOM);
    return df;
  };

  EditorHeadlessNew.prototype.callback = function(status) {};

  EditorHeadlessNew.prototype.getIgnoreDuplicationField = function() {
    if (this._hide_ignore_duplication_field) {
      return;
    }
    return EditorHeadlessNew.__super__.getIgnoreDuplicationField.call(this);
  };

  EditorHeadlessNew.prototype.__getFormFields = function() {
    var check_update_policy, fields, hierarchyField;
    check_update_policy = function(data) {
      var bulk_field;
      if (ez5.version("6")) {
        bulk_field = data.bulk_field;
        if (bulk_field && bulk_field instanceof EASColumnLinkedObject && !(bulk_field != null ? bulk_field.insideNested() : void 0)) {
          bulk_field = bulk_field.getLinkedObject();
        }
        if (data.update_mode === "insert") {
          if (bulk_field != null ? bulk_field.insideNested() : void 0) {
            return data.update_policy = EditorModalNew.FILE_APPEND_TYPE_CREATE;
          } else {
            return data.update_policy = EditorModalNew.FILE_APPEND_TYPE_CREATE_PREFERRED;
          }
        } else if (bulk_field != null ? bulk_field.insideNested() : void 0) {
          return data.update_policy = EditorModalNew.FILE_APPEND_TYPE_CREATE;
        }
      }
    };
    fields = EditorHeadlessNew.__super__.__getFormFields.call(this);
    if (this._show_update_object_fields) {
      hierarchyField = this.getHierarchyLinkedObjectField();
      if (hierarchyField) {
        fields.push(hierarchyField);
      }
    }
    if (this._show_update_object_fields) {
      fields.push({
        type: CUI.Select,
        data: this.editor_data,
        form: {
          label: $$("editor.headless.new.update-object.update_mode.label")
        },
        name: "update_mode",
        options: function() {
          return ["insert", "update", "upsert"].map(function(key) {
            return {
              text: $$("editor.headless.new.update-object.update_mode.option." + key),
              value: key
            };
          });
        },
        onDataInit: function(field, data) {
          return check_update_policy(data);
        },
        onDataChanged: (function(_this) {
          return function(data, field) {
            var enable, i, key, len, ref;
            check_update_policy(data);
            enable = data.update_mode !== "insert";
            ref = ["update_search_field", "update_policy"];
            for (i = 0, len = ref.length; i < len; i++) {
              key = ref[i];
              field = field.getForm().getFieldsByName(key)[0];
              if (enable) {
                field.enable();
              } else {
                field.disable();
              }
            }
          };
        })(this)
      });
      fields.push({
        type: ez5.FieldSelector,
        data: this.editor_data,
        form: {
          label: $$("editor.headless.new.update-object.update_search_field.label")
        },
        placeholder: $$("editor.headless.new.update-object.update_search_field.placeholder"),
        objecttype_data_key: "choice_table_id",
        name: "update_search_field",
        store_value: "fullname",
        onDataInit: function(field, data) {
          if (data.update_mode === "insert") {
            field.disable();
          } else {
            field.enable();
          }
        },
        onDataChanged: (function(_this) {
          return function(data, field) {
            field.getForm().getFieldsByName("update_policy")[0].reload();
          };
        })(this),
        filter: function(field) {
          var i, len, pfield, ref;
          ref = field.getFieldPath();
          for (i = 0, len = ref.length; i < len; i++) {
            pfield = ref[i];
            if (pfield instanceof ReverseLinkedTable) {
              return false;
            }
          }
          return field instanceof TextColumn && !(field instanceof LocaTextColumn) && !(field instanceof PrimaryKeyColumn);
        }
      });
      fields.push({
        type: CUI.Select,
        data: this.editor_data,
        form: {
          label: $$("editor.headless.new.update-object.update_policy.label")
        },
        name: "update_policy",
        disabled: this.editor_data.update_mode === "insert",
        options: function(select) {
          var eas_field, isNested, options;
          eas_field = select.getData().bulk_field;
          if (eas_field && eas_field instanceof EASColumnLinkedObject && !(eas_field != null ? eas_field.insideNested() : void 0)) {
            eas_field = eas_field.getLinkedObject();
          }
          isNested = eas_field != null ? eas_field.insideNested() : void 0;
          options = [
            {
              text: $$("editor.headless.new.update-object.update_policy." + (isNested ? 'append' : 'create_version') + ".label"),
              value: EditorModalNew.FILE_APPEND_TYPE_CREATE
            }, {
              text: $$("editor.headless.new.update-object.update_policy.replace.label"),
              value: EditorModalNew.FILE_APPEND_TYPE_REPLACE,
              disabled: isNested
            }, {
              text: $$("editor.headless.new.update-object.update_policy.create_version_preferred.label"),
              value: EditorModalNew.FILE_APPEND_TYPE_CREATE_PREFERRED,
              disabled: isNested
            }, {
              text: $$("editor.headless.new.update-object.update_policy.refuse.label"),
              value: EditorModalNew.FILE_APPEND_TYPE_REFUSE,
              disabled: isNested
            }
          ];
          return options;
        }
      });
    }
    return fields;
  };

  EditorHeadlessNew.prototype.getHierarchyLinkedObjectFields = function() {
    var e, mask, results;
    if (!this.editor_data.table || !this.editor_data.mask_name) {
      return [];
    }
    try {
      mask = Mask.getMaskByMaskName(this.editor_data.mask_name, this.editor_data.table.id());
    } catch (error) {
      e = error;
      return [];
    }
    if (!mask) {
      return [];
    }
    results = [];
    mask.invokeOnFields('editor', true, (function(_this) {
      return function(f) {
        var childField, i, len, linkedTable, ref;
        if (f instanceof LinkedObject && !(f instanceof TreeColumn)) {
          try {
            linkedTable = f.linkMask().table;
            if (linkedTable.isHierarchy() && !linkedTable.isPolyhierarchy()) {
              ref = f.linkMask().getFields('editor');
              for (i = 0, len = ref.length; i < len; i++) {
                childField = ref[i];
                if (childField instanceof TextColumn) {
                  results.push({
                    linkedObject: f,
                    field: childField,
                    fullName: f.fullName() + "." + childField.fullName(),
                    label: f.fullNameLocalized() + " / " + childField.nameLocalized()
                  });
                }
              }
            }
          } catch (error) {
            e = error;
          }
        }
      };
    })(this));
    return results;
  };

  EditorHeadlessNew.prototype.getHierarchyLinkedObjectField = function() {
    var compatibleFields, found, i, item, len, options;
    compatibleFields = this.getHierarchyLinkedObjectFields();
    if (compatibleFields.length === 0) {
      this.editor_data.hierarchy_linked_object_field = null;
      return null;
    }
    options = [];
    options.push({
      text: $$("editor.headless.new.hierarchy_linked_object.option.none"),
      value: null
    });
    for (i = 0, len = compatibleFields.length; i < len; i++) {
      item = compatibleFields[i];
      options.push({
        text: item.label,
        value: item.fullName
      });
    }
    if (this.editor_data.hierarchy_linked_object_field) {
      found = compatibleFields.some((function(_this) {
        return function(item) {
          return item.fullName === _this.editor_data.hierarchy_linked_object_field;
        };
      })(this));
      if (!found) {
        this.editor_data.hierarchy_linked_object_field = null;
      }
    }
    return {
      type: CUI.Select,
      data: this.editor_data,
      form: {
        label: $$("editor.headless.new.hierarchy_linked_object.label"),
        hint: $$("editor.headless.new.hierarchy_linked_object.hint")
      },
      name: "hierarchy_linked_object_field",
      options: options
    };
  };

  EditorHeadlessNew.prototype.getObjecttypeFieldOptions = function(all_objecttypes) {
    var options, ref, valid;
    if (all_objecttypes == null) {
      all_objecttypes = false;
    }
    this.__showAllObjecttypes = all_objecttypes;
    options = EditorHeadlessNew.__super__.getObjecttypeFieldOptions.call(this);
    if (this._filterObjecttypeOption) {
      options = options.filter((function(_this) {
        return function(option) {
          return _this._filterObjecttypeOption(option);
        };
      })(this));
    }
    if ((((ref = this.editor_data) != null ? ref.choice_table_id : void 0) != null) && options.length > 0) {
      valid = options.some((function(_this) {
        return function(option) {
          return option.value === _this.editor_data.choice_table_id;
        };
      })(this));
      if (!valid) {
        this.editor_data.choice_table_id = options[0].value;
        this.editor_data.table = new Table("CURRENT", this.editor_data.choice_table_id);
      }
    }
    return options;
  };

  return EditorHeadlessNew;

})(EditorModalNew);
// Generated by CoffeeScript 1.12.7
var EditorHeadlessNewBaseConfig,
  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;

EditorHeadlessNewBaseConfig = (function(superClass) {
  extend(EditorHeadlessNewBaseConfig, superClass);

  function EditorHeadlessNewBaseConfig() {
    return EditorHeadlessNewBaseConfig.__super__.constructor.apply(this, arguments);
  }

  EditorHeadlessNewBaseConfig.prototype.initOpts = function() {
    EditorHeadlessNewBaseConfig.__super__.initOpts.call(this);
    this.addOpts({
      pool_hint: {
        check: String
      }
    });
    return this;
  };

  EditorHeadlessNewBaseConfig.prototype.__getFormFields = function() {
    return [this.getObjecttypeField(), this.getPoolField(), this.getMaskField(), this.getEASField(), this.getMappingField()];
  };

  EditorHeadlessNewBaseConfig.prototype.getTagsField = function() {};

  EditorHeadlessNewBaseConfig.prototype.getPoolFieldHint = function() {
    return this._pool_hint;
  };

  EditorHeadlessNewBaseConfig.getBaseConfigButton = function(pname, opts) {
    var button, editor_data, proxyField, setButtonStatus, showEditorModal;
    button = null;
    setButtonStatus = (function(_this) {
      return function(df) {
        var ref;
        if (!CUI.util.isEmpty((ref = df.getData()) != null ? ref[pname] : void 0)) {
          return button.setActive(true);
        } else {
          return button.setActive(false);
        }
      };
    })(this);
    editor_data = {};
    showEditorModal = function(pname, df) {
      var editor_wrapper, modal, new_editor, ref, ref1, set_eas;
      if (!CUI.util.isEmpty(df.getData()[pname]) && CUI.util.isEmpty(editor_data)) {
        editor_data.mapping = df.getData()[pname].mapping;
        editor_data.mask_name = ez5.mask.CURRENT._mask_by_id[df.getData()[pname].mask_id].name;
        editor_data.choice_table_id = (ref = ez5.schema.CURRENT._table_by_name[df.getData()[pname].objecttype]) != null ? ref.table_id : void 0;
        editor_data._create_objects = true;
        set_eas = df.getData()[pname].eas_field;
        if (df.getData()[pname].pool_id) {
          editor_data._pool = (ref1 = ez5.pools.findPoolById(df.getData()[pname].pool_id)) != null ? ref1.getData() : void 0;
        }
        if (ez5.version("6") && df.getData()[pname].mapping_recipe_configs) {
          editor_data.mapping_recipe_configs = df.getData()[pname].mapping_recipe_configs;
        }
      }
      new_editor = new EditorHeadlessNewBaseConfig({
        data: editor_data,
        pool_hint: $$("editor.headless.edit.create_object.pool_hint"),
        hide_ignore_duplication_field: true,
        filterObjecttypeOption: (function(_this) {
          return function(option) {
            var easFields, idTable, objecttype;
            if (opts.filterObjecttypeOption) {
              if (!opts.filterObjecttypeOption(option)) {
                return false;
              }
            }
            idTable = option.value;
            objecttype = new Objecttype(ez5.schema.CURRENT._table_by_id[idTable]);
            if (!objecttype) {
              return false;
            }
            objecttype.addAllMasks();
            if (objecttype.masks.length === 0) {
              return false;
            }
            easFields = objecttype.getEASFields("all");
            return easFields.length > 0;
          };
        })(this)
      });
      if (set_eas) {
        new_editor.setEASFieldByCollectionStoreName(set_eas);
        set_eas = null;
      }
      editor_wrapper = new CUI.dom.div();
      modal = new CUI.Modal({
        cancel: true,
        size: 'm',
        pane: {
          title: $$("editor.headless.new." + pname + ".title"),
          content: editor_wrapper,
          footer_right: [
            {
              text: $$("base.ok"),
              primary: true,
              onClick: function() {
                var bulk_field, createObjectData, linked_pool_id, ref2, ref3, ref4, ref5, ref6, ref7;
                createObjectData = {
                  mapping: editor_data.mapping || "standard",
                  pool_id: (ref2 = editor_data._pool) != null ? (ref3 = ref2.pool) != null ? ref3._id : void 0 : void 0,
                  objecttype: (ref4 = editor_data.table) != null ? ref4.name() : void 0,
                  mask_id: ez5.mask.CURRENT._mask_by_name[editor_data.mask_name].mask_id,
                  eas_field: (ref5 = editor_data.bulk_field) != null ? ref5.nameForCollectionSave() : void 0,
                  linked_object_pools: null
                };
                if (ez5.version("6")) {
                  createObjectData.mapping_recipe_configs = editor_data.mapping_recipe_configs || null;
                }
                bulk_field = editor_data.bulk_field;
                if (bulk_field && bulk_field instanceof EASColumnLinkedObject && bulk_field.getLinkedObject().linkMask().table.poolLink()) {
                  if (createObjectData.pool_id != null) {
                    linked_pool_id = createObjectData.pool_id;
                  } else {
                    linked_pool_id = (ref6 = ez5.pools.findPoolById(2) || ez5.pools.getList()[0]) != null ? (ref7 = ref6.getData().pool) != null ? ref7._id : void 0 : void 0;
                  }
                  createObjectData.linked_pool_id = linked_pool_id;
                }
                df.getData()[pname] = createObjectData;
                setButtonStatus(df);
                CUI.Events.trigger({
                  node: df,
                  type: "data-changed",
                  info: {
                    element: df
                  }
                });
                return modal.destroy();
              }
            }
          ]
        }
      });
      modal.show();
      new_editor.setModalFormContainer(editor_wrapper);
      new_editor.initDbInfo(false).done((function(_this) {
        return function(opts) {
          if (opts.length === 0) {

          } else {
            return new_editor.updateModalForm().done(function() {
              return modal.autoSize();
            });
          }
        };
      })(this));
    };
    proxyField = {
      type: CUI.DataFieldProxy,
      element: function(df) {
        button = new CUI.Button({
          icon: "fa-pencil",
          text_inactive: opts.text_inactive,
          text_active: opts.text_active,
          onClick: (function(_this) {
            return function(ev, button) {
              return showEditorModal(pname, df);
            };
          })(this)
        });
        return setButtonStatus(df);
      }
    };
    return proxyField;
  };

  EditorHeadlessNewBaseConfig.prototype.getObjecttypeFieldOptions = function(all_objecttypes) {
    if (all_objecttypes == null) {
      all_objecttypes = true;
    }
    return EditorHeadlessNewBaseConfig.__super__.getObjecttypeFieldOptions.call(this, all_objecttypes);
  };

  return EditorHeadlessNewBaseConfig;

})(EditorHeadlessNew);
// Generated by CoffeeScript 1.12.7
var EditorHeadlessDelete,
  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;

EditorHeadlessDelete = (function(superClass) {
  extend(EditorHeadlessDelete, superClass);

  function EditorHeadlessDelete() {
    return EditorHeadlessDelete.__super__.constructor.apply(this, arguments);
  }

  EditorHeadlessDelete.prototype.initOpts = function() {
    CUI.Element.prototype.initOpts.call(this);
    return this.addOpts({
      object_list: {
        mandatory: true,
        check: ObjectList
      },
      require_comment: {
        "default": true,
        mandatory: true,
        check: Boolean
      }
    });
  };

  EditorHeadlessDelete.prototype.readOpts = function() {
    EditorHeadlessDelete.__super__.readOpts.call(this);
    return this._mode = "bulk";
  };

  return EditorHeadlessDelete;

})(Editor);
// Generated by CoffeeScript 1.12.7
var EditorSidebar,
  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;

EditorSidebar = (function(superClass) {
  extend(EditorSidebar, superClass);

  function EditorSidebar() {
    this.openFullScreen = bind(this.openFullScreen, this);
    return EditorSidebar.__super__.constructor.apply(this, arguments);
  }

  EditorSidebar.prototype.initOpts = function() {
    EditorSidebar.__super__.initOpts.call(this);
    return this.addOpts({
      onCloseEditor: {
        check: Function
      },
      onSaveAndNew: {
        check: Function
      },
      sidebar: {
        mandatory: true,
        check: Sidebar
      }
    });
  };

  EditorSidebar.prototype.loadGlobalObjectId = function(gid) {
    return this._sidebar.allow_unload().done((function(_this) {
      return function() {
        return _this._sidebar.loadEditor({
          global_object_id: gid
        });
      };
    })(this));
  };

  EditorSidebar.prototype.showWaitBlock = function() {};

  EditorSidebar.prototype.getCloseButton = function() {
    return new LocaButton({
      ui: "asset-browser-editor-sidebar-cancel-editor-button",
      loca_key: "editor.sidebar.close_sidebar",
      onClick: (function(_this) {
        return function(ev) {
          return _this.doClose(ev).done(function(callback) {
            return _this.callback("cancel");
          });
        };
      })(this)
    });
  };

  EditorSidebar.prototype.getToolbarRightContent = function() {
    return new LocaButton({
      loca_key: "editor.button.pen",
      ui: "editor.sidebar.edit.button",
      active: true,
      onClick: (function(_this) {
        return function(ev) {
          return _this.doClose(ev).done(function(callback) {
            return _this.callback("closeEditor");
          });
        };
      })(this)
    });
  };

  EditorSidebar.prototype.getCancelEditorButton = function() {
    return new LocaButton({
      loca_key: "editor.button.cancel",
      ui: "editor.sidebar.cancel.button",
      onClick: (function(_this) {
        return function(ev) {
          return _this.doClose(ev).done(function(callback) {
            return _this.callback("closeEditor");
          });
        };
      })(this)
    });
  };

  EditorSidebar.prototype.getSaveAndNewButton = function() {
    if (!this.modeIs(["new"]) || !ez5.version("6")) {
      return null;
    }
    return this.saveAndNewButton = new LocaButton({
      loca_key: "editor.sidebar.button.save_and_new",
      ui: "editor.sidebar.save_and_new.button",
      disabled: true,
      primary: true,
      onClick: (function(_this) {
        return function(ev) {
          _this.__clearServerValidationErrors();
          if (_this.rememberMaskSplitterStates()) {
            _this.storeMaskSplitterStates();
          }
          return _this.doSave(ev).done(function(received_data, read_only) {
            return _this.callback("saveAndNew", received_data);
          }).fail(function(error) {
            var ref, ref1, validation_problems;
            if (ez5.version("6.7") && (error != null ? (ref = error.response) != null ? ref.code : void 0 : void 0) === "validation.plugin.error") {
              validation_problems = (ref1 = error.response.parameters) != null ? ref1.problems : void 0;
              return _this.__processSeverValidationProblems(validation_problems);
            }
          });
        };
      })(this)
    });
  };

  EditorSidebar.prototype.updateSaveButton = function() {
    EditorSidebar.__super__.updateSaveButton.call(this);
    if (this.saveAndNewButton) {
      if (this.saveButton.isEnabled()) {
        return this.saveAndNewButton.enable();
      } else {
        return this.saveAndNewButton.disable();
      }
    }
  };

  EditorSidebar.prototype.getMainPane = function() {
    this.mainPane = new CUI.VerticalLayout({
      "class": "ez5-editor-pane",
      top: {
        "class": "ez5-editor-asset-browser ez5-sidebar-asset-browser",
        flexHandle: {
          hidden: true,
          closed: true,
          state_name: "editor-sidebar-top"
        }
      }
    });
    this.__pullOutDiv = this.mainPane.top();
    this.__pullOutFlexHandle = this.mainPane.getFlexHandle("top");
    if (ez5.version("6") && this.opts.mode === "new") {
      CUI.dom.waitForDOMInsert({
        node: this.mainPane
      }).done((function(_this) {
        return function() {
          var dimensions, i, input, len, ref;
          ref = _this.mainPane.DOM.querySelectorAll(":is(input, textarea):enabled");
          for (i = 0, len = ref.length; i < len; i++) {
            input = ref[i];
            dimensions = input.getBoundingClientRect();
            if (dimensions.width && dimensions.height) {
              input.focus();
              break;
            }
          }
        };
      })(this));
    }
    return this.mainPane;
  };

  EditorSidebar.prototype.getCurrentTools = function() {
    var copyToolOpts, dfr, mask, onCopyToolRun, parentInfo, resolve, tools;
    copyToolOpts = {
      favorite: true,
      disabled: true,
      sort: "B:2"
    };
    onCopyToolRun = (function(_this) {
      return function(opts) {
        if (opts.copyAsTemplate) {
          return _this.object.copyAsTemplate();
        } else {
          return _this.callback("copy", opts);
        }
      };
    })(this);
    this.copyTool = Sidebar.getCopyTool(this.object, onCopyToolRun, copyToolOpts);
    tools = [];
    if (this.modeIsNot(["new"]) && this.object.getId() && this.object.getMask().isHierarchy()) {
      mask = this.object.getMask();
      parentInfo = mask.schema.system_fields.parent;
      if (parentInfo && !TreeColumn.isReadOnly(parentInfo)) {
        this.__createNewChildTool = new ToolboxTool({
          name: "editor.sidebar.create_new_child",
          loca_key: "editor.sidebar.button.create_new_child",
          sort: "B:3",
          disabled: true,
          run: (function(_this) {
            return function() {
              return _this.callback("createNewChild");
            };
          })(this)
        });
        tools.push(this.__createNewChildTool);
      }
    }
    if (this.changeHistoryAvailable()) {
      tools.push(new ToolboxTool({
        name: "detail.change-history",
        loca_key: "detail.sidebar.change-history.button",
        run: (function(_this) {
          return function() {
            return _this.renderChangeHistory();
          };
        })(this)
      }));
    }
    dfr = new CUI.Deferred();
    resolve = (function(_this) {
      return function() {
        if (_this.object.hasRight("delete") && _this.object.id()) {
          tools.push(new ToolboxTool({
            name: "editor.delete",
            sort: "B:5",
            loca_key: "tool.editor.delete",
            run: function() {
              return _this.deleteObjects();
            }
          }));
        }
        return dfr.resolve(tools);
      };
    })(this);
    if (this.modeIsNot(["new"]) && this._onCopy) {
      DbInfo.canCreate({
        objecttypes: [new Objecttype(this.editor_data.table)]
      }).done((function(_this) {
        return function() {
          return tools.push(_this.copyTool);
        };
      })(this)).always((function(_this) {
        return function() {
          return resolve();
        };
      })(this));
    } else {
      resolve();
    }
    return dfr.promise();
  };

  EditorSidebar.prototype.renderChangeHistory = function() {
    var ref, ref1;
    if (!((ref = this.__pane) != null ? ref.center() : void 0)) {
      return;
    }
    this.__cachedEditorPaneContent = CUI.dom.children(this.__pane.center())[0];
    if (!this.__historyObject || ((ref1 = this.__historyObject) != null ? ref1.changelog().length : void 0) === 0) {
      this.__toolbarBottom.hide();
      this.__paneFooter.hide();
      this.__pane.empty("center");
      this.__waitBlock.show();
      return ResultObject.loadFromGlobalObjectId(this.object.getGlobalObjectId(), "full").done((function(_this) {
        return function(resultObject) {
          _this.__historyObject = resultObject;
          _this.__waitBlock.hide();
          return _this.__renderHistoryBrowser();
        };
      })(this));
    } else {
      return this.__renderHistoryBrowser();
    }
  };

  EditorSidebar.prototype.closeHistoryBrowser = function() {
    this.__paneFooter.show();
    this.__toolbarBottom.show();
    this.__pane.replace(this.__cachedEditorPaneContent, "center");
    this.renderAssetBrowser();
    this.enableTools();
    return delete this.__cachedEditorPaneContent;
  };

  EditorSidebar.prototype.__renderHistoryBrowser = function() {
    var closeButton;
    this.disableTools();
    closeButton = new LocaButton({
      ui: "detail.sidebar.change_history.close.button",
      loca_key: "detail.sidebar.change-history.close.button",
      onClick: (function(_this) {
        return function() {
          return _this.closeHistoryBrowser();
        };
      })(this)
    });
    return this.__pane.replace(this.__historyObject.renderHistoryBrowser(closeButton, this), "center");
  };

  EditorSidebar.prototype.ignoreEvents = function() {
    return !this._sidebar.isShown();
  };

  EditorSidebar.prototype.openFullScreen = function() {
    var applied, editor_modal;
    applied = false;
    editor_modal = new EditorModalSingle({
      editor_sidebar: this,
      mode: this.getMode(),
      next_previous_global_object_ids: this.__next_previous_global_object_ids,
      sort: "B:1",
      onCancel: (function(_this) {
        return function() {
          var ref;
          editor_modal.destroy();
          if (applied) {
            return (ref = _this._onSave) != null ? ref.apply(_this, arguments) : void 0;
          } else {
            return _this.reloadEditor();
          }
        };
      })(this),
      onApply: (function(_this) {
        return function() {
          return applied = true;
        };
      })(this),
      onSaveReadOnly: (function(_this) {
        return function() {
          var ref;
          editor_modal.destroy();
          return (ref = _this._onSaveReadOnly) != null ? ref.apply(_this, arguments) : void 0;
        };
      })(this),
      onSave: (function(_this) {
        return function() {
          var ref;
          editor_modal.destroy();
          return (ref = _this._onSave) != null ? ref.apply(_this, arguments) : void 0;
        };
      })(this),
      onDelete: (function(_this) {
        return function() {
          var ref;
          editor_modal.destroy();
          return (ref = _this._onDelete) != null ? ref.apply(_this, arguments) : void 0;
        };
      })(this),
      onCopy: (function(_this) {
        return function(_, opts) {
          var i, len, ref, tool;
          editor_modal.destroy();
          _this.__openFullScreenAfterCopy = true;
          ref = _this.copyTool.getTools();
          for (i = 0, len = ref.length; i < len; i++) {
            tool = ref[i];
            if (tool.getName() === opts.toolName) {
              tool.run(opts);
            }
          }
        };
      })(this)
    });
    return editor_modal.open();
  };

  EditorSidebar.prototype.enableTools = function() {
    var ref;
    this.__toolsDisabled = false;
    return (ref = this.__toolsButton) != null ? ref.enable() : void 0;
  };

  EditorSidebar.prototype.disableTools = function() {
    var ref;
    this.__toolsDisabled = true;
    return (ref = this.__toolsButton) != null ? ref.disable() : void 0;
  };

  EditorSidebar.prototype.registerChangeHistoryEvent = function() {
    return CUI.Events.listen({
      type: "show-change-history",
      node: this.DOM,
      call: (function(_this) {
        return function(ev, info) {
          var ref;
          if (((ref = _this.object) != null ? typeof ref.getId === "function" ? ref.getId() : void 0 : void 0) === (info != null ? info.object_id : void 0)) {
            if (_this.__toolsDisabled) {
              return;
            }
            return _this.renderChangeHistory();
          }
        };
      })(this)
    });
  };

  EditorSidebar.prototype.render = function() {
    EditorSidebar.__super__.render.call(this);
    this.__paneHeader.replace([
      new CUI.Button({
        icon: "fa-expand",
        tooltip: {
          text: $$("editor.sidebar.button.fullscreen|favorite_tooltip")
        },
        onClick: (function(_this) {
          return function() {
            return _this.openFullScreen();
          };
        })(this)
      }), this.getCloseButton()
    ], "right");
    this.__toolbar.replace([this.getPullOutSwitch(), this.getMaskSelectPlaceholder()], "left");
    CUI.dom.addClass(this.__toolbar.DOM, "ez5-sidebar-toolbar ez5-editor-sidebar-toolbar");
    this.__paneFooter.replace(this.getNavigationPreviousNext(), "center");
    this.__paneFooter.replace([typeof this.getCancelEditorButton === "function" ? this.getCancelEditorButton() : void 0, typeof this.getSaveAndNewButton === "function" ? this.getSaveAndNewButton() : void 0, this.getSaveButton()], "right");
    this.registerChangeHistoryEvent();
    this.__pane.addClass("cui-pane--window");
    return this.__pane;
  };

  EditorSidebar.prototype.changeHistoryAvailable = function() {
    var ref;
    return ez5.session.hasSystemRight("root", "frontend_features[changelog]", "frontend_features[changelog_with_user]") && !((ref = this.object) != null ? typeof ref.getInstance === "function" ? ref.getInstance() : void 0 : void 0);
  };

  EditorSidebar.prototype.getSearch = function() {
    return this._sidebar.getSearch();
  };

  EditorSidebar.prototype.getHistoryBrowserButton = function() {
    return null;
  };

  EditorSidebar.prototype.rememberScrollPosition = function() {
    return true;
  };

  EditorSidebar.prototype.rememberMaskSplitterStates = function() {
    return true;
  };

  EditorSidebar.prototype.unfocus = function() {
    var ref;
    if ((ref = this.focusNavigationManager) != null) {
      ref.destroy();
    }
    return this.focusNavigationManager = null;
  };

  EditorSidebar.prototype.destroy = function() {
    delete this.closeEditorButton;
    this.unfocus();
    return EditorSidebar.__super__.destroy.call(this);
  };

  return EditorSidebar;

})(Editor);
// Generated by CoffeeScript 1.12.7
var EditorPopover,
  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;

EditorPopover = (function(superClass) {
  extend(EditorPopover, superClass);

  function EditorPopover() {
    return EditorPopover.__super__.constructor.apply(this, arguments);
  }

  EditorPopover.prototype.initOpts = function() {
    EditorPopover.__super__.initOpts.call(this);
    return this.addOpts({
      popover_element: {
        check: function(v) {
          return CUI.util.isContent(v);
        }
      }
    });
  };

  EditorPopover.prototype.getMainPane = function() {
    var p;
    p = new CUI.VerticalLayout({
      ui: "editor.popover.content",
      "class": "ez5-editor-pane"
    });
    return p;
  };

  EditorPopover.prototype.getEditorWrapper = function() {
    return this.__mainPane;
  };

  EditorPopover.prototype.callback = function(status, arg1) {
    this.popover.destroy();
    this.popover = null;
    return EditorPopover.__super__.callback.call(this, status, arg1);
  };

  EditorPopover.prototype.destroy = function() {
    var ref;
    EditorPopover.__super__.destroy.call(this);
    if ((ref = this.popover) != null) {
      ref.destroy();
    }
    this.popover = null;
    return this;
  };

  EditorPopover.prototype.triggerCallback = function(type) {
    var ref;
    switch (type) {
      case "editor-render-object":
        if ((ref = this.popover) != null) {
          ref.position();
        }
    }
    return EditorPopover.__super__.triggerCallback.call(this, type);
  };

  EditorPopover.prototype.render = function() {
    EditorPopover.__super__.render.call(this);
    this.__toolbar.replace([this.getMaskSelectPlaceholder()], "left");
    this.__paneHeader.replace([
      CUI.Pane.getToggleFillScreenButton(), new LocaButton({
        loca_key: "editor.popover.button.close",
        icon: "close",
        onClick: (function(_this) {
          return function(ev) {
            return _this.doClose(ev).done(function() {
              _this.popover.destroy();
              return _this.callback("cancel");
            });
          };
        })(this)
      })
    ], "right");
    this.__paneFooter.replace(this.getNavigationPreviousNext(), "center");
    this.__paneFooter.replace([
      new CUI.Buttonbar({
        buttons: [this.getDeleteButton(), this.getCopyButton()]
      }), this.getSaveButton()
    ], "right");
    return this.__pane;
  };

  EditorPopover.prototype.open = function() {
    var waitBlock;
    this.render();
    if (this._popover_element) {
      this.popover = new CUI.Popover({
        "class": "ez5-editor-popover",
        element: this._popover_element,
        backdrop: {
          policy: "modal"
        },
        placement: "w",
        pane: this.__pane
      });
    } else {
      this.popover = new CUI.Modal({
        fill_space: "both",
        pane: this.__pane
      });
    }
    waitBlock = new CUI.WaitBlock({
      element: this.__pane.center()
    }).show();
    this.popover.show();
    return this.load().done((function(_this) {
      return function() {
        waitBlock.destroy();
        _this.popover.autoSize();
        return Field.focusFirstTextField(_this.__pane.DOM, true);
      };
    })(this)).fail((function(_this) {
      return function() {
        return _this.popover.destroy();
      };
    })(this));
  };

  return EditorPopover;

})(Editor);
// Generated by CoffeeScript 1.12.7
var DbInfo,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

DbInfo = (function(superClass) {
  extend(DbInfo, superClass);

  function DbInfo() {
    return DbInfo.__super__.constructor.apply(this, arguments);
  }

  DbInfo.prototype.load = function(_opts) {
    var mode, opts;
    if (_opts == null) {
      _opts = {};
    }
    opts = CUI.Element.readOpts(_opts, "DBInfo.load", {
      table: {
        check: Table
      },
      pool_id: {
        check: function(v) {
          return v > 0;
        }
      },
      tag_ids: {
        check: function(v) {
          return CUI.util.isArray(v);
        }
      },
      object_ids: {
        check: function(v) {
          return v.length > 0;
        }
      },
      ignore_not_found: {
        check: Boolean
      }
    });
    this.request = {};
    if (opts.table) {
      this.__table = opts.table;
      this.request.objecttype = this.__table.name();
    }
    if (opts.object_ids) {
      this.request.object_ids = opts.object_ids;
      mode = "update";
    } else {
      mode = "create";
    }
    if (opts.pool_id) {
      this.request.pool_id = opts.pool_id;
    }
    if (opts.tag_ids) {
      this.request.tag_ids = opts.tag_ids;
    }
    return ez5.api.db_info({
      type: "POST",
      api: "/" + mode,
      data: {
        debug: "DbInfo.load"
      },
      json_data: this.request,
      handle_error: (function(_this) {
        return function(xhr) {
          var ref, ref1;
          if (!opts.ignore_not_found) {
            return;
          }
          if ((ref = xhr != null ? (ref1 = xhr.responseJSON) != null ? ref1.code : void 0 : void 0) === "error.user.no_masks_for_create" || ref === "NoMasksForCreate") {
            return true;
          }
        };
      })(this)
    }).done((function(_this) {
      return function(data1) {
        _this.data = data1;
        return _this.request._mode = mode;
      };
    })(this)).fail((function(_this) {
      return function(xhr) {
        return _this.data = null;
      };
    })(this));
  };

  DbInfo.prototype.sortPoolIds = function(pool_ids) {
    pool_ids.sort(function(a, b) {
      var a_name, a_pool, b_name, b_pool;
      a_pool = ez5.pools.findPoolById(a);
      b_pool = ez5.pools.findPoolById(b);
      if (a_pool) {
        a_name = a_pool.getSortName();
      } else {
        a_name = "zzz";
      }
      if (b_pool) {
        b_name = b_pool.getSortName();
      } else {
        b_name = "zzz";
      }
      return CUI.util.compareIndex(a_name, b_name);
    });
    return pool_ids;
  };

  DbInfo.prototype.getGeneratedRights = function() {
    if (!this.data) {
      return {};
    }
    return this.data._generated_rights;
  };

  DbInfo.prototype.getPoolIds = function(ot_name, filtered) {
    var found_ot, i, len, ot, ots, pool_ids, ref, ref1;
    if (filtered == null) {
      filtered = true;
    }
    if (this.request._mode === "create") {
      found_ot = null;
      ots = (ref = this.data) != null ? ref._available_objecttypes : void 0;
      if (ots) {
        for (i = 0, len = ots.length; i < len; i++) {
          ot = ots[i];
          if (ot.name === ot_name || !ot_name) {
            found_ot = ot;
            break;
          }
        }
      }
      if (!found_ot) {
        return false;
      }
      pool_ids = found_ot.pool_ids;
    } else {
      CUI.util.assert(!ot_name, "DbInfo.getPoolIds", "ot_name can only be given for mode 'create'.", {
        request: this.request,
        data: this.data,
        ot_name: ot_name
      });
      pool_ids = (ref1 = this.data) != null ? ref1._available_pools : void 0;
      if (!pool_ids) {
        return false;
      }
    }
    CUI.util.assert(CUI.util.isArray(pool_ids), "DbInfo.getPoolIds", "No correct data available, make sure you called .load with on table given.", {
      request: this.request,
      data: this.data
    });
    if (filtered) {
      return this.sortPoolIds(DbInfo.filterPoolIds(pool_ids));
    } else {
      return this.sortPoolIds(pool_ids);
    }
  };

  DbInfo.prototype.maskNameAvailable = function(mask_name) {
    var av_mask, i, len, ref;
    ref = this.availableMasks();
    for (i = 0, len = ref.length; i < len; i++) {
      av_mask = ref[i];
      if (av_mask.hideInEditor()) {
        continue;
      }
      if (av_mask.name() === mask_name) {
        return true;
      }
    }
    return false;
  };

  DbInfo.prototype.getAvailableObjecttypes = function() {
    var _ots, i, len, ot, ots, ref;
    _ots = (ref = this.data) != null ? ref._available_objecttypes : void 0;
    CUI.util.assert(_ots, "DbInfo.getAvailableObjecttypes", "No data available, make sure you called .load.", {
      request: this.request,
      data: this.data
    });
    ots = {};
    for (i = 0, len = _ots.length; i < len; i++) {
      ot = _ots[i];
      ots[ot._id] = ot;
    }
    return ots;
  };

  DbInfo.prototype.availableMasks = function(all_fields_preferred) {
    var av_masks, i, len, m, mask, ref;
    if (all_fields_preferred == null) {
      all_fields_preferred = true;
    }
    CUI.util.assert(this.__table, "DbInfo.availableMasks", "Table not set, make sure you called .load with table given.");
    av_masks = [];
    if (this.data._available_masks) {
      ref = this.data._available_masks;
      for (i = 0, len = ref.length; i < len; i++) {
        m = ref[i];
        mask = Mask.getMaskByMaskName(m.name, this.__table.id(), 'CURRENT', all_fields_preferred);
        if (mask.hideInEditor()) {
          continue;
        }
        av_masks.push(mask);
      }
    }
    return av_masks;
  };

  DbInfo.prototype.availableTagById = function(tagId) {
    var ref;
    return (ref = this.data._available_tags) != null ? ref.find((function(_this) {
      return function(arg) {
        var _id;
        _id = arg._id;
        return _id === tagId;
      };
    })(this)) : void 0;
  };

  DbInfo.prototype.availableTagIds = function() {
    var av_tag;
    if (this.data._available_tags) {
      return ((function() {
        var i, len, ref, results;
        ref = this.data._available_tags;
        results = [];
        for (i = 0, len = ref.length; i < len; i++) {
          av_tag = ref[i];
          results.push(av_tag._id);
        }
        return results;
      }).call(this)).sort(function(a, b) {
        return a - b;
      });
    } else {
      return null;
    }
  };

  DbInfo.filterPoolIds = function(pool_ids) {
    var i, len, pool_id, valid_pool_ids;
    valid_pool_ids = [];
    for (i = 0, len = pool_ids.length; i < len; i++) {
      pool_id = pool_ids[i];
      if (!ez5.pools.findPoolById(pool_id)) {
        console.warn("DbInfo.filterPoolIds: Pool #" + pool_id + " is allowed by DbInfo, but not readable. Check rightsmanagement for pool to have BAG_READ right.");
        continue;
      }
      valid_pool_ids.push(pool_id);
    }
    return valid_pool_ids;
  };

  DbInfo.__loadingGeneratedRights = {};

  DbInfo.loadGeneratedRights = function(_opts) {
    var dfr, gids, opts;
    opts = CUI.Element.readOpts(_opts, "DbInfo.loadGeneratedRights", {
      global_object_ids: {
        mandatory: true,
        check: function(v) {
          return CUI.util.isArray(v) && v.length > 0;
        }
      }
    });
    gids = opts.global_object_ids;
    if (gids.length === 1) {
      if (this.__loadingGeneratedRights[gids[0]]) {
        console.warn("Re-Using Deferred:", gids[0]);
        return this.__loadingGeneratedRights[gids[0]];
      }
    }
    dfr = new CUI.Deferred();
    ez5.api.search({
      data: {
        debug: "DbInfo.loadGeneratedRights"
      },
      json_data: {
        format: "short",
        generate_rights: true,
        search: [
          {
            type: "in",
            fields: ["_global_object_id"],
            "in": gids
          }
        ]
      }
    }).done((function(_this) {
      return function(data) {
        var generated_rights, gid, i, j, len, len1, obj, ref;
        generated_rights = {};
        ref = data.objects;
        for (i = 0, len = ref.length; i < len; i++) {
          obj = ref[i];
          generated_rights[obj._global_object_id] = obj._generated_rights;
        }
        for (j = 0, len1 = gids.length; j < len1; j++) {
          gid = gids[j];
          if (!generated_rights[gid]) {
            generated_rights[gid] = {};
          }
        }
        return dfr.resolve(generated_rights);
      };
    })(this)).fail((function(_this) {
      return function() {
        return dfr.reject();
      };
    })(this));
    if (gids.length === 1) {
      this.__loadingGeneratedRights[gids[0]] = dfr;
      dfr.always((function(_this) {
        return function() {
          return delete _this.__loadingGeneratedRights[gids[0]];
        };
      })(this));
    }
    return dfr.promise();
  };

  DbInfo.canDelete = function(opts) {
    opts.right = "delete";
    return this.__checkRight(opts);
  };

  DbInfo.canWrite = function(opts) {
    opts.right = "write";
    return this.__checkRight(opts);
  };

  DbInfo.__checkRight = function(_opts, right) {
    var dfr, gid, opts, ref;
    opts = CUI.Element.readOpts(_opts, "DbInfo.canWrite", {
      object: {
        mandatory: true,
        check: "PlainObject"
      },
      right: {
        mandatory: true,
        check: ["write", "delete"]
      }
    });
    dfr = new CUI.Deferred();
    if ((ref = opts.object._generated_rights) != null ? ref[opts.right] : void 0) {
      dfr.resolve();
    } else {
      gid = opts.object._global_object_id;
      DbInfo.loadGeneratedRights({
        global_object_ids: [gid]
      }).done((function(_this) {
        return function(generated_rights) {
          opts.object._generated_rights = generated_rights[gid];
          if (generated_rights[gid][opts.right]) {
            return dfr.resolve();
          } else {
            return dfr.reject();
          }
        };
      })(this)).fail(dfr.reject);
    }
    return dfr.promise();
  };

  DbInfo.canCreate = function(_opts) {
    var dbInfo, dfr, opts, ots;
    opts = CUI.Element.readOpts(_opts, "DbInfo.canCreate", {
      objecttypes: {
        mandatory: true,
        check: function(v) {
          var i, item, len;
          if (CUI.util.isArray(v)) {
            for (i = 0, len = v.length; i < len; i++) {
              item = v[i];
              if (!(item instanceof Objecttype)) {
                return false;
              }
            }
            return true;
          } else {
            return false;
          }
        }
      }
    });
    ots = opts.objecttypes || [];
    ots = ots.filter(function(ot) {
      return !ot.getInstance();
    });
    dfr = new CUI.Deferred();
    if (ots.length === 1) {
      ez5.api.db_info({
        api: "/create",
        json_data: {
          objecttype: ots[0].name(),
          tag_ids: null
        },
        handle_error: (function(_this) {
          return function(xhr) {
            var ref;
            if ((xhr != null ? (ref = xhr.responseJSON) != null ? ref.code : void 0 : void 0) === "error.user.no_masks_for_create") {
              return true;
            }
          };
        })(this)
      }).done((function(_this) {
        return function(data) {
          var ref, ref1, ref2, ref3, ref4, ref5;
          if (!data) {
            dfr.reject();
          }
          if ((ref = data._available_masks) != null ? ref.length : void 0) {
            dfr.resolve(data);
            return;
          }
          if ((ref1 = data._available_objecttypes) != null ? (ref2 = ref1[0]) != null ? ref2.pool_ids : void 0 : void 0) {
            if (DbInfo.filterPoolIds((ref3 = data._available_objecttypes) != null ? (ref4 = ref3[0]) != null ? ref4.pool_ids : void 0 : void 0).length > 0) {
              dfr.resolve(data);
            } else {
              dfr.reject();
            }
            return;
          }
          if ((ref5 = data._available_objecttypes) != null ? ref5[0] : void 0) {
            dfr.resolve(data);
          } else {
            dfr.reject();
          }
        };
      })(this)).fail((function(_this) {
        return function(xhr) {
          return dfr.reject();
        };
      })(this));
    } else {
      dbInfo = new DbInfo();
      dbInfo.load({
        ignore_not_found: true
      }).done((function(_this) {
        return function(data) {
          var ok, ot, ot_id, ot_names, ref, ref1;
          ot_names = (function() {
            var i, len, results;
            results = [];
            for (i = 0, len = ots.length; i < len; i++) {
              ot = ots[i];
              results.push(ot.name());
            }
            return results;
          })();
          ok = false;
          ref = dbInfo.getAvailableObjecttypes();
          for (ot_id in ref) {
            ot = ref[ot_id];
            if (ref1 = ot.name, indexOf.call(ot_names, ref1) >= 0) {
              ok = true;
              break;
            }
          }
          if (ok) {
            dfr.resolve(data);
          } else {
            dfr.reject();
          }
        };
      })(this)).fail(dfr.reject);
    }
    return dfr.promise();
  };

  return DbInfo;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var AssetCropTool,
  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;

AssetCropTool = (function(superClass) {
  extend(AssetCropTool, superClass);

  function AssetCropTool() {
    this.startCrop = bind(this.startCrop, this);
    this.assetDetailEvent = bind(this.assetDetailEvent, this);
    return AssetCropTool.__super__.constructor.apply(this, arguments);
  }

  AssetCropTool.prototype.initOpts = function() {
    AssetCropTool.__super__.initOpts.call(this);
    return this.addOpts({
      content: {
        check: function(v) {
          return CUI.dom.isNode(v);
        }
      },
      asset: {
        check: function(v) {
          return v instanceof Asset;
        }
      }
    });
  };

  AssetCropTool.prototype.readOpts = function() {
    var k, ref, v;
    this.opts.name = "crop";
    AssetCropTool.__super__.readOpts.call(this);
    this.__asset = this._asset;
    this.__content = this._content;
    ref = {
      name: "crop",
      loca_key: "asset.versions.tool.crop",
      run: (function(_this) {
        return function(ev, btn) {
          _this.btn = btn;
          if (_this.btn.isActive()) {
            _this.btn.deactivate();
            return _this.stopCrop();
          } else {
            _this.btn.activate();
            return _this.startCrop(true);
          }
        };
      })(this)
    };
    for (k in ref) {
      v = ref[k];
      this.opts[k] = v;
    }
    CUI.Events.listen({
      type: "asset-detail",
      node: this.__content,
      instance: this,
      call: (function(_this) {
        return function(ev, info) {
          var ref1, ref2;
          if (!((ref1 = _this.btn) != null ? ref1.isActive() : void 0)) {
            return;
          }
          if (info.tool instanceof Zoomer || info.tool instanceof ZoomerV2) {
            if ((ref2 = info.type) === "init" || ref2 === "destroy") {
              return _this.reload();
            }
          }
        };
      })(this)
    });
    CUI.Events.listen({
      type: "eas_update",
      node: this.__content,
      instance: this,
      call: (function(_this) {
        return function(ev, info) {
          var cmd, j, len, ref1, ref2, ts;
          ts = [];
          if ((ref1 = _this.imgDim) != null ? ref1.transform : void 0) {
            ref2 = _this.imgDim.transform;
            for (j = 0, len = ref2.length; j < len; j++) {
              cmd = ref2[j];
              for (k in cmd) {
                v = cmd[k];
                ts.push(k + ":" + v);
              }
            }
          }
          return _this.updateCropPos();
        };
      })(this)
    });
    CUI.Events.listen({
      type: "zoomer-scroll",
      node: this.__content,
      instance: this,
      call: (function(_this) {
        return function(ev, info) {
          CUI.globalDrag.startCoordinates.pageY += info.y;
          return CUI.globalDrag.startCoordinates.pageX += info.x;
        };
      })(this)
    });
    CUI.Events.listen({
      type: "viewport-resize",
      instance: this,
      call: (function(_this) {
        return function(ev, info) {
          return CUI.setTimeout({
            ms: 0,
            call: function() {
              return _this.resize();
            }
          });
        };
      })(this)
    });
    CUI.dom.waitForDOMRemove({
      node: this._content
    }).done((function(_this) {
      return function() {
        if (!_this.isDestroyed()) {
          return _this.destroy();
        }
      };
    })(this));
    return AssetCropTool.__super__.readOpts.call(this, this.opts);
  };

  AssetCropTool.prototype.destroy = function() {
    var ref;
    this.__movableInst = null;
    this.__resizableInst = null;
    CUI.Events.ignore({
      instance: this
    });
    this.stopCrop();
    if ((ref = this.btn) != null) {
      ref.deactivate();
    }
    this.cropDiv = null;
    return this.cropMapDiv = null;
  };

  AssetCropTool.prototype.getProduceTransform = function() {
    var ref;
    if ((ref = this.btn) != null ? ref.isActive() : void 0) {
      return {
        crop: {
          top: this.cropPos.y,
          left: this.cropPos.x,
          width: this.cropPos.w,
          height: this.cropPos.h
        }
      };
    } else {
      return null;
    }
  };

  AssetCropTool.prototype.assetDetailEvent = function(ev_type, info) {
    var ref, ref1;
    switch (ev_type) {
      case "fade-in":
      case "start":
        if ((ref = this.$btn) != null ? ref.hasClass("btn-primary") : void 0) {
          return this.startCrop();
        }
        break;
      case "fade-out":
        if ((ref1 = this.$btn) != null ? ref1.hasClass("btn-primary") : void 0) {
          return this.startCrop();
        }
    }
  };

  AssetCropTool.prototype.resize = function() {
    return this.updateCropPos();
  };

  AssetCropTool.prototype.updateCropPos = function() {
    var _v, arr, cmd, dir, from, i, j, k, lastCropPos, oldCropPos, oldImgDim, ref, ref1, ref2, to, turn_x_180, turn_y_180, turn_z_minus_90, v;
    if (!this.cropDiv) {
      return;
    }
    oldImgDim = CUI.util.copyObject(this.imgDim);
    oldCropPos = CUI.util.copyObject(this.cropPos);
    oldCropPos.view_w = oldImgDim.original_width;
    oldCropPos.view_h = oldImgDim.original_height;
    lastCropPos = CUI.util.copyObject(oldCropPos);
    this.initImgDim();
    turn_z_minus_90 = (function(_this) {
      return function() {
        _this.cropPos.x = lastCropPos.y;
        _this.cropPos.y = lastCropPos.view_w - lastCropPos.x - lastCropPos.w;
        _this.cropPos.w = lastCropPos.h;
        _this.cropPos.h = lastCropPos.w;
        _this.cropPos.view_w = lastCropPos.view_h;
        _this.cropPos.view_h = lastCropPos.view_w;
        return lastCropPos = CUI.util.copyObject(_this.cropPos);
      };
    })(this);
    turn_x_180 = (function(_this) {
      return function() {
        _this.cropPos.y = lastCropPos.view_h - lastCropPos.y - lastCropPos.h;
        return lastCropPos = CUI.util.copyObject(_this.cropPos);
      };
    })(this);
    turn_y_180 = (function(_this) {
      return function() {
        _this.cropPos.x = lastCropPos.view_w - lastCropPos.x - lastCropPos.w;
        return lastCropPos = CUI.util.copyObject(_this.cropPos);
      };
    })(this);
    if (oldImgDim.transform.length < this.imgDim.transform.length) {
      from = oldImgDim.transform.length;
      to = this.imgDim.transform.length - 1;
      arr = this.imgDim.transform;
      dir = 1;
    } else {
      from = oldImgDim.transform.length - 1;
      to = this.imgDim.transform.length;
      arr = oldImgDim.transform;
      dir = -1;
    }
    for (i = j = ref = from, ref1 = to, ref2 = dir; ref2 > 0 ? j <= ref1 : j >= ref1; i = j += ref2) {
      cmd = arr[i];
      for (k in cmd) {
        _v = cmd[k];
        if (CUI.util.isInteger(_v)) {
          v = _v * dir;
          while (v < 0) {
            v += 360;
          }
        } else {
          continue;
        }
        if (v === 0) {
          continue;
        }
        switch (k) {
          case "rotate-z":
            if (v === 270) {
              turn_z_minus_90();
            } else if (v === 180) {
              turn_z_minus_90();
              turn_z_minus_90();
            } else if (v === 90) {
              turn_z_minus_90();
              turn_z_minus_90();
              turn_z_minus_90();
            } else {
              CUI.util.assert(false, "AssetCropTool.updateCropPos", "Unable to perform rotate-z: " + v);
            }
            break;
          case "rotate-x":
            if (v === 180) {
              turn_x_180();
            } else {
              CUI.util.assert(false, "AssetCropTool.updateCropPos", "Unable to perform rotate-x: " + v);
            }
            break;
          case "rotate-y":
            if (v === 180) {
              turn_y_180();
            } else {
              CUI.util.assert(false, "AssetCropTool.updateCropPos", "Unable to perform rotate-y: " + v);
            }
        }
      }
    }
    return this.positionCrop();
  };

  AssetCropTool.prototype.getAssetElement = function() {
    return CUI.dom.matchSelector(this.__content, ".ez-asset")[0];
  };

  AssetCropTool.prototype.getZoomer = function() {
    var assetBrowser, zoomer;
    assetBrowser = CUI.dom.matchSelector(this.__content, ".cui-asset-browser")[0];
    zoomer = CUI.dom.data(assetBrowser, "element").getActiveTool();
    if (zoomer instanceof Zoomer || zoomer instanceof ZoomerV2) {
      return zoomer;
    } else {
      return null;
    }
  };

  AssetCropTool.prototype.initImgDim = function() {
    var dest_h, dest_w, marginLeft, marginTop, ref, ref1, rotate, viewport;
    viewport = {
      width: CUI.dom.width(this.__asset.getElement()),
      height: CUI.dom.height(this.__asset.getElement())
    };
    rotate = EAS.getRotateMapFromTransform(this.__asset.value.transform);
    this.imgDim = (ref = rotate.z) === 90 || ref === 270 ? {
      original_width: this.__asset.getHeight(),
      original_height: this.__asset.getWidth(),
      transform: this.__asset.value.transform.slice(0)
    } : {
      original_width: this.__asset.getWidth(),
      original_height: this.__asset.getHeight(),
      transform: this.__asset.value.transform.slice(0)
    };
    if (this.zoomer) {
      if (this.zoomer instanceof ZoomerV2) {
        this.imgDim.getMarginLeft = (function(_this) {
          return function() {
            return _this.zoomer.getPanX();
          };
        })(this);
        this.imgDim.getMarginTop = (function(_this) {
          return function() {
            return _this.zoomer.getPanY();
          };
        })(this);
      } else {
        this.imgDim.getMarginLeft = function() {
          return 0;
        };
        this.imgDim.getMarginTop = function() {
          return 0;
        };
      }
      this.imgDim.getZoom = (function(_this) {
        return function() {
          return _this.zoomer.getZoom();
        };
      })(this);
    } else {
      ref1 = ez5.fitRectangle(this.imgDim.original_width, this.imgDim.original_height, viewport.width, viewport.height), dest_w = ref1[0], dest_h = ref1[1], marginTop = ref1[2], marginLeft = ref1[3];
      this.imgDim.getMarginLeft = function() {
        return marginLeft;
      };
      this.imgDim.getMarginTop = function() {
        return marginTop;
      };
      this.imgDim.getZoom = (function(_this) {
        return function() {
          return dest_w / _this.imgDim.original_width;
        };
      })(this);
    }
    return this.imgDim;
  };

  AssetCropTool.prototype.getLimitRect = function() {
    return {
      min_x: 0,
      min_y: 0,
      min_w: 1,
      min_h: 1,
      max_x: this.imgDim.original_width,
      max_w: this.imgDim.original_width,
      max_y: this.imgDim.original_height,
      max_h: this.imgDim.original_height
    };
  };

  AssetCropTool.prototype.startCrop = function(initial) {
    var do_drag, start_drag;
    if (initial == null) {
      initial = false;
    }
    CUI.dom.remove(this.cropDiv);
    CUI.dom.remove(this.cropMapDiv);
    this.cropDiv = new CUI.Template({
      name: "asset-crop-tool"
    }).DOM;
    CUI.dom.hideElement(this.cropDiv);
    this.zoomer = this.getZoomer();
    this.initImgDim();
    if (this.zoomer) {
      this.zoomer.registerPlugin(this.zoomerPlugin = new AssetDetailPlugin({
        name: "crop",
        destroy: (function(_this) {
          return function() {
            delete _this.zoomer;
            return delete _this.cropMapDiv;
          };
        })(this),
        update: (function(_this) {
          return function() {
            return _this.positionCrop();
          };
        })(this)
      }));
      CUI.dom.append(this.zoomer.innerDiv, this.cropDiv);
      this.cropMapDiv = new CUI.Template({
        name: "asset-crop-tool"
      }).DOM;
      CUI.dom.hideElement(this.cropMapDiv);
      CUI.dom.append(this.zoomer.mapDiv, this.cropMapDiv);
    } else {
      CUI.dom.append(this.getAssetElement(), this.cropDiv);
    }
    if (!this.cropPos) {
      this.cropPos = {
        w: Math.round(this.imgDim.original_width / 2),
        h: Math.round(this.imgDim.original_height / 2)
      };
      this.cropPos.x = Math.round((this.imgDim.original_width - this.cropPos.w) / 2);
      this.cropPos.y = Math.round((this.imgDim.original_height - this.cropPos.h) / 2);
    }
    console.debug("startCrop", this, this.cropPos);
    start_drag = (function(_this) {
      return function(ev, $target, diff) {
        console.warn("start drag movable", ev, $target, diff);
        _this.cropPosStart = CUI.util.copyObject(_this.cropPos);
        return _this.cropPosStart.shiftKey = ev.shiftKey();
      };
    })(this);
    do_drag = (function(_this) {
      return function(ev, $target, diff, instance) {
        return _this.moveCropDiv(diff, instance);
      };
    })(this);
    this.__resizableInst = new CUI.Resizable({
      element: this.cropDiv,
      limitRect: (function(_this) {
        return function() {
          return _this.getLimitRect();
        };
      })(this),
      start_drag: start_drag,
      do_drag: do_drag
    });
    this.__movableInst = new CUI.Movable({
      element: this.cropDiv,
      limitRect: (function(_this) {
        return function() {
          return _this.getLimitRect();
        };
      })(this),
      start_drag: start_drag,
      do_drag: do_drag
    });
    this.positionCrop();
    CUI.dom.showElement(this.cropDiv);
    if (this.zoomer) {
      return CUI.dom.showElement(this.cropMapDiv);
    }
  };

  AssetCropTool.prototype.moveCropDiv = function(diff, instance) {
    var j, k, len, newPos, ref;
    if (!this.cropPosStart.shiftKey) {
      diff.x /= this.imgDim.getZoom();
      diff.y /= this.imgDim.getZoom();
    }
    if (CUI.globalDrag.resize) {
      newPos = instance.getResizePos(this.cropPosStart, diff);
    } else {
      newPos = {
        x: this.cropPosStart.x + diff.x,
        y: this.cropPosStart.y + diff.y,
        w: this.cropPosStart.w,
        h: this.cropPosStart.h
      };
      instance.limitRect(newPos, this.cropPosStart);
    }
    if (newPos.w < 10) {
      newPos.w = 10;
    }
    if (newPos.h < 10) {
      newPos.h = 10;
    }
    ref = ["x", "y", "w", "h"];
    for (j = 0, len = ref.length; j < len; j++) {
      k = ref[j];
      newPos[k] = Math.round(newPos[k]);
    }
    this.cropPos = newPos;
    return this.positionCrop();
  };

  AssetCropTool.prototype.getCropPosition = function() {
    return "+" + (Math.round(this.cropPos.x)) + "+" + (Math.round(this.cropPos.y));
  };

  AssetCropTool.prototype.getCropDimension = function() {
    return (Math.round(this.cropPos.w)) + "x" + (Math.round(this.cropPos.h));
  };

  AssetCropTool.prototype.positionCrop = function() {
    var pos_div;
    CUI.dom.matchSelector(this.cropDiv, ".asset-crop-tool-position span > span ")[0].textContent = this.getCropPosition();
    CUI.dom.matchSelector(this.cropDiv, ".asset-crop-tool-dimensions span > span")[0].textContent = this.getCropDimension();
    pos_div = (function(_this) {
      return function(div, zoom) {
        var bw;
        bw = Math.max(1, zoom);
        CUI.dom.setStyle(div, {
          top: Math.round(_this.imgDim.getMarginTop() + _this.cropPos.y * zoom),
          left: Math.round(_this.imgDim.getMarginLeft() + _this.cropPos.x * zoom),
          borderWidth: bw
        });
        return CUI.dom.setDimensions(div, {
          marginBoxWidth: Math.floor(_this.cropPos.w * zoom),
          marginBoxHeight: Math.floor(_this.cropPos.h * zoom)
        });
      };
    })(this);
    pos_div(this.cropDiv, this.imgDim.getZoom());
    if (this.zoomer) {
      return pos_div(this.cropMapDiv, this.zoomer.getMapZoom());
    }
  };

  AssetCropTool.prototype.stop = function() {
    return this.stopCrop();
  };

  AssetCropTool.prototype.stopCrop = function() {
    var ref;
    if ((ref = this.zoomerPlugin) != null) {
      ref.deregister();
    }
    this.zoomerPlugin = null;
    if (this.cropDiv) {
      CUI.dom.remove(this.cropDiv);
    }
    if (this.zoomer && this.cropMapDiv) {
      CUI.dom.remove(this.cropMapDiv);
    }
    this.cropDiv = null;
    this.cropMapDiv = null;
    return this.cropPos = null;
  };

  AssetCropTool.prototype.reload = function() {
    var original_height, original_width, pos, transform;
    if (!CUI.dom.isInDOM(this._content)) {
      return;
    }
    pos = this.cropPos;
    transform = this.imgDim.transform;
    original_width = this.imgDim.original_width;
    original_height = this.imgDim.original_height;
    this.stopCrop();
    this.cropPos = pos;
    this.startCrop();
    this.imgDim.transform = transform;
    this.imgDim.original_width = original_width;
    return this.imgDim.original_height = original_height;
  };

  AssetCropTool.prototype.getTool = function() {};

  return AssetCropTool;

})(ToolboxTool);
// Generated by CoffeeScript 1.12.7
var AssetVersionsEditorPlugin,
  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;

AssetVersionsEditorPlugin = (function(superClass) {
  extend(AssetVersionsEditorPlugin, superClass);

  function AssetVersionsEditorPlugin() {
    return AssetVersionsEditorPlugin.__super__.constructor.apply(this, arguments);
  }

  AssetVersionsEditorPlugin.prototype.initOpts = function() {
    AssetVersionsEditorPlugin.__super__.initOpts.call(this);
    return this.addOpts({
      assetVersions: {
        mandatory: true,
        check: function(v) {
          return v instanceof AssetVersions;
        }
      },
      asset: {
        mandatory: true,
        check: function(v) {
          return v instanceof Asset;
        }
      },
      content: {
        mandatory: true,
        check: function(v) {
          return CUI.dom.isNode(v);
        }
      }
    });
  };

  AssetVersionsEditorPlugin.prototype.readOpts = function() {
    AssetVersionsEditorPlugin.__super__.readOpts.call(this);
    this.__assetVersions = this._assetVersions;
    this.__asset = this._asset;
    return this.__content = this._content;
  };

  AssetVersionsEditorPlugin.prototype.getTools = function() {
    return [];
  };

  AssetVersionsEditorPlugin.prototype.getManager = function() {
    return this.__assetVersions;
  };

  AssetVersionsEditorPlugin.prototype.getAsset = function() {
    return this.__asset;
  };

  AssetVersionsEditorPlugin.prototype.getContent = function() {
    return this.__content;
  };

  AssetVersionsEditorPlugin.prototype.onRegister = function() {
    return this;
  };

  return AssetVersionsEditorPlugin;

})(CUI.Plugin);

ez5.session_ready(function() {
  return AssetVersions.plugins = new CUI.PluginRegistry({
    "class": AssetVersionsEditorPlugin
  });
});
// Generated by CoffeeScript 1.12.7
var AssetVersions,
  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;

AssetVersions = (function(superClass) {
  extend(AssetVersions, superClass);

  function AssetVersions() {
    return AssetVersions.__super__.constructor.apply(this, arguments);
  }

  AssetVersions.prototype.versions = [];

  AssetVersions.prototype.initOpts = function() {
    AssetVersions.__super__.initOpts.call(this);
    return this.addOpts({
      field: {
        mandatory: true,
        check: Field
      },
      data: {
        mandatory: true,
        check: "PlainObject"
      },
      object_data: {
        check: "PlainObject"
      },
      mode: {
        mandatory: true,
        "default": "editor",
        check: ["editor", "detail"]
      },
      done: {
        "default": function() {},
        check: Function
      }
    });
  };

  AssetVersions.prototype.readOpts = function() {
    var values;
    AssetVersions.__super__.readOpts.call(this);
    this.mode = this._mode;
    this.data = this._data;
    this.field = this._field;
    this.__done = this._done;
    this.toolInstances = [];
    this.__exclusiveToolActive = null;
    this.__tmpl = new CUI.Template({
      name: "asset-versions",
      init_flex_handles: true,
      map: {
        list: true,
        list_buttons: true,
        tools: true,
        preview: true,
        drag_hint: true,
        form: true,
        info: true
      }
    });
    this.list = this.__tmpl.map.list;
    this.content = this.__tmpl.map.preview;
    this.tools = this.__tmpl.map.tools;
    if (this.mode === "editor") {
      this.__tmpl.append(new CUI.Label({
        multiline: true,
        text: $$('asset.versions.list.label.drag_hint')
      }), 'drag_hint');
    }
    this.__currentLbl = new CUI.Label({
      text: $$('asset.versions.list.label.current')
    }).DOM;
    this.__additionalLbl = new CUI.Label({
      text: $$('asset.versions.list.label.additional')
    }).DOM;
    this.init();
    CUI.dom.setAttribute(this.__tmpl, "ui", "asset.versions.container");
    this.modal = new CUI.Modal({
      ui: "asset.versions.modal",
      "class": "ez5-asset-versions-editor-modal ez5-asset-versions-editor-modal--" + this.mode,
      fill_space: "both",
      cancel: true,
      onCancel: (function(_this) {
        return function() {
          CUI.Events.ignore({
            instance: _this
          });
          if (_this.mode === "detail") {
            return;
          }
          if (_this.hasChanges() || !_this.__fileUpload.isDone()) {
            return CUI.confirm({
              text: $$("asset.versions.modal.close_confirm")
            }).done(function() {
              return _this.__fileUpload.clear();
            });
          } else {

          }
        };
      })(this),
      pane: {
        content: this.__tmpl,
        header_left: new LocaLabel({
          loca_key: "asset_versions.title." + this.mode
        }),
        footer_right: (function(_this) {
          return function() {
            return _this.buttons();
          };
        })(this)
      }
    });
    this.modal.show();
    values = this.data[this.field.name()];
    this.__data = {};
    if (values) {
      this.__data[this.field.name()] = CUI.util.copyObject(values, true);
    } else {
      this.__data[this.field.name()] = [];
    }
    this.renderList();
    this.__startValue = JSON.stringify(this.getSaveData());
    this.__updateButtons();
    CUI.Events.listen({
      type: "click",
      node: this.modal,
      call: (function(_this) {
        return function(ev) {
          var $target, asset, version;
          $target = ev.getTarget();
          if ((version = CUI.dom.closest($target, ".asset-version"))) {
            asset = CUI.dom.data(version, "asset");
            return _this.focus(asset);
          }
        };
      })(this)
    });
  };

  AssetVersions.prototype.hasChanges = function() {
    if (!this.__startValue) {
      return false;
    } else if (this.__startValue !== JSON.stringify(this.getSaveData())) {
      return true;
    } else {
      return false;
    }
  };

  AssetVersions.prototype.getSaveData = function() {
    return this.saveTrimValues(this.getSaveValues());
  };

  AssetVersions.prototype.saveTrimValues = function(values) {
    var _v, _values, j, k, l, len, len1, ref, v;
    _values = [];
    for (j = 0, len = values.length; j < len; j++) {
      v = values[j];
      _v = {};
      ref = ["_id", "_export", "transform", "name", "preferred"];
      for (l = 0, len1 = ref.length; l < len1; l++) {
        k = ref[l];
        if (v.hasOwnProperty(k)) {
          if (k === "name" && v["name"] === "" && ez5.version("6")) {
            _v[k] = void 0;
            continue;
          }
          _v[k] = v[k];
        } else if (k === "name") {
          _v[k] = void 0;
        }
      }
      _values.push(_v);
    }
    return _values;
  };

  AssetVersions.prototype.getSaveValues = function() {
    var asset, j, len, ref, results;
    ref = this.versions;
    results = [];
    for (j = 0, len = ref.length; j < len; j++) {
      asset = ref[j];
      results.push(CUI.dom.data(asset, "asset").value);
    }
    return results;
  };

  AssetVersions.prototype.buttons = function() {
    if (this.mode === "detail") {
      this.__doneButton = new LocaButton({
        loca_key: "asset.versions.button.done",
        ui: "asset.versions.done.button",
        primary: true,
        onClick: (function(_this) {
          return function(ev) {
            _this.modal.destroy();
            return _this.__done();
          };
        })(this)
      });
      return [this.__doneButton];
    }
    this.__applyButton = new LocaButton({
      loca_key: "asset.versions.button.apply",
      ui: "asset.versions.apply.button",
      primary: true,
      onClick: (function(_this) {
        return function(ev) {
          if (ev.hasModifierKey()) {
            return;
          }
          _this.data[_this.field.name()] = _this.getSaveValues();
          _this.modal.destroy();
          return _this.__done();
        };
      })(this)
    });
    this.__produceButton = new LocaButton({
      loca_key: "asset.versions.button.produce",
      ui: "asset.versions.produce.button",
      secondary: true,
      disabled: true,
      left: true,
      onClick: (function(_this) {
        return function(ev) {
          var doProduce, produceInfo;
          produceInfo = _this.__getProduceTransform(_this.__produce_asset);
          doProduce = function(name, setAsPreferred) {
            if (setAsPreferred == null) {
              setAsPreferred = false;
            }
            _this.__produceButton.startSpinner();
            _this.__produceButton.disable();
            if ((produceInfo.frontend_producer != null) && (produceInfo.frontend_producer.produceFrontendVariant != null)) {
              return produceInfo.frontend_producer.produceFrontendVariant(name, _this.__produce_asset, setAsPreferred).always(function() {
                return _this.__produceButton.stopSpinner();
              }).fail(function() {
                return _this.__produceButton.enable();
              }).done(function() {
                var ref, ref1, ref2, ref3, ref4;
                if (_this.__exclusiveToolActive && (((ref = _this.__exclusiveToolActive.$btn) != null ? typeof ref.isActive === "function" ? ref.isActive() : void 0 : void 0) || ((ref1 = _this.__exclusiveToolActive.btn) != null ? typeof ref1.isActive === "function" ? ref1.isActive() : void 0 : void 0))) {
                  if ((ref2 = _this.__exclusiveToolActive.$btn) != null ? typeof ref2.isActive === "function" ? ref2.isActive() : void 0 : void 0) {
                    _this.__exclusiveToolActive.$btn.deactivate();
                  } else if ((ref3 = _this.__exclusiveToolActive.btn) != null ? typeof ref3.isActive === "function" ? ref3.isActive() : void 0 : void 0) {
                    _this.__exclusiveToolActive.btn.deactivate();
                  }
                  return (ref4 = _this.__exclusiveToolActive) != null ? typeof ref4.stop === "function" ? ref4.stop() : void 0 : void 0;
                }
              });
            } else {
              return _this.__produceAsset(ev, {
                id: _this.__produce_asset.value._id,
                name: name,
                transform: produceInfo.transform,
                setAsPreferred: setAsPreferred
              }).always(function() {
                return _this.__produceButton.stopSpinner();
              }).fail(function() {
                return _this.__produceButton.enable();
              }).done(function() {
                _this.__produce_asset.value.transform = [];
                return _this.updateAsset(_this.__produce_asset);
              });
            }
          };
          if (ev.hasModifierKey()) {
            doProduce("", false);
          } else {
            _this.__showProduceDialog().done(function(result) {
              return doProduce(result.name, result.setAsPreferred);
            });
          }
        };
      })(this)
    });
    return [this.__produceButton, this.__applyButton];
  };

  AssetVersions.prototype.__showProduceDialog = function() {
    var dfr, dialogData, form, modal, okButton;
    dfr = new CUI.Deferred();
    dialogData = {
      name: "",
      setAsPreferred: false
    };
    okButton = new LocaButton({
      loca_key: "asset.versions.button.produce",
      primary: true,
      onClick: (function(_this) {
        return function() {
          modal.destroy();
          return dfr.resolve(dialogData);
        };
      })(this)
    });
    form = new CUI.Form({
      data: dialogData,
      fields: [
        {
          type: CUI.Output,
          multiline: true,
          text: $$('asset.versions.button.produce.name_prompt.msg')
        }, {
          type: CUI.Input,
          name: "name",
          placeholder: $$('asset.versions.button.produce.name_prompt.placeholder')
        }, {
          type: CUI.Checkbox,
          name: "setAsPreferred",
          text: $$('asset.versions.button.produce.set_as_preferred')
        }
      ]
    });
    form.start();
    modal = new CUI.ConfirmationDialog({
      title: $$("asset.versions.button.produce|text"),
      cancel: true,
      content: form,
      buttons: [okButton],
      onCancel: (function(_this) {
        return function() {
          dfr.reject();
        };
      })(this)
    });
    modal.show();
    return dfr.promise();
  };

  AssetVersions.prototype.__produceAsset = function(ev, _opts) {
    var command, opts, ref;
    if (_opts == null) {
      _opts = {};
    }
    opts = CUI.Element.readOpts(_opts, 'AssetVersions.__produceAsset', {
      id: {
        check: function(v) {
          return v > 0;
        },
        mandatory: true
      },
      name: {
        check: String
      },
      transform: {
        check: function(v) {
          return (v != null ? v.length : void 0) > 0;
        },
        mandatory: true
      },
      setAsPreferred: {
        check: Boolean,
        "default": false
      }
    });
    command = {
      eas_parent_id: opts.id,
      transform: opts.transform
    };
    if (ev.hasModifierKey()) {
      console.debug(CUI.util.dump(command));
      return new CUI.Deferred().reject().promise();
    }
    if (ez5.version("6")) {
      command.obj_uuid = (ref = this._object_data) != null ? ref._uuid : void 0;
    }
    return EAS.postToProduce(command).done((function(_this) {
      return function(new_value) {
        var asset;
        new_value.preferred = false;
        if (_this.mode === "export") {
          new_value._export = true;
        }
        new_value.name = opts.name;
        asset = new Asset(_this.field, new_value);
        if (opts.setAsPreferred) {
          _this.prependAsset(asset);
          _this.setFirstVersionPreferred();
        } else {
          _this.appendAsset(asset);
        }
        return _this.focus(asset);
      };
    })(this));
  };

  AssetVersions.prototype.init = function() {
    var bb, dupDialog, uploder_btn;
    if (this.mode !== "editor") {
      CUI.dom.remove(this.__tmpl.map.list_buttons);
      return;
    }
    dupDialog = new DuplicatesDialog({
      ui: "asset.versions.duplicates.dialog"
    });
    this.__fileUpload = new CUI.FileUpload({
      url: ez5.eas.getUploadUrl(),
      onBeforeDone: (function(_this) {
        return function(file) {
          return dupDialog.addFile(file);
        };
      })(this),
      onAdd: (function(_this) {
        return function(file) {
          var value;
          value = _this.field.uploadAdd(_this.__data, file);
          file._asset = new Asset(_this.field, value);
          _this.appendAsset(file._asset);
          _this.setFirstVersionPreferred();
          _this.focus(file._asset);
          return _this.__updateButtons();
        };
      })(this),
      onUpdate: (function(_this) {
        return function() {
          return _this.__updateButtons();
        };
      })(this),
      onDone: (function(_this) {
        return function(file) {
          _this.field.uploadDone(_this.__data, file);
          return _this.__updateButtons();
        };
      })(this),
      onFail: (function(_this) {
        return function(file) {
          if (file.getStatus() === "FAILED") {
            EAS.presentUploadError(file);
          }
          _this.removeAsset(file._asset);
          return _this.__updateButtons();
        };
      })(this)
    });
    uploder_btn = new CUI.FileUploadButton({
      ui: "asset.versions.file_upload.button",
      fileUpload: this.__fileUpload,
      multiple: false,
      tooltip: {
        text: $$("asset.versions.button.upload|tooltip")
      },
      group: "one",
      icon: $$("asset.versions.button.upload|icon")
    });
    this.removeButton = new LocaButton({
      loca_key: "asset.versions.edit.button.remove",
      ui: "asset.versions.remove.button",
      group: "one",
      onClick: (function(_this) {
        return function(ev) {
          return _this.removeAsset(CUI.dom.data(_this.focused_version, "asset"));
        };
      })(this)
    });
    bb = new CUI.Buttonbar({
      buttons: [uploder_btn, this.removeButton],
      size: "big"
    });
    this.__tmpl.replace(bb, "list_buttons");
    return this;
  };

  AssetVersions.addTransform = function(_transform, rotateOffset, flipX, flipY) {
    var axes, i, j, l, len, len1, m, map, newTransforms, ref, rotate, rotation, rx, ry, rz, sY, transform;
    if (flipX == null) {
      flipX = 1;
    }
    if (flipY == null) {
      flipY = 1;
    }
    axes = ['rotate-z', 'rotate-x', 'rotate-y'];
    newTransforms = [];
    for (i = j = 0; j <= 2; i = ++j) {
      map = {};
      rotation = 0;
      for (l = 0, len = _transform.length; l < len; l++) {
        transform = _transform[l];
        if (transform.hasOwnProperty(axes[i])) {
          rotation = transform[axes[i]];
          break;
        }
      }
      map[axes[i]] = rotation;
      newTransforms.push(map);
    }
    rotate = newTransforms[0]['rotate-z'] + rotateOffset;
    if (rotate % 180 !== 0) {
      sY = flipY;
      flipY = flipX;
      flipX = sY;
    }
    newTransforms[0]['rotate-z'] = rotate % 360;
    newTransforms[1]['rotate-x'] = (newTransforms[1]['rotate-x'] + 90 * flipY - 90) % 360;
    newTransforms[2]['rotate-y'] = (newTransforms[2]['rotate-y'] + 90 * flipX - 90) % 360;
    rz = newTransforms[0]['rotate-z'];
    rx = newTransforms[1]['rotate-x'];
    ry = newTransforms[2]['rotate-y'];
    if (Math.abs(rz) === 180 && rx === -180 && ry === -180) {
      newTransforms = [];
    } else {
      ref = [2, 1, 0];
      for (m = 0, len1 = ref.length; m < len1; m++) {
        i = ref[m];
        if (newTransforms[i][axes[i]] === 0) {
          newTransforms.splice(i, 1);
        }
      }
    }
    return newTransforms;
  };

  AssetVersions.prototype.getTools = function(asset) {
    var add_transform, base_tools, crop_idx, crop_tool, head, i, j, l, len, len1, len2, len3, m, n, plugin, plugin_tools, ref, ref1, ref2, ref3, ref4, ref5, ref6, reset_tool, reset_transform, t, tail, tools, tools_all, update_reset_tool, value;
    if (!(asset != null ? (ref = asset.value) != null ? (ref1 = ref.versions) != null ? ref1.original : void 0 : void 0 : void 0) || (asset != null ? (ref2 = asset.value) != null ? (ref3 = ref2.versions) != null ? ref3.original.status : void 0 : void 0 : void 0) !== "done") {
      return [];
    }
    if (!asset.canProduceNewVersion(asset)) {
      return [];
    }
    value = asset.value;
    if (value.versions.original["class"] !== "image") {
      return [];
    }
    update_reset_tool = (function(_this) {
      return function() {
        return reset_tool.$btn.setEnabled(value.transform && value.transform.length > 0);
      };
    })(this);
    add_transform = (function(_this) {
      return function(rotateOffset, flipX, flipY) {
        var element;
        if (flipX == null) {
          flipX = 1;
        }
        if (flipY == null) {
          flipY = 1;
        }
        value.transform = AssetVersions.addTransform(value.transform, rotateOffset, flipX, flipY);
        element = CUI.dom.matchSelector(_this.content, ".ez5-asset-element-transform")[0];
        EAS.setTransformStyle(element, value.transform);
        update_reset_tool();
        _this.__updateButtons(asset);
        return CUI.Events.trigger({
          type: "eas_update",
          node: element,
          info: {
            asset: asset
          }
        });
      };
    })(this);
    reset_transform = (function(_this) {
      return function() {
        var element;
        value.transform = [];
        element = CUI.dom.matchSelector(_this.content, ".ez5-asset-element-transform ")[0];
        EAS.setTransformStyle(element, value.transform);
        update_reset_tool();
        _this.__updateButtons(asset);
        return CUI.Events.trigger({
          type: "eas_update",
          node: element,
          info: {
            asset: asset
          }
        });
      };
    })(this);
    crop_tool = new AssetCropTool({
      asset: asset,
      content: this.content
    });
    crop_tool.__exclusive_tool = true;
    reset_tool = new ToolboxTool({
      name: "reset",
      loca_key: "asset.versions.tool.reset",
      disabled: !value.transform || value.transform.length === 0,
      run: (function(_this) {
        return function(ev, $btn) {
          return reset_transform();
        };
      })(this)
    });
    base_tools = [
      new ToolboxTool({
        name: "rotate-left",
        loca_key: "asset.versions.tool.rotate_left",
        group: "rotate",
        run: (function(_this) {
          return function() {
            return add_transform(-90);
          };
        })(this)
      }), new ToolboxTool({
        name: "rotate-right",
        loca_key: "asset.versions.tool.rotate_right",
        group: "rotate",
        run: (function(_this) {
          return function() {
            return add_transform(90);
          };
        })(this)
      }), new ToolboxTool({
        name: "flip",
        loca_key: "asset.versions.tool.rotate_vertical",
        group: "mirror",
        run: (function(_this) {
          return function(ev, $btn) {
            return add_transform(0, 1, -1);
          };
        })(this)
      }), new ToolboxTool({
        name: "flop",
        loca_key: "asset.versions.tool.rotate_horizontal",
        group: "mirror",
        run: (function(_this) {
          return function(ev, $btn) {
            return add_transform(0, -1, 1);
          };
        })(this)
      }), crop_tool
    ];
    plugin_tools = [];
    ref5 = ((ref4 = AssetVersions.plugins) != null ? ref4.newPlugins({
      assetVersions: this,
      asset: asset,
      content: this.content
    }) : void 0) || [];
    for (j = 0, len = ref5.length; j < len; j++) {
      plugin = ref5[j];
      tools = (typeof plugin.getTools === "function" ? plugin.getTools() : void 0) || [];
      if (CUI.util.isArray(tools)) {
        for (l = 0, len1 = tools.length; l < len1; l++) {
          t = tools[l];
          if (t) {
            plugin_tools.push(t);
          }
        }
      } else if (tools) {
        plugin_tools.push(tools);
      }
    }
    for (m = 0, len2 = plugin_tools.length; m < len2; m++) {
      t = plugin_tools[m];
      if (t) {
        t.__is_plugin_tool = true;
      }
    }
    tools_all = null;
    if (plugin_tools.length > 0) {
      crop_idx = -1;
      for (i = n = 0, len3 = base_tools.length; n < len3; i = ++n) {
        t = base_tools[i];
        if (!((t != null ? (ref6 = t.opts) != null ? ref6.name : void 0 : void 0) === "crop")) {
          continue;
        }
        crop_idx = i;
        break;
      }
      if (crop_idx >= 0) {
        head = base_tools.slice(0, crop_idx + 1);
        tail = base_tools.slice(crop_idx + 1);
        tools_all = head.concat(plugin_tools).concat(tail);
      } else {
        tools_all = base_tools.concat(plugin_tools);
      }
    } else {
      tools_all = base_tools;
    }
    tools_all.push(reset_tool);
    return tools_all;
  };

  AssetVersions.prototype.renderTools = function(asset) {
    var bb, buttons, idx, j, l, len, len1, ref, ref1, tool;
    if (this.mode === "detail") {
      return;
    }
    buttons = [];
    if (asset !== this.__tools_for_asset) {
      this.destroyTools();
    }
    this.__tools_for_asset = asset;
    ref = this.getTools(asset);
    for (j = 0, len = ref.length; j < len; j++) {
      tool = ref[j];
      if (!tool) {
        continue;
      }
      idx = CUI.util.idxInArray(tool, this.toolInstances, function(a, b) {
        return a.getName() === b.getName();
      });
      if (idx === -1) {
        this.toolInstances.push(tool);
      } else {
        tool.destroy();
      }
    }
    ref1 = this.toolInstances;
    for (l = 0, len1 = ref1.length; l < len1; l++) {
      tool = ref1[l];
      if (!tool.$btn) {
        (function(_this) {
          return (function(tool) {
            var name, nameSplit, opts;
            opts = tool.getLabelKeys();
            name = tool.getName() || "";
            nameSplit = name.split(".").join("_");
            opts.ui = "asset.versions.toolbox.tool.button:" + nameSplit;
            opts.icon = tool.getIcon();
            opts.size = "big";
            opts.group = tool.getGroup();
            opts.disabled = tool.isDisabled();
            opts.onClick = function(ev, $btn) {
              var confirmAndSwitch, curr, isExclusive, ref2, ref3, res;
              isExclusive = tool.__is_plugin_tool || tool.__exclusive_tool;
              if (isExclusive) {
                curr = _this.__exclusiveToolActive;
                if (curr && curr !== tool && (((ref2 = curr.$btn) != null ? typeof ref2.isActive === "function" ? ref2.isActive() : void 0 : void 0) || ((ref3 = curr.btn) != null ? typeof ref3.isActive === "function" ? ref3.isActive() : void 0 : void 0))) {
                  confirmAndSwitch = function() {
                    var ref4, ref5;
                    if (curr != null ? (ref4 = curr.$btn) != null ? typeof ref4.isActive === "function" ? ref4.isActive() : void 0 : void 0 : void 0) {
                      curr.$btn.deactivate();
                    } else if (curr != null ? (ref5 = curr.btn) != null ? typeof ref5.isActive === "function" ? ref5.isActive() : void 0 : void 0 : void 0) {
                      curr.btn.deactivate();
                    }
                    if (curr != null) {
                      if (typeof curr.stop === "function") {
                        curr.stop();
                      }
                    }
                    tool.run(ev, $btn);
                    _this.__exclusiveToolActive = tool;
                    _this.__updateButtons(asset);
                  };
                  if (typeof tool.confirmSwitchFrom === "function") {
                    return tool.confirmSwitchFrom(curr, function(ok) {
                      if (ok) {
                        return confirmAndSwitch();
                      }
                    });
                  } else if (typeof tool.willActivateWithOtherPluginActive === "function") {
                    res = tool.willActivateWithOtherPluginActive(curr);
                    if ((res != null ? res.then : void 0) != null) {
                      return res.then(function(ok) {
                        if (ok) {
                          return confirmAndSwitch();
                        }
                      });
                    } else {
                      if (res === true) {
                        confirmAndSwitch();
                      }
                      return;
                    }
                  }
                  CUI.confirm({
                    text: $$("asset.versions.tool.exclusive.confirm")
                  }).done(function() {
                    return confirmAndSwitch();
                  });
                  return;
                }
                tool.run(ev, $btn);
                _this.__exclusiveToolActive = tool;
                _this.__updateButtons(asset);
                return;
              }
              tool.run(ev, $btn);
              return _this.__updateButtons(asset);
            };
            return tool.$btn = new LocaButton(opts);
          });
        })(this)(tool);
      }
      buttons.push(tool.$btn);
    }
    this.__updateButtons(asset);
    bb = new CUI.Buttonbar({
      buttons: buttons
    });
    this.__tmpl.replace(bb, "tools");
    return this;
  };

  AssetVersions.prototype.setFirstVersionPreferred = function() {
    var c, idx, j, len, ref;
    if (this.mode === "export") {
      return;
    }
    ref = this.versions;
    for (idx = j = 0, len = ref.length; j < len; idx = ++j) {
      c = ref[idx];
      CUI.dom.data(c, "asset").getValue().preferred = idx === 0;
    }
    return this.__updateButtons();
  };

  AssetVersions.prototype.destroy = function() {
    var ref;
    this.destroyTools();
    if ((ref = this.__tmpl) != null) {
      ref.destroy();
    }
    return this.modal.destroy();
  };

  AssetVersions.prototype.renderList = function() {
    var focus_asset, j, l, len, len1, ref, ref1, ref2, value;
    CUI.dom.empty(this.list);
    this.versions = [];
    if ((ref = this.removeButton) != null) {
      ref.disable();
    }
    CUI.Events.listen({
      type: "eas_update",
      node: this.list,
      call: (function(_this) {
        return function(ev, info) {
          return _this.updateAsset(info.asset);
        };
      })(this)
    });
    if (this.__data[this.field.name()]) {
      ref1 = this.__data[this.field.name()];
      for (j = 0, len = ref1.length; j < len; j++) {
        value = ref1[j];
        if (value.preferred) {
          focus_asset = this.appendAsset(new Asset(this.field, value));
        }
      }
      ref2 = this.__data[this.field.name()];
      for (l = 0, len1 = ref2.length; l < len1; l++) {
        value = ref2[l];
        if (!value.preferred) {
          this.appendAsset(new Asset(this.field, value));
        }
      }
    }
    if (this.mode === "editor") {
      new CUI.Sortable({
        element: this.list,
        selector: ".ez5-asset-versions-list-item",
        dragend: (function(_this) {
          return function() {
            return _this.addListLabels();
          };
        })(this),
        dragstop: (function(_this) {
          return function() {
            return _this.addListLabels();
          };
        })(this),
        sorted: (function(_this) {
          return function() {
            var i, len2, m, ref3, version;
            ref3 = _this.list.querySelectorAll(".ez5-asset-versions-list-item");
            for (i = m = 0, len2 = ref3.length; m < len2; i = ++m) {
              version = ref3[i];
              _this.versions[i] = version;
            }
            return _this.setFirstVersionPreferred();
          };
        })(this)
      });
    }
    if (focus_asset) {
      this.focus(focus_asset);
    }
  };

  AssetVersions.prototype.removeAsset = function(asset) {
    var version;
    version = this.findVersionByAsset(asset);
    if (!version) {
      return;
    }
    this.versions.splice(this.versions.indexOf(version), 1);
    CUI.dom.remove(version);
    if (this.versions.length === 0) {
      asset = null;
    } else {
      if (asset.value.preferred) {
        this.setFirstVersionPreferred();
      }
      asset = CUI.dom.data(this.versions[0], "asset");
    }
    this.__updateButtons();
    this.addListLabels();
    this.focus(asset);
  };

  AssetVersions.prototype.appendAsset = function(asset) {
    var ref, version;
    if ((ref = this.removeButton) != null) {
      ref.enable();
    }
    version = this.getVersionElement(asset);
    CUI.dom.append(this.list, version);
    this.__updateButtons();
    this.versions.push(version);
    this.addListLabels();
    return asset;
  };

  AssetVersions.prototype.prependAsset = function(asset) {
    var ref, version;
    if ((ref = this.removeButton) != null) {
      ref.enable();
    }
    version = this.getVersionElement(asset);
    CUI.dom.prepend(this.list, version);
    this.__updateButtons();
    this.versions.unshift(version);
    this.addListLabels();
    return asset;
  };

  AssetVersions.prototype.addListLabels = function() {
    this.removeListLabels();
    if (this.list.children.length > 1) {
      CUI.dom.insertChildAtPosition(this.list, this.__additionalLbl, 1);
    }
    return CUI.dom.insertChildAtPosition(this.list, this.__currentLbl, 0);
  };

  AssetVersions.prototype.removeListLabels = function() {
    CUI.dom.remove(this.__currentLbl);
    return CUI.dom.remove(this.__additionalLbl);
  };

  AssetVersions.prototype.updateAsset = function(asset) {
    var current_version, new_version;
    new_version = this.getVersionElement(asset);
    current_version = this.findVersionByAsset(asset);
    if (CUI.dom.hasClass(current_version, ez5.defaults.focusClass)) {
      this.focused_version = new_version;
      CUI.dom.addClass(new_version, ez5.defaults.focusClass);
      this.renderTools(asset);
    }
    CUI.dom.replaceWith(current_version, new_version);
    this.versions.splice(this.versions.indexOf(current_version), 1, new_version);
    return this.__updateButtons();
  };

  AssetVersions.prototype.findVersionByAsset = function(asset) {
    var c, j, len, ref;
    ref = this.versions;
    for (j = 0, len = ref.length; j < len; j++) {
      c = ref[j];
      if (CUI.dom.data(c, "asset") === asset) {
        return c;
      }
    }
    CUI.util.assert(false, "AssetVersions.findVersionByValue", "version not found in list", {
      list: this.list,
      asset: asset
    });
    return asset;
  };

  AssetVersions.prototype.__getProduceTransform = function(asset) {
    var from_tools, frontend_producer, j, len, ref, ref1, ti, trans, transform;
    transform = ((ref = asset.value.transform) != null ? ref.length : void 0) ? asset.value.transform.slice(0) : [];
    from_tools = false;
    frontend_producer = null;
    ref1 = this.toolInstances;
    for (j = 0, len = ref1.length; j < len; j++) {
      ti = ref1[j];
      trans = typeof ti.getProduceTransform === "function" ? ti.getProduceTransform(asset) : void 0;
      if (!trans) {
        continue;
      }
      if (trans.__frontend_produce) {
        frontend_producer = ti;
        from_tools = true;
        continue;
      }
      transform.push(trans);
      from_tools = true;
    }
    return {
      transform: transform,
      from_tools: from_tools,
      frontend_producer: frontend_producer
    };
  };

  AssetVersions.prototype.__updateButtons = function(asset) {
    var info, ref, ref1, ref2;
    if (this.mode === "detail") {
      return;
    }
    if (asset) {
      info = this.__getProduceTransform(asset);
      if (info.transform.length === 0 && !info.frontend_producer) {
        this.__produceButton.disable();
      } else {
        this.__produceButton.enable();
        this.__produce_asset = asset;
      }
      if (info.from_tools) {
        this.__applyButton.disable();
        return this;
      }
    }
    if (!this.__fileUpload.isDone()) {
      if ((ref = this.removeButton) != null) {
        ref.disable();
      }
      this.__applyButton.disable();
      return this;
    }
    if (this.versions.length <= 1) {
      if ((ref1 = this.removeButton) != null) {
        ref1.disable();
      }
    } else {
      if ((ref2 = this.removeButton) != null) {
        ref2.enable();
      }
    }
    if (this.hasChanges()) {
      this.__onlyThumbnailChange = false;
      this.__applyButton.enable();
    } else {
      this.__applyButton.disable();
    }
    return this;
  };

  AssetVersions.prototype.getVersionElement = function(asset) {
    var date_uploaded_key, div, hl, ref, rows;
    CUI.util.assert(asset instanceof Asset, "AssetVersions.getVersionElement", "asset must be instance of Asset", {
      asset: asset
    });
    if (asset.value.eas_parent_id) {
      date_uploaded_key = "asset.versions.label.version_date_uploaded";
    } else {
      date_uploaded_key = "asset.versions.label.date_uploaded";
    }
    div = CUI.dom.element("DIV", {
      "class": "ez5-asset-versions-list-item asset-version"
    });
    CUI.dom.setAttribute(div, "ui", "asset.versions.list.item");
    hl = asset.renderDetailOutput();
    div.appendChild(hl.DOM);
    rows = [];
    if (asset.value.date_uploaded) {
      rows.push({
        key: $$(date_uploaded_key),
        value: ez5.format_date_and_time(asset.value.date_uploaded)
      });
    }
    if (((ref = asset.value.name) != null ? ref.trim().length : void 0) > 0) {
      rows.push({
        key: $$("asset.versions.label.name"),
        value: asset.value.name
      });
    }
    if (rows.length > 0) {
      div.appendChild(new CUI.Table({
        "class": "ez5-asset-versions-list-item-more-info",
        flex: true,
        rows: rows,
        key_value: true
      }).DOM);
    }
    CUI.dom.data(div, "asset", asset);
    return div;
  };

  AssetVersions.prototype.destroyTools = function() {
    var j, len, ref, ti;
    ref = this.toolInstances;
    for (j = 0, len = ref.length; j < len; j++) {
      ti = ref[j];
      if (typeof ti.destroy === "function") {
        ti.destroy();
      }
    }
    this.toolInstances = [];
    CUI.dom.empty(this.tools);
    return this;
  };

  AssetVersions.prototype.renderForm = function(asset) {
    var fields, form;
    fields = [];
    switch (this.mode) {
      case "export":
        fields.push({
          type: CUI.Checkbox,
          ui: "asset.versions.export.checkbox",
          form: {
            label: $$("asset.versions.label.export")
          },
          name: "_export"
        });
        break;
      case "editor":
        fields.push({
          type: CUI.Input,
          form: {
            label: $$("asset.versions.label.name")
          },
          ui: "asset.versions.name.label:editor",
          placeholder: $$("asset.versions.label.name.placeholder"),
          name: "name",
          maxLength: 30
        });
        break;
      case "detail":
        if (!CUI.util.isEmpty(asset.value.name)) {
          fields.push({
            type: CUI.Output,
            ui: "asset.versions.name.label:detail",
            form: {
              label: $$("asset.versions.label.name")
            },
            name: "name"
          });
        }
    }
    if (fields.length === 0) {
      return null;
    }
    return form = new CUI.Form({
      padded: true,
      maximize_horizontal: true,
      onDataChanged: (function(_this) {
        return function() {
          return _this.__updateButtons();
        };
      })(this),
      data: asset.value,
      fields: fields
    }).start();
  };

  AssetVersions.prototype.focus = function(asset) {
    var assetBrowser, version;
    CUI.util.assert(!asset || asset instanceof Asset, "AssetVersions.focus", "asset needs to be instanceof Asset", {
      asset: asset
    });
    if (this.focused_version) {
      CUI.dom.removeClass(this.focused_version, ez5.defaults.focusClass);
      this.focused_version = null;
    }
    CUI.dom.empty(this.content);
    CUI.Events.ignore({
      instance: this
    });
    this.renderTools(asset);
    if (!asset.data && this._object_data) {
      asset.data = this._object_data;
    }
    assetBrowser = new AssetBrowser({
      hires: true,
      assets: [asset]
    });
    this.__tmpl.replace(asset.getInfoTabs({
      include_flyout: this.mode === "detail",
      assetBrowser: assetBrowser
    }), "info");
    this.__tmpl.replace(this.renderForm(asset), "form");
    if (!asset) {
      return;
    }
    version = this.findVersionByAsset(asset);
    this.focused_version = version;
    CUI.dom.addClass(version, ez5.defaults.focusClass);
    CUI.dom.append(this.content, assetBrowser);
    CUI.Events.listen({
      node: this.content,
      instance: this,
      type: "asset-detail",
      call: (function(_this) {
        return function(ev, info) {
          var j, len, ref, ti;
          ref = _this.toolInstances;
          for (j = 0, len = ref.length; j < len; j++) {
            ti = ref[j];
            if (typeof ti.assetDetailEvent === "function") {
              ti.assetDetailEvent(info.type, info);
            }
          }
        };
      })(this)
    });
    CUI.Events.listen({
      node: this.content,
      instance: this,
      type: "eas_update",
      call: (function(_this) {
        return function(ev) {
          _this.updateAsset(asset);
        };
      })(this)
    });
  };

  return AssetVersions;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var RightPresetManagerAdmin,
  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;

RightPresetManagerAdmin = (function(superClass) {
  extend(RightPresetManagerAdmin, superClass);

  function RightPresetManagerAdmin() {
    return RightPresetManagerAdmin.__super__.constructor.apply(this, arguments);
  }

  RightPresetManagerAdmin.label = function() {
    return "right.preset.manager.admin.menu";
  };

  RightPresetManagerAdmin.group = function() {
    return "rightsmanagement";
  };

  RightPresetManagerAdmin.submenu = function() {
    return "rightsmanagement";
  };

  RightPresetManagerAdmin.path = function() {
    return ["rightpresetmanager"];
  };

  RightPresetManagerAdmin.is_allowed = function() {
    return ez5.session.hasSystemRight("root", "rightpresetmanager");
  };

  RightPresetManagerAdmin.prototype.hasFooter = function() {
    return false;
  };

  RightPresetManagerAdmin.prototype.loadFilter = false;

  RightPresetManagerAdmin.prototype.setTitle = function() {
    return this.appManager.setTitle("right.preset.manager.admin.title");
  };

  RightPresetManagerAdmin.prototype.getMissingName = function() {
    return $$("right.preset.manager.admin.empty");
  };

  RightPresetManagerAdmin.prototype.getLeftTitle = function() {
    return $$("right.preset.manager.admin.pane.left.title");
  };

  RightPresetManagerAdmin.prototype.getCenterTitle = function() {
    return $$("right.preset.manager.presetlist.title");
  };

  RightPresetManagerAdmin.prototype.getMenuTitle = function() {
    return new CUI.Label({
      text: $$("right.preset.manager.admin.list.context")
    });
  };

  RightPresetManagerAdmin.prototype.getListFields = function() {
    return [
      {
        th_label: "right.preset.manager.admin.list.context"
      }
    ];
  };

  RightPresetManagerAdmin.prototype.loadList = function(ev, info) {
    var dfr, i, len, managers, ref, server_context;
    managers = [];
    ref = RightPresetManager.getServerContexts();
    for (i = 0, len = ref.length; i < len; i++) {
      server_context = ref[i];
      managers.push(new RightPresetManager({
        manager: this,
        server_context: server_context
      }));
    }
    return dfr = new CUI.Deferred().resolve(managers);
  };

  return RightPresetManagerAdmin;

})(SystemListManager);

ez5.session_ready(function() {
  return ez5.rootMenu.registerApp(RightPresetManagerAdmin);
});
// Generated by CoffeeScript 1.12.7
var Presentation,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

Presentation = (function(superClass) {
  extend(Presentation, superClass);

  function Presentation() {
    return Presentation.__super__.constructor.apply(this, arguments);
  }

  Presentation.prototype.initOpts = function() {
    Presentation.__super__.initOpts.call(this);
    return this.addOpts({
      collection: {
        mandatory: true,
        check: CollectionWorkfolder
      }
    });
  };

  Presentation.prototype.readOpts = function() {
    Presentation.__super__.readOpts.call(this);
    this.__load_dfr = this.loadFromData();
    this.__objectCache = [];
    return this.__currentPage = 0;
  };

  Presentation.cacheSize = 100;

  Presentation.slidesLimit = 10;

  Presentation.prototype.update = function() {
    var overview, overviewOuter, slide;
    slide = this.__presentationOverview.getSelectedNode();
    if (!slide) {
      this.__presentationMainViewPane.replace(new EmptyLocaLabel({
        loca_key: "collection.presentation.main_view.select_slide",
        centered: true
      }), "center");
      this.minusButton.disable();
    } else {
      overview = CUI.dom.div("ez5-presentation-slide-overview");
      CUI.dom.append(overview, slide.renderSlide());
      overviewOuter = CUI.dom.div("ez5-presentation-slide-overview-outer");
      CUI.dom.append(overviewOuter, overview);
      this.__presentationMainViewPane.replace(overviewOuter, "center");
      if (slide.isDeletable()) {
        this.minusButton.enable();
      } else {
        this.minusButton.disable();
      }
    }
    this.updateSaveButton();
    return this;
  };

  Presentation.prototype.getCollection = function() {
    return this._collection;
  };

  Presentation.prototype.updateSaveButton = function() {
    this.__checkRemoteInstance();
    if (this.__saveData !== JSON.stringify(this.getSaveData())) {
      this.saveButton.enable();
    } else {
      this.saveButton.disable();
    }
    return this.setPresentationClassesAndAttributes();
  };

  Presentation.prototype.setPresentationClassesAndAttributes = function(divs) {
    var div, i, len;
    if (divs == null) {
      divs = [this.__presentationOverviewPane.DOM, this.__presentationMainViewPane.DOM];
    }
    for (i = 0, len = divs.length; i < len; i++) {
      div = divs[i];
      CUI.dom.setAttribute(div, "data-show-info", this.__settings.show_standard);
    }
    if (this.__settings.show_standard !== this.__last_show_standard) {
      this.__last_show_standard = this.__settings.show_standard;
      CUI.Events.trigger({
        type: "viewport-resize"
      });
    }
  };

  Presentation.prototype.loadObject = function(global_object_id) {
    var idx, object;
    idx = CUI.util.idxInArray(null, this.__objectCache, function(v) {
      return v.global_object_id === global_object_id;
    });
    if (idx > -1) {
      object = this.__objectCache[idx];
      this.__objectCache.splice(idx, 1);
      this.__objectCache.push(object);
      if (object.result_object) {
        return CUI.resolvedPromise(object.result_object);
      } else {
        return object.promise;
      }
    }
    object = {
      global_object_id: global_object_id,
      result_object: null,
      promise: null
    };
    this.__objectCache.push(object);
    if (this.__objectCache.length > Presentation.cacheSize) {
      this.__objectCache.shift();
    }
    return object.promise = ResultObject.loadFromGlobalObjectId(global_object_id, "long", null, true, false).done((function(_this) {
      return function(resultObject) {
        object.promise = null;
        object.result_object = resultObject;
      };
    })(this));
  };

  Presentation.prototype.__checkRemoteInstance = function() {
    var i, len, ref1, ref2, ref3, remoteObject, slide;
    ref1 = this.__slides;
    for (i = 0, len = ref1.length; i < len; i++) {
      slide = ref1[i];
      remoteObject = slide.hasRemoteObject();
      if (remoteObject) {
        break;
      }
    }
    if (remoteObject) {
      return (ref2 = this.downloadBtn) != null ? ref2.disable() : void 0;
    } else {
      return (ref3 = this.downloadBtn) != null ? ref3.enable() : void 0;
    }
  };

  Presentation.prototype.destroy = function() {
    Presentation.__super__.destroy.call(this);
    return delete this.__objectCache;
  };

  Presentation.prototype.getData = function() {
    return this.__pres_data;
  };

  Presentation.prototype.loadFromData = function() {
    var dfr, find_missing, fn, gid, gid_map, gids, has_start, i, j, k, len, len1, len2, lookup_by_ref, parts, pres_data, promises, ref, ref1, ref2, ref3, slide, values;
    dfr = new CUI.Deferred();
    pres_data = (ref1 = this._collection.getData().collection.webfrontend_props) != null ? ref1.presentation : void 0;
    if (pres_data) {
      this.__pres_data = CUI.util.copyObject(pres_data, true);
    } else {
      this.__pres_data = {};
    }
    if (this.__pres_data.settings) {
      this.__settings = this.__pres_data.settings;
    } else {
      this.__settings = this.getDefaultSettings();
    }
    if (this.__settings.show_info === "standard-info") {
      this.__settings.show_standard = "1 2";
    }
    delete this.__settings.show_info;
    if (this.__settings.show_standard && this.__settings.show_standard !== "1 2") {
      this.__settings.show_standard = "1 2";
    }
    this.__slides = [];
    if (this.__pres_data.slides) {
      ref2 = this.__pres_data.slides;
      for (i = 0, len = ref2.length; i < len; i++) {
        slide = ref2[i];
        this.__slides.push(PresentationSlide.newFromData(this, slide));
      }
    }
    has_start = false;
    ref3 = this.__slides;
    for (j = 0, len1 = ref3.length; j < len1; j++) {
      slide = ref3[j];
      if (slide instanceof PresentationSlideStart) {
        has_start = true;
      }
    }
    if (!has_start) {
      this.__slides.splice(0, 0, new PresentationSlideStart({
        presentation: this
      }));
    }
    this.__overviewRoot = new CUI.ListViewTreeNode({
      ui: "presentation.list_view",
      children: this.__getPageSlides()
    });
    this.__saveData = JSON.stringify(this.getSaveData());
    gids = this.getGlobalObjectIds();
    lookup_by_ref = {};
    for (k = 0, len2 = gids.length; k < len2; k++) {
      gid = gids[k];
      parts = gid.split(/@/);
      if (parts[1].startsWith("lookup:")) {
        ref = parts[1].substr(7);
        if (!lookup_by_ref[ref]) {
          lookup_by_ref[ref] = [];
        }
        lookup_by_ref[ref].push(parts[0]);
      }
    }
    promises = [];
    gid_map = {};
    fn = (function(_this) {
      return function(ref) {
        var column, table;
        table = ref.split(".")[0];
        column = ref.split(".")[1];
        return promises.push(CUI.chunkWork.call(_this, {
          items: values,
          chunk_size: 1000,
          call: function(items) {
            return ez5.api.search({
              json_data: {
                objecttypes: [table],
                best_mask_filter: true,
                generate_rights: false,
                limit: 1000,
                format: "short",
                include_fields: [ref],
                search: [
                  {
                    type: 'in',
                    fields: [ref],
                    "in": values
                  }
                ]
              }
            }).done(function(data) {
              var l, len3, obj, ref4;
              ref4 = data.objects;
              for (l = 0, len3 = ref4.length; l < len3; l++) {
                obj = ref4[l];
                gid_map[obj[table][column] + "@lookup:" + ref] = obj._global_object_id;
              }
            });
          }
        }));
      };
    })(this);
    for (ref in lookup_by_ref) {
      values = lookup_by_ref[ref];
      fn(ref);
    }
    find_missing = (function(_this) {
      return function() {
        return CUI.chunkWork.call(_this, {
          items: gids,
          chunk_size: 1000,
          call: function(items) {
            return ez5.api.search({
              json_data: {
                best_mask_filter: true,
                generate_rights: false,
                limit: 1000,
                format: 'short',
                search: [
                  {
                    type: 'in',
                    fields: ['_global_object_id'],
                    "in": items
                  }
                ]
              }
            }).done(function(data) {
              var l, len3, obj, ref4;
              ref4 = data.objects;
              for (l = 0, len3 = ref4.length; l < len3; l++) {
                obj = ref4[l];
                CUI.util.removeFromArray(obj._global_object_id, gids);
              }
            });
          }
        }).fail(dfr.reject).done(function() {
          var connector_count, gids2, go_on, l, len3;
          connector_count = 0;
          gids2 = [];
          for (l = 0, len3 = gids.length; l < len3; l++) {
            gid = gids[l];
            if (gid.endsWith("@easydb4")) {
              connector_count += 1;
            } else {
              gids2.push(gid);
            }
          }
          go_on = function() {
            if (gids2.length > 0) {
              return CUI.confirm({
                text: $$('presentation.load.not_all_objects_found.message', {
                  count: gids2.length + ""
                }),
                button_primary: 'ok',
                button_text_ok: $$('presentation.load.not_all_objects_found.button.ok'),
                button_text_cancel: $$('presentation.load.not_all_objects_found.button.cancel')
              }).done(function() {
                var len4, m, ref4;
                ref4 = _this.__slides;
                for (m = 0, len4 = ref4.length; m < len4; m++) {
                  slide = ref4[m];
                  slide.removeGlobalObjectIds(gids2);
                }
                return dfr.resolve();
              }).fail(dfr.resolve);
            } else {
              return dfr.resolve();
            }
          };
          if (connector_count > 0) {
            return CUI.alert({
              text: $$('presentation.load.connector_objects_found.message', {
                count: connector_count + ""
              })
            }).done(go_on);
          } else {
            return go_on();
          }
        });
      };
    })(this);
    CUI.when(promises).fail(dfr.reject).done((function(_this) {
      return function() {
        var _gid, gid_new, idx, l, len3, len4, m, ref4, replaced;
        ref4 = _this.__slides;
        for (l = 0, len3 = ref4.length; l < len3; l++) {
          slide = ref4[l];
          slide.replaceGlobalObjectIds(gid_map);
        }
        replaced = 0;
        for (gid in gid_map) {
          gid_new = gid_map[gid];
          for (idx = m = 0, len4 = gids.length; m < len4; idx = ++m) {
            _gid = gids[idx];
            if (_gid === gid) {
              gids[idx] = gid_new;
              replaced += 1;
            }
          }
        }
        if (replaced > 0) {
          return CUI.alert({
            text: $$('presentation.load.lookup_objects_found.message', {
              count: replaced + ""
            })
          }).done(find_missing);
        } else {
          return find_missing();
        }
      };
    })(this));
    return dfr.promise();
  };

  Presentation.prototype.__getSlideIdx = function() {
    var idx, ref1;
    if (!this.__presentationOverview) {
      return this.getData().slide_idx;
    } else {
      idx = ((ref1 = this.__presentationOverview.getSelectedNode()) != null ? ref1.getChildIdx() : void 0) || 0;
      idx += this.__getIndexOffset();
      return idx;
    }
  };

  Presentation.prototype.showEditor = function() {
    var show_dfr;
    show_dfr = new CUI.Deferred();
    this.__load_dfr.fail((function(_this) {
      return function() {
        CUI.alert({
          text: $$("presentation.error.loading"),
          ui: "presentation.error.loading.alert"
        });
        return show_dfr.reject();
      };
    })(this)).done((function(_this) {
      return function() {
        var dm, downloadManagers, i, idx, len, mod, psc, ref1;
        _this.plusButton = new LocaButton({
          loca_key: "presentation.edit.add.button",
          ui: "presentation.edit_add.button",
          group: "plusminus",
          menu: {
            items: function() {
              var fn, i, items, len, ref1, type;
              items = [];
              ref1 = PresentationSlide.getTypes();
              fn = function(type) {
                return items.push({
                  loca_key: "presentation.slide_type." + type.getType(),
                  ui: "presentation.menu.add_slide.button:" + (type.getType()),
                  onClick: function() {
                    return _this.__addSlide(new type({
                      presentation: _this
                    }));
                  }
                });
              };
              for (i = 0, len = ref1.length; i < len; i++) {
                type = ref1[i];
                if (!(new type({
                  presentation: _this
                }).isUserSelectable())) {
                  continue;
                }
                fn(type);
              }
              items.push({
                divider: true
              });
              items.push({
                loca_key: "presentation.menu.add_all_missing",
                ui: "presentation.menu.add_all_missing.button",
                onClick: function() {
                  return CUI.confirm({
                    text: $$("presentation.menu.add_all_missing.confirm")
                  }).done(function() {
                    var wb;
                    wb = new CUI.WaitBlock({
                      element: _this.__presentationLayout.left()
                    }).show();
                    return _this._collection.executeSearch({
                      limit: 1000
                    }).always(function() {
                      return wb.destroy();
                    }).done(function(data) {
                      var gids, j, len1, obj, ref2, ref3, slide;
                      gids = _this.getGlobalObjectIds();
                      ref2 = data.objects;
                      for (j = 0, len1 = ref2.length; j < len1; j++) {
                        obj = ref2[j];
                        if (ref3 = obj._global_object_id, indexOf.call(gids, ref3) < 0) {
                          slide = new PresentationSlideOne({
                            presentation: _this
                          });
                          slide.initFromData({
                            center: {
                              global_object_id: obj._global_object_id
                            }
                          });
                          _this.__addSlide(slide);
                        }
                      }
                      _this.updateSaveButton();
                    });
                  });
                }
              });
              return items;
            }
          }
        });
        _this.minusButton = new LocaButton({
          loca_key: "presentation.edit.minus.button",
          ui: "presentation.edit_minus.button",
          group: "plusminus",
          disabled: true,
          onClick: function(ev, btn) {
            var slide;
            btn.disable();
            slide = _this.__presentationOverview.getSelectedNode();
            _this.__removeSlide(slide);
          }
        });
        _this.saveButton = new LocaButton({
          loca_key: "presentation.edit.save.button",
          ui: "presentation.edit_save.button",
          primary: true,
          disabled: true,
          left: true,
          onClick: function(ev, btn) {
            btn.disable().startSpinner();
            return _this.save(ev).always(function() {
              return btn.enable().stopSpinner();
            }).done(function() {
              show_dfr.resolve();
              return mod.destroy();
            });
          }
        });
        _this.deleteButton = new LocaButton({
          loca_key: "presentation.edit.delete.button",
          ui: "presentation.edit_delete.button",
          secondary: true,
          onClick: function(ev) {
            return CUI.confirm({
              text: $$("presentation.edit.delete.confirm")
            }).done(function(choice, btn, ev) {
              btn.disable().startSpinner();
              return _this["delete"](ev).always(function() {
                return btn.enable().stopSpinner();
              }).done(function() {
                show_dfr.resolve();
                return mod.destroy();
              });
            });
          }
        });
        _this.playButton = new LocaButton({
          loca_key: "presentation.edit.start.button",
          ui: "presentation.edit_start.button",
          size: "big",
          "class": "ez5-play-button",
          onClick: function() {
            var start_idx;
            start_idx = _this.__getSlideIdx();
            return _this.play(start_idx).done(function(slide_no) {
              return _this.__selectSlideByIdx(slide_no);
            });
          }
        });
        _this.settingsButton = new LocaButton({
          loca_key: "presentation.button.settings",
          ui: "presentation.settings.button",
          group: "a",
          onClick: function() {
            return _this.showPresentationSettings();
          }
        });
        if (Presentation.downloadManagers.length > 0) {
          downloadManagers = [];
          ref1 = Presentation.downloadManagers;
          for (i = 0, len = ref1.length; i < len; i++) {
            dm = ref1[i];
            downloadManagers.push(new dm({
              presentation: _this
            }));
          }
          _this.downloadBtn = new LocaButton({
            group: "a",
            loca_key: "presentation.button.download",
            ui: "presentation.download.button",
            menu: {
              items: function() {
                var j, len1, results;
                results = [];
                for (j = 0, len1 = downloadManagers.length; j < len1; j++) {
                  dm = downloadManagers[j];
                  results.push(dm.getMenuButton());
                }
                return results;
              }
            }
          });
        }
        _this.__presentationOverview = new CUI.ListViewTree({
          selectableRows: true,
          rowMove: true,
          onRowMove: function(fromIndex, toIndex, after) {
            fromIndex = _this.__getIndexOffset() + fromIndex;
            toIndex = _this.__getIndexOffset() + toIndex;
            CUI.util.moveInArray(fromIndex, toIndex, _this.__slides, after);
            _this.__updateSlideCounters();
            return _this.updateSaveButton();
          },
          onSelect: function() {
            return _this.update();
          },
          onDeselect: function() {
            return _this.update();
          },
          no_hierarchy: true,
          root: _this.__overviewRoot,
          cols: ["maximize"],
          footer_left: new CUI.VerticalList({
            content: [
              _this.__getNavigation(), new CUI.Buttonbar({
                buttons: [_this.plusButton, _this.minusButton, _this.downloadBtn, _this.settingsButton]
              })
            ]
          })
        });
        _this.__presentationOverviewPane = new CUI.SimplePane({
          "class": "ez5-presentation-overview-pane",
          ui: "presentation.overview.pane",
          header_left: new LocaLabel({
            loca_key: "collection.presentation.overview.title"
          }),
          content: function() {
            var node;
            node = _this.__presentationOverview.render();
            _this.__presentationOverview.root.open();
            return node;
          }
        });
        _this.__presentationMainViewPane = new CUI.SimplePane({
          "class": "ez5-presentation-main-view-pane",
          ui: "presentation.main_view.pane",
          header_left: new LocaLabel({
            loca_key: "collection.presentation.main_view.title"
          })
        });
        _this.__presentationCollectionPane = new CUI.SimplePane({
          "class": "ez5-presentation-collection-pane",
          ui: "presentation.collection.pane",
          header_left: new LocaLabel({
            loca_key: "collection.presentation.collection.title"
          })
        });
        _this.__presentationLayout = new CUI.HorizontalLayout({
          absolute: true,
          "class": "ez5-collection-workfolder-presentation",
          left: {
            "class": "ez5-collection-workfolder-presentation-left",
            flexHandle: {
              state_name: "presentation-left",
              hidden: false
            },
            content: _this.__presentationOverviewPane
          },
          center: {
            "class": "ez5-collection-workfolder-presentation-center",
            content: _this.__presentationMainViewPane
          },
          right: {
            "class": "ez5-collection-workfolder-presentation-right",
            content: _this.__presentationCollectionPane,
            flexHandle: {
              state_name: "presentation-right",
              hidden: false
            }
          }
        });
        idx = _this.getData().slide_idx || 0;
        _this.__updateNavigation();
        _this.__selectSlideByIdx(idx);
        _this.update();
        _this.updateSaveButton();
        mod = new CUI.Modal({
          fill_space: "both",
          "class": "ez5-collection-workfolder-presentation-modal",
          cancel: true,
          onCancel: function() {
            var dfr;
            if (!_this.saveButton.isEnabled()) {
              mod.destroy();
              return true;
            }
            dfr = new CUI.Deferred();
            dfr.done(function() {
              mod.destroy();
              return show_dfr.resolve();
            });
            new CUI.ConfirmationChoice({
              text: $$("presentation.unsaved_changes.text"),
              choices: [
                {
                  _value: "discard",
                  text: $$("presentation.unsaved_changes.button.discard")
                }, {
                  _value: "cancel",
                  text: $$("base.cancel")
                }, {
                  _value: "save",
                  primary: true,
                  text: $$("presentation.unsaved_changes.button.save")
                }
              ]
            }).open().done(function(choice, btn, ev) {
              switch (choice._value) {
                case "discard":
                  return dfr.resolve();
                case "cancel":
                  return dfr.reject();
                case "save":
                  return _this.save().done(dfr.resolve).fail(dfr.reject);
              }
            });
            return dfr.promise();
          },
          pane: {
            header_left: new CUI.Label({
              text: _this._collection.renderNameAsText()
            }),
            content: _this.__presentationLayout,
            footer_left: _this.playButton,
            footer_right: [_this.deleteButton, _this.saveButton]
          }
        }).show();
        psc = new PresentationSearchCollection({
          container: _this.__presentationCollectionPane.center(),
          collection: _this._collection
        });
        _this.__addToolbox();
        return psc.init();
      };
    })(this));
    return show_dfr.promise();
  };

  Presentation.prototype.__addToolbox = function() {
    return CUI.Events.listen({
      node: this.__presentationOverviewPane,
      type: "toolbox",
      call: (function(_this) {
        return function(ev, info) {
          var lastPage, listViewTreeRowNode, slide;
          lastPage = _this.__navigationToolbar.getLastPage();
          listViewTreeRowNode = CUI.dom.data(ev.getTarget(), "drag-drop-select-draggable");
          if (!listViewTreeRowNode) {
            return;
          }
          slide = listViewTreeRowNode._row;
          if (slide instanceof PresentationSlideStart) {
            return;
          }
          slide.select();
          info.tools.push(new ToolboxTool({
            group: "presentation.slide.move",
            name: "first-page",
            loca_key: "collection.presentation.slide.move-actions.first-page",
            disabled: _this.getIndexOfSlide(slide) === 0 || _this.getIndexOfSlide(slide) === 1,
            run: function() {
              var currentIndex;
              currentIndex = _this.getIndexOfSlide(slide);
              CUI.util.moveInArray(currentIndex, 1, _this.__slides);
              _this.__currentPage = 0;
              _this.__updateNavigation();
              _this.__slides[1].select();
            }
          }));
          info.tools.push(new ToolboxTool({
            group: "presentation.slide.move",
            name: "previous-page",
            loca_key: "collection.presentation.slide.move-actions.previous-page",
            disabled: _this.getIndexOfSlide(slide) === 0 || _this.getIndexOfSlide(slide) === 1,
            run: function() {
              var currentIndex, newIndex;
              currentIndex = _this.getIndexOfSlide(slide);
              newIndex = Math.max(currentIndex - 1, 1);
              CUI.util.moveInArray(currentIndex, newIndex, _this.__slides);
              _this.__currentPage = Math.floor(newIndex / Presentation.slidesLimit);
              _this.__updateNavigation();
              _this.__slides[newIndex].select();
            }
          }));
          info.tools.push(new ToolboxTool({
            group: "presentation.slide.move",
            name: "next-page",
            loca_key: "collection.presentation.slide.move-actions.next-page",
            disabled: _this.getIndexOfSlide(slide) === _this.__slides.length || _this.getIndexOfSlide(slide) === 0,
            run: function() {
              var currentIndex, newIndex;
              currentIndex = _this.getIndexOfSlide(slide);
              newIndex = Math.min(currentIndex + 1, _this.__slides.length - 1);
              CUI.util.moveInArray(currentIndex, newIndex, _this.__slides, true);
              _this.__currentPage = Math.floor(newIndex / Presentation.slidesLimit);
              _this.__updateNavigation();
              _this.__slides[newIndex].select();
            }
          }));
          return info.tools.push(new ToolboxTool({
            group: "presentation.slide.move",
            name: "last-page",
            loca_key: "collection.presentation.slide.move-actions.last-page",
            disabled: _this.getIndexOfSlide(slide) === _this.__slides.length || _this.getIndexOfSlide(slide) === 0,
            run: function() {
              var currentIndex, newIndex;
              currentIndex = _this.getIndexOfSlide(slide);
              newIndex = _this.__slides.length - 1;
              CUI.util.moveInArray(currentIndex, newIndex, _this.__slides, true);
              _this.__currentPage = Math.floor(newIndex / Presentation.slidesLimit);
              _this.__updateNavigation();
              _this.__slides[_this.__slides.length - 1].select();
            }
          }));
        };
      })(this)
    });
  };

  Presentation.prototype.__getNavigation = function() {
    this.__navigationToolbar = new NavigationToolbar({
      append_count_label: false,
      onLoadPage: (function(_this) {
        return function(page) {
          return _this.__updateNavigation(page);
        };
      })(this)
    });
    return this.__navigationToolbar;
  };

  Presentation.prototype.__updateNavigation = function(page, idx) {
    var limit, offset, previousPage, ref1, selectedNode;
    if (page == null) {
      page = this.__currentPage;
    }
    previousPage = this.__currentPage;
    this.__currentPage = page;
    limit = Presentation.slidesLimit;
    offset = page * limit;
    this.__navigationToolbar.update({
      count: this.__slides.length,
      offset: offset,
      limit: limit
    });
    this.__updateSlideList();
    if (previousPage !== this.__currentPage) {
      if (!idx) {
        idx = this.__getIndexOffset();
      }
      this.__selectSlideByIdx(idx);
    }
    selectedNode = (ref1 = this.__presentationOverview) != null ? ref1.getSelectedNode() : void 0;
    if (selectedNode) {
      selectedNode.scrollIntoView();
      this.minusButton.enable();
    } else {
      this.minusButton.disable();
    }
  };

  Presentation.prototype.__updateSlideList = function() {
    var i, len, ref1, results, slide, slides;
    slides = this.__getPageSlides();
    this.__overviewRoot.setChildren([]);
    if ((ref1 = this.__presentationOverview) != null) {
      ref1.removeAllRows();
    }
    results = [];
    for (i = 0, len = slides.length; i < len; i++) {
      slide = slides[i];
      results.push(this.__overviewRoot.addNode(slide));
    }
    return results;
  };

  Presentation.prototype.__selectSlideByIdx = function(idx) {
    var pageWithIdx;
    if (this.__slides.length < idx) {
      return;
    }
    pageWithIdx = Math.floor(idx / Presentation.slidesLimit);
    if (this.__currentPage === pageWithIdx) {
      return this.__slides[idx].select();
    } else {
      return this.__updateNavigation(pageWithIdx, idx);
    }
  };

  Presentation.prototype.getGlobalObjectIds = function() {
    var gid, gids, i, j, len, len1, ref1, ref2, slide;
    gids = [];
    ref1 = this.__slides;
    for (i = 0, len = ref1.length; i < len; i++) {
      slide = ref1[i];
      ref2 = slide.getGlobalObjectIds();
      for (j = 0, len1 = ref2.length; j < len1; j++) {
        gid = ref2[j];
        CUI.util.pushOntoArray(gid, gids);
      }
    }
    return gids;
  };

  Presentation.prototype.save = function(ev) {
    return this._collection.save(ev, this.getSaveData());
  };

  Presentation.prototype["delete"] = function(ev) {
    return this._collection.save(ev, this.getSaveData(true));
  };

  Presentation.prototype.getFieldsForSettings = function() {
    return [
      {
        type: CUI.Options,
        ui: "presentation.settings.fields.show_standard",
        horizontal: false,
        undo_and_changed_support: false,
        form: {
          label: $$("presentation.settings.form.info.label")
        },
        radio: true,
        options: [
          {
            text: $$("presentation.settings.form.info.option.no-info"),
            value: "",
            ui: "presentation.settings.fields.show_standard.option.hide"
          }, {
            text: $$("presentation.settings.form.info.option.standard-info"),
            value: "1 2",
            ui: "presentation.settings.fields.show_standard.option.show"
          }
        ],
        name: "show_standard"
      }
    ];
  };

  Presentation.prototype.showPresentationSettings = function() {
    var form, popover;
    form = new CUI.Form({
      padded: true,
      data: this.__settings,
      undo_and_changed_support: false,
      fields: this.getFieldsForSettings(),
      onDataChanged: (function(_this) {
        return function() {
          return _this.setPresentationClassesAndAttributes();
        };
      })(this)
    }).start();
    popover = new CUI.Popover({
      element: this.settingsButton,
      placement: "nw",
      placements: ["nw", "n"],
      onHide: (function(_this) {
        return function() {
          return _this.updateSaveButton();
        };
      })(this),
      pane: {
        header_left: new LocaLabel({
          loca_key: "presentation.settings.popover.title"
        }),
        maximize: true,
        content: form
      }
    }).show();
    return popover;
  };

  Presentation.prototype.getDefaultSettings = function() {
    return {
      show_standard: "1 2"
    };
  };

  Presentation.prototype.__getSettings = function() {
    return this.__settings;
  };

  Presentation.prototype.checkRemoveObjects = function(collection_objects) {
    var co, dfr, gid, i, len, loca_key, remove_gids, txt;
    remove_gids = [];
    dfr = new CUI.Deferred();
    for (i = 0, len = collection_objects.length; i < len; i++) {
      co = collection_objects[i];
      gid = co.getGlobalObjectId();
      if (indexOf.call(this.getGlobalObjectIds(), gid) >= 0) {
        remove_gids.push(gid);
      }
    }
    if (remove_gids.length === 0) {
      return dfr.resolve().promise();
    }
    if (remove_gids.length === 1) {
      loca_key = "presentation.remove_objects.confirm.one";
    } else {
      loca_key = "presentation.remove_objects.confirm";
    }
    txt = $$(loca_key, {
      count: remove_gids.length
    });
    CUI.confirm({
      text: txt
    }).done((function(_this) {
      return function() {
        var j, len1, ref1, slide;
        ref1 = _this.__slides;
        for (j = 0, len1 = ref1.length; j < len1; j++) {
          slide = ref1[j];
          slide.removeGlobalObjectIds(remove_gids);
        }
        return _this.save().done(dfr.resolve).fail(dfr.reject);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  Presentation.prototype.getSaveData = function(delete_slides) {
    var c, i, len, ref1, sd, sd_pres, sd_slide;
    if (delete_slides == null) {
      delete_slides = false;
    }
    sd = this._collection.getSaveData();
    if (!sd.collection.webfrontend_props) {
      sd.collection.webfrontend_props = {};
    }
    if (delete_slides) {
      delete sd.collection.webfrontend_props.presentation;
      sd.collection.type = "workfolder";
    } else {
      sd_pres = sd.collection.webfrontend_props.presentation;
      if (!sd_pres) {
        sd_pres = sd.collection.webfrontend_props.presentation = {};
      }
      sd_pres.slides = [];
      sd_pres.slide_idx = this.__getSlideIdx();
      sd_pres.settings = this.__getSettings();
      if (!sd_pres.settings.show_standard) {
        sd_pres.settings.show_standard = "";
      }
      ref1 = this.__slides;
      for (i = 0, len = ref1.length; i < len; i++) {
        c = ref1[i];
        sd_slide = c.getSaveData();
        sd_pres.slides.push(sd_slide);
      }
      if (sd_pres.slides.length > 0) {
        sd.collection.type = "presentation";
      } else {
        sd.collection.type = "workfolder";
      }
    }
    return sd;
  };

  Presentation.prototype.play = function(slide_no) {
    var dfr;
    if (slide_no == null) {
      slide_no = 0;
    }
    dfr = new CUI.Deferred();
    this.__load_dfr.fail((function(_this) {
      return function() {
        return dfr.reject();
      };
    })(this)).done((function(_this) {
      return function() {
        var close, closeBtn, fn, i, keydownEvent, leftBtn, len, play_div, player_overview_div, player_overview_outer_div, present_slide, prevNext, rightBtn, slide, slide_idx, slides, update_btns;
        play_div = new CUI.Template({
          name: "presentation-player",
          map: {
            content: true,
            controls: true
          }
        });
        keydownEvent = CUI.Events.listen({
          type: "keydown",
          capture: true,
          node: window,
          call: function(event) {
            var eventKeyboard;
            eventKeyboard = event.getKeyboard();
            if (eventKeyboard === "Space" || eventKeyboard === "Right" || eventKeyboard === "PageDown" || eventKeyboard === "Return") {
              present_slide(slide_no + 1);
              return event.stop();
            }
            if (eventKeyboard === "PageUp" || eventKeyboard === "Left") {
              present_slide(slide_no - 1);
              return event.stop();
            }
            if (eventKeyboard === 'Esc') {
              close();
              return event.stop();
            }
          }
        });
        player_overview_outer_div = CUI.dom.div("cui-presentation-player-overview-outer");
        player_overview_div = CUI.dom.div("cui-presentation-player-overview");
        CUI.dom.append(player_overview_outer_div, player_overview_div);
        CUI.dom.setClassOnMousemove({
          element: player_overview_outer_div,
          ms: 2500,
          "class": "ez5-presentation-player-overview--show"
        });
        _this.setPresentationClassesAndAttributes([play_div.DOM]);
        CUI.dom.setClassOnMousemove({
          element: play_div.DOM,
          ms: 1000,
          "class": "ez5-presentation-player--show-controls"
        });
        closeBtn = new LocaButton({
          loca_key: "presentation.play.close.button",
          ui: "presentation.play.close.button",
          appearance: "transparent-border",
          "class": "ez5-presentation-player-close-button ez5-slide-in",
          onClick: function() {
            return close();
          }
        });
        leftBtn = new LocaButton({
          loca_key: "presentation.play.left.button",
          ui: "presentation.play.left.button",
          appearance: "transparent-border",
          disabled: true,
          onClick: function() {
            return present_slide(slide_no - 1);
          }
        });
        rightBtn = new LocaButton({
          loca_key: "presentation.play.right.button",
          ui: "presentation.play.right.button",
          appearance: "transparent-border",
          disabled: true,
          onClick: function() {
            return present_slide(slide_no + 1);
          }
        });
        slides = _this.__slides;
        fn = function(slide_idx) {
          var outer, overview_slide;
          overview_slide = slide.renderContent();
          if (overview_slide.DOM) {
            overview_slide = overview_slide.DOM;
          }
          CUI.dom.setAttribute(overview_slide, "slide-no", slide_idx);
          CUI.Events.listen({
            type: "click",
            node: overview_slide,
            call: function() {
              return present_slide(slide_idx);
            }
          });
          outer = CUI.dom.div("cui-presentation-player-overview-entry");
          CUI.dom.append(outer, overview_slide);
          return CUI.dom.append(player_overview_div, outer);
        };
        for (slide_idx = i = 0, len = slides.length; i < len; slide_idx = ++i) {
          slide = slides[slide_idx];
          fn(slide_idx);
        }
        update_btns = function() {
          if (slide_no === 0) {
            leftBtn.disable();
          } else {
            leftBtn.enable();
          }
          if (slide_no + 1 < slides.length) {
            return rightBtn.enable();
          } else {
            return rightBtn.disable();
          }
        };
        close = function() {
          CUI.dom.remove(play_div.DOM);
          CUI.dom.remove(player_overview_outer_div);
          keydownEvent.destroy();
          return dfr.resolve(slide_no);
        };
        prevNext = new CUI.Buttonbar({
          "class": "ez5-presentation-player-prev-next-buttonbar ez5-slide-in",
          buttons: [leftBtn, rightBtn]
        });
        play_div.append(closeBtn, "controls");
        play_div.append(prevNext, "controls");
        present_slide = function(new_no) {
          var div, divsFound, j, len1, parentNode, ref1;
          divsFound = CUI.dom.matchSelector(player_overview_div, ".cui-selected");
          for (j = 0, len1 = divsFound.length; j < len1; j++) {
            div = divsFound[j];
            CUI.dom.removeClass(div, "cui-selected");
          }
          parentNode = (ref1 = CUI.dom.matchSelector(player_overview_div, "[slide-no=\"" + new_no + "\"]")[0]) != null ? ref1.parentNode : void 0;
          if (parentNode) {
            slide_no = new_no;
            CUI.dom.addClass(parentNode, "cui-selected");
            play_div.replace(slides[slide_no].renderPresentation(), "content");
          }
          return update_btns();
        };
        present_slide(slide_no);
        document.body.appendChild(play_div.DOM);
        if (CUI.__ng__) {
          return document.body.appendChild(player_overview_outer_div);
        } else {
          return document.body.appendChild(player_overview_div);
        }
      };
    })(this));
    return dfr.promise();
  };

  Presentation.prototype.__addSlide = function(slide) {
    var lastPage, newPage, newSlideIndex, selectedSlide, selectedSlideIndex;
    selectedSlide = this.__presentationOverview.getSelectedNode();
    if (selectedSlide) {
      selectedSlideIndex = this.getIndexOfSlide(selectedSlide);
      this.__slides.splice(selectedSlideIndex + 1, 0, slide);
      if (selectedSlide.getChildIdx() === Presentation.slidesLimit - 1) {
        newPage = this.__currentPage + 1;
        this.__updateNavigation(newPage, 0);
      } else {
        this.__updateNavigation();
        this.__selectSlideByIdx(selectedSlideIndex + 1);
      }
    } else {
      this.__slides.push(slide);
      lastPage = this.__navigationToolbar.getLastPage();
      newSlideIndex = this.__slides.length - 1;
      if (this.__currentPage === lastPage) {
        this.__updateNavigation();
        this.__selectSlideByIdx(newSlideIndex);
      } else {
        this.__updateNavigation(lastPage, newSlideIndex);
      }
    }
    this.__updateSlideCounters();
    return slide;
  };

  Presentation.prototype.__removeSlide = function(slide) {
    var slides;
    if (!slide) {
      return;
    }
    if (slide instanceof PresentationSlideStart) {
      return;
    }
    slide.remove();
    CUI.util.removeFromArray(slide, this.__slides);
    if (this.__slides.length >= Presentation.slidesLimit) {
      slides = this.__getPageSlides();
      if (slides.length === 0) {
        this.__currentPage--;
      }
      this.__updateNavigation();
    }
  };

  Presentation.prototype.__updateSlideCounters = function() {
    var i, len, ref1, slide;
    ref1 = this.__presentationOverview.getRootChildren();
    for (i = 0, len = ref1.length; i < len; i++) {
      slide = ref1[i];
      slide.updateCounterLabel();
    }
  };

  Presentation.prototype.__getPageSlides = function() {
    var from;
    from = this.__currentPage * Presentation.slidesLimit;
    return this.__slides.slice(from, from + Presentation.slidesLimit);
  };

  Presentation.prototype.getIndexOfSlide = function(slide) {
    var _slide, i, index, len, ref1;
    ref1 = this.__slides;
    for (index = i = 0, len = ref1.length; i < len; index = ++i) {
      _slide = ref1[index];
      if (_slide === slide) {
        return index;
      }
    }
    return null;
  };

  Presentation.prototype.__getIndexOffset = function() {
    return this.__currentPage * Presentation.slidesLimit;
  };

  Presentation.registerDownloadManager = function(dm) {
    var inst;
    if (CUI.util.isFunction(dm)) {
      inst = new dm();
    }
    CUI.util.assert(inst instanceof PresentationDownloadManager, "Presentation.registerDownloadManager", "download manager needs to be instance of PresentationDownloadManager");
    this.downloadManagers.push(dm);
  };

  Presentation.downloadManagers = [];

  return Presentation;

})(CUI.Element);
// Generated by CoffeeScript 1.12.7
var PresentationDownloadManager,
  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;

PresentationDownloadManager = (function(superClass) {
  extend(PresentationDownloadManager, superClass);

  function PresentationDownloadManager(opts) {
    if (!opts) {
      return;
    }
    PresentationDownloadManager.__super__.constructor.call(this, opts);
  }

  PresentationDownloadManager.prototype.initOpts = function() {
    PresentationDownloadManager.__super__.initOpts.call(this);
    this.removeOpt("collection");
    this.removeOpt("result_object");
    return this.addOpts({
      presentation: {
        mandatory: true,
        check: Presentation
      }
    });
  };

  PresentationDownloadManager.prototype.readOpts = function() {
    ExportManager.prototype.readOpts.call(this);
    return this;
  };

  PresentationDownloadManager.prototype.init = function() {
    delete this["export"];
    return PresentationDownloadManager.__super__.init.call(this);
  };

  PresentationDownloadManager.prototype.showUserAdminMessages = function() {
    return CUI.resolvedPromise();
  };

  PresentationDownloadManager.prototype.getMenuButton = function() {
    return {
      text: this.__cls
    };
  };

  PresentationDownloadManager.prototype.startConnectorDownload = function() {
    return false;
  };

  PresentationDownloadManager.prototype.getExportManagerResultClass = function() {
    return window.PresentationDownloadManagerResult;
  };

  PresentationDownloadManager.prototype.getAssetVersionsToExport = function(asset, gid) {
    var i, len, ref, version, versions;
    versions = [];
    ref = asset.value.versions;
    for (i = 0, len = ref.length; i < len; i++) {
      version = ref[i];
      if (version._not_allowed || version.status !== "done") {
        continue;
      }
      versions.push(version);
    }
    return versions;
  };

  PresentationDownloadManager.prototype.gatherAssetsForExport = function(slides) {
    var asset, download_url, eas_id, eas_info, gid, i, j, k, l, len, len1, len2, produce_versions, ref, slide, v, version, versions;
    this.assets = {};
    this.eas_fields = {};
    eas_info = this.getEASColumnsInfo();
    this.data_by_gid = eas_info.data_by_gid;
    ref = eas_info.assets;
    for (i = 0, len = ref.length; i < len; i++) {
      asset = ref[i];
      gid = asset.__object_data._global_object_id;
      versions = this.getAssetVersionsToExport(asset, gid);
      if (!(versions != null ? versions.length : void 0)) {
        continue;
      }
      eas_id = asset.value._id;
      produce_versions = [];
      for (j = 0, len1 = versions.length; j < len1; j++) {
        version = versions[j];
        if (version.version === "original") {
          produce_versions.push({
            type: "current",
            metadata: "standard"
          });
        } else {
          produce_versions.push({
            type: "version",
            version: version.version,
            metadata: "standard"
          });
        }
        download_url = version.download_url;
      }
      for (l = 0, len2 = slides.length; l < len2; l++) {
        slide = slides[l];
        for (k in slide) {
          v = slide[k];
          if (!CUI.util.isPlainObject(v)) {
            continue;
          }
          if (v.global_object_id === gid && !v.asset_id) {
            v.asset_id = eas_id;
          }
          if (v.asset_id === eas_id) {
            if (asset.data._instance) {
              v.asset_url = download_url;
            } else {
              this.assets[eas_id] = {
                versions: produce_versions
              };
            }
          }
        }
      }
      if (!asset.data._instance) {
        this.eas_fields[asset.getField().fullName()] = {
          files: true
        };
      }
    }
  };

  PresentationDownloadManager.prototype.getExportSaveData = function() {
    var data, req, sd;
    sd = this._presentation.getSaveData();
    this.gatherAssetsForExport(sd.collection.webfrontend_props.presentation.slides);
    req = ExportManager.prototype.filterRequest.call(this, this.getRequest());
    data = {
      "export": {
        search: req,
        xml: false,
        flat: true,
        eas_fields: this.eas_fields,
        produce_options: {
          pptx: true,
          presentation: {
            slides: sd.collection.webfrontend_props.presentation.slides,
            settings: sd.collection.webfrontend_props.presentation.settings,
            data_by_gid: this.data_by_gid,
            filename: ez5.loca.getBestFrontendValue(sd.collection.displayname)
          }
        },
        filename_template: "%_asset.id%",
        type: "download",
        json: true,
        json_one_file_per_object: true,
        filename_original: null,
        assets: this.assets
      }
    };
    return data;
  };

  PresentationDownloadManager.prototype.startExport = function() {
    this.__setTemporaryCollection();
    return PresentationDownloadManager.__super__.startExport.call(this);
  };

  PresentationDownloadManager.prototype.__setTemporaryCollection = function() {
    var col, cos, globalObjectIds;
    col = new CollectionTemporary();
    cos = [];
    globalObjectIds = this._presentation.getGlobalObjectIds();
    if (globalObjectIds.length === 0) {
      cos = [
        new CollectionObject({
          _global_object_id: "-1"
        })
      ];
    } else {
      cos = globalObjectIds.map((function(_this) {
        return function(gid) {
          return new CollectionObject({
            _global_object_id: gid
          });
        };
      })(this));
    }
    col.insertObjects(cos);
    this._collection = col;
  };

  return PresentationDownloadManager;

})(DownloadManager);
// Generated by CoffeeScript 1.12.7
var PresentationDownloadManagerResult,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

PresentationDownloadManagerResult = (function(superClass) {
  extend(PresentationDownloadManagerResult, superClass);

  function PresentationDownloadManagerResult() {
    return PresentationDownloadManagerResult.__super__.constructor.apply(this, arguments);
  }

  PresentationDownloadManagerResult.prototype.showResult = function(request, data) {
    var gid, gids, i, j, len, obj, order, ref, ref1, standard, text;
    PresentationDownloadManagerResult.__super__.showResult.call(this, request, data);
    gids = this._manager.getOpt("presentation").getGlobalObjectIds();
    this._eas_info.data_by_gid = {};
    ref = data.objects;
    for (i = 0, len = ref.length; i < len; i++) {
      obj = ref[i];
      gid = obj._global_object_id;
      if (this._eas_info.data_by_gid[gid] === void 0 && indexOf.call(gids, gid) >= 0) {
        standard = {};
        for (order = j = 1; j <= 3; order = j += 1) {
          text = ez5.loca.getBestFrontendValue((ref1 = obj._standard[order]) != null ? ref1.text : void 0);
          if (CUI.util.isNull(text)) {
            standard[order] = "";
          } else {
            standard[order] = text;
          }
        }
        this._eas_info.data_by_gid[gid] = {
          standard_info: standard
        };
      }
    }
  };

  PresentationDownloadManagerResult.prototype.showResultCollectAssets = function() {
    return true;
  };

  return PresentationDownloadManagerResult;

})(ExportManagerResult);
// Generated by CoffeeScript 1.12.7
var PresentationSearchCollection,
  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;

PresentationSearchCollection = (function(superClass) {
  extend(PresentationSearchCollection, superClass);

  function PresentationSearchCollection() {
    return PresentationSearchCollection.__super__.constructor.apply(this, arguments);
  }

  PresentationSearchCollection.prototype.init = function() {
    this.__pane = new CUI.Pane({
      "class": "ez5-search-collection-pane",
      top: {
        "class": "ez5-search-collection-pane-top",
        content: [
          this.__buttonToolbar = new CUI.PaneToolbar({
            "class": "ez5-search-collection-toolbar"
          })
        ]
      },
      center: {
        "class": "ez5-search-collection-center"
      }
    });
    this.rc = this.__pane.center();
    this.container.append(this.__pane.DOM);
    this.registerResultContainer(this.rc);
    this.addResultSearchManager();
    return CUI.chainedCall(Search.prototype.init.call(this), (function(_this) {
      return function() {
        return _this.execute();
      };
    })(this), (function(_this) {
      return function() {
        return CUI.Events.trigger({
          node: _this.rc,
          type: "content-resize"
        });
      };
    })(this));
  };

  PresentationSearchCollection.prototype.addResultSearchManager = function() {
    return this.addSearchManager(new ResultManager({
      pref: "presentation_search_collection_view_data",
      managers: [
        new ResultStandard({
          container: this.getResultContainer(),
          selectable_opts: {
            collection: this.getCollection(),
            select_with_modifier: false,
            lasso: false,
            fullscreen: false,
            draggable: true,
            select: false,
            toolbox: true,
            onToolbox: (function(_this) {
              return function(event, tools) {
                return CUI.util.removeFromArray(null, tools, function(v) {
                  var ref;
                  return (ref = v.getName()) !== "object.download" && ref !== "object.export" && ref !== "object.print" && ref !== "object.show.popover";
                });
              };
            })(this)
          }
        })
      ]
    }));
  };

  return PresentationSearchCollection;

})(SearchCollection);
// Generated by CoffeeScript 1.12.7
var PresentationSlide,
  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;

PresentationSlide = (function(superClass) {
  extend(PresentationSlide, superClass);

  function PresentationSlide(opts1) {
    this.opts = opts1;
    if (this.opts) {
      PresentationSlide.__super__.constructor.call(this, this.opts);
    } else {
      return;
    }
  }

  PresentationSlide.prototype.initOpts = function() {
    PresentationSlide.__super__.initOpts.call(this);
    return this.addOpts({
      presentation: {
        check: Presentation
      }
    });
  };

  PresentationSlide.prototype.allowRowMove = function(to_node, new_father, after) {
    if (to_node.getDisplayRowIdx() === 0) {
      return false;
    } else {
      return true;
    }
  };

  PresentationSlide.prototype.getSaveData = function() {
    return {
      type: window[this.__cls].getType()
    };
  };

  PresentationSlide.prototype.getGlobalObjectIds = function() {
    return [];
  };

  PresentationSlide.prototype.replaceGlobalObjectIds = function(replace_map) {};

  PresentationSlide.prototype.removeGlobalObjectIds = function(gids) {};

  PresentationSlide.prototype.initFromData = function(data) {};

  PresentationSlide.prototype.isDeletable = function() {
    return true;
  };

  PresentationSlide.prototype.update = function() {
    this._presentation.updateSaveButton();
    return PresentationSlide.__super__.update.call(this);
  };

  PresentationSlide.prototype.isUserSelectable = function() {
    return true;
  };

  PresentationSlide.prototype.updateSlide = function() {
    this._presentation.update();
    return this.update();
  };

  PresentationSlide.prototype.updateCounterLabel = function() {
    if (!this.__counterLabel) {
      return;
    }
    return this.__counterLabel.setText(this.__getCounterLabelText());
  };

  PresentationSlide.prototype.renderContent = function() {
    var counterLabelText, div, overview;
    overview = this.renderOverview();
    div = CUI.dom.div("ez5-presentation-slide-overview");
    if (this._presentation) {
      counterLabelText = this.__getCounterLabelText();
      this.__counterLabel = new CUI.Label({
        text: counterLabelText
      });
      CUI.dom.append(div, this.__counterLabel);
      CUI.dom.setAttribute(div, "ui", "presentation.slide.number:" + counterLabelText);
    }
    CUI.dom.append(div, overview.DOM || overview);
    return div;
  };

  PresentationSlide.prototype.renderPresentation = function() {
    return CUI.util.assert(false, "PresentationSlide.renderPresentation", "Needs to be overwritten");
  };

  PresentationSlide.prototype.renderOverview = function() {
    return this.renderPresentation();
  };

  PresentationSlide.prototype.renderSlide = function() {
    return CUI.util.assert(false, "PresentationSlide.renderSlide", "Needs to be overwritten");
  };

  PresentationSlide.prototype.loadObject = function(global_object_id) {
    return this._presentation.loadObject(global_object_id);
  };

  PresentationSlide.prototype.__fillSlide = function(tmpl, key, hires, actionButton) {
    var addActionButton, object, replaceForTxt, txt;
    if (hires == null) {
      hires = false;
    }
    if (actionButton == null) {
      actionButton = false;
    }
    if (hires) {
      txt = new LocaLabel({
        loca_key: "presentation.slide.drag_info",
        centered: true,
        "class": "ez5-slide-drag-info"
      }).DOM;
    } else {
      txt = new LocaLabel({
        loca_key: "presentation.slide.text." + key,
        centered: true,
        "class": "ez5-slide-drag-info"
      }).DOM;
    }
    replaceForTxt = (function(_this) {
      return function() {
        return tmpl.replace(txt, key);
      };
    })(this);
    addActionButton = (function(_this) {
      return function() {
        if (actionButton) {
          return tmpl.append(new LocaButton({
            "class": "ez5-presentation-slide-remove-button",
            ui: "presentation.slide.remove.button",
            loca_key: "presentation.slide.trash",
            appearance: "transparent-border",
            onClick: function() {
              _this["__" + key] = null;
              return _this.updateSlide();
            }
          }), key);
        }
      };
    })(this);
    object = this["__" + key];
    if (object != null ? object.globalObjectId : void 0) {
      return this._presentation.loadObject(object.globalObjectId).done((function(_this) {
        return function(resultObject) {
          var assetBrowser, assetBrowserInfoControl, assets, content, enableTools, findAssetIdx, index, opts;
          assets = resultObject.getAssetsForBrowser(["detail", "standard"]);
          if (assets.length === 0 || assets === false) {
            tmpl.replace(resultObject.renderCardStandard({
              tags: false
            }), key);
            return;
          }
          findAssetIdx = function(idAsset) {
            var asset, i, index, len;
            for (index = i = 0, len = assets.length; i < len; index = ++i) {
              asset = assets[index];
              if (asset.getId() === idAsset) {
                return index;
              }
            }
            return -1;
          };
          index = findAssetIdx(object.asset_id);
          enableTools = actionButton ? [DetailInfo] : void 0;
          if (index === -1) {
            index = 0;
            object.asset_id = assets[index].getId();
          }
          assetBrowser = new AssetBrowser({
            resultObject: resultObject,
            assets: assets,
            hires: true,
            enable_tools: enableTools,
            start_idx: index
          });
          opts = {
            asset_browser_instance: assetBrowser
          };
          if (hires) {
            content = [resultObject.renderCardHires(opts)];
          } else {
            content = [resultObject.renderCardStandard(opts)];
          }
          if (actionButton) {
            CUI.Events.listen({
              node: assetBrowser.DOM,
              type: "asset-browser-idx-changed",
              call: function(_, info) {
                object.asset_id = info.asset.getId();
                return _this.updateSlide();
              }
            });
            assetBrowserInfoControl = new AssetBrowserInfoControl({
              assetBrowser: assetBrowser
            });
            content.push(assetBrowserInfoControl);
          }
          return tmpl.replace(content, key);
        };
      })(this)).fail((function(_this) {
        return function() {
          return tmpl.replace(new LocaLabel({
            loca_key: 'presentation.slide.error_loading',
            centered: true
          }), key);
        };
      })(this)).always((function(_this) {
        return function() {
          return addActionButton();
        };
      })(this));
    } else {
      return replaceForTxt();
    }
  };

  PresentationSlide.prototype.__getCounterLabelText = function() {
    return this._presentation.getIndexOfSlide(this) + 1;
  };

  PresentationSlide.prototype.hasRemoteObject = function() {
    var data, instance, k, v;
    data = this.getSaveData();
    for (k in data) {
      v = data[k];
      if (CUI.util.isPlainObject(v)) {
        if (v["global_object_id"]) {
          instance = v["global_object_id"].split("@")[1];
          if (instance && instance !== ez5.session.getInstance().name) {
            return true;
          }
        }
      }
    }
    return false;
  };

  PresentationSlide.__types = [];

  PresentationSlide.addType = function(type) {
    CUI.util.assert(new type() instanceof PresentationSlide, "PresentationSlide.addType", "Type needs to be instance of PresentationSlide.", {
      type: type
    });
    return this.__types.push(type);
  };

  PresentationSlide.getTypes = function() {
    return this.__types;
  };

  PresentationSlide.newFromData = function(presentation, data) {
    var found, i, len, ref, slide, type;
    ref = this.__types;
    for (i = 0, len = ref.length; i < len; i++) {
      type = ref[i];
      if (type.getType() === data.type) {
        found = type;
        break;
      }
    }
    CUI.util.assert(type, "PresentationSlide.newFromData", "Unable to load data, type " + data.type + " not found.", {
      data: data
    });
    slide = new type({
      presentation: presentation
    });
    slide.initFromData(data);
    return slide;
  };

  return PresentationSlide;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var PresentationSlideInfo,
  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;

PresentationSlideInfo = (function(superClass) {
  extend(PresentationSlideInfo, superClass);

  function PresentationSlideInfo() {
    return PresentationSlideInfo.__super__.constructor.apply(this, arguments);
  }

  PresentationSlideInfo.prototype.readOpts = function() {
    PresentationSlideInfo.__super__.readOpts.call(this);
    return this.initFromData({
      data: {}
    });
  };

  PresentationSlideInfo.prototype.isUserSelectable = function() {
    return false;
  };

  PresentationSlideInfo.prototype.initFromData = function(data) {
    PresentationSlideInfo.__super__.initFromData.call(this, data);
    this.data = data.data;
    if (!this.data.hasOwnProperty("title")) {
      this.data.title = this.getDefaultTitle();
    }
    if (CUI.util.isEmpty(this.data.info)) {
      this.data.info = "";
    }
    return this;
  };

  PresentationSlideInfo.prototype.getDefaultTitle = function() {
    return "";
  };

  PresentationSlideInfo.prototype.getSaveData = function() {
    var sd;
    sd = PresentationSlideInfo.__super__.getSaveData.call(this);
    sd.data = CUI.util.copyObject(this.data, true);
    delete sd.data._undo;
    return sd;
  };

  PresentationSlideInfo.prototype.getTemplate = function() {
    var tmpl;
    tmpl = new CUI.Template({
      name: "presentation-slide-info",
      map: {
        title: true,
        content: true
      }
    });
    return tmpl;
  };

  PresentationSlideInfo.prototype.renderSlide = function() {
    return new CUI.Form({
      data: this.data,
      undo_and_changed_support: false,
      onDataChanged: (function(_this) {
        return function() {
          return _this.update();
        };
      })(this),
      fields: [
        {
          type: CUI.Input,
          name: "title",
          maximize_horizontal: true,
          undo_and_changed_support: false,
          placeholder: $$('presentation.slide.info.placeholder.title'),
          content_size: false
        }, {
          type: CUI.Input,
          textarea: true,
          name: "info",
          maximize_horizontal: true,
          rows: 12,
          undo_and_changed_support: false,
          placeholder: $$('presentation.slide.info.placeholder.info'),
          content_size: true
        }
      ]
    }).start();
  };

  PresentationSlideInfo.getType = function() {
    return "info";
  };

  return PresentationSlideInfo;

})(PresentationSlide);

PresentationSlide.addType(PresentationSlideInfo);
// Generated by CoffeeScript 1.12.7
var PresentationSlideBullets,
  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;

PresentationSlideBullets = (function(superClass) {
  extend(PresentationSlideBullets, superClass);

  function PresentationSlideBullets() {
    return PresentationSlideBullets.__super__.constructor.apply(this, arguments);
  }

  PresentationSlideBullets.getType = function() {
    return "bullets";
  };

  PresentationSlideBullets.prototype.isUserSelectable = function() {
    return true;
  };

  PresentationSlideBullets.prototype.renderPresentation = function() {
    var bullet, i, len, li, list, ref, tmpl;
    tmpl = this.getTemplate();
    tmpl.replace(new CUI.Label({
      text: this.data.title
    }), "title");
    list = CUI.dom.ul("ez5-presentation-slide-bullets-list");
    ref = this.data.info.split("\n");
    for (i = 0, len = ref.length; i < len; i++) {
      bullet = ref[i];
      if (bullet.trim().length === 0) {
        continue;
      }
      li = CUI.dom.li();
      li.textContent = bullet.trim();
      CUI.dom.append(list, li);
    }
    tmpl.replace(new CUI.Label({
      "class": "ez5-presentation-bullets-list-label",
      multiline: true,
      content: list
    }), "content");
    return tmpl;
  };

  return PresentationSlideBullets;

})(PresentationSlideInfo);

PresentationSlide.addType(PresentationSlideBullets);
// Generated by CoffeeScript 1.12.7
var PresentationSlideStart,
  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;

PresentationSlideStart = (function(superClass) {
  extend(PresentationSlideStart, superClass);

  function PresentationSlideStart() {
    return PresentationSlideStart.__super__.constructor.apply(this, arguments);
  }

  PresentationSlideStart.prototype.isDeletable = function() {
    if (this.getDisplayRowIdx() === 0) {
      return false;
    } else {
      return true;
    }
  };

  PresentationSlideStart.prototype.renderPresentation = function() {
    var tmpl;
    tmpl = this.getTemplate();
    tmpl.replace(new CUI.Label({
      text: this.data.title
    }), "title");
    tmpl.replace(new CUI.Label({
      multiline: true,
      text: this.data.info
    }), "content");
    if (!CUI.util.isEmpty(this.data.title.trim())) {
      tmpl.addClass("ez5-presentation-slide-has-title");
    } else {
      tmpl.addClass("ez5-presentation-slide-no-title");
    }
    if (!CUI.util.isEmpty(this.data.info.trim())) {
      tmpl.addClass("ez5-presentation-slide-has-info");
    } else {
      tmpl.addClass("ez5-presentation-slide-no-info");
    }
    return tmpl;
  };

  PresentationSlideStart.prototype.getDefaultTitle = function() {
    return this._presentation.getCollection().renderNameAsText();
  };

  PresentationSlideStart.getType = function() {
    return "start";
  };

  PresentationSlideStart.prototype.allowRowMove = function() {
    return false;
  };

  return PresentationSlideStart;

})(PresentationSlideInfo);

PresentationSlide.addType(PresentationSlideStart);
// Generated by CoffeeScript 1.12.7
var PresentationSlideOne,
  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;

PresentationSlideOne = (function(superClass) {
  extend(PresentationSlideOne, superClass);

  function PresentationSlideOne() {
    return PresentationSlideOne.__super__.constructor.apply(this, arguments);
  }

  PresentationSlideOne.prototype.renderPresentation = function(hires) {
    var tmpl;
    if (hires == null) {
      hires = true;
    }
    tmpl = new CUI.Template({
      name: "presentation-slide-one",
      map: {
        center: true
      }
    });
    if (!this.__center) {
      this.__center = {};
    }
    this.__fillSlide(tmpl, "center", hires, false);
    return tmpl;
  };

  PresentationSlideOne.prototype.renderOverview = function() {
    return this.renderPresentation(false);
  };

  PresentationSlideOne.prototype.renderSlide = function() {
    var tmpl;
    tmpl = new CUI.Template({
      name: "presentation-slide-one",
      map: {
        center: true
      }
    });
    this.__fillSlide(tmpl, "center", true, true);
    new CUI.Droppable({
      element: tmpl.map.center,
      accept: (function(_this) {
        return function(ev, info) {
          var ref, ref1;
          if ((ref = info.globalDrag.objects) != null ? (ref1 = ref[0]) != null ? typeof ref1.getGlobalObjectId === "function" ? ref1.getGlobalObjectId() : void 0 : void 0 : void 0) {
            return true;
          } else {
            return false;
          }
        };
      })(this),
      drop: (function(_this) {
        return function(ev, info) {
          _this.__center.globalObjectId = info.globalDrag.objects[0].getGlobalObjectId();
          return _this.updateSlide();
        };
      })(this)
    });
    return tmpl;
  };

  PresentationSlideOne.prototype.initFromData = function(data) {
    if (data.center) {
      return this.__center = {
        globalObjectId: data.center.global_object_id,
        asset_id: data.center.asset_id
      };
    }
  };

  PresentationSlideOne.prototype.replaceGlobalObjectIds = function(gid_map) {
    var gid, gid_new;
    for (gid in gid_map) {
      gid_new = gid_map[gid];
      if (gid === this.__center) {
        this.__center = gid_new;
      }
    }
  };

  PresentationSlideOne.prototype.removeGlobalObjectIds = function(gids) {
    var gid, i, len, ref;
    for (i = 0, len = gids.length; i < len; i++) {
      gid = gids[i];
      if (gid === ((ref = this.__center) != null ? ref.globalObjectId : void 0)) {
        this.__center = null;
      }
    }
  };

  PresentationSlideOne.prototype.getGlobalObjectIds = function() {
    var gids, ref;
    gids = [];
    if ((ref = this.__center) != null ? ref.globalObjectId : void 0) {
      gids.push(this.__center.globalObjectId);
    }
    return gids;
  };

  PresentationSlideOne.prototype.getSaveData = function() {
    var ref, ref1, sd;
    sd = PresentationSlideOne.__super__.getSaveData.call(this);
    sd.center = {
      global_object_id: ((ref = this.__center) != null ? ref.globalObjectId : void 0) || null,
      asset_id: ((ref1 = this.__center) != null ? ref1.asset_id : void 0) || null
    };
    return sd;
  };

  PresentationSlideOne.getType = function() {
    return "one";
  };

  return PresentationSlideOne;

})(PresentationSlide);

PresentationSlide.addType(PresentationSlideOne);
// Generated by CoffeeScript 1.12.7
var PresentationSlideDuo,
  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;

PresentationSlideDuo = (function(superClass) {
  extend(PresentationSlideDuo, superClass);

  function PresentationSlideDuo() {
    return PresentationSlideDuo.__super__.constructor.apply(this, arguments);
  }

  PresentationSlideDuo.prototype.renderPresentation = function(hires) {
    var tmpl;
    if (hires == null) {
      hires = true;
    }
    tmpl = new CUI.Template({
      name: "presentation-slide-duo",
      map: {
        left: true,
        right: true
      }
    });
    if (!this.__left) {
      this.__left = {};
    }
    if (!this.__right) {
      this.__right = {};
    }
    this.__fillSlide(tmpl, "right", hires, false);
    this.__fillSlide(tmpl, "left", hires, false);
    return tmpl;
  };

  PresentationSlideDuo.prototype.renderOverview = function() {
    return this.renderPresentation(false);
  };

  PresentationSlideDuo.prototype.renderSlide = function() {
    var tmpl;
    tmpl = new CUI.Template({
      name: "presentation-slide-duo",
      map: {
        left: true,
        right: true
      }
    });
    this.__fillSlide(tmpl, "right", true, true);
    this.__fillSlide(tmpl, "left", true, true);
    new CUI.Droppable({
      element: tmpl.map.left,
      accept: (function(_this) {
        return function(ev, info) {
          var ref, ref1;
          if ((ref = info.globalDrag.objects) != null ? (ref1 = ref[0]) != null ? typeof ref1.getGlobalObjectId === "function" ? ref1.getGlobalObjectId() : void 0 : void 0 : void 0) {
            return true;
          } else {
            return false;
          }
        };
      })(this),
      drop: (function(_this) {
        return function(ev, info) {
          _this.__left.globalObjectId = info.globalDrag.objects[0].getGlobalObjectId();
          return _this.updateSlide();
        };
      })(this)
    });
    new CUI.Droppable({
      element: tmpl.map.right,
      accept: (function(_this) {
        return function(ev, info) {
          var ref, ref1;
          if ((ref = info.globalDrag.objects) != null ? (ref1 = ref[0]) != null ? typeof ref1.getGlobalObjectId === "function" ? ref1.getGlobalObjectId() : void 0 : void 0 : void 0) {
            return true;
          } else {
            return false;
          }
        };
      })(this),
      drop: (function(_this) {
        return function(ev, info) {
          _this.__right.globalObjectId = info.globalDrag.objects[0].getGlobalObjectId();
          return _this.updateSlide();
        };
      })(this)
    });
    return tmpl;
  };

  PresentationSlideDuo.prototype.initFromData = function(data) {
    if (data.left) {
      this.__left = {
        globalObjectId: data.left.global_object_id,
        asset_id: data.left.asset_id
      };
    }
    if (data.right) {
      return this.__right = {
        globalObjectId: data.right.global_object_id,
        asset_id: data.right.asset_id
      };
    }
  };

  PresentationSlideDuo.prototype.getGlobalObjectIds = function() {
    var gids;
    gids = [];
    if (this.__left.globalObjectId) {
      gids.push(this.__left.globalObjectId);
    }
    if (this.__right.globalObjectId) {
      gids.push(this.__right.globalObjectId);
    }
    return gids;
  };

  PresentationSlideDuo.prototype.replaceGlobalObjectIds = function(gid_map) {
    var gid, gid_new;
    for (gid in gid_map) {
      gid_new = gid_map[gid];
      if (gid === this.__left) {
        this.__left = gid_new;
      }
      if (gid === this.__right) {
        this.__right = gid_new;
      }
    }
  };

  PresentationSlideDuo.prototype.removeGlobalObjectIds = function(gids) {
    var gid, i, len, ref, ref1;
    for (i = 0, len = gids.length; i < len; i++) {
      gid = gids[i];
      if (gid === ((ref = this.__left) != null ? ref.globalObjectId : void 0)) {
        this.__left = null;
      }
      if (gid === ((ref1 = this.__right) != null ? ref1.globalObjectId : void 0)) {
        this.__right = null;
      }
    }
  };

  PresentationSlideDuo.prototype.getSaveData = function() {
    var ref, ref1, ref2, ref3, sd;
    sd = PresentationSlideDuo.__super__.getSaveData.call(this);
    sd.left = {
      global_object_id: ((ref = this.__left) != null ? ref.globalObjectId : void 0) || null,
      asset_id: ((ref1 = this.__left) != null ? ref1.asset_id : void 0) || null
    };
    sd.right = {
      global_object_id: ((ref2 = this.__right) != null ? ref2.globalObjectId : void 0) || null,
      asset_id: ((ref3 = this.__right) != null ? ref3.asset_id : void 0) || null
    };
    return sd;
  };

  PresentationSlideDuo.getType = function() {
    return "duo";
  };

  return PresentationSlideDuo;

})(PresentationSlide);

PresentationSlide.addType(PresentationSlideDuo);
// Generated by CoffeeScript 1.12.7
var PresentationSlideImageInfo,
  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;

PresentationSlideImageInfo = (function(superClass) {
  extend(PresentationSlideImageInfo, superClass);

  function PresentationSlideImageInfo() {
    return PresentationSlideImageInfo.__super__.constructor.apply(this, arguments);
  }

  PresentationSlideImageInfo.prototype.readOpts = function() {
    PresentationSlideImageInfo.__super__.readOpts.call(this);
    return this.data = {
      text: ""
    };
  };

  PresentationSlideImageInfo.prototype.renderPresentation = function(hires) {
    var bullet, i, len, li, list, ref, ref1, tmpl;
    if (hires == null) {
      hires = true;
    }
    tmpl = new CUI.Template({
      name: "presentation-slide-image-text",
      map: {
        left: true,
        right: true
      }
    });
    if (!this.__left) {
      this.__left = {};
    }
    this.__fillSlide(tmpl, "left", hires, false);
    list = CUI.dom.ul("ez5-presentation-slide-bullets-list");
    ref1 = ((ref = this.data.text) != null ? ref.split("\n") : void 0) || [];
    for (i = 0, len = ref1.length; i < len; i++) {
      bullet = ref1[i];
      if (bullet.trim().length === 0) {
        continue;
      }
      li = CUI.dom.li();
      li.textContent = bullet.trim();
      CUI.dom.append(list, li);
    }
    tmpl.replace(new CUI.Label({
      "class": "ez5-presentation-bullets-list-label",
      multiline: true,
      content: list
    }), "right");
    return tmpl;
  };

  PresentationSlideImageInfo.prototype.renderOverview = function() {
    return this.renderPresentation(false);
  };

  PresentationSlideImageInfo.prototype.renderSlide = function() {
    var textForm, tmpl;
    tmpl = new CUI.Template({
      name: "presentation-slide-image-text",
      map: {
        left: true,
        right: true
      }
    });
    this.__fillSlide(tmpl, "left", true, true);
    new CUI.Droppable({
      element: tmpl.map.left,
      accept: (function(_this) {
        return function(ev, info) {
          var ref, ref1;
          if ((ref = info.globalDrag.objects) != null ? (ref1 = ref[0]) != null ? typeof ref1.getGlobalObjectId === "function" ? ref1.getGlobalObjectId() : void 0 : void 0 : void 0) {
            return true;
          } else {
            return false;
          }
        };
      })(this),
      drop: (function(_this) {
        return function(ev, info) {
          _this.__left.globalObjectId = info.globalDrag.objects[0].getGlobalObjectId();
          return _this.updateSlide();
        };
      })(this)
    });
    textForm = new CUI.Form({
      data: this.data,
      undo_and_changed_support: false,
      onDataChanged: (function(_this) {
        return function() {
          return _this.update();
        };
      })(this),
      fields: [
        {
          type: CUI.Input,
          textarea: true,
          name: "text",
          maximize_horizontal: true,
          rows: 12,
          undo_and_changed_support: false,
          placeholder: $$('presentation.slide.info.placeholder.info'),
          content_size: true
        }
      ]
    });
    tmpl.replace(textForm.start(), "right");
    return tmpl;
  };

  PresentationSlideImageInfo.prototype.initFromData = function(data) {
    if (data.left) {
      this.__left = {
        globalObjectId: data.left.global_object_id,
        asset_id: data.left.asset_id
      };
    }
    return this.data = data.data || {};
  };

  PresentationSlideImageInfo.prototype.getGlobalObjectIds = function() {
    var gids;
    gids = [];
    if (this.__left.globalObjectId) {
      gids.push(this.__left.globalObjectId);
    }
    return gids;
  };

  PresentationSlideImageInfo.prototype.replaceGlobalObjectIds = function(gid_map) {
    var gid, gid_new;
    for (gid in gid_map) {
      gid_new = gid_map[gid];
      if (gid === this.__left) {
        this.__left = gid_new;
      }
    }
  };

  PresentationSlideImageInfo.prototype.removeGlobalObjectIds = function(gids) {
    var gid, i, len, ref;
    for (i = 0, len = gids.length; i < len; i++) {
      gid = gids[i];
      if (gid === ((ref = this.__left) != null ? ref.globalObjectId : void 0)) {
        this.__left = null;
      }
    }
  };

  PresentationSlideImageInfo.prototype.getSaveData = function() {
    var ref, ref1, sd;
    sd = PresentationSlideImageInfo.__super__.getSaveData.call(this);
    sd.data = CUI.util.copyObject(this.data, true);
    sd.left = {
      global_object_id: ((ref = this.__left) != null ? ref.globalObjectId : void 0) || null,
      asset_id: ((ref1 = this.__left) != null ? ref1.asset_id : void 0) || null
    };
    return sd;
  };

  PresentationSlideImageInfo.getType = function() {
    return "imageText";
  };

  return PresentationSlideImageInfo;

})(PresentationSlide);

PresentationSlide.addType(PresentationSlideImageInfo);
// Generated by CoffeeScript 1.12.7
var Filepicker,
  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;

Filepicker = (function(superClass) {
  extend(Filepicker, superClass);

  function Filepicker() {
    return Filepicker.__super__.constructor.apply(this, arguments);
  }

  Filepicker.prototype.type = function() {
    return CUI.util.assert(false, CUI.util.getObjectClass(this) + ".type", "Needs implentation.");
  };

  Filepicker.prototype.readOpts = function() {
    this.__type = this.type();
    return this.__TYPE = this.__type.toUpperCase();
  };

  Filepicker.prototype.setDownloadManagerClass = function(__downloadManagerCls) {
    this.__downloadManagerCls = __downloadManagerCls;
  };

  Filepicker.prototype.getCurrentTools = function(col) {
    var count, tools;
    tools = [];
    if (!(col instanceof CollectionSelection)) {
      return tools;
    }
    count = col.getCount();
    if (count === 0) {
      return tools;
    }
    tools.push(new ToolboxTool({
      group: col.getToolGroup(),
      name: col.getToolNamePrefix() + '.' + this.__type + '.download',
      sort: "D:3",
      loca_key: "tool." + col.getToolNamePrefix() + '.' + this.__type + '.download',
      loca_key_attrs: {
        count: count
      },
      favorite: true,
      run: (function(_this) {
        return function() {
          new _this.__downloadManagerCls({
            collection: col
          }).startExport();
        };
      })(this)
    }));
    return tools;
  };

  Filepicker.session_ready = function(type, plugin) {
    var base_conf, fp, lbl, set_filepicker, url_parm_name, url_parms;
    url_parms = CUI.decodeUrlData(document.location.search.substring(1));
    if (CUI.util.isString(type) && !type.endsWith('filepicker')) {
      url_parm_name = type + 'filepicker';
    } else {
      url_parm_name = type;
    }
    base_conf = ez5.session.getBaseConfig("plugin", plugin)[type] || {};
    set_filepicker = function(filepicker) {
      var fp;
      fp = JSON.parse(CUI.util.atou(filepicker));
      if (!(fp != null ? fp.callbackurl : void 0)) {
        return false;
      }
      if (fp.extensions == null) {
        fp.extensions = [];
      }
      if (fp.existing_files == null) {
        fp.existing_files = [];
      }
      fp.type = type;
      CUI.setSessionStorage('filepicker', fp);
      Filepicker.conf = fp;
      return true;
    };
    if (!url_parms[url_parm_name]) {
      fp = CUI.getSessionStorage('filepicker');
      if (!(fp != null ? fp.callbackurl : void 0) || (fp != null ? fp.type : void 0) !== type) {
        return;
      }
      if (fp.extensions == null) {
        fp.extensions = [];
      }
      if (fp.existing_files == null) {
        fp.existing_files = [];
      }
      Filepicker.conf = fp;
    } else {
      if (!base_conf.active) {
        CUI.setSessionStorage('filepicker');
        return CUI.problem({
          markdown: true,
          text: $$(type + '.filepicker.error.not_active.md')
        });
      }
      ez5.start.removeFromUrl(url_parm_name);
      if (!set_filepicker(url_parms[url_parm_name])) {
        CUI.setSessionStorage('filepicker');
        return;
      }
    }
    lbl = new LocaLabel({
      "class": 'ez5-modebar ez5-modebar--' + type,
      loca_key: type + '.filepicker.badge'
    });
    if (ez5.session.isDebug()) {
      new CUI.Tooltip({
        element: lbl,
        text: (function(_this) {
          return function() {
            return CUI.util.dump(Filepicker.conf);
          };
        })(this)
      });
    }
    document.documentElement.classList.add('ez5--has-modebar');
    if (window.opener) {
      CUI.Events.listen({
        node: window,
        type: 'beforeunload',
        call: (function(_this) {
          return function(ev) {
            return window.opener.postMessage({
              easydb: {
                action: 'close'
              }
            }, '*');
          };
        })(this)
      });
      CUI.Events.listen({
        node: window,
        type: 'message',
        call: (function(_this) {
          return function(ev) {
            var data, ref;
            console.debug("received a message from ", type, ev);
            data = ev.getNativeEvent().data;
            if (data != null ? (ref = data[type]) != null ? ref.config : void 0 : void 0) {
              return set_filepicker(data[type].config);
            }
          };
        })(this)
      });
      window.opener.postMessage({
        easydb: {
          action: 'send_config'
        }
      }, '*');
    }
    document.body.append(lbl.DOM);
    return Collection.registerPlugin(new this());
  };

  return Filepicker;

})(CollectionPlugin);
// Generated by CoffeeScript 1.12.7
var FilepickerDownloadManager,
  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,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

FilepickerDownloadManager = (function(superClass) {
  extend(FilepickerDownloadManager, superClass);

  function FilepickerDownloadManager() {
    return FilepickerDownloadManager.__super__.constructor.apply(this, arguments);
  }

  FilepickerDownloadManager.prototype.type = function() {
    return CUI.util.assert(false, CUI.util.getObjectClass(this) + ".type", "Needs implentation.");
  };

  FilepickerDownloadManager.prototype.readOpts = function() {
    FilepickerDownloadManager.__super__.readOpts.call(this);
    this.__base_conf = this.getBaseConfig();
    this.__type = this.type();
    return this.__TYPE = this.__type.toUpperCase();
  };

  FilepickerDownloadManager.prototype.getBaseConfig = function() {
    return CUI.util.assert(false, this.__cls + ".getBaseConfig", "Needs implementation");
  };

  FilepickerDownloadManager.prototype.getDownloadPrepareError = function() {
    return $$(this.__type + '.download.manager.prepare.error', {
      extensions: Filepicker.conf.extensions.join(', ')
    });
  };

  FilepickerDownloadManager.prototype.acceptVersionForDownload = function(version) {
    var ref;
    if (Filepicker.conf.extensions.length === 0) {
      return true;
    }
    if (ref = version.extension, indexOf.call(Filepicker.conf.extensions, ref) >= 0) {
      if (!this.__base_conf.send_files || !this.__base_conf.send_files_max_filesize) {
        return true;
      } else if (version.filesize <= this.__base_conf.send_files_max_filesize) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  };

  FilepickerDownloadManager.prototype.sendData = function(form_data, filepicker_files) {
    var xhr2;
    xhr2 = new CUI.XHR({
      method: "POST",
      headers: {},
      withCredentials: true,
      url: Filepicker.conf.callbackurl,
      body: form_data
    });
    return xhr2.start().done((function(_this) {
      return function(data) {
        var e, event, file, filepicker_file, j, len1, ref, ref1;
        if (!data) {
          console.warn("FilepickerDownloadManager: No data received. When sending files to the CMS, the CMS should return a list of files uploaded.");
          return;
        }
        try {
          ref = data.files;
          for (j = 0, len1 = ref.length; j < len1; j++) {
            file = ref[j];
            filepicker_file = CUI.util.findInArray(null, filepicker_files, function(v) {
              return v.uid = file.uid;
            });
            event = filepicker_file.event;
            event.info[_this.__type] = file;
            if (file.status === 'error') {
              event.type = _this.__TYPE + '_FILE_COPY_ERROR';
              _this.__upload_errors = _this.__upload_errors + 1;
            } else {
              event.type = _this.__TYPE + '_FILE_COPY';
            }
            EventPoller.saveEvent(event);
          }
        } catch (error) {
          e = error;
          console.warn("Error in FilepickerDownloadManager: ", e);
          CUI.alert({
            text: "Error - Server response: \n " + CUI.util.dump((ref1 = xhr2.getXHR()) != null ? ref1.response : void 0)
          });
        }
      };
    })(this)).fail((function(_this) {
      return function() {
        var _xhr, event, file, j, len1;
        _xhr = xhr2.getXHR();
        for (j = 0, len1 = filepicker_files.length; j < len1; j++) {
          file = filepicker_files[j];
          event = file.event;
          event.type = _this.__TYPE + '_FILE_COPY_ERROR';
          if (_xhr.responseJSON) {
            event.info.error = _xhr.responseJSON;
          } else {
            event.info.error = xhr2.statusText() + ":" + (_xhr.response || "<Empty Response>");
          }
          _this.__upload_errors = _this.__upload_errors + 1;
          EventPoller.saveEvent(event);
        }
      };
    })(this));
  };

  FilepickerDownloadManager.prototype.showProgress = function(loca_key, loca_key_attrs) {
    if (!this.__toaster) {
      this.__lbl = new LocaLabel({
        loca_key: loca_key,
        loca_key_attrs: loca_key_attrs
      });
      this.__toaster = new CUI.Toaster({
        content: this.__lbl,
        show_ms: 0
      });
      return this.__toaster.open();
    } else {
      return this.__lbl.setText($$(loca_key + '|text', loca_key_attrs));
    }
  };

  FilepickerDownloadManager.prototype.hideProgress = function() {
    var ref, ref1;
    if ((ref = this.__toaster) != null) {
      ref.destroy();
    }
    if ((ref1 = this.__lbl) != null) {
      ref1.destroy();
    }
    this.__toaster = null;
    return this.__lbl = null;
  };

  FilepickerDownloadManager.prototype.sendFiles = function(filepicker_files, blobs) {
    var dfr, existing_file, filepicker_file, get_form_data, go_on, j, len1, overwrite, overwrite_files, ref, send_data, show_report;
    dfr = new CUI.Deferred();
    if (this.__base_conf.send_files) {
      send_data = true;
    } else {
      send_data = false;
    }
    overwrite_files = [];
    overwrite = null;
    this.__upload_errors = null;
    ref = Filepicker.conf.existing_files;
    for (j = 0, len1 = ref.length; j < len1; j++) {
      existing_file = ref[j];
      filepicker_file = CUI.util.findInArray(null, filepicker_files, function(v) {
        return v.uid === existing_file.uid;
      });
      if (filepicker_file) {
        overwrite_files.push(filepicker_file);
      }
    }
    get_form_data = (function(_this) {
      return function(files) {
        var body, form_data;
        body = {
          files: files,
          window_preferences: {
            width: window.innerWidth,
            height: window.innerHeight
          },
          send_data: send_data
        };
        form_data = new FormData();
        form_data.append('body', JSON.stringify(body));
        return form_data;
      };
    })(this);
    show_report = (function(_this) {
      return function() {
        var attrs, loca, ref1, type;
        attrs = {
          errors: _this.__upload_errors,
          count: filepicker_files.length,
          success: filepicker_files.length - _this.__upload_errors
        };
        if (attrs.errors === attrs.count) {
          loca = 'error';
          type = 'problem';
        } else if (attrs.errors > 0) {
          loca = 'with_errors';
          type = 'problem';
        } else {
          loca = 'success';
          type = 'alert';
        }
        CUI[type]({
          text: $$(_this.__type + ".download.manager.report.upload_" + loca + ".md", attrs)
        });
        return (ref1 = window.opener) != null ? ref1.postMessage({
          easydb: {
            action: 'reload'
          }
        }, '*') : void 0;
      };
    })(this);
    dfr.always((function(_this) {
      return function() {
        return _this.hideProgress();
      };
    })(this));
    dfr.done((function(_this) {
      return function() {
        var l, len2;
        for (l = 0, len2 = filepicker_files.length; l < len2; l++) {
          filepicker_file = filepicker_files[l];
          CUI.util.pushOntoArray(filepicker_file, Filepicker.conf.existing_files, function(v) {
            return v.uid === filepicker_file.uid;
          });
        }
        CUI.setSessionStorage('filepicker', Filepicker.conf);
        return show_report();
      };
    })(this));
    dfr.fail((function(_this) {
      return function() {
        if (_this.__upload_errors === null) {
          return;
        }
        return show_report();
      };
    })(this));
    go_on = (function(_this) {
      return function() {
        var form_data;
        _this.__upload_errors = 0;
        if (!send_data) {
          _this.showProgress(_this.__type + '.download.manager.sending_files', {
            number: '1-' + filepicker_files.length,
            count: filepicker_files.length
          });
          form_data = get_form_data(filepicker_files);
          _this.sendData(form_data, filepicker_files).done(dfr.resolve).fail(dfr.reject);
          return dfr.promise();
        }
        return CUI.chunkWork.call(_this, {
          items: filepicker_files,
          chunk_size: 1,
          timeout: 0,
          call: function(items, idx, len) {
            var file, path;
            _this.showProgress(_this.__type + '.download.manager.sending_files', {
              number: idx + 1,
              count: len
            });
            file = CUI.util.copyObject(items[0], true);
            path = file.path;
            delete file.path;
            form_data = get_form_data([file]);
            form_data.append("files[]", new File([blobs[path]], file.filename));
            return _this.sendData(form_data, [file]);
          }
        }).done(dfr.resolve).fail(dfr.reject);
      };
    })(this);
    if (overwrite_files.length > 0) {
      new CUI.ConfirmationChoice({
        text: $$(this.__type + '.download.manager.ask_overwrite_files.msg.md', {
          count: overwrite_files.length
        }),
        choices: [
          {
            loca_key: this.__type + '.download.manager.ask_overwrite_files.button.cancel',
            cancel: true
          }, overwrite_files.length < filepicker_files.length ? {
            loca_key: this.__type + '.download.manager.ask_overwrite_files.button.skip',
            choice: 'skip'
          } : void 0, {
            loca_key: this.__type + '.download.manager.ask_overwrite_files.button.overwrite',
            choice: 'overwrite',
            primary: true
          }
        ]
      }).open().done((function(_this) {
        return function(choice) {
          var l, len2, overwrite_file;
          switch (choice.choice) {
            case 'skip':
              for (l = 0, len2 = overwrite_files.length; l < len2; l++) {
                overwrite_file = overwrite_files[l];
                CUI.util.removeFromArray(overwrite_file, filepicker_files);
              }
              break;
            case 'overwrite':
          }
          return go_on();
        };
      })(this)).fail(dfr.reject);
    } else {
      go_on();
    }
    return dfr.promise();
  };

  FilepickerDownloadManager.prototype.mapFromNodes = function(nodes) {
    var j, key, lang, len1, map, node, nodeName, ref, value, valueObj;
    map = {
      _items: 0
    };
    for (j = 0, len1 = nodes.length; j < len1; j++) {
      node = nodes[j];
      value = node.textContent;
      if (CUI.util.isEmpty(value)) {
        continue;
      }
      nodeName = node.nodeName;
      ref = node.nodeName.split('-'), key = ref[0], lang = ref[1];
      if (node.children.length > 0) {
        map[key] = this.mapFromNodes(node.children);
        if (map[key]) {
          map[key]._list = true;
        }
        continue;
      }
      valueObj = {
        'value': value,
        'type': node.getAttribute('type')
      };
      if (!lang) {
        lang = '_value';
      }
      if (!map[key]) {
        map[key] = {};
      }
      if (!map[key][lang]) {
        map[key][lang] = [valueObj];
      } else {
        map[key][lang].push(valueObj);
      }
      map._items = Math.max(map._items, map[key][lang].length);
    }
    return map;
  };

  FilepickerDownloadManager.prototype.getValue = function(info, idx) {
    var l1, l2, map, ref, value;
    if (idx == null) {
      idx = void 0;
    }
    value = (function(_this) {
      return function(v) {
        var i, k, len, parts, subparts;
        if (idx === void 0) {
          parts = [];
          len = v.length;
          i = 0;
          while (i < len) {
            subparts = [v[i].value];
            k = i;
            while (k < len - 1) {
              if (v[k].type === 'text_fixed') {
                subparts.push(v[k + 1].value);
                i++;
              } else {
                break;
              }
              k++;
            }
            parts.push(subparts.join(' '));
            i++;
          }
          return parts.join(' ');
        } else {
          return v[idx];
        }
      };
    })(this);
    if (info._list) {
      return this.getValueForList(info);
    }
    if (info._value) {
      return value(info._value);
    }
    map = {};
    ref = {
      'de': 'de-DE',
      'en': 'en-US',
      'es': 'es-ES',
      'it': 'it-IT'
    };
    for (l1 in ref) {
      l2 = ref[l1];
      if (info[l1]) {
        map[l2] = value(info[l1]);
      }
    }
    if (CUI.util.isEmptyObject(map)) {
      return void 0;
    } else {
      return map;
    }
  };

  FilepickerDownloadManager.prototype.getValueForList = function(info) {
    var _info, dataKey, j, key, keywordData, l, l1, l2, len1, len2, obj, ref, ref1, ref2, result, valueObj;
    result = [];
    dataKey = null;
    for (key in info) {
      _info = info[key];
      if (key !== '_list' && key !== '_items') {
        dataKey = key;
        break;
      }
    }
    if (!dataKey || !info[dataKey]) {
      return void 0;
    }
    keywordData = info[dataKey];
    ref = {
      'de': 'de-DE',
      'en': 'en-US',
      'es': 'es-ES',
      'it': 'it-IT'
    };
    for (l1 in ref) {
      l2 = ref[l1];
      if (keywordData[l1]) {
        ref1 = keywordData[l1];
        for (j = 0, len1 = ref1.length; j < len1; j++) {
          valueObj = ref1[j];
          obj = {};
          obj[l2] = valueObj.value;
          result.push(obj);
        }
      }
    }
    if (keywordData._value) {
      ref2 = keywordData._value;
      for (l = 0, len2 = ref2.length; l < len2; l++) {
        valueObj = ref2[l];
        obj = {};
        obj['default'] = valueObj.value;
        result.push(obj);
      }
    }
    if (result.length === 0) {
      return void 0;
    } else {
      return result;
    }
  };

  FilepickerDownloadManager.prototype.downloadFiles = function(_files) {
    var blobs, dfr, filepicker_files, files, idx, next_file, objects, ref, ref1, ref2, xmlParser, xml_info;
    files = ((ref = this["export"].getData()._transports) != null ? (ref1 = ref[0]) != null ? (ref2 = ref1._download) != null ? ref2._files : void 0 : void 0 : void 0) || [];
    if (files.length === 0 && ez5.version("6")) {
      files = _files.map((function(_this) {
        return function(file) {
          var path;
          path = decodeURI(file.path);
          return {
            path: path,
            url: _this.getDownloadUrl("file/" + (Export.encodeURIFilePath(file.path))),
            name: file.name
          };
        };
      })(this));
    }
    files.sort(function(a, b) {
      var get_value;
      get_value = (function(_this) {
        return function(file) {
          if (file.path.endsWith('.xml')) {
            return 0;
          } else if (file.path.endsWith('.json')) {
            return 1;
          } else {
            return 2;
          }
        };
      })(this);
      return CUI.util.compareIndex(get_value(a), get_value(b));
    });
    filepicker_files = [];
    objects = [];
    blobs = {};
    xml_info = {};
    xmlParser = new DOMParser();
    dfr = new CUI.Deferred();
    dfr.done((function(_this) {
      return function() {
        return _this.sendFiles(filepicker_files, blobs);
      };
    })(this));
    dfr.fail((function(_this) {
      return function() {
        _this.hideProgress();
        return CUI.problem({
          text: $$(_this.__type + '.download.manager.error.download')
        });
      };
    })(this));
    idx = -1;
    next_file = (function(_this) {
      return function() {
        var creds, file, restype, xhr;
        idx = idx + 1;
        if (idx === files.length) {
          dfr.resolve();
          return;
        }
        _this.showProgress(_this.__type + '.download.manager.loading_files', {
          number: idx + 1,
          count: files.length
        });
        file = files[idx];
        if (file.path.endsWith('.json')) {
          creds = true;
          restype = 'json';
        } else if (file.path.endsWith('.xml')) {
          creds = true;
          restype = 'text';
        } else if (_this.__base_conf.send_files) {
          creds = false;
          restype = 'blob';
        } else {
          return next_file();
        }
        xhr = new CUI.XHR({
          method: "GET",
          url: file.url,
          withCredentials: creds,
          responseType: restype
        });
        return xhr.start().fail(dfr.reject).done(function(data) {
          var __relative_filename, asset, asset_id, assets, bare_filename, do_export, doc, fileinfo, filepicker_file, info, info_map, j, k, key, l, len1, len2, map, ref3, ref4, ref5, ref6, ref7, ro, selected_versions, standard, v, version, vname;
          if (restype === 'text') {
            doc = xmlParser.parseFromString(data, 'text/xml');
            map = {};
            ref4 = _this.mapFromNodes(((ref3 = doc.getElementsByTagName('typo3')[0]) != null ? ref3.children : void 0) || []);
            for (key in ref4) {
              info = ref4[key];
              v = _this.getValue(info);
              if (!CUI.util.isEmpty(v)) {
                map[key] = v;
              }
            }
            xml_info[ez5.bareBasename(file.path)] = map;
            next_file();
            return;
          }
          if (restype === 'blob') {
            blobs[file.path] = data;
            next_file();
            return;
          }
          ro = new ResultObject();
          ro.setData(data);
          bare_filename = ez5.bareBasename(file.path);
          info_map = xml_info[bare_filename] || {};
          standard = ro.getStandard();
          if (CUI.util.isEmpty(_this.__base_conf.profile_mapping)) {
            ref6 = {
              title: ez5.loca.getBestFrontendValue(standard['1'].text) || "",
              description: ez5.loca.getBestFrontendValue((ref5 = standard['2']) != null ? ref5.text : void 0) || ""
            };
            for (k in ref6) {
              v = ref6[k];
              if (info_map[k] === void 0) {
                info_map[k] = v;
              }
            }
          }
          assets = ro.getAssetsForBrowser('detail');
          for (j = 0, len1 = assets.length; j < len1; j++) {
            asset = assets[j];
            if (!asset.value) {
              continue;
            }
            asset_id = asset.value._id;
            do_export = true;
            for (l = 0, len2 = filepicker_files.length; l < len2; l++) {
              filepicker_file = filepicker_files[l];
              if (filepicker_file.asset_id === asset_id) {
                do_export = false;
                break;
              }
            }
            if (!do_export) {
              continue;
            }
            ref7 = asset.value.versions || {};
            for (vname in ref7) {
              version = ref7[vname];
              if (ez5.version("6")) {
                selected_versions = _this["export"].data["export"].classes[version["class"]] || [];
                selected_versions = selected_versions.map(function(v) {
                  return v.version || "original";
                });
                if (indexOf.call(selected_versions, vname) < 0) {
                  continue;
                }
              }
              if (ez5.version("6")) {
                __relative_filename = version != null ? version.path : void 0;
              } else {
                __relative_filename = version != null ? version._relative_filename : void 0;
              }
              if (!__relative_filename) {
                continue;
              }
              fileinfo = {
                asset_id: asset_id,
                asset_version: vname,
                system_object_id: data._system_object_id,
                objecttype: data._objecttype,
                object_id: data[data._objecttype]._id,
                object_version: data[data._objecttype]._version,
                uuid: data._uuid,
                uid: data._uuid + '/' + asset_id + '/' + vname,
                event: {
                  objecttype: data._objecttype,
                  object_id: data[data._objecttype]._id,
                  object_version: data[data._objecttype]._version,
                  schema: 'USER',
                  info: {
                    asset: {
                      id: asset_id,
                      version: vname,
                      filesize: version.filesize,
                      filename: __relative_filename
                    }
                  }
                },
                filename: ez5.basename(__relative_filename)
              };
              if (_this.__base_conf.send_files) {
                if (ez5.version("6")) {
                  fileinfo.path = __relative_filename;
                } else {
                  fileinfo.path = ez5.dirname(file.path) + '/' + __relative_filename;
                }
              } else {
                fileinfo.url = ez5.dirname(file.url) + '/' + __relative_filename;
                if (ez5.version("6")) {
                  fileinfo.url = Session.addToken(fileinfo.url);
                }
              }
              for (k in info_map) {
                v = info_map[k];
                fileinfo[k] = v;
              }
              filepicker_files.push(fileinfo);
            }
          }
          return next_file();
        });
      };
    })(this);
    next_file();
    return dfr.promise();
  };

  FilepickerDownloadManager.prototype.getTitle = function() {
    return $$(this.__type + '.download.manager.modal.title');
  };

  FilepickerDownloadManager.prototype.getButtonStartLocaKey = function() {
    return this.__type + '.download.manager.modal.button.start';
  };

  FilepickerDownloadManager.prototype.getExportSaveData = function() {
    var data;
    data = FilepickerDownloadManager.__super__.getExportSaveData.call(this);
    data["export"].json = true;
    data["export"].json_one_file_per_object = true;
    data["export"].xml = true;
    data["export"].xml_one_file_per_object = true;
    data["export"].mapping = this.__base_conf.profile_mapping;
    data._transports = [
      {
        type: 'download',
        packer: null
      }
    ];
    return data;
  };

  return FilepickerDownloadManager;

})(DownloadManager);
