User:KokoroSenshi/MediaWiki:Gadget-Sandbox1.js: Difference between revisions

From Zelda Wiki, the Zelda encyclopedia
Jump to navigation Jump to search
m (Converted to use tabs; Changed description)
m (See if I can fix MediaWiki:UploadPreview.js)
Line 1: Line 1:
// --------------------------------------------------------
// <source lang="javascript">
// Staff Highlighting (adapted from http://en.wikipedia.org/wiki/User:Ais523/adminrights.js)
// This script changes the color of links to staffs' userpages in the bodyContent of
// various pages including Special, History pages, diff pages, and old page revisions.
// ("bodyContent" being the content below the page title).
// Based on [[User:ais523/highlightmyname.js]].
// --------------------------------------------------------


var adminrights   = {},
/*
    traineerights = {},
   Preview button for file uploads. Adapted from http://commons.wikimedia.org/wiki/MediaWiki:UploadForm.js by Lupo, March 2008.
    execrights    = {},
  Adaptation by http://rationalwiki.org/wiki/User:Nx
    botrights    = {},
  Source: http://rationalwiki.org/wiki/MediaWiki:UploadPreview.js
    retiredrights = {};
  Modified for compatibility with Zelda Wiki's FileInfo template.
  License: GPL
*/


adminrights = {
var canonicalNamespace = mw.config.get("wgCanonicalNamespace");
"52katie"           :1,
var canonicalSpecialPageName = mw.config.get("wgCanonicalSpecialPageName");
Clefairy52          :1,
var script = mw.config.get("wgScript");
Androidos18          :1,
var scriptPath = mw.config.get("wgScriptPath");
Astroninja1          :1,
var articlePath = mw.config.get("wgArticlePath");
AzelleAx            :1,
var server = mw.config.get("wgServer");
Azelleax            :1,
 
Chuck               :1,
var wpPreviewUploadLbl = "Show preview";
Caralista            :1,
var wpPreviewUploadTooltip = "Preview your changes, please use this before saving!";
EzloSpirit          :1,
var wpPreviewOverwriteError ='You will upload over an already existing file.'
Ezlospirit           :1,
    +'If you proceed, the information in this form will not appear on the description page.';
KokoroSenshi         :1,
 
Link_Lab             :1,
var wpCategoriesUploadLbl = "Categories:";
Midoro              :1,
 
Pixel                :1,
 
SnorlaxMonster       :1,
if (typeof (UploadForm) == 'undefined') {
Snorlaxmonster       :1,
 
Vaati_The_Wind_Demon :1
var UploadForm = {
};
 
  isInstalled : false,
  isReupload : false,
  the_form : null,
 
  install : function() {
    if (UploadForm.isInstalled) return; // Do this only once per page!
    UploadForm.isInstalled = true;
 
    if (document.URL.indexOf ('uploadpreview=disabled') >= 0) return; // We're disabled
 
    //Only on Special:Upload
    if (canonicalNamespace != 'Special' || canonicalSpecialPageName != 'Upload') return;
    var form =    document.getElementById ('upload')
              || document.getElementById ('mw-upload-form');
    var original_desc = document.getElementById ('wpUploadDescription');
    if (!form || !original_desc) return; // Oops. Not good: bail out; don't do anything.
    var reupload = document.getElementById ('wpForReUpload');
    var destFile = document.getElementById ('wpDestFile');
    if (reupload)
      UploadForm.isReupload = !!reupload.value;
    else {
      UploadForm.isReupload = destFile && (destFile.disabled || destFile.readOnly);
    }
    if (destFile && !!destFile.disabled) {
      destFile.readOnly = true;
      destFile.disabled = false;
    }
    if (destFile && UploadForm.isReupload) {
      destFile.onkeyup = function (evt) {};
      destFile.onchange = function (evt) {};
    }
    UploadForm.the_form = form;
    if (!UploadForm.isReupload) {
      UploadForm.check_initial_dest_file ();
      UploadForm.addPreviewButton();
    }
  },
 
  check_initial_dest_file : function ()
  {
    var dest_file = document.getElementById ('wpDestFile');
    if (  dest_file && dest_file.value && dest_file.value.length > 0
        && wgUploadWarningObj && typeof (wgUploadWarningObj.keypress) == 'function')
    {
      wgUploadWarningObj.keypress();
    }
  },
 
  makePreview : function (description, is_overwrite)
  {
    if ( is_overwrite )
    {
      UploadForm.showPreview (
          '\<div style="border:1px solid red; padding:0.5em;"\>'
        + '\<div class="error"\>'
        + wpPreviewOverwriteError
        + '\<\/div\>'
        + '\<\/div\>'
      );
    } else {
      var text = '\<div style="border:1px solid red; padding:0.5em;"\>\n'
              + '\<div class="previewnote"\>\n'
              + '\{\{int:previewnote\}\}\n'
              + '\<\/div>\n';
      var source  = document.getElementsByName("wpsource")[0].value;
      var game =  document.getElementById ('wpgames');
      var game_text = '';
      if (  game != null && game.selectedIndex >= 0
          && game.options[game.selectedIndex].value.length > 0) {
        game_text = game.options[game.selectedIndex].value;
      }
      var filetype =  document.getElementById ('wpfiletype');
      var filetype_text = null;
      if (  filetype != null && filetype.selectedIndex >= 0
          && filetype.options[filetype.selectedIndex].value.length > 0) {
        filetype_text = filetype.options[filetype.selectedIndex].value;
      }
      var license = document.getElementById ('wplicenses');
      var license_text = null;
      if (  license != null && license.selectedIndex >= 0
          && license.options[license.selectedIndex].value.length > 0) {
        license_text = license.options[license.selectedIndex].value;
      }
 
      text = "<h2>Preview</h2>\n{{FileInfo|summary=" + description + "|type=" + filetype_text + "|source=" + source +  "|game=" + game_text + "|licensing=" + license_text + "}}";
      // Make the Ajax call
      var req = sajax_init_object ();
      if (!req) return;
      var button = document.getElementById ('wpUploadPreview');
      var page  = document.getElementById ('wpDestFile');
      if (page) page = page.value;
      if (page != null && page.length == 0) page = null;
      if (button && typeof (injectSpinner) == 'function')
        injectSpinner (button, 'wpUploadPreviewSpinner');
      var uri  = server + scriptPath + '/api.php';
      var args = 'action=parse&pst&text=' + encodeURIComponent (text)
               + (page ? '&title=File:' + encodeURIComponent (page.replace (/ /g, '_')) : "")
              + '&prop=text|categories&format=json';
      // "&pst" is "Pre-save transform": tilde replacement, pipe magic for links like [[foo|foo]].
      // Don't use a callback directly, add the function call ourselves *after* the call, since
      // the API somehow resolves tildes to an IP number instead of the username if a callback
      // is used. C.f. https://bugzilla.wikimedia.org/show_bug.cgi?id=16616
      // Apparently, that's a feature, not a bug...
      var request_length = uri.length + args.length + 1;
      if (!!window.ActiveXObject && request_length > 2000 || request_length > 8100) {
        // IE has a URL limit of 2083 character (2048 in the path), WMF servers appear to have an 8kB
        // limit;
        req.open ('POST', uri, true);
        req.setRequestHeader ('Content-Type', 'application/x-www-form-urlencoded');
      } else {
        uri += '?' + args; args = null;
        req.open ('GET', uri, true);
      }
      req.setRequestHeader ('Pragma', 'cache=no');
      req.setRequestHeader ('Cache-Control', 'no-transform');
      req.onreadystatechange =
        function ()
        {
           if (req.readyState != 4) return;
          if (typeof (removeSpinner) == 'function') removeSpinner ('wpUploadPreviewSpinner');
          if (req.status != 200) return;
          // Add the "callback"...
          if (req.responseText && req.responseText.indexOf ('{') == 0)
            // Primitive sanity check. If the response text does *not* start with '{', it might have been
            // spoofed and contain a function call... of course, this simple check cannot catch more
            // elaborate spoof attempts.
            eval ('UploadForm.jsonPreview (' + req.responseText + ')');
        };
      req.send (args);
    }
  },
 
  jsonPreview : function (result)
  {
    if (result && result.parse && result.parse.text && result.parse.text['*'] != null) {
      var txt = result.parse.text['*'];
      var categories = result.parse.categories;
      if (categories && categories.length > 0) {
        // Add a mock-up of a category bar. We don't care about non-existing categories, and we
         // can't identify hidden categories.
        var catbar = '<div class="catlinks"><div id="mw-normal-catlinks">'
                  + wpCategoriesUploadLbl;
        categories.sort (
          function (a, b) {
            var key_a = a['*'].toLowerCase (), key_b = b['*'].toLowerCase ();
            if (key_a < key_b) return -1;
            if (key_a > key_b) return 1;
            return 0;
          }
        );
        for (var i = 0; i < categories.length; i++) {
          var catname = categories[i]['*'];
          if (catname && catname.length > 0) {
            if (i > 0) catbar += ' |';
             catbar += ' <a ' + 'href="/Category:' + encodeURI (catname) + '">'
                      + catname.replace(/_/g, ' ') + '</a>';
          }
        }
        catbar += '</div></div>';
        // Now insert it into text.
        var end = txt.lastIndexOf ('</div>');
        txt += catbar;
      }
      UploadForm.showPreview (txt);
    }
  },
 
  isOverwrite : function () {
    if (document.getElementById ('wpUploadWarningFileexists') != null) return true;
    var destfile_warning = document.getElementById ('wpDestFile-warning');
    if (destfile_warning == null) return false;
    var dest_file = document.getElementById ('wpDestFile');
    if (dest_file == null || dest_file.value == null || dest_file.value.length == 0) return false;
    var lks = destfile_warning.getElementsByTagName ('a');
    if (lks == null || lks.length == 0) return false;
    var fn1 =
      dest_file.value.replace(/^\s\s*/, '').replace(/\s\s*$/, '').replace(/ /g, '_');
    fn1    = fn1.substr (0, 1).toUpperCase () + fn1.substring (1);
    var fn0 = 'Image:' + fn1;
    fn1    = 'File:' + fn1;
    // Trimmed, blanks replaced by underscores, first character capitalized
 
    for (var i = 0; i < lks.length; i++) {
      var href = lks[i].getAttribute ('href', 2);
      if (href.indexOf (script + '?') == 0 || href.indexOf (server + script + '?') == 0) {
        var m = /[&?]title=([^&]*)/.exec (href);
        if (m && m.length > 1) href = m[1]; else href = null;
      } else {
        var prefix = articlePath.replace ('$1', "");
        if (href.indexOf (prefix) != 0) prefix = server + prefix; // Fully expanded URL?
        if (href.indexOf (prefix) == 0) href = href.substring (prefix.length); else href = null;
       }
      if (!href) continue;
      href = decodeURIComponent (href).replace (/ /g, '_');
       if (href == fn0 || href == fn1) return true;
    }
    return false;
  },
 
  isChildOf : function (child, ancestor)
  {
    if (!ancestor) return false;
    while (child && child != ancestor) child = child.parentNode;
    return (child == ancestor);
  },
 
  showPreview : function (result)
  {
    var preview = document.getElementById ('wpUploadPreviewDisplay');
    if (preview == null) {
      var before = document.getElementById ('mw-upload-permitted');
      if (!before || UploadForm.isChildOf (before, UploadForm.the_form))
        before = UploadForm.the_form;
          if (!before) return; // Don't know where to insert preview display. Error message here?
        preview = document.createElement ('div');
        preview.setAttribute ('id', 'wpUploadPreviewDisplay');
        before.parentNode.insertBefore (preview, before);
    }
    try {
      preview.innerHTML = result;
    } catch (ex) {
      preview.innerHTML = ""; // Error message here instead?
    }
    preview.style.display = ""; // Show it
    preview.scrollIntoView();
  },
 
  addPreviewButton : function ()
  {
    var request = sajax_init_object ();
    // If we don't have Ajax, our preview won't work anyway.
    if (request == null) return;
    var uploadButton = document.getElementsByName ('wpUpload')[0]; // Has no ID...
    // If we can't find the upload button, we don't know where to insert the preview button.
    if (uploadButton == null) return;


traineerights = {
    var previewButton = document.createElement ('input');
Barquero              :1,
    previewButton.setAttribute ('id', 'wpUploadPreview');
Mrbarquero            :1,
    previewButton.setAttribute ('name', 'wpUploadPreview');
Barquero13095        :1,
    previewButton.type    = 'button';
Bwar                  :1,
    previewButton.accessKey = 'p';
Bwar1133              :1,
    previewButton.value  = wpPreviewUploadLbl;
Tralinde              :1,
    previewButton.title  = wpPreviewUploadTooltip + ' [p]';
Ganman3              :1,
    previewButton.onclick = UploadForm.preview;
Djanonx              :1,
Legend_of_Zelda_Freak :1,
Hylian_Pi            :1,
Hylian_pi            :1,
Paragonfishhead      :1,
Jjgodden              :1,
benfitzy              :1,
Benfitzy              :1,
MannedTooth          :1
};


execrights = {
    previewButton.setAttribute ('style', 'margin-left: 0.5em;');
Calebzw      :1,
     updateTooltipAccessKeys([previewButton]);
Cody        :1,
    uploadButton.parentNode.insertBefore (previewButton, uploadButton.nextSibling);
Cody2958     :1,
   },
Codydaviestv :1,
GoldenChaos  :1,
Hylian_King  :1,
HylianKing   :1,
Jason        :1,
Joshua      :1,
Justin      :1,
Justin4408  :1,
Shona        :1,
Shona3212    :1,
Tony        :1,
TriforceTony :1
};


botrights = {
  preview : function (evt)
Ashler89          :1,
  {
KaeporaGaebora     :1,
     var overwrite = UploadForm.isOverwrite ();
KaeporaGaebora4988 :1,
Redirect_fixer     :1,
     var desc = document.getElementById ('wpUploadDescription');
The_Groosenator    :1,
    UploadForm.makePreview (desc.value, overwrite);
Yuga              :1,
    return true;
Yuga17953          :1,
  }
Rescue_Knight      :1,
};


retiredrights = {
Abdullah            :1,
Abdullah5599        :1,
Adam                :1,
Adam660              :1,
Alexander            :1,
Ando                :1,
Aranok              :1,
AtrumLevis          :1,
Autydi              :1,
Axiomist            :1,
Axle_the_Beast      :1,
Bob23                :1,
Captain_Cornflake    :1,
Captain_Desdinova    :1,
Cartoons            :1,
Chocoroko            :1,
Chrono              :1,
Cipriano            :1,
Dannyboy601          :1,
Dany36              :1,
Davogones            :1,
Deku_Link            :1,
DIUM                :1,
Dustin              :1,
EA                  :1,
Einstein95          :1,
Eientei95            :1,
Embyr_75            :1,
EpicFaceLOL991      :1,
Fizzle              :1,
Fox                  :1,
Fury_Three          :1,
Gateway2Drillbit    :1,
"Hammer_Bro._Mike"  :1,
Henhouse            :1,
Ice_Medallion        :1,
Jin                  :1,
JohnGames            :1,
K2L                  :1,
Kain                :1,
Lahvu                :1,
Lars                :1,
Lee                  :1,
LegendZelda          :1,
Leminnes            :1,
Liyuanzao            :1,
"Lord-of-shadow"    :1,
Lord_of_the_Twilight :1,
Lozzie              :1,
Mandi                :1,
Mases                :1,
Matt                :1,
Melchizedek          :1,
Minish_Link          :1,
"Mr._Wiggles"        :1,
Nathan              :1,
Noble_Wrot          :1,
Nox                  :1,
Owl                  :1,
Peefy                :1,
Petenu              :1,
PPLToast            :1,
Sadida              :1,
Sagasaki            :1,
Scott                :1,
SearanoX            :1,
Shetani              :1,
Shiningpikablu252    :1,
Sluzorz              :1,
Steven              :1,
Steven2113          :1,
Tappy                :1,
The_Forbidden_One    :1,
TheDarkHunter        :1,
Thewindmaker        :1,
Toby                :1,
Trico                :1,
Triforce_of_the_Gods :1,
Wielder_of_the_Sword :1,
WilliamLC            :1,
Xizor                :1,
Yami                :1
};
};


var action = mw.config.get("wgAction"),
}
    canonicalNamespace = mw.config.get("wgCanonicalNamespace");
