// 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
ez5.GeonamesUtil = (function() {
  function GeonamesUtil() {}

  GeonamesUtil.getConceptNameFromObject = function(object) {
    var conceptName;
    conceptName = '';
    if (object != null ? object.asciiName : void 0) {
      conceptName = object.asciiName;
    }
    return conceptName;
  };

  GeonamesUtil.getConceptURIFromObject = function(object) {
    var conceptURI;
    conceptURI = '';
    if (object != null ? object.geonameId : void 0) {
      conceptURI = 'http://geonames.org/' + object.geonameId;
    }
    return conceptURI;
  };

  GeonamesUtil.getConceptAncestorsFromObject = function(object) {
    var conceptAncestors;
    conceptAncestors = [];
    if (object != null ? object.countryId : void 0) {
      conceptAncestors.push('http://geonames.org/' + object.countryId);
    }
    if (object != null ? object.adminId1 : void 0) {
      conceptAncestors.push('http://geonames.org/' + object.adminId1);
    }
    if (object != null ? object.adminId2 : void 0) {
      conceptAncestors.push('http://geonames.org/' + object.adminId2);
    }
    if (object != null ? object.adminId3 : void 0) {
      conceptAncestors.push('http://geonames.org/' + object.adminId3);
    }
    if (object != null ? object.adminId4 : void 0) {
      conceptAncestors.push('http://geonames.org/' + object.adminId4);
    }
    conceptAncestors.push('http://geonames.org/' + object.geonameId);
    conceptAncestors = conceptAncestors.join(' ');
    return conceptAncestors;
  };

  GeonamesUtil.getStandardTextFromObject = function(context, object, cdata, databaseLanguages) {
    var _standard, activeFrontendLanguage, i, l10nObject, l10nObjectKey, l10nObjectValue, language, len, ref, shortenedDatabaseLanguages, standardTextString;
    if (databaseLanguages == null) {
      databaseLanguages = false;
    }
    if (databaseLanguages === false) {
      databaseLanguages = ez5.loca.getDatabaseLanguages();
    }
    shortenedDatabaseLanguages = databaseLanguages.map(function(value, key, array) {
      return value.split('-').shift();
    });
    activeFrontendLanguage = null;
    if (context) {
      activeFrontendLanguage = context.getFrontendLanguage();
    }
    if (cdata != null ? cdata.frontendLanguage : void 0) {
      if ((cdata != null ? (ref = cdata.frontendLanguage) != null ? ref.length : void 0 : void 0) === 2) {
        activeFrontendLanguage = cdata.frontendLanguage;
      }
    }
    if (Array.isArray(object)) {
      object = object[0];
    }
    _standard = {};
    standardTextString = '';
    l10nObject = {};
    for (i = 0, len = databaseLanguages.length; i < len; i++) {
      language = databaseLanguages[i];
      l10nObject[language] = '';
    }
    for (l10nObjectKey in l10nObject) {
      l10nObjectValue = l10nObject[l10nObjectKey];
      l10nObject[l10nObjectKey] = object.asciiName;
    }
    _standard.l10ntext = l10nObject;
    return _standard;
  };

  GeonamesUtil.getFullTextFromObject = function(object, databaseLanguages) {
    var _fulltext, altnameVal, altnamekey, arrayValue, arrayValueOfObject, fullTextString, i, j, k, key, l, l10nObject, l10nObjectKey, l10nObjectValue, l10nObjectWithShortenedLanguages, l10nObjectWithShortenedLanguagesKey, l10nObjectWithShortenedLanguagesValue, language, len, len1, len2, len3, objectKey, objectKeys, objectValue, propertyType, ref, ref1, ref2, shortenedDatabaseLanguages, shortenedLanguage, value;
    if (databaseLanguages == null) {
      databaseLanguages = false;
    }
    if (databaseLanguages === false) {
      databaseLanguages = ez5.loca.getDatabaseLanguages();
    }
    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 = ["asciiName", "alternateNames", "toponymName", "geonameId", "countryName"];
    for (key in object) {
      value = object[key];
      if (objectKeys.includes(key)) {
        propertyType = typeof value;
        if (propertyType === 'string' || propertyType === 'number') {
          fullTextString += value + ' ';
          for (l10nObjectWithShortenedLanguagesKey in l10nObjectWithShortenedLanguages) {
            l10nObjectWithShortenedLanguagesValue = l10nObjectWithShortenedLanguages[l10nObjectWithShortenedLanguagesKey];
            l10nObjectWithShortenedLanguages[l10nObjectWithShortenedLanguagesKey] = l10nObjectWithShortenedLanguagesValue + value + ' ';
          }
        }
        if (propertyType === 'object') {
          if (Array.isArray(object[key])) {
            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 + ' ';
                  }
                }
              }
            }
            if (typeof object[key] === 'object') {
              ref1 = object[key];
              for (altnamekey in ref1) {
                altnameVal = ref1[altnamekey];
                if (altnameVal.name) {
                  fullTextString += altnameVal.name + ' ';
                  for (l10nObjectWithShortenedLanguagesKey in l10nObjectWithShortenedLanguages) {
                    l10nObjectWithShortenedLanguagesValue = l10nObjectWithShortenedLanguages[l10nObjectWithShortenedLanguagesKey];
                    l10nObjectWithShortenedLanguages[l10nObjectWithShortenedLanguagesKey] = l10nObjectWithShortenedLanguagesValue + altnameVal.name + ' ';
                  }
                }
              }
            }
          } 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.hasOwnProperty(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;
  };

  return GeonamesUtil;

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

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

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

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

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

  CustomDataTypeGeonames.prototype.getFrontendLanguage = function() {
    var desiredLanguage;
    desiredLanguage = ez5.loca.getLanguage();
    desiredLanguage = desiredLanguage.split('-');
    desiredLanguage = desiredLanguage[0];
    return desiredLanguage;
  };

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

  CustomDataTypeGeonames.prototype.getSearchFilter = function(data, key) {
    var filter, givenGeonamesID, givenURI, givenURIParts, ref, that, uri;
    if (key == null) {
      key = this.name();
    }
    that = this;
    if (data[this.name()] === void 0 || data[this.name()] === {} || data[this.name()] === null) {
      return;
    }
    if (data[key + ":unset"]) {
      filter = {
        type: "in",
        fields: [this.fullName() + ".conceptName"],
        "in": [null]
      };
      filter._unnest = true;
      filter._unset_filter = true;
      return filter;
    }
    filter = null;
    if ((ref = data[this.name()]) != null ? ref.conceptURI : void 0) {
      givenURI = data[this.name()].conceptURI;
      givenURIParts = givenURI.split('/');
      givenGeonamesID = givenURIParts.pop();
      uri = 'http://www.geonames.org/' + givenGeonamesID;
      filter = {
        type: "complex",
        search: [
          {
            type: "in",
            mode: "token",
            bool: "must",
            phrase: false,
            fields: [this.path() + '.' + this.name() + ".conceptURI"],
            "in": [uri]
          }
        ]
      };
    }
    return filter;
  };

  CustomDataTypeGeonames.prototype.getQueryFieldBadge = function(data) {
    var ref, 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;
    }
    return {
      name: this.nameLocalized(),
      value: value
    };
  };

  CustomDataTypeGeonames.prototype.__getAdditionalTooltipInfo = function(uri, tooltip, extendedInfo_xhr) {
    var geonamesID, geonamesURI, that;
    that = this;
    geonamesURI = uri;
    geonamesID = decodeURIComponent(uri);
    geonamesID = geonamesID.split("/");
    geonamesID = geonamesID.pop();
    if (extendedInfo_xhr.xhr !== void 0) {
      extendedInfo_xhr.xhr.abort();
    }
    extendedInfo_xhr.xhr = new CUI.XHR({
      url: location.protocol + '//uri.gbv.de/terminology/geonames/' + geonamesID + '?format=json'
    });
    extendedInfo_xhr.xhr.start().done(function(data, status, statusText) {
      var bounds, coord1, coord2, encodedGeoJSON, htmlContent, imageSrc, json, jsonStr, mapbox_api_key, ref, ref1, size, value, vp;
      htmlContent = '<span style="padding: 10px 10px 0px 10px; font-weight: bold">' + $$('custom.data.type.geonames.config.parameter.mask.infopop.info.label') + '</span>';
      coord1 = 0;
      coord1 = 0;
      if (data.lat) {
        coord1 = data.lat;
      }
      if (data.lat) {
        coord2 = data.lng;
      }
      if ((ref = that.getCustomSchemaSettings().mapbox_api_key) != null ? ref.value : void 0) {
        mapbox_api_key = (ref1 = that.getCustomSchemaSettings().mapbox_api_key) != null ? ref1.value : void 0;
        if (coord1 !== 0 & coord2 !== 0) {
          value = JSON.parse('{"geometry": {"type": "Point","coordinates": [' + coord2 + ',' + coord1 + ']}}');
          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 = 12;
            }
            imageSrc = 'https://api.mapbox.com/styles/v1/mapbox/satellite-streets-v9/static/geojson(' + encodedGeoJSON + ')/' + vp.center.join(',') + ',' + vp.zoom + '/' + size.join('x') + '@2x?access_token=' + mapbox_api_key;
            htmlContent += '<div style="width:400px; height: 250px; background-size: contain; background-image: url(\'' + imageSrc + '\'); background-repeat: no-repeat; background-position: center center;"></div>';
          }
        }
      }
      htmlContent += '<table style="border-spacing: 10px; border-collapse: separate;">';
      if (data.name) {
        if (typeof data.name !== 'object') {
          htmlContent += '<tr><td>' + $$('custom.data.type.geonames.config.parameter.mask.infopop.name.label') + ':</td><td>' + data.name + '</td></tr>';
        }
      }
      if (data.adminName4) {
        if (typeof data.adminName4 !== 'object') {
          htmlContent += '<tr><td>' + $$('custom.data.type.geonames.config.parameter.mask.infopop.einteilung4.label') + ':</td><td>' + data.adminName4 + '</td></tr>';
        }
      }
      if (data.adminName3) {
        if (typeof data.adminName3 !== 'object') {
          htmlContent += '<tr><td>' + $$('custom.data.type.geonames.config.parameter.mask.infopop.einteilung3.label') + ':</td><td>' + data.adminName3 + '</td></tr>';
        }
      }
      if (data.adminName2) {
        if (typeof data.adminName2 !== 'object') {
          htmlContent += '<tr><td>' + $$('custom.data.type.geonames.config.parameter.mask.infopop.einteilung2.label') + ':</td><td>' + data.adminName2 + '</td></tr>';
        }
      }
      if (data.adminName1) {
        if (typeof data.adminName1 !== 'object') {
          htmlContent += '<tr><td>' + $$('custom.data.type.geonames.config.parameter.mask.infopop.einteilung1.label') + ':</td><td>' + data.adminName1 + '</td></tr>';
        }
      }
      if (data.countryName) {
        if (typeof data.countryName !== 'object') {
          htmlContent += '<tr><td>' + $$('custom.data.type.geonames.config.parameter.mask.infopop.land.label') + ':</td><td>' + data.countryName + '</td></tr>';
        }
      }
      if (data.continentCode) {
        if (typeof data.continentCode !== 'object') {
          htmlContent += '<tr><td>' + $$('custom.data.type.geonames.config.parameter.mask.infopop.kontinent.label') + ':</td><td>' + data.continentCode + '</td></tr>';
        }
      }
      if (data.population) {
        if (typeof data.population !== 'object') {
          htmlContent += '<tr><td>' + $$('custom.data.type.geonames.config.parameter.mask.infopop.einwohner.label') + ':</td><td>' + data.population + '</td></tr>';
        }
      }
      if (data.fclName) {
        if (typeof data.fclName !== 'object') {
          htmlContent += '<tr><td>' + $$('custom.data.type.geonames.config.parameter.mask.infopop.typ.label') + ':</td><td>' + data.fclName + '</td></tr>';
        }
      }
      if (data.timezone) {
        if (typeof data.timezone !== 'object') {
          htmlContent += '<tr><td>' + $$('custom.data.type.geonames.config.parameter.mask.infopop.zeitzone.label') + ':</td><td>' + data.timezone + '</td></tr>';
        }
      }
      tooltip.DOM.innerHTML = htmlContent;
      return tooltip.autoSize();
    });
  };

  CustomDataTypeGeonames.prototype.__getFeaturecodesFromDANTE = function(thisSelect, featureclassCode) {
    var dfr, searchsuggest_xhr, values;
    dfr = new CUI.Deferred();
    values = [];
    searchsuggest_xhr = new CUI.XHR({
      url: 'https://api.dante.gbv.de/suggest?search=&voc=place_type_geonames&language=' + this.getFrontendLanguage() + '&limit=1000&cache=1'
    });
    searchsuggest_xhr.start().done(function(data, status, statusText) {
      var codeNotation, featureClassCodeExtraction, i, item, key, len, ref, select_items, suggestion, uriParts;
      select_items = [];
      item = {
        text: $$('custom.data.type.geonames.config.parameter.mask.config_featurecodes.all.label'),
        value: null
      };
      select_items.push(item);
      ref = data[1];
      for (key = i = 0, len = ref.length; i < len; key = ++i) {
        suggestion = ref[key];
        uriParts = data[3][key];
        uriParts = uriParts.split('.');
        codeNotation = uriParts.pop();
        featureClassCodeExtraction = uriParts[2].split('#');
        featureClassCodeExtraction = featureClassCodeExtraction[1];
        if ((featureClassCodeExtraction === featureclassCode) || featureclassCode === '' || !featureclassCode || featureclassCode === null) {
          item = {
            text: suggestion,
            value: codeNotation
          };
          select_items.push(item);
        }
      }
      thisSelect.enable();
      return dfr.resolve(select_items);
    });
    return dfr.promise();
  };

  CustomDataTypeGeonames.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) {
          var defaultText, featureclassParameter, ref, ref1, ref2, ref3;
          if (((ref = _this.getCustomMaskSettings().config_featureclasses) != null ? ref.value : void 0) && ((ref1 = _this.getCustomMaskSettings().config_featurecodes) != null ? ref1.value : void 0)) {
            if (elem.opts.name === 'geonamesSelectFeatureClasses') {
              featureclassParameter = '';
              if ((data != null ? data.geonamesSelectFeatureClasses : void 0) !== '' && (data != null ? data.geonamesSelectFeatureClasses : void 0) !== null) {
                featureclassParameter = data.geonamesSelectFeatureClasses;
              }
              data.geonamesSelectFeatureCodes = null;
              cdata.geonamesSelectFeatureCodes = null;
              if ((ref2 = cdata_form.getFieldsByName("geonamesSelectFeatureCodes")[0]) != null) {
                ref2.setValue(null);
              }
              defaultText = cdata_form.getFieldsByName("geonamesSelectFeatureCodes")[0].default_opt.text;
              cdata_form.getFieldsByName("geonamesSelectFeatureCodes")[0].reload();
              if ((ref3 = cdata_form.getFieldsByName("geonamesSelectFeatureCodes")[0]) != null) {
                ref3.setText('test');
              }
            }
          }
          _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();
  };

  CustomDataTypeGeonames.prototype.__updateSuggestionsMenu = function(cdata, cdata_form, searchstring, input, suggest_Menu, searchsuggest_xhr, layout, opts) {
    var delayMillisseconds, that;
    that = this;
    delayMillisseconds = 200;
    return setTimeout((function() {
      var ancestorsQuery, countryQuery, expandQuery, expandStatus, extendedInfo_xhr, geonames_countSuggestions, geonames_country, geonames_featureclass, geonames_featurecode, geonames_searchterm, ref, ref1, ref2;
      geonames_searchterm = searchstring;
      geonames_countSuggestions = 50;
      geonames_featureclass = '';
      geonames_featurecode = '';
      geonames_country = '';
      expandQuery = '';
      if (cdata_form) {
        geonames_searchterm = cdata_form.getFieldsByName("searchbarInput")[0].getValue();
        geonames_featureclass = (ref = cdata_form.getFieldsByName("geonamesSelectFeatureClasses")[0]) != null ? ref.getValue() : void 0;
        if (geonames_featureclass === void 0 || geonames_featureclass === null) {
          geonames_featureclass = '';
        }
        geonames_featurecode = (ref1 = cdata_form.getFieldsByName("geonamesSelectFeatureCodes")[0]) != null ? ref1.getValue() : void 0;
        if (geonames_featurecode === void 0 || geonames_featurecode === null) {
          geonames_featurecode = '';
        }
        geonames_countSuggestions = cdata_form.getFieldsByName("countOfSuggestions")[0].getValue();
        expandStatus = cdata_form.getFieldsByName("expandSearchCheckbox")[0].getValue();
        expandQuery = '&expand=' + expandStatus;
      }
      if (geonames_searchterm.length === 0) {
        return;
      }
      countryQuery = '';
      if (cdata != null ? cdata.geonamesSelectCountry : void 0) {
        countryQuery = '&country=' + cdata.geonamesSelectCountry;
      }
      ancestorsQuery = '&ancestors=false';
      if ((ref2 = that.getCustomMaskSettings().use_ancestors) != null ? ref2.value : void 0) {
        ancestorsQuery = '&ancestors=true';
      }
      extendedInfo_xhr = {
        "xhr": void 0
      };
      if (searchsuggest_xhr.xhr !== void 0) {
        searchsuggest_xhr.xhr.abort();
      }
      searchsuggest_xhr.xhr = new CUI.XHR({
        url: location.protocol + '//ws.gbv.de/suggest/geonames2/?searchterm=' + geonames_searchterm + '&language=' + that.getFrontendLanguage() + '&featureclass=' + geonames_featureclass + '&featurecode=' + geonames_featurecode + '&count=' + geonames_countSuggestions + countryQuery + expandQuery + ancestorsQuery
      });
      return searchsuggest_xhr.xhr.start().done(function(data, status, statusText) {
        var fn, i, itemList, key, len, menu_items, ref3, suggestion;
        menu_items = [];
        ref3 = data[1];
        fn = function(key) {
          var aktType, item, lastType;
          aktType = data[2][key];
          lastType = '';
          if (key > 0) {
            lastType = data[2][key - 1];
          }
          if (aktType !== lastType) {
            item = {
              divider: true
            };
            menu_items.push(item);
            item = {
              label: aktType
            };
            menu_items.push(item);
            item = {
              divider: true
            };
            menu_items.push(item);
          }
          item = {
            text: suggestion,
            value: data[3][key],
            tooltip: {
              markdown: true,
              placement: "e",
              content: function(tooltip) {
                that.__getAdditionalTooltipInfo(data[3][key], tooltip, extendedInfo_xhr);
                return new CUI.Label({
                  icon: "spinner",
                  text: "lade Informationen"
                });
              }
            }
          };
          return menu_items.push(item);
        };
        for (key = i = 0, len = ref3.length; i < len; key = ++i) {
          suggestion = ref3[key];
          fn(key);
        }
        itemList = {
          keyboardControl: true,
          onClick: function(ev2, btn) {
            var dataEntry_xhr, encodedURL, geonamesID, geonamesUsername, ref4;
            cdata.conceptURI = btn.getOpt("value");
            cdata.conceptName = btn.getText();
            cdata._fulltext = {};
            cdata._standard = {};
            cdata._fulltext.text = cdata.conceptName;
            cdata._standard.text = cdata.conceptName;
            geonamesUsername = '';
            if ((ref4 = that.getCustomSchemaSettings().geonames_username) != null ? ref4.value : void 0) {
              geonamesUsername = that.getCustomSchemaSettings().geonames_username.value;
              geonamesID = cdata.conceptURI;
              geonamesID = geonamesID.replace('http://www.geonames.org/', '');
              encodedURL = encodeURIComponent('http://api.geonames.org/getJSON?formatted=true&geonameId=' + geonamesID + '&username=' + geonamesUsername + '&style=full');
              dataEntry_xhr = new CUI.XHR({
                url: location.protocol + '//jsontojsonp.gbv.de/?url=' + encodedURL
              });
              return dataEntry_xhr.start().done(function(data, status, statusText) {
                cdata.conceptName = ez5.GeonamesUtil.getConceptNameFromObject(data);
                cdata.conceptURI = ez5.GeonamesUtil.getConceptURIFromObject(data);
                cdata._fulltext = ez5.GeonamesUtil.getFullTextFromObject(data, false);
                cdata._standard = ez5.GeonamesUtil.getStandardTextFromObject(that, data, cdata, false);
                cdata.conceptAncestors = ez5.GeonamesUtil.getConceptAncestorsFromObject(data);
                that.__updateResult(cdata, layout, opts);
                suggest_Menu.hide();
                if (that.popover) {
                  return that.popover.hide();
                }
              });
            } else {
              that.__updateResult(cdata, layout, opts);
              suggest_Menu.hide();
              if (that.popover) {
                return that.popover.hide();
              }
            }
          },
          items: menu_items
        };
        if (itemList.items.length === 0) {
          itemList = {
            items: [
              {
                text: "kein Treffer",
                value: void 0
              }
            ]
          };
        }
        suggest_Menu.setItemList(itemList);
        return suggest_Menu.show();
      });
    }), delayMillisseconds);
  };

  CustomDataTypeGeonames.prototype.__getEditorFields = function(cdata) {
    var countryCodeOption, countryCodeOptions, countrycode, defaultCountryCode, featureclassesOptions, field, fields, i, len, ref, ref1, ref2, ref3, ref4, that;
    that = this;
    fields = [
      {
        type: CUI.Select,
        "class": "commonPlugin_Select",
        undo_and_changed_support: false,
        form: {
          label: $$('custom.data.type.geonames.modal.form.text.count')
        },
        options: [
          {
            value: 10,
            text: '10 ' + $$('custom.data.type.geonames.modal.form.text.count_short')
          }, {
            value: 20,
            text: '20 ' + $$('custom.data.type.geonames.modal.form.text.count_short')
          }, {
            value: 50,
            text: '50 ' + $$('custom.data.type.geonames.modal.form.text.count_short')
          }, {
            value: 100,
            text: '100 ' + $$('custom.data.type.geonames.modal.form.text.count_short')
          }
        ],
        name: 'countOfSuggestions'
      }, {
        type: CUI.Checkbox,
        "class": "commonPlugin_Checkbox",
        undo_and_changed_support: false,
        form: {
          label: $$('custom.data.type.geonames.modal.form.text.expand')
        },
        name: 'expandSearchCheckbox'
      }, {
        type: CUI.Input,
        "class": "commonPlugin_Input",
        undo_and_changed_support: false,
        form: {
          label: $$("custom.data.type.geonames.modal.form.text.searchbar")
        },
        placeholder: $$("custom.data.type.geonames.modal.form.text.searchbar.placeholder"),
        name: "searchbarInput"
      }
    ];
    countryCodeOptions = [
      {
        value: '',
        text: $$('custom.data.type.geonames.country.name.all')
      }
    ];
    if ((ref = that.getCustomMaskSettings().default_expand) != null ? ref.value : void 0) {
      cdata.expandSearchCheckbox = that.getCustomMaskSettings().default_expand.value;
    }
    if ((ref1 = this.getCustomMaskSettings().default_country_code) != null ? ref1.value : void 0) {
      defaultCountryCode = (ref2 = this.getCustomMaskSettings().default_country_code) != null ? ref2.value : void 0;
      defaultCountryCode = defaultCountryCode.toLowerCase();
      cdata.geonamesSelectCountry = defaultCountryCode;
    } else {
      cdata.geonamesSelectCountry = '';
    }
    for (i = 0, len = geonamesCountryCodes.length; i < len; i++) {
      countrycode = geonamesCountryCodes[i];
      countryCodeOption = {
        value: countrycode,
        text: $$('custom.data.type.geonames.country.name.' + countrycode)
      };
      countryCodeOptions.push(countryCodeOption);
    }
    field = {
      type: CUI.Select,
      undo_and_changed_support: false,
      form: {
        label: $$('custom.data.type.geonames.modal.form.text.countrys')
      },
      options: countryCodeOptions,
      name: 'geonamesSelectCountry',
      "class": 'commonPlugin_Select'
    };
    fields.unshift(field);
    if ((ref3 = this.getCustomMaskSettings().config_featurecodes) != null ? ref3.value : void 0) {
      field = {
        type: CUI.Select,
        undo_and_changed_support: false,
        form: {
          label: $$('custom.data.type.geonames.modal.form.text.featurecodes')
        },
        name: 'geonamesSelectFeatureCodes',
        "class": 'commonPlugin_Select',
        options: (function(_this) {
          return function(thisSelect) {
            var featureclassParameter;
            featureclassParameter = '';
            if ((cdata != null ? cdata.geonamesSelectFeatureClasses : void 0) !== '' && (cdata != null ? cdata.geonamesSelectFeatureClasses : void 0) !== null) {
              featureclassParameter = cdata.geonamesSelectFeatureClasses;
            }
            return that.__getFeaturecodesFromDANTE(thisSelect, featureclassParameter);
          };
        })(this)
      };
      fields.unshift(field);
    }
    if ((ref4 = this.getCustomMaskSettings().config_featureclasses) != null ? ref4.value : void 0) {
      featureclassesOptions = [
        {
          value: '',
          text: $$('custom.data.type.geonames.config.parameter.mask.config_featureclasses.all.label')
        }, {
          value: 'A',
          text: $$('custom.data.type.geonames.config.parameter.mask.config_featureclasses.a.label')
        }, {
          value: 'H',
          text: $$('custom.data.type.geonames.config.parameter.mask.config_featureclasses.h.label')
        }, {
          value: 'L',
          text: $$('custom.data.type.geonames.config.parameter.mask.config_featureclasses.l.label')
        }, {
          value: 'P',
          text: $$('custom.data.type.geonames.config.parameter.mask.config_featureclasses.p.label')
        }, {
          value: 'R',
          text: $$('custom.data.type.geonames.config.parameter.mask.config_featureclasses.r.label')
        }, {
          value: 'S',
          text: $$('custom.data.type.geonames.config.parameter.mask.config_featureclasses.s.label')
        }, {
          value: 'T',
          text: $$('custom.data.type.geonames.config.parameter.mask.config_featureclasses.t.label')
        }, {
          value: 'U',
          text: $$('custom.data.type.geonames.config.parameter.mask.config_featureclasses.u.label')
        }, {
          value: 'V',
          text: $$('custom.data.type.geonames.config.parameter.mask.config_featureclasses.v.label')
        }
      ];
      field = {
        type: CUI.Select,
        undo_and_changed_support: false,
        form: {
          label: $$('custom.data.type.geonames.modal.form.text.featureclasses')
        },
        options: featureclassesOptions,
        name: 'geonamesSelectFeatureClasses',
        "class": 'commonPlugin_Select'
      };
      fields.unshift(field);
    }
    return fields;
  };

  CustomDataTypeGeonames.prototype.__renderButtonByData = function(cdata) {
    var extendedInfo_xhr, that;
    that = this;
    switch (this.getDataStatus(cdata)) {
      case "empty":
        return new CUI.EmptyLabel({
          text: $$("custom.data.type.geonames.edit.no_geonames")
        }).DOM;
      case "invalid":
        return new CUI.EmptyLabel({
          text: $$("custom.data.type.geonames.edit.no_valid_geonames")
        }).DOM;
    }
    cdata.conceptURI = CUI.parseLocation(cdata.conceptURI).url;
    extendedInfo_xhr = {
      "xhr": void 0
    };
    return new CUI.HorizontalLayout({
      maximize: false,
      left: {
        content: new CUI.Label({
          centered: false,
          multiline: true,
          text: cdata.conceptName
        })
      },
      center: {
        content: new CUI.ButtonHref({
          appearance: "link",
          href: cdata.conceptURI,
          target: "_blank",
          tooltip: {
            markdown: true,
            placement: 'n',
            content: function(tooltip) {
              that.__getAdditionalTooltipInfo(cdata.conceptURI, tooltip, extendedInfo_xhr);
              return new CUI.Label({
                icon: "spinner",
                text: "lade Informationen"
              });
            }
          },
          text: ' '
        })
      },
      right: null
    }).DOM;
  };

  CustomDataTypeGeonames.prototype.getCustomDataOptionsInDatamodelInfo = function(custom_settings) {
    var ref, ref1, tags;
    tags = [];
    if ((ref = custom_settings.mapbox_api_key) != null ? ref.value : void 0) {
      tags.push("✓ mapbox-token");
    } else {
      tags.push("✘ mapbox-token");
    }
    if ((ref1 = custom_settings.geonames_username) != null ? ref1.value : void 0) {
      tags.push("✓ geonames-Username");
    } else {
      tags.push("✘ geonames-Username");
    }
    return tags;
  };

  return CustomDataTypeGeonames;

})(CustomDataTypeWithCommons);

