MediaWiki:Common.js: Difference between revisions

From wiki.jriver.com
Jump to navigation Jump to search
No edit summary
No edit summary
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
/* Any JavaScript here will be loaded for all users on every page load. */
/* Any JavaScript here will be loaded for all users on every page load. */


// Wikia's own WikiaScriptLoader isn't automatically included in other skins such as monobook.
// add &__vanilla=1 to URL to disable all scripts except gadgets (as enabled in [[Special:Preferences]])
// Presumably this is because they no longer support them. This checks to see if WikiaScriptLoader
if (mw.util.getParamValue('__vanilla'))
// function reference has been declared, and if it has not, it creates it. Backwards compatibility
throw void 0; // return is invalid here. oh well.
// for everybody! - Blame User:Tierrie @ DA Wiki if this works. Blame someone else if it breaks.
if(typeof WikiaScriptLoader === 'undefined') {
/*
var WikiaScriptLoader=WikiaScriptLoader?WikiaScriptLoader:function(){var b=navigator.userAgent.toLowerCase();this.useDOMInjection=b.indexOf("opera")!=-1||b.indexOf("firefox")!=-1&&b.indexOf("/4.0b")==-1;this.isIE=b.indexOf("opera")==-1&&b.indexOf("msie")!=-1;this.headNode=document.getElementsByTagName("HEAD")[0]}; WikiaScriptLoader.prototype={loadScript:function(b,c){this.useDOMInjection?this.loadScriptDOMInjection(b,c):this.loadScriptDocumentWrite(b,c)},loadScriptDOMInjection:function(b,c){var a=document.createElement("script");a.type="text/javascript";a.src=b;var d=function(){a.onloadDone=true;typeof c=="function"&&c()};a.onloadDone=false;a.onload=d;a.onreadystatechange=function(){a.readyState=="loaded"&&!a.onloadDone&&d()};this.headNode.appendChild(a)},loadScriptDocumentWrite:function(b,c){document.write('<script src="'+ b+'" type="text/javascript"><\/script>');var a=function(){typeof c=="function"&&c()};typeof c=="function"&&this.addHandler(window,"load",a)},loadScriptAjax:function(b,c){var a=this,d=this.getXHRObject();d.onreadystatechange=function(){if(d.readyState==4){var e=d.responseText;if(a.isIE)eval(e);else{var f=document.createElement("script");f.type="text/javascript";f.text=e;a.headNode.appendChild(f)}typeof c=="function"&&c()}};d.open("GET",b,true);d.send("")},loadCSS:function(b,c){var a=document.createElement("link"); a.rel="stylesheet";a.type="text/css";a.media=c||"";a.href=b;this.headNode.appendChild(a)},addHandler:function(b,c,a){if(window.addEventListener)window.addEventListener(c,a,false);else window.attachEvent&&window.attachEvent("on"+c,a)},getXHRObject:function(){var b=false;try{b=new XMLHttpRequest}catch(c){for(var a=["Msxml2.XMLHTTP.6.0","Msxml2.XMLHTTP.3.0","Msxml2.XMLHTTP","Microsoft.XMLHTTP"],d=a.length,e=0;e<d;e++){try{b=new ActiveXObject(a[e])}catch(f){continue}break}}return b}};window.wsl=new WikiaScriptLoader;
== [[WT:PREFS]] v2.0 ==
*/

try { (function () {
"use strict";

var prefs;
try {
prefs = window.localStorage.getItem('AGprefs');
} catch (e) {
prefs = jQuery.cookie('AGprefs');
}
}
prefs = prefs && (window.JSON ? window.JSON.parse(prefs) : eval('(' + prefs + ')'));


/** Archive edit tab disabling *************************************
if (wgUserGroups.indexOf('autoconfirmed') !== -1)
* Disables the edit tab on old forum topic pages to stop new people bumping old topics.
return;
* Page can still be edited by going via the edit tab on the history etc, or by

* typing the edit address manually.
if (wgUserGroups.indexOf('user') === -1)
* By [[User:Spang|Spang]]
if ((wgAction === 'view') && (wgPageName === 'Wiktionary:Preferences/V2')) {
* Monaco support by [[User:Uberfuzzy|Uberfuzzy]]
mw.loader.load('ext.gadget.AGprefs');
* Copied from [[w:c:Community:MediaWiki:Common.js]] on 3-Sep-2010
*/
if(wgNamespaceNumber == 110) {
function disableOldForumEdit() {
if( typeof( enableOldForumEdit ) != 'undefined' && enableOldForumEdit )
return;
if(!document.getElementById('old-forum-warning') ||
!document.getElementById('ca-edit') )
return;
if( skin == 'monaco' )
{
editLink = document.getElementById('ca-edit');
}
}
else if( skin == 'monobook' )

{
if (!prefs)
editLink = document.getElementById('ca-edit').firstChild;
return;

mw.loader.state('the_pope_is_an_atheist_woman_alien', 'missing');
for (var key in prefs.modules) {
if (prefs.modules[key]) {
mw.loader.load(key);
} else {
// unavoidable race condition. to prevent it, every enabled-by-default gadget should have "site" as a dependency
if (mw.loader.getState(key) !== 'ready') {
mw.loader.moduleRegistry[key].dependencies.push('the_pope_is_an_atheist_woman_alien');
mw.loader.state(key, 'missing');
} else {
// XXX
mw.log.warn(key + ": the milk has been spilt.");
}
}
}
editLink.removeAttribute('href', 0);
editLink.removeAttribute('title', 0);
editLink.style.color = 'gray';
editLink.innerHTML = 'Archived';
$('span.editsection-upper').remove();
}
}
addOnloadHook( disableOldForumEdit );

for (var key in prefs.sheets) {
importStylesheet('MediaWiki:Gadget-' + key);
}
}


/*
for (var key in prefs.scripts) {
Replaces {{USERNAME}} with the name of the user browsing the page.
importScript('MediaWiki:Gadget-' + key);
Requires copying Template:USERNAME.
}
*/


function UserNameReplace() {
if (wgUserGroups.indexOf('user') !== -1) {
if(typeof(disableUsernameReplace) != 'undefined' && disableUsernameReplace || wgUserName == null) return;
var changes = [];
$("span.insertusername").html(wgUserName);
for (var key in prefs.gadgets)
}
changes.push('gadget-' + key + '=' + (prefs.gadgets[key] ? '1' : '0'));
addOnloadHook(UserNameReplace);


/* Test if an element has a certain class **************************************
(new mw.Api()).postWithToken('options', {
action: 'options',
change: changes.join('|')
}).fail(function () {
jQuery.cookie('AGprefs', null);
try { window.localStorage.removeItem('AGprefs'); } catch (e) { /* */ }
mw.util.jsMessage(
'<b>Your <a href="/wiki/Wiktionary:Preferences/V2">per-browser preferences</a> have been migrated</b><br/><br/>' +
'From now on, you should use your <a href="/wiki/Special:Preferenced">user preferences page</a>. ' +
'Preferences will no longer apply after you log out.'
);
});
}

})(); } catch (e) { mw.log.warn(e); }

