User:Cooljeanius/monobook.js

From Wikipedia, the free encyclopedia

If a message on your talk page led you here, please be wary of who left it. Code that you insert on this page could contain malicious content capable of compromising your account. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. If this is a .js page, the code will be executed when previewing the page.
Note: After saving, you have to bypass your browser's cache to see the changes. In Internet Explorer and Firefox, hold down the Ctrl key and click the Refresh or Reload button. Opera users have to clear their caches through Tools→Preferences, see the instructions for Opera. Konqueror and Safari users can just click the Reload button.
/////////////////////////////////////////
// By Alek Storm
// Please see talk page for instructions
/////////////////////////////////////////
 
var body; // shortcut for body node
var xmlhttp; // XMLHTTPRequest object
var startNode; // div that includes section header and edit link
var editSec; // edit link
var editForm; // spliced edit form
var preview; // spliced preview or diff content
var oldContent; // original content of section
var xmlhttpDone = false; // kludge to prevent multiple calls to callback
 
importScript("User:Supadawg/util.js");
 
function inc(path) {
  var lt = String.fromCharCode(60);
  var gt = String.fromCharCode(62);
  document.writeln(lt+'script type="text/javascript" src="/w/index.php?title='+path+'&action=raw&ctype=text/javascript&dontcountme=s"'+gt+lt+'/script'+gt);
}
 
