// Generated by CoffeeScript 1.12.7
var CustomDataTypeCommonFacet, CustomDataTypeWithCommons,
  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;

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

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

  CustomDataTypeWithCommons.prototype.initData = function(data) {
    var cdata;
    if (!data[this.name()]) {
      cdata = null;
      data[this.name()] = cdata;
    } else {
      cdata = data[this.name()];
    }
    if (!cdata.url) {
      cdata.url = "";
    }
    return cdata;
  };

  CustomDataTypeWithCommons.prototype.renderFieldAsGroup = function() {
    return false;
  };

  CustomDataTypeWithCommons.prototype.renderRowAsBlock = function(data, top_level_data, opts) {
    return false;
  };

  CustomDataTypeWithCommons.prototype.getQueryFieldBadge = function(data) {
    var value;
    if (data[(this.name()) + ":unset"]) {
      value = $$("text.column.badge.without");
    } else {
      value = data[this.name()];
    }
    return {
      name: this.nameLocalized(),
      value: value
    };
  };

  CustomDataTypeWithCommons.prototype.supportsStandard = function() {
    return true;
  };

  CustomDataTypeWithCommons.prototype.supportsPrinting = function() {
    return true;
  };

  CustomDataTypeWithCommons.prototype.supportsFacet = function() {
    return true;
  };

  CustomDataTypeWithCommons.prototype.getFacet = function(opts) {
    opts.field = this;
    return new CustomDataTypeCommonFacet(opts);
  };

  CustomDataTypeWithCommons.prototype.getSortFunction = function() {
    return (function(_this) {
      return function(a, b) {
        var ref, ref1;
        return CUI.util.compareIndex(((ref = a[_this.name()]) != null ? ref.conceptName : void 0) || 'zzz', ((ref1 = b[_this.name()]) != null ? ref1.conceptName : void 0) || 'zzz');
      };
    })(this);
  };

  CustomDataTypeWithCommons.prototype.hasRenderForSort = function() {
    return true;
  };

  CustomDataTypeWithCommons.prototype.sortExtraOpts = function() {
    return [
      {
        text: "conceptName",
        value: "conceptName"
      }, {
        text: "conceptURI",
        value: "conceptURI"
      }
    ];
  };

  CustomDataTypeWithCommons.prototype.renderSearchInput = function(data, opts) {
    var search_token;
    if (opts == null) {
      opts = {};
    }
    return search_token = new SearchToken({
      column: this,
      data: data,
      fields: opts.fields
    }).getInput().DOM;
  };

  CustomDataTypeWithCommons.prototype.getFieldNamesForSearch = function() {
    return this.getFieldNames();
  };

  CustomDataTypeWithCommons.prototype.getFieldNamesForSuggest = function() {
    return this.getFieldNames();
  };

  CustomDataTypeWithCommons.prototype.getFieldNames = function() {
    var field_names;
    field_names = [this.fullName() + ".conceptURI", this.fullName() + ".conceptName"];
    return field_names;
  };

  CustomDataTypeWithCommons.prototype.getSearchFilter = function(data, key) {
    var filter, phrase, ref, str, val;
    if (key == null) {
      key = this.name();
    }
    if (data[key + ":unset"]) {
      filter = {
        type: "in",
        fields: [this.fullName() + ".conceptName"],
        "in": [null]
      };
      filter._unnest = true;
      filter._unset_filter = true;
      return filter;
    }
    filter = CustomDataTypeWithCommons.__super__.getSearchFilter.call(this, data, key);
    if (filter) {
      return filter;
    }
    if (CUI.util.isEmpty(data[key])) {
      return;
    }
    val = data[key];
    ref = Search.getPhrase(val), str = ref[0], phrase = ref[1];
    switch (data[key + ":type"]) {
      case "token":
      case "fulltext":
      case void 0:
        filter = {
          type: "match",
          mode: data[key + ":mode"],
          fields: this.getFieldNamesForSearch(),
          string: str,
          phrase: phrase
        };
        break;
      case "field":
        filter = {
          type: "in",
          fields: this.getFieldNamesForSearch(),
          "in": [str]
        };
    }
    return filter;
  };

  CustomDataTypeWithCommons.prototype.renderEditorInput = function(data, top_level_data, opts) {
    var name;
    name = this.name(opts);
    if (!data[name]) {
      data[name] = {
        conceptName: '',
        conceptURI: ''
      };
    }
    return this.__renderEditorInputPopover(data, data[name], opts);
  };

  CustomDataTypeWithCommons.prototype.__renderEditorInputPopover = function(data, cdata, opts, customButtonBarEntrys) {
    var classNameForBurgerMenuButton, layout, that;
    if (opts == null) {
      opts = {};
    }
    if (customButtonBarEntrys == null) {
      customButtonBarEntrys = false;
    }
    that = this;
    this.dotsButtonMenu = {};
    layout = {};
    classNameForBurgerMenuButton = 'pluginDirectSelectEditSearch';
    if (ez5.version("6")) {
      classNameForBurgerMenuButton = 'pluginDirectSelectEditSearchFylr';
    } else if (ez5.version("5")) {
      classNameForBurgerMenuButton = 'pluginDirectSelectEditSearch';
    }
    layout = new CUI.HorizontalLayout({
      "class": 'customPluginEditorLayout',
      center: {
        "class": ''
      },
      right: {
        content: new CUI.Buttonbar({
          buttons: [
            new CUI.Button({
              text: '',
              icon: new CUI.Icon({
                "class": "fa-ellipsis-v"
              }),
              "class": classNameForBurgerMenuButton,
              onClick: (function(_this) {
                return function(e, dotsButton) {
                  var deleteClear, detailinfo, itemList, menu_items, uriCall;
                  that.dotsButtonMenu = new CUI.Menu({
                    "class": "customDataTypeCommonsMenu",
                    element: dotsButton
                  }, menu_items = [
                    {
                      text: $$('custom.data.type.commons.controls.search.label'),
                      value: 'search',
                      icon_left: new CUI.Icon({
                        "class": "fa-search"
                      }),
                      onClick: function(e2, btn2) {
                        that.showEditPopover(dotsButton, data, cdata, layout, opts);
                        return that.dotsButtonMenu.hide();
                      }
                    }
                  ], typeof that.__getAdditionalTooltipInfo === "function" ? (detailinfo = {
                    text: $$('custom.data.type.commons.controls.detailinfo.label'),
                    value: 'detail',
                    icon_left: new CUI.Icon({
                      "class": "fa-info-circle"
                    }),
                    disabled: that.isEmpty(data, 0, opts),
                    onClick: function(eDetailInfo, btnDetailInfo) {
                      var tooltip;
                      tooltip = new CUI.Tooltip({
                        element: btnDetailInfo,
                        placement: 'w',
                        markdown: true,
                        show_ms: 1000,
                        hide_ms: 200,
                        content: function(tooltip) {
                          var encodedURI, extendedInfo_xhr;
                          if (!that.isEmpty(data, 0, opts)) {
                            encodedURI = encodeURIComponent(cdata.conceptURI);
                            extendedInfo_xhr = {
                              "xhr": void 0
                            };
                            that.__getAdditionalTooltipInfo(encodedURI, tooltip, extendedInfo_xhr);
                            return new CUI.Label({
                              icon: "spinner",
                              text: $$('custom.data.type.commons.modal.form.popup.loadingstring')
                            });
                          }
                        }
                      });
                      tooltip.show();
                      return CUI.Events.listen({
                        type: ["click", "dblclick", "mouseout"],
                        capture: true,
                        node: btnDetailInfo,
                        only_once: true,
                        call: (function(_this) {
                          return function(ev) {
                            return that.dotsButtonMenu.hide();
                          };
                        })(this)
                      });
                    }
                  }, menu_items.push(detailinfo)) : void 0, uriCall = {
                    text: $$('custom.data.type.commons.controls.calluri.label'),
                    value: 'uri',
                    icon_left: new CUI.Icon({
                      "class": "fa-external-link"
                    }),
                    disabled: that.isEmpty(data, 0, opts) || !CUI.parseLocation(cdata.conceptURI),
                    onClick: function() {
                      window.open(cdata.conceptURI, "_blank");
                      return that.dotsButtonMenu.hide();
                    }
                  }, menu_items.push(uriCall), deleteClear = {
                    text: $$('custom.data.type.commons.controls.delete.label'),
                    value: 'delete',
                    name: 'deleteValueFromDANTEPlugin',
                    "class": 'deleteValueFromDANTEPlugin',
                    icon_left: new CUI.Icon({
                      "class": "fa-trash"
                    }),
                    disabled: that.isEmpty(data, 0, opts),
                    onClick: function() {
                      cdata = {
                        conceptName: '',
                        conceptURI: ''
                      };
                      data[that.name(opts)] = cdata;
                      that.__updateResult(cdata, layout, opts);
                      return that.dotsButtonMenu.hide();
                    }
                  }, menu_items.push(deleteClear), (customButtonBarEntrys != null ? customButtonBarEntrys.length : void 0) > 0 ? menu_items.push.apply(menu_items, customButtonBarEntrys) : void 0, itemList = {
                    items: menu_items
                  });
                  that.dotsButtonMenu._auto_close_after_click = false;
                  that.dotsButtonMenu.setItemList(itemList);
                  return that.dotsButtonMenu.show();
                };
              })(this)
            })
          ]
        })
      }
    });
    this.layout = layout;
    CUI.Events.registerEvent({
      type: "custom-deleteDataFromPlugin",
      bubble: false
    });
    CUI.Events.listen({
      type: "custom-deleteDataFromPlugin",
      instance: that,
      node: layout,
      call: (function(_this) {
        return function() {
          var key;
          for (key in cdata) {
            delete cdata[key];
          }
          data[that.name(opts)] = cdata;
          opts.deleteDataFromPlugin = true;
          return that.__updateResult(cdata, layout, opts);
        };
      })(this)
    });
    this.__updateResult(cdata, layout, opts);
    opts.initialcallfrompoolmanager = false;
    return layout;
  };

  CustomDataTypeWithCommons.prototype.showEditPopover = function(btn, data, cdata, layout, opts) {
    var cdata_form, searchsuggest_xhr, suggest_Menu, that;
    that = this;
    suggest_Menu;
    searchsuggest_xhr = {
      "xhr": void 0
    };
    cdata.countOfSuggestions = 50;
    cdata_form = new CUI.Form({
      "class": 'cdtFormWithPadding',
      data: cdata,
      fields: that.__getEditorFields(cdata),
      onDataChanged: (function(_this) {
        return function(data, elem) {
          _this.__updateResult(cdata, layout, opts);
          _this.__setEditorFieldStatus(cdata, layout);
          return _this.__updateSuggestionsMenu(cdata, cdata_form, data.searchbarInput, elem, suggest_Menu, searchsuggest_xhr, layout, opts);
        };
      })(this)
    }).start();
    suggest_Menu = new CUI.Menu({
      element: cdata_form.getFieldsByName("searchbarInput")[0],
      use_element_width_as_min_width: true,
      "class": "customDataTypeCommonsMenu"
    });
    return this.popover = new CUI.Popover({
      element: btn,
      placement: "wn",
      "class": "commonPlugin_Popover",
      pane: {
        header_left: new CUI.Label({
          text: $$('custom.data.type.commons.popover.choose.label')
        }),
        content: cdata_form
      }
    }).show();
  };

  CustomDataTypeWithCommons.prototype.isEmpty = function(data, top_level_data, opts) {
    var ref, ref1;
    if (opts == null) {
      opts = {};
    }
    if ((opts != null ? opts.mode : void 0) === "expert") {
      if (typeof data[this.name(opts)] === 'object') {
        return CUI.util.isEmpty(data[this.name(opts)] != null);
      } else {
        return CUI.util.isEmpty((ref = data[this.name(opts)]) != null ? ref.trim() : void 0);
      }
    }
    return !((ref1 = data[this.name(opts)]) != null ? ref1.conceptName : void 0);
  };

  CustomDataTypeWithCommons.prototype.getSaveData = function(data, save_data, opts) {
    var cdata, conceptFulltext, conceptNameChosenByHand, conceptNameWithHierarchie, conceptStandard, frontendLanguage, frontendLanguages, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, that;
    that = this;
    if (opts.demo_data) {
      return {
        conceptName: 'Example',
        conceptURI: 'https://example.com'
      };
    }
    cdata = data[this.name(opts)] || ((ref = data._template) != null ? ref[this.name(opts)] : void 0);
    switch (this.getDataStatus(cdata)) {
      case "invalid":
        if (opts.copy) {
          return save_data[this.name(opts)] = null;
        } else {
          throw new InvalidSaveDataException();
        }
        break;
      case "empty":
        return save_data[this.name(opts)] = null;
      case "ok":
        conceptFulltext = {};
        if (cdata != null ? cdata._fulltext : void 0) {
          if ((ref1 = cdata._fulltext) != null ? ref1.string : void 0) {
            if (((ref2 = cdata._fulltext) != null ? ref2.string : void 0) !== '') {
              conceptFulltext.string = cdata._fulltext.string;
            }
          }
          if ((ref3 = cdata._fulltext) != null ? ref3.l10ntext : void 0) {
            if (cdata._fulltext.l10ntext) {
              conceptFulltext.l10ntext = cdata._fulltext.l10ntext;
            }
          }
          if ((ref4 = cdata._fulltext) != null ? ref4.text : void 0) {
            if (cdata._fulltext.text) {
              conceptFulltext.text = cdata._fulltext.text;
            }
          }
        } else {
          conceptFulltext.text = cdata.conceptName.trim();
        }
        conceptStandard = {};
        if (cdata != null ? cdata._standard : void 0) {
          if ((ref5 = cdata._standard) != null ? ref5.l10ntext : void 0) {
            if (cdata._standard.l10ntext) {
              conceptStandard.l10ntext = cdata._standard.l10ntext;
            }
          } else {
            if ((ref6 = cdata._standard) != null ? ref6.text : void 0) {
              if (((ref7 = cdata._standard) != null ? ref7.text : void 0) !== '') {
                conceptStandard.text = cdata._standard.text;
              }
            }
          }
          if ((ref8 = cdata._standard) != null ? ref8.geo : void 0) {
            if (cdata._standard.geo) {
              conceptStandard.geo = cdata._standard.geo;
            }
          }
        }
        frontendLanguages = ez5.loca.getLanguage();
        frontendLanguages = frontendLanguages.split('-');
        frontendLanguage = frontendLanguages[0];
        conceptNameChosenByHand = false;
        if (cdata != null ? cdata.conceptNameChosenByHand : void 0) {
          if (cdata.conceptNameChosenByHand === true) {
            conceptNameChosenByHand = true;
          }
        }
        conceptNameWithHierarchie = false;
        if (cdata != null ? cdata.conceptNameWithHierarchie : void 0) {
          if (cdata.conceptNameWithHierarchie === true) {
            conceptNameWithHierarchie = true;
          }
        }
        save_data[this.name(opts)] = {
          conceptName: cdata.conceptName.trim(),
          conceptURI: cdata.conceptURI.trim(),
          frontendLanguage: frontendLanguage,
          _fulltext: conceptFulltext,
          _standard: conceptStandard
        };
        if (cdata != null ? cdata.conceptAncestors : void 0) {
          if (cdata.conceptAncestors.length > 0) {
            if (Array.isArray(cdata.conceptAncestors)) {
              cdata.conceptAncestors = cdata.conceptAncestors.join(' ');
            }
            save_data[this.name(opts)]['conceptAncestors'] = cdata.conceptAncestors;
          }
        }
        if (cdata != null ? cdata.conceptSource : void 0) {
          if (typeof cdata.conceptSource === 'string') {
            if (cdata.conceptSource.length > 0) {
              save_data[this.name(opts)]['conceptSource'] = cdata.conceptSource;
            }
          }
        }
        if (cdata != null ? cdata.conceptGeoJSON : void 0) {
          if (typeof cdata.conceptGeoJSON === 'object') {
            if (Object.keys(cdata.conceptGeoJSON).length > 0) {
              save_data[this.name(opts)]['conceptGeoJSON'] = cdata.conceptGeoJSON;
            }
          }
        }
        if (cdata != null ? cdata.conceptNameChosenByHand : void 0) {
          if (cdata.conceptNameChosenByHand === true) {
            save_data[this.name(opts)]['conceptNameChosenByHand'] = true;
          }
        }
        if (cdata != null ? cdata.conceptNameWithHierarchie : void 0) {
          if (cdata.conceptNameWithHierarchie === true) {
            save_data[this.name(opts)]['conceptNameWithHierarchie'] = true;
          }
        }
        if (cdata != null ? cdata.facetTerm : void 0) {
          return save_data[this.name(opts)]['facetTerm'] = cdata.facetTerm;
        }
    }
  };

  CustomDataTypeWithCommons.prototype.__updateResult = function(cdata, layout, opts) {
    var displayURI, info, inputX, onelineButtonbar, onelineDisplay, options, ref, ref1, ref2, ref3, ref4, rendered, searchsuggest_xhr, suggest_Menu_directInput, that, topContent;
    that = this;
    if (opts.data) {
      opts.data[that.name(opts)] = cdata;
    }
    onelineDisplay = false;
    if (((ref = this.FieldSchema) != null ? (ref1 = ref.custom_settings) != null ? (ref2 = ref1.editor_display) != null ? ref2.value : void 0 : void 0 : void 0) === 'condensed' || (opts != null ? (ref3 = opts.custom_settings) != null ? (ref4 = ref3.editor_display) != null ? ref4.value : void 0 : void 0 : void 0) === 'condensed') {
      onelineDisplay = true;
    }
    if (cdata != null ? cdata.conceptURI : void 0) {
      displayURI = cdata.conceptURI;
      if (displayURI.length > 20) {
        displayURI = displayURI.replace('http://', '');
        displayURI = displayURI.replace('https://', '');
      }
      if (displayURI.length > 30) {
        displayURI = displayURI.replace('uri.gbv.de/terminology/', '…/');
      }
      topContent = {
        content: new CUI.Label({
          text: cdata.conceptName,
          multiline: true
        })
      };
      if (onelineDisplay && typeof that.__getAdditionalTooltipInfo === "function") {
        onelineButtonbar = new CUI.Buttonbar({
          buttons: [
            new CUI.Label({
              centered: false,
              text: cdata.conceptName,
              multiline: true
            }), new CUI.ButtonHref({
              name: "outputButtonHref",
              "class": "pluginResultButton",
              appearance: "link",
              size: "normal",
              href: cdata.conceptURI,
              target: "_blank",
              tooltip: {
                markdown: true,
                placement: 'nw',
                content: function(tooltip) {
                  var encodedURI, extendedInfo_xhr;
                  extendedInfo_xhr = {
                    "xhr": void 0
                  };
                  encodedURI = encodeURIComponent(cdata.conceptURI);
                  that.__getAdditionalTooltipInfo(encodedURI, tooltip, extendedInfo_xhr);
                  return new CUI.Label({
                    icon: "spinner"
                  });
                }
              }
            })
          ]
        });
        onelineButtonbar.DOM.style.maxWidth = '92%';
        topContent = {
          content: onelineButtonbar
        };
      }
      info = new CUI.VerticalLayout({
        "class": 'ez5-info_commonPlugin',
        top: topContent,
        bottom: !onelineDisplay ? {
          content: new CUI.Button({
            name: "outputButtonHref",
            appearance: "flat",
            size: "normal",
            text: displayURI,
            tooltip: {
              markdown: true,
              placement: 'w',
              content: function(tooltip) {
                var encodedURI, extendedInfo_xhr;
                encodedURI = encodeURIComponent(cdata.conceptURI);
                extendedInfo_xhr = {
                  "xhr": void 0
                };
                if (typeof that.__getAdditionalTooltipInfo === "function") {
                  that.__getAdditionalTooltipInfo(encodedURI, tooltip, extendedInfo_xhr);
                  return new CUI.Label({
                    icon: "spinner",
                    text: $$('custom.data.type.commons.modal.form.popup.loadingstring')
                  });
                }
              }
            },
            onClick: (function(_this) {
              return function(evt, button) {
                return window.open(cdata.conceptURI, "_blank");
              };
            })(this)
          })
        } : void 0
      });
      layout.replace(info, 'center');
      layout.addClass('ez5-linked-object-edit');
      options = {
        "class": 'ez5-linked-object-container'
      };
      layout.__initPane(options, 'center');
    }
    if (!(cdata != null ? cdata.conceptURI : void 0)) {
      suggest_Menu_directInput;
      inputX = new CUI.Input({
        "class": "pluginDirectSelectEditInput",
        undo_and_changed_support: false,
        name: "directSelectInput",
        content_size: false,
        onKeyup: (function(_this) {
          return function(input) {
            var searchstring;
            searchstring = input.getValueForInput();
            if (typeof that.__updateSuggestionsMenu === "function") {
              return _this.__updateSuggestionsMenu(cdata, 0, searchstring, input, suggest_Menu_directInput, searchsuggest_xhr, layout, opts);
            }
          };
        })(this)
      });
      rendered = false;
      if (!(opts != null ? opts.callfrompoolmanager : void 0)) {
        rendered = true;
        inputX.render();
      }
      if (opts.initialcallfrompoolmanager === false && rendered === false) {
        inputX.render();
      }
      opts.initialcallfrompoolmanager = false;
      suggest_Menu_directInput = new CUI.Menu({
        element: inputX,
        use_element_width_as_min_width: true,
        "class": "customDataTypeCommonsMenu"
      });
      searchsuggest_xhr = {
        "xhr": void 0
      };
      layout.replace(inputX, 'center');
      layout.removeClass('ez5-linked-object-edit');
      options = {
        "class": ''
      };
      layout.__initPane(options, 'center');
    }
    if (!opts.deleteDataFromPlugin) {
      return that.__setEditorFieldStatus(cdata, layout);
    }
  };

  CustomDataTypeWithCommons.prototype.__setEditorFieldStatus = function(cdata, element) {
    switch (this.getDataStatus(cdata)) {
      case "invalid":
        element.addClass("cui-input-invalid");
        break;
      default:
        element.removeClass("cui-input-invalid");
    }
    CUI.Events.trigger({
      node: element,
      type: "editor-changed"
    });
    CUI.Events.trigger({
      node: element,
      type: "data-changed"
    });
    return this;
  };

  CustomDataTypeWithCommons.prototype.renderDetailOutput = function(data, top_level_data, opts) {
    return this.__renderButtonByData(data[this.name(opts)]);
  };

  CustomDataTypeWithCommons.prototype.getDataStatus = function(cdata) {
    var nameCheck, uriCheck;
    if (cdata) {
      if (cdata.conceptURI && cdata.conceptName) {
        uriCheck = CUI.parseLocation(cdata.conceptURI);
        nameCheck = cdata.conceptName ? cdata.conceptName.trim() : void 0;
        if (uriCheck && nameCheck) {
          return "ok";
        }
        if (cdata.conceptURI.trim() === '' && cdata.conceptName.trim() === '') {
          return "empty";
        }
        return "invalid";
      }
    }
    return "empty";
  };

  return CustomDataTypeWithCommons;

})(CustomDataType);

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

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

  CustomDataTypeCommonFacet.prototype.initOpts = function() {
    CustomDataTypeCommonFacet.__super__.initOpts.call(this);
    return this.addOpts({
      field: {
        mandatory: true,
        check: Field
      }
    });
  };

  CustomDataTypeCommonFacet.prototype.requestFacetWithLimit = function(obj) {
    return {
      limit: this.getLimit(),
      field: this._field.fullName() + ".conceptName",
      sort: "count",
      type: "term"
    };
  };

  CustomDataTypeCommonFacet.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) || [];
  };

  CustomDataTypeCommonFacet.prototype.renderObjectText = function(object) {
    return object.term;
  };

  CustomDataTypeCommonFacet.prototype.getObjectPath = function(obj) {
    return [obj.term];
  };

  CustomDataTypeCommonFacet.prototype.name = function() {
    return this._field.fullName() + ".conceptName";
  };

  CustomDataTypeCommonFacet.prototype.requestSearchFilter = function(obj) {
    return {
      bool: "must",
      fields: [this._field.fullName() + ".conceptName"],
      type: "in",
      "in": [obj.term]
    };
  };

  CustomDataTypeCommonFacet.prototype.getObjectsSorted = function(objects) {
    return CustomDataTypeCommonFacet.__super__.getObjectsSorted.call(this, objects);
  };

  CustomDataTypeCommonFacet.prototype.__isAndButtonAvailable = function() {
    return this._field.insideNested();
  };

  return CustomDataTypeCommonFacet;

})(FieldFacet);
// Generated by CoffeeScript 1.12.7
var CustomDataTypeDANTE,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[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; };

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

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

  CustomDataTypeDANTE.prototype.getFacet = function(opts) {
    opts.field = this;
    if (ez5.version("6")) {
      console.log("use fylr facet");
      new CustomDataTypeDANTEFacet(opts);
    }
    if (ez5.version("5")) {
      console.log("use easydb5 facet");
      return new CustomDataTypeCommonFacet(opts);
    }
  };

  CustomDataTypeDANTE.prototype.getCustomDataTypeName = function() {
    return "custom:base.custom-data-type-dante.dante";
  };

  CustomDataTypeDANTE.prototype.getCustomMaskSettings = function() {
    if (this.ColumnSchema) {
      return this.FieldSchema.custom_settings || {};
    } else {
      return {};
    }
  };

  CustomDataTypeDANTE.prototype.getCustomSchemaSettings = function() {
    if (this.ColumnSchema) {
      return this.ColumnSchema.custom_settings || {};
    } else {
      return {};
    }
  };

  CustomDataTypeDANTE.prototype.name = function(opts) {
    var ref;
    if (opts == null) {
      opts = {};
    }
    if (!this.ColumnSchema) {
      if ((opts != null ? opts.callfrompoolmanager : void 0) && (opts != null ? opts.name : void 0) !== '') {
        return opts.name;
      } else {
        return "noNameSet";
      }
    } else {
      return (ref = this.ColumnSchema) != null ? ref.name : void 0;
    }
  };

  CustomDataTypeDANTE.prototype.getCustomDataTypeNameLocalized = function() {
    return $$("custom.data.type.dante.name");
  };

  CustomDataTypeDANTE.prototype.getVocabularyNameFromDatamodel = function(opts) {
    var ref, xreturn;
    if (opts == null) {
      opts = {};
    }
    xreturn = (ref = this.getCustomSchemaSettings().vocabulary_name) != null ? ref.value : void 0;
    if (!xreturn) {
      if (opts != null ? opts.callfrompoolmanager : void 0) {
        if (opts != null ? opts.voc : void 0) {
          return opts != null ? opts.voc : void 0;
        }
      }
      xreturn = 'gender';
    }
    return xreturn;
  };


  /*
  getIngestPermissionStatus: ->
    status = false;
    if @getCustomSchemaSettings()?.insert_allowed
      if @getCustomSchemaSettings()?.insert_username
        if @getCustomSchemaSettings()?.insert_token
          if @getCustomSchemaSettings().insert_username != '' && @getCustomSchemaSettings().insert_token != ''
            status = true
    status
   */


  /*
  getCustomButtonBarEntryForNewRecordAddition: ->
    that = @
    addNew =
        text: $$('custom.data.type.commons.controls.addnew.label')
        value: 'new'
        name: 'addnewValueFromDANTEPlugin'
        class: 'addnewValueFromDANTEPlugin'
        icon_left: new CUI.Icon(class: "fa-plus")
        onClick: ->
          console.log "clicked on add-button"
           * open modal with form for entering of basic record information
          modal = new CUI.Modal
              placement: "c"
              pane:
                  content: "No Content. Fill it."
                  header_left: new CUI.Label( text: "LEFT" )
                  header_right: new CUI.Label( text: "RIGHT" )
                  footer_right: =>
                    [
                      new CUI.Button
                        text: "Fill"
                        class: "cui-dialog"
                        onClick: =>
                          @mod.append(@getBlindText())
                    ,
                      new CUI.Button
                        text: "Cancel"
                        class: "cui-dialog"
                        onClick: =>
                          @mod.destroy()
                    ,
                      new CUI.Button
                        text: "Ok"
                        class: "cui-dialog"
                        primary: true
                        onClick: =>
                          @mod.destroy()
                    ]
          modal.show()
          #that.__updateResult(cdata, layout, opts)
   */

  CustomDataTypeDANTE.prototype.renderPopupAsTreeview = function() {
    var ref, result;
    result = false;
    if (((ref = this.getCustomMaskSettings().editor_style) != null ? ref.value : void 0) === 'popover_with_treeview') {
      result = true;
    }
    return result;
  };

  CustomDataTypeDANTE.prototype.getActiveVocabularyName = function(cdata) {
    var ref, that, vocParameter;
    that = this;
    if (cdata.dante_PopoverVocabularySelect && ((ref = that.popover) != null ? ref.isShown() : void 0)) {
      vocParameter = cdata.dante_PopoverVocabularySelect;
    } else {
      vocParameter = that.getVocabularyNameFromDatamodel();
    }
    return vocParameter;
  };

  CustomDataTypeDANTE.prototype.renderSearchInput = function(data, opts) {
    var form, that;
    that = this;
    if (!data[this.name()]) {
      data[this.name()] = {};
    }
    that.callFromExpertSearch = true;
    form = this.renderEditorInput(data, '', {});
    CUI.Events.listen({
      type: "data-changed",
      node: form,
      call: (function(_this) {
        return function() {
          CUI.Events.trigger({
            type: "search-input-change",
            node: form
          });
          CUI.Events.trigger({
            type: "editor-changed",
            node: form
          });
          CUI.Events.trigger({
            type: "change",
            node: form
          });
          return CUI.Events.trigger({
            type: "input",
            node: form
          });
        };
      })(this)
    });
    return form.DOM;
  };

  CustomDataTypeDANTE.prototype.needsDirectRender = function() {
    return true;
  };

  CustomDataTypeDANTE.prototype.getSearchFilter = function(data, key) {
    var filter, objecttype, ref, ref1, ref2, ref3, that;
    if (key == null) {
      key = this.name();
    }
    that = this;
    objecttype = this.path();
    objecttype = objecttype.split('.');
    objecttype = objecttype[0];
    if (data[key + ":unset"]) {
      filter = {
        type: "in",
        fields: [this.fullName() + ".conceptName"],
        "in": [null]
      };
      filter._unnest = true;
      filter._unset_filter = true;
      return filter;
    }
    if (!that.renderPopupAsTreeview() || !((ref = data[key]) != null ? ref.experthierarchicalsearchmode : void 0)) {
      filter = {
        type: "complex",
        search: [
          {
            type: "in",
            mode: "fulltext",
            bool: "must",
            phrase: false,
            fields: [this.path() + '.' + this.name() + ".conceptURI"]
          }
        ]
      };
      if (!data[this.name()]) {
        filter.search[0]["in"] = [null];
      } else if ((ref1 = data[this.name()]) != null ? ref1.conceptURI : void 0) {
        filter.search[0]["in"] = [data[this.name()].conceptURI];
      } else {
        filter = null;
      }
    }
    if (that.renderPopupAsTreeview()) {
      if (data[key].experthierarchicalsearchmode === 'include_children') {
        filter = {
          type: "complex",
          search: [
            {
              type: "match",
              mode: "token",
              bool: "must",
              phrase: false,
              fields: [this.path() + '.' + this.name() + ".conceptAncestors"]
            }
          ]
        };
        if (!data[this.name()]) {
          filter.search[0].string = null;
        } else if ((ref2 = data[this.name()]) != null ? ref2.conceptURI : void 0) {
          filter.search[0].string = data[this.name()].conceptURI;
        } else {
          filter = null;
        }
      }
      if (data[key].experthierarchicalsearchmode === 'exact') {
        filter = {
          type: "complex",
          search: [
            {
              type: "in",
              mode: "fulltext",
              bool: "must",
              phrase: false,
              fields: [this.path() + '.' + this.name() + ".conceptURI"]
            }
          ]
        };
        if (!data[this.name()]) {
          filter.search[0]["in"] = [null];
        } else if ((ref3 = data[this.name()]) != null ? ref3.conceptURI : void 0) {
          filter.search[0]["in"] = [data[this.name()].conceptURI];
        } else {
          filter = null;
        }
      }
    }
    return filter;
  };

  CustomDataTypeDANTE.prototype.getQueryFieldBadge = function(data) {
    var ref, ref1, ref2, searchModeAddition, value;
    if (!data[this.name()]) {
      value = $$("field.search.badge.without");
    } else if (!((ref = data[this.name()]) != null ? ref.conceptURI : void 0)) {
      value = $$("field.search.badge.without");
    } else {
      value = data[this.name()].conceptName;
    }
    if (((ref1 = data[this.name()]) != null ? ref1.experthierarchicalsearchmode : void 0) === 'exact' || ((ref2 = data[this.name()]) != null ? ref2.experthierarchicalsearchmode : void 0) === 'include_children') {
      searchModeAddition = $$("custom.data.type.dante.modal.form.popup.choose_expertsearchmode_." + data[this.name()].experthierarchicalsearchmode + "_short");
      value = searchModeAddition + ': ' + value;
    }
    return {
      name: this.nameLocalized(),
      value: value
    };
  };

  CustomDataTypeDANTE.prototype.__chooseLabelManually = function(cdata, layout, resultJSKOS, anchor, opts) {
    var button, choiceLabels, chooseLabelContent, chooseLabelPopover, key, key2, prefLabelButtons, ref, ref1, that, value, value2;
    that = this;
    choiceLabels = [];
    ref = resultJSKOS.prefLabel;
    for (key in ref) {
      value = ref[key];
      choiceLabels.push(value);
    }
    ref1 = resultJSKOS.altLabel;
    for (key in ref1) {
      value = ref1[key];
      for (key2 in value) {
        value2 = value[key2];
        choiceLabels.push(value2);
      }
    }
    prefLabelButtons = [];
    for (key in choiceLabels) {
      value = choiceLabels[key];
      button = new CUI.Button({
        text: value,
        appearance: "flat",
        icon_left: new CUI.Icon({
          "class": "fa-arrow-circle-o-right"
        }),
        "class": 'dantePlugin_SearchButton',
        onClick: (function(_this) {
          return function(evt, button) {
            cdata.conceptName = button.opts.text;
            that.__updateResult(cdata, layout, opts);
            if (that.popover) {
              that.popover.hide();
            }
            if (chooseLabelPopover) {
              chooseLabelPopover.hide();
            }
            return _this;
          };
        })(this)
      });
      prefLabelButtons.push(button);
    }
    chooseLabelPopover = new CUI.Popover({
      element: anchor,
      placement: "wn",
      "class": "commonPlugin_Popover"
    });
    chooseLabelContent = new CUI.VerticalLayout({
      "class": "cui-pane",
      top: {
        content: [
          new CUI.PaneHeader({
            left: {
              content: new CUI.Label({
                text: $$('custom.data.type.dante.modal.form.popup.choose_manual_label')
              })
            }
          })
        ]
      },
      center: {
        content: [prefLabelButtons]
      },
      bottom: null
    });
    chooseLabelPopover.setContent(chooseLabelContent);
    return chooseLabelPopover.show();
  };

  CustomDataTypeDANTE.prototype.__chooseExpertHierarchicalSearchMode = function(cdata, layout, resultJSKOS, anchor, opts) {
    var ConfirmationDialog, that;
    that = this;
    ConfirmationDialog = new CUI.ConfirmationDialog({
      text: $$('custom.data.type.dante.modal.form.popup.choose_expertsearchmode_label2') + '\n\n' + $$('custom.data.type.dante.modal.form.popup.choose_expertsearchmode_label3') + ': ' + cdata.conceptURI + '\n',
      title: $$('custom.data.type.dante.modal.form.popup.choose_expertsearchmode_label'),
      icon: "question",
      cancel: false,
      buttons: [
        {
          text: $$('custom.data.type.dante.modal.form.popup.choose_expertsearchmode_.exact'),
          onClick: (function(_this) {
            return function() {
              cdata.experthierarchicalsearchmode = 'exact';
              that.__updateResult(cdata, layout, opts);
              return ConfirmationDialog.destroy();
            };
          })(this)
        }, {
          text: $$('custom.data.type.dante.modal.form.popup.choose_expertsearchmode_.include_children'),
          primary: true,
          onClick: (function(_this) {
            return function() {
              cdata.experthierarchicalsearchmode = 'include_children';
              that.__updateResult(cdata, layout, opts);
              return ConfirmationDialog.destroy();
            };
          })(this)
        }
      ]
    });
    return ConfirmationDialog.show();
  };

  CustomDataTypeDANTE.prototype.__updateSuggestionsMenu = function(cdata, cdata_form, dante_searchstring, input, suggest_Menu, searchsuggest_xhr, layout, opts) {
    var delayMillisseconds, itemList, menu_items, that;
    that = this;
    delayMillisseconds = 50;
    menu_items = [
      {
        text: $$('custom.data.type.dante.modal.form.loadingSuggestions'),
        icon_left: new CUI.Icon({
          "class": "fa-spinner fa-spin"
        }),
        disabled: true
      }
    ];
    itemList = {
      items: menu_items
    };
    suggest_Menu.setItemList(itemList);
    return setTimeout((function() {
      var cache, dante_countSuggestions, ref, vocParameter;
      dante_searchstring = dante_searchstring.replace(/^\s+|\s+$/g, "");
      if (dante_searchstring.length === 0) {
        return;
      }
      suggest_Menu.show();
      dante_countSuggestions = 50;
      if (searchsuggest_xhr.xhr !== void 0) {
        searchsuggest_xhr.xhr.abort();
      }
      cache = '&cache=0';
      if ((ref = that.getCustomMaskSettings().use_cache) != null ? ref.value : void 0) {
        cache = '&cache=1';
      }
      vocParameter = that.getActiveVocabularyName(cdata);
      if (opts != null ? opts.callfrompoolmanager : void 0) {
        vocParameter = that.getVocabularyNameFromDatamodel(opts);
      }
      searchsuggest_xhr.xhr = new CUI.XHR({
        url: location.protocol + '//api.dante.gbv.de/suggest?search=' + dante_searchstring + '&voc=' + vocParameter + '&language=' + that.getFrontendLanguage() + '&limit=' + dante_countSuggestions + cache
      });
      return searchsuggest_xhr.xhr.start().done(function(data_1, status, statusText) {
        var actualVocab, extendedInfo_xhr, fn, i, item, j, key, key2, len, len1, multibleVocs, part, ref1, ref2, ref3, ref4, showHeadlines, suggestion, tmp_items, unique_text_items, unique_text_suggestions, vocTest, vocTestArr, vocab;
        extendedInfo_xhr = {
          "xhr": void 0
        };
        showHeadlines = false;
        multibleVocs = false;
        vocTest = that.getVocabularyNameFromDatamodel();
        vocTestArr = vocTest.split('|');
        if (vocTestArr.length > 1) {
          multibleVocs = true;
        }
        if (!((ref1 = that.popover) != null ? ref1.isShown() : void 0)) {
          if (multibleVocs === false) {
            showHeadlines = false;
          } else {

          }
          if (multibleVocs === true) {
            showHeadlines = true;
          }
        } else if ((ref2 = that.popover) != null ? ref2.isShown() : void 0) {
          if (multibleVocs === true) {
            if ((cdata != null ? cdata.dante_PopoverVocabularySelect : void 0) !== '' && (cdata != null ? cdata.dante_PopoverVocabularySelect : void 0) !== vocTest) {
              showHeadlines = false;
            } else {

            }
            if ((cdata != null ? cdata.dante_PopoverVocabularySelect : void 0) === vocTest) {
              showHeadlines = true;
            }
          } else {
            if (multibleVocs === false) {
              showHeadlines = false;
            }
          }
        }
        actualVocab = '';
        tmp_items = [];
        unique_text_suggestions = [];
        unique_text_items = [];
        ref3 = data_1[1];
        fn = function(key) {
          var item;
          item = {
            text: suggestion,
            value: data_1[3][key],
            tooltip: {
              markdown: true,
              placement: "ne",
              content: function(tooltip) {
                var encodedURI;
                encodedURI = encodeURIComponent(data_1[3][key]);
                that.__getAdditionalTooltipInfo(encodedURI, tooltip, extendedInfo_xhr);
                return new CUI.Label({
                  icon: "spinner",
                  text: $$('custom.data.type.dante.modal.form.popup.loadingstring')
                });
              }
            }
          };
          tmp_items[vocab].push(item);
          if (indexOf.call(unique_text_suggestions, suggestion) < 0) {
            unique_text_suggestions.push(suggestion);
            item = {
              text: suggestion,
              value: suggestion
            };
            return unique_text_items.push(item);
          }
        };
        for (key = i = 0, len = ref3.length; i < len; key = ++i) {
          suggestion = ref3[key];
          vocab = 'default';
          if (showHeadlines) {
            vocab = data_1[3][key];
            vocab = vocab.replace('https://', '');
            vocab = vocab.replace('http://', '');
            vocab = vocab.replace('uri.gbv.de/terminology/', '');
            vocab = vocab.split('/').shift();
          }
          if (!Array.isArray(tmp_items[vocab])) {
            tmp_items[vocab] = [];
          }
          fn(key);
        }
        menu_items = [];
        actualVocab = '';
        for (vocab in tmp_items) {
          part = tmp_items[vocab];
          if (showHeadlines) {
            if ((actualVocab === '' || actualVocab !== vocab) && vocab !== 'default') {
              actualVocab = vocab;
              item = {
                divider: true
              };
              menu_items.push(item);
              item = {
                label: actualVocab
              };
              menu_items.push(item);
              item = {
                divider: true
              };
              menu_items.push(item);
            }
          }
          for (key2 = j = 0, len1 = part.length; j < len1; key2 = ++j) {
            suggestion = part[key2];
            menu_items.push(suggestion);
          }
        }
        itemList = {
          onClick: function(ev2, btn) {
            var ancestors, dataEntry_xhr, newLoaderPanel, ref4, searchUri, suggestAPIPath;
            if (!that.renderPopupAsTreeview() || !((ref4 = that.popover) != null ? ref4.isShown() : void 0)) {
              searchUri = btn.getOpt("value");
              if (that.popover) {
                newLoaderPanel = new CUI.Pane({
                  "class": "cui-pane",
                  top: {
                    content: [
                      new CUI.PaneHeader({
                        left: {
                          content: new CUI.Label({
                            text: $$('custom.data.type.dante.modal.form.popup.choose')
                          })
                        },
                        right: {
                          content: new CUI.EmptyLabel({
                            text: that.getVocabularyNameFromDatamodel()
                          })
                        }
                      })
                    ]
                  },
                  center: {
                    content: [
                      new CUI.HorizontalLayout({
                        maximize: true,
                        left: null,
                        center: {
                          content: new CUI.Label({
                            centered: true,
                            size: "big",
                            icon: "spinner",
                            text: $$('custom.data.type.dante.modal.form.popup.loadingstring')
                          })
                        },
                        right: null
                      })
                    ]
                  }
                });
                that.popover.setContent(newLoaderPanel);
              }

              /*
               */
              ancestors = '';
              if (that.renderPopupAsTreeview()) {
                ancestors = ',ancestors';
              }
              searchUri = encodeURIComponent(searchUri);
              suggestAPIPath = location.protocol + '//api.dante.gbv.de/data?uri=' + searchUri + cache + '&properties=+hiddenLabel,notation,scopeNote,definition,identifier,example,location,depiction,startDate,endDate,startPlace,endPlace' + ancestors;
              dataEntry_xhr = new CUI.XHR({
                url: suggestAPIPath
              });
              dataEntry_xhr.start().done(function(data_suggest, status, statusText) {
                var anchor, jskos, k, len2, ref5, ref6, ref7, ref8, ref9, resultJSKOS;
                resultJSKOS = data_suggest[0];
                cdata.conceptAncestors = [];
                if (that.renderPopupAsTreeview()) {
                  if ((resultJSKOS != null ? (ref5 = resultJSKOS.ancestors) != null ? ref5.length : void 0 : void 0) > 0) {
                    ref6 = resultJSKOS.ancestors;
                    for (k = 0, len2 = ref6.length; k < len2; k++) {
                      jskos = ref6[k];
                      cdata.conceptAncestors.push(jskos.uri);
                    }
                  }
                  cdata.conceptAncestors.push(searchUri);
                  cdata.conceptAncestors = cdata.conceptAncestors.join(' ');
                }
                if (resultJSKOS.uri) {
                  cdata.conceptURI = resultJSKOS.uri;
                  cdata._fulltext = ez5.DANTEUtil.getFullTextFromJSKOSObject(resultJSKOS);
                  cdata._standard = ez5.DANTEUtil.getStandardFromJSKOSObject(resultJSKOS);
                  cdata.facetTerm = ez5.DANTEUtil.getFacetTermFromJSKOSObject(resultJSKOS);
                  if (((ref7 = that.getCustomMaskSettings().allow_label_choice) != null ? ref7.value : void 0) && (opts != null ? opts.mode : void 0) === 'editor') {
                    if (newLoaderPanel) {
                      anchor = newLoaderPanel;
                    } else {
                      anchor = input;
                    }
                    return that.__chooseLabelManually(cdata, layout, resultJSKOS, anchor, opts);
                  } else {
                    if ((ref8 = resultJSKOS.prefLabel) != null ? ref8[that.getFrontendLanguage()] : void 0) {
                      cdata.conceptName = (ref9 = resultJSKOS.prefLabel) != null ? ref9[that.getFrontendLanguage()] : void 0;
                    } else {
                      cdata.conceptName = resultJSKOS.prefLabel[Object.keys(resultJSKOS.prefLabel)[0]];
                    }
                    that.__updateResult(cdata, layout, opts);
                    if (that.popover) {
                      that.popover.hide();
                    }
                    return this;
                  }
                }
              });
            }
            if (that.renderPopupAsTreeview() && that.popover) {
              if (cdata_form) {
                return cdata_form.getFieldsByName("searchbarInput")[0].setValue(btn.getText());
              }
            }
          },
          items: menu_items
        };
        if (that.renderPopupAsTreeview() && ((ref4 = that.popover) != null ? ref4.isShown() : void 0)) {
          itemList.items = unique_text_items;
        }
        if (itemList.items.length === 0) {
          itemList = {
            items: [
              {
                text: $$('custom.data.type.dante.modal.form.popup.suggest.nohit'),
                value: void 0
              }
            ]
          };
        }
        suggest_Menu.setItemList(itemList);
        return suggest_Menu.show();
      });
    }), delayMillisseconds);
  };

  CustomDataTypeDANTE.prototype.renderEditorInput = function(data, top_level_data, opts) {
    var cdata, dropdown, editorStyle, ref, ref1, ref2, ref3, ref4, that;
    that = this;
    if (!(opts != null ? opts.callfrompoolmanager : void 0)) {
      if (!data[this.name()]) {
        cdata = {
          conceptName: '',
          conceptURI: ''
        };
        if (((ref = this.getCustomMaskSettings().default_concept_uri) != null ? ref.value : void 0) && ((ref1 = this.getCustomMaskSettings().default_concept_name) != null ? ref1.value : void 0)) {
          cdata = {
            conceptName: (ref2 = this.getCustomMaskSettings().default_concept_name) != null ? ref2.value : void 0,
            conceptURI: (ref3 = this.getCustomMaskSettings().default_concept_uri) != null ? ref3.value : void 0,
            _fulltext: {},
            _standard: {},
            facetTerm: {},
            conceptAncestors: null
          };
        }
        data[this.name()] = cdata;
      } else {
        cdata = data[this.name()];
      }
    } else {
      cdata = data[this.name(opts)];
      if (!(cdata != null ? cdata.conceptURI : void 0)) {
        cdata = {};
      }
    }
    dropdown = false;
    if (opts != null ? opts.editorstyle : void 0) {
      editorStyle = opts.editorstyle;
    } else {
      if (((ref4 = this.getCustomMaskSettings().editor_style) != null ? ref4.value : void 0) === 'dropdown') {
        editorStyle = 'dropdown';
      } else {
        editorStyle = 'popup';
      }
    }
    if (editorStyle === 'dropdown') {
      return this.__renderEditorInputInline(data, cdata, opts);
    } else {
      return this.__renderEditorInputPopover(data, cdata, opts);
    }
  };

  CustomDataTypeDANTE.prototype.getFrontendLanguage = function() {
    var desiredLanguage, ref;
    desiredLanguage = typeof ez5 !== "undefined" && ez5 !== null ? (ref = ez5.loca) != null ? ref.getLanguage() : void 0 : void 0;
    if (desiredLanguage) {
      desiredLanguage = desiredLanguage.split('-');
      desiredLanguage = desiredLanguage[0];
    } else {
      desiredLanguage = false;
    }
    return desiredLanguage;
  };

  CustomDataTypeDANTE.prototype.__renderEditorInputInline = function(data, cdata, opts) {
    var cdata_form, fields, select, that;
    if (opts == null) {
      opts = {};
    }
    that = this;
    fields = [];
    select = {
      type: CUI.Select,
      undo_and_changed_support: false,
      empty_text: $$('custom.data.type.dante.modal.form.dropdown.loadingentries'),
      options: (function(_this) {
        return function(thisSelect) {
          var cache, dfr, ref, ref1, searchsuggest_xhr, values, voc, vocTest;
          dfr = new CUI.Deferred();
          values = [];
          cache = '&cache=0';
          if ((ref = _this.getCustomMaskSettings()) != null ? (ref1 = ref.use_cache) != null ? ref1.value : void 0 : void 0) {
            cache = '&cache=1';
          }
          vocTest = _this.getVocabularyNameFromDatamodel(opts);
          vocTest = vocTest.split('|');
          if (vocTest.length > 1) {
            voc = vocTest[0];
          } else {
            voc = _this.getVocabularyNameFromDatamodel(opts);
          }
          searchsuggest_xhr = new CUI.XHR({
            url: location.protocol + '//api.dante.gbv.de/suggest?search=&voc=' + voc + '&language=' + _this.getFrontendLanguage() + '&limit=1000' + cache
          });
          searchsuggest_xhr.start().done(function(data, status, statusText) {
            var givenOpt, givenUUID, i, item, j, k, key, len, len1, len2, ref2, ref3, select_items, suggestion, testUUID;
            select_items = [];
            item = {
              text: $$('custom.data.type.dante.modal.form.dropdown.choose'),
              value: null
            };
            select_items.push(item);
            ref2 = data[1];
            for (key = i = 0, len = ref2.length; i < len; key = ++i) {
              suggestion = ref2[key];
              item = {
                text: suggestion,
                value: data[3][key]
              };
              select_items.push(item);
            }
            if ((cdata != null ? cdata.conceptURI : void 0) !== '') {
              if (((ref3 = cdata.conceptURI) != null ? ref3.indexOf('uri.gbv.de/terminology') : void 0) > 0) {
                givenUUID = cdata != null ? cdata.conceptURI.split('/') : void 0;
                givenUUID = givenUUID.pop();
                for (j = 0, len1 = select_items.length; j < len1; j++) {
                  givenOpt = select_items[j];
                  if (givenOpt.value !== null) {
                    testUUID = givenOpt.value.split('/');
                    testUUID = testUUID.pop();
                    if (testUUID === givenUUID) {
                      thisSelect.setValue(givenOpt.value);
                      thisSelect.setText(givenOpt.text);
                    }
                  }
                }
              } else {
                for (k = 0, len2 = select_items.length; k < len2; k++) {
                  givenOpt = select_items[k];
                  if (givenOpt.value !== null) {
                    if (givenOpt.value === (cdata != null ? cdata.conceptURI : void 0)) {
                      thisSelect.setValue(givenOpt.value);
                      thisSelect.setText(givenOpt.text);
                    }
                  }
                }
              }
            }
            thisSelect.enable();
            return dfr.resolve(select_items);
          });
          return dfr.promise();
        };
      })(this),
      name: 'dante_InlineSelect'
    };
    fields.push(select);
    if (cdata.length === 0) {
      cdata = {};
    }
    cdata_form = new CUI.Form({
      data: cdata,
      onDataChanged: (function(_this) {
        return function() {
          var element, fulltext_xhr;
          element = cdata_form.getFieldsByName("dante_InlineSelect")[0];
          cdata.conceptURI = element.getValue();
          element.displayValue();
          cdata.conceptName = element.getText();
          cdata.conceptAncestors = null;
          if (cdata.conceptURI !== null) {
            fulltext_xhr = new CUI.XHR({
              url: location.protocol + '//api.dante.gbv.de/data?uri=' + encodeURIComponent(cdata.conceptURI) + '&cache=1&properties=+ancestors,hiddenLabel,notation,scopeNote,definition,identifier,example,location,depiction,startDate,endDate,startPlace,endPlace'
            });
            return fulltext_xhr.start().done(function(detail_data, status, statusText) {
              cdata._fulltext = ez5.DANTEUtil.getFullTextFromJSKOSObject(detail_data);
              cdata._standard = ez5.DANTEUtil.getStandardFromJSKOSObject(detail_data);
              cdata.facetTerm = ez5.DANTEUtil.getFacetTermFromJSKOSObject(detail_data);
              if (!(cdata != null ? cdata.conceptURI : void 0)) {
                cdata = {};
              }
              data[that.name(opts)] = cdata;
              data.lastsaved = Date.now();
              return CUI.Events.trigger({
                node: element,
                type: "editor-changed"
              });
            });
          }
        };
      })(this),
      fields: fields
    }).start();
    cdata_form.getFieldsByName("dante_InlineSelect")[0].disable();
    return cdata_form;
  };

  CustomDataTypeDANTE.prototype.__getAdditionalTooltipInfo = function(uri, tooltip, extendedInfo_xhr, context) {
    var mapbox_access_token, ref, that;
    if (context == null) {
      context = null;
    }
    that = this;
    if (context) {
      that = context;
    }
    if (extendedInfo_xhr.xhr !== void 0) {
      extendedInfo_xhr.xhr.abort();
    }
    if ((ref = that.getCustomSchemaSettings().mapbox_access_token) != null ? ref.value : void 0) {
      mapbox_access_token = that.getCustomSchemaSettings().mapbox_access_token.value;
    }
    extendedInfo_xhr.xhr = new CUI.XHR({
      url: location.protocol + '//api.dante.gbv.de/data?uri=' + uri + '&format=json&properties=+ancestors,hiddenLabel,notation,scopeNote,definition,identifier,example,location,depiction,startDate,endDate,startPlace,endPlace&cache=1'
    });
    extendedInfo_xhr.xhr.start().done(function(data, status, statusText) {
      var htmlContent;
      htmlContent = that.getJSKOSPreview(data, mapbox_access_token);
      tooltip.DOM.innerHTML = htmlContent;
      return tooltip.autoSize();
    });
  };

  CustomDataTypeDANTE.prototype.buildAndSetTreeviewLayout = function(popover, layout, cdata, cdata_form, that, returnDfr, opts) {
    var popoverVocabularySelectTest, treeview, treeviewDfr, treeviewPane, vocParameter;
    if (returnDfr == null) {
      returnDfr = false;
    }
    if (this != null ? this.callFromExpertSearch : void 0) {
      opts.callFromExpertSearch = this.callFromExpertSearch;
    } else {
      opts.callFromExpertSearch = false;
    }
    popoverVocabularySelectTest = cdata_form.getFieldsByName("dante_PopoverVocabularySelect")[0];
    if (popoverVocabularySelectTest != null ? popoverVocabularySelectTest.getValue() : void 0) {
      vocParameter = popoverVocabularySelectTest != null ? popoverVocabularySelectTest.getValue() : void 0;
    } else {
      vocParameter = that.getActiveVocabularyName(cdata);
      vocParameter = vocParameter.split('|');
      vocParameter = vocParameter[0];
    }
    treeview = new DANTE_ListViewTree(popover, layout, cdata, cdata_form, that, opts, vocParameter);
    if (returnDfr === false) {
      treeview.getTopTreeView(vocParameter, 1);
    } else {
      treeviewDfr = treeview.getTopTreeView(vocParameter, 1);
    }
    treeviewPane = new CUI.Pane({
      "class": "cui-pane dante_treeviewPane",
      top: {
        content: [
          new CUI.PaneHeader({
            left: {
              content: new CUI.Label({
                text: $$('custom.data.type.dante.modal.form.popup.choose')
              })
            },
            right: {
              content: new CUI.EmptyLabel({
                text: that.getVocabularyNameFromDatamodel()
              })
            }
          })
        ]
      },
      center: {
        content: [treeview.treeview, cdata_form]
      }
    });
    this.popover.setContent(treeviewPane);
    if (returnDfr === false) {
      return treeview;
    } else {
      return treeviewDfr;
    }
  };

  CustomDataTypeDANTE.prototype.showEditPopover = function(btn, data, cdata, layout, opts) {
    var cache, cdata_form, defaultPane, ref, resetButton, searchButton, searchsuggest_xhr, suggest_Menu, that;
    that = this;
    that.resettedPopup = false;
    suggest_Menu;
    cdata_form;
    this.popover = new CUI.Popover({
      element: btn,
      placement: "wn",
      "class": "commonPlugin_Popover",
      onHide: (function(_this) {
        return function() {
          var searchbar, vocDropdown;
          delete cdata.dante_PopoverVocabularySelect;
          vocDropdown = cdata_form.getFieldsByName("dante_PopoverVocabularySelect")[0];
          if (vocDropdown) {
            vocDropdown.reload();
          }
          searchbar = cdata_form.getFieldsByName("searchbarInput")[0];
          if (searchbar) {
            return searchbar.reset();
          }
        };
      })(this)
    });
    searchsuggest_xhr = {
      "xhr": void 0
    };
    cdata_form = new CUI.Form({
      "class": "danteFormWithPadding",
      data: cdata,
      fields: that.__getEditorFields(cdata),
      onDataChanged: (function(_this) {
        return function(data, elem) {
          that.__updateResult(cdata, layout, opts);
          if (elem.opts.name === 'dante_PopoverVocabularySelect' && that.renderPopupAsTreeview()) {
            _this.buildAndSetTreeviewLayout(_this.popover, layout, cdata, cdata_form, that, false, opts);
          }
          that.__setEditorFieldStatus(cdata, layout);
          if (elem.opts.name === 'searchbarInput' || elem.opts.name === 'dante_PopoverVocabularySelect') {
            return that.__updateSuggestionsMenu(cdata, cdata_form, data.searchbarInput, elem, suggest_Menu, searchsuggest_xhr, layout, opts);
          }
        };
      })(this)
    }).start();
    suggest_Menu = new CUI.Menu({
      element: cdata_form.getFieldsByName("searchbarInput")[0],
      use_element_width_as_min_width: true
    });
    if (that.renderPopupAsTreeview()) {
      this.buildAndSetTreeviewLayout(this.popover, layout, cdata, cdata_form, that, false, opts);
      cache = 0;
      if ((ref = this.getCustomMaskSettings().use_cache) != null ? ref.value : void 0) {
        cache = 1;
      }
      searchButton = new CUI.Button({
        text: $$('custom.data.type.dante.modal.form.popup.treeviewsearch'),
        icon_left: new CUI.Icon({
          "class": "fa-search"
        }),
        "class": 'dantePlugin_SearchButton',
        onClick: (function(_this) {
          return function(evt, button) {
            var newTreeview, searchTerm, vocParameter;
            suggest_Menu.hide();
            searchTerm = cdata_form.getFieldsByName("searchbarInput")[0].getValue();
            if (searchTerm.length > 2) {
              searchButton.setEnabled(false);
              resetButton.setEnabled(false);
              button.setIcon(new CUI.Icon({
                "class": "fa-spinner fa-spin"
              }));
              newTreeview = _this.buildAndSetTreeviewLayout(_this.popover, layout, cdata, cdata_form, that, false, opts);
              vocParameter = that.getActiveVocabularyName(cdata);
              newTreeview.getSearchResultTree(searchTerm, vocParameter, cache).done(function() {
                searchButton.setEnabled(true);
                resetButton.setEnabled(true);
                button.setIcon(new CUI.Icon({
                  "class": "fa-search"
                }));
                that.popover.position();
                setTimeout((function() {
                  return CUI.Events.trigger({
                    node: that.popover,
                    type: "content-resize"
                  });
                }), 50);
                return setTimeout((function() {
                  return CUI.Events.trigger({
                    node: that.popover,
                    type: "content-resize"
                  });
                }), 100);
              });
              return _this;
            }
          };
        })(this)
      });
      cdata_form.getFieldsByName("searchbarInput")[0].append(searchButton);
      resetButton = new CUI.Button({
        text: $$('custom.data.type.dante.modal.form.popup.treeviewreset'),
        icon_left: new CUI.Icon({
          "class": "fa-undo"
        }),
        "class": 'dantePlugin_ResetButton',
        onClick: (function(_this) {
          return function(evt, button) {
            var newTreeviewDfr;
            that.resettedPopup = true;
            cdata_form.getFieldsByName("searchbarInput")[0].setValue('').displayValue();
            searchButton.setEnabled(false);
            resetButton.setEnabled(false);
            button.setIcon(new CUI.Icon({
              "class": "fa-spinner fa-spin"
            }));
            newTreeviewDfr = _this.buildAndSetTreeviewLayout(_this.popover, layout, cdata, cdata_form, that, true, opts);
            return newTreeviewDfr.done(function() {
              searchButton.setEnabled(true);
              resetButton.setEnabled(true);
              return button.setIcon(new CUI.Icon({
                "class": "fa-undo"
              }));
            });
          };
        })(this)
      });
      cdata_form.getFieldsByName("searchbarInput")[0].append(resetButton);
    } else {
      defaultPane = new CUI.Pane({
        "class": "cui-pane",
        top: {
          content: [
            new CUI.PaneHeader({
              left: {
                content: new CUI.Label({
                  text: $$('custom.data.type.dante.modal.form.popup.choose')
                })
              },
              right: {
                content: new CUI.EmptyLabel({
                  text: that.getVocabularyNameFromDatamodel(opts)
                })
              }
            })
          ]
        },
        center: {
          content: [cdata_form]
        }
      });
      this.popover.setContent(defaultPane);
    }
    return this.popover.show();
  };

  CustomDataTypeDANTE.prototype.__getEditorFields = function(cdata) {
    var fields, option, select, that, vocTest, vocTestArr;
    that = this;
    fields = [];
    vocTest = that.getVocabularyNameFromDatamodel();
    vocTestArr = vocTest.split('|');
    if (vocTestArr.length > 1 || vocTest === '*') {
      select = {
        type: CUI.Select,
        undo_and_changed_support: false,
        name: 'dante_PopoverVocabularySelect',
        form: {
          label: $$("custom.data.type.dante.modal.form.dropdown.selectvocabularyLabel")
        },
        options: (function(_this) {
          return function(thisSelect) {
            var dfr, notationStr, searchsuggest_xhr, values;
            dfr = new CUI.Deferred();
            values = [];
            notationStr = '&notation=' + that.getVocabularyNameFromDatamodel();
            if (that.getVocabularyNameFromDatamodel() === '*') {
              notationStr = '';
            }
            searchsuggest_xhr = new CUI.XHR({
              url: location.protocol + '//api.dante.gbv.de/voc?cache=1' + notationStr
            });
            searchsuggest_xhr.start().done(function(data, status, statusText) {
              var entry, i, item, key, len, select_items;
              select_items = [];
              if (!that.renderPopupAsTreeview()) {
                item = {
                  text: $$('custom.data.type.dante.modal.form.dropdown.choosefromvocall'),
                  value: that.getVocabularyNameFromDatamodel()
                };
                select_items.push(item);
              }
              for (key = i = 0, len = data.length; i < len; key = ++i) {
                entry = data[key];
                item = {
                  text: entry.prefLabel.de,
                  value: entry.notation[0]
                };
                select_items.push(item);
              }
              thisSelect.enable();
              return dfr.resolve(select_items);
            });
            return dfr.promise();
          };
        })(this)
      };
      fields.push(select);
    }
    option = {
      type: CUI.Input,
      "class": "commonPlugin_Input",
      undo_and_changed_support: false,
      form: {
        label: $$("custom.data.type.dante.modal.form.text.searchbar")
      },
      placeholder: $$("custom.data.type.dante.modal.form.text.searchbar.placeholder"),
      name: "searchbarInput"
    };
    fields.push(option);
    return fields;
  };

  CustomDataTypeDANTE.prototype.__renderButtonByData = function(cdata) {
    var encodedURI, extendedInfo_xhr, that;
    that = this;
    switch (this.getDataStatus(cdata)) {
      case "empty":
        return new CUI.EmptyLabel({
          text: $$("custom.data.type.dante.edit.no_dante")
        }).DOM;
      case "invalid":
        return new CUI.EmptyLabel({
          text: $$("custom.data.type.dante.edit.no_valid_dante")
        }).DOM;
    }
    extendedInfo_xhr = {
      "xhr": void 0
    };
    encodedURI = encodeURIComponent(cdata.conceptURI);
    return new CUI.HorizontalLayout({
      maximize: true,
      left: {
        content: new CUI.Label({
          centered: false,
          text: cdata.conceptName
        })
      },
      center: {
        content: new CUI.ButtonHref({
          name: "outputButtonHref",
          "class": "pluginResultButton",
          appearance: "link",
          size: "normal",
          href: 'https://uri.gbv.de/terminology/?uri=' + encodedURI,
          target: "_blank",
          "class": "cdt_dante_smallMarginTop",
          tooltip: {
            markdown: true,
            placement: 'nw',
            content: function(tooltip) {
              that.__getAdditionalTooltipInfo(encodedURI, tooltip, extendedInfo_xhr);
              return new CUI.Label({
                icon: "spinner",
                text: $$('custom.data.type.dante.modal.form.popup.loadingstring')
              });
            }
          }
        })
      },
      right: null
    }).DOM;
  };

  CustomDataTypeDANTE.prototype.getCustomDataOptionsInDatamodelInfo = function(custom_settings) {
    var ref, ref1, tags;
    tags = [];
    if ((ref = custom_settings.vocabulary_name) != null ? ref.value : void 0) {
      tags.push($$("custom.data.type.dante.name") + ': ' + custom_settings.vocabulary_name.value);
    } else {
      tags.push($$("custom.data.type.dante.setting.schema.no_choosen_vocabulary"));
    }
    if ((ref1 = custom_settings.mapbox_access_token) != null ? ref1.value : void 0) {
      tags.push("✓ Mapbox-Access-Token");
    } else {
      tags.push("✘ Mapbox-Access-Token");
    }
    return tags;
  };

  return CustomDataTypeDANTE;

})(CustomDataTypeWithCommons);

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

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

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

  CustomDataTypeDANTEFacet.prototype.initOpts = function() {
    CustomDataTypeDANTEFacet.__super__.initOpts.call(this);
    return this.addOpts({
      field: {
        mandatory: true,
        check: Field
      }
    });
  };

  CustomDataTypeDANTEFacet.prototype.requestFacetWithLimit = function(obj) {
    return {
      limit: this.getLimit(),
      field: this._field.fullName() + ".facetTerm",
      sort: "count",
      type: "term"
    };
  };

  CustomDataTypeDANTEFacet.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) || [];
  };

  CustomDataTypeDANTEFacet.prototype.renderObjectText = function(object) {
    var label, parts;
    parts = object.term.split('@$@');
    label = '---';
    if (parts.length === 2) {
      if (parts[0] !== '') {
        label = parts[0];
      }
    }
    return label;
  };

  CustomDataTypeDANTEFacet.prototype.getObjectPath = function(obj) {
    return [obj.term];
  };

  CustomDataTypeDANTEFacet.prototype.name = function() {
    return this._field.fullName() + ".facetTerm";
  };

  CustomDataTypeDANTEFacet.prototype.requestSearchFilter = function(obj) {
    return {
      bool: "must",
      fields: [this._field.fullName() + ".facetTerm"],
      type: "in",
      "in": [obj.term]
    };
  };

  return CustomDataTypeDANTEFacet;

})(FieldFacet);
// Generated by CoffeeScript 1.12.7
CustomDataTypeDANTE.prototype.getJSKOSPreview = function(data, mapbox_access_token) {
  var altLabels, ancestors, bounds, colorPreview, definition, depictionPreview, encodedGeoJSON, endPlaces, example, hiddenLabels, html, htmlContent, i, imageSrc, json, jsonStr, key, key2, location, namewithpath, notations, prefLabel, prefLabels, ref, ref1, ref10, ref11, ref12, ref13, ref14, ref15, ref16, ref17, ref18, ref19, ref2, ref20, ref21, ref3, ref4, ref5, ref6, ref7, ref8, ref9, scopeNote, size, spaces, startPlaces, that, tmpPrefLabel, val, val2, value, value2, vp, xuri;
  if (mapbox_access_token == null) {
    mapbox_access_token = false;
  }
  that = this;
  html = '';
  ancestors = '';
  spaces = '';
  namewithpath = '';
  if (data instanceof Array) {
    data = data[0];
  }
  prefLabel = $$('custom.data.type.dante.modal.form.popup.jskospreview.nopreflabel');
  if (data != null ? data.prefLabel : void 0) {
    prefLabel = that.getPrefLabelFromJSKOS(data);
  }
  xuri = data.uri.replace(/terminology/g, '...');
  html += '<div style="font-size: 12px; color: #999;"><span class="cui-label-icon"><i class="fa  fa-external-link"></i></span>&nbsp;' + xuri + '</div>';
  html += '<h3><span class="cui-label-icon"><i class="fa  fa-info-circle"></i></span>&nbsp;' + prefLabel + '</h3>';
  if (data.ancestors) {
    data.ancestors = data.ancestors.reverse();
    ref = data.ancestors;
    for (key in ref) {
      val = ref[key];
      if (val !== null) {
        tmpPrefLabel = that.getPrefLabelFromJSKOS(val);
        spaces = '';
        i = 0;
        while (i < key) {
          spaces += '&nbsp;&nbsp;';
          i++;
        }
        namewithpath += tmpPrefLabel + ' > ';
        ancestors += spaces + '<span class="danteTooltipAncestors"><span class="cui-label-icon"><i class="fa fa-sitemap" aria-hidden="true"></i></span> ' + tmpPrefLabel + '</span><br />';
      }
    }
  }
  if (ancestors !== '') {
    html += ancestors + spaces + '<span class="danteTooltipAncestors">&nbsp;&nbsp;<span class="cui-label-icon"><i class="fa fa-arrow-circle-o-right" aria-hidden="true"></i></span> ' + prefLabel + '</span><br />';
    namewithpath += prefLabel;
  }
  if (namewithpath === '') {
    namewithpath = prefLabel;
  }
  prefLabels = '';
  if (data != null ? data.prefLabel : void 0) {
    ref1 = data.prefLabel;
    for (key in ref1) {
      val = ref1[key];
      if (val !== prefLabel) {
        prefLabels = ' - ' + val + ' (' + key + ')<br />' + prefLabels;
      }
    }
  }
  if (prefLabels) {
    html += '<h4>' + $$('custom.data.type.dante.modal.form.popup.jskospreview.terms') + '</h4>' + prefLabels;
  }
  altLabels = '';
  if (data.altLabel) {
    ref2 = data.altLabel;
    for (key in ref2) {
      val = ref2[key];
      for (key2 in val) {
        val2 = val[key2];
        altLabels = ' - ' + val2 + '<br />' + altLabels;
      }
    }
  }
  if (altLabels) {
    html += '<h4>' + $$('custom.data.type.dante.modal.form.popup.jskospreview.altterms') + '</h4>' + altLabels;
  }
  hiddenLabels = [];
  if (data.hiddenLabel) {
    ref3 = data.hiddenLabel;
    for (key in ref3) {
      val = ref3[key];
      for (key2 in val) {
        val2 = val[key2];
        hiddenLabels.push(val2);
      }
    }
  }
  if (hiddenLabels.length > 0) {
    hiddenLabels = hiddenLabels.join(', ');
    html += '<h4>' + $$('custom.data.type.dante.modal.form.popup.jskospreview.keywords') + '</h4>' + hiddenLabels;
  }
  notations = '';
  if (data.notation) {
    ref4 = data.notation;
    for (key in ref4) {
      val = ref4[key];
      notations = ' &#8226; ' + val + '<br />' + notations;
    }
  }
  if (notations) {
    html += '<h4>' + $$('custom.data.type.dante.modal.form.popup.jskospreview.notations') + '</h4>' + notations;
  }
  startPlaces = [];
  if (data.startDate || data.startPlace) {
    html += '<h4>' + $$('custom.data.type.dante.modal.form.popup.jskospreview.startDate') + '</h4>';
    if (data.startDate) {
      html += data.startDate + '<br />';
    }
    if (data.startPlace) {
      ref5 = data.startPlace;
      for (key in ref5) {
        val = ref5[key];
        startPlaces.push(' &#8226; ' + val.prefLabel.und);
      }
      startPlaces = startPlaces.filter(function(item, i, ar) {
        return ar.indexOf(item) === i;
      });
      html += startPlaces.join('<br />');
    }
  }
  endPlaces = [];
  if (data.endDate || data.endPlace) {
    html += '<h4>' + $$('custom.data.type.dante.modal.form.popup.jskospreview.endDate') + '</h4>';
    if (data.endDate) {
      html += data.endDate + '<br />';
    }
    if (data.endPlace) {
      ref6 = data.endPlace;
      for (key in ref6) {
        val = ref6[key];
        endPlaces.push(' &#8226; ' + val.prefLabel.und);
      }
      endPlaces = endPlaces.filter(function(item, i, ar) {
        return ar.indexOf(item) === i;
      });
      html += endPlaces.join('<br />');
    }
  }
  if (data.depiction) {
    depictionPreview = '';
    ref7 = data.depiction;
    for (key in ref7) {
      value = ref7[key];
      depictionPreview += '<div class="depictionPreview" style="background-image: url(' + value + ')"></div>';
    }
    if (depictionPreview !== '') {
      html += '<h4>' + $$('custom.data.type.dante.modal.form.popup.jskospreview.depiction') + '</h4>' + depictionPreview;
    }
  }
  if (notations !== '') {
    colorPreview = '';
    ref8 = data.notation;
    for (key in ref8) {
      value = ref8[key];
      if (/^#[0-9a-f]{6}/i.test(value)) {
        colorPreview += '<div class="colorPreview" style="background-color: ' + value + '"></div>';
      }
    }
    if (colorPreview !== '') {
      html += '<h4>' + $$('custom.data.type.dante.modal.form.popup.jskospreview.colors') + '</h4>' + colorPreview;
    }
  }
  location = '';
  if (data.location) {
    if (data.location.length > 0) {
      if (mapbox_access_token) {
        ref9 = data.location;
        for (key in ref9) {
          value = ref9[key];
          value = JSON.parse('{"geometry": ' + JSON.stringify(value) + '}');
          htmlContent = '{"type": "FeatureCollection","features": []}';
          jsonStr = '{"type": "FeatureCollection","features": []}';
          json = JSON.parse(jsonStr);
          json.features.push(value);
          bounds = geojsonExtent(json);
          if (bounds) {
            size = [500, 300];
            vp = geoViewport.viewport(bounds, size);
            encodedGeoJSON = value;
            encodedGeoJSON.properties = {};
            encodedGeoJSON.type = "Feature";
            encodedGeoJSON.properties['stroke-width'] = 4;
            encodedGeoJSON.properties['stroke'] = '#C20000';
            encodedGeoJSON = JSON.stringify(encodedGeoJSON);
            encodedGeoJSON = encodeURIComponent(encodedGeoJSON);
            if (vp.zoom > 16) {
              vp.zoom = 15;
            }
            imageSrc = window.location.protocol + '//api.mapbox.com/v4/mapbox.streets-satellite/geojson(' + encodedGeoJSON + ')/' + vp.center.join(',') + ',' + vp.zoom + '/' + size.join('x') + '@2x.png?access_token=' + mapbox_access_token;
            htmlContent = "<div class=\"mapImage\" style=\"background-image: url('" + imageSrc + "');\"></div>";
            location += htmlContent;
          }
        }
        if (location !== '') {
          html += '<h4>' + $$('custom.data.type.dante.modal.form.popup.jskospreview.georef') + '</h4>' + location;
        }
      }
    }
  }
  definition = '';
  if (data.definition) {
    if (data.definition.de) {
      ref10 = data.definition.de;
      for (key in ref10) {
        value = ref10[key];
        definition += value + '<br />';
      }
    }
    if (definition === '') {
      if (data.definition.en) {
        ref11 = data.definition.en;
        for (key in ref11) {
          value = ref11[key];
          definition += value + '<br />';
        }
      }
    }
    if (definition === '') {
      ref12 = data.definition;
      for (key in ref12) {
        value = ref12[key];
        ref13 = data.definition.key;
        for (key2 in ref13) {
          value2 = ref13[key2];
          definition += value2 + '<br />';
        }
      }
    }
  }
  if (definition) {
    html += '<h4>' + $$('custom.data.type.dante.modal.form.popup.jskospreview.definition') + '</h4>' + definition;
  }
  scopeNote = '';
  if (data.scopeNote) {
    if (data.scopeNote.de) {
      ref14 = data.scopeNote.de;
      for (key in ref14) {
        value = ref14[key];
        scopeNote += value + '<br />';
      }
    }
    if (scopeNote === '') {
      if (data.scopeNote.en) {
        ref15 = data.scopeNote.en;
        for (key in ref15) {
          value = ref15[key];
          scopeNote += value + '<br />';
        }
      }
    }
    if (scopeNote === '') {
      ref16 = data.scopeNote;
      for (key in ref16) {
        value = ref16[key];
        ref17 = data.scopeNote.key;
        for (key2 in ref17) {
          value2 = ref17[key2];
          scopeNote += value2 + '<br />';
        }
      }
    }
  }
  if (scopeNote) {
    html += '<h4>' + $$('custom.data.type.dante.modal.form.popup.jskospreview.scopenote') + '</h4>' + scopeNote;
  }
  example = '';
  if (data.example) {
    if (data.example.de) {
      ref18 = data.example.de;
      for (key in ref18) {
        value = ref18[key];
        example += value + '<br />';
      }
    }
    if (example === '') {
      if (data.example.en) {
        ref19 = data.example.en;
        for (key in ref19) {
          value = ref19[key];
          example += value + '<br />';
        }
      }
    }
    if (example === '') {
      ref20 = data.example;
      for (key in ref20) {
        value = ref20[key];
        ref21 = data.example.key;
        for (key2 in ref21) {
          value2 = ref21[key2];
          example += value2 + '<br />';
        }
      }
    }
  }
  if (example) {
    html += '<h4>' + $$('custom.data.type.dante.modal.form.popup.jskospreview.example') + '</h4>' + example;
  }
  html = '<style>.danteTooltip { padding: 10px; min-width:200px; } .danteTooltip h4 { margin-bottom: 0px; } .danteTooltip .danteTooltipAncestors { font-size: 13px; font-weight: bold; margin-top: 0px;} .danteTooltip .mapImage {background-color: #EFEFEF; position: relative; width: 100%; height: 150px; background-size: cover; background-repeat: no-repeat; margin-bottom: 6px; border-radius: 2px;} .danteTooltip .colorPreview{ width:100%; height: 100px; } .depictionPreview {background-size: contain; background-repeat: no-repeat; background-position: center center; width: 100%; height:150px; background-color: #EFEFEF;}</style><div class="danteTooltip">' + html + '</div>';
  return html;
};

