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

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

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

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

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

  CustomDataTypeGazetteer.prototype.getCustomDataOptionsInDatamodelInfo = function(custom_settings) {
    return [];
  };

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

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

  CustomDataTypeGazetteer.prototype.getFieldNamesForSearch = function() {
    return this.__getFieldNames();
  };

  CustomDataTypeGazetteer.prototype.getFieldNamesForSuggest = function() {
    return this.__getFieldNames();
  };

  CustomDataTypeGazetteer.prototype.renderEditorInput = function(data) {
    var content, initData, setContent, waitBlock;
    initData = this.__initData(data);
    content = CUI.dom.div();
    waitBlock = new CUI.WaitBlock({
      element: content
    });
    setContent = (function(_this) {
      return function() {
        var displayOutput, ref, searchInput;
        ref = _this.__initForm(initData), searchInput = ref[0], displayOutput = ref[1];
        searchInput.start();
        displayOutput.start();
        CUI.dom.append(content, searchInput);
        CUI.dom.append(content, displayOutput);
        return waitBlock.destroy();
      };
    })(this);
    waitBlock.show();
    this.__fillMissingData(initData).done(setContent);
    return content;
  };

  CustomDataTypeGazetteer.prototype.renderTableOutput = function(data, _, opts) {
    var content, initData;
    initData = this.__initData(data);
    content = this.__renderOutput({
      data: initData,
      onlyText: true
    });
    return content;
  };

  CustomDataTypeGazetteer.prototype.renderDetailOutput = function(data, _, opts) {
    var content, i, initData, len, plugin, plugins, ref, ref1, setContent, waitBlock;
    initData = this.__initData(data);
    content = CUI.dom.div();
    waitBlock = new CUI.WaitBlock({
      element: content
    });
    setContent = (function(_this) {
      return function() {
        var i, len, mapPlugin, outputFieldElement, plugin, plugins;
        outputFieldElement = _this.__renderOutput({
          data: initData
        });
        CUI.dom.replace(content, outputFieldElement);
        waitBlock.destroy();
        if (CUI.Map.isValidPosition(initData.position) && opts.detail) {
          plugins = opts.detail.getPlugins();
          for (i = 0, len = plugins.length; i < len; i++) {
            plugin = plugins[i];
            if (plugin instanceof MapDetailPlugin) {
              mapPlugin = plugin;
              break;
            }
          }
          if (mapPlugin) {
            return mapPlugin.addMarker({
              position: initData.position,
              iconName: initData.iconName,
              iconColor: "#6786ad"
            });
          }
        }
      };
    })(this);
    waitBlock.show();
    this.__fillMissingData(initData).done(setContent);
    plugins = (ref = (ref1 = opts.detail) != null ? ref1.getPlugins() : void 0) != null ? ref : [];
    for (i = 0, len = plugins.length; i < len; i++) {
      plugin = plugins[i];
      if (typeof MapDetailPlugin !== 'undefined' && plugin instanceof MapDetailPlugin) {
        CUI.Events.listen({
          type: "map-detail-click-location",
          node: content,
          call: (function(_this) {
            return function(_, info) {
              var ref2;
              if (((ref2 = info.data) != null ? ref2.position : void 0) === initData.position) {
                return CUI.dom.scrollIntoView(content);
              }
            };
          })(this)
        });
        break;
      }
    }
    return content;
  };

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

  CustomDataTypeGazetteer.prototype.getTemplateData = function(data) {
    var ref;
    return data != null ? (ref = data._template) != null ? ref[this.name()] : void 0 : void 0;
  };

  CustomDataTypeGazetteer.prototype.getSaveData = function(data, save_data) {
    var fieldData, templateData;
    fieldData = data[this.name()];
    if (CUI.util.isEmpty(fieldData) || CUI.util.isEmpty(fieldData.gazId)) {
      templateData = this.getTemplateData(data);
      if (!CUI.util.isEmpty(templateData)) {
        return save_data[this.name()] = templateData;
      }
      return save_data[this.name()] = null;
    }
    if (fieldData.notFound) {
      throw new InvalidSaveDataException();
    }
    return save_data[this.name()] = ez5.GazetteerUtil.getSaveDataObject(fieldData);
  };

  CustomDataTypeGazetteer.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
    };
  };

  CustomDataTypeGazetteer.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() + ".displayName"],
        "in": [null]
      };
      filter._unnest = true;
      filter._unset_filter = true;
      return filter;
    }
    filter = CustomDataTypeGazetteer.__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;
  };

  CustomDataTypeGazetteer.prototype.__getFieldNames = function() {
    return [this.fullName() + ".gazId", this.fullName() + ".displayName"];
  };

  CustomDataTypeGazetteer.prototype.__initForm = function(formData) {
    var autocompletionPopup, cleanData, loadingContainer, loadingLabel, noResultsContainer, noResultsLabel, onDelete, outputDiv, outputField, resultsContainer, search, searchData, searchField, searchXHR, setData, showOutputField;
    searchData = {
      q: ""
    };
    resultsContainer = "results";
    loadingContainer = "loading";
    noResultsContainer = "no_results";
    loadingLabel = new LocaLabel({
      loca_key: "autocompletion.loading",
      padded: true
    });
    noResultsLabel = new LocaLabel({
      loca_key: "custom.data.type.gazetteer.search.no-results",
      padded: true
    });
    searchField = new CUI.Input({
      name: "q",
      hidden: true,
      placeholder: $$("custom.data.type.gazetteer.search.placeholder"),
      maximize_horizontal: true,
      data: searchData,
      onDataChanged: (function(_this) {
        return function() {
          return CUI.scheduleCallback({
            ms: 200,
            call: search
          });
        };
      })(this)
    });
    autocompletionPopup = new AutocompletionPopup({
      element: searchField,
      onHide: (function(_this) {
        return function() {
          return autocompletionPopup.hide();
        };
      })(this)
    });
    autocompletionPopup.addContainer(resultsContainer);
    autocompletionPopup.addContainer(loadingContainer);
    autocompletionPopup.addContainer(noResultsContainer);
    outputDiv = CUI.dom.div();
    outputField = new CUI.DataFieldProxy({
      name: "displayName",
      hidden: true,
      element: outputDiv
    });
    onDelete = (function(_this) {
      return function() {
        searchField.show();
        outputField.hide();
        cleanData();
        searchField.reload();
        return CUI.Events.trigger({
          node: searchField,
          type: "editor-changed"
        });
      };
    })(this);
    showOutputField = (function(_this) {
      return function() {
        var card;
        card = _this.__renderOutput({
          data: formData,
          editor: true,
          onDelete: onDelete,
          onModify: function() {
            var id;
            id = formData.gazId;
            onDelete();
            searchData.q = id;
            searchField.reload();
            return search();
          }
        });
        CUI.dom.replace(outputDiv, card);
        return outputField.show();
      };
    })(this);
    cleanData = (function(_this) {
      return function() {
        delete formData.displayName;
        delete formData.gazId;
        delete formData.otherNames;
        delete formData.types;
        delete formData.position;
        return delete formData.iconName;
      };
    })(this);
    setData = (function(_this) {
      return function(object) {
        searchData.q = "";
        return ez5.GazetteerUtil.setObjectData(formData, object);
      };
    })(this);
    searchXHR = null;
    search = (function(_this) {
      return function() {
        if (searchXHR != null) {
          searchXHR.abort();
        }
        autocompletionPopup.emptyContainer(resultsContainer);
        autocompletionPopup.emptyContainer(loadingContainer);
        autocompletionPopup.emptyContainer(noResultsContainer);
        if (searchData.q.length === 0) {
          return;
        }
        autocompletionPopup.getContainer(loadingContainer).replace(loadingLabel);
        autocompletionPopup.show();
        searchXHR = new CUI.XHR({
          method: "GET",
          url: ez5.GazetteerUtil.SEARCH_API_URL + CUI.encodeUrlData(searchData)
        });
        return searchXHR.start().done(function(data) {
          var fn, i, len, object, ref, ref1;
          autocompletionPopup.emptyContainer(loadingContainer);
          if (((ref = data.result) != null ? ref.length : void 0) === 0) {
            autocompletionPopup.getContainer(noResultsContainer).replace(noResultsLabel);
            return;
          }
          ref1 = data.result;
          fn = function(object) {
            var item;
            item = autocompletionPopup.appendItem(resultsContainer, _this.__renderAutocompleteCard(object));
            return CUI.Events.listen({
              type: "click",
              node: item,
              call: function(ev) {
                ev.stopPropagation();
                if (object) {
                  setData(object);
                } else {
                  cleanData();
                }
                searchField.hide();
                showOutputField();
                autocompletionPopup.hide();
                CUI.Events.trigger({
                  node: searchField,
                  type: "editor-changed"
                });
              }
            });
          };
          for (i = 0, len = ref1.length; i < len; i++) {
            object = ref1[i];
            fn(object);
          }
          return CUI.Events.trigger({
            type: "content-resize",
            node: autocompletionPopup
          });
        });
      };
    })(this);
    if (CUI.util.isEmpty(formData) || formData.notFound || !formData.gazId) {
      searchField.show();
    } else {
      showOutputField();
    }
    return [searchField, outputField];
  };

  CustomDataTypeGazetteer.prototype.__initData = function(data) {
    var initData;
    if (!data[this.name()]) {
      initData = {};
      data[this.name()] = initData;
    } else {
      initData = data[this.name()];
    }
    return initData;
  };

  CustomDataTypeGazetteer.prototype.__renderOutput = function(opts) {
    var formData;
    formData = opts.data;
    if (formData.notFound) {
      return new CUI.EmptyLabel({
        text: $$("custom.data.type.gazetteer.preview.id-not-found"),
        "class": "ez-label-invalid"
      });
    }
    if (formData.gazId) {
      return this.__renderCard(opts);
    } else {
      return new CUI.EmptyLabel({
        text: $$("custom.data.type.gazetteer.preview.empty-label")
      });
    }
  };

  CustomDataTypeGazetteer.prototype.__renderAutocompleteCard = function(data) {
    var object;
    object = {};
    ez5.GazetteerUtil.setObjectData(object, data);
    return this.__renderCard({
      data: object,
      small: true
    });
  };

  CustomDataTypeGazetteer.prototype.__renderCard = function(_opts) {
    var content, data, editor, i, j, len, len1, link, list, menuButton, menuItems, onDelete, onModify, onlyText, opts, otherName, otherNameLabels, otherNames, plugin, previewImage, ref, ref1, ref2, showLess, showMore, showMoreLessButton, showingMore, small, type, types, verticalList, verticalListContent;
    opts = CUI.Element.readOpts(_opts, "CustomDataTypeGazetteer.__renderCard", {
      data: {
        check: "PlainObject",
        mandatory: true
      },
      editor: {
        check: Boolean,
        "default": false
      },
      small: {
        check: Boolean,
        "default": false
      },
      onlyText: {
        check: Boolean,
        "default": false
      },
      onDelete: {
        check: Function
      },
      onModify: {
        check: Function
      }
    });
    data = opts.data, editor = opts.editor, small = opts.small, onDelete = opts.onDelete, onModify = opts.onModify, onlyText = opts.onlyText;
    content = [
      new CUI.Label({
        text: data.displayName,
        appearance: "title",
        multiline: true
      })
    ];
    if (onlyText) {
      return content[0];
    }
    link = ez5.GazetteerUtil.PLACE_URL + data.gazId;
    menuItems = [
      new LocaButtonHref({
        loca_key: "custom.data.type.gazetteer.link.button",
        href: link,
        target: "_blank"
      })
    ];
    if (!small) {
      if (CUI.Map.isValidPosition(data.position)) {
        menuItems.push(new LocaButton({
          loca_key: "custom.data.type.gazetteer.preview.button",
          onClick: (function(_this) {
            return function() {
              var previewPopover;
              previewPopover = new CUI.Popover({
                element: menuButton,
                placement: "sw",
                pane: _this.__buildPreviewMap(data.position, data.iconName),
                onHide: function() {
                  return previewPopover.destroy();
                }
              });
              return previewPopover.show();
            };
          })(this)
        }));
      }
      if (editor) {
        menuItems.push(new LocaButton({
          loca_key: "custom.data.type.gazetteer.delete.button",
          onClick: (function(_this) {
            return function() {
              return typeof onDelete === "function" ? onDelete() : void 0;
            };
          })(this)
        }));
        menuItems.push(new LocaButton({
          loca_key: "custom.data.type.gazetteer.modify.button",
          onClick: (function(_this) {
            return function() {
              return typeof onModify === "function" ? onModify() : void 0;
            };
          })(this)
        }));
      }
      menuButton = new LocaButton({
        loca_key: "custom.data.type.gazetteer.menu.button",
        icon: "ellipsis_v",
        icon_right: false,
        appearance: "flat",
        menu: {
          items: menuItems
        }
      });
    }
    if (data.types) {
      types = [];
      ref = data.types;
      for (i = 0, len = ref.length; i < len; i++) {
        type = ref[i];
        types.push($$("custom.data.type.gazetteer.types." + type + ".text"));
      }
      content.push(new CUI.Label({
        text: types.join(", "),
        appearance: "secondary"
      }));
    }
    if (!CUI.util.isEmpty(data.otherNames) && ((ref1 = ez5.session.getBaseConfig("plugin", "custom-data-type-gazetteer").gazetteer_plugin_settings) != null ? ref1.show_alternative_names : void 0)) {
      otherNameLabels = [];
      showingMore = false;
      showMoreLessButton = new CUI.Button({
        text: "",
        appearance: "link",
        size: "mini",
        onClick: (function(_this) {
          return function() {
            if (showingMore) {
              showLess();
            } else {
              showMore();
            }
            return showingMore = !showingMore;
          };
        })(this)
      });
      CUI.dom.hideElement(showMoreLessButton);
      showLess = function() {
        var j, k, label, len1, level;
        for (j = 0, len1 = otherNameLabels.length; j < len1; j++) {
          label = otherNameLabels[j];
          CUI.dom.hideElement(label);
        }
        for (level = k = 0; k <= 3; level = k += 1) {
          if (!otherNameLabels[level]) {
            continue;
          }
          CUI.dom.showElement(otherNameLabels[level]);
        }
        if (otherNameLabels.length > 4) {
          showMoreLessButton.setText($$("custom.data.type.gazetteer.types.card.show-more-button"));
          CUI.dom.showElement(showMoreLessButton);
        }
      };
      showMore = function() {
        var j, label, len1;
        for (j = 0, len1 = otherNameLabels.length; j < len1; j++) {
          label = otherNameLabels[j];
          CUI.dom.showElement(label);
        }
        showMoreLessButton.setText($$("custom.data.type.gazetteer.types.card.show-less-button"));
      };
      otherNames = data.otherNames.map(function(otherName) {
        return otherName.title;
      });
      for (j = 0, len1 = otherNames.length; j < len1; j++) {
        otherName = otherNames[j];
        otherNameLabels.push(new CUI.Label({
          text: otherName,
          appearance: "secondary"
        }));
      }
      showLess();
      verticalListContent = small ? otherNameLabels : otherNameLabels.concat([showMoreLessButton]);
      verticalList = new CUI.VerticalList({
        content: verticalListContent
      });
      content.push(verticalList);
    }
    if (!CUI.util.isEmpty(data.position) && ((ref2 = ez5.session.getBaseConfig("plugin", "custom-data-type-gazetteer").gazetteer_plugin_settings) != null ? ref2.show_lat_lng : void 0)) {
      content.push(new CUI.Label({
        text: $$("custom.data.type.gazetteer.types.latitude_longitude.text", data.position),
        appearance: "secondary"
      }));
    }
    list = new CUI.VerticalList({
      content: content
    });
    if (small) {
      return list;
    } else {
      plugin = ez5.pluginManager.getPlugin("custom-data-type-gazetteer");
      previewImage = new Image(36, 36);
      previewImage.src = plugin.getBaseURL() + plugin.getWebfrontend().logo;
      return new CUI.HorizontalLayout({
        "class": "ez5-field-object ez5-custom-data-type-gazetteer-card",
        left: {
          content: previewImage
        },
        center: {
          content: list
        },
        right: {
          content: menuButton
        }
      });
    }
  };

  CustomDataTypeGazetteer.prototype.__buildPreviewMap = function(position, iconName) {
    return new CUI.MapInput.defaults.mapClass({
      selectedMarkerPosition: position,
      selectedMarkerOptions: {
        iconName: iconName,
        iconColor: "#6786ad"
      },
      centerPosition: position,
      clickable: false,
      zoom: 10
    });
  };

  CustomDataTypeGazetteer.prototype.__fillMissingData = function(data) {
    var deferred;
    if (data.gazId && (!data.displayName || !data.types)) {
      deferred = new CUI.Deferred();
      ez5.GazetteerUtil.searchById(data.gazId).done((function(_this) {
        return function(dataFound) {
          return ez5.GazetteerUtil.setObjectData(data, dataFound);
        };
      })(this)).fail((function(_this) {
        return function() {
          return data.notFound = true;
        };
      })(this)).always(deferred.resolve);
      return deferred.promise();
    } else {
      return CUI.resolvedPromise();
    }
  };

  CustomDataTypeGazetteer.prototype.isPluginSupported = function(plugin) {
    if (plugin instanceof MapDetailPlugin) {
      return true;
    }
    return false;
  };

  return CustomDataTypeGazetteer;

})(CustomDataType);

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

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

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

  CustomBaseConfigGazetteer.prototype.getFieldDefFromParm = function(baseConfig, fieldName, def) {
    var field, getMask, getTopLevelRequiredFields;
    getMask = function(idTable) {
      if (CUI.util.isString(idTable)) {
        return false;
      }
      return Mask.getMaskByMaskName("_all_fields", idTable);
    };
    getTopLevelRequiredFields = function(objecttype) {
      return objecttype.getFields().filter(function(field) {
        return field.isTopLevelField() && field.isRequired();
      });
    };
    switch (def.plugin_type) {
      case "objecttype":
        field = new ez5.ObjecttypeSelector({
          form: {
            label: $$("custom.data.type.gazetteer.config.objecttype.label")
          },
          name: fieldName,
          show_name: true,
          store_value: "fullname",
          filter: function(objecttype) {
            var hasGazetteerField, mask, requiredUniqueFields;
            if (!objecttype.isHierarchy()) {
              return false;
            }
            mask = getMask(objecttype.table.id());
            if (!mask) {
              return false;
            }
            objecttype.addMask(mask);
            hasGazetteerField = objecttype.getFields().some(function(field) {
              return field instanceof CustomDataTypeGazetteer;
            });
            if (!hasGazetteerField) {
              return false;
            }
            requiredUniqueFields = getTopLevelRequiredFields(objecttype);
            if (requiredUniqueFields.length === 0) {
              return true;
            }
            if (requiredUniqueFields.length > 1) {
              return false;
            }
            return requiredUniqueFields[0] instanceof CustomDataTypeGazetteer;
          }
        });
        break;
      case "field_from":
        field = new ez5.FieldSelector({
          form: {
            label: $$("custom.data.type.gazetteer.config.field_from.label")
          },
          name: fieldName,
          objecttype_data_key: "objecttype",
          store_value: "fullname",
          show_name: true,
          placeholder: $$("custom.data.type.gazetteer.config.field-from-empty-text"),
          filter: function(field) {
            return field instanceof TextColumn && !(field instanceof NestedTable) && !(field instanceof NumberColumn) && !(field instanceof LocaTextColumn) && !field.isTopLevelField() && !field.insideNested();
          }
        });
        break;
      case "field_to":
        field = new ez5.FieldSelector({
          form: {
            label: $$("custom.data.type.gazetteer.config.field_to.label")
          },
          name: fieldName,
          objecttype_data_key: "objecttype",
          store_value: "fullname",
          show_name: true,
          filter: (function(_this) {
            return function(fieldTo) {
              var mask, objecttype, requiredUniqueFields;
              if (!(fieldTo instanceof CustomDataTypeGazetteer)) {
                return false;
              }
              if (fieldTo.insideNested()) {
                return false;
              }
              mask = getMask(fieldTo.table.id());
              if (!mask) {
                return false;
              }
              objecttype = new Objecttype(mask);
              requiredUniqueFields = getTopLevelRequiredFields(objecttype);
              if (requiredUniqueFields.length === 0) {
                return true;
              }
              return requiredUniqueFields[0].id() === fieldTo.id();
            };
          })(this)
        });
    }
    return field;
  };

  return CustomBaseConfigGazetteer;

})(BaseConfigPlugin);

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

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

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

  CasterGazetteer.prototype.__initCasters = function() {
    return [
      {
        name: $$("custom.data.type.gazetteer.name.caster.name"),
        description: $$("custom.data.type.gazetteer.name.caster.description"),
        canCast: (function(_this) {
          return function(from, to) {
            return !(from instanceof LocaTextColumn) && from instanceof TextColumn && to instanceof CustomDataTypeGazetteer;
          };
        })(this),
        doCast: (function(_this) {
          return function(value) {
            var deferred, gazId;
            gazId = CUI.util.getInt(value);
            if (CUI.util.isNull(gazId)) {
              return;
            }
            deferred = new CUI.Deferred();
            ez5.GazetteerUtil.searchById(gazId).done(function(dataFound) {
              var newData;
              newData = {};
              ez5.GazetteerUtil.setObjectData(newData, dataFound);
              return deferred.resolve(newData);
            }).fail(function() {
              return deferred.resolve();
            });
            return deferred.promise();
          };
        })(this)
      }
    ];
  };

  return CasterGazetteer;

})(ez5.CasterPlugin);

