// 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);
