Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// Adds [[Template:Ncd]]]
// Created by [[User:Legoktm|Legoktm]]
// Adds a tab at the top of the page says "ncd"
// Adds [[Template:Ncd]] and substitutes it
if(wgNamespaceNumber == 6) {
  if(wgAction == 'edit' || wgAction == 'submit') {
    addOnloadHook(function () { mw.util.addPortletLink('p-cactions','javascript:doNcd()','ncd','ca-ncd'); });
  } else {
    var url = mw.config.get('wgServer') + mw.config.get('wgScript') + '?title=' + encodeURIComponent(mw.config.get('wgPageName')) + '&action=edit&autoncd=true';
    addOnloadHook(function () { mw.util.addPortletLink('p-cactions',url,'ncd','ca-ncd'); });
  }
}
if(queryString('autoncd')) addOnloadHook(function() { doNcd(); })
function doNcd() {
  var txt = document.getElementById('wpTextbox1');
  if(!txt) return;
  txt.value = txt.value.replace(/\{\{[\s\t\n\r]*(mtc|ctwc|tocommons|movetocommons|move[ -_]to[ -_]commons)[\s\t\n\r]*\}\}/ig,'');
  txt.value = '{' + '{' + 'subst:ncd}}\n\n' + txt.value;
  document.getElementById('wpSummary').value += ' automatically tagging {'+'{ncd}}';
  document.getElementById('wpSave').click();
}

function queryString(p) {
  var re = RegExp('[&?]' + p + '=([^&]*)');
  var matches;
  if (matches = re.exec(document.location)) {
    try { 
      return decodeURI(matches[1]);
    } catch (e) {
    }
  }
  return null;
}