User:Patstuart/Extrascripts.js

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: press Ctrl-F5, Mozilla: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Opera/Konqueror: press F5, Safari: hold down Shift + Alt while clicking Reload, Chrome: hold down Shift while clicking Reload.
//<nowiki>
var autoAppend=true;
var doneClick;

function str_trim(str)
{
  return str.replace(/^\s+|\s+$/g,"");
}

function auto_template()
{
  var template = decodeURIComponent(getParamValue("msg"));
  var pgName = decodeURIComponent(getParamValue("pg"));
  if (pgName==null)
    pgName="";

  var textboxVal = document.editform.wpTextbox1.value ;
  if (textboxVal.length==0 || textboxVal.charAt(textboxVal.length-1)!='\n')
    document.editform.wpTextbox1.value +='\n';
  document.editform.wpTextbox1.value += "\n{{subst:"+template+"|1="+pgName+"}} ~~~~";
  document.editform.wpSummary.value = "Auto-adding {{[[Template:"+template+"|"+template+"]]}} to inform user";
  document.editform.wpMinoredit.checked = false;
  return true;
}

function notify_user(templateName, lang)
{
  var user = getUploader;
  if (user==null)
    return false;

  if (lang!="en")
  {
    var tmpname=templateName+ "/"+lang;
    if (false) //not working for now  (!checkPageExists("Template:" + tmpname))
    {
      if (prompt("Language template does exist: default to English?"))
        templateName=tmpname;
      else
        return false;
    }
    else
      templateName=tmpname;
  }
  

  var uploader = getUploader();
  if (uploader==null)
    return false;

  window.open(wgScript + "?title=User_talk:" + encodeURIComponent(uploader) + "&action=edit&functionName=auto_template&msg=" + encodeURIComponent(templateName) + "&pg=" + encodeURIComponent(mw.config.get('wgPageName')));
  return true;
}

//cannabalized  shamelessly (GFDL!) from </nowiki>[[MediaWiki:Gadget-HotCat.js]]<nowiki>
function checkPageExists(pageName)
{
  var url = wgServer + wgScriptPath
            + "/query.php?what=content&titles=" + encodeURIComponent( pageName ) ;
  var request = sajax_init_object() ;

  //0 - failed transmision; 1 - false, no such page, 2 - page found, 3 - still running
  var response=3;

  //can't establish if page exists; assume good faith
  if (request == null) 
    return true;

  request.open('GET', url, true);
  request.onreadystatechange = function ()
  {
    if (request.readyState == 4)
    {
      var xml = request.responseXML ;
      if ( xml == null )
      {
        response=0;
        return ;
      }
      var idArray = xml.getElementsByTagName( "id" ) ;
      if (idArray==null)
      {
        response=0;
        return ;
      }
      
      var id = idArray[0].childNodes[0].nodeValue;
      if (id ==null)
      {
        response=0;
        return ;
      }

      id = parseInt(id);
      if (id==0) //no page
        response=1;
      else
        response=2;
      return; 
    }
  };
  request.setRequestHeader ('Pragma', 'cache=yes');
  request.setRequestHeader ('Cache-Control', 'no-transform');
  request.send(null);

  while(response==3);
  if (response==1)
    return false;
  else //assume good faith: bad transmission means it exists
    return true;
}

//stolen shamelessly (GFDL!) from </nowiki>[[MediaWiki:Quick-delete.js]]<nowiki>
function getUploader() {
  // Get uploader from first point in the list under "File history"
  // Uploader is stored in second A tag in UL tag under "File history"
  // Returns title of user page (without name space) in URL form
  var el = document.getElementById('filehistory')
  if (!el) {
    alert("getUploader: Cannot find filehistory ... exiting");
    return null;
  }
  while (el.nextSibling) {
    el = el.nextSibling;
    if (el.tagName && el.tagName.toLowerCase() == 'table') 
      break;
  }
  if (!el) {
    alert("getUploader: Cannot find table tag ... exiting");
    return null;
  }
 
  var as = el.getElementsByTagName('a');
 
  var re1 = new RegExp((mw.config.get('wgServer') + mw.config.get('wgArticlePath').substr(0, wgArticlePath.length-2) ).replace(/\./g, '\\.') + 'User:(.*)$');
  var re2 = new RegExp((wgServer  + wgScript).replace(/\./g, '\\.') + '\\?title=User:([^&]*)');
  var m;
  for (var k=0; k<as.length; k++) {
     m = re1.exec(as[k].href);
     if (m) return m[1];
     m = re2.exec(as[k].href);
     if (m) return m[1];
  }
  alert("getUploader: Cannot find uploader ... exiting");
  return null;
}

