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

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

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

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

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

  CustomDataTypeGND.prototype.__getAdditionalTooltipInfo = function(uri, tooltip, extendedInfo_xhr) {
    var gndID, gndIDTest, xurl;
    gndID = uri;
    gndIDTest = gndID.split("/");
    if (gndIDTest.length === 1) {
      gndID = gndID.split("%2F");
    } else {
      gndID = gndIDTest;
    }
    gndID = gndID.pop();
    if (extendedInfo_xhr.xhr !== void 0) {
      extendedInfo_xhr.abort();
    }
    xurl = location.protocol + '//jsontojsonp.gbv.de/?url=http://hub.culturegraph.org/entityfacts/' + gndID;
    extendedInfo_xhr = new CUI.XHR({
      url: xurl
    });
    extendedInfo_xhr.start().done(function(data, status, statusText) {
      var biographicalOrHistoricalInformation, dateOfBirth, dateOfDeath, dateOfEstablishment, depiction, hierarchicallySuperiorOrganisation, htmlContent, i, j, k, l, len, len1, len2, len3, len4, m, organisation, organisations, place, placeOfBirth, placeOfBusiness, placeOfDeath, placeOfEvent, places, profession, professionOrOccupation, professions, t, topic, topics, variantName, variantNames;
      if (!data.preferredName) {
        return tooltip.hide();
      } else {
        htmlContent = '';
        htmlContent += '<table style="border-spacing: 10px; border-collapse: separate;">';
        htmlContent += '<tr><td colspan="2"><h4>Informationen über den Eintrag</h4></td></tr>';
        htmlContent += "<tr><td>Name:</td><td>" + data.preferredName + "</td></tr>";
        depiction = data.depiction;
        if (depiction) {
          if (depiction.thumbnail) {
            htmlContent += '<tr><td>Abbildung:</td><td><img src="' + depiction.thumbnail['@id'] + '" style="border: 0; max.width:120px; max-height:150px;" /></td></tr>';
          }
        }
        dateOfBirth = data.dateOfBirth;
        dateOfDeath = data.dateOfDeath;
        if (dateOfBirth || dateOfDeath) {
          htmlContent += "<tr><td>Lebensdaten:</td><td>";
          if (dateOfBirth && dateOfDeath) {
            htmlContent += dateOfBirth + " bis " + dateOfDeath;
          } else if (dateOfBirth && !dateOfDeath) {
            htmlContent += dateOfBirth + " bis unbekannt";
          } else if (!dateOfBirth && dateOfDeath) {
            htmlContent += "unbekannt bis " + dateOfDeath;
          }
          htmlContent += "</td></tr>";
        }
        dateOfEstablishment = data.dateOfEstablishment;
        if (dateOfEstablishment) {
          htmlContent += "<tr><td>Gründung:</td><td>" + dateOfEstablishment[0] + "</td></tr>";
        }
        placeOfBusiness = data.placeOfBusiness;
        places = [];
        if (placeOfBusiness) {
          if (placeOfBusiness.length > 0) {
            for (i = 0, len = placeOfBusiness.length; i < len; i++) {
              place = placeOfBusiness[i];
              places.push(place.preferredName);
            }
            htmlContent += "<tr><td>Niederlassung(en):</td><td>" + places.join("<br />") + "</td></tr>";
          }
        }
        placeOfEvent = data.placeOfEvent;
        places = [];
        if (placeOfEvent) {
          if (placeOfEvent.length > 0) {
            for (j = 0, len1 = placeOfEvent.length; j < len1; j++) {
              place = placeOfEvent[j];
              places.push(place.preferredName);
            }
            htmlContent += "<tr><td>Veranstaltungsort(e):</td><td>" + places.join("<br />") + "</td></tr>";
          }
        }
        hierarchicallySuperiorOrganisation = data.hierarchicallySuperiorOrganisation;
        organisations = [];
        if (hierarchicallySuperiorOrganisation) {
          if (hierarchicallySuperiorOrganisation.length > 0) {
            for (k = 0, len2 = hierarchicallySuperiorOrganisation.length; k < len2; k++) {
              organisation = hierarchicallySuperiorOrganisation[k];
              organisations.push(organisation.preferredName);
            }
            htmlContent += "<tr><td>Übergeordnete Körperschaft(en):</td><td>" + organisations.join("<br />") + "</td></tr>";
          }
        }
        placeOfBirth = data.placeOfBirth;
        if (placeOfBirth) {
          htmlContent += "<tr><td>Geburtsort:</td><td>" + placeOfBirth[0].preferredName + "</td></tr>";
        }
        placeOfDeath = data.placeOfDeath;
        if (placeOfDeath) {
          htmlContent += "<tr><td>Sterbeort:</td><td>" + placeOfDeath[0].preferredName + "</td></tr>";
        }
        professionOrOccupation = data.professionOrOccupation;
        professions = [];
        if (professionOrOccupation) {
          if (professionOrOccupation.length > 0) {
            for (l = 0, len3 = professionOrOccupation.length; l < len3; l++) {
              profession = professionOrOccupation[l];
              professions.push(profession.preferredName);
            }
            htmlContent += "<tr><td>Beruf(e):</td><td>" + professions.join("<br />") + "</td></tr>";
          }
        }
        biographicalOrHistoricalInformation = data.biographicalOrHistoricalInformation;
        if (biographicalOrHistoricalInformation) {
          htmlContent += "<tr><td>Biographie:</td><td>" + biographicalOrHistoricalInformation + "</td></tr>";
        }
        topic = data.topic;
        topics = [];
        if (topic) {
          if (topic.length > 0) {
            for (m = 0, len4 = topic.length; m < len4; m++) {
              t = topic[m];
              topics.push(t.preferredName);
            }
            htmlContent += "<tr><td>Themen:</td><td>" + topics.join("<br />") + "</td></tr>";
          }
        }
        variantName = data.variantName;
        if (variantName) {
          if (variantName.length > 0) {
            variantNames = variantName.join("<br />");
            htmlContent += "<tr><td>Synonyme:</td><td>" + variantNames + "</td></tr>";
          }
        }
        htmlContent += "</table>";
        tooltip.DOM.innerHTML = htmlContent;
        return tooltip.autoSize();
      }
    }).fail(function(data, status, statusText) {
      return tooltip.hide();
    });
  };

  CustomDataTypeGND.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 gnd_countSuggestions, gnd_searchterm, gnd_searchtype, ref, ref1, ref2, ref3, ref4, ref5, ref6, subclass, subclassQuery;
      gnd_searchterm = searchstring;
      gnd_searchtype = false;
      gnd_countSuggestions = 50;
      if (cdata_form) {
        gnd_searchtype = cdata_form.getFieldsByName("gndSelectType")[0].getValue();
        gnd_countSuggestions = cdata_form.getFieldsByName("countOfSuggestions")[0].getValue();
      }
      if (gnd_searchtype === 'all_supported_types' || !gnd_searchtype) {
        gnd_searchtype = [];
        if ((ref = that.getCustomSchemaSettings().add_differentiatedpersons) != null ? ref.value : void 0) {
          gnd_searchtype.push('DifferentiatedPerson');
        }
        if ((ref1 = that.getCustomSchemaSettings().add_coorporates) != null ? ref1.value : void 0) {
          gnd_searchtype.push('CorporateBody');
        }
        if ((ref2 = that.getCustomSchemaSettings().add_geographicplaces) != null ? ref2.value : void 0) {
          gnd_searchtype.push('PlaceOrGeographicName');
        }
        if ((ref3 = that.getCustomSchemaSettings().add_subjects) != null ? ref3.value : void 0) {
          gnd_searchtype.push('SubjectHeading');
        }
        if ((ref4 = that.getCustomSchemaSettings().add_works) != null ? ref4.value : void 0) {
          gnd_searchtype.push('Work');
        }
        if ((ref5 = that.getCustomSchemaSettings().add_conferenceorevent) != null ? ref5.value : void 0) {
          gnd_searchtype.push('ConferenceOrEvent');
        }
        gnd_searchtype = gnd_searchtype.join(',');
      }
      subclass = (ref6 = that.getCustomSchemaSettings().exact_types) != null ? ref6.value : void 0;
      subclassQuery = '';
      if (subclass !== void 0) {
        if (subclass !== 'ALLE') {
          subclassQuery = '&exact_type=' + subclass;
        }
      }
      if (gnd_searchterm.length === 0) {
        return;
      }
      if (searchsuggest_xhr.xhr !== void 0) {
        searchsuggest_xhr.xhr.abort();
      }
      searchsuggest_xhr.xhr = new CUI.XHR({
        url: location.protocol + '//ws.gbv.de/suggest/gnd/?searchterm=' + gnd_searchterm + '&type=' + gnd_searchtype + subclassQuery + '&count=' + gnd_countSuggestions
      });
      return searchsuggest_xhr.xhr.start().done(function(data, status, statusText) {
        var extendedInfo_xhr, fn, i, itemList, key, len, menu_items, ref7, suggestion;
        extendedInfo_xhr = {
          "xhr": void 0
        };
        menu_items = [];
        ref7 = 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) {
                var ref8;
                if ((ref8 = that.getCustomMaskSettings().show_infopopup) != null ? ref8.value : void 0) {
                  aktType = aktType.split(' / ');
                  aktType = aktType[0];
                  if (aktType === "DifferentiatedPerson" || aktType === "CorporateBody" || aktType === "PlaceOrGeographicName" || aktType === "ConferenceOrEvent") {
                    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 = ref7.length; i < len; key = ++i) {
          suggestion = ref7[key];
          fn(key);
        }
        itemList = {
          keyboardControl: true,
          onClick: function(ev2, btn) {
            var GNDId, GNDURIParts, xurl;
            cdata.conceptURI = btn.getOpt("value");
            GNDURIParts = cdata.conceptURI.split('/');
            GNDId = GNDURIParts.pop();
            cdata.conceptName = btn.getText();
            xurl = 'https://jsontojsonp.gbv.de/?url=' + CUI.encodeURIComponentNicely('https://lobid.org/gnd/' + GNDId);
            extendedInfo_xhr = new CUI.XHR({
              url: xurl
            });
            return extendedInfo_xhr.start().done(function(data, status, statusText) {
              var resultsGNDID;
              resultsGNDID = data['gndIdentifier'];
              cdata.conceptURI = data['id'];
              cdata._standard = {
                text: cdata.conceptName
              };
              return cdata._fulltext = {
                text: ez5.GNDUtil.getFullTextFromEntityFactsJSON(data)
              };
            }).always(function() {
              that.__updateResult(cdata, layout, opts);
              suggest_Menu.hide();
              if (that.popover) {
                that.popover.hide();
              }
              return this;
            });
          },
          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);
  };

  CustomDataTypeGND.prototype.__getEditorFields = function(cdata) {
    var dropDownSearchOptions, option, ref, ref1, ref2, ref3, ref4, ref5;
    dropDownSearchOptions = [];
    if ((ref = this.getCustomSchemaSettings().add_differentiatedpersons) != null ? ref.value : void 0) {
      option = {
        value: 'DifferentiatedPerson',
        text: $$('custom.data.type.gnd.config.parameter.schema.add_differentiatedpersons.value.checkbox')
      };
      dropDownSearchOptions.push(option);
    }
    if ((ref1 = this.getCustomSchemaSettings().add_coorporates) != null ? ref1.value : void 0) {
      option = {
        value: 'CorporateBody',
        text: $$('custom.data.type.gnd.config.parameter.schema.add_coorporates.value.checkbox')
      };
      dropDownSearchOptions.push(option);
    }
    if ((ref2 = this.getCustomSchemaSettings().add_geographicplaces) != null ? ref2.value : void 0) {
      option = {
        value: 'PlaceOrGeographicName',
        text: $$('custom.data.type.gnd.config.parameter.schema.add_geographicplaces.value.checkbox')
      };
      dropDownSearchOptions.push(option);
    }
    if ((ref3 = this.getCustomSchemaSettings().add_subjects) != null ? ref3.value : void 0) {
      option = {
        value: 'SubjectHeading',
        text: $$('custom.data.type.gnd.config.parameter.schema.add_subjects.value.checkbox')
      };
      dropDownSearchOptions.push(option);
    }
    if ((ref4 = this.getCustomSchemaSettings().add_works) != null ? ref4.value : void 0) {
      option = {
        value: 'Work',
        text: $$('custom.data.type.gnd.config.parameter.schema.add_works.value.checkbox')
      };
      dropDownSearchOptions.push(option);
    }
    if ((ref5 = this.getCustomSchemaSettings().add_conferenceorevent) != null ? ref5.value : void 0) {
      option = {
        value: 'ConferenceOrEvent',
        text: $$('custom.data.type.gnd.config.parameter.schema.add_conferenceorevent.value.checkbox')
      };
      dropDownSearchOptions.push(option);
    }
    if (dropDownSearchOptions.length > 1) {
      option = {
        value: 'all_supported_types',
        text: $$('custom.data.type.gnd.config.option.schema.exact_types.value.all')
      };
      dropDownSearchOptions.unshift(option);
    }
    if (dropDownSearchOptions.length === 0) {
      dropDownSearchOptions = [
        {
          value: 'DifferentiatedPerson',
          text: 'Individualisierte Personen'
        }, {
          value: 'CorporateBody',
          text: 'Körperschaften'
        }, {
          value: 'PlaceOrGeographicName',
          text: 'Orte und Geographische Namen'
        }, {
          value: 'SubjectHeading',
          text: 'Schlagwörter'
        }, {
          value: 'Work',
          text: 'Werke'
        }, {
          value: 'ConferenceOrEvent',
          text: 'Konferenzen und Veranstaltungen'
        }
      ];
    }
    return [
      {
        type: CUI.Select,
        undo_and_changed_support: false,
        form: {
          label: $$('custom.data.type.gnd.modal.form.text.type')
        },
        options: dropDownSearchOptions,
        name: 'gndSelectType',
        "class": 'commonPlugin_Select'
      }, {
        type: CUI.Select,
        undo_and_changed_support: false,
        "class": 'commonPlugin_Select',
        form: {
          label: $$('custom.data.type.gnd.modal.form.text.count')
        },
        options: [
          {
            value: 10,
            text: '10 ' + $$('custom.data.type.gnd.modal.form.text.count_short')
          }, {
            value: 20,
            text: '20 ' + $$('custom.data.type.gnd.modal.form.text.count_short')
          }, {
            value: 50,
            text: '50 ' + $$('custom.data.type.gnd.modal.form.text.count_short')
          }, {
            value: 100,
            text: '100 ' + $$('custom.data.type.gnd.modal.form.text.count_short')
          }, {
            value: 250,
            text: '250 ' + $$('custom.data.type.gnd.modal.form.text.count_short')
          }
        ],
        name: 'countOfSuggestions'
      }, {
        type: CUI.Input,
        undo_and_changed_support: false,
        form: {
          label: $$("custom.data.type.gnd.modal.form.text.searchbar")
        },
        placeholder: $$("custom.data.type.gnd.modal.form.text.searchbar.placeholder"),
        name: "searchbarInput",
        "class": 'commonPlugin_Input'
      }, {
        form: {
          label: $$('custom.data.type.gnd.modal.form.text.result.label')
        },
        type: CUI.Output,
        name: "conceptName",
        data: {
          conceptName: cdata.conceptName
        }
      }, {
        form: {
          label: $$('custom.data.type.gnd.modal.form.text.uri.label')
        },
        type: CUI.FormButton,
        name: "conceptURI",
        icon: new CUI.Icon({
          "class": "fa-lightbulb-o"
        }),
        text: cdata.conceptURI,
        onClick: (function(_this) {
          return function(evt, button) {
            return window.open(cdata.conceptURI, "_blank");
          };
        })(this),
        onRender: (function(_this) {
          return function(_this) {
            if (cdata.conceptURI === '') {
              return _this.hide();
            }
          };
        })(this)
      }
    ];
  };

  CustomDataTypeGND.prototype.__renderButtonByData = function(cdata) {
    var conceptURI, encodedURI, tt_text;
    switch (this.getDataStatus(cdata)) {
      case "empty":
        return new CUI.EmptyLabel({
          text: $$("custom.data.type.gnd.edit.no_gnd")
        }).DOM;
      case "invalid":
        return new CUI.EmptyLabel({
          text: $$("custom.data.type.gnd.edit.no_valid_gnd")
        }).DOM;
    }
    conceptURI = CUI.parseLocation(cdata.conceptURI).url;
    tt_text = $$("custom.data.type.gnd.url.tooltip", {
      name: cdata.conceptName
    });
    encodedURI = encodeURIComponent(cdata.conceptURI);
    return new CUI.HorizontalLayout({
      maximize: true,
      left: {
        content: new CUI.Label({
          centered: false,
          text: cdata.conceptName
        })
      },
      center: {
        content: new CUI.ButtonHref({
          appearance: "link",
          href: cdata.conceptURI,
          target: "_blank",
          tooltip: {
            markdown: true,
            text: tt_text
          }
        })
      },
      right: null
    }).DOM;
  };

  CustomDataTypeGND.prototype.getCustomDataOptionsInDatamodelInfo = function(custom_settings) {
    var ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, tags;
    tags = [];
    if ((ref = custom_settings.add_differentiatedpersons) != null ? ref.value : void 0) {
      tags.push("✓ Personen");
    } else {
      tags.push("✘ Personen");
    }
    if ((ref1 = custom_settings.add_coorporates) != null ? ref1.value : void 0) {
      tags.push("✓ Körperschaften");
    } else {
      tags.push("✘ Körperschaften");
    }
    if ((ref2 = custom_settings.add_geographicplaces) != null ? ref2.value : void 0) {
      tags.push("✓ Orte");
    } else {
      tags.push("✘ Orte");
    }
    if ((ref3 = custom_settings.add_subjects) != null ? ref3.value : void 0) {
      tags.push("✓ Schlagwörter");
    } else {
      tags.push("✘ Schlagwörter");
    }
    if ((ref4 = custom_settings.add_works) != null ? ref4.value : void 0) {
      tags.push("✓ Werke");
    } else {
      tags.push("✘ Werke");
    }
    if ((ref5 = custom_settings.add_conferenceorevent) != null ? ref5.value : void 0) {
      tags.push("✓ Konferenzen und Veranstaltungen");
    } else {
      tags.push("✘ Konferenzen und Veranstaltungen");
    }
    if ((ref6 = custom_settings.exact_types) != null ? ref6.value : void 0) {
      tags.push("✓ Exakter Typ: " + ((ref7 = custom_settings.exact_types) != null ? ref7.value : void 0));
    } else {
      tags.push("✘ Exakter Typ");
    }
    return tags;
  };

  return CustomDataTypeGND;

})(CustomDataTypeWithCommons);

CustomDataType.register(CustomDataTypeGND);