/*</pre>
===importScript===
<pre>*/

/**
* importScript inserts a javascript page either
* from Wiktionary: importScript('User:Connel MacKensie/yetanother.js');
* from another Wikimedia wiki: importScript('User:Lupin/insane.js','en.wikipedia.org');
*
*
* Description: Uses regular expressions and caching for better performance.
* by specifying the third argument, an oldid can be passed to ensure that updates to the script are not included.
* Maintainers: [[User:Mike Dillon]], [[User:R. Koot]], [[User:SG]]
* by specifying the fourth argument, a specific version of JavaScript can be declared.
*
*/
* based on [[w:MediaWiki:Common.js]] 2007-11-29
**/
function importScript(page, wiki, oldid, jsver) {
if (wiki || oldid || jsver) {
mw.log.warn("importScript called with more than one argument. This may be unreliable.");
}


var hasClass = (function () {
// Default to local
var reCache = {};
if (!wiki) {
return function (element, className) {
wiki=wgScript;
return (reCache[className] ? reCache[className] : (reCache[className] = new RegExp("(?:\\s|^)" + className + "(?:\\s|$)"))).test(element.className);
} else {
};
wiki='//'+escape(wiki)+'/w/index.php';
})();
}


/** Collapsible tables *********************************************************
var url = wiki + '?title='
+ mw.util.wikiUrlencode(page)
+ (oldid ? '&oldid=' + encodeURIComponent(oldid) : '')
+ '&action=raw&ctype=text/javascript';

//Only include scripts once
if (loadedScripts[url]) {
return false;
}
loadedScripts[url] = true;

var scriptElem = document.createElement("script");
scriptElem.setAttribute("src",url);
scriptElem.setAttribute("type", jsver ? "application/javascript;version=" + jsver : "text/javascript");
document.getElementsByTagName("head")[0].appendChild(scriptElem);
return true;
}

/*</pre>
=== DOM creation ===
<pre>*/
/**
* Create a new DOM node for the current document.
* Basic usage: var mySpan = newNode('span', "Hello World!")
* Supports attributes and event handlers*: var mySpan = newNode('span', {style:"color: red", focus: function(){alert(this)}, id:"hello"}, "World, Hello!")
* Also allows nesting to create trees: var myPar = newNode('p', newNode('b',{style:"color: blue"},"Hello"), mySpan)
*
*
* Description: Allows tables to be collapsed, showing only the header. See
* *event handlers, there are some issues with IE6 not registering event handlers on some nodes that are not yet attached to the DOM,
* [[Wikipedia:NavFrame]].
* it may be safer to add event handlers later manually.
* Maintainers: [[User:R. Koot]]
**/
function newNode(tagname){
var node = document.createElement(tagname);

for (var i = 1; i < arguments.length; ++i){
if (typeof arguments[i] == 'string') { // text
node.appendChild(document.createTextNode(arguments[i]));
} else if (typeof arguments[i] == 'object') {
if (arguments[i].nodeName) { //If it is a DOM Node
node.appendChild(arguments[i]);
} else { // Attributes (hopefully)
for (var j in arguments[i]){
if (j == 'class') { //Classname different because...
node.className = arguments[i][j];
} else if (j == 'style') { //Style is special
node.style.cssText = arguments[i][j];
} else if (typeof arguments[i][j] == 'function') { //Basic event handlers
newNode.addEventHandler(node, j, arguments[i][j]);
} else {
node.setAttribute(j, arguments[i][j]); //Normal attributes
}
}
}
}
}

node.addEventHandler = function(eventName, handler) {
newNode.addEventHandler(this, eventName, handler);
};

return node;
}

newNode.addEventHandler = function(node, eventName, handler)
{
try{ node.addEventListener(eventName,handler,false); //W3C
}catch(e){try{ node.attachEvent('on'+eventName,handler,"Language"); //MSIE
}catch(e){ node['on'+eventName]=handler; }} //Legacy
};
/*</pre>

=== CSS ===
<pre>*/

/**
* Cross browser CSS - yurk
* @deprecated: Use mw.util.addCSS() instead
*/
*/
var p_styleSheet=false;
window.addCSSRule = function (selector,cssText) {
mw.log.warn("deprecated function addCSSRule called; use mw.util.addCSS(css) instead");
mw.util.addCSS( selector+'{' + cssText + '}' );
}


var autoCollapse = 2;
/*</pre>
var collapseCaption = "hide";
var expandCaption = "show";


function collapseTable( tableIndex )
===Cookies===
<pre>
*/

/* @deprecated: Use $.cookie instead */
function setCookie(cookieName, cookieValue) {
mw.log.warn("deprecated function setCookie called; use jQuery.cookie instead");
var today = new Date();
var expire = new Date();
var nDays = 30;
expire.setTime( today.getTime() + (3600000 * 24 * nDays) );
document.cookie = cookieName + "=" + escape(cookieValue)
+ ";path=/"
+ ";expires="+expire.toGMTString();
}

function getCookie(cookieName) {
mw.log.warn("deprecated function getCookie called; use jQuery.cookie instead");
var start = document.cookie.indexOf( cookieName + "=" );
if ( start == -1 ) return "";
var len = start + cookieName.length + 1;
if ( ( !start ) &&
( cookieName != document.cookie.substring( 0, cookieName.length ) ) )
{
return "";
}
var end = document.cookie.indexOf( ";", len );
if ( end == -1 ) end = document.cookie.length;
return unescape( document.cookie.substring( len, end ) );
}

function deleteCookie(cookieName) {
mw.log.warn("deprecated function deleteCookie called; use jQuery.cookie instead");
if (getCookie(cookieName)) {
document.cookie = cookieName + "=" + ";path=/" + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
}

/*</pre>

==Wiktionary Customisation==
<pre>*/

if ( document.getElementById('footer') ) {
jQuery.ready()
}

//initialize the storage for script options. Gadgets that set script
//options should also include this line as they are loaded before us.
if ( typeof WiktScriptPrefs == 'undefined') {
WiktScriptPrefs = {};
}

/*</pre>
===[[MediaWiki:Youhavenewmessages]] to display differently for non-newbies with JS than for others===
<pre>*/
/* Suspected unresponsive page culprit: see the GP (Nov. 2010, "Blocking script execution on each page") */
/* if (wgUserGroups && wgUserGroups.join("").indexOf("autoconfirmed") > -1)
{
{
var Button = document.getElementById( "collapseButton" + tableIndex );
addCSSRule(".msgfornewbies", "display: none");
var Table = document.getElementById( "collapsibleTable" + tableIndex );
}else{
addCSSRule(".msgfornonnewbies", "display: none");
} */
/*</pre>


if ( !Table || !Button ) {
===[[WT:FEED]]===
return false;
<pre>*/
}
if ( !wgUserName ) {
importScript('User:Conrad.Irwin/feedback.js');
}
/*</pre>
===WT:PREFS===
<pre>*/

if ( jQuery.cookie('WiktPrefs') || mw.config.get('wgPageName') == "Wiktionary:Per-browser_preferences") {
//importScript('User:Connel_MacKenzie/custom.js');
importScript('User:Hippietrail/custom.js');
}

/*</pre>

===Edit page javascript===
<pre>*/
$(document).ready( function() {
if ( wgAction == 'edit' || wgAction == 'submit' || document.getElementById('editpage-specialchars') ) {
importScript('MediaWiki:Edit.js');
}
});
/*</pre>


var Rows = Table.rows;
===Page specific extensions===
<pre>*/


if ( Button.firstChild.data == collapseCaption ) {
/*</pre>
for ( var i = 1; i < Rows.length; i++ ) {
====Wiktionary:Main Page====
Rows[i].style.display = "none";
<pre>*/
}
// Hide the title and "Redirected from" (maybe we should keep the redirected from so's people update their bookmarks ;)
Button.firstChild.data = expandCaption;
// Broken in IE!
} else {
if ( wgPageName == 'Wiktionary:Main_Page' && !( wgAction == 'view' || wgAction == 'submit' ) ){
for ( var i = 1; i < Rows.length; i++ ) {
mw.util.addCSS( '.firstHeading { display: block !important; }' );
Rows[i].style.display = Rows[0].style.display;
mw.util.addCSS( '#contentSub { display: inline !important; }' );
}
Button.firstChild.data = collapseCaption;
}
}
}