function initSecEdit()
{
  body = document.getElementsByTagName("body")[0];
 
  // apply to all divs of class "editsection"
  var editSecs = document.getElementsByTagName("span");
  var secCount = 1;
  var pagetitleRe=/\/(wiki\/|w\/index\.php\?title=)([^&?]*)/; // from [Wikipedia:WikiProject User scripts/Techniques]
  for ( var i = 0; i < editSecs.length; i++ ) {
    if ( editSecs[i].getAttribute("class") == "editsection" ) {
      for ( var k = 0; k < editSecs[i].childNodes.length; k++ ) {
        if ( editSecs[i].childNodes[k].nodeName == "A" ) {
          // grab editing uri, escape it, then put it back in
          var editURI = "http://en.wikipedia.org/w/index.php?title="+encodeURIComponent2(pagetitleRe.exec(decodeURI(editSecs[i].childNodes[k].getAttribute("href")))[2]).replace(/\"/gi, "%22").replace(/\'/gi, "%27")+"&action=edit&section="+secCount;
          // give it a unique id
          editSecs[i].childNodes[k].setAttribute( "id", "editSection"+secCount );
          // swap the href with a function call, passing the original href as the second parameter
          editSecs[i].childNodes[k].setAttribute( "href", "javascript:editSection( document.getElementById('editSection" + secCount + "'), '"+editURI+"' );" );
          secCount++;
        }
      }
    }
  }
}
 
// called on click of section edit link
function editSection( elem, editURI )
{
  cancelEdit(); // get rid of any other sections being edited
  editSec = elem;
  startNode = elem.parentNode.parentNode;
 
  // initiate xmlhttprequest for section edit page
  xmlhttpDone = false;
  xmlhttp = null // kludge
  xmlhttp = createXMLHTTP( "GET", editURI, stateChange );
}
 
// put raw input returned from XMLHTTPRequest into a div so we can grab specific elements
function makeDiv( rawHTML )
{
  var div = createNode( body, "div", {style: "visibility: hidden; position: absolute;"} );
  div.innerHTML = rawHTML.replace(/<script[^>]*><\/script>/gi, ""); // if script tags are placed into the DOM, they force reload of files, and nasty things happen
  return div;
}
 
function isHTag( node )
{
  return node.nodeName.charAt(0) == 'H' && !isNaN( parseInt( node.nodeName.charAt(1) ) );
}
 
// callback for onclick of an edit link
function stateChange()
{
  if ( xmlhttp && xmlhttp.readyState == 4 ) {
    if ( xmlhttp.status == 200 ) {
      if ( xmlhttpDone )
        return;
      xmlhttpDone = true;
 
      // store old content of section - loop until we hit header of same spot in hierarchy
      if ( !oldContent ) {
        oldContent = makeDiv("");
        var curElem = startNode.nextSibling;
        while ( curElem ) {
          var hitSiblingSection = false;
          if ( isHTag( curElem ) ) {
            for ( var i = 0; i < curElem.childNodes.length; i++ ) {
              if ( curElem.childNodes[i].nodeName == "SPAN"
                   && curElem.childNodes[i].getAttribute("class") == "editsection"
                   && parseInt( curElem.nodeName.charAt(1) ) <= parseInt( startNode.nodeName.charAt(1) ) )
                  hitSiblingSection = true;
            }
          }
          else if ( curElem.nodeName == "DIV" && curElem.getAttribute("class") == "printfooter" )
            break;
 
          if ( hitSiblingSection )
            break;
          var nextElem = curElem.nextSibling;
          oldContent.appendChild( curElem );
          curElem = nextElem;
        }
      }
      else
        removeNode( oldContent );
 
      var div = makeDiv( xmlhttp.responseText );
      editForm = $("editform");
      // change onclick of preview and diff buttons to our function
      $("wpPreview").setAttribute( "type", "button" );
      $("wpPreview").setAttribute( "onclick", "javascript:getEditData( previewChanged, $('wpPreview') );" );
      $("wpDiff").setAttribute( "type", "button" );
      $("wpDiff").setAttribute( "onclick", "javascript:getEditData( diffChanged, $('wpDiff') );" );
      insertAfter( editForm, startNode );
      removeNode( div );
 
      editSec.setAttribute( "oldHref", editSec.getAttribute("href") );
      editSec.setAttribute( "href", "javascript:cancelEdit();" );
      editSec.innerHTML = "cancel";
    }
    else
      alert("Problem retrieving data - status: "+xmlhttp.status);
  }
}
 
// firefox hack, not sure if this is a problem in other browsers
function encodeURIComponent2( content )
{
  // from [http://en.wikipedia.org/wiki/User:Topaz/wputil.js]
  content = content.replace(/\&lt\;/gi, "<");
  content = content.replace(/\&gt\;/gi, ">");
  content = content.replace(/\&quot\;/gi, "\"");
  content = content.replace(/\&amp\;/gi, "&");
  return encodeURIComponent( content );
}
 
// encode differently based on type of form element
function field2Post( node, allowButton )
{
  var reqBody = "";
  switch ( node.nodeName ) {
    case "TEXTAREA":
      reqBody += "&"+node.getAttribute("name")+"="+encodeURIComponent2( node.value );
      break;
    case "INPUT":
      var inputType = node.getAttribute("type");
      if ( inputType == "checkbox" ) {
        if ( node.checked )
          reqBody += "&"+node.getAttribute("name")+"=on"
      }
      else if ( allowButton || (inputType != "submit" && inputType != "button") )
        reqBody += "&"+node.getAttribute("name")+"="+encodeURIComponent2( node.value );
      break;
    case "DIV":
      reqBody += form2Post( node, false );
      break;
  }
  return reqBody;
}
 
// manually encodes a form element for XMLHTTPRequest
function form2Post( node )
{
  var reqBody = "";
  for ( var i = 0; i < node.childNodes.length; i++ )
    reqBody += field2Post( node.childNodes[i], false );
  return reqBody;
}
 
// get preview or diff data
function getEditData( callback, clickedBut )
{
  xmlhttpDone = false;
  xmlhttp = null; // kludge
  var action = editForm.getAttribute("action");
  xmlhttp = createXMLHTTP( "POST", "http://en.wikipedia.org"+action, callback, {
    body: form2Post( editForm ) + field2Post( clickedBut, true ),
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Referer": "http://en.wikipedia.org" + action.substring( 0, action.indexOf('&') ) + "&action=edit&section="+(parseInt(editSec.getAttribute("id").substring(11))+1)
    }
  } );
}
 
// callback for preview data
function previewChanged()
{
  if ( xmlhttp && xmlhttp.readyState == 4 ) {
    if ( xmlhttp.status == 200 ) {
      if ( xmlhttpDone )
        return;
      xmlhttpDone = true;
      var div = makeDiv( xmlhttp.responseText );
      if ( preview )
        removeNode( preview );
      preview = $("wikiPreview");
      insertAfter( preview, startNode );
      removeNode( div );
    }
    else
      alert("Problem retrieving data - status: "+xmlhttp.status);
  }
}
 