CustomDataTypeDANTE.prototype.getPrefLabelFromJSKOS = function(jskos) {
  var desiredLanguage, frontendLanguages, key, prefLabel, prefLabelFallback, prefLabels, tmp, value;
  prefLabelFallback = $$("custom.data.type.dante.modal.form.popup.treeview.nopreflabel");
  if (!jskos.prefLabel) {
    return prefLabelFallback;
  }
  prefLabels = jskos.prefLabel;
  prefLabel = prefLabelFallback;
  desiredLanguage = ez5.loca.getLanguage();
  desiredLanguage = desiredLanguage.split('-');
  desiredLanguage = desiredLanguage[0];
  frontendLanguages = ez5.session.getConfigFrontendLanguages().slice();
  for (key in frontendLanguages) {
    value = frontendLanguages[key];
    tmp = value.split('-');
    tmp = tmp[0];
    frontendLanguages[key] = tmp;
  }
  if (prefLabels instanceof Array || prefLabels instanceof Object) {
    if (prefLabels.count === 0) {
      prefLabels = void 0;
    }
    if (prefLabels.hasOwnProperty(desiredLanguage)) {
      prefLabel = prefLabels[desiredLanguage];
    }
    if (!prefLabel || prefLabel === void 0 || prefLabel === 'undefined' || prefLabel === prefLabelFallback) {
      for (key in frontendLanguages) {
        value = frontendLanguages[key];
        if (prefLabels.hasOwnProperty(value)) {
          prefLabel = prefLabels[value];
        }
      }
      if (!prefLabel || prefLabel === void 0 || prefLabel === 'undefined' || prefLabel === prefLabelFallback) {
        for (key in prefLabels) {
          value = prefLabels[key];
          prefLabel = prefLabels[key];
          break;
        }
      }
    }
    return prefLabel;
  }
};
// Generated by CoffeeScript 1.12.7
var DANTE_ListViewTree, DANTE_ListViewTreeNode,
  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; };

DANTE_ListViewTree = (function() {
  function DANTE_ListViewTree(popover, editor_layout, cdata, cdata_form, context, dante_opts, vocParameter) {
    var column, options, row, that, treeview;
    this.popover = popover != null ? popover : null;
    this.editor_layout = editor_layout != null ? editor_layout : null;
    this.cdata = cdata != null ? cdata : null;
    this.cdata_form = cdata_form != null ? cdata_form : null;
    this.context = context != null ? context : null;
    this.dante_opts = dante_opts != null ? dante_opts : {};
    this.vocParameter = vocParameter != null ? vocParameter : 'test';
    options = {
      "class": "dantePlugin_Treeview",
      cols: ["maximize", "auto"],
      fixedRows: 0,
      fixedCols: 0,
      no_hierarchy: false
    };
    that = this;
    treeview = new CUI.ListViewTree(options);
    treeview.render();
    treeview.root.open();
    row = new CUI.ListViewRow();
    column = new CUI.ListViewColumn({
      colspan: 2,
      element: new CUI.Label({
        icon: "spinner",
        appearance: "title",
        text: $$("custom.data.type.dante.modal.form.popup.loadingstringtreeview")
      })
    });
    row.addColumn(column);
    treeview.appendRow(row);
    treeview.root.open();
    this.treeview = treeview;
    this.treeview;
  }

  DANTE_ListViewTree.prototype.getTopTreeView = function(vocName, cache) {
    var dfr, that, topTree_xhr, url;
    if (cache == null) {
      cache = 1;
    }
    dfr = new CUI.Deferred();
    that = this;
    topTree_xhr = {
      "xhr": void 0
    };
    if (cache !== 1 && cache !== 0) {
      cache = 1;
    }
    url = location.protocol + '//api.dante.gbv.de/voc/' + vocName + '/top?format=json&properties=+notation&limit=100&cache=' + cache;
    topTree_xhr.xhr = new CUI.XHR({
      url: url
    });
    topTree_xhr.xhr.start().done(function(data, status, statusText) {
      var hasNarrowers, i, jskos, key, len, newNode, prefLabel, ref;
      if (that.treeview.getRow(0)) {
        that.treeview.removeRow(0);
      }
      for (key = i = 0, len = data.length; i < len; key = ++i) {
        jskos = data[key];
        prefLabel = CustomDataTypeDANTE.prototype.getPrefLabelFromJSKOS(jskos);
        if (((ref = jskos.narrower) != null ? ref.length : void 0) > 0) {
          hasNarrowers = true;
        } else {
          hasNarrowers = false;
        }
        newNode = new DANTE_ListViewTreeNode({
          selectable: false,
          prefLabel: prefLabel,
          uri: jskos.uri,
          hasNarrowers: hasNarrowers,
          popover: that.popover,
          cdata: that.cdata,
          cdata_form: that.cdata_form,
          guideTerm: DANTE_ListViewTreeNode.prototype.isGuideTerm(jskos),
          context: that.context,
          vocParameter: that.vocParameter,
          dante_opts: that.dante_opts,
          editor_layout: that.editor_layout
        });
        that.treeview.addNode(newNode);
      }
      CUI.Events.trigger({
        node: that.popover,
        type: "content-resize"
      });
      dfr.resolve();
      return dfr.promise();
    });
    return dfr;
  };

  DANTE_ListViewTree.prototype.getSearchResultTree = function(searchTerm, vocName, cache) {
    var dfr, searchTree_xhr, that, url;
    if (cache == null) {
      cache = 1;
    }
    dfr = new CUI.Deferred();
    that = this;
    searchTree_xhr = {
      "xhr": void 0
    };
    url = location.protocol + '//api.dante.gbv.de/search?voc=' + vocName + '&query=' + searchTerm + '&format=json&limit=100&cache=' + cache + '&properties=+ancestors,notation&offset=0';
    searchTree_xhr.xhr = new CUI.XHR({
      url: url
    });
    searchTree_xhr.xhr.start().done(function(data, status, statusText) {
      var addToVirtualTree, ancestorLevel, ancestorValue, children, childrenCount, counter, getChildNodesFromVirtualTree, hasNarrowers, i, itselfAsAncestor, j, jskos, key, len, len1, maxCount, newNode, node, ref, value, virtualTree;
      that.treeview.removeAllRows();
      virtualTree = [];
      counter = 0;
      maxCount = 10000;
      addToVirtualTree = function(treePart, newNode, parentUri) {
        var nodeKey, nodeValue;
        if (counter > maxCount) {
          exit;
        }
        for (nodeKey in treePart) {
          nodeValue = treePart[nodeKey];
          if (nodeKey === parentUri) {
            if (!nodeValue['children'][newNode.uri]) {
              nodeValue['children'][newNode.uri] = newNode;
            }
            return;
          } else {
            addToVirtualTree(nodeValue['children'], newNode, parentUri);
          }
        }
      };
      for (key = i = 0, len = data.length; i < len; key = ++i) {
        value = data[key];
        if (data[key] !== null) {
          jskos = value;
          itselfAsAncestor = {
            prefLabel: jskos.prefLabel,
            uri: jskos.uri,
            type: jskos.type
          };
          jskos.ancestors.unshift(itselfAsAncestor);
          if (jskos.ancestors.length > 0) {
            jskos.ancestors = jskos.ancestors.reverse();
            ref = jskos.ancestors;
            for (ancestorLevel = j = 0, len1 = ref.length; j < len1; ancestorLevel = ++j) {
              ancestorValue = ref[ancestorLevel];
              node = {
                prefLabel: CustomDataTypeDANTE.prototype.getPrefLabelFromJSKOS(ancestorValue),
                uri: ancestorValue.uri,
                guideTerm: DANTE_ListViewTreeNode.prototype.isGuideTerm(ancestorValue),
                children: {}
              };
              if (ancestorLevel === 0) {
                if (!virtualTree[ancestorValue.uri]) {
                  virtualTree[ancestorValue.uri] = node;
                }
              } else if (ancestorLevel > 0) {
                addToVirtualTree(virtualTree, node, jskos.ancestors[ancestorLevel - 1].uri);
              }
            }
          }
        }
      }
      counter = 0;
      getChildNodesFromVirtualTree = function(treePart) {
        var childrenCount, hasNarrowers, newNode, nodeKey, nodeValue, nodes;
        nodes = [];
        counter++;
        if (counter > maxCount) {
          exit;
        }
        for (nodeKey in treePart) {
          nodeValue = treePart[nodeKey];
          childrenCount = Object.keys(nodeValue.children).length;
          hasNarrowers = childrenCount > 0 ? true : false;
          newNode = new DANTE_ListViewTreeNode({
            selectable: false,
            open: hasNarrowers,
            children: getChildNodesFromVirtualTree(nodeValue.children),
            prefLabel: nodeValue.prefLabel,
            uri: nodeValue.uri,
            vocParameter: that.vocParameter,
            hasNarrowers: hasNarrowers,
            guideTerm: nodeValue.guideTerm,
            popover: that.popover,
            cdata: that.cdata,
            cdata_form: that.cdata_form,
            context: that.context,
            dante_opts: that.dante_opts,
            editor_layout: that.editor_layout
          });
          nodes.push(newNode);
        }
        return nodes;
      };
      for (key in virtualTree) {
        value = virtualTree[key];
        childrenCount = Object.keys(value.children).length;
        hasNarrowers = childrenCount > 0 ? true : false;
        children = [];
        if (hasNarrowers) {
          children = getChildNodesFromVirtualTree(value.children);
        }
        newNode = new DANTE_ListViewTreeNode({
          selectable: false,
          open: hasNarrowers,
          hasChildren: hasNarrowers,
          children: children,
          prefLabel: value.prefLabel,
          uri: value.uri,
          vocParameter: that.vocParameter,
          hasNarrowers: hasNarrowers,
          guideTerm: value.guideTerm,
          popover: that.popover,
          cdata: that.cdata,
          cdata_form: that.cdata_form,
          context: that.context,
          dante_opts: that.dante_opts,
          editor_layout: that.editor_layout
        });
        that.treeview.addNode(newNode);
      }
      dfr.resolve();
      return dfr.promise();
    });
    return dfr;
  };

  return DANTE_ListViewTree;

})();

