Jump to content

User:Random832/common.js

From Wikipedia, the free encyclopedia
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.
// wikibits customization
if(window.histrowinit) window.removeEventListener('load',histrowinit,false);
ts_alternate_row_colors = false;

// General library stuff {{{

// Event handler function {{{ 
function mkEvt(elem,evtname,handler) {
	// old-style event handlers have more robust canceling and target
	// finding - here's a trick to let me attach multiple ones
    var oldhandler = elem['on'+evtname];
    elem['on'+evtname] = function() {
        if(oldhandler) {
         elem._eventTemp = oldhandler;
         if(elem._eventTemp() == false) return false;
        }
        elem._eventTemp = handler;
        return elem._eventTemp();
    }
}
//}}}*/

// Hack to fix race condition w/ importScript {{{
addOnloadHook = function(hookFunct) {
   // Allows add-on scripts to add onload functions
   if(doneOnloadHook) hookFunct();
   else onloadFuncts[onloadFuncts.length] = hookFunct;
};
// }}} */

// tricks with getElementById {{{
document._realGEBI = document.getElementById;
document.getElementById = function(id){
   if(id=="p-cactions") {
       if(this._realGEBI("p-cactions2"))
          return this._realGEBI("p-cactions2");
   }
   var x = this._realGEBI(id);
   if(x) return x;
   else {
      switch(id) {
	 case "content": x= this._realGEBI("mw_content");break;
	 case "column-content": x= this._realGEBI("mw_contentwrapper");break;
	 case "bodyContent": x= this._realGEBI("mw_contentholder");break;
	 case "column-one": x= this._realGEBI("mw_portlets");break;
	 case "globalWrapper": x= this._realGEBI("mw_main");break;
	 default: return null;
      }
   }
   return x;
}
// }}} */

/* }}} */

/* check if page is discussion {{{ */
var pageIsDiscussion = false;

addOnloadHook(function pageIsDiscussion_hook() {
  if(wgNamespaceNumber % 2) {
      pageIsDiscussion = true; return;
  }
  if(wgNamespaceNumber == 4) {
        if(wgPageName.indexOf("noticeboard") > 0) {
            pageIsDiscussion = true; return;
        }
        if(wgPageName.indexOf("Village_pump") > 0) {
            pageIsDiscussion = true; return;
        }
        if(wgPageName.indexOf("_for_deletion/") > 0) {
            pageIsDiscussion = true; return;
        }
        if(wgPageName.indexOf("_for_discussion/") > 0) {
            pageIsDiscussion = true; return;
        }
        if(wgPageName.indexOf("Requests_for_comment/User_names") > 0) {
            pageIsDiscussion = true; return;
        }
    }
});
/* }}} */

/* Add a tab for arbitrary actions {{{
// TODO undelete
// event handling here isn't making sense, and the style is somehow 
// broken anyway (needs a skin check maybe?)
addOnloadHook(function blankTab_hook() {
 try {
   var theList = $('p-cactions').getElementsByTagName("UL")[0];
   var myLi = document.createElement("LI");
   var myForm = document.createElement("FORM");
   var myInput = document.createElement("INPUT");
   myForm.appendChild(myInput);
   myLi.appendChild(myForm);
   theList.appendChild(myLi);
// TODO move to .css
   myLi.style.cssText = "float: right; padding-top: 1px;"
   myForm.style.cssText = "display: inline"
   myInput.style.cssText = "width: 4em; background-color:white; font: inherit; border: none; text-align: right"
   myForm.onsubmit = function(e) {
      e.preventDefault();
      switch(myInput.value) {
         case 'move':
           location.href = ('Special:Movepage/'+wgPageName)
                           .replace(/(.*)/,wgArticlePath);
           break;
         case 'contribs':
           location.href = ('Special:Contributions/'+wgPageName.replace(/^[^:]*:/,'').replace(/\/(.*)/,''))
                           .replace(/(.*)/,wgArticlePath);
           break;
         case 'links':
           location.href = ('Special:Whatlinkshere/'+wgPageName)
                           .replace(/(.*)/,wgArticlePath);
           break;
         case 'log': case 'logs':
           location.href = ('Special:Log')
                           .replace(/(.*)/,wgArticlePath)
                           +'?page='+escape(wgPageName);
           break;
         case 'edit lead':
           location.href = wgScriptPath+'/index.php?' +
                              'title='+escape(wgPageName) + "&" +
                              'action=edit&section=0';
           break;
      default: location.href = wgScriptPath+'/index.php?' +
                              'title='+escape(wgPageName) + "&" +
                              'action='+escape(myInput.value)
      }
   }
 } catch(x) { Debug(x,'addBlankTab') }
});
// }}} */

// Alt text {{{
$(function() {
   try {
      for(var i=0;i<document.images.length;i++) {
         var img = document.images[i];
         if(img.alt && !img.title) img.title = 'alt: '+img.alt;
      }
   } catch(x) { Debug(x,'processImages') }
});
// }}} */

// [[User:Random832]] script for finding "resolved" tags. {{{
// semi-experimental, not yet adapted for anything but ANI.
if (wgPageName == "Wikipedia:Administrators\'_noticeboard/Incidents" && wgAction == "view") {
   addOnloadHook(function ANI_toc_hook(){
      var sections = document.getElementById('toc').getElementsByTagName("li");
      for(var i=0;i<sections.length;i++) {
         try {
            var link = sections[i].firstChild;
            var target=document.getElementsByName(link.hash.slice(1))[0];
            var next = target.parentNode.nextSibling;
            // discard text nodes
            while(next.nodeType != 1) next = next.nextSibling;

            // now we have the header, now skip another
            if(next.tagName != "H2") { continue; }
            next = next.nextSibling;
            while(next.nodeType != 1) next = next.nextSibling;

            if ((/\bresolved\b/.test(next.className))) { 
               //resolved
               sections[i].className = "ani_resolved"
               sections[i].style.fontStyle = 'italic'
               //sections[i].appendChild(document.createTextNode("resolved"))
            } else {
               //not resolved
               sections[i].className = "ani_unresolved"
               sections[i].style.fontWeight = 'bold'
            }
            // BUG: chokes on sections beginning with a digit
            // (anchor has name instead of id).
         } catch(x) {
            if(window.console) //firebug
               console.log("caught %o",x);
         }//end try
      }//end for
   });//end onloadhook function
}//end if WP:ANI
// }}}

(function submit_validation_hook() { // set up submit validation {{{
  var validators = [];
  var is_preview = false;
  window.addOnSubmitValidator = function(x) {
   validators[validators.length] = x;
  }
  addOnloadHook(function() {
    var editform = document.getElementById('editform');
    if(!editform) return;
    mkEvt(editform,'submit',function() {
      if(is_preview) return true;
      for(var i=0;i<validators.length;i++) {
        var result = validators[i]();
        if(!result) return false;
      }
    });
    if (document.getElementById('wpPreview')) {
      mkEvt(document.getElementById('wpPreview'),'click',function () {
        is_preview = true;
      });
    }
  });
})(); // }}}

// Edit summary check {{{
addOnSubmitValidator(function() {
  var editsummary = document.getElementById('wpSummary').value;
  if( /^\/\*.*\*\/\s*$/.test(editsummary)) editsummary = ''
  if(!editsummary) return confirm("Submit this edit without an edit summary?");
  else return true;
});
// }}} */

// links on CAT:PER {{{ 
if(wgPageName=="Category:Wikipedia_protected_edit_requests")
$(function(){
   var pagediv = document.getElementById("mw-pages");
   var links = pagediv.getElementsByTagName("A");
   for(var i=0;i<links.length;i++) {
      links[i].hash = '#editprotected';
   }
});
// }}} */

$(function() {
   var s = document.createElement('STYLE');
   s.textContent = '#edittools_hide_for_script_test {display:none}';
   document.getElementsByTagName('HEAD')[0].appendChild(s);
});

/* change diff to history in new messages {{{
$(function() {
    var contentSub = document.getElementById("contentSub");
    if(!contentSub) return;
    var elem = contentSub.nextSibling;
    while(elem.nodeType != 1) elem = elem.nextSibling;
    if(elem.className != 'usermessage') return;
    elem.getElementsByTagName('A')[1].href = elem.getElementsByTagName('A')[1].href.replace("diff=cur","action=history")
    elem.getElementsByTagName('A')[1].textContent = "history";
});
// }}}*/

// Section organizer for ANI {{{
if (wgPageName == "Wikipedia:Administrators\'_noticeboard/Incidents" && wgAction == "view") {
   addOnloadHook(function ani_sections() {
       var headers = document.getElementsByTagName('H2');
       for(var i=1;i<headers.length;i++) {
           // starting from 1, to skip the toc header.
           var section = document.createElement("DIV");
           section.className = "sectionContainer";
           var anchor = headers[i].previousSibling;
           while(anchor.nodeType != 1) anchor = anchor.previousSibling;
           headers[i].parentNode.insertBefore(section,headers[i]);
           section.appendChild(anchor);
           section.appendChild(headers[i]);
           var innerSection = document.createElement("DIV");
           innerSection.className = "sectionContentHolder";
           section.appendChild(innerSection);
           while(section.nextSibling && section.nextSibling.tagName != 'H2' && section.nextSibling.id != 'catlinks') {
               // look ahead
               var anchorcheck = section.nextSibling.nextSibling;
               while(anchorcheck && anchorcheck.nodeType!=1) anchorcheck = anchorcheck.nextSibling;
               if(anchorcheck && anchorcheck.tagName == 'H2') break;
               innerSection.appendChild(section.nextSibling);
           }

           var ntimestamps = 0;
           // evil evil hack
           var lastTimestamp = new Date(0);
           var lastTimestampText = '(No Timestamp)';
           innerSection.textContent.replace(/[0-9][0-9]:[0-9][0-9], [0-3]?[0-9] [A-Z][a-z]* [0-9][0-9][0-9][0-9]/g,function(match) {
               var thisTimestamp = new Date(match);
               if(thisTimestamp.valueOf() > lastTimestamp.valueOf()) {
                   lastTimestamp = thisTimestamp;
                   lastTimestampText = match;
               }
               ntimestamps++;
           });
           // was done incorrrectly in local time, convert from UTC
           lastTimestamp.setMinutes(
              lastTimestamp.getMinutes()-lastTimestamp.getTimezoneOffset()
           );
           var age = (new Date()).getTime() - lastTimestamp.getTime();
           var hideDefault = false;
           if (age > 21600000) // 6 hours
              hideDefault = true;
           if(innerSection.textContent.length < 600) // bytes
              hideDefault = false; // no reason to hide in this case
           if(ntimestamps < 2) // unanswered
              hideDefault = false;

           // hide if resolved, also, place the resolved header in the visible part.
           var resolved = getElementsByClassName(innerSection,'DIV','resolved');
           if(resolved.length) {
             resolved = resolved[0];
             // [1] to skip an annoying whitespace node
             if (resolved != innerSection.firstChild && resolved != innerSection.childNodes[1]) resolved = resolved.cloneNode(true);
             section.insertBefore(resolved,innerSection);
             hideDefault = true;
           }

           section.insertBefore(document.createTextNode('Last: ' + lastTimestampText + ".  "),innerSection);
           section.insertBefore(document.createTextNode(innerSection.textContent.length + " text bytes. "),innerSection);
           section.insertBefore(document.createTextNode(ntimestamps + " comments. "),innerSection);

           (function ani_sections_closure(){
               var header = headers[i];
               var innerSectionFix = innerSection;
               var button = document.createElement('BUTTON');
               if(hideDefault)
               button.textContent = 'show';
               else
               button.textContent = 'hide';
               button.onclick = function ani_sections_onclick() {
                   if(innerSectionFix.style.display == 'none') {
                     innerSectionFix.style.display = 'block';
                     this.textContent = 'hide'; }
                   else {
                     innerSectionFix.style.display = 'none';
                     this.textContent = 'show'; }
               }
               header.insertBefore(button,header.firstChild);
               button.style.cssText='float: right';
               if(hideDefault) innerSection.style.display='none';
           })();
       }
   });
}
// }}}

/* proof of concept for edit summary length. Not yet converted to wikipedia
<script>
window.onload = function() {
	var box = document.getElementById("editsummary")
	var len = document.getElementById("length_value")
	function utfslop(s) {
		var count = 3;
		for(var i=0;i<s.length;i++) {
			if(s[i] > '\u007f') count++;
			if(s[i] > '\u07ff') count++;
		}
		return count;
	}
	box.onkeypress = function(evt) {
		this.maxLength = 255 - utfslop(this.value);
		if(this.value.length > this.maxLength)
			this.value = this.value.substr(0,this.maxLength);
	}
}
</scr\ipt>
<input id="editsummary">
<input id="length_value">
*/

/* addOnloadHook(function() {
   var item = mw.util.addPortletLink('p-cactions','','ßsocks','ca-betasocks','Check socks with Betacommand\'s tool','',null);
   var link=item.firstChild;
   link.onclick = function() {
       jsMsg('<form action="http://tools.wikimedia.de/~betacommand/cgi-bin/compare">'+
'<table>' +
'<tr><th>Master<\/th><td><input name="master"><\/td><\/tr>' +
'<tr><th>Socks<\/th><td><input name="socks"><\/td><\/tr>' +
'<tr><th>Key<\/th><td><input name="key"><\/td><\/tr>' +
'<tr><td colspan="2"><input type="submit"><\/td><\/tr><\/table>'+'<\/form>','betasocks');
       return false;
   }
}); */

$(function() {
   var p = document.getElementById("p-logo");
   if(!p) return;
   var a = p.firstChild;
   while(a.nodeType != 1) a = a.nextSibling;
   var done = false;
   a.onclick = function() {
       if(!done) this.style.backgroundImage = 'none';
       var ret = done; done = true; return ret;
   }
});

/* convert this bookmarklet later on. javascript:(function(){if(!window['$ssZapClosedXFD']){var x=document.createElement('STYLE');x.textContent='.xfd-closed{display:none} .boilerplate.metadata.vfd{display:none}';
document.getElementsByTagName('HEAD')[0].appendChild(x);
window['$ssZapClosedXFD']=x.sheet}else{
window['$ssZapClosedXFD'].disabled=!window['$ssZapClosedXFD'].disabled}})(); */

/* snippet for WP:AN semi-protection, look at later
if (wgEditRestriction.length > 0) {
  addOnloadHook(function() {
    var msg_cantedit = document.getElementById("cantedit-msg");
    var msg_isprotected = document.getElementById("isprotected-msg");
    if(!msg_cantedit && !msg_isprotected) 
    var canEdit = false;
    for(var i=0;i<wgUserGroups.length;i++) {
        for(var ii=0;ii<wgEditRestriction.length;ii++) {
            if(wgUserGroups[i] == wgEditRestriction[ii]) canEdit = true;
        }
    }
    if(canEdit) { if(msg_isprotected) msg_isprotected.style.display='block'; }
    else { if(msg_cantedit) msg_cantedit.style.display='block'; }
  });
}
*/

if(wgPageName == 'Special:Watchlist') {
  addOnloadHook(function() {
    document.forms[0].method = 'get'; // TODO make more robust
  });
}

function addEditWarnings(warntext) {
  if(!warntext) warntext = "Are you sure you want to edit this page?";
  function do_warn() {
    return confirm(warntext);
  }
  var spans = document.getElementsByTagName('SPAN');
  for(var i=0;i<spans.length;i++) {
    if(/\beditsection\b/.test(spans[i].className)) mkEvt(spans[i],'click',do_warn);
  }
  mkEvt(document.getElementById('ca-edit'),'click',do_warn);
}

function logCalls(obj,prop) {
    var oldfn = obj[prop];
    obj[prop] = (function(ofn,nm) {
    return (function() 
    {
        var ret = ofn.apply(this,arguments);
        console.debug("called %s on %o with arguments %o, returned %o",nm,this,arguments,ret);
    });
    })(oldfn,prop);
}

logCalls(window,'hookEvent');
logCalls(window,'addHandler');
logCalls(window,'addClickHandler');