// callback for diff data
function diffChanged()
{
  if ( xmlhttp && xmlhttp.readyState == 4 ) {
    if ( xmlhttp.status == 200 ) {
      if ( xmlhttpDone )
        return;
      xmlhttpDone = true;
      var div = makeDiv( xmlhttp.responseText );
      if ( preview )
        removeNode( preview );
      preview = $("wikiDiff");
      insertAfter( preview, startNode );
      removeNode( div );
    }
    else
      alert("Problem retrieving data - status: "+xmlhttp.status);
  }
}
 
// remove form and preview or diff data
function cancelEdit()
{
  if ( preview )
    removeNode( preview );
  preview = null;
  if ( editForm )
    removeNode( editForm );
  editForm = null;
  if ( oldContent ) {
    oldContent.setAttribute( "style", "position: static; visibility: visible;" );
    insertAfter( oldContent, startNode );
  }
  oldContent = null;
  if ( editSec ) {
    editSec.setAttribute( "href", editSec.getAttribute("oldHref") );
    editSec.innerHTML = "edit";
  }
}
 
addEventListener( "load", initSecEdit, false );
 
importScript('User:Cameltrader/Advisor.js');
 
*/
//Wikipedia:WikiProject User scripts | Scripts
 
function format() {
    var txt = document.editform.wpTextbox1;
    txt.value = catFixer(txt.value);
    txt.value = entities(txt.value);
    txt.value = fixheadings(txt.value);
    txt.value = fixsyntax(txt.value);
    txt.value = linkfixer(txt.value, false);
    //txt.value = imagefixer(txt.value);
    txt.value = whitespace(txt.value);
    txt.value = linksimplifyer(txt.value);
    txt.value = trim(txt.value);
}
 