function createCollapseButtons()
if (wgPageName == 'Wiktionary:Main_Page') {
$(function () {
mw.util.addPortletLink('p-lang', '//meta.wikimedia.org/wiki/Wiktionary#List_of_Wiktionaries',
'Complete list', 'interwiki-completelist', 'Complete list of Wiktionaries');
});
}

/*</pre>
====Special:Search====
<pre>*/

if ( wgPageName == 'Special:Search') {
importScript('MediaWiki:SpecialSearch.js');
importScript('User:Yair rand/FindTrans.js');
}
jQuery(document).ready(function () { if(document.getElementById('preloadGuide')) {
importScript('MediaWiki:SpecialSearch.js');
}});

/*</pre>
====Unsupported titles====
<pre>*/

if (wgTitle.indexOf('Unsupported titles/') === 0)
$(document).ready(function () {
//if (wgCanonicalNamespace != 'Appendix') return;
//pages have been moved to mainspace, so commenting out this line
var newTitle;
if (document.getElementById('unsupportedpage')) {
newTitle = document.getElementById('unsupportedpage').title;
} else {
newTitle = "[" + wgTitle.slice(19) + "]";
}
document.getElementById('firstHeading').innerHTML = newTitle;
});

/*</pre>

====Custom search engines====
<pre>*/

if( wgPageName=='Help:Tips_and_tricks' ){
importScript('MediaWiki:CustomSearch.js');
}

/*</pre>

====Turn headings in comments into real headings on JavaScript source pages====
<pre>*/

else if ((wgNamespaceNumber == 2 || wgNamespaceNumber == 8) && wgTitle.lastIndexOf('.js') != -1 && wgAction == 'view') {
importScript('MediaWiki:JavascriptHeadings.js');
}