// helper function
function isWhitespace(c)
{
  if (c==" " || c=="\t" || c=="\r" || c=="\n" || c=="\f")
    return true;
  return false;
}

function replaceCat(big, small, replacer)
{
  small="[" + small.charAt(0).toUpperCase() + small.charAt(0) + "]" + small.substring(1);
  return big.replace(new RegExp("\\[\\[\\s*[Cc]ategory\\s*:"+small+"\\s*(\\|.*)?\\]\\]\\n?"), replacer);
}


// duplicate tagger (initially developed by Patstuart)
function duplicate(){
  var site;
  var type = confirm('{{badname}}? (cancel for {{duplicate}})')?
             '{{badname|1=' : '{{duplicate|1=';
  

  do
  {
    site = prompt("Original?");
    //cancel button pressed
    if (site==null)
      return false;
  } while(site.indexOf("Image:")==-1 && (alert("Illegal name"), true))
 
  document.editform.wpTextbox1.value = type +site+'}}\n' + document.editform.wpTextbox1.value;
  document.editform.wpSummary.value = 'Tagging image as a duplicate image';
  document.editform.wpMinoredit.checked = false;
  return true;
}

// copyvio tagger (initially developed by Patstuart)
function copyvio(){
  var site = prompt("Location?");
  
  //cancel button pressed
  if (site==null)
    return false;

  if (site=="")
    document.editform.wpTextbox1.value = '{{copyvio}}\n' + document.editform.wpTextbox1.value;
  else
    document.editform.wpTextbox1.value = '{{copyvio|1='+site+'}}\n' + document.editform.wpTextbox1.value;

  document.editform.wpSummary.value = 'Tagging image as a [[Commons:Licensing|copyright violation]]';
  document.editform.wpMinoredit.checked = false;
  return true;
}

// speedydelete tagger (initially developed by Patstuart)
function speedy(){
  var reason = prompt("Reason?");
  
  //cancel button pressed
  if (reason==null)
    return false;

  if (reason=="")
    document.editform.wpTextbox1.value = '{{speedydelete}}\n' + document.editform.wpTextbox1.value;
  else
    document.editform.wpTextbox1.value = '{{speedydelete|1='+reason+'}}\n' + document.editform.wpTextbox1.value;

  document.editform.wpSummary.value = 'Tagging image for [[Commons:Deletion_guidelines#Speedy_deletion|speedy deletion]]';
  document.editform.wpMinoredit.checked = false;
  return true;
}


// rename tagger (initially developed by Patstuart)
function rename()
{
  var template;
  var name; 
  var reason;
  var textboxVal = document.editform.wpTextbox1.value;

  do
  {
    name = prompt("New name");
    if (name == null) //cancel button
      return false; 

    if (name.indexOf('.')==-1)
    {
      alert("Need image extension (e.g., .jpg, .png)");
      continue;
    }

    if (str_trim(name).search(/I|image:/)==0)
      name=str_trim(name.substring(6));
  } while(name=="" && (alert("Invalid image name"), true));

  reason = prompt("Reason (blank for nothing)");
  if (reason == null) //cancel button
    return;

  template = "{{rename|"+name;
  if (reason!="")
    template+="|"+reason;
  template+="}}\n"

  var ex = new RegExp("{{\\s*[R|r]ename image\\s*}}").exec(textboxVal);
  if (ex==null)
    ex = new RegExp("{{\\s*[R|r]ename media failed\\s*}}").exec(textboxVal);
  if (ex==null)
    ex = new RegExp("{{\\s*[R|r]ename\\s*}}").exec(textboxVal);

  if (ex != null)
    document.editform.wpTextbox1.value = textboxVal.replace(ex, template);
  else
    document.editform.wpTextbox1.value = template + textboxVal;

  document.editform.wpSummary.value = 'Tagging image for automated [[:Category:Media requiring renaming|renaming]].';
  document.editform.wpMinoredit.checked = false;
  return true;
}

