Hinweis: Leere nach dem Veröffentlichen den Browser-Cache, um die Änderungen sehen zu können.

  • Firefox/Safari: Umschalttaste drücken und gleichzeitig Aktualisieren anklicken oder entweder Strg+F5 oder Strg+R (⌘+R auf dem Mac) drücken
  • Google Chrome: Umschalttaste+Strg+R (⌘+Umschalttaste+R auf dem Mac) drücken
  • Edge: Strg+F5 drücken oder Strg drücken und gleichzeitig Aktualisieren anklicken
// <nowiki>
var EightSisters = {
  queryPageProps      : {
    action: 'query',
    prop: ['pageprops', 'extlinks'],
    ppprop: 'wikibase_item',
    elquery: 'commons.wikimedia.org',
    pageids: mw.config.get('wgArticleId'),
  },
  api : 0,
  qId : '',
  redirCatFrom : null,
  redirCatTo : null,
  haveAny : false,
  addWeblinks : -1,
  sisterData : {
    0 : { tmpl : 'Commons',     sitelink : 'commonswiki',   property : 'P935', pagelnk: 'https://commons.wikimedia.org/wiki/' },
    1 : { tmpl : 'Commonscat',                              property : 'P373', pagelnk: 'https://commons.wikimedia.org/wiki/Category:' },
    2 : { tmpl : 'Wikibooks',   sitelink : 'dewikibooks',                      pagelnk: 'https://de.wikibooks.org/wiki/' },
    3 : { tmpl : 'Wikispecies', sitelink : 'specieswiki',                      pagelnk: 'https://species.wikimedia.org/wiki/' },
    4 : { tmpl : 'Wikiquote',   sitelink : 'dewikiquote',                      pagelnk: 'https://de.wikiquote.org/wiki/' },
    5 : { tmpl : 'Wikisource',  sitelink : 'dewikisource',                     pagelnk: 'https://de.wikisource.org/wiki/' },
    6 : { tmpl : 'Wikiversity', sitelink : 'dewikiversity',                    pagelnk: 'https://de.wikiversity.org/wiki/' },
    7 : { tmpl : 'Wikivoyage',  sitelink : 'dewikivoyage',                     pagelnk: 'https://de.wikivoyage.org/wiki/' },
    8 : { tmpl : 'Wiktionary',  sitelink : 'dewiktionary',                     pagelnk: 'https://de.wiktionary.org/wiki/' }
   },

  execute : function () {
    if(mw.config.get('wgNamespaceNumber') != 0 &&
       mw.config.get('wgNamespaceNumber') != 14)
      return;
    if(mw.config.get('wgNamespaceNumber') == 14) {
      EightSisters.sisterData[ 9] = { tmpl: 'Themenkategorie Welterbe',        pagelnk: 'https://commons.wikimedia.org/wiki/Category:', add: 1, param: 5,            data: 'v' };
      EightSisters.sisterData[10] = { tmpl: 'Kategorie Curling',               pagelnk: 'https://commons.wikimedia.org/wiki/Category:', add: 1, param: 'Commonscat', data: null }; // Nur bei "nein" dieses entfernen
      EightSisters.sisterData[11] = { tmpl: 'Kategorie Eishockey',             pagelnk: 'https://commons.wikimedia.org/wiki/Category:', add: 1, param: 'Commonscat', data: null }; // Nur bei "nein" dieses entfernen
      EightSisters.sisterData[12] = { tmpl: 'Kategorie Filmjahr nach Jahr',    pagelnk: 'https://commons.wikimedia.org/wiki/Category:', add: 1, param: 'Commonscat', data: 'pv' }; // C&C Wert einsetzen
      EightSisters.sisterData[13] = { tmpl: 'Kategorie Filmjahr nach Jahr',    pagelnk: 'https://commons.wikimedia.org/wiki/Category:', add: 0, param: 'Commons',    data: 'pv' }; // C&C Wert einsetzen
      EightSisters.sisterData[14] = { tmpl: 'Kategorie Jahrhundert',           pagelnk: 'https://commons.wikimedia.org/wiki/Category:', add: 1, param: 'Commonscat', data: 'pv' }; // Cat Wert einsetzen
      EightSisters.sisterData[15] = { tmpl: 'Kategorie Raumfahrer nach Staat', pagelnk: 'https://commons.wikimedia.org/wiki/Category:', add: 1, param: 'Commonscat', data: /Astronauts[ _]+from[ _]+/, hint: 'Commonstitel' }; // Cat Inhalt: "Astronauts from " rausnehmen
      EightSisters.sisterData[16] = { tmpl: 'Kategorie Raumfahrt nach Staat',  pagelnk: 'https://commons.wikimedia.org/wiki/Category:', add: 1, param: 'Commonscat', data: 'pv', hint: 'Commonstitel' }; // Cat & Tite Wert einsetzenl
      EightSisters.sisterData[17] = { tmpl: 'Musikgruppe als Thema',           pagelnk: 'https://commons.wikimedia.org/wiki/Category:', add: 1, param: 'Commonscat', data: 'pv' }; // C&C Wert einsetzen
      EightSisters.sisterData[18] = { tmpl: 'Musikgruppe als Thema',           pagelnk: 'https://commons.wikimedia.org/wiki/Category:', add: 0, param: 'Commons',    data: 'pv' }; // C&C Wert einsetzen
      EightSisters.sisterData[19] = { tmpl: 'Person als Thema',                pagelnk: 'https://commons.wikimedia.org/wiki/Category:', add: 1, param: 'Commonscat', data: 'pv' }; // C&C Wert einsetzen
      EightSisters.sisterData[20] = { tmpl: 'Person als Thema',                pagelnk: 'https://commons.wikimedia.org/wiki/Category:', add: 0, param: 'Commons',    data: 'pv' }; // C&C Wert einsetzen
      EightSisters.sisterData[21] = { tmpl: 'Kategorie Ereignis nach Jahr',    pagelnk: 'https://commons.wikimedia.org/wiki/Category:', add: 1, param: 'Commonscat', data: 'pv' }; // C&C Wert einsetzen
      EightSisters.sisterData[22] = { tmpl: 'Kategorie Ereignis nach Jahr',    pagelnk: 'https://commons.wikimedia.org/wiki/Category:', add: 0, param: 'Commons',    data: 'pv' }; // C&C Wert einsetzen
      // EightSisters.sisterData[23] = { tmpl: 'KsPB-Allgemein-Kategorien und Commons',pagelnk:'https://commons.wikimedia.org/wiki/Category:',add: 1,param:'Commonscat',data: 'pv', hint: 'Commonstitel' }; // C&C Wert einsetzen
    }
    var action = mw.config.get('wgAction');
    if(action != 'edit' && action != 'submit')
      return;
    var message = mw.config.get('wgEditMessage');
    if(message != 'editing')
      return;

    if($('#wpTextbox1').textSelection('getContents').search(RegExp('{{\\s*[Ss]chwesterprojekte\\s*[\\|}]'/*}*/)) != -1)
      return;

    var lang = mw.config.get('wgPageContentLanguage');
    EightSisters.api = new mw.Api();
    EightSisters.queryWikidataId(EightSisters.api, EightSisters.gotWikidataId, EightSisters.queryPageProps);
  },

  gotWikidataId : function(data) {
    var pages = data.query.pages;
    var extLink = null;
    for(var p in pages) {
      if(pages[p].pageprops && pages[p].pageprops.wikibase_item)
        EightSisters.qId = pages[p].pageprops.wikibase_item;
      if(pages[p].extlinks) {
        for(var e in pages[p].extlinks) {
          if(pages[p].extlinks[e]['*']) {
            var url = pages[p].extlinks[e]['*'];
            var pos;
            if((pos = url.lastIndexOf('?')) != -1)
              url = url.substring(0, pos);
            if((pos = url.lastIndexOf('wiki/Category:')) != -1)
              url = url.substring(pos + 5);
            url = decodeURIComponent(url.replaceAll('_', ' '));
            extLink = url;
          }
        }
      }
    }
    // console.log('ExternalLinks: ' + extLink);
    if(EightSisters.qId != '') {
      var siteLinks = '';
      for(var key in Object.keys(EightSisters.sisterData)) {
        if(EightSisters.sisterData[key].sitelink)
          if(siteLinks == '')
            siteLinks += EightSisters.sisterData[key].sitelink;
          else
            siteLinks += '|' + EightSisters.sisterData[key].sitelink;
      }
      fetch('https://www.wikidata.org/w/api.php?action=wbgetentities&format=json&ids=' + EightSisters.qId + '&props=sitelinks&sitefilter=' + siteLinks + '&formatversion=2&origin=*').then(function(response) {
          // console.log("1 Response" + response);
          return response.json();
        }).then(function(response) {
          // console.log("2 Response" + response);
          for(var c in response.entities) {
            if(response.entities[c].sitelinks)
              for(var key in Object.keys(EightSisters.sisterData)) {
                if(EightSisters.sisterData[key].sitelink && response.entities[c].sitelinks[EightSisters.sisterData[key].sitelink]) {
                  if(key == 0 && response.entities[c].sitelinks[EightSisters.sisterData[key].sitelink].title.startsWith('Category:'))
                    EightSisters.sisterData[1].commonsData = response.entities[c].sitelinks[EightSisters.sisterData[key].sitelink].title.substring(9);
                  else
                    EightSisters.sisterData[key].commonsData = response.entities[c].sitelinks[EightSisters.sisterData[key].sitelink].title;
                  EightSisters.haveAny = true;
                }
              }
          }
          fetch('https://www.wikidata.org/w/api.php?action=wbgetclaims&format=json&entity=' + EightSisters.qId + '&formatversion=2&origin=*').then(function(response) {
              // console.log("1 Response" + response);
              return response.json();
            }).then(function(response) {
              // console.log("2 Response" + response);
              if(response.claims) {
                for(var key in Object.keys(EightSisters.sisterData)) {
                  if(EightSisters.sisterData[key].property && response.claims[EightSisters.sisterData[key].property])
                    for(var cc in response.claims[EightSisters.sisterData[key].property]) {
                      if(response.claims[EightSisters.sisterData[key].property][cc].rank != 'deprecated') {
                        if(key == 0 && EightSisters.sisterData[key].commonsData != null && EightSisters.sisterData[key].commonsData != response.claims[EightSisters.sisterData[key].property][cc].mainsnak.datavalue.value) {
                          console.log("Sitelink (" + EightSisters.sisterData[key].commonsData + ") is different to Property " + EightSisters.sisterData[key].property + " (" + response.claims[EightSisters.sisterData[key].property][cc].mainsnak.datavalue.value + ")");
                        }
                        else if(!EightSisters.sisterData[key].commonsData) {
                          EightSisters.sisterData[key].commonsData = response.claims[EightSisters.sisterData[key].property][cc].mainsnak.datavalue.value;
                          EightSisters.haveAny = true;
                        }
                        break;
                      }
                    }
                }
              }
              if(extLink == 0)
                EightSisters.analyseText(true);
              else
                fetch('https://commons.wikimedia.org/w/api.php?action=query&format=json&prop=revisions&titles=' + extLink + '&formatversion=2' + "&rvprop=content&rvslots=main&origin=*").then(function(response) {
                    // console.log("1 Response" + response);
                    return response.json();
                  }).then(function(response) {
                    // console.log("3 Response" + JSON.stringify(response));
                    if(response.query && response.query.pages) {
                      for(var p in response.query.pages) {
                        // console.log("p: " + JSON.stringify(response.query.pages[p]));
                        if(response.query.pages[p].revisions) {
                          var revs = response.query.pages[p].revisions;
                          for(var r in revs) {
                            // console.log("r: " + JSON.stringify(revs[r].slots.main.content));
                            if(revs[r].slots.main.content) {
                              var c = revs[r].slots.main.content;
                              var found = c.match(RegExp('{{\\s*[cC]ategory[ _]+redirect\\s*\\|(Category:)?(?<p1>[^}]*)}}'));
                              // console.log("found: " + JSON.stringify(found));
                              if(found && found.groups) {
                                EightSisters.redirCatFrom = extLink;
                                var found1 = found.groups.p1.match(RegExp('1=(?<p1>[^|}]*)'));
                                if(found && found.groups)
                                  EightSisters.redirCatTo = found1.groups.p1;
                                else {
                                  var pos = found.groups.p1.indexOf('|');
                                  if(pos != -1)
                                    EightSisters.redirCatTo = found.groups.p1.substring(0, pos);
                                  else
                                    EightSisters.redirCatTo = found.groups.p1;
                                }
                              }
                            }
                          }
                        }
                      }
                    }
                    EightSisters.analyseText(true);
                });
            });
        });
    }
  },

  analyseText : function(initial) {
    var $textbox = $('#wpTextbox1');
    var text = $textbox.textSelection('getContents');
    EightSisters.addWeblinks = -1;
    var weblinkPos = -1;
    var canInsert = true;
    if(mw.config.get('wgNamespaceNumber') != 14) {
      var sections = text.match(/\n==.*\n/g);
      if(sections) {
        for(var i = sections.length - 1; i >= 0; -- i) {
          if(sections[i].indexOf('Weblink') != -1) {
            weblinkPos = text.lastIndexOf(sections[i]) + sections[i].length;
            break;
          }
        }
        if(weblinkPos == -1)
          for(var i = sections.length - 1; i >= 0; -- i) {
            if(sections[i].indexOf('Siehe auch') != -1) {
              weblinkPos = text.lastIndexOf(sections[i]) + sections[i].length;
              break;
            }
          }
        if(weblinkPos == -1)
          for(var i = sections.length - 1; i >= 0; -- i) {
            if(sections[i].indexOf('Verweise') != -1) {
              weblinkPos = text.lastIndexOf(sections[i]) + sections[i].length;
              break;
            }
          }
      }

      if(weblinkPos == -1) {
        weblinkPos = text.lastIndexOf('<references');
        if(weblinkPos != -1) {
          weblinkPos = text.substring(0, weblinkPos).lastIndexOf('\n==');
          EightSisters.addWeblinks = weblinkPos;
        }

        if(weblinkPos == -1) {
          var minWeblinkPos = 0;
          if(sections)
            minWeblinkPos = text.indexOf(sections[sections.length - 1]);
          var pos = text.indexOf('{{Normdaten', minWeblinkPos); // }}
          if(pos != -1)
            weblinkPos = pos;
          if((pos = text.indexOf('{{Navi', minWeblinkPos)) != -1 && (weblinkPos == -1 || pos < weblinkPos)) // }}
            weblinkPos = pos;
          if((pos = text.indexOf('[[Kategorie', minWeblinkPos)) != -1 && (weblinkPos == -1 || pos < weblinkPos))
            weblinkPos = pos;
          if((pos = text.indexOf('{{DEFAULTSORT', minWeblinkPos)) != -1 && (weblinkPos == -1 || pos < weblinkPos)) // }}
            weblinkPos = pos;
          if((pos = text.indexOf('{{SORTIERUNG', minWeblinkPos)) != -1 && (weblinkPos == -1 || pos < weblinkPos)) // }}
            weblinkPos = pos;
          if((pos = text.indexOf('{{Hinweis ', minWeblinkPos)) != -1 && (weblinkPos == -1 || pos < weblinkPos)) // }}
            weblinkPos = pos;
          if((pos = text.indexOf('{{Hinweis|', minWeblinkPos)) != -1 && (weblinkPos == -1 || pos < weblinkPos)) // }}
            weblinkPos = pos;
          if(weblinkPos != -1)
            EightSisters.addWeblinks = weblinkPos;
        }
      }
    }
    else {
      if((pos = text.indexOf('[[Kategorie')) != -1) {
        weblinkPos = pos;
        while(text.substring(weblinkPos - 2, weblinkPos) == '\n\n')
          -- weblinkPos;
      }
      else if((pos = text.lastIndexOf(/*{{*/'}}')) != -1) {
        weblinkPos = pos + 2;
        if(text.substring(weblinkPos, weblinkPos + 1) == '\n')
          ++ weblinkPos;
      }
    }

    for(var key in Object.keys(EightSisters.sisterData)) {
      var tmplPos;
      for(var from = 0;;) {
        tmplPos = text.substring(from).search(RegExp("{{\\s*[" + EightSisters.sisterData[key].tmpl.substring(0, 1) + EightSisters.sisterData[key].tmpl.substring(0, 1).toLowerCase() + "]" + EightSisters.sisterData[key].tmpl.substring(1).replaceAll(' ', '[ _]+') + /*{*/'\\s*[\\|}]'));
        if(tmplPos == -1)
          break;
        if(EightSisters.inRefOrComment(text, tmplPos)) {
          from += tmplPos + 2;
        }
        else {
          tmplPos += from;
          break;
        }
      }
      EightSisters.sisterData[key].foundAt = tmplPos;
      if(tmplPos != -1) {
        if(mw.config.get('wgNamespaceNumber') != 14) {
          var sectionPos = text.substring(0, tmplPos).lastIndexOf('==\n');
          if(weblinkPos == -1)
            weblinkPos = sectionPos;
          else if(weblinkPos != sectionPos + 3) {
            console.log("Mismatch position of " + EightSisters.sisterData[key].tmpl + " (" + weblinkPos + ") and position of section Weblinks (" + (sectionPos + 3) + ")");
            // canInsert = false;
          }
        }
        EightSisters.sisterData[key].tmplpos = tmplPos;
        EightSisters.sisterData[key].endpos = text.indexOf('\n', tmplPos) + 1;
        if(key == 1) {
          var tmpl = text.substring(EightSisters.sisterData[key].tmplpos, EightSisters.sisterData[key].endpos);
          var found = tmpl.match(RegExp('{{\\s*[cC]ommonscat\\s*\\|(?<p1>[^}|]*)[|}]'));
          if(found && found.groups && ('Category:' + found.groups.p1) == EightSisters.redirCatFrom) {
            EightSisters.sisterData[key].show = true;
          }
          else {
            var found = tmpl.match(RegExp('{{\\s*[cC]ommonscat\\s*}}'));
            if(found && EightSisters.redirCatFrom && EightSisters.redirCatTo)
              EightSisters.sisterData[key].show = true;
          }
        }
      }
      else {
        EightSisters.sisterData[key].tmplpos = -1;
        EightSisters.sisterData[key].endpos = -1;
        if(initial == true && EightSisters.sisterData[key].commonsData)
          EightSisters.sisterData[key].show = true;
      }
    }

    if(mw.config.get('wgNamespaceNumber') == 14) {
      for(key = 9; key < Object.keys(EightSisters.sisterData).length; ++ key) {
        if(EightSisters.sisterData[key].foundAt != -1) {
          if(EightSisters.sisterData[EightSisters.sisterData[key].add].commonsData == null) {
            EightSisters.sisterData[key].foundAt = -1;
            continue;
          }
          EightSisters.sisterData[key].show = false;
          var endPos = text.indexOf(/*{{*/'}}', EightSisters.sisterData[key].foundAt + 2);
          if(endPos !== -1) {
            var found = false;
            var tmplStart = endPos;
            var tmplEnd = endPos;
            var params = text.substring(EightSisters.sisterData[key].foundAt + 2, endPos).split('|');
            var pos = EightSisters.sisterData[key].foundAt + 2 + params[0].length;
            var nIdx = 0; // index of unnamed parameters
            for(var fndPIdx = 1; fndPIdx < params.length; ++ fndPIdx) {
              var matches;
              if((matches = params[fndPIdx].match(RegExp('^\\s*' + EightSisters.sisterData[key].param + '\\s*=\\s*(.*)$', 's'))) != null) {
                // if matches[1] == null, just Commons=
                if(EightSisters.sisterData[key].data == null) {
                  if(matches[1] != null && matches[1].trim() == 'nein') {
                    found = true;
                    tmplStart = pos;
                    tmplEnd = pos + params[fndPIdx].length + 1;
                    break;
                  }
                }
                else {
                  if(matches[1] == null || matches[1] == '') {
                    tmplStart = pos;
                    tmplEnd = pos + params[fndPIdx].length + 1;
                    if(params[fndPIdx].endsWith('\n'))
                      -- tmplEnd;
                  }
                  else {
                    found = true;
                    break;
                  }
                }
              }
              if(typeof(params[fndPIdx]) == 'number') {
                if(params[fndPIdx].indexOf('=') == -1) {
                  ++ nIdx;
                  if(nIdx == EightSisters.sisterData[key].param) {
                    if(params[fndPIdx].trim() == '') {
                      tmplStart = pos;
                      tmplEnd = pos + params[fndPIdx].length + 1;
                      if(params[fndPIdx].endsWith('\n'))
                        -- tmplEnd;
                    }
                    else {
                      found = true;
                      break;
                    }
                  }
                }
              }
              pos += params[fndPIdx].length + 1; // +1 for the '|'
              /* DEBUG* */ if(fndPIdx == params.length - 1 && pos != endPos) console.log('*** pos ' + pos + ' is not equal to expected endpos ' + endpos);
            }

            if(EightSisters.sisterData[key].data == null) {
              if(found == true) {
                EightSisters.sisterData[key].tmplpos = tmplStart;
                EightSisters.sisterData[key].tmplend = tmplEnd;
                EightSisters.sisterData[key].foundAt = -1;
                EightSisters.sisterData[key].show = true;
              }
            }
            else if(found == false) {
              EightSisters.sisterData[key].tmplpos = tmplStart;
              EightSisters.sisterData[key].tmplend = tmplEnd;
              EightSisters.sisterData[key].foundAt = -1;
              EightSisters.sisterData[key].show = true;
            }
            EightSisters.sisterData[EightSisters.sisterData[key].add].show = false;
          }
          else
            EightSisters.sisterData[key].show = false;
        }
        else
          EightSisters.sisterData[key].show = false;
      }
    }
    var haveAny = false;
    for(var key in Object.keys(EightSisters.sisterData)) {
      if(EightSisters.sisterData[key].show == true) {
        haveAny = true;
      }
    }

    if(weblinkPos == -1) {
      console.log("position of section Weblinks not found");
      canInsert = false;
    }
    for(var key in Object.keys(EightSisters.sisterData)) {
      if(EightSisters.sisterData[key].endpos == -1)
        EightSisters.sisterData[key].endpos = weblinkPos;
    }

    var displKey;
    if(canInsert == true && haveAny == true && initial == true) {
      var innerHtml = '<div id="chSisters" class="oo-ui-layout oo-ui-labelElement oo-ui-fieldLayout oo-ui-fieldLayout-align-top editOptions" style="border-radius: 0.25em 0.25em 0.25em 0.25em; margin-bottom:0.5em"><div class="oo-ui-layout oo-ui-horizontalLayout">';
      var section = '';
      if(mw.config.get('wgNamespaceNumber') != 14)
        section = ' im Abschnitt Weblinks';

      for(var key in Object.keys(EightSisters.sisterData)) {
        if(EightSisters.sisterData[key].show) {
          var addLabel = '';
          if(key == 0 && EightSisters.sisterData[1].tmplpos != -1) {
            addLabel = ' <span style="font-weight: bold">Achtung!</span> {{Commonscat|…}} ist schon vorhanden';
          }
          else if(key == 1 && EightSisters.sisterData[0].tmplpos != -1) {
            addLabel = ' <span style="font-weight: bold">Achtung!</span> {{Commons|…}} ist schon vorhanden';
          }

          if(key >= 9) {
            if(key > 9 && EightSisters.sisterData[key].tmpl == EightSisters.sisterData[key - 1].tmpl && EightSisters.sisterData[key - 1].show == false)
              addLabel = ' <span style="font-weight: bold">Achtung!</span> {{' + EightSisters.sisterData[key - 1].param  + '|…}} ist schon vorhanden';
            if(key + 1 < Object.keys(EightSisters.sisterData) && EightSisters.sisterData[key].tmpl == EightSisters.sisterData[key + 1].tmpl && EightSisters.sisterData[key + 1].show == false)
              addLabel = ' <span style="font-weight: bold">Achtung!</span> {{' + EightSisters.sisterData[key + 1].param  + '|…}} ist schon vorhanden';
          }

          var template = EightSisters.makeTemplate(key, true);

          var doAdd = '';
          var doAdd2 = '+ ';
          if(key >= 9)
            doAdd = 'hinzufügen';
          else if(key == 1 && EightSisters.sisterData[key].tmplpos != -1) {
            doAdd = 'korrigieren';
            doAdd2 = '± ';
            addLabel += ' (Weiterleitung auflösen)';
          }
          else
            doAdd = 'ergänzen';
          innerHtml += '<div id="editpage-addEightSisters' + key + '" class="oo-ui-layout oo-ui-labelElement oo-ui-fieldLayout oo-ui-fieldLayout-align-inline">' +
              '<div class="oo-ui-fieldLayout-body" id="bodyEightSisters' + key + '" >' +
                '<a class="editMenus-button" title="EightSisters' + key + '" id="buttonEightSisters' + key + '"style="text-decoration: none; white-space: nowrap;">' +
                  '<img data-id="' + key + '" title="Vorlage ' + EightSisters.sisterData[key].tmpl + section + ' ' + doAdd + '" alt="' + EightSisters.sisterData[key].tmpl + '" src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f6/OOjs_UI_icon_check-constructive.svg/18px-OOjs_UI_icon_check-constructive.svg.png" width="18" height="18" style="cursor:pointer">' +
                '</a>' +
                '<span class="oo-ui-fieldLayout-header" id="headerEightSisters' + key + '">' +
                  '<label id="labelEightSisters' + key + '" title="Vorlage:' + EightSisters.sisterData[key].tmpl + section + ' ' + doAdd + '" for="AddEightSisters' + key + '" class="oo-ui-labelElement-label oo-ui-optionWidget" disabled="true">' + doAdd2 + template + addLabel +
                  '</label>' +
                '</span>' +
              '</div>' +
            '</div>';
        }
      }
      innerHtml += '</div></div>';
      var e = document.getElementById('wpSummaryLabel').parentElement;
      e.insertAdjacentHTML('beforebegin', innerHtml);

      for(var key in Object.keys(EightSisters.sisterData)) {
        if(EightSisters.sisterData[key].show) {
          document.getElementById('buttonEightSisters' + key).addEventListener('click', EightSisters.addTemplate);
        }
      }
    }
  },

  inRefOrComment : function(text, tmplPos) {
    var refStart = text.substring(0, tmplPos).lastIndexOf('<ref');
    if(refStart != -1) {
      if(text.substring(refStart, tmplPos).match(/<ref[^>]*\/>/) == false &&
         text.substring(refStart, tmplPos).indexOf('</ref') == -1)
        return true;
    }
    var commentStart = text.substring(0, tmplPos).lastIndexOf('<!--');
    if(commentStart != -1) {
      if(text.substring(commentStart, tmplPos).indexOf('-->') == -1)
        return true;
    }
    return false;
  },

  makeTemplate : function(key, withLink) {
    var template;
    if(withLink == true)
      template = '{{<a href="' + EightSisters.sisterData[key].pagelnk + EightSisters.sisterData[key >= 9 ? EightSisters.sisterData[key].add : key].commonsData + '">' + EightSisters.sisterData[key].tmpl + '</a>'; // }}
    else
      template = '{{' + EightSisters.sisterData[key].tmpl; // }}
    if(key >= 9) {
      if(typeof(EightSisters.sisterData[key].param) == 'number')
        template += '|…|' + EightSisters.sisterData[EightSisters.sisterData[key].add].commonsData;
      else if(EightSisters.sisterData[key].data == 'pv')
        template += '|…|' + EightSisters.sisterData[key].param + '=' + EightSisters.sisterData[EightSisters.sisterData[key].add].commonsData;
      else if(EightSisters.sisterData[key].data == null)
        template += '|…<s>' + $('#wpTextbox1').textSelection('getContents').substring(EightSisters.sisterData[key].tmplpos, EightSisters.sisterData[key].tmplend) + '</s>';
      else if(EightSisters.sisterData[key].data instanceof RegExp)
        template += '|…|' + EightSisters.sisterData[key].param + '=' + EightSisters.sisterData[EightSisters.sisterData[key].add].commonsData.replace(EightSisters.sisterData[key].data, '');
      else
        template += '|…|?';
    }
    else {
      var title = mw.config.get('wgTitle');
      if(title != EightSisters.sisterData[key].commonsData) {
        if(key == 1 && EightSisters.sisterData[key].tmplpos != -1) {
          template += '|' + EightSisters.redirCatTo;
        }
        else {
          template += '|' + EightSisters.sisterData[key].commonsData + '|';
          if(mw.config.get('wgNamespaceNumber') != 14) {
            if(title.endsWith(')')) {
              var brPos = title.lastIndexOf(' (');
              if(brPos != -1)
                template += title.substring(0, brPos);
              else
                template += title;
            }
            else
              template += title;
          }
          else {
            template += '{{SEITENNAME}}'
          }
        }
      }
    }
    return template + /*{{*/'}}';
  },

  addTemplate : function(event) {
    EightSisters.analyseText(false);
    var img = event.target;
    if(!img.attributes['data-id'])
      img = img.firstChild;
    var targetKey = img.attributes['data-id'].value;
    var insertFrom = 0;
    var insertTo = 0;
    var $textbox = $('#wpTextbox1');
    var text = $textbox.textSelection('getContents');
    var template;
    if(EightSisters.sisterData[targetKey].foundAt != -1) {
      if(targetKey != 1)
        return;
      var tmpl = text.substring(EightSisters.sisterData[targetKey].tmplpos, EightSisters.sisterData[targetKey].endpos);
      var found = tmpl.match(RegExp('{{\\s*[cC]ommonscat\\s*\\|(?<p1>[^}|]*)[|}]'));
      if(!found || !found.groups || ('Category:' + found.groups.p1) != EightSisters.redirCatFrom) {
        var found = tmpl.match(RegExp('{{\\s*[cC]ommonscat\\s*(?<p1>}})'));
        if(!found || !EightSisters.redirCatFrom || !EightSisters.redirCatTo)
          return;
        insertFrom = text.indexOf(found.groups.p1, EightSisters.sisterData[targetKey].tmplpos);
        insertTo = insertFrom;
        template = '|' + EightSisters.redirCatTo;
      }
      else {
        insertFrom = text.indexOf(found.groups.p1, EightSisters.sisterData[targetKey].tmplpos);
        insertTo = insertFrom + found.groups.p1.length;
        template = EightSisters.redirCatTo;
      }
    }
    else {
      if(targetKey >= 9) {
        insertFrom = EightSisters.sisterData[targetKey].tmplpos;
        insertTo = EightSisters.sisterData[targetKey].tmplend;
      }
      else {
        if(EightSisters.addWeblinks == -1) {
          for(var key = 0; key <= targetKey; ++ key) {
            if(insertFrom < EightSisters.sisterData[targetKey].endpos)
              insertFrom = EightSisters.sisterData[targetKey].endpos;
          }
        }
        else
          insertFrom = EightSisters.addWeblinks;
        insertTo = insertFrom;
      }
      if(targetKey >= 9) {
        if(typeof(EightSisters.sisterData[targetKey].param) == 'number')
          template = '|' + EightSisters.sisterData[EightSisters.sisterData[targetKey].add].commonsData;
        else if(EightSisters.sisterData[targetKey].data == 'pv')
          template = '|' + EightSisters.sisterData[targetKey].param + '=' + EightSisters.sisterData[EightSisters.sisterData[targetKey].add].commonsData;
        else if(EightSisters.sisterData[targetKey].data == null)
          template = '';
        else if(EightSisters.sisterData[targetKey].data instanceof RegExp)
          template = '|' + EightSisters.sisterData[targetKey].param + '=' + EightSisters.sisterData[EightSisters.sisterData[targetKey].add].commonsData.replace(EightSisters.sisterData[targetKey].data, '');
        else
          return;
      }
      else
        template = EightSisters.makeTemplate(targetKey, false) + '\n';
    }
    var fixPos = 0;
    var addComment = '';
    if(EightSisters.sisterData[targetKey].foundAt == -1) {
      if(mw.config.get('wgNamespaceNumber') != 14 && EightSisters.sisterData[targetKey].foundAt == -1) {
        if(EightSisters.addWeblinks != -1) {
          var newSection;
          if(text.substring(insertFrom - 2, insertFrom) == '\n\n')
            newSection = '== Weblinks ==\n';
          else
            newSection = '\n== Weblinks ==\n';
          for(var key in Object.keys(EightSisters.sisterData)) {
            if(EightSisters.sisterData[key].tmplpos != -1) {
              newSection += text.substring(EightSisters.sisterData[key].tmplpos, EightSisters.sisterData[key].endpos);
              text = text.substring(0, EightSisters.sisterData[key].tmplpos) + text.substring(EightSisters.sisterData[key].endpos);
              $textbox.textSelection('setSelection', { start: EightSisters.sisterData[key].tmplpos, end: EightSisters.sisterData[key].endpos });
              $textbox.textSelection('replaceSelection', '');
              if(EightSisters.sisterData[key].tmplpos < insertFrom)
                insertFrom -= EightSisters.sisterData[key].endpos - EightSisters.sisterData[key].tmplpos;
            }
            else if(key == targetKey)
              newSection += template;
          }
          if(text.substring(insertFrom, insertFrom + 1) != '\n')
            newSection += '\n';
          template = newSection;
        }
        else {
          if(text.substring(insertFrom, insertFrom + 1) == '\n' && text.substring(insertFrom + 1, insertFrom + 1) != '=')
            template = template.substring(0, template.length - 1);
        }
      }
      else {
        if(targetKey < 9) {
          if(text == '' || text.substring(insertFrom, insertFrom + 1) != '\n')
            template += '\n';
        }
      }

      if(targetKey >= 9 && EightSisters.sisterData[EightSisters.sisterData[targetKey].add].tmplpos != null) {
        var from = EightSisters.sisterData[EightSisters.sisterData[targetKey].add].tmplpos;
        var to = text.indexOf('}}', from);
        if(to != -1)  {
          to += 2;
          while(to < text.length && (text.substring(to, to + 1) == ' ' || text.substring(to, to + 1) == '\n'))
            ++ to;
        }

        $textbox.textSelection('setSelection', { start: from - 1, end: to });
        $textbox.textSelection('replaceSelection', text.substring(from - 1, from));
        addComment = ' (' + EightSisters.sisterData[targetKey].param + ' verschoben)';

        if(insertFrom > to) {
          insertFrom -= to - from;
          insertTo -= to - from;
        }
      }
    }

    $textbox.textSelection('setSelection', { start: insertFrom, end: insertTo });
    $textbox.textSelection('replaceSelection', template);
    $textbox.textSelection('setSelection', { start: insertFrom, end: insertFrom + template.length });
    $textbox.textSelection('scrollToCaretPosition');

    e = document.getElementById('wpSummary');
    if(targetKey >= 9) {
      var addText = EightSisters.sisterData[targetKey].tmpl + ' mit [[Benutzer:Wurgl/8Schwestern|Helferlein]] ergänzt' + addComment;
      if(e.value == '')
        e.value = addText;
      else {
        if(e.value.indexOf(addText) == -1)
          e.value += ', ' + addText;
      }
    }
    else {
      if(EightSisters.sisterData[targetKey].foundAt != -1)
        e.value = EightSisters.sisterData[targetKey].tmpl + ' mit [[Benutzer:Wurgl/8Schwestern|Helferlein]] korrigiert';
      else if(e.value == '')
        e.value = EightSisters.sisterData[targetKey].tmpl + ' mit [[Benutzer:Wurgl/8Schwestern|Helferlein]] hinzugefügt';
      else {
        var parts = e.value.split(',');
        for(var i = 0; i < parts.length; ++ i) {
          if(parts[i].trim() == EightSisters.sisterData[targetKey].tmpl)
            return;
          var pos = parts[i].indexOf(' mit [[Benutzer:Wurgl/8Schwestern|Helferlein]] hinzugefügt');
          if(pos != -1) {
            var posU = parts[i].indexOf(' und ');
            if(posU != -1) {
              parts[i] = parts[i].substring(0, posU) + ', ' + parts[i].substring(posU + 5);
              pos -= 3;
            }
            if(parts[i].substring(0, pos) == EightSisters.sisterData[targetKey].tmpl)
              return;
            parts[i] = parts[i].substring(0, pos) + ' und ' + EightSisters.sisterData[targetKey].tmpl + parts[i].substring(pos);
            e.value = parts.join(', ');
            return;
          }
        }
        e.value += ', ' + EightSisters.sisterData[targetKey].tmpl + ' mit [[Benutzer:Wurgl/8Schwestern|Helferlein]] hinzugefügt';
      }
    }
    if(EightSisters.sisterData[targetKey].hint != null)
      mw.notify('EightSisters: Parameter "' + EightSisters.sisterData[targetKey].hint + '" eventuell ergänzen', {tag: 'parameter-hint', type: 'warn', autoHideSeconds: 30});
  },

  queryWikidataId : function(api, callback, queryParams) {
    api.get($.extend({}, queryParams, { 'continue': '' })).then(function(data) {
      callback(data);
    }).fail(function(code, data) {
      var extraText;
      if(code === 'http' && data) {
        extraText = (data.xhr && data.xhr.status ? '[' + data.xhr.status + ']' : '') +
                    (data.textStatus ? '' + data.textStatus + (data.exception ? ': ' : '') : '') +
                    (data.exception ? '' + data.exception : '');
      }
      else {
        extraText = code + (data && data.error && data.error.info ? ': ' + data.error.info : '');
      }
      mw.notify('EightSisters: Fehler beim Lesen der Wikidata-ID ' + ' (' + extraText + ')', {tag: 'EightSisters-error'});
    });
  }
};
$(EightSisters.execute);
// </nowiki>