/*</pre>
====Geonotice====
<pre>*/
/*Ended December 2009
else if (wgPageName == "Special:Watchlist") //watchlist scripts
{
{
var tableIndex = 0;
importScriptURI('http://toolserver.org/~para/geoip.fcgi');
var NavigationBoxes = new Object();
addOnloadHook(function() { importScriptURI('http://en.wiktionary.org/w/index.php?title=MediaWiki:Geonotice.js&action=raw&ctype=text/javascript&maxage=3600'); });
var Tables = document.getElementsByTagName( "table" );
}
*/
/*</pre>
====New-section redirects====
<pre>*/
// This allows the new-section link (the "+" tab) to point to a different
// URL, as specified by the page (so that, for example, the new-section link
// for the Grease pit will add a new section to the appropriate monthly
// subpage):
importScript('MediaWiki:NewSectionRedirects.js');
/*</pre>


for ( var i = 0; i < Tables.length; i++ ) {
===Add editor.js for editing translations===
if ( hasClass( Tables[i], "collapsible" ) ) {
<pre>*/


/* only add button and increment count if there is a header row to work with */
importScript('User:Conrad.Irwin/editor.js');
var HeaderRow = Tables[i].getElementsByTagName( "tr" )[0];
if (!HeaderRow) continue;
var Header = HeaderRow.getElementsByTagName( "th" )[0];
if (!Header) continue;


NavigationBoxes[ tableIndex ] = Tables[i];
/*</pre>
Tables[i].setAttribute( "id", "collapsibleTable" + tableIndex );


var Button = document.createElement( "span" );
===Import newentrywiz.js===
var ButtonLink = document.createElement( "a" );
<pre>*/
var ButtonText = document.createTextNode( collapseCaption );
jQuery(document).ready(function(){
if(document.getElementById('necblah')){
importScript('User:Yair rand/newentrywiz.js');
}
});


Button.style.styleFloat = "right"; //

Button.style.cssFloat = "right"; // REMOVE THESE LINES
/*</pre>
Button.style.fontWeight = "normal"; // ON 10 FEBRUARY 2009
===Import adddefinition.js===
Button.style.textAlign = "right"; //
<pre>*/
Button.style.width = "6em"; //
importScript('User:Yair rand/adddefinition.js');
/*</pre>
===Import rhymesedit.js===
<pre>*/
wgNamespaceNumber == 106 && importScript("User:Yair rand/rhymesedit.js");
/*</pre>
===Import Targeted Translations===
<pre>*/
importScript("User:Yair rand/TargetedTranslations.js");
/*</pre>

==URL Fixes==
<pre>*/

/**
* doRedirect will redirect if a did you mean box is found, and create a
* "redirected from X" if a rdfrom is passed in the get parameters
* The first half is an ugly workaround for Bugzilla:3339, :(
* The second half is an ugly workaround for not having serverware support :(
**/

/*</pre>
===Did you mean ____ redirects===
<pre>*/