$(function() {
  var uploadtab = document.getElementById('t-upload');
  if(!uploadtab) return
  var uploadtablink = uploadtab.getElementsByTagName('a')[0];
  if(!uploadtablink) return;
  uploadtablink.href = wgArticlePath.replace('\$1','Special:Upload');
});

function shortenTabs() {
    function st(id, text) {
     try {
      document.getElementById(id).getElementsByTagName('A')[0].textContent = text;
      } catch(x) {}
    }
    function img(src,alt) {
        var x=document.createElement('IMG');
        x.src=src;
        x.alt=alt;
        return x;
    }
    st('ca-edit','Edit');
    st('ca-talk','Talk');
    st('ca-delete','Delete');
    st('ca-protect','Prot.');
    var unprotect = document.getElementById('ca-unprotect');
    if(unprotect) {
       unprotect = unprotect.getElementsByTagName('A')[0];
       unprotect.textContent = '';
       if(wgRestrictionEdit[0] && wgRestrictionEdit[0] == "autoconfirmed")
            unprotect.appendChild(img('http://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Padlock-silver-medium.svg/16px-Padlock-silver-medium.svg.png','SP'));
       if(wgRestrictionEdit[0] && wgRestrictionEdit[0] == "sysop")
            unprotect.appendChild(img('http://upload.wikimedia.org/wikipedia/en/thumb/5/59/Padlock.svg/16px-Padlock.svg.png','FP'));
       else if(wgRestrictionMove[0] && wgRestrictionMove[0] == "sysop")
            unprotect.appendChild(img('http://upload.wikimedia.org/wikipedia/commons/thumb/5/58/Padlock-olive.svg/16px-Padlock-olive.svg.png','MP'))
    }
}

$(shortenTabs);

// Twinkle Lite
importScript('User:AzaToth/morebits.js');
importScript('User:AzaToth/twinklefluff.js');
//importScript('User:AzaToth/twinklewarn.js');
//importScript('User:AzaToth/twinklearv.js');
//importScript('User:AzaToth/twinklespeedy.js');
importScript('User:AzaToth/twinklediff.js');
//importScript('User:AzaToth/twinkleprotect.js');
//importScript('User:AzaToth/twinkleprod.js');
//importScript('User:AzaToth/twinklexfd.js');
//importScript('User:AzaToth/twinkleimage.js');
//importScript('User:AzaToth/twinkleunlink.js');
//importScript('User:AzaToth/twinkledelimages.js');
//importScript('User:AzaToth/twinkledeprod.js');
//importScript('User:AzaToth/twinklebatchdelete.js');
//importScript('User:AzaToth/twinklebatchprotect.js');
//importScript('User:AzaToth/twinkleimagetraverse.js');

// install [[User:Cacycle/wikEdDiff]] enhanced diff view using ajax
document.write('<script type="text/javascript" src="'
+ 'http://en.wikipedia.org/w/index.php?title=User:Cacycle/wikEdDiff.js'
+ '&action=raw&ctype=text/javascript&dontcountme=s"><\/script>');

/*
var fractions = {
2:{1:'½'},3:{1:'⅓',2:'⅔'},4:{1:'¼',3:'¾'},8:{1:'⅛',3:'⅜',5:'⅝',7:'⅞'}
/*,5:{1:'⅕',2:'⅖',3:'⅗',4:'⅘'},6:{1:'⅙',5:'⅚'}*//*
};

function fixfracs() {
 var spans = document.getElementsByTagName('SPAN');
 for(var i=0;i<spans.length;i++) { var span=spans[i];
   if(span.className != 'template-frac') continue;
   var den = span.lastChild.textContent;
   var num = span.firstChild.textContent;
   if(fractions[den] && fractions[den][num]) {
   span.textContent = fractions[den][num];
   span.className = 'template-frac-vulgarized';
  }
 }
}

$(fixfracs);
*/

function toolsbreak() {
function del(x) {
var y = document.getElementById(x);
if(!y) return;
document.removeElement(y)
}
del("ca-delete");
del("ca-undelete");
del("ca-protect");
// not removing ca-unprotect since i've configured it to show
// accurate information about the current protection status
del("t-blockip");
}

$(toolsbreak);