ez5.session_ready(function() {
  var ref;
  return (ref = ez5.ScriptRunner.FieldsMigrator.casterPlugins) != null ? ref.registerPlugin(ez5.CasterGazetteer) : void 0;
});
// Generated by CoffeeScript 1.12.7
ez5.GazetteerUtil = (function() {
  function GazetteerUtil() {}

  GazetteerUtil.SEARCH_API_URL = "https://gazetteer.dainst.org/search.json?limit=20&";

  GazetteerUtil.SEARCH_QUERY_API_URL = "https://gazetteer.dainst.org/search.json?q=";

  GazetteerUtil.ID_API_URL = "https://gazetteer.dainst.org/doc/";

  GazetteerUtil.PLACE_URL = "https://gazetteer.dainst.org/place/";

  GazetteerUtil.JSON_EXTENSION = ".json";

  GazetteerUtil.searchById = function(id) {
    var xhr;
    xhr = new CUI.XHR({
      method: "GET",
      url: ez5.GazetteerUtil.ID_API_URL + id + ez5.GazetteerUtil.JSON_EXTENSION
    });
    return xhr.start();
  };

  GazetteerUtil.searchByQuery = function(query, _options) {
    var options, xhr;
    if (_options == null) {
      _options = {};
    }
    options = {
      method: "GET",
      url: ez5.GazetteerUtil.SEARCH_QUERY_API_URL + query
    };
    CUI.util.mergeMap(options, _options);
    xhr = new CUI.XHR(options);
    return xhr.start();
  };

  GazetteerUtil.setObjectData = function(object, data) {
    var position, ref, ref1, ref2, ref3;
    if (CUI.util.isEmpty(data)) {
      return object;
    }
    delete object.notFound;
    object.displayName = (ref = data.prefName) != null ? ref.title : void 0;
    object.gazId = data.gazId;
    object.otherNames = data.names;
    object.types = data.types || [];
    if ((ref1 = data.prefLocation) != null ? ref1.coordinates : void 0) {
      position = {
        lng: (ref2 = data.prefLocation) != null ? ref2.coordinates[0] : void 0,
        lat: (ref3 = data.prefLocation) != null ? ref3.coordinates[1] : void 0
      };
      if (CUI.Map.isValidPosition(position)) {
        object.position = position;
        object.iconName = data.prefLocation ? "fa-map" : "fa-map-marker";
      }
    }
    return object;
  };

  GazetteerUtil.getSaveDataObject = function(data) {
    var fulltext, object, ref;
    fulltext = data.displayName;
    if (((ref = data.otherNames) != null ? ref.length : void 0) > 0) {
      fulltext = data.otherNames.map(function(otherName) {
        return otherName.title;
      }).concat(fulltext).join(' ');
    }
    object = {
      displayName: data.displayName,
      gazId: data.gazId,
      position: data.position,
      iconName: data.iconName,
      otherNames: data.otherNames,
      types: data.types,
      _fulltext: {
        text: fulltext,
        string: data.gazId
      },
      _standard: {
        text: data.displayName
      }
    };
    return object;
  };

  return GazetteerUtil;

})();
