MediaWiki:Gadget-Vorlagenmeister/core.js

aus Wikipedia, der freien Enzyklopädie
< MediaWiki:Gadget-Vorlagenmeister
Dies ist die aktuelle Version dieser Seite, zuletzt bearbeitet am 5. November 2018 um 20:51 Uhr durch imported>NordNordWest(512619) (https://de.wikipedia.org/w/index.php?title=Wikipedia:Technik/Skin/MediaWiki/Änderungen&curid=10453259&diff=182493404&oldid=182378813).
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)

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
  • Internet Explorer/Edge: Strg+F5 drücken oder Strg drücken und gleichzeitig Aktualisieren anklicken
  • Opera: Strg+F5
/**
* Project:  Vorlagen-Meister
* Version:  0.590+ *** Date: 2018-08-25 or later (see VERSION)
* Copyright (C) 2007-2013 [[de:Benutzer:Revvar]]
* Released under the GPL license version 2
* http://www.gnu.org/copyleft/gpl.html
* Download from
*    https://de.wikipedia.org/wiki/MediaWiki:Gadget-Vorlagenmeister.js
*    https://de.wikipedia.org/wiki/MediaWiki:Gadget-Vorlagenmeister/core.js
*    https://de.wikipedia.org/wiki/MediaWiki:Gadget-Vorlagenmeister.css
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE.
* See the GNU General Public License for more details.
*/

/* global window:false,
          ActiveXObject:false, DOMParser:false, XSLTProcessor:false    */
/* jshint forin:false,
          bitwise:true, curly:true, eqeqeq:true, latedef:true,
          laxbreak:true,
          nocomma:true, strict:true, undef:true, unused:true           */