// uncat tagger (initially developed by Patstuart)
function uncat(){
  var txtval=document.editform.wpTextbox1.value; 
  
  if (txtval.indexOf('{{uncat}}')>-1 || txtval.indexOf('[[Category:')>-1 || txtval.indexOf('[[category:')>-1)
    if (!confirm("Appears to already have a category: are you sure?"))
      return false;

  document.editform.wpTextbox1.value += '\n{{uncat}}'
  document.editform.wpSummary.value = 'Tagging image or page as [[Commons:Categories|uncategorized]] (please link your images and pages!)';
  document.editform.wpMinoredit.checked = true;
  return true;
}

// nld tagger (initially developed by Patstuart)
function nld(){
  document.editform.wpTextbox1.value = '{{subst:nld}}\n' + document.editform.wpTextbox1.value
  document.editform.wpSummary.value = 'Tagging image as [[COM:L|lacking a license tag]]. This image may be deleted after seven days.';
  document.editform.wpMinoredit.checked = false;
}

// nsd tagger (initially developed by Patstuart)
function nsd(){
  document.editform.wpTextbox1.value = '{{subst:nsd}}\n' + document.editform.wpTextbox1.value
  document.editform.wpSummary.value = 'Tagging image as [[COM:L|lacking a source]]. This image may be deleted after seven days.';
  document.editform.wpMinoredit.checked = false;
  return true;
}

// npd tagger (initially developed by Patstuart)
function npd(){
  document.editform.wpTextbox1.value = '{{subst:npd}}\n' + document.editform.wpTextbox1.value
  document.editform.wpSummary.value = 'Tagging image as [[Template:No_permission_since|lacking proof of permission]]. This image may be deleted after seven days.';
  document.editform.wpMinoredit.checked = false;
  return true;
}

// bsr tagger (initially developed by Patstuart)
function bsr(){
  document.editform.wpTextbox1.value = '{{bsr}}\n' + document.editform.wpTextbox1.value
  document.editform.wpSummary.value = 'Tagging image as [[Template:bsr|lacking specific source information]]. Please update the image to better indicate the source.';
  document.editform.wpMinoredit.checked = false;
  return true;
}


// defaultsort
function defaultsort(){
  var name;
  var message;
  var textboxVal = document.editform.wpTextbox1.value;

  if (textboxVal.search(/\{\{\s*DEFAULTSORT\s*.*\}\}/)>-1)
  {
    alert("Default sort already present.");
    return false;
  }
  if (wgTitle.substr(0, 4)=="The")
  {
    message = '[[Commons:Categories#People|Category sorting]]: "The" is not relevant to sort'
    name = wgTitle.substring(4) + ", The";
  }
  else
  {
    message = '[[Commons:Categories#People|Category sorting]] page or image of person by last name first';
    var index = wgTitle.lastIndexOf(' ');
    var firstname = wgTitle.substring(0, index);
    var lastname = wgTitle.substring(index+1);
    name = lastname + ", " + firstname;
    if (firstname.indexOf(' ')>-1)
    {
      name=prompt("",wgTitle);
      if(name==null) //cancel button
        return false;
    }
  }

  textboxVal = textboxVal.replace(new RegExp("\\[\\[\\s*Category\\s*:\\s*(.*)\\s*\\|\\s*" + name.replace(/([\\\^\*\$\+\?\.\(\)\|\\{\}\,\[\]])/g, "\\$1") + "\\s*\\]\\]", "g"), "[[Category:$1]]");
  var index =  textboxVal.indexOf("[[Category:")
  document.editform.wpTextbox1.value=textboxVal.substring(0, index) +
    "{{DEFAULTSORT:"+name+"}}\n"+textboxVal.substring(index);
  document.editform.wpSummary.value = message;
  document.editform.wpMinoredit.checked = true;
  return true;
}

// tmpfunc tagger - specific function only meant for my only use
function tmpfunc(){

  var year;  
  var yeartxt;
  var birth;
  var death;
  var textboxVal = document.editform.wpTextbox1.value;

  var ex = new RegExp("[0-9]{4} births((\s*)|(|.*))]]") .exec(textboxVal ); 
  if (ex==null)
  {
    var uglyExpression = "(\\'\\'\\')[A-Za-z]+(\\s*[A-Za-z]+){1,4}(\\'\\'\\')\\s+\\(\\s*[A-Z][a-z]+\\s+[0-9]{1,2},\\s+[0-9]{4}\\s*((\\&ndash\\;)|\\-|\\–)\\s*[A-Z][a-z]+\\s+[0-9]{1,2},\\s+[0-9]{4}\\s*\\)";
    
    ex = new RegExp(uglyExpression ).exec(textboxVal );
    if (ex!=null && ex.index==0)
    {
      var birthstart = textboxVal.indexOf(',')+1;
      birth = parseInt(textboxVal.substr(birthstart, 5));
      death = parseInt(textboxVal.substr(textboxVal.indexOf(',', birthstart)+1, 5)); 
    }
    else
      ex=null;
  }
  else 
  {
    birth=0;
    death=0;
  }  
  
  //can't determine DOB automagically
  if (ex==null)
  {
    do
    {
      yeartxt = prompt("Year?");
      if (yeartxt==null) //cancel button
        return false;

      birth = parseInt(yeartxt);

      if (yeartxt.indexOf("-")>-1)
        death = parseInt(yeartxt.substring(yeartxt.indexOf('-')+1));
      else
        death = 0;

    } while(!(birth>=1800 && birth<2000 && (death==0 || (death>=1800 && death<=2008))) && (alert("Illegal Year"), true));
  
  }

  if (birth!=0)
  {
    var appendtext;
    var index = textboxVal.lastIndexOf("[[Category:");

    if (index==-1)
      index = textboxVal.length-1;
    else
      index = textboxVal.indexOf("]]", index) + 2;
    
    if (index==1)
    {
      alert("Parse error");
      return false;
    }
    
    appendtext = "\n[[Category:" + birth+ " births]]";
    if (death!=0)
      appendtext += "\n[[Category:" + death+ " deaths]]";

    document.editform.wpTextbox1.value=textboxVal.substring(0, index) + appendtext  + textboxVal.substring(index); 
    year = parseInt(birth/10)*10;
  }

  //DOB determined via categories
  else
  {
    year = textboxVal.substr(ex.index, 4);
    year = parseInt(year/10)*10;

    if (year<1800 || year>=2000)
      return false;
  }
  if (year<1900)
    yeartxt = "Actresses from the United States born in the 19th century"
  else
    yeartxt = "Actresses from the United States born in the " + year+"s"

  document.editform.wpTextbox1.value =
      document.editform.wpTextbox1.value.replace(/(A|a)ctresses from the United States(|.*)]]/g,
                                                   yeartxt+"$2]]");
  
  if (document.editform.wpTextbox1.value.indexOf("{{DEFAULTSORT")==-1)
    defaultsort(false);

  document.editform.wpSummary.value = 'Recategorizing to [[:Category:' + yeartxt + ']] and/or adding birth/death year categories (report errors [[User talk:Patstuart|here]]). ';
  document.editform.wpMinoredit.checked = true;
  return true;
}

// galleryToCat
function galleryToCat(){

  var textboxVal = document.editform.wpTextbox1.value;

  //creating category from gallery
  if (wgCanonicalNamespace=="" || wgPageName == "User:Patstuart/test1")
  {
    var catname = prompt("Category name?", wgTitle);
    if (catname==null) //cancel button pressed
      return false;

    var cats = new Array(0);
    var nextcat;
    while(nextcat= textboxVal.search(/\[\[\s*Category\s*:.*\]\]/gi), nextcat!=-1)
    {
      //store category
      var nextbar = textboxVal.indexOf('|', nextcat);
      var nextendcat = textboxVal.indexOf(']]', nextcat);
      var endcatname = nextbar<nextendcat ? (nextbar==-1?nextendcat:nextbar) : (nextendcat==-1?nextbar:nextendcat);
      cats.push(str_trim(textboxVal.substring(textboxVal.indexOf(':', nextcat)+1, endcatname)));

      //remove category from page
      var endcat = nextendcat+2;
      if (textboxVal.charAt(endcat)=='\n' && (nextcat==0 || textboxVal.charAt(nextcat-1)=='\n'))
        endcat++;
      textboxVal=textboxVal.substring(0, nextcat) + textboxVal.substring(endcat);
    }
    if (cats.length==0)
      if (!confirm("Uncategorized gallery. Continue?"))
        return false;

    //add new cat to gallery
    if (textboxVal.charAt(textboxVal.length-1)!='\n')
      textboxVal+='\n';
    textboxVal+="[[Category:"+catname+"|*]]";

    //store images in gallery
    var startgallery = textboxVal.search(/<gallery\s*>/i);
    if (startgallery==-1)
    {
      alert("Empty gallery");
      return false;
    }
    startgallery=textboxVal.indexOf('>', startgallery) + 1;

    var endgallery = textboxVal.substring(startgallery).search(/<\/gallery\s*>/i)+startgallery;
    if (endgallery==-1)
    {
      alert("Unable to determine end of gallery");
      return false;
    }
    var galleryNoDescriptions = textboxVal.substring(startgallery, endgallery).replace(/\|.*\n/g, "\n");
    var imagesNamesOnly = galleryNoDescriptions.replace(/image\s*:\s*/gi, "");
    imagesNamesOnly = imagesNamesOnly.replace(/\s*\n\s*/g, "\n");     //remove whitespace
    imagesNamesOnly = str_trim(imagesNamesOnly);
    var images = imagesNamesOnly.split("\n");    

    //store gallery description for new category
    var description = textboxVal.substring(0, textboxVal.search(/<gallery\s*>/i));
    
    //store defaultsort
    var defaultsort = textboxVal.indexOf("{{DEFAULTSORT");
    if (defaultsort>-1)
      description+=textboxVal.substring(defaultsort, textboxVal.indexOf("}}", defaultsort)+2);
   
    //store categories
    for (i in cats)
      description+="\n[[Category:"+cats[i]+"]]";

    if (images.length>4)
      if (!confirm("There are " + images.length + " images in this gallery, meaning that " + images.length + " new windows will be opened. Are you sure you want to proceed?"))
        return false;

    //open each image
    for (j=0; j<images.length; j++)
    {        
      window.open(wgScript + "?title=Image:" + images[j] + "&action=edit&functionName=galleryToCat&cats=" + encodeURIComponent(cats) + "&newcat="+ encodeURIComponent(catname));        
    }

    window.open(wgScript + "?title=Category:" + catname + "&action=edit&functionName=galleryToCat&catText=" + encodeURIComponent(description), "NewCategoryWindow");

    document.editform.wpSummary.value = 'Semi-automatic porting gallery to [[commons:category|category]] [[:Category:' + catname + ']] (report errors [[User talk:Patstuart|here]]).'
    document.editform.wpTextbox1.value = textboxVal;
    document.editform.wpMinoredit.checked = true;
    return true; 
  }
  else if (wgCanonicalNamespace=="Image" || wgCanonicalNamespace=="File")
  {
    var numReplacedCats = 0;
    var editsummary; 
    //bad image?
    if (textboxVal.length==0)
    {
      if (!confirm("Image does not exist or description page is blank. Continue?"))
        return false;
    }

    //remove categories soon to be redundant to supercat
    var cats = decodeURIComponent(getParamValue("cats")).split(',');
    for (i in cats)
    {
      var newval = replaceCat(textboxVal, cats[i], "");
      if (newval!=textboxVal)
      {
        textboxVal=newval;
        numReplacedCats++;
      }
    }
    if (textboxVal.charAt(textboxVal.length-1)!='\n')
      textboxVal+='\n';
    var catname = decodeURIComponent(getParamValue("newcat"));
    textboxVal = replaceCat(textboxVal, catname, ""); //remove double cat
    textboxVal+="[[Category:" + catname + "]]";
    
    if (numReplacedCats==0)
      document.editform.wpSummary.value = 'Semi-automatic porting gallery to [[Commons:Category|category]] [[:Category:' + catname + ']] (report errors [[User talk:Patstuart|here]]).';
    else
      document.editform.wpSummary.value = 'Semi-automatic porting gallery to [[Commons:Category|category]] [[:Category:' + catname + ']]; ' + numReplacedCats + (numReplacedCats > 1 ? ' supercategories ' : ' supercategory ') + 'removed (report errors [[User talk:Patstuart|here]]).';
    document.editform.wpTextbox1.value = textboxVal;
    document.editform.wpMinoredit.checked = true;
    return false; //operation it too complicated; should be checked manually.
  }
  else if (wgCanonicalNamespace=="Category")
  {

    if (textboxVal.length!=0)
    {
      if (!confirm("Category already exists. Continue?"))
        return;
    }

    //add text
    textboxVal = decodeURIComponent(getParamValue("catText"));
    document.editform.wpSummary.value = 'Semi-automatic porting gallery to [[commons:category|category]] (report errors [[User talk:Patstuart|here]]).'
    document.editform.wpTextbox1.value = textboxVal;
    document.editform.wpMinoredit.checked = false;
    return false; //operation it too complicated; should be checked manually.
  }
  else
  {
    alert("Script error; illegal namespace");
    return false;
  }
}

function deathdates(){
  var textboxVal =  document.editform.wpTextbox1.value;
  var year = parseInt(wgTitle);
  var ones = year%10;
  var tmp =(year-ones)/10;
  var tens = tmp %10;
  var hundreds=(tmp-tens)/10;

  textboxVal = replaceCat(textboxVal, "" + year, "");
  textboxVal = replaceCat(textboxVal, century + " century deaths", "");
  textboxVal = textboxVal.replace(/\{\{\s*[Dd]eathcat\s*\|.*\}\}/, "{{deathcat2|"+hundreds+"|"+tens+"|"+ones+"}}");
  if (textboxVal.search(/\{\{deathcat2\|.*\}\}/))
  {
    textboxVal=str_trim(textboxVal) 
    if (textboxVal!="")
    {
      if (!confirm("Add template?"))
        return false;
    }
    textboxVal = "{{deathcat2|"+hundreds+"|"+tens+"|"+ones+"}}\n" + textboxVal; 
  }
  
  var century = ones==0 && tens==0? hundreds:hundreds+1;
  switch (century)
  {
    case 1:
      century="1st";
      break;
    case 2:
      century="2nd";
      break;
    case 3:
      century="3rd";
      break;
    case 21:
      century="21st";
      break;
    default:
      century=century+"th";
  }
   
  //minor edit iff category previously existed
  if (document.editform.wpTextbox1.value!="")
  {
    document.editform.wpMinoredit.checked = true;
    document.editform.wpSummary.value = 'Semi-automatically updating category via [[template:deathcat2|new template]] (report errors [[User talk:Patstuart|here]])';
  }
  else
  {
    document.editform.wpMinoredit.checked = false;
    document.editform.wpSummary.value = 'Semi-automatically creation of new death by year category (report errors [[User talk:Patstuart|here]])';
  }

  document.editform.wpTextbox1.value = textboxVal;
  return true;
}

//stolen shamelessly and modified from the add {{information}} template text
function add_toolbox_button(text, _href, secondaryToolboxOptions) 
{
  var toolbox = document.getElementById ( "p-tb" ) ;
  if ( !toolbox )
    return ;
  var ul = toolbox.getElementsByTagName ( "UL" ) [0] ;
  var li = document.createElement ( "LI" ) ;
  var a = document.createElement ( "A" ) ;
  a.appendChild (document.createTextNode(text));
  a.href = _href;
  a.className = "external" ;
  li.appendChild ( a ) ;
  if (secondaryToolboxOptions)
  {
    var aSecondary = new Array(secondaryToolboxOptions.length);
    for (i=0; i<secondaryToolboxOptions.length; i++)
    {
      li.innerHTML +="•";
      aSecondary[i] = document.createElement ( "A" ) ;
      aSecondary[i].appendChild (document.createTextNode(secondaryToolboxOptions[i][0]));
      aSecondary[i].href = "javascript:var lang = prompt('Lang?', 'en'); if (lang && notify_user('"+secondaryToolboxOptions[i][1]+"', lang)) window.location = '" + _href + "';";
      aSecondary[i].className = "external" ;
      li.appendChild ( aSecondary[i] );
    }
  }
  ul.appendChild ( li ) ;
}