jQuery(document).ready(function () {
// REDIRECTED FROM
if( window.location.href.indexOf('rdfrom=') != -1 ) {
var wiktDYMfrom = decodeURIComponent(window.location.href.replace(/^(.+[&\?]rdfrom=([^&]+).*|.*)?$/,"$2"));

jQuery('#siteSub').after(
newNode('div', {id: 'contentSub'}, '(Auto-redirected from ',
newNode('a', {href: mw.util.getUrl(wiktDYMfrom) + '?redirect=no', 'class': 'new'}, wiktDYMfrom),
')'));

} else {
// DID YOU MEAN
var target = jQuery('#did-you-mean a').html(),
pagetitle = jQuery('h1').first().text().replace(/^\s+|\s+$/g, '');

if (target && target != pagetitle
&& !window.location.href.match(/[&\?]redirect=no|[&\?]action=(?!view)/)
&& (jQuery.cookie('WiktionaryDisableAutoRedirect') != 'true')
&& wgArticleId === 0
&& !/Redirected from/.test(jQuery('#contentSub').html())
) {
document.location = mw.util.getUrl( target, { "rdfrom": pagetitle } );
}
}

// Random page in a given language
document.location.toString().replace(/[?&]rndlang=([^&#]+)[^#]*(?:#(.+))?/, function (m, lang, headlang) {
var script = 'http://toolserver.org/~hippietrail/randompage.fcgi';

var insert = document.getElementById('contentSub');
if (headlang) {
var heading = document.getElementById(headlang);
if (heading) heading = heading.parentNode;
if (heading) {
insert = newNode('div', {style: 'font-size: 84%; line-height: 1.2em;'});
heading.parentNode.insertBefore(insert, heading.nextSibling)
}
}

if (!insert || insert.innerHTML != "") return;

insert.appendChild(newNode('span', {style: 'color: #888;'}, "Another ",
newNode('a', {href: script + '?langs=1'}, "Random"), " word in ",
newNode('a', {href: script + '?langname=' + lang}, decodeURIComponent(lang))
));
});
})

/*</pre>

===Fix Wikified section titles===
<pre>*/
jQuery(document).ready(function () {
// {temp|template}
if (/\.7B\.7Btemp\.7C(.*?)\.7D\.7D/.test(window.location.href)) {
var url=window.location.href.replace(/\.7B\.7Btemp.7C/g, ".7B.7B");
window.location = url;
}
});

jQuery(document).ready(function () {
if(wgAction != 'edit')
return;
if(! /[?&]section=\d/.test(window.location.href))
return;
var wpSummary = document.getElementById('wpSummary');
if(! wpSummary)
return;
if(wpSummary.value.substr(0, 3) != '/* ')
return;
if(wpSummary.value.substr(wpSummary.value.length - 4) != ' */ ')
return;
wpSummary.value = wpSummary.value.replace(/\{\{temp(late)?\|/g, '{{');
});

/*</pre>
== Visibility toggling ==
<pre>*/
var VisibilityToggles = {
// toggles[category] = [[show, hide],...]; statuses[category] = [true, false,...]; buttons = <li>
toggles: {}, statuses: {}, buttons: null,

// Add a new toggle, adds a Show/Hide category button in the toolbar,
// and will call show_function and hide_function once on register, and every alternate click.
register: function (category, show_function, hide_function) {

var id = 0;
if (!this.toggles[category]) {
this.toggles[category] = [];
this.statuses[category] = [];
} else {
id = this.toggles[category].length;
}
this.toggles[category].push([show_function, hide_function]);
this.statuses[category].push(this.currentStatus(category));
this.addGlobalToggle(category);

(this.statuses[category][id] ? show_function : hide_function)();

return function () {
var statuses = VisibilityToggles.statuses[category];
statuses[id] = !statuses[id]
VisibilityToggles.checkGlobalToggle(category);
return (statuses[id] ? show_function : hide_function)();
}

},

// Add a new global toggle to the side bar
addGlobalToggle: function(category) {
if (document.getElementById('p-visibility-'+category))
return;
if (!this.buttons) {
this.buttons = newNode('ul');
var collapsed = $.cookie("vector-nav-p-visibility") == "false", toolbox = newNode('div', {'class': "portal portlet "+(collapsed?"collapsed":"expanded"), 'id': 'p-visibility'},
newNode('h3', 'Visibility'),
newNode('div', {'class': "pBody body"}, collapsed?undefined:{'style':'display:block;'}, this.buttons)
);
var sidebar = document.getElementById('mw-panel') || document.getElementById('column-one');
var insert = null;
if (insert = (document.getElementById('p-lang') || document.getElementById('p-feedback')))
sidebar.insertBefore(toolbox, insert);
else
sidebar.appendChild(toolbox);

}
var status = this.currentStatus(category);
var newToggle = newNode('li', newNode('a', {
id: 'p-visibility-' + category,
style: 'cursor: pointer',
href: '#visibility-' + category,
click: function(e)
{
VisibilityToggles.toggleGlobal(category);
if (e && e.preventDefault)
e.preventDefault();
else
window.event.returnValue = false;
return false;
}},
(status ? 'Hide ' : 'Show ') + category));
for (var i=0; i < this.buttons.childNodes.length; i++) {
if (this.buttons.childNodes[i].id < newToggle.id) {
this.buttons.insertBefore(newToggle, this.buttons.childNodes[i]);
return;
}
}
this.buttons.appendChild(newToggle);
},

// Update the toggle-all buttons when all things are toggled one way
checkGlobalToggle: function(category) {
var statuses = this.statuses[category];
var status = statuses[0];
for (var i = 1; i < statuses.length; i++) {
if (status != statuses[i])
return;
}
document.getElementById('p-visibility-' + category).innerHTML = (status ? 'Hide ' : 'Show ') + category;
},

// Toggle all un-toggled elements when the global button is clicked
toggleGlobal: function(category) {
var status = document.getElementById('p-visibility-' + category).innerHTML.indexOf('Show ') == 0;
for (var i = 0; i < this.toggles[category].length; i++ ) {
if (this.statuses[category][i] != status) {
this.toggles[category][i][status ? 0 : 1]();
this.statuses[category][i] = status;
}
}
document.getElementById('p-visibility-' + category).innerHTML = (status ? 'Hide ' : 'Show ') + category;
var current = jQuery.cookie('Visibility');
if (!current)
current = ";";
current = current.replace(';' + category + ';', ';');
if (status)
current = current + category + ";";
setCookie('Visibility', current);
},

currentStatus: function(category) {
if (window.location.hash.toLowerCase().split('_')[0] == '#' + category.toLowerCase())
return true;
if (window.location.href.search(/[?](.*&)?hidecats=/) > 0)
{
var hidecats = window.location.href;
hidecats = hidecats.replace(/^[^?]+[?]((?!hidecats=)[^&]*&)*hidecats=/, '');
hidecats = hidecats.replace(/&.*/, '');
hidecats = hidecats.split(',');
for (var i = 0; i < hidecats.length; ++i)
if (hidecats[i] == category || hidecats[i] == 'all')
return false;
else if (hidecats[i] == '!' + category || hidecats[i] == 'none')
return true;
}
if (jQuery.cookie('WiktionaryPreferencesShowNav') == 'true')
return true;
if ((jQuery.cookie('Visibility') || "").indexOf(';' + category + ';') >= 0)
return true;
// TODO check category-specific cookies
return false;
}
}

/*</pre>
=== NavBars ===
<pre>*/
var NavigationBarHide = 'hide ▲';
var NavigationBarShow = 'show ▼';

function NavToggleCategory(navFrame)
{
var table = navFrame.getElementsByTagName('table')[0];
if (table && table.className == "translations")
return "translations";

var heading = navFrame.previousSibling;
while (heading) {
if (/[hH][4-6]/.test(heading.nodeName)) {
if (heading.getElementsByTagName('span')[1])
heading = heading.getElementsByTagName('span')[0];
return $(heading).text().toLowerCase()
// jQuery's .text() is inconsistent about whitespace:
.replace(/^\s+|\s+$/g, '').replace(/\s+/g, ' ')
// remove numbers added by the "Auto-number headings" pref:
.replace(/^[1-9][0-9.]+ ?/, '');
}
else if (/[hH][1-3]/.test(heading.nodeName))
break;
heading = heading.previousSibling;
}
return "other boxes";
}

function createNavToggle(navFrame){
var navHead, navToggle, navContent;
for (var j=0; j < navFrame.childNodes.length; j++) {
var div = navFrame.childNodes[j];
switch (div.className) {
case 'NavHead':
navHead = div;
break;
case 'NavContent':
navContent = div;
break;
}
}
if (!navHead || !navContent)
return;
// Step 1, don't react when a subitem is clicked.
for (var i=0; i<navHead.childNodes.length; i++) {
var child = navHead.childNodes[i];
if (child.nodeName == "A") {
child.onclick = function (e)
{
if (e && e.stopPropagation)
e.stopPropagation();
else
window.event.cancelBubble = true;
}
}
}
// Step 2, toggle visibility when bar is clicked.
// NOTE This function was chosen due to some funny behaviour in Safari.
navToggle = newNode('a', {href: 'javascript:(function(){})()'}, '');
navHead.insertBefore(newNode('span', {'class': 'NavToggle'}, '[', navToggle, ']'), navHead.firstChild);

navHead.style.cursor = "pointer";
navHead.onclick = VisibilityToggles.register(NavToggleCategory(navFrame),
function show() {
navToggle.innerHTML = NavigationBarHide;
if (navContent)
navContent.style.display = "block";
},
function hide() {
navToggle.innerHTML = NavigationBarShow;
if (navContent)
navContent.style.display = "none";
});
};

jQuery(document).ready( function ()
{
var divs = $(".NavFrame");
for (var i=0; i<divs.length; i++) {
// NOTE: some templates use a class of NavFrame for the style, but for legacy reasons, are not NavFrames
if (divs[i].className == "NavFrame") {
createNavToggle(divs[i]);
}
}

});

/*</pre>

===Hidden Quotes===
<pre>*/

function setupHiddenQuotes(li) {
var HQToggle, liComp, dl;
var HQShow = 'quotations ▼';
var HQHide = 'quotations ▲';
for (var k = 0; k < li.childNodes.length; k++) {
// Look at each component of the definition.
liComp = li.childNodes[k];
if ( liComp.nodeName.toLowerCase() === "dl" && !dl ) {
dl = liComp;
}
// If we find a ul or dl, we have quotes or example sentences, and thus need a button.
if (/^(ul|UL)$/.test(liComp.nodeName)) {
HQToggle = newNode('a', {href: 'javascript:(function(){})()'}, '');
li.insertBefore(newNode('span', {'class': 'HQToggle'}, ' [', HQToggle, ']'), dl || liComp);
HQToggle.onclick = VisibilityToggles.register('quotations',
function show() {
HQToggle.innerHTML = HQHide;
for (var child = li.firstChild; child != null; child = child.nextSibling) {
if (/^(ul|UL)$/.test(child.nodeName)) {
child.style.display = 'block';
}
}
},
function hide() {
HQToggle.innerHTML = HQShow;
for (var child = li.firstChild; child != null; child = child.nextSibling) {
if (/^(ul|UL)$/.test(child.nodeName)) {
child.style.display = 'none';
}
}
});

break;
}
}
}
Button.className = "collapseButton"; //Styles are declared in Common.css
jQuery(document).ready(function () {
if (wgNamespaceNumber == 0) {
var ols, lis, li;
// First, find all the ordered lists, i.e. all the series of definitions.
var ols = document.getElementsByTagName('ol');
for(var i = 0; i < ols.length; i++) {
// Then, for every set, find all the individual definitions.
for (var j = 0; j < ols[i].childNodes.length; j++) {
li = ols[i].childNodes[j];
if (li.nodeName.toUpperCase() == 'LI') {
setupHiddenQuotes(li);
}
}
}
}
});


ButtonLink.style.color = Header.style.color;
/*</pre>
ButtonLink.setAttribute( "id", "collapseButton" + tableIndex );
ButtonLink.setAttribute( "href", "javascript:collapseTable(" + tableIndex + ");" );
ButtonLink.appendChild( ButtonText );


Button.appendChild( document.createTextNode( "[" ) );
== Interproject links ==
Button.appendChild( ButtonLink );
<pre>*/
Button.appendChild( document.createTextNode( "]" ) );


Header.insertBefore( Button, Header.childNodes[0] );
/*
tableIndex++;
#########
}
### ProjectLinks
}
### by [[user:Pathoschild]] (idea from an older, uncredited script)
### * generates a sidebar list of links to other projects from {{projectlinks}}
#########
*/
jQuery(document).ready(function () {
var elements = new Array();
var spans = document.getElementsByTagName('span');


for ( var i = 0; i < tableIndex; i++ ) {
// filter for projectlinks
if ( hasClass( NavigationBoxes[i], "collapsed" ) || ( tableIndex >= autoCollapse && hasClass( NavigationBoxes[i], "autocollapse" ) ) ) {
for (var i=0, j=0; i<spans.length; i++) {
collapseTable( i );
if (spans[i].className == 'interProject') {
}
elements[j] = spans[i].getElementsByTagName('a')[0];
else if ( hasClass( NavigationBoxes[i], "innercollapse" ) ) {
j++;
var element = NavigationBoxes[i];
}
while (element = element.parentNode) {
}
if ( hasClass( element, "outercollapse" ) ) {

collapseTable ( i );
if (j == 0)
break;
return;
}

}
// sort alphabetically
}
function sortbylabel(a,b) {
}
// get labels
a = a.innerHTML.replace(/^.*<a[^>]*>(.*)<\/a>.*$/i,'$1');
b = b.innerHTML.replace(/^.*<a[^>]*>(.*)<\/a>.*$/i,'$1');

// return sort order
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
elements.sort(sortbylabel);

// Create the list of project links
var pllist = newNode('ul');
for (var i=0; i<elements.length; i++) {
pllist.appendChild(newNode('li', elements[i]));
}
var collapsed = $.cookie("vector-nav-p-projects") == "false";
var projectBox = newNode('div', {'class': 'portlet portal '+(collapsed?"collapsed":"expanded"), id: 'p-projects'},
newNode('h3', 'In other projects'),
newNode('div', {'class': 'pBody body'}, collapsed?undefined:{'style':'display:block;'}, pllist)
);

var insert = document.getElementById('p-tb');
if (!insert)
return;

if (insert.nextSibling)
insert.parentNode.insertBefore(projectBox, insert.nextSibling);
else
insert.parentNode.appendChild(projectBox);
});

/*</pre>
===Scripts specific to Internet Explorer===
<pre>*/
if (navigator.appName == "Microsoft Internet Explorer") {
/** Internet Explorer bug fix **************************************************
*
* Description: Fixes IE horizontal scrollbar bug
* Maintainers: [[User:Tom-]]?
*/

var oldWidth;
var docEl = document.documentElement;

function fixIEScroll()
{
if (!oldWidth || docEl.clientWidth > oldWidth)
doFixIEScroll();
else
setTimeout(doFixIEScroll, 1);

oldWidth = docEl.clientWidth;
}

function doFixIEScroll() {
docEl.style.overflowX = (docEl.scrollWidth - docEl.clientWidth < 4) ? "hidden" : "";
}
document.attachEvent("onreadystatechange", fixIEScroll);
document.attachEvent("onresize", fixIEScroll);

// In print IE (7?) does not like line-height
mw.util.addCSS( '@media print { sup, sub, p, .documentDescription { line-height: normal; }}');

// IE overflow bug
mw.util.addCSS('div.overflowbugx { overflow-x: scroll !important; overflow-y: hidden !important; } div.overflowbugy { overflow-y: scroll !important; overflow-x: hidden !important; }');

// IE zoomfix
// Use to fix right floating div/table inside tables
mw.util.addCSS('.iezoomfix div, .iezoomfix table { zoom: 1;}');

// Import scripts specific to Internet Explorer 6
if (navigator.appVersion.substr(22, 1) == "6") {
importScript("MediaWiki:Common.js/IE60Fixes.js")
}
}
}


addOnloadHook( createCollapseButtons );
/*</pre>
===Category page fixes===
<pre>*/

$(document).ready(function($){
var s, c = "", lang;
if( wgNamespaceNumber === 14 && ( s = document.getElementById("catfix") ) ) {
lang = s.className.split("CATFIX-")[1]
if (lang.length > 0)
{
c = "#" + lang;
}

s = s.getElementsByTagName("*")[0] || document.createElement("span");
$("#mw-pages>.mw-content-ltr").find("li>a").each(function(){
var li = this.parentNode, clone = s.cloneNode( false );
li.removeChild( this );
this.setAttribute("href", this.getAttribute("href", 2) + c );
clone.appendChild( this );
li.appendChild( clone );
})
}
})

/*</pre>
===Temporary button for enabling two proposed scripts===
<pre>*/

if ( $.cookie("YRNewStuff") || location.search.indexOf("tabbedlanguages=on") != -1 )
{
importScript("User:Yair rand/editor2.js")
importScript("User:Yair rand/TabbedLanguages2.js")
}

jQuery(document).ready(function () {
if(document.getElementById('YRNewStuff-enable-button'))
{
document.getElementById('YRNewStuff-enable-button').innerHTML = ""
var toggle = newNode('span', {click: function ()
{
if( $.cookie("YRNewStuff") ){
$.cookie("YRNewStuff", null,{path:"/"})
toggle.innerHTML = "Enable tabbed languages and definition editing options."
}
else{
$.cookie("YRNewStuff",1,{expires:30,path:"/"})
toggle.innerHTML = "Disable tabbed languages and definition editing options."
}
} }, ($.cookie("YRNewStuff")?"Disable":"Enable")+" tabbed languages and definition editing options.")
document.getElementById('YRNewStuff-enable-button').appendChild(toggle);
}
})

/*</pre>
===WT:ES Discussion tool===
<pre>*/

wgPageName == "Wiktionary:Etymology_scriptorium" && importScript("User:Yair rand/DiscussionSandbox.js");

$(document).ready(function() {
$("table.unit-tests th.unit-tests-img-corner").bind("click", function () {
var table = this;
while (table.tagName !== "TABLE")
table = table.parentNode;
table.classList.toggle("unit-tests-hide-passing");
})
});

Latest revision as of 05:14, 11 April 2014

/* Any JavaScript here will be loaded for all users on every page load. */

// Wikia's own WikiaScriptLoader isn't automatically included in other skins such as monobook.
// Presumably this is because they no longer support them. This checks to see if WikiaScriptLoader 
// function reference has been declared, and if it has not, it creates it. Backwards compatibility
// for everybody! - Blame User:Tierrie @ DA Wiki if this works. Blame someone else if it breaks.
if(typeof WikiaScriptLoader === 'undefined') {
  var WikiaScriptLoader=WikiaScriptLoader?WikiaScriptLoader:function(){var b=navigator.userAgent.toLowerCase();this.useDOMInjection=b.indexOf("opera")!=-1||b.indexOf("firefox")!=-1&&b.indexOf("/4.0b")==-1;this.isIE=b.indexOf("opera")==-1&&b.indexOf("msie")!=-1;this.headNode=document.getElementsByTagName("HEAD")[0]}; WikiaScriptLoader.prototype={loadScript:function(b,c){this.useDOMInjection?this.loadScriptDOMInjection(b,c):this.loadScriptDocumentWrite(b,c)},loadScriptDOMInjection:function(b,c){var a=document.createElement("script");a.type="text/javascript";a.src=b;var d=function(){a.onloadDone=true;typeof c=="function"&&c()};a.onloadDone=false;a.onload=d;a.onreadystatechange=function(){a.readyState=="loaded"&&!a.onloadDone&&d()};this.headNode.appendChild(a)},loadScriptDocumentWrite:function(b,c){document.write('<script src="'+ b+'" type="text/javascript"><\/script>');var a=function(){typeof c=="function"&&c()};typeof c=="function"&&this.addHandler(window,"load",a)},loadScriptAjax:function(b,c){var a=this,d=this.getXHRObject();d.onreadystatechange=function(){if(d.readyState==4){var e=d.responseText;if(a.isIE)eval(e);else{var f=document.createElement("script");f.type="text/javascript";f.text=e;a.headNode.appendChild(f)}typeof c=="function"&&c()}};d.open("GET",b,true);d.send("")},loadCSS:function(b,c){var a=document.createElement("link"); a.rel="stylesheet";a.type="text/css";a.media=c||"";a.href=b;this.headNode.appendChild(a)},addHandler:function(b,c,a){if(window.addEventListener)window.addEventListener(c,a,false);else window.attachEvent&&window.attachEvent("on"+c,a)},getXHRObject:function(){var b=false;try{b=new XMLHttpRequest}catch(c){for(var a=["Msxml2.XMLHTTP.6.0","Msxml2.XMLHTTP.3.0","Msxml2.XMLHTTP","Microsoft.XMLHTTP"],d=a.length,e=0;e<d;e++){try{b=new ActiveXObject(a[e])}catch(f){continue}break}}return b}};window.wsl=new WikiaScriptLoader;
}

/** Archive edit tab disabling *************************************
 * Disables the edit tab on old forum topic pages to stop new people bumping old topics.
 * Page can still be edited by going via the edit tab on the history etc, or by 
 * typing the edit address manually.
 * By [[User:Spang|Spang]]
 * Monaco support by [[User:Uberfuzzy|Uberfuzzy]]
 * Copied from [[w:c:Community:MediaWiki:Common.js]] on 3-Sep-2010
 */
 
if(wgNamespaceNumber == 110) {
 
function disableOldForumEdit() {
	if( typeof( enableOldForumEdit ) != 'undefined' && enableOldForumEdit )
		return;
	if(!document.getElementById('old-forum-warning') ||
		 !document.getElementById('ca-edit') )
		return;
 
	if( skin == 'monaco' )
	{
		editLink = document.getElementById('ca-edit');
	}
	else if( skin == 'monobook' )
	{
		editLink = document.getElementById('ca-edit').firstChild;
	}
 
	editLink.removeAttribute('href', 0);
	editLink.removeAttribute('title', 0);
	editLink.style.color = 'gray';
	editLink.innerHTML = 'Archived';
 
	$('span.editsection-upper').remove();
 
}
addOnloadHook( disableOldForumEdit );
}

/*
    Replaces {{USERNAME}} with the name of the user browsing the page.
    Requires copying Template:USERNAME.
*/

function UserNameReplace() {
    if(typeof(disableUsernameReplace) != 'undefined' && disableUsernameReplace || wgUserName == null) return;
    $("span.insertusername").html(wgUserName);
 }
 addOnloadHook(UserNameReplace);

/* Test if an element has a certain class **************************************
 *
 * Description: Uses regular expressions and caching for better performance.
 * Maintainers: [[User:Mike Dillon]], [[User:R. Koot]], [[User:SG]]
 */

var hasClass = (function () {
    var reCache = {};
    return function (element, className) {
        return (reCache[className] ? reCache[className] : (reCache[className] = new RegExp("(?:\\s|^)" + className + "(?:\\s|$)"))).test(element.className);
    };
})();

/** Collapsible tables *********************************************************
 *
 *  Description: Allows tables to be collapsed, showing only the header. See
 *               [[Wikipedia:NavFrame]].
 *  Maintainers: [[User:R. Koot]]
 */

var autoCollapse = 2;
var collapseCaption = "hide";
var expandCaption = "show";

function collapseTable( tableIndex )
{
    var Button = document.getElementById( "collapseButton" + tableIndex );
    var Table = document.getElementById( "collapsibleTable" + tableIndex );

    if ( !Table || !Button ) {
        return false;
    }

    var Rows = Table.rows;

    if ( Button.firstChild.data == collapseCaption ) {
        for ( var i = 1; i < Rows.length; i++ ) {
            Rows[i].style.display = "none";
        }
        Button.firstChild.data = expandCaption;
    } else {
        for ( var i = 1; i < Rows.length; i++ ) {
            Rows[i].style.display = Rows[0].style.display;
        }
        Button.firstChild.data = collapseCaption;
    }
}

function createCollapseButtons()
{
    var tableIndex = 0;
    var NavigationBoxes = new Object();
    var Tables = document.getElementsByTagName( "table" );

    for ( var i = 0; i < Tables.length; i++ ) {
        if ( hasClass( Tables[i], "collapsible" ) ) {

            /* only add button and increment count if there is a header row to work with */
            var HeaderRow = Tables[i].getElementsByTagName( "tr" )[0];
            if (!HeaderRow) continue;
            var Header = HeaderRow.getElementsByTagName( "th" )[0];
            if (!Header) continue;

            NavigationBoxes[ tableIndex ] = Tables[i];
            Tables[i].setAttribute( "id", "collapsibleTable" + tableIndex );

            var Button     = document.createElement( "span" );
            var ButtonLink = document.createElement( "a" );
            var ButtonText = document.createTextNode( collapseCaption );

            Button.style.styleFloat = "right";    //
            Button.style.cssFloat = "right";      // REMOVE THESE LINES
            Button.style.fontWeight = "normal";   // ON 10 FEBRUARY 2009
            Button.style.textAlign = "right";     // 
            Button.style.width = "6em";           //
 
            Button.className = "collapseButton";  //Styles are declared in Common.css

            ButtonLink.style.color = Header.style.color;
            ButtonLink.setAttribute( "id", "collapseButton" + tableIndex );
            ButtonLink.setAttribute( "href", "javascript:collapseTable(" + tableIndex + ");" );
            ButtonLink.appendChild( ButtonText );

            Button.appendChild( document.createTextNode( "[" ) );
            Button.appendChild( ButtonLink );
            Button.appendChild( document.createTextNode( "]" ) );

            Header.insertBefore( Button, Header.childNodes[0] );
            tableIndex++;
        }
    }

    for ( var i = 0;  i < tableIndex; i++ ) {
        if ( hasClass( NavigationBoxes[i], "collapsed" ) || ( tableIndex >= autoCollapse && hasClass( NavigationBoxes[i], "autocollapse" ) ) ) {
            collapseTable( i );
        } 
        else if ( hasClass( NavigationBoxes[i], "innercollapse" ) ) {
            var element = NavigationBoxes[i];
            while (element = element.parentNode) {
                if ( hasClass( element, "outercollapse" ) ) {
                    collapseTable ( i );
                    break;
                }
            }
        }
    }
}

addOnloadHook( createCollapseButtons );