$(document).ready(UploadForm.install);


if (  canonicalNamespace == 'Special'
// </source>
  || canonicalNamespace == 'Help'
  || action == 'history'
  || document.URL.indexOf('&diff=') > 0
  || document.URL.indexOf('&oldid=') > 0) {
$(document).ready(function() {
$("#bodyContent a").each(function() {
var n = $(this),
u = null,
linkHref = $(this).attr('href');
if (linkHref.substr(0,6) === "/User:") {
u = linkHref.substr(6);
} else if (linkHref.substr(0,22) === "/index.php?title=User:") {
u = linkHref.substr(22);
}
if (u !== null) {
if      (adminrights[u] === 1)  n.addClass("admin");
else if (traineerights[u] === 1) n.addClass("trainee admin");
else if (execrights[u] === 1)    n.addClass("executive");
else if (botrights[u] === 1)    n.addClass("bot");
else if (retiredrights[u] === 1) n.addClass("retired");
}
});
});
}

Revision as of 13:32, 30 June 2017

// <source lang="javascript">

/*
  Preview button for file uploads. Adapted from http://commons.wikimedia.org/wiki/MediaWiki:UploadForm.js by Lupo, March 2008. 
  Adaptation by http://rationalwiki.org/wiki/User:Nx
  Source: http://rationalwiki.org/wiki/MediaWiki:UploadPreview.js
  Modified for compatibility with Zelda Wiki's FileInfo template.
  License: GPL
*/