//stolen shamelessly and modified from the add {{information}} template text
function add_topbar_button(text, _href) 
{
  mw.util.addPortletLink("p-cactions", _href, text, "");
}
function addFunction(functionNameString, buttonDisplayName, checkNameSpaceFlag, whereAdd, secondaryToolboxOptions)
{
  checkNameSpaceFlag|= (wgPageName=="User:Patstuart/test1");
  if (!checkNameSpaceFlag)
    return;

  if (getParamValue('functionName')==functionNameString)
  {
    addOnloadHook
    (
      function ()
      {
        //function autosaves when clicked outside box. Does not save if function returns null or false.
        if (!doneClick && eval(functionNameString+"()"))
        {
          doneClick=true; //avoid running function again if back button is pressed
          document.editform.submit();        
        }
        else 
          doneClick=true; //avoid running function again if back button is pressed
      }
    );
  }

  var _href;
  if (wgAction=="edit") 
    _href = "javascript:var ignored="+functionNameString+"();";
  else
    _href = wgScript + "?title="+encodeURIComponent(mw.config.get('wgPageName'))+ "&action=edit&functionName="+functionNameString;

  if (whereAdd=="top")
    addOnloadHook(function (){add_topbar_button(buttonDisplayName, _href);})
  else if (whereAdd=="toolbox") 
    addOnloadHook(function (){add_toolbox_button(buttonDisplayName, _href, secondaryToolboxOptions);})
}

function addImageFunction(functionNameString, buttonDisplayName, buttonLocation, secondaryToolboxOptions)
{
  addFunction(functionNameString, buttonDisplayName, wgCanonicalNamespace=="Image" || wgCanonicalNamespace=="" || wgCanonicalNamespace=="Category", buttonLocation, secondaryToolboxOptions);
}
function addNonTalkFunction(functionNameString, buttonDisplayName, buttonLocation, secondaryToolboxOptions)
{
  addFunction(functionNameString, buttonDisplayName, wgCanonicalNamespace.indexOf("talk")==-1 && !wgCanonicalSpecialPageName, buttonLocation, secondaryToolboxOptions);
}

addFunction("auto_template", "auto_template", true, "hidden");
addNonTalkFunction("uncat", "{{uncat}}", "toolbox", new Array(new Array("notify", "please link images")));
addNonTalkFunction("tmpfunc", "tmpfunc", "top");
addImageFunction("speedy", "{{speedydelete}}", "toolbox");
addImageFunction("copyvio", "copyvio", "toolbox", new Array(new Array("notify", "copyvionote"), new Array("swhat", "speedywhat")));
addImageFunction("duplicate", "{{badname}}", "toolbox", new Array(new Array("notify", "please name images")));
addImageFunction("nld", "{{nld}}", "toolbox", new Array(new Array("notify", "no tag message")));
addImageFunction("nsd", "{{nsd}}", "toolbox", new Array(new Array("notify", "image source")));
addImageFunction("npd", "{{npd}}", "toolbox", new Array(new Array("notify", "image permission")));;
addImageFunction("bsr", "{{bsr}}", "toolbox", new Array(new Array("notify", "bsr-user")));;
addNonTalkFunction("defaultsort", "{{DEFAULTSORT}}", "toolbox");
addImageFunction("rename", "{{rename}}", "toolbox", new Array(new Array("notify", "please name images")));
addFunction("galleryToCat", "galleryToCat", wgCanonicalNamespace=="Category" ||  wgCanonicalNamespace=="Image", "hidden");
addFunction("galleryToCat", "galleryToCat", wgCanonicalNamespace=="", "toolbox");
addFunction("deathdates", "Death date upgrade", wgCanonicalNamespace=="Category" && wgTitle.search(/[0-9]{3,4} deaths$/)>-1, "toolbox");


//</nowiki>