function whitespace(str){
    str = str.replace(/\t/g, " ");
 
    str = str.replace(/^ ? ? \n/gm, "\n");
    str = str.replace(/(\n\n)\n+/g, "$1");
    str = str.replace(/== ? ?\n\n==/g, "==\n==");
    str = str.replace(/\n\n(\* ?\[?http)/g, "\n$1");
 
    str = str.replace(/^ ? ? \n/gm, "\n");
    str = str.replace(/\n\n\*/g, "\n*");
    str = str.replace(/[ \t][ \t]+/g, " ");
    str = str.replace(/([=\n]\n)\n+/g, "$1");
    str = str.replace(/ \n/g, "\n");
 
    //* bullet points
    str = str.replace(/^([\*#]+) /gm, "$1");
    str = str.replace(/^([\*#]+)/gm, "$1 ");
 
    //==Headings==
    str = str.replace(/^(={1,4}) ?(.*?) ?(={1,4})$/gm, "$1$2$3");
 
    //dash — spacing
    str = str.replace(/ ?(–|&#150;|&ndash;|&#8211;|&#x2013;) ?/g, "$1");
    str = str.replace(/ ?(—|&#151;|&mdash;|&#8212;|&#x2014;) ?/g, "$1");
    str = str.replace(/([^1-9])(—|&#151;|&mdash;|&#8212;|&#x2014;|–|&#150;|&ndash;|&#8211;|&#x2013;)([^1-9])/g, "$1 $2 $3");
 
    return trim(str);
}
 
function entities(str){
    //str = str.replace(//g, "");
    str = str.replace(/&#150;|&#8211;|&#x2013;/g, "&ndash;");
    str = str.replace(/&#151;|&#8212;|&#x2014;/g, "&mdash;");
   // str = str.replace(/(cm| m|km|mi)<sup>2</sup>/g, "$1²");
    str = str.replace(/&sup2;/g, "²");
    str = str.replace(/&deg;/g, "°");
 
    return trim(str);
}
 
//Fix ==See also== and similar section common errors.
function fixheadings(str)
{
  if( !str.match(/= ?See also ?=/) )
    str = str.replace(/(== ?)(see also:?|related topics:?|related articles:?|internal links:?|also see:?)( ?==)/gi, "$1See also$3");
 
  str = str.replace(/(== ?)(external links?:?|outside links?|web ?links?:?|exterior links?:?)( ?==)/gi, "$1External links$3");
  str = str.replace(/(== ?)(references?:?)( ?==)/gi, "$1References$3");
  str = str.replace(/(== ?)(sources?:?)( ?==)/gi, "$1Sources$3");
  str = str.replace(/(== ?)(further readings?:?)( ?==)/gi, "$1Further reading$3");
 
  return str;
}
 
function catFixer(str){
    str = str.replace(/\[\[ ?[Cc]ategory ?: ?/g, "[[Category:");
 
    return trim(str);
}
 
//fixes many common syntax problems
function fixsyntax(str)
{
  //replace html with wiki syntax
  if( !str.match(/'<\/?[ib]>|<\/?[ib]>'/gi) )
  {
    str = str.replace(/<i>(.*?)<\/i>/gi, "''$1''");
    str = str.replace(/<b>(.*?)<\/b>/gi, "'''$1'''");
  }
  str = str.replace(/<br\/>/gi, "<br />");
  str = str.replace(/<br>/gi, "<br />");
 
  return trim(str);
}
 
//formats links in standard fashion
function linkfixer(str, checkImages)
{ 
  str = str.replace(/\]\[/g, "] [");
  var m = str.match(/\[?\[[^\]]*?\]\]?/g);
  if (m)
  {
    for (var i = 0; i < m.length; i++)
    {
      var x = m[i].toString();
      var y = x;
 
      //internal links only
      if ( !y.match(/^\[?\[http:\/\//i) && !y.match(/^\[?\[image:/i) )
      {
        if (y.indexOf(":") == -1 && y.substr(0,3) != "[[_" && y.indexOf("|_") == -1)
        {
          if (y.indexOf("|") == -1)
            y = y.replace(/_/g, " ");
          else
            y = y.replace( y.substr(0, y.indexOf("|")), y.substr(0, y.indexOf("|")).replace(/_/g, " "));
        }  
 
        y = y.replace(/ ?\| ?/, "|").replace("|]]", "| ]]");
 
      }
 
      str = str.replace(x, y);
    }
  }
 
  //repair bad internal links
  str = str.replace(/\[\[ ?([^\]]*?) ?\]\]/g, "[[$1]]");
  str = str.replace(/\[\[([^\]]*?)( |_)#([^\]]*?)\]\]/g, "[[$1#$3]]");
 
  //repair bad external links
  str = str.replace(/\[?\[http:\/\/([^\]]*?)\]\]?/gi, "[http://$1]");
  str = str.replace(/\[http:\/\/([^\]]*?)\|([^\]]*?)\]/gi, "[http://$1 $2]");
 
  return trim(str);
}
 
//fixes images
function imagefixer(str)
{
 
  //remove external images
  str = str.replace(/\[?\[image:http:\/\/([^\]]*?)\]\]?/gi, "[http://$1]");
 
  //fix links within internal images
  var m = str.match(/\[?\[image:[^\[\]]*?(\[?\[[^\]]*?\]*?[^\[\]]*?)*?\]+/gi);
  if (m)
  {
    for (var i = 0; i < m.length; i++)
    {
      var x = m[i].toString();
      var y = x;
 
      y = y.replace(/^\[\[i/i, "I").replace(/\]\]$/, "");
      y = y.replace(/(\[[^\]]*?)$/, "$1]");
      y = linkfixer(y, true);
      y = "[[" + y + "]]";
 
      str = str.replace(x, y);
    }
  }
 
  return trim(str);
}
 
//simplifies some links e.g. [[Dog|dog]] to [[dog]] and [[Dog|dogs]] to [[dog]]s
function linksimplifyer(str){
  var m = str.match(/\[\[([^[]*?)\|([^[]*?)\]\]/g);
  if (m)
  {
    for (var i = 0; i < m.length; i++)
    {
      var n_arr = m[i].toString().match(/\[\[([^[]*?)\|([^[]*?)\]\]/);
      var n = n_arr[0];
      var a = n_arr[1];
      var b = n_arr[2];
 
      if (b.indexOf(a) == 0 || b.indexOf(TurnFirstToLower(a)) == 0)
      {
        var k = n.replace(/\[\[([^\]\|]*?)\|(\1)([\w]*?)\]\]/i, "[[$2]]$3");
        str = str.replace(n, k);
      }
    }
  }
 
  str = str.replace(/\[\[([^\]\|]+)\|([^\]\|]+)\]\]([A-Za-z\'][A-Za-z]*)([\.\,\;\:\"\!\?\s\n])/g, "[[$1|$2$3]]$4"); // ' // Help the syntax highlighter...
 
  return str;
}
 
//trim start and end, trim spaces from the end of lines
function trim(str) {
   str = str.replace(/ $/gm, "");
   return str.replace(/^\s*|\s*$/g, "");
}
 
//turns first character to lowercase
function TurnFirstToLower(input) {
  if (input != "")
  {
    var input = trim(input);
    var temp = input.substr(0, 1);
    return temp.toLowerCase() + input.substr(1, input.length);
  }
  else
    return "";
}
 
//entities that should never be unicoded
function noUnicodify(str) {
  str = str.replace(" &amp; ", " & ");
  str = str.replace("&amp;", "&amp;amp;").replace("&amp;lt;", "&amp;amp;lt;").replace("&amp;gt;", "&amp;amp;gt;").replace("&amp;quot;", "&amp;amp;quot;").replace("&amp;apos;", "&amp;amp;apos;");
  str = str.replace("&minus;", "&amp;minus;").replace("&times;", "&amp;times;");
 
  str = str.replace("&nbsp;", "&amp;nbsp;").replace("&thinsp;", "&amp;thinsp;").replace("&shy;", "&amp;shy;");
  str = str.replace("&prime;", "&amp;prime;");
  str = str.replace(/&(#0?9[13];)/, "&amp;$1");
  str = str.replace(/&(#0?12[345];)/, "&amp;$1");
 
  return str;
}
 
addOnloadHook(function () {
  if(document.forms.editform) {
    addPortletLink('p-cactions', 'javascript:format()', 'format', 'ca-format', 'Format article', '', document.getElementById('ca-edit'));
  }
});
 
/*
 
/* Watchlist notifier ([[User:Ais523/watchlistnotifier.js]]); displays a message every time a watched page changes. */
//<pre><nowiki>
 
var wmwpajax;
// From [[WP:US]] mainpage (wpajax renamed to wmwpajax)
wmwpajax={
        download:function(bundle) {
                // mandatory: bundle.url
                // optional:  bundle.onSuccess (xmlhttprequest, bundle)
                // optional:  bundle.onFailure (xmlhttprequest, bundle)
                // optional:  bundle.otherStuff OK too, passed to onSuccess and onFailure
 
                var x = window.XMLHttpRequest ? new XMLHttpRequest()
                : window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP")
                : false;
 
                if (x) {
                        x.onreadystatechange=function() {
                                x.readyState==4 && wmwpajax.downloadComplete(x,bundle);
                        };
                        x.open("GET",bundle.url,true);
                        x.send(null); 
                }
                return x;
        },
 
        downloadComplete:function(x,bundle) {
                x.status==200 && ( bundle.onSuccess && bundle.onSuccess(x,bundle) || true )
                || ( bundle.onFailure && bundle.onFailure(x,bundle) || alert(x.statusText+': '+bundle.url));
        }
};
 
// Example:
// function dlComplete(xmlreq, data) {
//      alert(data.message + xmlreq.responseText);
// }
//  wmwpajax.download({url:'http://en.wikipedia.org/w/index.php?title=Thresher&action=raw', 
//                   onSuccess: dlComplete, message: "Here's what we got:\n\n" });
 
// End of [[WP:US]] quote
 
function wmWatchEditFound(xmlreq, data) {
  var watchrev, watchsum, watchrevold, watchpage, junk;
  if(xmlreq.responseText.indexOf('revid=')==-1)
  {
    document.getElementById('contentSub').innerHTML+=
      "<div class='watchlistnotify'>(<i>watchlistnotifier can't determine whether a "+
      "watched page has changed<i>)</div>";
    return;
  }
  watchrev=xmlreq.responseText.split('revid="')[1].split('"')[0];
  try
  {
    watchrevold=document.cookie.split('ais523wmwatchrev=')[1].split('.')[0];
  }
  catch(junk) {watchrevold=0;}
  if(wgPageName == "Special:Watchlist")
  {
    document.cookie="ais523wmwatchrev="+watchrev+".; path=/";
    var aas=document.getElementById('bodyContent').getElementsByTagName('a');
    var i=aas.length;
    while(i--)
    {
      if(aas[i].href.indexOf('diff=')!=-1&&watchrevold)
        if(+(aas[i].href.split('diff=')[1].split('&')[0])>watchrevold)
          aas[i].parentNode.style.fontWeight='bold';
    }
  }
  else
  {
    watchsum=xmlreq.responseText.split('comment="')[1].split('"')[0];
    watchpage=xmlreq.responseText.split('title="')[1].split('"')[0];
    watchsum=watchsum.split('<').join('&lt;').split('>').join('&gt;');
    watchpage=watchpage.split('<').join('&lt;').split('>').join('&gt;');
    if(watchrev!=watchrevold)
      document.getElementById('contentSub').innerHTML+=
        "<div class='watchlistnotify'>\""+watchpage+'" changed: "'+watchsum+
        '". (<a href="/wiki/Special:Watchlist">watchlist</a>)</div>';
  }
}
 
addOnloadHook(function() {
  /* Find the top item in the watchlist, and its edit summary. We only need one item, so
     set the limit to 1 to ease the load on the server. */
    wmwpajax.download({url:'http://en.wikipedia.org/w/api.php?action=query&list=watchlist&wllimit=1&'+
      'wldir=older&format=xml&wlprop=comment|ids|title', onSuccess: wmWatchEditFound});
});
// </nowiki></pre>
// [[Category:Wikipedia scripts]]
 
// Add date and time to your monobook "personal menu" list at the very top of the page.
// Created by [[User:Mathwiz2020]]
 
// Indicate where you would like the time to appear:
// 1 is first (before username), 2 is second (before talk link), ... 7 is last (after log out link)
insertBeforeNum = 7;
 
// Do NOT edit below this line unless you're experiened in javascript
insertBeforeArr = new Array("","pt-userpage","pt-mytalk","pt-preferences","pt-watchlist","pt-mycontris","pt-logout","");
insertBefore = insertBeforeArr[insertBeforeNum];
 
function makeTime()
{
  var li = document.createElement( 'li' );
  li.id = 'pt-time';
 
  var mySpan = document.createElement( 'span' );
  mySpan.appendChild( document.createTextNode( 'date and time' ) );
 
  li.appendChild( mySpan );
 
  if ( insertBefore )
  {
    var before = document.getElementById( insertBefore );
    before.appendChild( li, before );
  }
  else // append to end (right) of list
  {
    document.getElementById( 'pt-logout' ).parentNode.appendChild( li );
  }
 
  getTime();
}
 
if      ( window.addEventListener ) window.addEventListener ( 'load', makeTime, false );
else if ( window.attachEvent      ) window.attachEvent      ( 'onload', makeTime      );
 
function getTime()
{
    var time    = new Date();
    var date    = time.getUTCDate();
    var months  = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ');
        month   = months[time.getUTCMonth()];
    var year    = time.getUTCFullYear();
    var hours   = '0' + time.getUTCHours();
        hours   = hours.substr(hours.length-2, hours.length);
    var minutes = '0' + time.getUTCMinutes();
        minutes = minutes.substr(minutes.length-2, minutes.length);
    var seconds = '0' + time.getUTCSeconds();
        seconds = seconds.substr(seconds.length-2, seconds.length);
    var curTime = hours + ":" + minutes + ":" + seconds + ", " + date + " " + month + " " + year + " (UTC)";
    datePlace   = document.getElementById('pt-time').childNodes[0].childNodes[0];
                  datePlace.replaceData(0, datePlace.length, curTime);
    doTime      = window.setTimeout("getTime()", 1000);
}
//
 
importScript('User:AzaToth/twinkle.js');