CustomDataType.register(CustomDataTypeGeonames);
// Generated by CoffeeScript 1.12.7
var geonamesCountryCodes;

geonamesCountryCodes = ["af", "eg", "ax", "al", "dz", "as", "vi", "ad", "ao", "ai", "aq", "ag", "gq", "ar", "am", "aw", "az", "et", "au", "bs", "bh", "bd", "bb", "be", "bz", "bj", "bm", "bt", "bo", "bq", "ba", "bw", "bv", "br", "vg", "io", "bn", "bg", "bf", "bi", "cl", "ck", "cr", "cw", "dk", "de", "dm", "do", "dj", "ec", "sv", "ci", "er", "ee", "fk", "fo", "fj", "fi", "fr", "gf", "pf", "tf", "ga", "gm", "ge", "gh", "gi", "gd", "gr", "gl", "gp", "gu", "gt", "gg", "gn", "gw", "gy", "ht", "hm", "hn", "hk", "in", "id", "im", "iq", "ir", "ie", "is", "il", "it", "jm", "jp", "ye", "je", "jo", "ky", "kh", "cm", "ca", "cv", "kz", "qa", "ke", "kg", "ki", "cc", "co", "km", "cd", "cg", "kp", "kr", "hr", "cu", "kw", "la", "ls", "lv", "lb", "lr", "ly", "li", "lt", "lu", "mo", "mg", "mw", "my", "mv", "ml", "mt", "ma", "mh", "mq", "mr", "mu", "yt", "mx", "fm", "md", "mc", "mn", "me", "ms", "mz", "mm", "na", "nr", "np", "nc", "nz", "ni", "nl", "ne", "ng", "nu", "mp", "mk", "nf", "no", "om", "at", "tl", "pk", "ps", "pw", "pa", "pg", "py", "pe", "ph", "pn", "pl", "pt", "pr", "tw", "re", "rw", "ro", "ru", "bl", "mf", "pm", "sb", "zm", "ws", "sm", "st", "sa", "se", "ch", "sn", "rs", "sc", "sl", "zw", "sg", "sx", "sk", "si", "so", "es", "sj", "lk", "sh", "kn", "lc", "vc", "za", "sd", "gs", "ss", "sr", "sz", "sy", "tj", "tz", "th", "tg", "tk", "to", "tt", "td", "cz", "tn", "tr", "tm", "tc", "tv", "ug", "ua", "hu", "um", "uy", "uz", "vu", "va", "ve", "ae", "us", "gb", "vn", "cn", "wf", "cx", "by", "eh", "cf", "cy"];
!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)});