DANTE_ListViewTreeNode = (function(superClass) {
  var prefLabel, uri;

  extend(DANTE_ListViewTreeNode, superClass);

  function DANTE_ListViewTreeNode() {
    this.renderContent = bind(this.renderContent, this);
    this.isLeaf = bind(this.isLeaf, this);
    this.getChildren = bind(this.getChildren, this);
    this.isGuideTerm = bind(this.isGuideTerm, this);
    return DANTE_ListViewTreeNode.__super__.constructor.apply(this, arguments);
  }

  prefLabel = '';

  uri = '';

  DANTE_ListViewTreeNode.prototype.initOpts = function() {
    DANTE_ListViewTreeNode.__super__.initOpts.call(this);
    return this.addOpts({
      prefLabel: {
        check: String
      },
      uri: {
        check: String
      },
      vocParameter: {
        check: String
      },
      children: {
        check: Array
      },
      guideTerm: {
        check: Boolean,
        "default": false
      },
      hasNarrowers: {
        check: Boolean,
        "default": false
      },
      popover: {
        check: CUI.Popover
      },
      cdata: {
        check: "PlainObject",
        "default": {}
      },
      cdata_form: {
        check: CUI.Form
      },
      context: {
        check: CustomDataTypeDANTE
      },
      dante_opts: {
        check: "PlainObject",
        "default": {}
      },
      editor_layout: {
        check: CUI.HorizontalLayout
      }
    });
  };

  DANTE_ListViewTreeNode.prototype.readOpts = function() {
    return DANTE_ListViewTreeNode.__super__.readOpts.call(this);
  };

  DANTE_ListViewTreeNode.prototype.isGuideTerm = function(jskos) {
    if (indexOf.call(jskos.type, 'http://vocab.getty.edu/ontology#GuideTerm') >= 0) {
      return true;
    } else {
      return false;
    }
  };

  DANTE_ListViewTreeNode.prototype.getChildren = function() {
    var cache, children, dfr, getChildren_xhr, that, url;
    that = this;
    dfr = new CUI.Deferred();
    children = [];
    cache = '1';
    if (that._context.resettedPopup) {
      cache = '0';
    }
    url = location.protocol + '//api.dante.gbv.de/narrower?format=json&uri=' + this._uri + '&limit=100&cache=' + cache + '&voc=' + this._vocParameter;
    getChildren_xhr = {
      "xhr": void 0
    };
    getChildren_xhr.xhr = new CUI.XHR({
      url: url
    });
    getChildren_xhr.xhr.start().done(function(data, status, statusText) {
      var hasNarrowers, i, jskos, key, len, newNode, ref;
      for (key = i = 0, len = data.length; i < len; key = ++i) {
        jskos = data[key];
        prefLabel = CustomDataTypeDANTE.prototype.getPrefLabelFromJSKOS(jskos);
        if (((ref = jskos.narrower) != null ? ref.length : void 0) > 0) {
          hasNarrowers = true;
        } else {
          hasNarrowers = false;
        }
        newNode = new DANTE_ListViewTreeNode({
          selectable: false,
          prefLabel: prefLabel,
          uri: jskos.uri,
          vocParameter: that._vocParameter,
          hasNarrowers: hasNarrowers,
          popover: that._popover,
          cdata: that._cdata,
          cdata_form: that._cdata_form,
          guideTerm: that.isGuideTerm(jskos),
          context: that._context,
          dante_opts: that._dante_opts,
          editor_layout: that._editor_layout
        });
        children.push(newNode);
      }
      return dfr.resolve(children);
    });
    return dfr.promise();
  };

  DANTE_ListViewTreeNode.prototype.isLeaf = function() {
    if (this.opts.hasNarrowers === true) {
      return false;
    } else {
      return true;
    }
  };

  DANTE_ListViewTreeNode.prototype.renderContent = function() {
    var buttonBar, buttons, d, extendedInfo_xhr, icon, infoButton, plusButton, that, tooltipText;
    that = this;
    extendedInfo_xhr = {
      "xhr": void 0
    };
    d = CUI.dom.div();
    buttons = [];
    icon = 'fa-plus-circle';
    tooltipText = $$('custom.data.type.dante.modal.form.popup.add_choose');
    if (that._guideTerm) {
      icon = 'fa-sitemap';
      tooltipText = $$('custom.data.type.dante.modal.form.popup.add_sitemap');
    }
    plusButton = new CUI.Button({
      text: "",
      icon_left: new CUI.Icon({
        "class": icon
      }),
      active: false,
      group: "default",
      tooltip: {
        text: tooltipText
      },
      onClick: (function(_this) {
        return function() {
          var allDataAPIPath, cache, dataEntry_xhr;
          cache = '&cache=0';
          if (that._context.resettedPopup) {
            cache = '&cache=1';
          }
          allDataAPIPath = location.protocol + '//api.dante.gbv.de/data?uri=' + that._uri + cache + '&properties=+ancestors';
          dataEntry_xhr = new CUI.XHR({
            url: allDataAPIPath
          });
          return dataEntry_xhr.start().done(function(data_response, status, statusText) {
            var i, jskos, len, ref, ref1, ref2, ref3, ref4, ref5, ref6, resultJSKOS;
            resultJSKOS = data_response[0];
            that._cdata.conceptAncestors = [];
            if (resultJSKOS.ancestors.length > 0) {
              ref = resultJSKOS.ancestors;
              for (i = 0, len = ref.length; i < len; i++) {
                jskos = ref[i];
                that._cdata.conceptAncestors.push(jskos.uri);
              }
            }
            that._cdata.conceptAncestors.push(that._uri);
            that._cdata.conceptAncestors = that._cdata.conceptAncestors.join(' ');
            if (((ref1 = that._context) != null ? (ref2 = ref1.FieldSchema) != null ? (ref3 = ref2.custom_settings) != null ? (ref4 = ref3.allow_label_choice) != null ? ref4.value : void 0 : void 0 : void 0 : void 0) === true && ((ref5 = that._dante_opts) != null ? ref5.mode : void 0) === 'editor') {
              CustomDataTypeDANTE.prototype.__chooseLabelManually(that._cdata, that._editor_layout, resultJSKOS, that._editor_layout, that._dante_opts);
            }
            that._cdata.conceptName = that._prefLabel;
            that._cdata.conceptURI = that._uri;
            that._cdata._fulltext = ez5.DANTEUtil.getFullTextFromJSKOSObject(resultJSKOS);
            that._cdata._standard = ez5.DANTEUtil.getStandardFromJSKOSObject(resultJSKOS);
            that._cdata.facetTerm = ez5.DANTEUtil.getFacetTermFromJSKOSObject(resultJSKOS);
            if (((ref6 = that._dante_opts) != null ? ref6.callFromExpertSearch : void 0) === true) {
              CustomDataTypeDANTE.prototype.__chooseExpertHierarchicalSearchMode(that._cdata, that._editor_layout, resultJSKOS, that._editor_layout, that._dante_opts);
            }
            CustomDataTypeDANTE.prototype.__updateResult(that._cdata, that._editor_layout, that._dante_opts);
            return that._popover.hide();
          });
        };
      })(this)
    });
    plusButton.setEnabled(!that._guideTerm);
    buttons.push(plusButton);
    infoButton = new CUI.Button({
      text: "",
      icon_left: new CUI.Icon({
        "class": "fa-info-circle"
      }),
      active: false,
      group: "default",
      tooltip: {
        markdown: true,
        placement: "e",
        content: function(tooltip) {
          CustomDataTypeDANTE.prototype.__getAdditionalTooltipInfo(that._uri, tooltip, extendedInfo_xhr, that._context);
          return new CUI.Label({
            icon: "spinner",
            text: $$('custom.data.type.dante.modal.form.popup.loadingstring')
          });
        }
      }
    });
    buttons.push(infoButton);
    buttonBar = new CUI.Buttonbar({
      buttons: buttons
    });
    CUI.dom.append(d, CUI.dom.append(CUI.dom.div(), buttonBar.DOM));
    this.addColumn(new CUI.ListViewColumn({
      element: d,
      colspan: 1
    }));
    CUI.Events.trigger({
      node: that._popover,
      type: "content-resize"
    });
    return new CUI.Label({
      text: this._prefLabel
    });
  };

  return DANTE_ListViewTreeNode;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
ez5.DANTEUtil = (function() {
  function DANTEUtil() {}


  /*
  @name         getFullTextFromJSKOSObject
  @description  This function generates the _fulltext-Object, which is required for search
                   Structure is documented here: https://docs.easydb.de/en/technical/plugins/customdatatype/#general-keys
  @param        {object}                JSKOS                 a jskos-object
  @param        {array}                 databaseLanguages     a list of easydb5-languages
  @return       {object}                returns _standard-Object
   */

  DANTEUtil.getFullTextFromJSKOSObject = function(object, databaseLanguages) {
    var _fulltext, arrayValue, arrayValueOfObject, fullTextString, i, j, k, key, l, l10nObject, l10nObjectKey, l10nObjectValue, l10nObjectWithShortenedLanguages, l10nObjectWithShortenedLanguagesKey, l10nObjectWithShortenedLanguagesValue, language, len, len1, len2, len3, objectKey, objectKeys, objectValue, prefLabelOfArrayKey, prefLabelOfArrayValue, propertyType, ref, ref1, ref2, shortenedDatabaseLanguages, shortenedLanguage, value;
    if (databaseLanguages == null) {
      databaseLanguages = false;
    }
    if (databaseLanguages === false) {
      databaseLanguages = ez5.loca.getLanguageControl().getLanguages().slice();
    }
    shortenedDatabaseLanguages = databaseLanguages.map(function(value, key, array) {
      return value.split('-').shift();
    });
    if (Array.isArray(object)) {
      object = object[0];
    }
    _fulltext = {};
    fullTextString = '';
    l10nObject = {};
    l10nObjectWithShortenedLanguages = {};
    for (i = 0, len = databaseLanguages.length; i < len; i++) {
      language = databaseLanguages[i];
      l10nObject[language] = '';
    }
    for (j = 0, len1 = shortenedDatabaseLanguages.length; j < len1; j++) {
      language = shortenedDatabaseLanguages[j];
      l10nObjectWithShortenedLanguages[language] = '';
    }
    objectKeys = ['prefLabel', 'altLabel', 'hiddenLabel', 'identifier', 'notation', 'uri', 'scopeNote', 'definition', 'startDate', 'endDate', 'example', 'historyNote', 'note', 'changeNote', 'startPlace', 'endPlace'];
    for (key in object) {
      value = object[key];
      if (objectKeys.includes(key)) {
        propertyType = typeof value;
        if (propertyType === 'string') {
          fullTextString += value + ' ';
          for (l10nObjectWithShortenedLanguagesKey in l10nObjectWithShortenedLanguages) {
            l10nObjectWithShortenedLanguagesValue = l10nObjectWithShortenedLanguages[l10nObjectWithShortenedLanguagesKey];
            l10nObjectWithShortenedLanguages[l10nObjectWithShortenedLanguagesKey] = l10nObjectWithShortenedLanguagesValue + value + ' ';
          }
        }
        if (propertyType === 'object') {
          if (Array.isArray(object[key])) {
            ref = object[key];
            for (k = 0, len2 = ref.length; k < len2; k++) {
              arrayValue = ref[k];
              if (typeof arrayValue === 'string') {
                fullTextString += arrayValue + ' ';
                for (l10nObjectWithShortenedLanguagesKey in l10nObjectWithShortenedLanguages) {
                  l10nObjectWithShortenedLanguagesValue = l10nObjectWithShortenedLanguages[l10nObjectWithShortenedLanguagesKey];
                  l10nObjectWithShortenedLanguages[l10nObjectWithShortenedLanguagesKey] = l10nObjectWithShortenedLanguagesValue + arrayValue + ' ';
                }
              } else if (typeof arrayValue === 'object') {
                if (arrayValue != null ? arrayValue.prefLabel : void 0) {
                  ref1 = arrayValue.prefLabel;
                  for (prefLabelOfArrayKey in ref1) {
                    prefLabelOfArrayValue = ref1[prefLabelOfArrayKey];
                    fullTextString += prefLabelOfArrayValue + ' ';
                    for (l10nObjectWithShortenedLanguagesKey in l10nObjectWithShortenedLanguages) {
                      l10nObjectWithShortenedLanguagesValue = l10nObjectWithShortenedLanguages[l10nObjectWithShortenedLanguagesKey];
                      l10nObjectWithShortenedLanguages[l10nObjectWithShortenedLanguagesKey] = l10nObjectWithShortenedLanguagesValue + prefLabelOfArrayValue + ' ';
                    }
                  }
                }
              }
            }
          } else {
            ref2 = object[key];
            for (objectKey in ref2) {
              objectValue = ref2[objectKey];
              if (Array.isArray(objectValue)) {
                for (l = 0, len3 = objectValue.length; l < len3; l++) {
                  arrayValueOfObject = objectValue[l];
                  fullTextString += arrayValueOfObject + ' ';
                  if (l10nObjectWithShortenedLanguages.hasOwnProperty(objectKey)) {
                    l10nObjectWithShortenedLanguages[objectKey] += arrayValueOfObject + ' ';
                  }
                }
              }
              if (typeof objectValue === 'string') {
                fullTextString += objectValue + ' ';
                if (l10nObjectWithShortenedLanguages[objectKey]) {
                  l10nObjectWithShortenedLanguages[objectKey] += objectValue + ' ';
                }
              }
            }
          }
        }
      }
    }
    for (l10nObjectKey in l10nObject) {
      l10nObjectValue = l10nObject[l10nObjectKey];
      shortenedLanguage = l10nObjectKey.split('-')[0];
      if (l10nObjectWithShortenedLanguages[shortenedLanguage]) {
        l10nObject[l10nObjectKey] = l10nObjectWithShortenedLanguages[shortenedLanguage];
      }
    }
    _fulltext.text = fullTextString;
    _fulltext.l10ntext = l10nObject;
    return _fulltext;
  };


  /*
  @name         getStandardFromJSKOSObject
  @description  This function generates the _standard-Object, which is required for display-purposes
                   Structure is documented here: https://docs.easydb.de/en/technical/plugins/customdatatype/#general-keys
  @param        {object}     JSKOS     a jskos-object
  @return       {object}              returns _standard-Object
   */

  DANTEUtil.getStandardFromJSKOSObject = function(JSKOS, databaseLanguages) {
    var _standard, hasl10n, i, l10nObject, l10nObjectKey, l10nObjectValue, language, len, shortenedDatabaseLanguages, shortenedLanguage;
    if (databaseLanguages == null) {
      databaseLanguages = false;
    }
    if (databaseLanguages === false) {
      databaseLanguages = ez5.loca.getLanguageControl().getLanguages().slice();
    }
    shortenedDatabaseLanguages = databaseLanguages.map(function(value, key, array) {
      return value.split('-').shift();
    });
    if (Array.isArray(JSKOS)) {
      JSKOS = JSKOS[0];
    }
    _standard = {};
    l10nObject = {};
    for (i = 0, len = databaseLanguages.length; i < len; i++) {
      language = databaseLanguages[i];
      l10nObject[language] = '';
    }
    hasl10n = false;
    for (l10nObjectKey in l10nObject) {
      l10nObjectValue = l10nObject[l10nObjectKey];
      shortenedLanguage = l10nObjectKey.split('-')[0];
      if (JSKOS.prefLabel[shortenedLanguage]) {
        l10nObject[l10nObjectKey] = JSKOS.prefLabel[shortenedLanguage];
        hasl10n = true;
      }
    }
    if (hasl10n) {
      for (l10nObjectKey in l10nObject) {
        l10nObjectValue = l10nObject[l10nObjectKey];
        if (l10nObject[l10nObjectKey] === '') {
          l10nObject[l10nObjectKey] = JSKOS.prefLabel[Object.keys(JSKOS.prefLabel)[0]];
        }
      }
    }
    if (!hasl10n) {
      for (l10nObjectKey in l10nObject) {
        l10nObjectValue = l10nObject[l10nObjectKey];
        if (JSKOS.prefLabel['und']) {
          l10nObject[l10nObjectKey] = JSKOS.prefLabel['und'];
        } else if (JSKOS.prefLabel['zxx']) {
          l10nObject[l10nObjectKey] = JSKOS.prefLabel['zxx'];
        } else if (JSKOS.prefLabel['mis']) {
          l10nObject[l10nObjectKey] = JSKOS.prefLabel['mis'];
        } else if (JSKOS.prefLabel['mul']) {
          l10nObject[l10nObjectKey] = JSKOS.prefLabel['mul'];
        }
      }
    }
    _standard.l10ntext = l10nObject;
    return _standard;
  };


  /*
  @name         getFacetTermFromJSKOSObject
  @description  generates a json-structure, which is only used for facetting (aka filter) in frontend
   */

  DANTEUtil.getFacetTermFromJSKOSObject = function(JSKOS) {
    var _facet_term, databaseLanguages, hasl10n, i, l10nObject, l10nObjectKey, l10nObjectValue, language, len, shortenedDatabaseLanguages, shortenedLanguage;
    console.log("f:getFacetTermFromJSKOSObject");
    databaseLanguages = ez5.loca.getLanguageControl().getLanguages().slice();
    shortenedDatabaseLanguages = databaseLanguages.map(function(value, key, array) {
      return value.split('-').shift();
    });
    if (Array.isArray(JSKOS)) {
      JSKOS = JSKOS[0];
    }
    _facet_term = {};
    l10nObject = {};
    for (i = 0, len = databaseLanguages.length; i < len; i++) {
      language = databaseLanguages[i];
      l10nObject[language] = '';
    }
    hasl10n = false;
    for (l10nObjectKey in l10nObject) {
      l10nObjectValue = l10nObject[l10nObjectKey];
      shortenedLanguage = l10nObjectKey.split('-')[0];
      if (JSKOS.prefLabel[shortenedLanguage]) {
        l10nObject[l10nObjectKey] = JSKOS.prefLabel[shortenedLanguage];
        l10nObject[l10nObjectKey] = l10nObject[l10nObjectKey] + '@$@' + JSKOS.uri;
        hasl10n = true;
      }
    }
    if (hasl10n) {
      for (l10nObjectKey in l10nObject) {
        l10nObjectValue = l10nObject[l10nObjectKey];
        if (l10nObject[l10nObjectKey] === '') {
          l10nObject[l10nObjectKey] = JSKOS.prefLabel[Object.keys(JSKOS.prefLabel)[0]];
          l10nObject[l10nObjectKey] = l10nObject[l10nObjectKey] + '@$@' + JSKOS.uri;
        }
      }
    }
    if (!hasl10n) {
      for (l10nObjectKey in l10nObject) {
        l10nObjectValue = l10nObject[l10nObjectKey];
        if (JSKOS.prefLabel['und']) {
          l10nObject[l10nObjectKey] = JSKOS.prefLabel['und'];
        } else if (JSKOS.prefLabel['zxx']) {
          l10nObject[l10nObjectKey] = JSKOS.prefLabel['zxx'];
        } else if (JSKOS.prefLabel['mis']) {
          l10nObject[l10nObjectKey] = JSKOS.prefLabel['mis'];
        } else if (JSKOS.prefLabel['mul']) {
          l10nObject[l10nObjectKey] = JSKOS.prefLabel['mul'];
        }
        l10nObject[l10nObjectKey] = l10nObject[l10nObjectKey] + '@$@' + JSKOS.uri;
      }
    }
    _facet_term = l10nObject;
    return _facet_term;
  };

  return DANTEUtil;

})();
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var n;"undefined"!=typeof window?n=window:"undefined"!=typeof global?n=global:"undefined"!=typeof self&&(n=self),n.geojsonExtent=e()}}(function(){return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module){function getExtent(_){for(var ext=extent(),coords=geojsonCoords(_),i=0;i<coords.length;i++)ext.include(coords[i]);return ext}var geojsonCoords=require("geojson-coords"),traverse=require("traverse"),extent=require("extent"),geojsonTypes=["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon","Feature","FeatureCollection","GeometryCollection"];module.exports=function(_){return getExtent(_).bbox()},module.exports.polygon=function(_){return getExtent(_).polygon()},module.exports.bboxify=function(_){return traverse(_).map(function(value){value&&-1!==typeof geojsonTypes.indexOf(value.type)&&(console.log(value.type,value),value.bbox=getExtent(value).bbox(),this.update(value))})}},{extent:2,"geojson-coords":4,traverse:7}],2:[function(require,module){function Extent(){return this instanceof Extent?(this._bbox=[1/0,1/0,-(1/0),-(1/0)],void(this._valid=!1)):new Extent}module.exports=Extent,Extent.prototype.include=function(ll){return this._valid=!0,this._bbox[0]=Math.min(this._bbox[0],ll[0]),this._bbox[1]=Math.min(this._bbox[1],ll[1]),this._bbox[2]=Math.max(this._bbox[2],ll[0]),this._bbox[3]=Math.max(this._bbox[3],ll[1]),this},Extent.prototype.union=function(other){return this._valid=!0,this._bbox[0]=Math.min(this._bbox[0],other[0]),this._bbox[1]=Math.min(this._bbox[1],other[1]),this._bbox[2]=Math.max(this._bbox[2],other[2]),this._bbox[3]=Math.max(this._bbox[3],other[3]),this},Extent.prototype.bbox=function(){return this._valid?this._bbox:null},Extent.prototype.contains=function(ll){return this._valid?this._bbox[0]<=ll[0]&&this._bbox[1]<=ll[1]&&this._bbox[2]>=ll[0]&&this._bbox[3]>=ll[1]:null},Extent.prototype.polygon=function(){return this._valid?{type:"Polygon",coordinates:[[[this._bbox[0],this._bbox[1]],[this._bbox[2],this._bbox[1]],[this._bbox[2],this._bbox[3]],[this._bbox[0],this._bbox[3]],[this._bbox[0],this._bbox[1]]]]}:null}},{}],3:[function(require,module){module.exports=function(list){function _flatten(list){return Array.isArray(list)&&list.length&&"number"==typeof list[0]?[list]:list.reduce(function(acc,item){return Array.isArray(item)&&Array.isArray(item[0])?acc.concat(_flatten(item)):(acc.push(item),acc)},[])}return _flatten(list)}},{}],4:[function(require,module){var geojsonNormalize=require("geojson-normalize"),geojsonFlatten=require("geojson-flatten"),flatten=require("./flatten");module.exports=function(_){if(!_)return[];var normalized=geojsonFlatten(geojsonNormalize(_)),coordinates=[];return normalized.features.forEach(function(feature){feature.geometry&&(coordinates=coordinates.concat(flatten(feature.geometry.coordinates)))}),coordinates}},{"./flatten":3,"geojson-flatten":5,"geojson-normalize":6}],5:[function(require,module){function flatten(gj){switch(gj&&gj.type||null){case"FeatureCollection":return gj.features=gj.features.reduce(function(mem,feature){return mem.concat(flatten(feature))},[]),gj;case"Feature":return flatten(gj.geometry).map(function(geom){return{type:"Feature",properties:JSON.parse(JSON.stringify(gj.properties)),geometry:geom}});case"MultiPoint":return gj.coordinates.map(function(_){return{type:"Point",coordinates:_}});case"MultiPolygon":return gj.coordinates.map(function(_){return{type:"Polygon",coordinates:_}});case"MultiLineString":return gj.coordinates.map(function(_){return{type:"LineString",coordinates:_}});case"GeometryCollection":return gj.geometries;case"Point":case"Polygon":case"LineString":return[gj];default:return gj}}module.exports=flatten},{}],6:[function(require,module){function normalize(gj){if(!gj||!gj.type)return null;var type=types[gj.type];return type?"geometry"===type?{type:"FeatureCollection",features:[{type:"Feature",properties:{},geometry:gj}]}:"feature"===type?{type:"FeatureCollection",features:[gj]}:"featurecollection"===type?gj:void 0:null}module.exports=normalize;var types={Point:"geometry",MultiPoint:"geometry",LineString:"geometry",MultiLineString:"geometry",Polygon:"geometry",MultiPolygon:"geometry",GeometryCollection:"geometry",Feature:"feature",FeatureCollection:"featurecollection"}},{}],7:[function(require,module){function Traverse(obj){this.value=obj}function walk(root,cb,immutable){var path=[],parents=[],alive=!0;return function walker(node_){function updateState(){if("object"==typeof state.node&&null!==state.node){state.keys&&state.node_===state.node||(state.keys=objectKeys(state.node)),state.isLeaf=0==state.keys.length;for(var i=0;i<parents.length;i++)if(parents[i].node_===node_){state.circular=parents[i];break}}else state.isLeaf=!0,state.keys=null;state.notLeaf=!state.isLeaf,state.notRoot=!state.isRoot}var node=immutable?copy(node_):node_,modifiers={},keepGoing=!0,state={node:node,node_:node_,path:[].concat(path),parent:parents[parents.length-1],parents:parents,key:path.slice(-1)[0],isRoot:0===path.length,level:path.length,circular:null,update:function(x,stopHere){state.isRoot||(state.parent.node[state.key]=x),state.node=x,stopHere&&(keepGoing=!1)},"delete":function(stopHere){delete state.parent.node[state.key],stopHere&&(keepGoing=!1)},remove:function(stopHere){isArray(state.parent.node)?state.parent.node.splice(state.key,1):delete state.parent.node[state.key],stopHere&&(keepGoing=!1)},keys:null,before:function(f){modifiers.before=f},after:function(f){modifiers.after=f},pre:function(f){modifiers.pre=f},post:function(f){modifiers.post=f},stop:function(){alive=!1},block:function(){keepGoing=!1}};if(!alive)return state;updateState();var ret=cb.call(state,state.node);return void 0!==ret&&state.update&&state.update(ret),modifiers.before&&modifiers.before.call(state,state.node),keepGoing?("object"!=typeof state.node||null===state.node||state.circular||(parents.push(state),updateState(),forEach(state.keys,function(key,i){path.push(key),modifiers.pre&&modifiers.pre.call(state,state.node[key],key);var child=walker(state.node[key]);immutable&&hasOwnProperty.call(state.node,key)&&(state.node[key]=child.node),child.isLast=i==state.keys.length-1,child.isFirst=0==i,modifiers.post&&modifiers.post.call(state,child),path.pop()}),parents.pop()),modifiers.after&&modifiers.after.call(state,state.node),state):state}(root).node}function copy(src){if("object"==typeof src&&null!==src){var dst;if(isArray(src))dst=[];else if(isDate(src))dst=new Date(src.getTime?src.getTime():src);else if(isRegExp(src))dst=new RegExp(src);else if(isError(src))dst={message:src.message};else if(isBoolean(src))dst=new Boolean(src);else if(isNumber(src))dst=new Number(src);else if(isString(src))dst=new String(src);else if(Object.create&&Object.getPrototypeOf)dst=Object.create(Object.getPrototypeOf(src));else if(src.constructor===Object)dst={};else{var proto=src.constructor&&src.constructor.prototype||src.__proto__||{},T=function(){};T.prototype=proto,dst=new T}return forEach(objectKeys(src),function(key){dst[key]=src[key]}),dst}return src}function toS(obj){return Object.prototype.toString.call(obj)}function isDate(obj){return"[object Date]"===toS(obj)}function isRegExp(obj){return"[object RegExp]"===toS(obj)}function isError(obj){return"[object Error]"===toS(obj)}function isBoolean(obj){return"[object Boolean]"===toS(obj)}function isNumber(obj){return"[object Number]"===toS(obj)}function isString(obj){return"[object String]"===toS(obj)}var traverse=module.exports=function(obj){return new Traverse(obj)};Traverse.prototype.get=function(ps){for(var node=this.value,i=0;i<ps.length;i++){var key=ps[i];if(!node||!hasOwnProperty.call(node,key)){node=void 0;break}node=node[key]}return node},Traverse.prototype.has=function(ps){for(var node=this.value,i=0;i<ps.length;i++){var key=ps[i];if(!node||!hasOwnProperty.call(node,key))return!1;node=node[key]}return!0},Traverse.prototype.set=function(ps,value){for(var node=this.value,i=0;i<ps.length-1;i++){var key=ps[i];hasOwnProperty.call(node,key)||(node[key]={}),node=node[key]}return node[ps[i]]=value,value},Traverse.prototype.map=function(cb){return walk(this.value,cb,!0)},Traverse.prototype.forEach=function(cb){return this.value=walk(this.value,cb,!1),this.value},Traverse.prototype.reduce=function(cb,init){var skip=1===arguments.length,acc=skip?this.value:init;return this.forEach(function(x){this.isRoot&&skip||(acc=cb.call(this,acc,x))}),acc},Traverse.prototype.paths=function(){var acc=[];return this.forEach(function(){acc.push(this.path)}),acc},Traverse.prototype.nodes=function(){var acc=[];return this.forEach(function(){acc.push(this.node)}),acc},Traverse.prototype.clone=function(){var parents=[],nodes=[];return function clone(src){for(var i=0;i<parents.length;i++)if(parents[i]===src)return nodes[i];if("object"==typeof src&&null!==src){var dst=copy(src);return parents.push(src),nodes.push(dst),forEach(objectKeys(src),function(key){dst[key]=clone(src[key])}),parents.pop(),nodes.pop(),dst}return src}(this.value)};var objectKeys=Object.keys||function(obj){var res=[];for(var key in obj)res.push(key);return res},isArray=Array.isArray||function(xs){return"[object Array]"===Object.prototype.toString.call(xs)},forEach=function(xs,fn){if(xs.forEach)return xs.forEach(fn);for(var i=0;i<xs.length;i++)fn(xs[i],i,xs)};forEach(objectKeys(Traverse.prototype),function(key){traverse[key]=function(obj){var args=[].slice.call(arguments,1),t=new Traverse(obj);return t[key].apply(t,args)}});var hasOwnProperty=Object.hasOwnProperty||function(obj,key){return key in obj}},{}]},{},[1])(1)});!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var o;"undefined"!=typeof window?o=window:"undefined"!=typeof global?o=global:"undefined"!=typeof self&&(o=self),o.geoViewport=e()}}(function(){return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(_dereq_,module){function viewport(bounds,dimensions,minzoom,maxzoom){minzoom=void 0===minzoom?0:minzoom,maxzoom=void 0===maxzoom?20:maxzoom;var base=maxzoom,bl=merc.px([bounds[0],bounds[1]],base),tr=merc.px([bounds[2],bounds[3]],base),width=tr[0]-bl[0],height=bl[1]-tr[1],ratios=[width/dimensions[0],height/dimensions[1]],center=[(bounds[0]+bounds[2])/2,(bounds[1]+bounds[3])/2],adjusted=Math.floor(Math.min(base-Math.log(ratios[0])/Math.log(2),base-Math.log(ratios[1])/Math.log(2))),zoom=Math.max(minzoom,Math.min(maxzoom,adjusted));return{center:center,zoom:zoom}}function bounds(viewport,zoom,dimensions){void 0!==viewport.lon&&(viewport=[viewport.lon,viewport.lat]);var px=merc.px(viewport,zoom),tl=merc.ll([px[0]-dimensions[0]/2,px[1]-dimensions[1]/2],zoom),br=merc.ll([px[0]+dimensions[0]/2,px[1]+dimensions[1]/2],zoom);return[tl[0],br[1],br[0],tl[1]]}var merc=new(_dereq_("sphericalmercator"));module.exports.viewport=viewport,module.exports.bounds=bounds},{sphericalmercator:2}],2:[function(_dereq_,module,exports){var SphericalMercator=function(){function SphericalMercator(options){if(options=options||{},this.size=options.size||256,!cache[this.size]){var size=this.size,c=cache[this.size]={};c.Bc=[],c.Cc=[],c.zc=[],c.Ac=[];for(var d=0;30>d;d++)c.Bc.push(size/360),c.Cc.push(size/(2*Math.PI)),c.zc.push(size/2),c.Ac.push(size),size*=2}this.Bc=cache[this.size].Bc,this.Cc=cache[this.size].Cc,this.zc=cache[this.size].zc,this.Ac=cache[this.size].Ac}var cache={},D2R=Math.PI/180,R2D=180/Math.PI,A=6378137,MAXEXTENT=20037508.34;return SphericalMercator.prototype.px=function(ll,zoom){var d=this.zc[zoom],f=Math.min(Math.max(Math.sin(D2R*ll[1]),-.9999),.9999),x=Math.round(d+ll[0]*this.Bc[zoom]),y=Math.round(d+.5*Math.log((1+f)/(1-f))*-this.Cc[zoom]);return x>this.Ac[zoom]&&(x=this.Ac[zoom]),y>this.Ac[zoom]&&(y=this.Ac[zoom]),[x,y]},SphericalMercator.prototype.ll=function(px,zoom){var g=(px[1]-this.zc[zoom])/-this.Cc[zoom],lon=(px[0]-this.zc[zoom])/this.Bc[zoom],lat=R2D*(2*Math.atan(Math.exp(g))-.5*Math.PI);return[lon,lat]},SphericalMercator.prototype.bbox=function(x,y,zoom,tms_style,srs){tms_style&&(y=Math.pow(2,zoom)-1-y);var ll=[x*this.size,(+y+1)*this.size],ur=[(+x+1)*this.size,y*this.size],bbox=this.ll(ll,zoom).concat(this.ll(ur,zoom));return"900913"===srs?this.convert(bbox,"900913"):bbox},SphericalMercator.prototype.xyz=function(bbox,zoom,tms_style,srs){"900913"===srs&&(bbox=this.convert(bbox,"WGS84"));var ll=[bbox[0],bbox[1]],ur=[bbox[2],bbox[3]],px_ll=this.px(ll,zoom),px_ur=this.px(ur,zoom),bounds={minX:Math.floor(px_ll[0]/this.size),minY:Math.floor(px_ur[1]/this.size),maxX:Math.floor((px_ur[0]-1)/this.size),maxY:Math.floor((px_ll[1]-1)/this.size)};if(tms_style){var tms={minY:Math.pow(2,zoom)-1-bounds.maxY,maxY:Math.pow(2,zoom)-1-bounds.minY};bounds.minY=tms.minY,bounds.maxY=tms.maxY}return bounds},SphericalMercator.prototype.convert=function(bbox,to){return"900913"===to?this.forward(bbox.slice(0,2)).concat(this.forward(bbox.slice(2,4))):this.inverse(bbox.slice(0,2)).concat(this.inverse(bbox.slice(2,4)))},SphericalMercator.prototype.forward=function(ll){var xy=[A*ll[0]*D2R,A*Math.log(Math.tan(.25*Math.PI+.5*ll[1]*D2R))];return xy[0]>MAXEXTENT&&(xy[0]=MAXEXTENT),xy[0]<-MAXEXTENT&&(xy[0]=-MAXEXTENT),xy[1]>MAXEXTENT&&(xy[1]=MAXEXTENT),xy[1]<-MAXEXTENT&&(xy[1]=-MAXEXTENT),xy},SphericalMercator.prototype.inverse=function(xy){return[xy[0]*R2D/A,(.5*Math.PI-2*Math.atan(Math.exp(-xy[1]/A)))*R2D]},SphericalMercator}();"undefined"!=typeof module&&"undefined"!=typeof exports&&(module.exports=exports=SphericalMercator)},{}]},{},[1])(1)});