var canonicalNamespace = mw.config.get("wgCanonicalNamespace");
var canonicalSpecialPageName = mw.config.get("wgCanonicalSpecialPageName");
var script = mw.config.get("wgScript");
var scriptPath = mw.config.get("wgScriptPath");
var articlePath = mw.config.get("wgArticlePath");
var server = mw.config.get("wgServer");

var wpPreviewUploadLbl = "Show preview";
var wpPreviewUploadTooltip = "Preview your changes, please use this before saving!";
var wpPreviewOverwriteError ='You will upload over an already existing file.'
     +'If you proceed, the information in this form will not appear on the description page.';

var wpCategoriesUploadLbl = "Categories:";


if (typeof (UploadForm) == 'undefined') {

var UploadForm = {

  isInstalled : false,
  isReupload : false,
  the_form : null,

  install : function() {
    if (UploadForm.isInstalled) return; // Do this only once per page!
    UploadForm.isInstalled = true;

    if (document.URL.indexOf ('uploadpreview=disabled') >= 0) return; // We're disabled

    //Only on Special:Upload
    if (canonicalNamespace != 'Special' || canonicalSpecialPageName != 'Upload') return;
    var form =    document.getElementById ('upload')
               || document.getElementById ('mw-upload-form');
    var original_desc = document.getElementById ('wpUploadDescription');
    if (!form || !original_desc) return; // Oops. Not good: bail out; don't do anything.
    var reupload = document.getElementById ('wpForReUpload');
    var destFile = document.getElementById ('wpDestFile');
    if (reupload)
      UploadForm.isReupload = !!reupload.value;
    else {
      UploadForm.isReupload = destFile && (destFile.disabled || destFile.readOnly);
    }
    if (destFile && !!destFile.disabled) {
      destFile.readOnly = true;
      destFile.disabled = false;
    }
    if (destFile && UploadForm.isReupload) {
      destFile.onkeyup = function (evt) {};
      destFile.onchange = function (evt) {};
    }
    UploadForm.the_form = form;
    if (!UploadForm.isReupload) {
      UploadForm.check_initial_dest_file ();
      UploadForm.addPreviewButton();
    }
  },

  check_initial_dest_file : function ()
  {
    var dest_file = document.getElementById ('wpDestFile');
    if (   dest_file && dest_file.value && dest_file.value.length > 0
        && wgUploadWarningObj && typeof (wgUploadWarningObj.keypress) == 'function')
    {
      wgUploadWarningObj.keypress();
    }
  },

  makePreview : function (description, is_overwrite)
  {
    if ( is_overwrite )
    {
      UploadForm.showPreview (
          '\<div style="border:1px solid red; padding:0.5em;"\>'
        + '\<div class="error"\>'
        + wpPreviewOverwriteError
        + '\<\/div\>'
        + '\<\/div\>'
      );
    } else {
      var text = '\<div style="border:1px solid red; padding:0.5em;"\>\n'
               + '\<div class="previewnote"\>\n'
               + '\{\{int:previewnote\}\}\n'
               + '\<\/div>\n';
      var source   = document.getElementsByName("wpsource")[0].value;
      var game =  document.getElementById ('wpgames');
      var game_text = '';
      if (   game != null && game.selectedIndex >= 0
          && game.options[game.selectedIndex].value.length > 0) {
        game_text = game.options[game.selectedIndex].value;
      }
      var filetype =  document.getElementById ('wpfiletype');
      var filetype_text = null;
      if (   filetype != null && filetype.selectedIndex >= 0
          && filetype.options[filetype.selectedIndex].value.length > 0) {
        filetype_text = filetype.options[filetype.selectedIndex].value;
      }
      var license = document.getElementById ('wplicenses');
      var license_text = null;
      if (   license != null && license.selectedIndex >= 0
          && license.options[license.selectedIndex].value.length > 0) {
        license_text = license.options[license.selectedIndex].value;
      }

      text = "<h2>Preview</h2>\n{{FileInfo|summary=" + description + "|type=" + filetype_text + "|source=" + source +  "|game=" + game_text + "|licensing=" + license_text + "}}";
 
      // Make the Ajax call
      var req = sajax_init_object ();
      if (!req) return;
      var button = document.getElementById ('wpUploadPreview');
      var page   = document.getElementById ('wpDestFile');
      if (page) page = page.value;
      if (page != null && page.length == 0) page = null;
      if (button && typeof (injectSpinner) == 'function')
        injectSpinner (button, 'wpUploadPreviewSpinner');
      var uri  = server + scriptPath + '/api.php';
      var args = 'action=parse&pst&text=' + encodeURIComponent (text)
               + (page ? '&title=File:' + encodeURIComponent (page.replace (/ /g, '_')) : "")
               + '&prop=text|categories&format=json';
      // "&pst" is "Pre-save transform": tilde replacement, pipe magic for links like [[foo|foo]].
      // Don't use a callback directly, add the function call ourselves *after* the call, since
      // the API somehow resolves tildes to an IP number instead of the username if a callback
      // is used. C.f. https://bugzilla.wikimedia.org/show_bug.cgi?id=16616
      // Apparently, that's a feature, not a bug...
      var request_length = uri.length + args.length + 1;
      if (!!window.ActiveXObject && request_length > 2000 || request_length > 8100) {
        // IE has a URL limit of 2083 character (2048 in the path), WMF servers appear to have an 8kB
        // limit;
        req.open ('POST', uri, true);
        req.setRequestHeader ('Content-Type', 'application/x-www-form-urlencoded');
      } else {
        uri += '?' + args; args = null;
        req.open ('GET', uri, true);
      }
      req.setRequestHeader ('Pragma', 'cache=no');
      req.setRequestHeader ('Cache-Control', 'no-transform');
      req.onreadystatechange =
        function ()
        {
          if (req.readyState != 4) return;
          if (typeof (removeSpinner) == 'function') removeSpinner ('wpUploadPreviewSpinner');
          if (req.status != 200) return;
          // Add the "callback"...
          if (req.responseText && req.responseText.indexOf ('{') == 0)
            // Primitive sanity check. If the response text does *not* start with '{', it might have been
            // spoofed and contain a function call... of course, this simple check cannot catch more
            // elaborate spoof attempts.
            eval ('UploadForm.jsonPreview (' + req.responseText + ')');
        };
      req.send (args);
    }
  },

  jsonPreview : function (result)
  {
    if (result && result.parse && result.parse.text && result.parse.text['*'] != null) {
      var txt = result.parse.text['*'];
      var categories = result.parse.categories;
      if (categories && categories.length > 0) {
        // Add a mock-up of a category bar. We don't care about non-existing categories, and we
        // can't identify hidden categories.
        var catbar = '<div class="catlinks"><div id="mw-normal-catlinks">'
                   + wpCategoriesUploadLbl;
        categories.sort (
          function (a, b) {
            var key_a = a['*'].toLowerCase (), key_b = b['*'].toLowerCase ();
            if (key_a < key_b) return -1;
            if (key_a > key_b) return 1;
            return 0;
          }
        );
        for (var i = 0; i < categories.length; i++) {
          var catname = categories[i]['*'];
          if (catname && catname.length > 0) {
            if (i > 0) catbar += ' |';
            catbar += ' <a ' + 'href="/Category:' + encodeURI (catname) + '">'
                      + catname.replace(/_/g, ' ') + '</a>';
          }
        }
        catbar += '</div></div>';
        // Now insert it into text.
        var end = txt.lastIndexOf ('</div>');
        txt += catbar;
      }
      UploadForm.showPreview (txt);
    }
  },

  isOverwrite : function () {
    if (document.getElementById ('wpUploadWarningFileexists') != null) return true;
    var destfile_warning = document.getElementById ('wpDestFile-warning');
    if (destfile_warning == null) return false;
    var dest_file = document.getElementById ('wpDestFile');
    if (dest_file == null || dest_file.value == null || dest_file.value.length == 0) return false;
    var lks = destfile_warning.getElementsByTagName ('a');
    if (lks == null || lks.length == 0) return false;
 
    var fn1 =
      dest_file.value.replace(/^\s\s*/, '').replace(/\s\s*$/, '').replace(/ /g, '_');
    fn1     = fn1.substr (0, 1).toUpperCase () + fn1.substring (1);
    var fn0 = 'Image:' + fn1;
    fn1     = 'File:' + fn1;
    // Trimmed, blanks replaced by underscores, first character capitalized

    for (var i = 0; i < lks.length; i++) {
      var href = lks[i].getAttribute ('href', 2);
      if (href.indexOf (script + '?') == 0 || href.indexOf (server + script + '?') == 0) {
        var m = /[&?]title=([^&]*)/.exec (href);
        if (m && m.length > 1) href = m[1]; else href = null;
      } else {
        var prefix = articlePath.replace ('$1', "");
        if (href.indexOf (prefix) != 0) prefix = server + prefix; // Fully expanded URL?
        if (href.indexOf (prefix) == 0) href = href.substring (prefix.length); else href = null;
      }
      if (!href) continue;
      href = decodeURIComponent (href).replace (/ /g, '_');
      if (href == fn0 || href == fn1) return true;
    }
    return false;
  },

  isChildOf : function (child, ancestor)
  {
    if (!ancestor) return false;
    while (child && child != ancestor) child = child.parentNode;
    return (child == ancestor);
  },

  showPreview : function (result)
  {
    var preview = document.getElementById ('wpUploadPreviewDisplay');
    if (preview == null) {
      var before = document.getElementById ('mw-upload-permitted');
      if (!before || UploadForm.isChildOf (before, UploadForm.the_form))
        before = UploadForm.the_form;
          if (!before) return; // Don't know where to insert preview display. Error message here?
        preview = document.createElement ('div');
        preview.setAttribute ('id', 'wpUploadPreviewDisplay');
        before.parentNode.insertBefore (preview, before);
    }
    try {
      preview.innerHTML = result;
    } catch (ex) {
      preview.innerHTML = ""; // Error message here instead?
    }
    preview.style.display = ""; // Show it
    preview.scrollIntoView();
  },

  addPreviewButton : function ()
  {
    var request = sajax_init_object ();
    // If we don't have Ajax, our preview won't work anyway.
    if (request == null) return;
 
    var uploadButton = document.getElementsByName ('wpUpload')[0]; // Has no ID...
    // If we can't find the upload button, we don't know where to insert the preview button.
    if (uploadButton == null) return;

    var previewButton = document.createElement ('input');
    previewButton.setAttribute ('id', 'wpUploadPreview');
    previewButton.setAttribute ('name', 'wpUploadPreview');
    previewButton.type    = 'button';
    previewButton.accessKey = 'p';
    previewButton.value   = wpPreviewUploadLbl;
    previewButton.title   = wpPreviewUploadTooltip + ' [p]';
    previewButton.onclick = UploadForm.preview;

    previewButton.setAttribute ('style', 'margin-left: 0.5em;');
    updateTooltipAccessKeys([previewButton]);
    uploadButton.parentNode.insertBefore (previewButton, uploadButton.nextSibling);
  },

  preview : function (evt)
  {
    var overwrite = UploadForm.isOverwrite ();
 
    var desc = document.getElementById ('wpUploadDescription');
    UploadForm.makePreview (desc.value, overwrite);
    return true;
  }

};

}
	
$(document).ready(UploadForm.install);

// </source>