( function ( mw, $ ) {
   "use strict";
   var VERSION   = "0.594 * BETA * 2018-10-24",
       document  = window.document,
       LOCALS    = { me: "Vorlagenmeister" },
       MW_LIB    = "vorlagenmeister",
       SIGNATURE = "ext.gadget." + LOCALS.me + "/core",
       rLoader   = { },
       BUTTONICON, I18N, IS_IE, OPTIONS, PAR_START;
   if ( ! mw.loader.getState( SIGNATURE ) ) {
      rLoader[ SIGNATURE ] = "loading";
      mw.loader.state( rLoader );
   }



   //## File: tm_locals_de.js ####################################
   /*
   * Lokalisierung "Deutsch" des Vorlagen-Meister
   * Copyright (C) 2007-2013 [[de:Benutzer:Revvar]] <revvar@gmx.de>
   * Released under the GPL license version 2
   * http://www.gnu.org/copyleft/gpl.html
   *
   * This program is free software; you can redistribute it and/or modify
   * it under the terms of the GNU General Public License version 2 as
   * published by the Free Software Foundation.
   *
   * This program is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty
   * of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE.
   * See the GNU General Public License for more details.
   */



   I18N = { langs:  { }  };
   I18N.langs.de = {
      ButtonText: "VM",
      Okay:       "Okay",
      Submit:     "Übernehmen",
      Cancel:     "Abbrechen",
      createXML:  "XML-Beschreibung generieren ...",
      progress:   "wird geladen",
      seekTD:     "Suche TemplateData ...",
      seekXML:    "Suche XML ...",
      showTdoc:   "Doku",
      sys_load_error: "Konnte Vorlageninfo zu \"$1\" nicht laden.",
      sys_no_usage_section: "Keine XML-Beschreibung in der Vorlage \"$1\" gefunden.",
      sys_no_such_template: "Keine Vorlage mit dem Namen \"$1\" gefunden.",
      sys_no_help: "(Leider keine Hilfe vorhanden.)",
      sys_invalid_condition: "XML-Beschreibung enthält ein ungültiges <Condition>-Element: \"$1\".",
      sys_conflict_null_AutoValue: "XML-Beschreibung enthält Konflikt zwischen null=false und <AutoValue>",
      sys_invalid_value: "Ungültiger Wert",
      sys_value_pipe_active: "Ungültiger Wert: aktive | Pipe",
      sys_enter_value: "Bitte gib einen Wert ein!",
      sys_enter_valid_value: "Bitte gib einen gültigen Wert ein!",
      sys_please_correct_errors: "Es sind Fehler aufgetreten. Bitte korrigiere die rot markierten Felder.",
      sys_question_repeat_http_request: "Willst du die Anfrage wiederholen=[Okay] oder [Abbrechen] ?",
      sys_unknown_parameter: "Der Vorlagentext enthält folgende unbekannte Parameter: \"$1\". Gründe: Schreibfehler, z.B. Groß- bzw. Kleinschreibung wurde nicht beachtet, oder die Beschreibung der Vorlage ist unvollständig.",
      w2t_plugin_selection: "Bitte wähle eine Vorlage, welche mit dem ausgewählten Text ausgefüllt werden soll:"
   };
   I18N.langs["de-formal"] = {
      ButtonText: "VM",
      Okay:       "Okay",
      Submit:     "Übernehmen",
      Cancel:     "Abbrechen",
      createXML:  "XML-Beschreibung generieren ...",
      progress:   "wird geladen",
      seekTD:     "Suche TemplateData ...",
      seekXML:    "Suche XML ...",
      showTdoc:   "Doku",
      sys_load_error: "Konnte Vorlageninfo zu \"$1\" nicht laden.",
      sys_no_usage_section: "Keine XML-Beschreibung in der Vorlage \"$1\" gefunden.",
      sys_no_such_template: "Keine Vorlage mit dem Namen \"$1\" gefunden.",
      sys_no_help: "(Leider keine Hilfe vorhanden.)",
      sys_invalid_condition: "XML-Beschreibung enthält ein ungültiges <Condition>-Element: \"$1\".",
      sys_conflict_null_AutoValue: "XML-Beschreibung enthält Konflikt zwischen null=false und <AutoValue>",
      sys_invalid_value: "Ungültiger Wert",
      sys_value_pipe_active: "Ungültiger Wert: aktive | Pipe",
      sys_enter_value: "Bitte geben Sie einen Wert ein!",
      sys_enter_valid_value: "Bitte geben Sie einen gültigen Wert ein!",
      sys_please_correct_errors: "Es sind Fehler aufgetreten. Bitte korrigieren Sie die rot markierten Felder.",
      sys_question_repeat_http_request: "Wollen Sie die Anfrage wiederholen=[Ok] oder [Abbrechen] ?",
      sys_unknown_parameter: "Der Vorlagentext enthält folgende unbekannte Parameter: \"$1\". Gründe: Schreibfehler, z.B. Groß- bzw. Kleinschreibung wurde nicht beachtet, oder die Beschreibung der Vorlage ist unvollständig.",
      w2t_plugin_selection: "Bitte wählen Sie eine Vorlage, welche mit dem ausgewählten Text ausgefüllt werden soll:"
   };
   I18N.langs.en = {
      ButtonText: "TM",
      Okay:       "Okay",
      Submit:     "Apply",
      Cancel:     "Abort",
      createXML:  "Create XML description ...",
      progress:   "loading",
      seekTD:     "Looking for TemplateData ...",
      seekXML:    "Looking for XML ...",
      showTdoc:   "doc",
      sys_load_error: "Unable to load \"$1\" template info.",
      sys_no_usage_section: "No XML description found in \"$1\" template.",
      sys_no_such_template: "For \"$1\" no template was found.",
      sys_no_help: "(Imagine, there is no help.)",
      sys_invalid_condition: "Invalid <Condition> element in XML description: \"$1\".",
      sys_conflict_null_AutoValue: "Conflict in XML description; both null=false and <AutoValue>",
      sys_invalid_value: "Invalid value",
      sys_value_pipe_active: "Invalid value: active | pipe",
      sys_enter_value: "Please enter a value.",
      sys_enter_valid_value: "Please enter an appopriate value.",
      sys_please_correct_errors: "Errors occurred. Please correct fields marked in red colour.",
      sys_question_repeat_http_request: "Do you want to repeat=[Okay] the request or [Abort] ?",
      sys_unknown_parameter: "The template source contains the following unknown parameters: \"$1\". Reasons: typo, e.g. upcasing/downcasing, or incomplete XML template description.",
      w2t_plugin_selection: "Please choose a template to be filled with the selected text:"
   };
   I18N.langs.hu = {
      ButtonText: "SM",
      Okay:       "OK",
      Submit:     "Elküld",
      Cancel:     "Mégse",
      createXML:  "XML-leírás generálása…",
      progress:   "Betöltés folyamatban",
      seekTD:     "TemplateData-leírás keresése…",
      seekXML:    "XML-leírás keresése…",
      showTdoc:   "doc",
      sys_load_error:  "A(z) \"$1\" sablont nem lehet betölteni.",
      sys_no_usage_section:  "A(z) \"$1\" sablonhoz nem található XML-leírás.",
      sys_no_such_template:  "Nem található \"$1\" nevű sablon.",
      sys_no_help:  "(Nincs rendelkezésre álló segítség.)",
      sys_invalid_condition:  "Az XML-leírás egy érvénytelen feltétel-paramétert tartalmaz: \"$1\".",
      sys_conflict_null_AutoValue: "Conflict in XML description; both null=false and <AutoValue>",
      sys_invalid_value:  "Nem megfelelő érték",
      sys_enter_value:  "Adj meg egy értéket!",
      sys_value_pipe_active: "Invalid value: active | pipe",
      sys_enter_valid_value:  "Adj meg egy megfelelő értéket!",
      sys_please_correct_errors:  "Hiba történt. Javítsd ki a pirossal jelzett mezőket.",
      sys_question_repeat_http_request:  "Szeretnéd a kérést megismételni=[OK] vagy [félbeszakítani] ?",
      sys_unknown_parameter:  "A sablonszöveg a következő ismeretlen paramétert tartalmazza: \"$1\". Okok: elütés, pl. kis- és nagybetűk nem lettek figyelembe véve, vagy a sablon leírása hiányos.",
      w2t_plugin_selection:  "Válassz egy sablont, amellyel a kijelölt szöveget szeretnéd kitölteni:"
   };



   I18N.projects = {
     dewiki: {
        summary_generated: "Automatisch erzeugt"
                           + " mit dem [[WP:HW/VM|Vorlagen-Meister]]"
     },
     huwiki: {
        summary_generated: "Automatikusan létrehozva"
                           + " a [[Wikipédia:Sablonmester|Sablonmester]]"
                           + " segítségével"
     }
   };



   I18N.translate  =  {   // fallback languages
      // 2012-12-19 PerfektesChaos@de.wikipedia
      "als" :  "de",
      "bar" :  "de",
      "dsb" :  "de",
      "frr" :  "de",
      "gsw" :  "de",
      "hsb" :  "de",
      "ksh" :  "de",
      "lb" :   "de",
      "nds" :  "de",
      "pdc" :  "de",
      "pdt" :  "de",
      "pfl" :  "de",
      "sli" :  "de",
      "stq" :  "de",
      "vmf" :  "de"
   };   // I18N.translate



   function log_message( about ) {
      var s = LOCALS.me + " " + VERSION + ":\r\n" + about;
      window.alert( s );
      if ( typeof window.console  ===  "object"
           &&     window.console ) {
         if ( typeof window.console.error  ===  "function" ) {
            window.console.error( s );
         } else if ( typeof window.console.log  ===  "function" ) {
            window.console.log( s );
         }
      }
   }   // log_message()



   I18N.facilitate  =  function ( available, accept, achieve ) {
      // Localize in language or sub-language
      // Precondition:
      //    available  -- translation object
      //    accept     -- string, language code
      //    achieve    -- string, requested type
      //                          ("string", "object", "function")
      // Postcondition:
      //    Returns translation thing, or not
      // Uses:
      //    >  I18N.translate
      // 2015-01-01 PerfektesChaos@de.wikipedia
      var slang = accept.toLowerCase(),
          i, r;
      if ( typeof available[ slang ]  ===  achieve ) {
         r = available[ slang ];
      } else {
         i = slang.indexOf( "-", 2 );
         if ( i > 0 ) {
            slang = slang.substr( 0, i );
            if ( typeof available[ slang ]  ===  achieve ) {
               r = available[ slang ];
            }
         }
      }
      if ( ! r ) {
         if ( typeof I18N.translate[ slang ]  ===  achieve ) {
            slang = I18N.translate[ slang ];
            if ( typeof available[ slang ]  ===  achieve ) {
               r = available[ slang ];
            }
         }
      }
      return r;
   };   // I18N.facilitate()



   I18N.facility  =  function ( available, achieve ) {
      // Localize in user language, GUI only
      // Precondition:
      //    available  -- translation object
      //    achieve    -- string, requested type
      //                          ("string", "object", "function")
      // Postcondition:
      //    Returns translation thing, at least English, or type achieve
      // Uses:
      //    mw.config.get()
      //    I18N.facilitate()
      // 2015-01-01 PerfektesChaos@de.wikipedia
      var env = mw.config.get( [ "wgUserLanguage",
                                 "wgContentLanguage" ] ),
          r   = I18N.facilitate( available,
                                 env.wgUserLanguage,
                                 achieve );
      if ( ! r ) {
         if ( env.wgContentLanguage !== env.wgUserLanguage ) {
            r = I18N.facilitate( available,
                                 env.wgContentLanguage,
                                 achieve );
         }
         if ( ! r ) {
            r = available.en;
         }
      }
      if ( typeof r  !==  achieve ) {
         switch ( achieve ) {
            case "function" :
               r = false;
               break;
            case "object" :
               r = { };
               break;
            case "string" :
               r = "";
               break;
         }   // switch achieve
      }
      return r;
   };   // I18N.facility()



   I18N.fire  =  function () {
      // Localization
      // Postcondition:
      //    Returns object, adopted to current environment
      // Uses:
      //    this
      //    >  I18N.langs
      //    >  LOCALS.me
      //    >  I18N.projects
      //    mw.config.get()
      //    I18N.facility()
      // 2014-12-30 PerfektesChaos@de.wikipedia
      var env = mw.config.get( [ "wgDBname",
                                 "wgFormattedNamespaces" ] ),
          r   = this.facility( this.langs, "object" );
      r.me       = LOCALS.me;
      r.template = env.wgFormattedNamespaces[ 10 ];
      if ( typeof this.projects[ env.wgDBname ]  ===  "object" ) {
         r.project = this.projects[ env.wgDBname ];
         if ( typeof r.project.summary_generated  ===  "string" ) {
            r.summary_generated = r.project.summary_generated;
         }
      }
      if ( typeof r.summary_generated  !==  "string" ) {
         r.summary_generated = "Automatically generated"
                               + " by Vorlagen-Meister (TemplateMaster)";
      }
      return r;
   };   // I18N.fire()



   function preventDefault(event) {
      // if ( ! IS_IE  ||  IS_IE_9plus ) {
         event.preventDefault();
      // }
   }   // preventDefault()



   function parseXML(text) {
      var dom = null,
          aError, aHtmlText, aLocation, error, parser, sError;
      if ( IS_IE ) {
         try {
            dom = new ActiveXObject( "Microsoft.XMLDOM" );
            dom.async = "false";
            dom.loadXML( text );
         } catch(e) {
            log_message( "parseXML(IE:ActiveXObject) " + e.message );
         }
      }
      if ( ! dom ) {
         try {
            parser = new DOMParser();
            dom = parser.parseFromString( text, "text/xml" );
            error = dom.getElementsByTagName( "parsererror" );
            if ( error[0] ) {
               sError = error[0].firstChild.nodeValue;
               log_message("parseXML() " + sError);
               aError = sError.split("\n");
               if (aError[2]) {
                  aLocation=aError[2].match(/[0-9]+/g);
                  if (aLocation[0]) {
                     aHtmlText = text.split("\n");
                     log_message("error line:"
                                 + aHtmlText[ aLocation[0]-1 ]);
                  }
               } else {
                  log_message("no error position");
               }
            }
         } catch(e) {
            log_message( "parseXML(DOMParser) " + e.message );
         }
      }
      return dom;
   }   // parseXML()



//## File: tm_formular.xsl.js #################################

function get_xsl_dom() {
// 2014-12-27 PerfektesChaos@de.wikipedia
return parseXML(
'<?xml version="1.0" encoding="utf-8" ?>\n'+
'<!--\n'+
'* Copyright (C) 2007-2013 [[de:Benutzer:Revvar]] <revvar@gmx.de>\n'+
'* Released under the GPL license\n'+
'* http://www.gnu.org/copyleft/gpl.html\n'+
'-->\n'+
'<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >\n'+
'   <xsl:output method="html" />\n'+
'   <xsl:param name="locals_submit" />\n'+
'   <xsl:param name="locals_cancel" />\n'+
'   <xsl:param name="locals_createxml" />\n'+
'   <xsl:param name="locals_template" />\n'+
'   <xsl:param name="locals_nohelp" />\n'+
'   <xsl:param name="locals_version" />\n'+
'   <xsl:template match="/TemplateUsage">\n'+
'\n'+
'      <!-- create basic gui -->\n'+
'      <div id="tm_main_frame" class="tm_main_frame" style="overflow:hidden" tm_output="{@output}" tm_max_value_indentation="{@max_value_indentation}">\n'+
'      <div id="tm_header" class="tm_header">\n'+
'            <span class="tm_template"><xsl:choose><xsl:when test="$locals_template"><xsl:value-of select="$locals_template" /></xsl:when><xsl:otherwise>locals_template</xsl:otherwise></xsl:choose>:&#160; </span>\n'+
'            <input type="text" id="tm_template" class="tm_template" size="32" disabled="true" />\n'+
'            <span id="tm_template-doc" class="tm_template-doc"></span>\n'+
'            <span class="tm_version"><xsl:choose><xsl:when test="$locals_version"><xsl:value-of select="$locals_version" /></xsl:when><xsl:otherwise>locals_version</xsl:otherwise></xsl:choose></span>\n'+
'      </div>\n'+
'      <div id="tm_group_selector" class="tm_group_selector">\n'+
'         <xsl:apply-templates mode="group_selector" />\n'+
'      </div>\n'+
'      <div id="tm_form" class="tm_form" style="overflow:auto">\n'+
'      <!-- create form -->\n'+
'      <form style="overflow:auto">\n'+
'      <xsl:for-each select="Group">\n'+
'         <div id="tm_group_{position()}" tm_name="tm_formelem" class="tm_group" tabindex="{4000+position()}">\n'+
'            <xsl:choose>\n'+
'               <xsl:when test="@showempty=\'false\'">\n'+
'                  <xsl:attribute name="tm_showempty">false</xsl:attribute>\n'+
'               </xsl:when>\n'+
'               <xsl:otherwise>\n'+
'                  <xsl:attribute name="tm_showempty">true</xsl:attribute>\n'+
'               </xsl:otherwise>\n'+
'            </xsl:choose>\n'+
'            <xsl:if test="@name">\n'+
'               <h3 class="tm_group_heading"><xsl:value-of select="@name" /></h3>\n'+
'            </xsl:if>\n'+
'            <xsl:for-each select="Parameter">\n'+
'               <div class="tm_formelem"><table class="tm_table">\n'+
'                  <xsl:if test="@length=\'max\'">\n'+
'                     <xsl:attribute name="class">tm_table tm_table_max</xsl:attribute>\n'+
'                  </xsl:if>\n'+
'                  <xsl:choose><xsl:when test="count(Value)=1">\n'+
'                     <input type="checkbox" tm_name="tm_formelem" value="{Value}">\n'+
'                        <xsl:call-template name="SetBasicAttributes" />\n'+
'                     </input>\n'+
'                     <span>'+
'                        <xsl:choose>\n'+
'                           <xsl:when test="@label">\n'+
'                              <xsl:value-of select="@label" />\n'+
'                           </xsl:when>\n'+
'                           <xsl:otherwise>\n'+
'                              <xsl:value-of select="@name" />\n'+
'                           </xsl:otherwise>\n'+
'                        </xsl:choose>\n'+
'                     </span>\n'+
'                  </xsl:when><xsl:otherwise>\n'+
'                     <tr class="tm_tr">\n'+
'                        <xsl:choose>\n'+
'                           <xsl:when test="@deprecated=\'true\'">\n'+
'                              <xsl:attribute name="class">'+
'                                 tm_deprecated'+
'                              </xsl:attribute>\n'+
'                           </xsl:when>\n'+
'                        </xsl:choose>\n'+
'                     <td class="tm_td_label"><span>\n'+
'                        <xsl:choose>\n'+
'                           <xsl:when test="@null=\'false\'">\n'+
'                              <xsl:attribute name="class">tm_param</xsl:attribute>\n'+
'                           </xsl:when>\n'+
'                           <xsl:otherwise>\n'+
'                              <xsl:attribute name="class">tm_opt_param</xsl:attribute>\n'+
'                           </xsl:otherwise>\n'+
'                        </xsl:choose>\n'+
'                        <xsl:choose>\n'+
'                           <xsl:when test="@label">\n'+
'                              <xsl:value-of select="@label" />:\n'+
'                           </xsl:when>\n'+
'                           <xsl:otherwise>\n'+
'                              <xsl:value-of select="@name" />:\n'+
'                           </xsl:otherwise>\n'+
'                        </xsl:choose>\n'+
'                     </span></td><td class="tm_td_content">\n'+
'                     <xsl:choose><xsl:when test="Value">\n'+
'                        <select tm_name="tm_formelem">\n'+
'                           <xsl:call-template name="SetBasicAttributes" />\n'+
'                           <xsl:if test="not (@null=\'false\')">\n'+
'                              <option />\n'+
'                           </xsl:if>\n'+
'                           <xsl:for-each select="Value">\n'+
'                              <option value="{text()}">\n'+
'                                 <xsl:attribute name="id">' + PAR_START + '<xsl:value-of select="@name"/>_<xsl:value-of select="position()"/></xsl:attribute>\n'+
'                                 <xsl:choose><xsl:when test="@label">\n'+
'                                 <xsl:value-of select="@label" />\n'+
'                                 </xsl:when>\n'+
'                                 <xsl:otherwise>\n'+
'                                    <xsl:value-of select="text()" />\n'+
'                                 </xsl:otherwise></xsl:choose>\n'+
'                                 <xsl:if test="position()=0">\n'+
'                                    <xsl:attribute name="selected" />\n'+
'                                 </xsl:if>\n'+
'                              </option>\n'+
'                           </xsl:for-each>\n'+
'                        </select>\n'+
'                     </xsl:when><xsl:when test="@height">\n'+
'                        <textarea tm_name="tm_formelem" rows="{@height}">\n'+
'                           <xsl:call-template name="SetBasicAttributes" />\n'+
'                           <xsl:choose><xsl:when test="@length=\'max\'">\n'+
'                              <xsl:attribute name="class">tm_textarea tm_textarea_max</xsl:attribute>\n'+
'                           </xsl:when><xsl:otherwise>\n'+
'                              <xsl:attribute name="class">tm_textarea tm_textarea_auto</xsl:attribute>\n'+
'                              <xsl:attribute name="cols">\n'+
'                                 <xsl:choose><xsl:when test="@length">\n'+
'                                    <xsl:value-of select="@length" />\n'+
'                                 </xsl:when>\n'+
'                                 <xsl:otherwise>20</xsl:otherwise></xsl:choose>\n'+
'                              </xsl:attribute>\n'+
'                           </xsl:otherwise></xsl:choose>\n'+
'                           <xsl:value-of select="Default" />\n'+
'                        </textarea>\n'+
'                     </xsl:when><xsl:otherwise>\n'+
//   '   <xsl:when test="@type=\'boolean\'">
//   '      <input type="checkbox" tm_name="tm_formelem" value="1">\n'+
//   '         <xsl:call-template name="SetBasicAttributes" />\n'+
//   '      </input>\n'+
//   '   </xsl:when>\n'+
//   '   <xsl:otherwise>\n'+
//
//   '   </xsl:otherwise>\n'+
'                        <input type="text" tm_name="tm_formelem" value="{Default}" class="tm_input">\n'+
'                           <xsl:call-template name="SetBasicAttributes" />\n'+
'                           <xsl:choose><xsl:when test="@length=\'max\'">\n'+
'                              <xsl:attribute name="class">tm_input tm_input_max</xsl:attribute>\n'+
'                           </xsl:when><xsl:otherwise>\n'+
'                              <xsl:attribute name="size">\n'+
'                                 <xsl:choose><xsl:when test="@length">\n'+
'                                    <xsl:value-of select="@length" />\n'+
'                                 </xsl:when>\n'+
'                                 <xsl:otherwise>20</xsl:otherwise></xsl:choose>\n'+
'                              </xsl:attribute>\n'+
'                           </xsl:otherwise></xsl:choose>\n'+
'                        </input>\n'+
'                     </xsl:otherwise></xsl:choose>\n'+
'                     </td></tr>\n'+
'                  </xsl:otherwise></xsl:choose></table>\n'+
'               </div>\n'+
'            </xsl:for-each>\n'+
'         </div>\n'+
'      </xsl:for-each>\n'+
'      </form>\n'+
'      <!-- end formular creation -->\n'+
'      </div> <!-- formular -->\n'+
'      <div id="tm_state" class="tm_state">:-)</div>\n'+
'      <div id="tm_footer" class="tm_footer">\n'+
'             <button id="tm_submit" class="tm_button" tabindex="5000" disabled="true"><xsl:choose><xsl:when test="$locals_submit"><xsl:value-of select="$locals_submit" /></xsl:when><xsl:otherwise>locals_submit</xsl:otherwise></xsl:choose></button>\n'+
'             <button id="tm_cancel" class="tm_button" tabindex="5001" disabled="true"><xsl:choose><xsl:when test="$locals_cancel"><xsl:value-of select="$locals_cancel" /></xsl:when><xsl:otherwise>locals_cancel</xsl:otherwise></xsl:choose></button>\n'+
'             <button id="tm_createxml" class="tm_button" tabindex="5002" disabled="true" style="visibility:hidden"><xsl:choose><xsl:when test="$locals_createxml"><xsl:value-of select="$locals_createxml" /></xsl:when><xsl:otherwise>locals_createxml</xsl:otherwise></xsl:choose></button>\n'+
'      </div>\n'+
'      </div> <!-- main frame -->\n'+
'\n'+
'   </xsl:template>\n'+
'   \n'+
'   <xsl:template match="Group" mode="group_selector">\n'+
'      <xsl:if test="@name">\n'+
'         <a id="tm_group_select_{position() div 2}" class="tm_button tm_selector tm_group_selector"><xsl:value-of select="@name"/></a>\n'+
'      </xsl:if>\n'+
'   </xsl:template>\n'+
'   \n'+
'   <xsl:template name="SetBasicAttributes">\n'+
'      <xsl:attribute name="id">' + PAR_START + '<xsl:value-of select="@name"/></xsl:attribute>\n'+
'      <xsl:attribute name="title"><xsl:choose>\n'+
'         <xsl:when test="Help">\n'+
'            <xsl:value-of select="Help"/>\n'+
'         </xsl:when>\n'+
'         <xsl:otherwise><xsl:choose><xsl:when test="$locals_nohelp"><xsl:value-of select="$locals_nohelp" /></xsl:when>'+
'            <xsl:otherwise>locals_nohelp</xsl:otherwise></xsl:choose></xsl:otherwise>\n'+
'      </xsl:choose>   </xsl:attribute>\n'+
'      <xsl:attribute name="tm_condition"><xsl:value-of select="Condition"/></xsl:attribute>\n'+
'      <xsl:attribute name="tm_autovalue"><xsl:value-of select="AutoValue"/></xsl:attribute>\n'+
'      <xsl:attribute name="tabindex"><xsl:value-of select="20+count(preceding::*)"/></xsl:attribute>\n'+
'      <xsl:attribute name="tm_type">\n'+
'         <xsl:choose>\n'+
'            <xsl:when test="@type">\n'+
'               <xsl:value-of select="@type" />\n'+
'            </xsl:when>\n'+
'         </xsl:choose>\n'+
'      </xsl:attribute>\n'+
'      <xsl:choose>\n'+
'         <xsl:when test="@null=\'false\'">\n'+
'            <xsl:attribute name="tm_null">false</xsl:attribute>\n'+
'         </xsl:when>\n'+
'         <xsl:otherwise>\n'+
'            <xsl:attribute name="tm_null">true</xsl:attribute>\n'+
'         </xsl:otherwise>\n'+
'      </xsl:choose>\n'+
'      <xsl:choose>\n'+
'         <xsl:when test="@predefined=\'true\'">\n'+
'            <xsl:attribute name="tm_predefined">true</xsl:attribute>\n'+
'         </xsl:when>\n'+
'         <xsl:otherwise>\n'+
'            <xsl:attribute name="tm_predefined">false</xsl:attribute>\n'+
'         </xsl:otherwise>\n'+
'      </xsl:choose>\n'+
'      <xsl:attribute name="tm_error">false</xsl:attribute>\n'+
'   </xsl:template>\n'+
'</xsl:stylesheet>'
);
}   // get_xsl_dom()



   //## File: vorlagenmeister.js #################################

   /*
   * Copyright (C) 2007-2013 [[de:Benutzer:Revvar]] <revvar@gmx.de>
   * Released under the GPL license version 2
   * http://www.gnu.org/copyleft/gpl.html
   *
   * This program is free software; you can redistribute it and/or modify
   * it under the terms of the GNU General Public License version 2 as
   * published by the Free Software Foundation.
   *
   * This program is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty
   * of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE.
   * See the GNU General Public License for more details.
   */



/* Plugin objects */
var TM_PluginList = [ ]; //< list with the plugins

/**
 Abstract PlugIn objects, to announce a plugin to the TemplateMaster
*/
function TM_Plugin() {
   this.opGetName = null; //< returns plugin name for the user as String
   this.opGetType = null; //< returns plugin type as String
   this.opGetTemplate = null;  //< returns the template name the PlugIn is written for as String
}

/**
 Abstract object for a Wiki2Template plugin.
*/
function TM_P_Wiki2Template() {
   var type = "Wiki2Template";
   TM_Plugin.call(this);
   this.opGetType = function() { return type; };
   this.opTransform = function(wiki_text) {
      if ( ! ( wiki_text
               &&  typeof(wiki_text) === "string"
               &&  wiki_text.length > 0 ) ) {
         throw("(TMP_Wiki2Template:contructor) Error: Invalid arguments.");
      }
      return wiki_text;
   };
}   // TM_P_Wiki2Template()
TM_P_Wiki2Template.prototype = new TM_Plugin();

/*END: Plugin objects */



   function tm_init() {
      // Start actions on current page
      // Precondition:
      //    Any required module has been loaded
      //    document.ready
      //    editing mode
      var escapeSyntax = "#~\f~#",
          max_tics     = 50,
          milli_sec    = 200,
          more_tics    = max_tics,
          sel_fields   = "input[title],select[title],textarea[title]",
          xmlHTTP      = { },
          Act_input,
          Divs,
          Template,
          Tm_box,
          act_view,
          generated_xml,
          is_gecko,
          is_opera,
          is_xml_generated,
          max_value_indentation,
          resize_mutex,
          $sel_fields,
          $Statebar;



      function addEventListener( aNode, event, callback ) {
         if ( IS_IE
              &&   ( typeof( aNode.attachEvent ) === "object"  ||
                     typeof( aNode.attachEvent ) === "function" ) ) {
            // ... IE10
            aNode.attachEvent( "on"+event, callback );
         } else {
            aNode.addEventListener( event, callback, false );
         }
      }   // tm_init().addEventListener()



      function removeEventListener( aNode, event, callback ) {
         if ( IS_IE
              &&   ( typeof( aNode.detachEvent ) === "object"  ||
                     typeof( aNode.detachEvent ) === "function" ) ) {
            // ... IE10
            aNode.detachEvent("on"+event, callback);
         } else {
            aNode.removeEventListener(event, callback, false);
         }
      }   // tm_init().removeEventListener()



      function replace_all( text, regexp, replacement ) {
         var count_tmp = 1000;
         while ( text.search(regexp) >= 0  &&  count_tmp ) {
            text = text.replace(regexp, replacement);
            count_tmp--;
         }
         if (! count_tmp) {
            log_message("replace_all: Internal error - infinite loop");
            text = null;
         }
         return text;
      }   // tm_init().replace_all()



      function trim( text ) {
         text = "" + text;
         text = replace_all(text, /^\s+/g, "");
         text = replace_all(text, /^(.*?)\s+$/, "$1");
         text = replace_all(text, "\n\n", "\n");
         if (text.search(/[^\s]/) < 0) {
            text = "";
         }
         return text;
      }   // tm_init().trim()



      function setStyleAttribute( aNode, attribute ) {
         var aid;
         if ( aNode && attribute ) {
            for ( aid in attribute ) {
               aNode.style[ aid ] = attribute[ aid ];
            }
         }
      }   // tm_init().setStyleAttribute()




      function Sanitize() {
         // HTML sanitizer; good luck (singleton)
         var reFirst  = new RegExp( "<\\W*(\\w+)\\W", "g" ),
             saveHTML = " a b bdi bdo br caption cite code col colgroup"
                        + " dd del dfn div dl dt em"
                        + " h1 h2 h3 h4 h5 h6 hr i ins kbd li ol"
                        + " p pre q ruby rp rt"
                        + " s samp small span strong sub sup "
                        + " table tbody td th thead tfoot tr tt"
                        + " u ul var ";
         function first( all, approve ) {
            // Sanitize HTML tags
            var r,
                s = " " + approve.toLowercase() + " ";
            if ( saveHTML.indexOf( s )  <  0 ) {
               r = "&lt;" + all.substr( 1 );
            } else {
               r = all;
            }
            return r;
         }   // tm_init().Sanitize().first()
         function further( $a, all ) {
            // Sanitize jQuery object
            //    $a   -- jQuery element, with children
            //    all  -- string, with entire HTML code
            //    return sanitized string
            var r   = all,
                dom, i, j, s, shit, $e;
            for ( i = 0;  i < $a.length;  i++ ) {
               dom = $a.get( i );
// console.log( dom.nodeType, dom.nodeName )
               if ( dom.nodeType === window.document.ELEMENT_NODE ) {
                  $e = $a.eq( i );
                  s  = $e.attr( "style" );
                  if ( s   &&   s.indexOf( "//" )  >  0 ) {
                     shit = "HTML sanitized (possible URL)";
                     break;   // for i
                  }
                  dom = dom.attributes;
                  for ( j = 0;  j < dom.length;  j++ ) {
                     s = dom.item( j ).nodeName.toLowerCase();
// console.log( j, s )
                     if ( s.substr( 0, 2 ) === "on" ) {
                        shit = "HTML sanitized attribute " + s + "=";
                        break;   // for j
                     }
                  }   // for j
                  if ( shit ) {
                     break;   // for i
                  } else {
                     $e = $e.children();
                     if ( $e.length ) {
                        r = further( $e, r );
                     }
                  }
               }
            }   // for i
            if ( shit ) {
               r = "****** " + shit + " ******";
            }
            return r;
         }   // tm_init().Sanitize().further()
         Sanitize.fire = function ( all ) {
            // Start sanitizing
            //    all  -- string, with entire HTML code
            //    return sanitized string
            var r  = all.replace( reFirst, first ),
                $t = $( "<div>" ).html( r );
            return further( $t, r );
         };   // tm_init().Sanitize.fire()
      }   // tm_init().Sanitize()


      function cNode( nRoot, nType, nText, nAttr ) {
      /**
        Creates a new GUI node.

       @param nRoot null or reference to the prefered root node object
       @param nType HTML type string ("div" for example)
       @param nText null or string with the text for the text child node
       @param nAttr null or object with attribute attributes, ({style:"...",width:"100%"} for example)
       @return the new node object
       @author [[de:Benutzer:Revvar]]
      */
         var elem = document.createElement(nType),
             re1  = /^\s*([^:]+):.*$/,
             re2  = /^\s*[^:]+:\s*([^\s;]+)[\s;]*$/,
             aid,
             i,
             style_attr,
             style_id,
             style_obj,
             style_value;
         if (nAttr) {
            for (aid in nAttr) {
               if (aid === "style") {
                  style_attr = nAttr[aid].split(";");
                  style_obj = { };
                  for (i = 0; i < style_attr.length; i++) {
                     style_id = style_attr[i].replace(re1, "$1");
                     style_value = style_attr[i].replace(re2,"$1");
                     if (style_id.length > 0) {
                        style_obj[style_id] = style_value;
                     }
         //             log_message(style_id + ":" + style_value);
                  }
                  setStyleAttribute(elem, style_obj);
               } else {
                  if (aid === "class") {
                     elem.className = nAttr[aid];
                  } else {
                     elem.setAttribute(aid, nAttr[aid]);
                  }
               }
            }   // for aid in nAttr
         }
         if (nText) {
            elem.appendChild(document.createTextNode(nText));
         }
         if (nRoot) {
            nRoot.appendChild(elem);
         }
         return elem;
      }   // tm_init().cNode()



      function deprecated() {
         var $d = $( ".tm_deprecated" ),
             i, $e, $i;
         for ( i = 0;  i < $d.length;  i++ ) {
            $e = $d.eq( i );
            $i = $e.find( "input[type=\"text\"]" );
            if ( $i.length === 1   &&
                 trim( $i.eq( 0 ).val() )  ===  "" ) {
               $e.hide();
            }
         }   // for i
      }   // tm_init().deprecated()



      function getNamespaceNumber( pagename, defaultspace ) {
         // return identified number, or defaultspace
         var s = pagename.replace( /^\s+/, "" ),
             i = s.indexOf( ":" ),
             n, r;
         if ( i < 0 ) {
            r = defaultspace;
         } else if ( i ) {
            if ( typeof(LOCALS.wgNamespaceIds) !== "object" ) {
               LOCALS.wgNamespaceIds = mw.config.get( "wgNamespaceIds" );
            }
            s = s.substr( 0,  i - 1 )
                 .replace( /\s*$/, "" )
                 .replace( /\s+/, "_" )
                 .toLowerCase();
            n = LOCALS.wgNamespaceIds[ s ];
            if ( n ) {
               r = n;
            }
         } else {
            r = 0;
         }
         return r;
      }   // tm_init().getNamespaceNumber()



      function getFullTemplatePagename( page ) {
         // return pagename, defaulting to template namespace
         var nsn = getNamespaceNumber( page, 10 ),
             r   = trim( page );
         r   = ( nsn === 10  ?  LOCALS.template + ":" + r
                             :  r );
         return r.replace( /\s+/g, "_");
      }   // tm_init().getFullTemplatePagename()



      function insertUnknown(e) {
         var text;
         if (IS_IE) {
            text = e.srcElement.title;
         } else {
            text = e.target.title;
         }
         preventDefault(e);
         if ( Act_input   &&
              ! Act_input.nodeName.search(/^(input|select|textarea)$/i)
              &&   Act_input.type.search(/^checkbox$/i) < 0 ) {
            Act_input.value = text;
         }
      }   // tm_init().insertUnknown()



      function resizeInputBox( oInputBox, extra_spaces ) {
         var right_pos = oInputBox.offsetWidth,
             tmp_str = "",
             node = oInputBox,
             table_node = null,
             old_width;
         if (resize_mutex === true) {
            return;
         }
         resize_mutex = true;
         if ( ! ( oInputBox.nodeName   &&
                  ! oInputBox.nodeName.search(/^input$/i)   &&
                  oInputBox.type   &&
                  ! oInputBox.type.search(/^text$/i) ) ) {
            log_message("Internal error: call of resizeInputBox with an unsupported node type: " + oInputBox);
            resize_mutex = false;
            return;
         }

         /* first call for this node ? */
         if (!(oInputBox.tm_org_size)) {
            oInputBox.tm_org_size = oInputBox.size; // save orginal size
         }

         if (oInputBox.tm_org_size >= oInputBox.value.length)  {
            resize_mutex = false;
            return;
         }
         oInputBox.size = oInputBox.value.length + extra_spaces;
         right_pos = oInputBox.offsetWidth;
         tmp_str = "";
         node = oInputBox;
         table_node = null;
         do {
            if (node.className.search("tm_table") >= 0) {
               table_node = node;
            } else {
               right_pos += node.offsetLeft;
               tmp_str   += node.offsetLeft + "px +";
            }
            node = node.parentNode;
         } while (node.className.search("tm_group") < 0);
         if ((right_pos + 8) > node.offsetWidth) {
            if (IS_IE) {
               while ((right_pos + 8) > node.offsetWidth) {
                  old_width = oInputBox.offsetWidth;
                  oInputBox.size--;
                  right_pos -= old_width - oInputBox.offsetWidth;
               }
            } else {
               oInputBox.size = oInputBox.tm_org_size;
               if (table_node) {
                  table_node.className = "tm_table tm_table_max";
               } else {
                  log_message("internal error: table not found");
               }
               oInputBox.className = "tm_input tm_input_max";
            }
            removeEventListener(oInputBox, "keyup", resizeHandler);
         }
         resize_mutex = false;
         return;
      } // tm_init().resizeInputBox()



      function resizeHandler(e) {
         var org_end, org_start, org_value;
         Act_input = (IS_IE ? e.srcElement : e.target);
         Act_input.tm_old_size = Act_input.size;
         resizeInputBox(Act_input, 1);
         if (is_gecko && (Act_input.tm_old_size !== Act_input.size)) {
            org_value = Act_input.value;
            org_start = Act_input.selectionStart;
            org_end = Act_input.selectionEnd;
            Act_input.value = "";
            Act_input.value = org_value;
            if (org_end >= org_start) {
               Act_input.selectionEnd = org_end;
            }
            Act_input.selectionStart = org_start;
            if (org_end < org_start) {
               Act_input.selectionEnd = org_end;
            }
         }
      }   // tm_init().resizeHandler()



      function selectGroup(e) {
         var Form_div, Group_div, position, text;
         preventDefault(e);
         try {
            text = "" + (IS_IE ? e.srcElement : e.target).id;
            position = Math.round( parseFloat( text.replace( /^.+_([0-9\.]+)$/,
                                                             "$1") )
                                   * ( IS_IE ? 2 : 1 ) );
            Group_div = document.getElementById("tm_group_"+position);
            Form_div = document.getElementById("tm_form");
            Form_div.scrollTop = Group_div.offsetTop
                                 - Group_div.parentNode.offsetTop;
         } catch(exc) {
            log_message(exc.message+"\n"+"Internal error: Can't select group div with id=\"tm_group_"+position+"\".");
            switch_view_to("EB");
         }
      }   // tm_init().selectGroup()



      function template_doc(  ) {
         var $wrap = $( "#tm_template-doc" ),
             s     = $( "#tm_template").val(),
             $a;
         $wrap.empty();
         if ( s) {
            s  = getFullTemplatePagename( s );
            $a = $( "<a>" );
            $a.attr( { href:   mw.util.getUrl( s ),
                       target: "_blank" } )
              .text( LOCALS.showTdoc );

            $wrap.append( $a );
         }
      }   // tm_init().template_doc()



      function tipsy() {
         var opts = { gravity: "n",
                      html:    true,
                      opcity:  0.66,
                      trigger: "hover" },
             i, $e;
         for ( i = 0;  i < $sel_fields.length;  i++ ) {
            $e = $sel_fields.eq( i );
            $e.attr( "title",
                     Sanitize.fire( $e.attr( "title" ) ) );
         }   // for i
         $sel_fields.tipsy( opts );
      }   // tm_init().tipsy()



      function whenDOMready() {
         $sel_fields = $( "#tm_main_frame" ).find( sel_fields );
         if ( $sel_fields.length ) {
            more_tics = false;
         }
         if ( more_tics ) {
            more_tics--;
            window.setTimeout( whenDOMready, milli_sec );
         } else {
            more_tics = max_tics;
            // BETA-Test  deprecated();
            template_doc();
            tipsy();
         }
      }   // tm_init().whenDOMready()



      /* shows the template master */
      function show() {
         var marker_end   = "##\f#template_master_marker_end##\f#",
             marker_start = "##\f#template_master_marker_start##\f#",
             act_depth, cursor_pos, cursor_depth, cursor_dist, depth,
             Editbox, end, end_index, i,
             new_part, new_pos, new_template_source,
             source, start, start_index,
             tag_list, tag_pos, Target, Template_given, template_source,
             x_htmlcomment, x_nowiki, x_tag;



         function makeTMbox() {
            var bx = document.getElementById( "wpTextbox1" ),
                r = cNode( bx.parentNode,
                           "div",
                           null,
                           {"id":    "tm_dummy_div",
                            "style": "position:absolute;" +
                                     "z-index:99;" +
                                     "left:" + bx.offsetLeft + "px;" +
                                     "top:" + bx.offsetTop + "px;" +
                                     "width:" + bx.offsetWidth + "px;" +
                                     "height:" + bx.offsetHeight +"px;" +
                                     ( IS_IE  ?  "overflow-x:hidden;" +
                                                 "overflow-y:auto;"
                                              : "overflow:auto;" ) } );
               return r;
         }   // tm_init().show().makeTMbox()



         function pluginSelect( Target, Tm_box ) {
            var A_cancel, A_plugin, Editbox, handler, i, name,
                Plugin_div, plugins, Template_given, type;
            if ( TM_PluginList && TM_PluginList.length ) {
               /* create plugin list */
               plugins = [ ];
               for ( i = 0; i < TM_PluginList.length; i++ ) {
                  try {
                     name = TM_PluginList[i].opGetName();
                     type = TM_PluginList[i].opGetType();
                     if ( type === "Wiki2Template"  &&  name ) {
                        plugins.push( TM_PluginList[i] );
                     }
                  } catch(e) {
                     log_message("Incompatible Plugin: " + e.message);
                  }
               }   // for i
               if ( plugins.length > 0 ) {
                  Plugin_div = cNode( null,
                                      "div",
                                      LOCALS.w2t_plugin_selection,
                                      {"class": "tm_plugin_selector"} );
                  handler = function (e) {
                        var plugin = ( IS_IE ? e.srcElement
                                             : e.target ).tm_plugin;
                        if (plugin) {
                           Template_given = plugin.opTransform(Editbox.value.substring(Target.start, Target.end + 1));
                           if (Template_given) {
                              Plugin_div.parentNode.removeChild(Plugin_div);
                              show_template(Tm_box, false, Template_given, Target);
                           }
                        } else {
                           log_message("Internal error: No tm_plugin attribute found.");
                        }
                  };   // handler()
                  for ( i = 0; i < plugins.length; i++ ) {
                     A_plugin = cNode(Plugin_div,
                                      "a",
                                      plugins[i].opGetName(),
                                      {"class":"tm_button tm_v_selector tm_plugin_selector"});
                     A_plugin.tm_plugin = plugins[i];
                     addEventListener( A_plugin, "click", handler );
                  }   // for i
                  A_cancel = cNode( Plugin_div,
                                    "a",
                                    LOCALS.Cancel,
                                    { "class": "tm_button tm_v_selector tm_cancel_button",
                                      "style": "margin-top:8px !important"
                                    } );
                  addEventListener( A_cancel,
                                    "click",
                                    function() {
                              Plugin_div.parentNode.removeChild(Plugin_div);
                              show_template(Tm_box, false, null, Target);
                                    } );
                  Tm_box.appendChild(Plugin_div);
               }
   /*
               log_message(plugins.join(","));
               Template_given =
                  TM_PluginList[0].opTransform(Editbox.value.substring(Target.start,
                                                                       Target.end + 1));
   */
            }
         }   // tm_init().show().pluginSelect()



         function wikEdEnclose( obj ) {
            window.wikEd.GetText( obj, "selection, cursor" );
            if ( obj.selection.plain === "" ) {
               obj.sel = window.wikEd.GetSelection();
               if ( obj.sel.anchorNode.previousSibling ) {
                  obj.changed = obj.cursor;
               } else {
                  window.wikEd.GetText( obj, "whole" );
                  obj.changed = obj.whole;
               }
            } else {
               obj.changed = obj.selection;
            }
            obj.changed.plain = marker_start
                                + obj.changed.plain
                                + marker_end;
         }   // tm_init().show().wikEdEnclose()



         /* set some globals to their defaults */
         if ( document.getElementById( "tm_dummy_div" ) ) {
            switch_view_to();
            return;
         }

         /* check if cursor within template wikitext and parse it */
         Target = { };
         Editbox = document.getElementById( "wpTextbox1" );
         Target.Editbox = Editbox;

         // CodeMirror

         /* get cursor/mark position (browser dependant) */
         if ( typeof( OPTIONS.wikEd ) === "object"
              &&  window.wikEd.useWikEd ) {
            window.wikEd.EditButton( null, null, null, wikEdEnclose );
            window.wikEd.UpdateTextarea();
            window.wikEd.SetEditArea( false, false );
            window.wikEd.useWikEd = false;
            Target.start  = Editbox.value.search( marker_start );
            Editbox.value = Editbox.value.replace( marker_start, "" );
            Target.end    = Editbox.value.search( marker_end ) - 1;
            Editbox.value = Editbox.value.replace( marker_end, "" );
            window.wikEd.UpdateFrame();
            Target.cursor = Target.start;
            OPTIONS.wikEd.live = true;
/*
   2018-10-24   TEST   IE complaints??
         } else if ( IS_IE ) {
            mw.toolbar.insertTags( marker_start, marker_end, "" );
            Target.start  = Editbox.value.search( marker_start );
            Editbox.value = Editbox.value.replace( marker_start, "" );
            Target.end    = Editbox.value.search( marker_end ) - 1;
            Editbox.value = Editbox.value.replace( marker_end, "" );
*/
         } else {
            Target.cursor = Editbox.selectionStart;
            Target.start  = Editbox.selectionStart;
            Target.end    = Editbox.selectionEnd - 1;
         }

         /* search if cursor within a template */

         /* (1) replace syntax chars within nowiki-tags and html-comments */
         x_nowiki = /(<nowiki>.*?)[{|}](.*?<\/nowiki>)/g;
         source = replace_all(Editbox.value, x_nowiki, "$1#$2");
         x_htmlcomment = /(<!--.*?)[{|}](.*?-->)/g;
         source = replace_all(Editbox.value, x_htmlcomment, "$1#$2");

         /* (2) create a list of all remaining template tags */
         tag_list = [ ];
         depth = 0;
         x_tag = /(\{\{|\}\})/;
         tag_pos = -2;
         new_pos = 0;
         do {
            new_pos = (source.substring(tag_pos + 2)).search(x_tag);
            if (new_pos >= 0) {
               tag_pos += new_pos + 2;
               switch (source.substring(tag_pos, tag_pos + 2)) {
                  case "{{":
                     tag_list.push( { type:     0,
                                      depth:    depth,
                                      position: tag_pos } );
                     depth++;
                     break;
                  case "}}":
                     depth--;
                     tag_list.push( { type:     1,
                                      depth:    depth,
                                      position: tag_pos } );
                     break;
                  default:
                     log_message("Internal error: Searching template tags failed ("+source.substring(tag_pos, tag_pos + 2)+").");
                     return;
               }   // switch
            }
         } while (new_pos >= 0);

         /* (3) find nearest tag pair (same depth) around the cursor position */
         start = -1;
         end = -1;
         start_index = -1;
         end_index = -1;
         act_depth = 0;
         cursor_pos = Target.start;
         cursor_depth = 0;
         cursor_dist = 1000000;

         /* (a) find the depth at cursor pos */
         for (i = 0;  i < tag_list.length;  i++) {
            if (tag_list[i].type) {
               if (cursor_pos > tag_list[i].position   &&
                   cursor_pos - tag_list[i].position  <  cursor_dist) {
                  cursor_depth = tag_list[i].depth - 1;
                  cursor_dist = cursor_pos - tag_list[i].position;
               }
            } else {
               if (cursor_pos >= tag_list[i].position    &&
                   cursor_pos - tag_list[i].position  <  cursor_dist) {
                  cursor_depth = tag_list[i].depth;
                  cursor_dist = cursor_pos - tag_list[i].position;
               }
            }
            if (cursor_pos < tag_list[i].position) {
               break;   // sorted array
            }
         }   // for i

         /* (b) search */
         for ( i = 0;  i < tag_list.length;  i++ ) {
            if ( cursor_pos >= tag_list[i].position ) {
               if ( ! tag_list[i].type
                   &&  cursor_depth >= tag_list[i].depth ) {
                  start = tag_list[i].position;
                  start_index = i;
                  act_depth = tag_list[i].depth;
               }
               if ( start > -1   &&
                    tag_list[i].type === 1   &&
                    act_depth === tag_list[i].depth   &&
                    cursor_pos > tag_list[i].position ) {
                  start = -1;
                  start_index = -1;
               }
            } else {
               break;
            }
         }   // for i
         if ( start > -1 ) {
            for ( i = tag_list.length - 1;  i > 0;  i-- ) {
               if ( cursor_pos <= tag_list[i].position ) {
                  if ( cursor_depth >= tag_list[i].depth
                       && tag_list[i].type === 1
                       && act_depth === tag_list[i].depth ) {
                     end = tag_list[i].position;
                     end_index = i;
                  }
               } else {
                  break;
               }
            }   // for i
         }

         /* (4) get template source code without the surrounding brackets */
         if ( start >=0  &&  end >= 0 ) {
            template_source = Editbox.value.substring(start + 2, end);
         } else {
            template_source = null;
         }

         /* defuse nested templates */
         new_template_source = "";
         if ( start_index + 1  <  end_index - 1 ) {
            new_template_source = template_source.substring(0,
                                                            tag_list[start_index + 1].position - start);
            for ( i = start_index + 1;  i < end_index - 1;  i++ ) {
               new_part = template_source.substring(tag_list[i].position - start,
                                                    tag_list[i+1].position - start);
               if (tag_list[i].depth - tag_list[i].type > act_depth) {
                  new_part = replace_all(new_part, /\|/g, escapeSyntax);
               }
               new_template_source += new_part;
            }
            new_template_source += template_source.substring(tag_list[end_index - 1].position
                                                             - start, template_source.length);
            template_source = new_template_source;
         }

         /* parse source */
         if (template_source) {
            Template_given = parse_template_source(template_source);
            if (Template_given) {
               // save new positions only, if template parsed successfull
               Target.start = start;
               Target.end = end + 1;
            } else {
               template_source = null;
            }
         }

         switch_view_to();
         /* dummy main div */
         Tm_box = makeTMbox();

         if ( template_source === null
             &&  Target.start <= Target.end ) {
            // ask, if the user want to use a Wikitext_To_Template-Plugin
            pluginSelect( Target, Tm_box );
         } else {
            /* load given template */
            show_template( Tm_box, false, Template_given, Target );
         }
      }   // tm_init().show()



/* shows specific template */
function show_template(Root_node, template_name, Template_given, Target) {
   var $buttonOkay = false,
       $throbber   = false,
       REclose, REopen, Template_new, $inputTemplateName;



   function iso8601( date, local, max ) {
      var n = ( max ? max : 19 ),
          k, r;
      function f( a ) {
         return ( local ? "get" : "getUTC" )  +  a;
      }
      r = date[ f( "FullYear" ) ]()  +  "";
      if ( n >= 7 ) {
         r = r + "-";
         k = date[ f( "Month" ) ]()  +  1;
         if ( k < 10 ) {
             r = r + "0";
         }
         r = r + k;
         if ( n >= 10 ) {
            r = r + "-";
            k = date[ f( "Date" ) ]();
            if ( k < 10 ) {
               r = r + "0";
            }
            r = r + k;
            if ( n >= 13 ) {
               r = r + " ";
               k = date[ f( "Hours" ) ]();
               if ( k < 10 ) {
                  r = r + "0";
               }
               r = r + k;
               if ( n >= 16 ) {
                  r = r + ":";
                  k = date[ f( "Minutes" ) ]();
                  if ( k < 10 ) {
                     r = r + "0";
                  }
                  r = r + k;
                  if ( n >= 19 ) {
                     r = r + ":";
                     k = date[ f( "Seconds" ) ]();
                     if ( k < 10 ) {
                        r = r + "0";
                     }
                     r = r + k;
                  }
               }
            }
         }
      }
      return r;
   }   // tm_init().show_template().iso8601()



   function traverse(Parent, name) {
      var childs = [ ],
          Child = Parent.firstChild;
      while (Child) {
         if ((Child.getAttribute) && (Child.getAttribute("tm_name"))) {
            if ( ! (""+Child.getAttribute("tm_name")).search(name) ) {
               childs.push(Child);
            }
         }
         if (Child.firstChild) {
            childs = childs.concat(traverse(Child, name));
         }
         Child = Child.nextSibling;
      }
      return childs;
   }   // tm_init().show_template().traverse()



   function attachForm(dom) {
      /* append formular to root node */
      var Mf = dom.getElementById("tm_main_frame"),
          i, Input_node, new_height,
          Tm_footer, Tm_form, Tm_header, Tm_main;
      if (IS_IE) {
         Root_node.removeChild(document.getElementById("tm_dummy_ie_div"));
      }
      Root_node.appendChild(Mf);

      Tm_main   = document.getElementById("tm_main_frame");
      Tm_header = document.getElementById("tm_header");
      Tm_form   = document.getElementById("tm_form");
      Tm_footer = document.getElementById("tm_footer");

      /* resize all input boxes*/
      Input_node = traverse(Tm_form, "tm_formelem");
      for (i = 0; i < Input_node.length; i++) {
         if (Input_node[i].className === "tm_input") {
            resizeInputBox(Input_node[i], 1);
         }
      }

      /* resize formular */
      new_height = Root_node.offsetHeight
                   - Tm_header.offsetHeight - Tm_footer.offsetHeight;
      setStyleAttribute(Tm_form, {"height": new_height + "px"});
      setStyleAttribute(Tm_form, {"height": (new_height + Root_node.offsetHeight - Tm_main.offsetHeight)
                                            + "px"} );
   }   // tm_init().show_template().attachForm()



   function autovalue( assign ) {
      var r = "",
          date, local, n, perform;
      if ( typeof assign  ===  "string"   &&   assign ) {
         r = trim( assign );
         if ( r.charCodeAt( 0 )  ===  124 ) {   // '|'
            perform = r.split( "|" );
            switch ( perform[ 1 ] ) {
               case "localtime" :
                  local = true;
                  // fall through
               case "utc" :
                  date = new Date();
                  if ( perform[ 2 ] ) {
                     n = perform[ 2 ].length;
                  }
                  r = iso8601( date, local, n );
                  break;
               default:
                  r = "";
            }   // switch perform[0]
         }
      }
      return r;
   }   // tm_init().show_template().autovalue()



   function cancelTemplate(e) {
      preventDefault(e);
      switch_view_to("EB");
   }   // tm_init().show_template().cancelTemplate()



   function createXML(e) {
      var env = mw.config.get( [ "wgScript",
                                 "wgServer" ] ),
          full_name = getFullTemplatePagename( template_name ),
          tb, textbox, xml_window;
      preventDefault(e);
      xml_window = window.open(
                   env.wgServer + env.wgScript
                   + "?action=edit&summary="
                   + encodeURIComponent(LOCALS.summary_generated)
                   + "&title=" + encodeURIComponent(full_name)
                   + "/XML" );
      xml_window.focus();
      textbox = xml_window.document.getElementById("wpTextbox1");
      if (textbox) {
         textbox.value = generated_xml;
      } else {
         addEventListener(xml_window,
                          "load",
                          function () {
               tb = xml_window.document.getElementById("wpTextbox1");
               if (tb) {
                  tb.value = generated_xml;
               }
                          } );
      }
   }   // tm_init().show_template().createXML()



   function completeForm(dom) {
      var comment_counter = 0,
          is_changed = false,
          Button_cancel, Button_createXML, Button_submit,
          Group_button, group_count, Group_div, Group_selector,
          i, id, Input_node, name, Name_node, new_name,
          s, sx, Temp_real, Template_used,
          unknown_div, Unknown_link, unknown_parameter;



      function mapParameter(Temp_plugin, Temp_real) {
         var Temp_given = { },
             id, pi_id;
         for (id in Temp_real) {
            if (Temp_plugin[id]) {
               Temp_given[id] = Temp_plugin[id];
               Temp_plugin[id] = null;
            } else {
               for (pi_id in Temp_plugin) {
                  if (Temp_plugin[pi_id] &&
                      id.toLowerCase() === pi_id.toLowerCase()) {
                     Temp_given[id] = Temp_plugin[pi_id];
                     Temp_plugin[pi_id] = null;
                     break;
                  }
               }   // for pi_id in Temp_plugin
            }
         }   // for id in Temp_real

         /* append all unknown params */
         for (pi_id in Temp_plugin) {
            if (Temp_plugin[pi_id]) {
               Temp_given[pi_id] = Temp_plugin[pi_id];
            }
         }   // for pi_id in Temp_plugin
         return Temp_given;
      }   // tm_init().show_template().completeForm().mapParameter()



      function removeForm() {
         $( "#tm_main_frame" ).remove();
      }   // tm_init().show_template().removeForm()



      function showHelp(e) {
         var div = [ "#tm_main_frame",         // [0]
                     "#tm_form",               // [1]
                     "#tm_footer",             // [2]
                     "#tm_header",
                     "#tm_group_selector" ],
             i, n, s, $elem;
         preventDefault(e);
         if ( ! Divs ) {
            Divs = [ ];
            for ( i = 0;  i < div.length;  i++ ) {
               s = div[ i ];
               if ( i ) {
                  $elem = Divs[ 0 ][ 0 ].find( s );
               } else {
                  $elem = $( s );
               }
               Divs.push( [ $elem, $elem.height() ] );
            }   // for i
            $Statebar = Divs[ 0 ][ 0 ].find( "#tm_state" );
            $Statebar.css( { width:    "100%",
                             top:      "auto",
                             bottom:   Divs[ 2 ][ 1 ],
                             left:     "1em",
                             right:    "1em" } );
         }
         Act_input = (IS_IE ? e.srcElement : e.target);
         $elem     = $( Act_input );
         s         = $elem.attr( "title" )  ||
                     $elem.attr( "original-title" );
         $Statebar.empty().html( s )
                          .css( { "background-color": null } );
         n = Divs[ 0 ][ 1 ]  -  $Statebar.height();
         for ( i = 2;  i < Divs.length;  i++ ) {
            n -= Divs[ i ][ 1 ];
         }   // for i
         Divs[ 1 ][ 0 ].height( n );
      }   // tm_init().showHelp()



      function template_name_changed( e ) {
         var learnt = ( ! is_changed );
         if ( learnt ) {
            if ( e.type === "keypress" ) {
               if ( typeof( e.which ) === "number" ) {
                  learnt = ( e.which === 13 );
               } else if ( typeof( e.keyCode ) === "number" ) {
                  learnt = ( e.keyCode === 13 );
               } else {
                  learnt = false;
               }
            } else {
               learnt = false;
            }
            if ( learnt ) {
               new_name =  trim( $inputTemplateName.val() );
               if ( new_name.length ) {
                  new_name = new_name.substr( 0, 1 ).toUpperCase()
                             + new_name.substr( 1 );
                  is_changed = true;
                  removeForm();
                  show_template(Root_node, new_name, null, Target);
               } else {
                  $inputTemplateName.val( "" );
               }
            }
         }
      }   // tm_init().show_template().completeForm().template_name_changed()



      function template_name_submit() {
         template_name_changed( { type:  "keypress",
                                  which: 13 } );
      }   // tm_init().show_template().completeForm().template_name_submit()


      $Statebar = $( "#tm_state" );
      Name_node = dom.getElementById( "tm_template" );
      $inputTemplateName = $( Name_node );
      if ( template_name || Template_given ) {
         if ( Template_given ) {
            template_name = Template_given.template_name;
         }
         template_name = trim( template_name );
         template_name = template_name.replace( /_+/g, " " )
                                      .replace( /  +/g, " " );
         i = { readOnly: true };
         if (template_name.length > 32) {
            i.size = template_name.length;
         }
         $inputTemplateName.val( template_name );
         $inputTemplateName.attr( i );
         whenDOMready();
      } else {
         $inputTemplateName.val( "" );
         $buttonOkay = $( "<button>" );
         $buttonOkay.attr( { type: "button" } );
         $buttonOkay.css( { "margin-left": "1em" } );
         $buttonOkay.click( template_name_submit );
         $buttonOkay.text( LOCALS.Okay );
         $inputTemplateName.after( $buttonOkay );
         $inputTemplateName.keypress( template_name_changed );
         $inputTemplateName.mousemove( template_name_changed );
         $inputTemplateName.dblclick( template_name_submit );
      }

      /* fix an ie width problem for the group divs */
      if (IS_IE) {
         group_count = 1;
         do {
            Group_div = dom.getElementById("tm_group_" + group_count);
            if ( Group_div   &&
                 Group_div.className   &&
                 ("" + Group_div.className).search("tm_ie_group") < 0 ) {
               Group_div.className = "tm_group tm_ie_group";
            }
            group_count++;
         } while (Group_div);
      }

      Input_node  = traverse(dom, "tm_formelem");
      group_count = 1;

      /* save references to nodes and set help attribute */
      for ( i = 0;  i < Input_node.length;  i++ ) {
         if (Input_node[i].className === "tm_group") {
            id = "tm_group_" + group_count;
            Group_div = dom.getElementById(id);
            if ( Group_div ) {
               Template_new[id] = Group_div;
               Template_new[id].value = "";
               Template_new[id].showempty =
                    (Group_div.getAttribute("tm_showempty") !== "false");
            }
            group_count++;
         } else if (Input_node[i].className === "tm_group_heading") {
            id = "tm_comment_" + comment_counter;
            Template_new[id].value = "";
            if (comment_counter) {
               Template_new[id].value += "\n";
            }
            Template_new[id].value += "<!-- "
                              + Input_node[i].firstChild.data + " -->\n";
            comment_counter++;
         } else {
            id = Input_node[i].id;
            if (id === null) {
               log_message("Internal error: XSLT created input node without id.");
               switch_view_to( "EB" );
               return false;
            }
            if (Template_new[id]) {
               log_message("Internal error: Duplicate id \"" + id + "\".");
               switch_view_to( "EB" );
               return false;
            }
            Input_node[i].tm_help = Input_node[i].title;
            Template_new[id] = Input_node[i];
         }
      }

      /* transform all condition attributes from text to a RegExp */
      for (i = 0; i < Input_node.length; i++) {
         sx = Input_node[i].getAttribute("tm_type");
         if ( sx  &&  typeof sx === "string" ) {
            switch ( sx ) {
               case "boolean" :
                  s = "[01]";
                  break;
               case "date" :
                  s = "(1[0-9][0-9][0-9]|20[0-2][0-9])"
                      + "(-(1[0-2]|0[0-9])"
                       + "(-(3[01]|[012][0-9])"
                        + "([ T][012][0-9]"
                         + "(:[0-5][0-9]"
                          + "(:[0-5][0-9]"
                           + "(.[0-9]+"
                           + ")?"
                          + ")?"
                         + ")?"
                        + ")?"
                       + ")?"
                      + ")?";
                  break;
               case "line" :
                  s = "[^\n]+";
                  break;
               case "number" :
                  s = "[+-" + String.fromCharCode(8722) + "]?";
                  s = s + "[0-9.,]*[0-9]+[0-9.,]*"
                      + "([eE]" + s + "[0-9]+)?";
                  break;
               case "wiki-file-name" :
                  s = "[^/#<>{}]+\\.[a-zA-Z][a-zA-Z][a-zA-Z]+";
                  break;
               case "wiki-page-name" :
                  s = "[^#<>{}]+";
                  break;
               case "wiki-user-name" :
                  s = "[^/#<>{}]+";
                  break;
               default:
                  s = false;
            }   // switch
            if ( s ) {
               Input_node[i].tm_type = new RegExp( "^" + s + "$" );
               if ( ! sx.indexOf( "wiki-" ) ) {
                  Input_node[i].tm_legalWikipage = true;
               }
            }
         }
         s = Input_node[i].getAttribute("tm_condition");
         if (s  &&  typeof s === "string") {
            try {
               Input_node[i].tm_condition = new RegExp(s);
            } catch(e) {
               log_message(e.message+"\n"
                           +LOCALS.sys_invalid_condition.replace("$1",
                                                                 s));
               switch_view_to( "EB" );
               return false;
            }
         }
         s = Input_node[i].getAttribute("tm_autovalue");
         if (s  &&  typeof s === "string") {
            if ( Input_node[i].getAttribute("tm_null") === "false" ) {
               s  =  Input_node[i].id;
               if ( s   &&   s.substr(0, 8)  ===  "tm_form_" ) {
                  s  =  LOCALS.sys_conflict_null_AutoValue
                        + " *** " + s.substr(8);
               } else {
                  s  =  LOCALS.sys_conflict_null_AutoValue;
               }
               log_message( s );
               switch_view_to( "EB" );
               return false;
            } else {
               Input_node[i].tm_autovalue = trim(s);
            }
         }
      }

      /* map suggested to existing parameter names */
      if (Template_given
          && Template_given.source
          && Template_given.source === "plug-in") {
         /* create a list with all valid parameter names */
         Temp_real = { };
         for (i = 0; i < Input_node.length; i++) {
            name = "" + Input_node[i].id;
            if (name.length && name.length>0) {
               Temp_real[name] = true;
            }
         }
         Template_given = mapParameter(Template_given, Temp_real);
      }


      /* fill the form with the given template and add resize handler */
      Template_used = { };
      if (Template_given) {
         for (i = 0; i < Input_node.length; i++) {
            name = "" + Input_node[i].id;
            if (typeof Template_given[name] === "string") {
               Template_used[name] = true; /* mark given parameter to find unknown */
            }
            if (name
                && name.length
                && name.length > 0
                && Template_given[name]
                && Template_given[name].length > 0) {
               if ( Input_node[i].nodeName.search(/^select$/i)) {
                  if ( ! Input_node[i].type.search(/^checkbox$/i) ) {
                     Input_node[i].checked = (Input_node[i].value
                                          &&  Input_node[i].value !== "0");
                  } else  {   // <select>
                     Input_node[i].value = Template_given[name];
                     if ( ! Input_node[i].nodeName.search(/^input$/i) ) {
                        /* (1) replace newlines with <br /> */
                        Input_node[i].value = replace_all(Input_node[i].value,
                                                          new RegExp("\n","g"),
                                                          "<br />");
                     }
                  }
               } else {
                  Input_node[i].value = Template_given[name];
                  if (Input_node[i].value !== Template_given[name]) {
                     Input_node[i].title = LOCALS.sys_invalid_value
                                 + ": \"" + Template_given[name] + "\"! "
                                 + Input_node[i].tm_help;
                     Input_node[i].className = "tm_input tm_error";
                     Input_node[i].setAttribute("tm_error", "true");
                  }
               }
            }
         }
      }

      /* add function to show help text at state bar on focus and to trace act input field + add resize handler */
      for ( i = 0;  i < Input_node.length;  i++ ) {
         // addEventListener(Input_node[i], "focus", showHelp);
         if ( ! Input_node[i].nodeName.search(/^input$/i)  &&
              ! Input_node[i].type.search(/^text$/i)  &&
              Input_node[i].className.search(/tm_input_max/i) < 0 ) {
            addEventListener(Input_node[i], "keyup", resizeHandler);
         }
      }

      /* add function for the group selection button */
      Group_selector = dom.getElementById("tm_group_selector");
      if (Group_selector) {
         Group_button = Group_selector.firstChild;
         while (Group_button) {
            if (Group_button.nodeName.search(/^a$/i) === 0) {
               addEventListener(Group_button, "click", selectGroup);
            }
            Group_button = Group_button.nextSibling;
         }
      }

      /* search unknown given named parameter */
      if (Template_given && Template_used) {
         unknown_parameter = [ ];
         for ( id in Template_given ) {
            if ( ! (Template_used[id] && Template_used[id] === true)  &&
                 id !== "source"  &&
                 id !== "template_name"  &&
                 id !== "tm_form_parameter"/* ??? */ ) {
               name = id.substr( PAR_START.length );
               unknown_parameter.push( name );
            }
         }   // for id
         if (unknown_parameter.length > 0) {
            unknown_div = cNode( dom.getElementById("tm_group_selector"),
                                 "div",
                                 null,
                                 { "class": "tm_unknown_selector",
                                   "id"   : "tm_unknown_selector" } );
            for ( i = 0;  i < unknown_parameter.length;  i++ ) {
               Unknown_link = cNode(unknown_div,
                                    "a",
                                    unknown_parameter[i],
                                    { "class": "tm_button tm_selector tm_unknown_selector",
                                      "title": Template_given[ PAR_START + unknown_parameter[i] ]
                                    } );
               addEventListener(Unknown_link, "click", insertUnknown);
            }   // for i
         }
      }

      /* buttons */
      Button_submit = dom.getElementById("tm_submit");
      addEventListener(Button_submit, "click", submitTemplate);
      Button_cancel = dom.getElementById("tm_cancel");
      addEventListener(Button_cancel, "click", cancelTemplate);
      if ( is_xml_generated   &&   ! is_opera ) {
         Button_createXML = dom.getElementById("tm_createxml");
         setStyleAttribute( Button_createXML,
                            { visibility: "visible" } );
         Button_createXML.removeAttribute("disabled");
         if (Button_createXML) {
            addEventListener(Button_createXML, "click", createXML);
         }
      }

      /* last op (possible race condition!): enable Template_name node and buttons */
      $inputTemplateName.attr( "disabled", null );
      Button_cancel.removeAttribute("disabled");
      if (template_name !== false) {
         Button_submit.removeAttribute("disabled");
      }
      return dom;
   }   // tm_init().show_template().completeForm()



   function createForm( Xml_dom, Xsl_dom ) {
      var Result_dom,
          group_div,
          Processor,
          Result_div,
          result_xml,
          xslDoc,
          xslt;
         /* transform XML formular spec with loaded stylesheet */
      if ( typeof(XSLTProcessor) !== "undefined" ) {
         Processor = new XSLTProcessor();
         Processor.importStylesheet( Xsl_dom );
         Processor.setParameter(null, "locals_submit",
                                LOCALS.Submit);
         Processor.setParameter(null, "locals_cancel",
                                LOCALS.Cancel);
         Processor.setParameter(null, "locals_createxml",
                                LOCALS.createXML);
         Processor.setParameter(null, "locals_template",
                                LOCALS.template);
         Processor.setParameter(null, "locals_nohelp",
                                LOCALS.sys_no_help);
         Processor.setParameter(null, "locals_version",
                                VERSION);
         Result_dom = Processor.transformToDocument( Xml_dom );
      } else {
         Result_dom = null;
      }
      if ( ! Result_dom  &&  IS_IE ) {
         result_xml = null;
         if ( IS_IE <= 8 ) {
            if ( typeof( Xml_dom.transformNode ) !== "undefined" ) {
               result_xml = Xml_dom.transformNode( Xsl_dom.documentElement );
            }
         } else {
            try {
               xslt = new ActiveXObject( "Msxml2.XSLTemplate" );
               xslDoc = new ActiveXObject( "Msxml2.FreeThreadedDOMDocument" );
               xslDoc.loadXML( Xsl_dom.xml );
               xslt.stylesheet = xslDoc;
               Processor = xslt.createProcessor();
               Processor.input = Xml_dom;
               Processor.transform();
               result_xml = Processor.output;
            } catch (e) {
               log_message( "createForm(IE:ActiveXObject) " + e.message );
            }
         }
         if ( result_xml ) {
            result_xml = result_xml.replace("locals_submit",
                                            LOCALS.Submit)
                                   .replace("locals_cancel",
                                            LOCALS.Cancel)
                                   .replace("locals_createxml",
                                            LOCALS.createXML)
                                   .replace("locals_template",
                                            LOCALS.template)
                                   .replace(/locals_nohelp/g,
                                            LOCALS.sys_no_help)
                                   .replace("locals_version",
                                            VERSION);
            Result_div = cNode( null,
                                "div",
                                null,
                                { id:    "tm_dummy_ie_div",
                                  style: "visibility:hidden;" } );
            Result_div.innerHTML = result_xml;
            Root_node.appendChild( Result_div );
            Result_dom = document;
            group_div = document.getElementById( "tm_group_selector" );
            if ( ! group_div.firstChild ) {
               group_div.parentNode.removeChild( group_div );
            }
         }
      }
      if ( Result_dom ) {
         /* add program logic */
         Result_dom = completeForm( Result_dom );
      } else {
         log_message( "XSLTProcessor et al. unavailable" );
      }
      return Result_dom;
   }   // tm_init().show_template().createForm()



      function mwXmlHttpRequest( data ) {
         // Start possible actions on current page
         // Precondition:
         //    data.api      true  or  false->index.php
         //    data.pars     details
         //    data.onload   callback
         //    data.onerror  function on failure
         // Postcondition:
         //    ajax request launched
         // 2014-06-20 PerfektesChaos@de.wikipedia
         var defaults;
         if ( typeof xmlHTTP[ data.api ]  !==  "object" ) {
            if ( data.api ) {
               xmlHTTP[ true ] = new mw.Api();
            } else {
               defaults = { ajax:       { url:      mw.util.wikiScript(),
                                          dataType: "text" },
                            parameters: { action: "raw" } };
               xmlHTTP[ false ] = new mw.Api( defaults );
            }
         }
         xmlHTTP[ data.api ].get( data.pars )
                            .done( data.onload )
                            .fail( data.onerror );
      }   // tm_init().mwXmlHttpRequest()



   function makeXMLfromTemplateData( apply ) {
      // 2016-05-31
      var r = "",
          o, p, params, sign, slang, story;
      function f( assembly, access ) {
         var s, t;
         switch ( typeof assembly[ access ] ) {
            case "object" :
               if ( typeof slang  !==  "string" ) {
                  slang = mw.config.get( "wgContentLanguage" );
               }
               t = assembly[ access ];
               if ( t ) {
                  if ( typeof t[ slang ]  ===  "string" ) {
                     s = t[ slang ];
                  }
               }
               break;
            case "string" :
               s = assembly[ access ];
               break;
         }   // switch typeof component
         if ( s ) {
            s = s.replace( /^\s+/,    "" )
                 .replace( /\s+$/,    "" )
                 .replace( /&nbsp;/g, "&#160;" )
                 .replace( /\\/g,     "\\\\" );
         }
         return s;
      }   // tm_init().show_template().makeXMLfromTemplateData().f()
      if ( typeof apply.pages  ===  "object" ) {
         for ( p in apply.pages ) {
            o = apply.pages[ p ];
            break;
         }   // for  in .params
      }
      if ( o ) {
         if ( typeof o.params  ===  "object"   &&
              o.params ) {
            params = o.params;
            for ( sign in params ) {
               if ( sign   &&
                    typeof params[ sign ]  ===  "object" ) {
                  r     = r + '     <Parameter name="' + sign + '"';
                  p     = params[ sign ];
                  story = f( p, "label" );
                  if ( story ) {
                     r = r + ' label="'
                           + story.replace( /</g, "&lt;" )
                                  .replace( />/g, "&gt;" )
                           + '"';
                  }
                  if ( typeof p.required  ===  "boolean"   &&
                       p.required ) {
                     r = r + ' null="false"';
                  }
                  if ( typeof p.type  ===  "string" ) {
                     story = trim( p.type ).toLowerCase();
                     if ( ! story.indexOf( "string/" ) ) {
                        story = story.substr( 7 );
                     }
                     if ( story  &&  story !== "unknown" ) {
                        r = r + ' type="' + story + '"';
                     }
                  }
                  story = typeof p.deprecated;
                  if ( ( story === "boolean"  ||  story === "string" )
                         &&   p.deprecated ) {
                     r = r + ' deprecated="true"';
                  }
                  r = r + '>\n';
                  story = f( p, "description" );
                  if ( story ) {
                     r = r + '       <Help>'
                         + story.replace( /</g, "&lt;" )
                                .replace( /&nbsp;/g, "&#160;" )
                         + '</Help>\n';
                  }
                  if ( typeof p[ "default" ]  ===  "string" ) {
                     story = p[ "default" ].replace( /^\s+/, "" )
                                           .replace( /\s+$/, "" );
                     if ( story ) {
                        r = r + '       <Default>'
                           + story.replace( /</g, "&lt;" )
                           + '</Default>\n';
                     }
                  }
                  if ( typeof p.autovalue  ===  "string" ) {
                     story = p.autovalue.replace( /^\s+/, "" )
                                        .replace( /\s+$/, "" );
                     if ( story ) {
                        r = r + '       <AutoValue>'
                           + story.replace( /</g, "&lt;" )
                           + '</AutoValue>\n';
                     }
                  }
                  r = r + '     </Parameter>\n';
               }
            }   // for sign in .params
         }
      }
      r = '<?xml version="1.0" encoding="utf-8"?>\n'
          + ' <TemplateUsage output="collapse">\n'
          + '   <Group>\n'
          + r
          + '   </Group>\n'
          + ' </TemplateUsage>';
      return r;
   }   // tm_init().show_template().makeXMLfromTemplateData()



   function load_TemplateData( full_name ) {
      var s = full_name.replace( /\/.*$/, "" );
      mwXmlHttpRequest( {
           api:     true,
           pars:    { action: "templatedata",
                      titles: s },
         onload:  function( answer ) {
                     var story;
                     if ( answer ) {
                        $throbber.hide();
                        story = makeXMLfromTemplateData( answer );
                        parseUsage( story, s );
                     } else {
                        $throbber.hide();
                     }
                  },
         onerror: function() {
                     $throbber.hide();
                     log_message( LOCALS.sys_load_error.replace("$1",
                                                                template_name) );
                     switch_view_to( "EB" );
                  }
      } );
   }   // tm_init().show_template().load_TemplateData()



   function throbber( access ) {
      // Show throbber
      // Use: $throbber
      var spooling = "//upload.wikimedia.org/wikipedia/commons"
                     + "/d/de/Ajax-loader.gif",   // throbber URL
          $img, $root, $span;
      if ( $throbber ) {
         $throbber.find( "span" ).text( LOCALS[ access ] );
      } else {
         $throbber = $( "<div>" );
         $throbber.css( { "position": "absolute",
                          "left":     "50px",
                          "top":      "32px" } );
         $img = $( "<img />" );
         $img.attr( { src:    spooling,
                      id:     "ajax_throbber",
                      height: "32",
                      alt:    "Ajax" } );
         $throbber.append( $img );
         $span = $( "<span>" );
         $span.css( { "margin-left": "3em" } );
         $span.text( LOCALS[ access ] );
         $throbber.append( $span );
         $root = $( Root_node );
         $root.find( "#tm_main_frame" ).remove();
         $root.append( $throbber );
      }
      $throbber.show();
   } // tm_init().show_template().throbber()



   function load_templateXML( template_name ) {
      var full_name = getFullTemplatePagename( template_name );



      mwXmlHttpRequest( {
         api:     false,
         pars:    { title:  full_name + "/XML" },
         onload:  function( answer ) {
                     var s;
                     switch ( typeof answer ) {
                        case "string":
                           s = answer;
                           break;
                        case "object":
                           s = answer.responseText;
                           break;
                        default:
                           s = false;   // try TemplateData
                     }   // switch
                     if ( s ) {
                        $throbber.hide();
                        parseUsage( s, full_name );
                     } else {
                        throbber( "seekTD" );
                        load_TemplateData( full_name );
                     }
                  },
         onerror: function() {
                     throbber( "seekTD" );
                     load_TemplateData( full_name );
                  }
      } );
   }   // tm_init().show_template().load_templateXML()



   function parseUsage( source, full_name ) {
      // source: XML document
      var usage_text, Xml_dom, Xsl_dom;

      function onload() {
         var dom = createForm(Xml_dom, Xsl_dom);
         if (dom) {
            attachForm(dom);

            /* cache template */
            Template[template_name] = { };
            Template[template_name].Xml_dom = Xml_dom;
            Template[template_name].Xsl_dom = Xsl_dom;
         } else {
            switch_view_to( "EB" );
         }
      }   // tm_init().show_template().parseUsage().onload()



      try {
         Xml_dom = null;
         Xsl_dom = null;
         is_xml_generated = false;

         if ( source.length ) {
            usage_text = source;
         } else {
            mwXmlHttpRequest( {
                api:     true,
                pars:    { prop:    "revisions",
                           rvprop:  "content",
                           rvlimit: "1",
                           titles:  encodeURIComponent(full_name) },
                onload: function(rD) {
                           var endPos, i, names, rT, startPos, tmp,
                               varname, vars, xVarname;
                  try {
                     rT = rD.responseText;
                     startPos = rT.search('\\[\\{"\\*":"') + 7;
                     endPos   = rT.search('"\\}\\]\\}\\}\\},"');

                     if (endPos < 0) {
                        log_message(LOCALS.sys_no_such_template.replace("$1",
                                                                        template_name));
                        switch_view_to("EB");
                        return;
                     }

                     rT = rT.substring(startPos, endPos);
                     xVarname = /\{\{\{[\s]*([^\s\|\}]([^\|\}]*[^\s\|\}]){0,1})[\s\|\}]/g;
                     names = rT.match(xVarname);
                     vars = { };
                     if (names) {
                        for (i = 0; i < names.length; i++) {
                           tmp = names[i].replace(xVarname, "$1");
                           tmp = tmp.replace(/<[^>]+>/g, '');
                           tmp = decodeURI(tmp);
                           tmp = tmp.replace("\\u00f6", "ö")
                                    .replace("\\u00fc", "ü")
                                    .replace("\\u00e4", "ä")
                                    .replace("\\u00df", "ß")
                                    .replace("\\u00d6", "Ö")
                                    .replace("\\u00dc", "Ü")
                                    .replace("\\u00c4", "Ä");
                           vars[tmp] = true;
                        }
                     }
                     usage_text =  "<?xml version='1.0' encoding='utf-8'?>\n"
                                   + "<?mediawiki '{{XML-Warnung|"
                                              + template_name + "}}'?>\n"
                                   + " <TemplateUsage output='expand'>\n"
                                   + "   <Group>\n";
                     for (varname in vars) {
                        usage_text +=   "     <Parameter name='"
                                                       + varname + "'>\n"
                                      + "       <Help></Help>\n"
                                      + "     </Parameter>\n";
                     }
                     usage_text +=   "   </Group>\n"
                                   + " </TemplateUsage>\n";

                     Xml_dom = parseXML(usage_text);
                     Xsl_dom = get_xsl_dom();

                     is_xml_generated = true;
                     generated_xml    = usage_text;

                     onload();
                  } catch (e) {
                     log_message("parseUsage(onload) " + e.message);
                     switch_view_to("EB");
                  }
                        },   // onload:
               onerror: function() {
                  log_message(LOCALS.sys_load_error.replace("$1",
                                                            template_name) );
                  switch_view_to("EB");
                        }   // onerror:
            });
            return;
         }

         /* create document from XML text */
         Xml_dom = parseXML(usage_text);
         Xsl_dom = get_xsl_dom();

         /* load style sheet for the transformation */
//          var Xsl_dom = document.implementation.createDocument("", "", null);
//          Xsl_dom.addEventListener("load", onload, false);
//          Xsl_dom.load("http://tools.wikimedia.de/~revvar/tm_formular.xsl");

         /* next step "function onload" */
         onload();
      } catch(e) {
         log_message("parseUsage() " + e.message);
         switch_view_to("EB");
      }
   }   // tm_init().show_template().parseUsage()



   function pipeActive( assign ) {
      var i      = assign.indexOf( "|" ),
          scream = "sys_value_pipe_active",
          r;
      if ( i >= 0 ) {
         if ( ! REopen ) {
            REopen = new RegExp( "(\\[|\\{\\{)" );
         }
         if ( REopen.test( assign.substr( 0, i ) ) ) {
            if ( ! REclose ) {
               REclose = new RegExp( "(\\]|\\}\\})" );
            }
            i = assign.lastIndexOf( "|" );
            if ( ! REclose.test( assign.substr( i ) ) ) {
               r = scream;
            }
         } else {
            r = scream;
         }
      }
      return r;
   }   // tm_init().show_template().pipeActive()



   function restoreTemplate( name ) {
      var r = false,
          dom;
      if (Template[name]) {
         dom = createForm( Template[name].Xml_dom,
                           Template[name].Xsl_dom );
         if (dom) {
            attachForm(dom);
            r = true;
         }
      }
      return r;
   }   // tm_init().show_template().restoreTemplate()



   function submitTemplate(e) {
      var First_error_node = null,
          i = PAR_START.length,
          n = 0,
          reNumber = /^[1-9][0-9]*$/,
          success = true,
          unnamedEqual = false,
          group_count, group_template, group_showempty,
          id, lines, max_parameter_length,
          new_template, Node,
          output, parameter_space, prevEmptyNumbers,
          Range, space, scream, scroll_top, tmp_param;
      preventDefault(e);

      /* read all results and correct them if necessary */
      for ( id in Template_new ) {   // all template paremeter names
         Node = Template_new[id];
         if ( id.search( /^(source|template_name|tm_comment_)/ ) ) {
            Node.tm_parName = id.substr( i );
            if ( reNumber.test( Node.tm_parName ) ) {
               Node.tm_numbered = parseInt( Node.tm_parName );
               if ( Node.tm_numbered <= n ) {
                  log_message( "Internal / XML spec error: "
                               + "Positional order in object/XML. ("
                               + Node.tm_parName + ")" );
                  switch_view_to( "EB" );
                  return;
                  // Template_new should be Array rather than object.
               }
               n = Node.tm_numbered;
            }

            switch ( (""+Node.nodeName).toLowerCase() ) {
               case "textarea":
                  Node.tm_value = trim(Node.value);
                  lines = Node.tm_value.split("\n");
                  if ( lines.length - 1 > 1
                      && (lines[lines.length - 1].search(/[\S]/) < 0)) {
                     lines.pop();
                  }
                  Node.tm_value = lines.join("\n");
                  if ( lines.length > 1 ) {
                     Node.tm_value = "\n" + Node.tm_value;
                  }
                  break;
               case "input":
                  if ( (""+Node.type).toLowerCase() === "checkbox" ) {
                     if ( Node.checked === true ) {
                        Node.tm_value = trim(Node.value);
                     } else {
                        Node.tm_value = "";
                     }
                  } else {
                     Node.tm_value = trim(Node.value);
                  }
                  break;
               case "select":
                  Node.tm_value = trim(Node.value);
                  break;
               case "div":
                  break;
               default:
                  log_message( "Internal Error: Unknown Node type \""
                               + Node.nodeName + " (" + id + ")\"." );
                  switch_view_to( "EB" );
                  return;
            }   // switch
            if ( Node.tm_numbered  &&
                 ! unnamedEqual  &&
                 Node.tm_value.indexOf( "=" ) >= 0 ) {
               unnamedEqual = true;
            }

            /* verify values */
            if ( typeof Node.tm_value  ===  "string" ) {
               scream = false;
               if ( Node.getAttribute("tm_null") === "false"   &&
                    ! Node.tm_value ) {
                  scream = "sys_enter_value";
               } else {
                  scream = pipeActive( Node.tm_value );
               }
               if ( ! scream  &&
                    Node.tm_condition    &&
                    ( Node.getAttribute("tm_null") !== "true"   ||
                      Node.tm_value )    &&
                    Node.tm_value.search( Node.tm_condition ) ) {
                  scream = "sys_enter_valid_value";
               }
               if ( ! scream  &&  Node.tm_type  &&  Node.tm_value ) {
                  if ( Node.tm_value.search( Node.tm_type ) ) {
                     scream = "sys_enter_valid_value";
                  } else if ( Node.tm_legalWikipage  &&
                              ( Node.tm_value.indexOf( "[" )  >= 0   ||
                                Node.tm_value.indexOf( "]" )  >= 0 ) ) {
                     scream = "sys_enter_valid_value";
                  }
               }
               if ( ! scream   &&
                    Node.tm_autovalue   &&
                    ! Node.tm_value ) {
                  Node.tm_value = autovalue( Node.tm_autovalue );
               }
               if ( scream ) {
                  success = false;
                  if ( ! First_error_node ) {
                     First_error_node = Node;
                  }
                  Node.title = LOCALS[ scream ] + " *** " + Node.tm_help;
                  Node.className = "tm_input tm_error";
                  Node.setAttribute("tm_error", "true");
               } else {
                  Node.setAttribute("tm_error", "false");
                  Node.className = "tm_input";
                  Node.title = Node.tm_help;
               }
            }
         } else if ( id !== "source"  &&  id !== "template_name" ) {
            Node.tm_leader = true;
            Node.tm_value = "\0";
         }
      }   // for id in Template_new
      if ( ! success ) {
         if ( $Statebar ) {
            $Statebar.empty().html( LOCALS.sys_please_correct_errors )
                             .css( { "background-color": "#FFFF00" } );
         }
         First_error_node.focus();
         return;
      }

      if ( n && unnamedEqual ) {
         for ( id in Template_new ) {
            Node = Template_new[id];
            if ( Node.tm_numbered ) {
               Node.tm_numbered = false;
            }
         }   // for id in Template_new
      }

      /* create new template source */
      output = document.getElementById( "tm_main_frame" );
      if ( output ) {
         if ( output.getAttribute("tm_max_value_indentation") ) {
            max_value_indentation = 0
                       + output.getAttribute("tm_max_value_indentation");
         }
         output = ( output.getAttribute( "tm_output" ) === "expand" );
      } else {
         output = false;
      }

      new_template = "{{" + Template_new.template_name
                          + ( output ? "\n" : "" );
      group_count = 0;
      group_template = "";
      group_showempty = false;

      // get max parameter length
      max_parameter_length = 0;
      for ( id in Template_new ) {
         Node = Template_new[id];
         if ( Node.tm_parName  &&  Node.tm_value  &&
              ( output || Node.tm_value.length ) ) {
            if ( max_parameter_length < Node.tm_parName.length ) {
               max_parameter_length = Node.tm_parName.length;
            }
         }
      }   // for id in Template_new

      parameter_space = "";
      prevEmptyNumbers = "";
      if ( OPTIONS.lotsOfSpaces ) {
         space = " ";
      } else {
         n = ( max_parameter_length > max_value_indentation
               ? max_value_indentation
               : max_parameter_length );
         for ( i = 0;  i < n;  i++ ) {
            parameter_space += " ";
         }   // for i
         space = "";
      }
      for ( id in Template_new ) {
         Node = Template_new[id];
         if ( Node.tm_leader || Node.tm_parName ) {
            tmp_param = Node.tm_parName;
            if ( output ) {   // expand
               if ( ! id.search("tm_group_") ) {
                  if ( group_count || group_showempty ) {
                     new_template += group_template;
                  }
                  group_count = 0;
                  group_template = "";
                  group_showempty = Node.showempty;
               } else if ( id.search("tm_comment_") ) {
                  if (tmp_param.length < parameter_space.length) {
                     tmp_param = (tmp_param + parameter_space).substr(0,
                                                                      parameter_space.length);
                  }
                  group_template += space + "|";
                  if ( ! Node.tm_numbered ) {
                     group_template += tmp_param + "= ";
                  }
                  i = Node.tm_value.length;
                  if ( i   ||
                       Node.getAttribute("tm_predefined") === "false") {
                     group_template += Node.tm_value;
                     if ( i ) {
                        group_count++;
                     }
                  }
                  group_template += "\n";
               }
            } else if ( Node.tm_value  &&   Node.tm_value.length
                        &&  ! Node.tm_leader ) {
               tmp_param = tmp_param + space;
               new_template += prevEmptyNumbers;
               prevEmptyNumbers = "";
               if ( Node.tm_numbered ) {
                  new_template += space + "|"
                                  + Node.tm_value;
               } else {
                  new_template += space + "| " + tmp_param + "=" + space
                                  + Node.tm_value;
               }
            } else if ( Node.tm_numbered ) {
               prevEmptyNumbers += "|";
            }
         }
      }   // for id in Template_new
      if ( output  &&
           ( group_count || group_showempty ) ) {
         new_template += group_template;
      }
      new_template += space + "}}";

      switch_view_to("EB");

      /* insert source into Editbox at cursor */
      scroll_top = Target.Editbox.scrollTop;
      Target.Editbox.value = Target.Editbox.value.substring(0, Target.start)
                             + new_template
                             + Target.Editbox.value.substring(Target.end + 1);
      if ( IS_IE ) {
         Range = Target.Editbox.createTextRange();
         Range.collapse(true);
         Range.moveEnd("character", Target.start);
         Range.moveStart("character", Target.start);
         Range.select();
      } else {
         Target.Editbox.selectionStart = Target.cursor;
         Target.Editbox.selectionEnd = Target.cursor;
         Target.Editbox.scrollTop = scroll_top;
      }
      if ( typeof( OPTIONS.wikEd ) === "object"
           && window.wikEd.useWikEd ) {
         window.wikEd.UpdateFrame();
      }
      // CodeMirror
   } // tm_init().show_template().submitTemplate()



   function show_execute( Template_given, template_name ) {
      // check parameter
      if (Template_given  &&
          Template_given.template_name !== template_name) {
         template_name = Template_given.template_name;
      }

      if ( ! Template_given  &&  template_name === false ) {
         // create empty form
         Template_new = { };
         parseUsage( "<?xml version='1.0' encoding='utf-8'?>"
                     + "<TemplateUsage>"
                     +    "<Group></Group>"
                     + "</TemplateUsage>",
                     "" );
      } else {
         Template_new = { template_name: template_name };
         if ( restoreTemplate(template_name) !== true ) {
            throbber( "seekXML" );
            load_templateXML( template_name );
         }
         whenDOMready();
      }
   } // tm_init().show_template().show_execute()



   show_execute( Template_given, template_name );
}   // tm_init().show_template()



      function switch_view_to( view ) {
         var Editbox = document.getElementById( "wpTextbox1" );
         if ( ( view === "VM"  ||  ! view )
              &&   act_view === "EB" ) {
            if ( typeof( OPTIONS.wikEd ) === "object"
                 &&  OPTIONS.wikEd.live ) {
               window.wikEd.saveButton.disabled = true;
               window.wikEd.previewButton.disabled = true;
               window.wikEd.diffPreviewButton.disabled = true;
            } else if ( Editbox ) {
               setStyleAttribute( Editbox,
                                  { "visibility": "hidden" } );
               Editbox.readOnly = true;
               document.getElementById("wpSave").disabled = true;
               document.getElementById("wpPreview").disabled = true;
               document.getElementById("wpDiff").disabled = true;
            }
            Tm_box = document.getElementById( "tm_dummy_div" );
            if ( Tm_box ) {
               setStyleAttribute( Tm_box,
                                  { "visibility": "visible",
                                    "z-index":    "99" } );
            }
            act_view = "VM";
         } else if ( ( view === "EB"  ||  ! view )
                     &&   act_view === "VM" ) {
            if ( Tm_box ) {
               setStyleAttribute( Tm_box,
                                  { "visibility": "hidden",
                                    "z-index":    "0" } );
               if ( view === "EB" ) {
                  // removes user interface
                  Tm_box.parentNode.removeChild( Tm_box );
                  Tm_box = null;
               }
            }
            if ( typeof( OPTIONS.wikEd ) === "object"
                 &&  OPTIONS.wikEd.live ) {
               OPTIONS.wikEd.live = false;
               window.wikEd.useWikEd = true;
               window.wikEd.saveButton.removeAttribute("disabled");
               window.wikEd.previewButton.removeAttribute("disabled");
               window.wikEd.diffPreviewButton.removeAttribute("disabled");
               window.wikEd.SetEditArea( true, false );
               window.wikEd.frameWindow.focus();
            } else if ( Editbox ) {
               if ( view === "EB" ) {
                  Editbox.removeAttribute("readonly");
                  document.getElementById("wpSave").removeAttribute("disabled");
                  document.getElementById("wpPreview").removeAttribute("disabled");
                  document.getElementById("wpDiff").removeAttribute("disabled");
               }
               setStyleAttribute( Editbox,
                                  { "visibility": "visible" } );
               Editbox.focus();
            }
            act_view = "EB";
         } else if ( view !== act_view ) {
            log_message("Internal error: act_view='" + act_view
                        + "' conflicts with view parameter '"
                        + view + "'");
         }
      }   // tm_init().switch_view_to()



      function parse_template_source( source ) {
         var k = 0,
             re_back = new RegExp( escapeSyntax, "g" ),
             rep12 = "$1" + escapeSyntax + "$2",
             Template_given = { },
             x_comment = /<!--.*?-->/g,
             x_nowiki_1 = /(<\s*nowiki\s*>.*?)\|(.*?<\s*\/nowiki\s*>)/gi,
             x_nowiki_2 = /(<\s*nowiki\s*>.*?)=(.*?<\s*\/nowiki\s*>)/gi,
             x_wikilinks = /(\[\[[^\]]+)\|([^\]]*)/g,
             equals, i, par, parameter, par_name, par_value, re;

         source = replace_all(source, x_comment, "");

         /* replace split chars within nowiki segments and nested templates */
         source = replace_all(source, x_nowiki_1, rep12);

         /* replace split chars within wikilinks */
         source = replace_all(source, x_wikilinks, rep12);

         parameter = source.split("|");
         for ( i = 0;  i < parameter.length;  i++ ) {
            par = replace_all(parameter[i], re_back, "|");
            if (i) {
               par = replace_all( par, x_nowiki_2, rep12 );
               equals = par.search("=");
               if (equals < 0) {
                  k++;
                  par_name  = PAR_START + k;
                  par_value = trim(par);
               } else {
                  par_name  = PAR_START + trim(par.substring(0, equals));
                  par_value = trim(par.substring(equals + 1));
               }
               if (Template_given[ par_name ]) {
                  log_message( "Syntax error: Parameter name \""
                               + par_name.substr( PAR_START.length )
                               + "\" already in use.");
                  return null;
               }
               /* correct format errors */
               par_value = replace_all( par_value, re_back, "=" );
               Template_given[par_name] = par_value;
            } else {
               re = new RegExp( "^(Template|" + LOCALS.template + "): *(.*)$",
                                "i" );
               Template_given.template_name = trim(par);
               if ( ! Template_given.template_name.search( re ) ) {
                  Template_given.template_name = Template_given.template_name.replace(re, "$2");
               }
            }
         }   // for i
         Template_given.source = "source code";
         return Template_given;
      }   // tm_init().parse_template_source()



      /* == helper functions ==========================================*/



      function buttonWikiEditor() {
         try {
         $( "#wpTextbox1" ).wikiEditor( "addToToolbar",
                        { "section": "main",
                          "group":   "format",
                          "tools":   { "vorlagenmeister":
                                         { type:   "button",
                                           label:  LOCALS.me,
                                           icon:   BUTTONICON,
                                           action: { type:    "callback",
                                                     execute: show
                                                   }
                                         }
                                     }
                        } );
         } catch(e) {
            log_message("tm_init().buttonWikiEditor()\r\n" + e.message);
         }
      } // tm_init().buttonWikiEditor()



      function buttonToolbar() {
         var $toolbar = $( "#toolbar" ),
             BUTTONBASE = "//upload.wikimedia.org/wikipedia/commons/"
                          + "e/ec/Button_base.png",
             $btn, r, show;
         if ( $toolbar.length ) {
         try {
            r    = "tm_switch_button";
            $btn = $( "<div>" );
            $btn.attr( { "id":    r,
                         "class": r + " mw-toolbar-editbutton",
                         "title": LOCALS.me } );
            $btn.css( { "background-image": "url(" + BUTTONBASE + ")",
                        "display":          "inline",
                        "height":           "22px",
                        "width":            "23px" } );
            if ( typeof OPTIONS.toolbarLabel  ===  "string"
                 &&     OPTIONS.toolbarLabel ) {
               show = OPTIONS.toolbarLabel;
            } else {
               show = LOCALS.ButtonText;
            }
            $btn.text( show );
            $toolbar.prepend( $btn );
         } catch(e) {
            log_message("tm_init().buttonToolbar()\r\n" + e.message);
         }
         }
         return r;
      } // tm_init().buttonToolbar()



      function equipGUI() {
         var lucky  = false,
             opts   = mw.user.options.get( [ "showtoolbar",
                                             "usebetatoolbar" ] ),
             shower = false;
         if ( typeof( window.wikEd ) === "object" ) {
            OPTIONS.wikEd = { live: false };
            if ( typeof( window.wikEd.config ) === "object"   &&
                 typeof( window.wikEd.config.button ) === "object"   &&
                 typeof( window.wikEd.config.button[ 745 ] ) === "object" ) {
               OPTIONS.wikEd.click = show;
            }
         }
         if ( opts.usebetatoolbar ) {
            mw.loader.using( [ "ext.wikiEditor" ],
                             buttonWikiEditor );
            lucky = true;
         } else if ( opts.showtoolbar ) {
            shower = buttonToolbar();
            lucky  = shower;
         }
         if ( ! lucky ) {
            shower = "t-vorlagenmeister";
            try {
               mw.util.addPortletLink( "p-tb", "#", LOCALS.me, shower );
            } catch(e) {
               log_message("mw.util.addPortletLink()\r\n" + e.message);
            }
         }
         if ( shower ) {
            $( "#" + shower ).click( show );
         }
      } // tm_init().equipGUI()



      function init() {
         var sXML = mw.util.getParamValue( "tm_xml_content" ),
             userAgent;

         OPTIONS.loading = false;

         if ( sXML ) {
            $( "#wpTextbox1" ).val( sXML );
         } else {
            try {
               try {
                  LOCALS = I18N.fire();
               } catch(e) {
                  log_message("init() I18N.fire()\r\n" + e.message);
               }
               try {
                  Sanitize();
               } catch(e) {
                  log_message("init() Sanitize()\r\n" + e.message);
               }
               try {
                  equipGUI();
               } catch(e) {
                  log_message("init() equipGUI()\r\n" + e.message);
               }
               // globals
               PAR_START = "tm_form_";
               $Statebar = null;
               Template = { };
               Tm_box = null;
               act_view = "EB";
               Act_input = null;
               is_xml_generated = false;
               generated_xml = "";
               max_value_indentation = 32;
               resize_mutex = false;
               if ( ! IS_IE ) {
                  userAgent = $.client.profile();
                  is_gecko = ( userAgent.layout === "gecko" );
                  is_opera = ( userAgent.name === "opera" );
               }
            } catch(e) {
               log_message("init()\r\n" + e.message);
            }
         }
      } // tm_init().init()



      init();
   } // tm_init()



//## File: tm_w2t_infobox_schienenfahrzeug.js #################

/**
* Wiki2Template-Plugin des Vorlagen-Meister fuer die Vorlage "Infobox Schienenfahrzeug", Version: 0.1beta, Date: 2007-02-04
* Copyright (C) 2007 [[de:Benutzer:Revvar]] <revvar@gmx.de>
* Released under the GPL license version 2
* http://www.gnu.org/copyleft/gpl.html
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE.
* See the GNU General Public License for more details.
*/

function TM_P_Infobox_Schienenfahrzeug() {
   TM_P_Wiki2Template.call(this);

   var name = "Infobox Schienenfahrzeug";
   this.opGetName = function() {
      return name;
   };
   var template = "Infobox Schienenfahrzeug";
   this.opGetTemplate = function() {
      return template;
   };
   var super_opTransform = this.opTransform;
   this.opTransform = function(wiki_text) {
      wiki_text = super_opTransform(wiki_text);
      var Template = { };
      Template.template_name = template;
      Template.source = "plug-in";
      var line = wiki_text.split("\n");
      for (var i = 0; i < line.length; i++) {
         if (line[i].search(/\s*(\|-|\|\}|\{\|)/) !== 0
             &&  line[i].search(/\|\|/) > 0) {
            var entry = line[i].split("||");
            if (entry.length !== 2) {
               log_message("TM_P_Infobox_Schienenfahrzeug: Momentan wird nur ein ||-Trenner pro Zeile unterstützt.");
               return null;
            }
            var x_wikilink = /\[\[[^|]+\|([^\]]+)\]\]/;
            if (entry[0].search(x_wikilink) >= 0) {
               entry[0] = entry[0].replace(x_wikilink, "$1");
            }
            entry[0] = entry[0].replace(/^\s*\|\s*/g, "").replace(/^\s*(\S.*\S)\s*$/g,"$1").replace(/[^a-zA-ZäöüÄÖÜß0-9_]/g,"");
            entry[1] = entry[1].replace(/^\s*(\S.*\S)\s*$/g,"$1");
            if ( entry[1].charCodeAt( 0 )  ===  124 ) {   // '|'
               entry[1] = entry[1].substring(1);
            }
            if ( ! entry[0].search(/^Indienststellung$/i) ) {
               entry[0] = "Baujahre";
            }
            if ((entry[1].search(/^\s*k\s*\.\s*A\s*(\.){0,1}\s*$/) < 0) && (entry[1].search(/^\s*-+\s*/) < 0)) {
               Template[ PAR_START + entry[0] ] = entry[1];
            }
         } else if (line[i].search(/^\s*!.*((color:|background)[^\|]*){2,2}\|.*/) === 0) {
            var base_color_name = {"aqua":"00ffff", "black":"000000", "blue":"0000ff", "fuchsia":"ff00ff", "gray":"808080", "green":"008000", "lime":"00ff00", "maroon":"800000", "navy":"000080", "olive":"808000", "purple":"800080", "red":"ff0000", "silver":"c0c0c0", "teal":"008080", "white":"ffffff", "yellow":"ffff00"};
            // Baureihe, Farbe1 und Farbe2
            var baureihe = line[i].substring(line[i].search(/\|/) + 1).replace(/^\s*(\S.*\S)\s*$/g,"$1");
            var farbe2 = line[i].replace(/^.*[^a-zA-Z]color\s*:\s*(#[a-fA-F0-9]{6,6}|[a-zA-Z]+).*/,"$1").replace(/^\s*(\S.*\S)\s*$/g,"$1");
            var farbe1 = line[i].replace(/^.*[^a-zA-Z]background(-color){0,1}\s*:\s*(#[a-fA-F0-9]{6,6}|[a-zA-Z]+).*/,"$2").replace(/^\s*(\S.*\S)\s*$/g,"$1");
            if (farbe1.charCodeAt( 0 )  ===  35 ) {   // '#'
               farbe1 = farbe1.substring(1);
            }
            else if (base_color_name[farbe1.toLowerCase()]) {
               farbe1 = base_color_name[farbe1.toLowerCase()];
            }
            else {
               farbe1 = null;
            }
            if (farbe2.charCodeAt( 0 )  ===  35 ) {   // '#'
               farbe2 = farbe2.substring(1);
            } else if (base_color_name[farbe2.toLowerCase()]) {
               farbe2 = base_color_name[farbe2.toLowerCase()];
            } else {
               farbe2 = null;
            }
            Template[PAR_START + "Baureihe"] = baureihe;
            if (farbe1) {
               Template[PAR_START + "Farbe1"] = farbe1;
            }
            if (farbe2) {
               Template[PAR_START + "Farbe2"] = farbe2;
            }
         } else if (line[i].search(/^\s*(!|\|[^\-]).*\[\[(Bild|Image):[^\]]+\]\]/) === 0) {
            var bild = line[i].replace(/^\s*(!|\|).*\[\[(Bild|Image):([^\]]+)\]\].*/,"$3");
            bild = bild.split("|");
            Template[PAR_START + "Abbildung"] = bild[0];
            for (var k = 1; k < bild.length; k++) {
               if (bild[k].search("[0-9]px") < 0) {
                  Template[PAR_START + "Name"] = bild[k].replace(/^\s*(\S.*\S)\s*$/g,"$1");
               }
            }   // for k
         }
      }
      return Template;
   };
}   // TM_P_Infobox_Schienenfahrzeug()
TM_P_Infobox_Schienenfahrzeug.prototype=new TM_P_Wiki2Template();

TM_PluginList.push(new TM_P_Infobox_Schienenfahrzeug()); // register plugin



   // ###################################################################



   function initialize() {
      // Start action on current page
      // Precondition:
      //    configs have been loaded
      // Postcondition:
      //    tm_init() will be called upon document.ready
      // 2014-07-21 PerfektesChaos@de.wikipedia
      BUTTONICON = "//upload.wikimedia.org/wikipedia/commons/"
                   + "e/eb/Button_templatelink.png";
      if ( mw.user.options.get( "gadget-wikEd" )
           ||  typeof( window.wikEd ) === "object" ) {
         if ( typeof( window.wikEd ) !== "object" ) {
            window.wikEd = {  config: { }  };
         }
         if ( typeof( window.wikEd.config ) !== "object" ) {
            window.wikEd.config = { button:    { },
                                    buttonBar: { } };
         }
         if ( typeof( window.wikEd.config.button  ) !== "object" ) {
            window.wikEd.config.button = { };
         }
         window.wikEd.config.button[ 745 ] = [ "wikEdVorlagenmeister",
                                               "wikEdButton",
                                               "Vorlagenmeister",
                                               BUTTONICON, "16", "16",
                                               "DIV",
                                               "window.mediaWiki.libs."
                                               + MW_LIB
                                               + ".wikEd.click();"
                                             ];
         if ( typeof( window.wikEd.config.buttonBar ) !== "object" ) {
            window.wikEd.config.buttonBar = { };
         }
         if ( typeof( window.wikEd.config.buttonBar.custom1 ) !== "object" ) {
            window.wikEd.config.buttonBar.custom1 =
                                               [ "wikEdButtonBarCustom1",
                                                 "wikEdButtonBarCustom1",
                                                 "wikEdButtonsCustom1",
                                                 "wikEdButtonsCustom1",
                                                 44,
                                                 "Meine Buttons",
                                                 [ ]
                                               ];
         }
         window.wikEd.config.buttonBar.custom1[ 6 ].push( 745 );
      }
      $( tm_init );
   }   // initialize()



   function loadStyleIE( area, access ) {
      // Load stylesheet where mw.loader.load() fails for IE.
      // Precondition:
      //    mw.util.wikiScript() :: mediawiki.util
      //    mw.Api() :: mediawiki.api
      //    mediawiki.api has been loaded
      // 2014-08-04 PerfektesChaos@de.wikipedia
      var defaults = { ajax: { url:  area + mw.util.wikiScript( "api" )
                             }
                     },
          done = function ( arrived ) {
                     var q, $style;
                     if ( typeof arrived  ===  "object"   &&
                          typeof arrived.query  ===  "object"   &&
                          typeof arrived.query.pages  ===  "object"   &&
                          typeof arrived.query.pageids  ===  "object" ) {
                        q  =  arrived.query;
                        q  =  q.pages[ q.pageids[ 0 ] ];
                        if ( typeof q  ===  "object"   &&
                             typeof q.revisions  ===  "object" ) {
                           q  =  q.revisions[ 0 ];
                           if ( typeof q  ===  "object"   &&
                                typeof q[ "*" ]  ===  "string" ) {
                              $style = $( "<style>"
                                       + q[ "*" ]
                                       + "</style>" );
                              $style.attr( { title: "loadStyleIE",
                                             type:  "text/css" } );
                              $( "head" ).append( $style );
                           }
                        }
                     }
                  },
          params = { prop:         "revisions",
                     indexpageids: true,
                     rvprop:       "content",
                     rvlimit:      "1",
                     titles:       access
                   },
          request = new mw.Api( defaults );
      request.get( params )
             .done( done );
   }   // loadStyleIE()



   function autoRun() {
      // Start possible actions on current page
      // Precondition:
      //    jquery.client and configs have been loaded
      //    $.client() :: jquery.client
      // Postcondition:
      //    initialize() will be called, if appropriate
      //    IS_IE has been defined
      // 2016-11-01 PerfektesChaos@de.wikipedia
      var env    = mw.config.get( [ "wgAction",
                                    "wgIsProbablyEditable",
                                    "wgNamespaceNumber",
                                    "wgPageContentModel",
                                    "wgScript",
                                    "wgServer",
                                    "wgTitle" ] ),
          server = "//de.wikipedia.beta.wmflabs.org",
          sheet  = "MediaWiki:Gadget-Vorlagenmeister.css",
          legacy, maxage, userAgent;
      if ( ( env.wgAction === "edit"  ||  env.wgAction === "submit" )  &&
           env.wgIsProbablyEditable  &&
           env.wgPageContentModel === "wikitext"  &&
           ! ( env.wgNamespaceNumber === 10  &&
               /\/XML$/.test( env.wgTitle ) ) ) {
         if ( env.wgServer.indexOf( server )  <  0 ) {
            server = "https://de.wikipedia.org";
            maxage = 1209600;   // 14 d
         } else {
            maxage = 0;
         }
         userAgent = $.client.profile();
         IS_IE     = ( userAgent.name === "msie" );
         if ( IS_IE ) {
            IS_IE = userAgent.versionNumber;
            /*
            if ( userAgent.versionNumber >= 9 ) {
               IS_IE_9plus  = userAgent.versionNumber;
            }
            */
            legacy = ( IS_IE < 11 );
         } else {
            legacy = false;
         }
         if ( legacy ) {
            // Old IE (like IE8) ignore <link rel="stylesheet">
            // if arriving after document.load has been reached.
            mw.loader.using( [ "mediawiki.api" ],
                             function () {
                                loadStyleIE( server, sheet );
                             } );
         } else {
            sheet = server + env.wgScript
                    + "?title=" + sheet
                    + "&bcache=1&maxage=" + maxage
                    + "&action=raw&ctype=text/css";
            mw.loader.load( sheet, "text/css" );
         }
         mw.loader.using( [ "mediawiki.api",
                            "mediawiki.user",
                            "mediawiki.util",
                            "jquery.tipsy" ],   // DEPRECATED (known)
                          initialize );
      }
   }   // autoRun()



   if ( mw.loader.getState( SIGNATURE ) !== "ready" ) {
      if ( typeof( mw.libs[ MW_LIB ] ) !== "object"   ||
           ! mw.libs[ MW_LIB ] ) {
         mw.libs[ MW_LIB ] = { };
      }
      mw.libs[ MW_LIB ].type = MW_LIB;
      OPTIONS                = mw.libs[ MW_LIB ];
      OPTIONS.vsn = VERSION;
      mw.loader.using( [ "jquery.client",
                         "site",
                         "user",
                         "user.options" ],
                       autoRun );
      rLoader[ SIGNATURE ] = "ready";
      mw.loader.state( rLoader );
      mw.hook( OPTIONS.type + ".ready" ).fire( OPTIONS );
   }
}( window.mediaWiki, window.jQuery ) );



// Emacs
// Local Variables:
// coding: utf-8-dos
// fill-column: 80
// End: