Järjestelmäviesti:Common.js

Greedopedia, Tähtien sota -huumoriwiki, jossa on yli 582 967 853 artikkelia
Siirry navigaatioonSiirry hakuun

Huomautus: Selaimen välimuisti pitää tyhjentää asetusten tallentamisen jälkeen, jotta muutokset tulisivat voimaan.

  • Firefox ja Safari: Napsauta Shift-näppäin pohjassa Päivitä, tai paina Ctrl-F5 tai Ctrl-R (⌘-R Macilla)
  • Google Chrome: Paina Ctrl-Shift-R (⌘-Shift-R Macilla)
  • Internet Explorer: Napsauta Ctrl-näppäin pohjassa Päivitä tai paina Ctrl-F5
  • Opera: Valikko → Asetukset (Opera → Asetukset Macilla) ja sitten Tietosuoja ja turvallisuus → Tyhjennä selaustiedot → Välimuistissa olevat kuvat ja tiedostot.
/* Tämän sivun koodi liitetään jokaiseen sivulataukseen */
/* <pre><nowiki> */

// Onload stuff
var firstRun = true;

function loadFunc() {
	if ( firstRun ) {
		firstRun = false;
	} else {
		return;
	}

	window.pageName = mw.config.get( 'wgPageName' );
	window.storagePresent = ( typeof localStorage != 'undefined' );

	initFunctionsJS();

	addHideButtons();

	if ( document.getElementById( 'mp3-navlink' ) !== null ) {
		document.getElementById( 'mp3-navlink' ).onclick = onArticleNavClick;
		document.getElementById( 'mp3-navlink' ).getElementsByTagName( 'a' )[0].href = 'javascript:void(0)';
	}

	if ( window.storagePresent ) {
		initVisibility();
	}

	fillEditSummaries();
	fillPreloads();

	substUsername();
	substUsernameTOC();
	rewriteTitle();
	showEras( 'title-eraicons' );
	showEras( 'title-shortcut' );
	rewriteHover();
	checkBlock();
	fixSearch();

	if ( typeof onPageLoad != 'undefined' ) {
		onPageLoad();
	}
}

// **************************************************
// Experimental JavaScript countdown timer (Splarka)
// Version 0.0.4
// **************************************************
//
// Usage example:
//  <span class="countdown" style="display:none;">
//  Only <span class="countdowndate">January 01 2007 00:00:00 PST</span> until New years.
//  </span>
//  <span class="nocountdown">JavaScript disabled.</span>
function updateTimer( i ) {
	var now = new Date();
	var then = timers[i].eventdate;
	var diff = count = Math.floor( ( then.getTime() - now.getTime() ) / 1000 );

	// catch bad date strings
	if ( isNaN( diff ) ) {
		timers[i].firstChild.nodeValue = '** ' + timers[i].eventdate + ' **';
		return;
	}

	// determine plus/minus
	if ( diff < 0 ) {
		diff = -diff;
		var tpm = 'T plus ';
	} else {
		var tpm = 'T minus ';
	}

	// calculate the diff
	var left = ( diff % 60 ) + ' sekuntia';
	diff = Math.floor( diff / 60 );
	if ( diff > 0 ) {
		left = ( diff % 60 ) + ' minuuttia ' + left;
	}
	diff = Math.floor( diff / 60 );
	if ( diff > 0 ) {
		left = ( diff % 24 ) + ' tuntia ' + left;
	}
	diff = Math.floor( diff / 24 );
	if ( diff > 0 ) {
		left = diff + ' päivää ' + left;
	}
	timers[i].firstChild.nodeValue = tpm + left;

	// a setInterval() is more efficient, but calling setTimeout()
	// makes errors break the script rather than infinitely recurse
	timeouts[i] = setTimeout( 'updateTimer(' + i + ')', 1000 );
}

function checkTimers() {
	// hide 'nocountdown' and show 'countdown'
	$( '.nocountdown' ).hide();
	$( '.countdown' ).show();

	// set up global objects timers and timeouts.
	timers = $( '.countdowndate' ); // global
	timeouts = new Array(); // generic holder for the timeouts, global
	if ( timers.length == 0 ) {
		return;
	}

	for ( var i = 0; i < timers.length ;i++ ) {
		timers[i].eventdate = new Date( timers[i].firstChild.nodeValue );
		updateTimer( i ); // start it up
	}
}
$( checkTimers );
// **************************************************
//  - end -  Experimental JavaScript countdown timer
// **************************************************

// Custom edit buttons
var customizeToolbar = function () {
	$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
		'section': 'main',
		'group': 'insert',
		'tools': {
			'redirect': {
				label: 'Ohjaus',
				type: 'button',
				icon: 'http://images.shoutwiki.com/fi.darth/c/c8/Button_redirect.png',
				action: {
					type: 'encapsulate',
					options: {
						pre: '#OHJAUS [[',
						peri: 'Kohdesivun nimi tähän',
						post: ']]'
					}
				}
			},
			'strike': {
				label: 'Yliviivattu',
				type: 'button',
				icon: 'http://images.shoutwiki.com/fi.darth/c/c9/Button_strike.png',
				action: {
					type: 'encapsulate',
					options: {
						pre: '<s>',
						peri: 'Yliviivattua tekstiä',
						post: '</s>'
					}
				}
			},
			'enter': {
				label: 'Rivinvaihto',
				type: 'button',
				icon: 'http://images.shoutwiki.com/fi.darth/1/13/Button_enter.png',
				action: {
					type: 'encapsulate',
					options: {
						pre: '<br />'
					}
				}
			},
			'comment': {
				label: 'Ainoastaan muokkaajille näkyvä kommentti',
				type: 'button',
				icon: 'http://images.shoutwiki.com/fi.darth/7/74/Button_comment.png',
				action: {
					type: 'encapsulate',
					options: {
						pre: '<!-- ',
						peri: 'Kirjoita kommentti tähän',
						post: ' -->'
					}
				}
			},
			'welcome': {
				label: 'Toivota uusia käyttäjiä tervetulleeksi',
				filters: [ 'body.ns-3' ],
				type: 'button',
				icon: 'http://images.shoutwiki.com/fi.darth/4/4a/Button_welcome.png',
				action: {
					type: 'encapsulate',
					options: {
						pre: '{{subst:tervetuloa|~~~~}}'
					}
				}
			},
			'dyp': {
				label: 'Linkki tuhota planeettasi -sivulle',
				type: 'button',
				icon: 'http://images.shoutwiki.com/fi.darth/5/5e/Button_DYP.png',
				action: {
					type: 'encapsulate',
					options: {
						pre: '[[Tuhota planeettasi]] '
					}
				}
			}
		}
	} );
};

/* Check if view is in edit mode and that the required modules are available. Then, customize the toolbar … */
if ( [ 'edit', 'submit' ].indexOf( mw.config.get( 'wgAction' ) ) !== -1 ) {
	mw.loader.using( 'user.options' ).then( function () {
		// This can be the string "0" if the user disabled the preference ([[phab:T54542#555387]])
		if ( mw.user.options.get( 'usebetatoolbar' ) == 1 ) {
			$.when(
				mw.loader.using( 'ext.wikiEditor' ), $.ready
			).then( customizeToolbar );
		}
	} );
}
// end custom edit buttons

/* Stores the (unmodified) page title. */
function storePageName() {
	if ( mw.config.get( 'skin' ) == 'monobook' || mw.config.get( 'skin' ) == 'vector' ) {
		window.pageName = $( 'h1#firstHeading span' ).text();
	} else if ( mw.config.get( 'skin' ) == 'bluecloud' || mw.config.get( 'skin' ) == 'eminence' || mw.config.get( 'skin' ) == 'monaco' ) {
		window.pageName = $( 'h1.firstHeading' ).text();
	} else if ( mw.config.get( 'skin' ) == 'games' || mw.config.get( 'skin' ) == 'nimbus' || mw.config.get( 'skin' ) == 'sports' ) {
		window.pageName = $( 'h1.pagetitle' ).text();
	} else if ( mw.config.get( 'skin' ) == 'hope' ) {
		window.pageName = $( 'h2#one' ).text();
	} else if ( mw.config.get( 'skin' ) == 'modern' ) {
		window.pageName = $( 'h1#firstHeading span' ).text();
	} else if ( mw.config.get( 'skin' ) == 'truglass' ) {
		window.pageName = $( 'h1#title' ).text();
	}
}

/* Adds a trim method to string variables. */
String.prototype.trim = function() {
	return this.replace( /^\s+|\s+$/g, '' );
};

/* Searches an array for an element and returns its index, or -1 if it's not in the array. */
function arrayFind( array, value ) {
	for ( var i = 0; i < array.length; i++ ) {
		if ( array[i] == value ) {
			return i;
		}
	}

	return -1;
}

/* Removes the first occurrence of an element in an array, if it is there. */
function arrayRemove( array, value ) {
	var i = arrayFind( array, value );

	if ( i != -1 ) {
		array.splice( i, 1 );
	}
}

/*
	the ContentLoader class to encapsulate "creative differences" with XHR

	Usage:
		- construct a ContentLoader object: var loader = new ContentLoader();
		- set necessary state parameters (via fields); e.g. loader.myvar = 'mytext';
		- set the callback: loader.callback = myfunc;
		- send the request:
			loader.send(url, postdata = null, contentType = 'application/x-www-form-urlencoded');
			(if postdata isn't null or omitted, POST is used, otherwise GET)
		- the callback function is called when the content is loaded
			- the ContentLoader object is this
			- the raw response data is this.text
			- the XML DOM object, if any, is this.document
*/
function ContentLoader() {
	this.cache = true;
}

ContentLoader.prototype.enableCache = function( caching ) {
	this.cache = ( caching == null ) ? true : this.cache;
}

ContentLoader.prototype.createRequest = function() {
	if ( typeof XMLHttpRequest != 'undefined' ) {
		return new XMLHttpRequest();
	} else if ( typeof ActiveXObject != 'undefined' ) {
		return new ActiveXObject( 'Msxml2.XMLHTTP' );
	}

	return null;
}

ContentLoader.prototype.send = function( url, postdata, contentType ) {
	var method = ( postdata == null ) ? 'GET' : 'POST';
	this.request = this.createRequest();
	this.request.open( method, url );

	if ( !this.cache ) {
		this.request.setRequestHeader( 'If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT' );
	}

	var request = this.request;
	var loader = this;

	if ( postdata == null ) {
		if ( contentType == null ) {
			contentType = 'application/x-www-form-urlencoded';
		}

		request.setRequestHeader( 'Content-type', contentType );
	}

	var f = function() {
		if ( request.readyState == 4 ) {
			loader.text = request.responseText;
			loader.document = request.responseXML;
			request = null;
			loader.request = null;
			loader.callback();
		}
	}

	this.request.onreadystatechange = f;
	this.request.send( postdata );
}
/* end ContentLoader */

/*
    Source: http://www.dustindiaz.com/getelementsbyclass/
    getElementsByClass, which complements getElementById and getElementsByTagName, returns an array of all subelements of ''node'' that are tagged with a specific CSS class (''searchClass'') and are of the tag name ''tag''. If tag is null, it searches for any suitable elements regardless of the tag name.
    Example: getElementsByClass('infobox', document.getElementById('content'), 'div') selects the same elements as the CSS declaration #content div.infobox
*/
function getElementsByClass( searchClass, node, tag ) {
	var classElements = new Array();

	if ( node == null ) {
		node = document;
	}

	if ( tag == null ) {
		tag = '*';
	}

	var els = node.getElementsByTagName( tag );
	var elsLen = els.length;
	var tester = new ClassTester( searchClass );

	for ( i = 0, j = 0; i < elsLen; i++ ) {
		if ( tester.isMatch( els[i] ) ) {
			classElements[j] = els[i];
			j++;
		}
	}

	return classElements;
}

function ClassTester( className ) {
	this.regex = new RegExp( "(^|\\s)" + className + "(\\s|$)" );
}

ClassTester.prototype.isMatch = function( element ) {
	return this.regex.test( element.className );
}
/* end getElementsByClass */

/* Returns the parameter as it appears in the query string. Equivalent to $_GET[p] in PHP. */
function queryString( p ) {
	var re = RegExp( '[&?]' + p + '=([^&]*)' );
	var matches;

	if ( matches = re.exec( document.location ) ) {
		try {
			return decodeURI( matches[1] );
		} catch ( e ) {
			// Jack: added this
			if ( typeof window.console != 'undefined' ) {
				console.log( 'Exception in JS function queryString! Exception was:' + e );
			}
		}
	}

	return null;
}
/* end temporary per-page unique CSS (Splarka) */

/* Dynamically load a combobox's content by pagename (e. g. Template:Stdsummaries) */
function requestComboFill( id, page ) {
	var loader = new ContentLoader();
	loader.comboID = id;
	loader.callback = onComboDataArrival;
	loader.send( mw.config.get( 'wgScriptPath' ) + '/index.php?title=' + page + '&action=raw&ctype=text/plain' );
}

function onComboDataArrival() {
	fillCombo( this.text, this.comboID );
}

function fillCombo( text, comboid ) {
	var combo = document.getElementById( comboid );
	var lines = text.split( '\n' );

	for ( var i = 0; i < lines.length; i++ ) {
		var value = lines[i].indexOf( '-- ' ) == 0 ? lines[i].substring( 3 ) : '';
		var option = document.createElement( 'option' );
		option.setAttribute( 'value', value );
		option.appendChild( document.createTextNode( lines[i] ) );
		combo.appendChild( option );
	}
}
/* end combo fill code */

/* Loads the current source of the page "pagename" (as stored in the database) and inserts it at the cursor position */
function doPreload( pagename ) {
	var loader = new ContentLoader();
	loader.callback = onPreloadArrival;
	loader.send( mw.config.get( 'wgScriptPath' ) + '/index.php?title=' + pagename + '&action=raw&ctype=text/plain' );
}

function insertAtCursor( myField, myValue ) {
	// IE support
	if ( document.selection ) {
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;
	} else if ( myField.selectionStart || myField.selectionStart == '0' ) { // MOZILLA/NETSCAPE support
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring( 0, startPos ) + myValue +
			myField.value.substring( endPos, myField.value.length );
	} else {
		myField.value += myValue;
	}
}

function onPreloadArrival() {
	insertAtCursor( document.getElementById( 'wpTextbox1' ), this.text );
}
/* end preload code */

/* Returns h1.firstHeading (the page title element). */
function getFirstHeading() {
	var elements = getElementsByClass( 'firstHeading', document.getElementById( 'content' ), 'h1' );
	return ( elements !== null && elements.length > 0 ) ? elements[0] : null;
}

/* Returns the element's nearest parent that has the specified CSS class. */
function getParentByClass( className, element ) {
	var tester = new ClassTester( className );
	var node = element.parentNode;

	while ( node !== null && node != document ) {
		if ( tester.isMatch( node ) ) {
			return node;
		}

		node = node.parentNode;
	}

	return null;
}

/*
	Replaces {{USERNAME}} with the name of the user browsing the page.
	Requires copying Template:USERNAME.
*/
function substUsername() {
	var username = mw.config.get( 'wgUserName' );

	if ( username == null ) {
		return;
	}

	$( 'span.insertusername' ).html( username );
}

/*
	Performs dynamic hover class rewriting to work around the IE6 :hover bug
	(needs CSS changes as well)
*/
function rewriteHover() {
	var gbl = document.getElementById( 'hover-global' );

	if ( gbl === null ) {
		return;
	}

	var nodes = getElementsByClass( 'hoverable', gbl );

	for ( var i = 0; i < nodes.length; i++ ) {
		nodes[i].onmouseover = function() {
			this.className += ' over';
		};
		nodes[i].onmouseout = function() {
			this.className = this.className.replace( new RegExp( " over\\b" ), '' );
		};
	}
}

/* to call in onload hooks */
function initFunctionsJS() {
	storePageName();
}

/**
 * JAX PAVAN
 * @author Pinky
 * @author Splarka
 * @author Jack Phoenix
 * @author --miki--
 */

/**
 * Convert a number to have commas in it
 * from mredkj.com
 */
function addCommas( nStr ) {
	nStr += ''; // make it a string
	x = nStr;
	var rgx = /(\d+)(\d{3})/;
	while ( rgx.test( x ) ) {
		x = x.replace( rgx, '$1' + ' ' + '$2' );
	}
	return x;
}

// given string argument with a number like "1,000", corrects the article count and then returns as string
function correctArticleCount( numbar ) {
	// get rid of commas
	numbar = numbar.replace( /,/, '' );
	// damn germans/dutch/spanish/italians/etc.
	numbar = numbar.replace( /\./, '' );
	// damn french/finns/poles/etc
	numbar = numbar.replace( / /, '' );
	numbar = parseInt( numbar );
	numbar += 582797753/*jaxes*/;
	numbar += 170000/*wynns*/;
	// add commas and such back
	return addCommas( numbar );
}

// special random page
if ( mw.config.get( 'wgPageName' ).toLowerCase() == 'toiminnot:satunnainen_jax' ) {
	var rand = Math.floor( Math.random() * 582797754 ); // 1 number above the maximum
	window.location = mw.config.get( 'wgServer' ) + mw.config.get( 'wgScript' ) + '?title=Jax_Pavan_' + addCommas( rand );
}

// Make it show {{jax}} if the article doesn't exist
if ( mw.config.get( 'wgTitle' ).match( /Jax Pavan \d+/ ) && mw.config.get( 'wgArticleId' ) == 0 ) {
	mw.loader.using( 'mediawiki.util', function () {
		mw.util.addCSS('.noarticletext {display:none;} #p-cactions li.selected a {color:#FFD942;} #contentSub2 {display:none;} .mw-warning-with-logexcerpt {display:none;} .mw-newarticletext {display:none;}');
	} );
	$( function() {
		if ( mw.config.get( 'wgAction') == 'view' ) {
			$( '#bodyContent' ).append( '<table border="0" cellpadding="0" cellspacing="0" width="100%" align="center" class="noprint"><tr><td></td></tr></table><div class="disambig noprint" style="border-radius:0.5em; -moz-border-radius:0.5em; -webkit-border-radius:0.5em;">Tämä artikkeli kertoo ihmismiehestä nimeltään <b>Jax Pavan</b>, joka asui Coruscantissa. Saatat etsiä <b><a href="/wiki/Jax_Pavan_%28täsmennyssivu%29" title="Jax Pavan (täsmennyssivu)">jotakuta muuta 582 797 753:sta Jax Pavanista</a></b>.</div><p><b>Jax Pavan</b> oli yksi <a linkindex="3" href="/wiki/Jax_Pavan_%28täsmennyssivu%29" title="Jax Pavan (täsmennyssivu)">582 797 754:stä ihmismiehestä nimeltään Jax Pavan</a> <a linkindex="4" href="/wiki/Coruscant" title="Coruscant">Coruscantissa</a>.<div id="catlinks" class="catlinks"><div id="mw-normal-catlinks"><a href="/wiki/Toiminnot:Luokat" title="Toiminnot:Luokat">Luokka</a>:&#32;<span dir="ltr"><a href="/wiki/Luokka:Ihmismiehet_nimeltään_Jax_Pavan" title="Luokka:Ihmismiehet nimeltään Jax Pavan">Ihmismiehet nimeltään Jax Pavan</a></span></div></div>' );
		}
		var mainbutton = $( '#ca-nstab-main' );
		mainbutton.removeClass( 'new' ); // make the article link blue
		var editbutton = $( '#ca-edit' );
		// Monaco skin is a special case
		if ( mw.config.get( 'skin' ) == 'monaco' ) {
			mainbutton.attr( 'href', function( i, href ) {
				return href.replace( /\&action\=edit/, '' ); // link to article and not &action=edit
			} );
			editbutton.html( 'Muokkaa' ); // change create->edit
		} else {
			mainbutton.find( 'a' ).attr( 'href', function( i, href ) {
				return href.replace( /\&action\=edit/, '' ); // link to article and not &action=edit
			} );
			editbutton.find( 'a' ).html( 'Muokkaa' ); // change create->edit
		}
	} );
}

// Make the default edit text "{{jax}}"
if ( mw.config.get( 'wgTitle' ).match( /Jax Pavan \d+/ ) && mw.config.get( 'wgArticleId' ) == 0 && mw.config.get( 'wgAction' ) == 'edit' ) {
	$( '#wpTextbox1' ).append( '{{jax}}' );
}

// Make redlinks turn blue
// Hopefully doesn't slow down pageloads too much
$( function() {
	var a = $( 'a.new[title^="Jax Pavan"], a.new[title^="Wynn Dorvan"]' );
	a.attr( 'href', function( i, h ) {
		return h.replace( /\&action\=edit(\&redlink\=1)?/, '' );
	} );
	a.attr( 'title', function( j, t ) {
		return t.replace( / \(sivua ei ole\)/, '' );
	} );
	a.removeClass( 'new' );
} );

// fixxor up Special:Statistics article count
if ( mw.config.get( 'wgCanonicalSpecialPageName' ) == 'Statistics' ) {
	$( function() {
		$( 'td.mw-statistics-numbers:lt(2)' ).html( function( i, h ) {
			return correctArticleCount( h );
		} );
	} );
}

/**
 * Wynn Dorvan code - fork of MediaWiki:Jax.js
 * @author Pinky
 * @author Splarka
 * @author Jack Phoenix
 * @author --miki--
 */

// special random page
if ( mw.config.get( 'wgPageName' ).toLowerCase() == 'toiminnot:satunnainen_wynn' ) {
	var rand = Math.floor( Math.random() * 170000 ); // 1 number above the maximum
	window.location = mw.config.get( 'wgServer' ) + mw.config.get( 'wgScript' ) + '?title=Wynn_Dorvan_' + addCommas( rand );
}

// Make it show {{wynn}} if the article doesn't exist
if ( mw.config.get( 'wgTitle' ).match( /Wynn Dorvan \d+/ ) && mw.config.get( 'wgArticleId' ) == 0 ) {
	mw.loader.using( 'mediawiki.util', function () {
		mw.util.addCSS('.noarticletext {display:none;} #p-cactions li.selected a {color:#FFD942;} #contentSub2 {display:none;} .mw-warning-with-logexcerpt {display:none;} .mw-newarticletext {display:none;}');
	} );
	$( function() {
		var content = document.getElementById( 'bodyContent' );
		if ( mw.config.get( 'wgAction' ) == 'view' ) {
			$( '#bodyContent' ).append( '<table border="0" cellpadding="0" cellspacing="0" width="100%" align="center" class="noprint"><tr><td></td></tr></table><div class="disambig noprint" style="border-radius:0.5em; -moz-border-radius:0.5em; -webkit-border-radius:0.5em;">Tämä artikkeli kertoo <a href="/wiki/Coruscant" title="Coruscant">coruscantilaisesta</a> yksilöstä nimeltään <b>Wynn Dorvan</b>. Saatat etsiä <b><a href="/wiki/Wynn_Dorvan_%28täsmennyssivu%29" title="Wynn Dorvan (täsmennyssivu)">yhtä 170 000:sta muusta</a></b>.</div><p><b>Wynn Dorvan</b> oli yksi <a linkindex="3" href="/wiki/Wynn_Dorvan_%28täsmennyssivu%29" title="Wynn Dorvan (täsmennyssivu)">170 000:sta yksilöstä nimeltään Wynn Dorvan</a> <a linkindex="4" href="/wiki/Coruscant" title="Coruscant">Coruscantissa</a>.<div id="catlinks" class="catlinks"><div id="mw-normal-catlinks"><a href="/wiki/Toiminnot:Luokat" title="Toiminnot:Luokat">Luokka</a>:&#32;<span dir="ltr"><a href="/wiki/Luokka:Merkittävät_yksilöt_nimeltään_Wynn_Dorvan" title="Luokka:Merkittävät yksilöt nimeltään Wynn Dorvan">Merkittävät yksilöt nimeltään Wynn Dorvan</a></span></div></div>' );
		}
		var mainbutton = $( '#ca-nstab-main' );
		mainbutton.removeClass( 'new' ); // make the article link blue
		var editbutton = $( '#ca-edit' );
		// Monaco skin is a special case
		if ( mw.config.get( 'skin' ) == 'monaco' ) {
			mainbutton.attr( 'href', function( i, href ) {
				return href.replace( /\&action\=edit/, '' ); // link to article and not &action=edit
			} );
			editbutton.html( 'Muokkaa' ); // change create->edit
		} else {
			mainbutton.find( 'a' ).attr( 'href', function( i, href ) {
				return href.replace( /\&action\=edit/, '' ); // link to article and not &action=edit
			} );
			editbutton.find( 'a' ).html( 'Muokkaa' ); // change create->edit
		}
	} );
}

// Make the default edit text "{{wynn}}"
if ( mw.config.get( 'wgTitle' ).match( /Wynn Dorvan \d+/ ) && mw.config.get( 'wgArticleId' ) == 0 && mw.config.get( 'wgAction' ) == 'edit' ) {
	$( '#wpTextbox1' ).append( '{{wynn}}' );
}

function infoboxToggle() {
	var page = window.pageName.replace( /\W/g, '_' );
	var nowShown;

	if ( document.getElementById( 'infoboxtoggle' ).innerHTML == '[Piilota]' ) {
		document.getElementById( 'infoboxinternal' ).style.display = 'none';
		document.getElementById( 'infoboxtoggle' ).innerHTML = '[Näytä]';
		nowShown = false;
	} else {
		document.getElementById( 'infoboxinternal' ).style.display = 'block';
		document.getElementById( 'infoboxtoggle' ).innerHTML = '[Piilota]';
		nowShown = true;
	}

	if ( window.storagePresent ) {
		localStorage.setItem( 'infoboxshow-' + page, nowShown );
	}
}

/**
 * jQuery version of Sikon's fillEditSummaries
 * @author Grunny
 */
function fillEditSummaries() {
	if ( !$( '#wpSummaryLabel' ).length ) {
		return;
	}

	$.get( mw.config.get( 'wgScript' ), { title: 'Malline:Yleiset yhteenvedot', action: 'raw', ctype: 'text/plain' } ).done( function( data ) {
		var	$summaryOptionsList,
			$summaryLabel = $( '#wpSummaryLabel' ),
			lines = data.split( '\n' ),
			$wrapper = $( '<div>' ).addClass( 'edit-widemode-hide' ).text( 'Yleiset yhteenvedot: ' );

		$summaryOptionsList = $( '<select />' ).attr( 'id', 'stdEditSummaries' ).change( function() {
			var editSummary = $( this ).val();
			if ( editSummary !== '' ) {
				$( '#wpSummaryWidget input[name="wpSummary"]' ).val( editSummary );
			}
		} );

		for ( var i = 0; i < lines.length; i++ ) {
			var editSummaryText = ( lines[i].indexOf( '-- ' ) === 0 ) ? lines[i].substring( 3 ) : '';
			$summaryOptionsList.append( $( '<option>' ).val( editSummaryText ).text( lines[i] ) );
		}

		$summaryLabel.prepend( $wrapper.append( $summaryOptionsList ) );
	} );

}

/**
 * jQuery version of Sikon's fillPreloads
 * @author Grunny
 */
function fillPreloads() {
	if ( !$( '#lf-preload' ).length ) {
		return;
	}

	$( '#lf-preload' ).attr( 'style', 'display: block' );

	$.get( mw.config.get( 'wgScript' ), { title: 'Malline:Stdpreloads', action: 'raw', ctype: 'text/plain' } ).done( function( data ) {
		var	$preloadOptionsList,
			lines = data.split( '\n' );

		$preloadOptionsList = $( '<select />' ).attr( 'id', 'stdSummaries' ).change( function() {
			var templateName = $( this ).val();
			if ( templateName !== '' ) {
				templateName = 'Malline:' + templateName + '/preload';
				templateName = templateName.replace( ' ', '_' );
				$.get( mw.config.get( 'wgScript' ), { title: templateName, action: 'raw', ctype: 'text/plain' } ).done( function( data ) {
					insertAtCursor( document.getElementById( 'wpTextbox1' ), data );
				} );
			}
		} );

		for ( var i = 0; i < lines.length; i++ ) {
			var templateText = ( lines[i].indexOf( '-- ' ) === 0 ) ? lines[i].substring(3) : '';
			$preloadOptionsList.append( $( '<option>' ).val( templateText ).text( lines[i] ) );
		}

		$( '#lf-preload-cbox' ).html( $preloadOptionsList );
	} );

	$( '#lf-preload-pagename' ).html( '<input type="text" class="textbox" />' );
	$( '#lf-preload-button' ).html( '<input type="button" class="button" value="Insert" onclick="doCustomPreload()" />' );
}

function doCustomPreload() {
	var value = $( '#lf-preload-pagename > input' ).val();
	value = value.replace( ' ', '_' );
	$.get( mw.config.get( 'wgScript' ), { title: value, action: 'raw', ctype: 'text/plain' } ).done( function( data ) {
		insertAtCursor( document.getElementById( 'wpTextbox1' ), data );
	} );
}

// ============================================================
// BEGIN JavaScript title rewrite
function rewriteTitle() {
	if ( typeof window.SKIP_TITLE_REWRITE != 'undefined' && window.SKIP_TITLE_REWRITE ) {
		return;
	}

	var titleDiv = document.getElementById( 'title-meta' );

	if ( titleDiv === null ) {
		return;
	}

	var cloneNode = titleDiv.cloneNode( true );
	var firstHeading = getFirstHeading();
	var node = firstHeading.childNodes[0];

	// new, then old!
	firstHeading.replaceChild( cloneNode, node );
	cloneNode.style.display = 'inline';

	var titleAlign = document.getElementById( 'title-align' );
	firstHeading.style.textAlign = titleAlign.childNodes[0].nodeValue;
}

function showEras( className ) {
	if ( typeof window.SKIP_ERAS != 'undefined' && window.SKIP_ERAS ) {
		return;
	}

	var titleDiv = document.getElementById( className );

	if ( titleDiv === null || titleDiv === undefined ) {
		return;
	}

	var cloneNode = titleDiv.cloneNode( true );
	var firstHeading = getFirstHeading();
	firstHeading.insertBefore( cloneNode, firstHeading.childNodes[0] );
	cloneNode.style.display = 'block';
}
// END JavaScript title rewrite

function initVisibility() {
	var page = window.pageName.replace( /\W/g, '_' );
	var show = localStorage.getItem( 'infoboxshow-' + page );

	if ( show == 'false' ) {
		infoboxToggle();
	}

	var hidables = getElementsByClass( 'hidable' );

	for ( var i = 0; i < hidables.length; i++ ) {
		show = localStorage.getItem('hidableshow-' + i  + '_' + page);

		var content, button;
		if ( show == 'false' ) {
			content = getElementsByClass( 'hidable-content', hidables[i] );
			button = getElementsByClass( 'hidable-button', hidables[i] );

			if (
				content !== null && content.length > 0 &&
				button !== null && button.length > 0 &&
				content[0].style.display != 'none'
			)
			{
				button[0].onclick( 'bypass' );
			}
		} else if ( show == 'true' ) {
			content = getElementsByClass( 'hidable-content', hidables[i] );
			button = getElementsByClass( 'hidable-button', hidables[i] );

			if (
				content !== null && content.length > 0 &&
				button !== null && button.length > 0 &&
				content[0].style.display == 'none'
			)
			{
				button[0].onclick( 'bypass' );
			}
		}
	}
}

function onArticleNavClick() {
	var div = document.getElementById( 'mp3-nav' );

	if ( div.style.display == 'block' ) {
		div.style.display = 'none';
	} else {
		div.style.display = 'block';
	}
}

function addHideButtons() {
	var hidables = getElementsByClass( 'hidable' );

	for ( var i = 0; i < hidables.length; i++ ) {
		var box = hidables[i];
		var button = getElementsByClass( 'hidable-button', box, 'span' );

		if ( button !== null && button.length > 0 ) {
			button = button[0];

			button.onclick = toggleHidable;
			button.appendChild( document.createTextNode( '[Piilota]' ) );

			if ( new ClassTester( 'start-hidden' ).isMatch( box ) ) {
				button.onclick( 'bypass' );
			}
		}
	}
}

function toggleHidable( bypassStorage ) {
	var parent = getParentByClass( 'hidable', this );
	var content = getElementsByClass( 'hidable-content', parent );
	var nowShown;

	if ( content !== null && content.length > 0 ) {
		content = content[0];

		if ( content.style.display == 'none' ) {
			content.style.display = content.oldDisplayStyle;
			this.firstChild.nodeValue = '[Piilota]';
			nowShown = true;
		} else {
			content.oldDisplayStyle = content.style.display;
			content.style.display = 'none';
			this.firstChild.nodeValue = '[Näytä]';
			nowShown = false;
		}

		if ( window.storagePresent && ( typeof bypassStorage == 'undefined' || bypassStorage != 'bypass' ) ) {
			var page = window.pageName.replace( /\W/g, '_' );
			var items = getElementsByClass( 'hidable' );
			var item = -1;

			for ( var i = 0; i < items.length; i++ ) {
				if ( items[i] == parent ) {
					item = i;
					break;
				}
			}

			if ( item == -1 ) {
				return;
			}

			localStorage.setItem( 'hidableshow-' + item + '_' + page, nowShown );
		}
	}
}

function substUsernameTOC() {
	var toc = $( '#toc' );
	var userpage = $( '#pt-userpage' );

	if ( !userpage || !toc ) {
		return;
	}

	var username = $( '#pt-userpage' ).children( ':first-child' ).text();
	$( 'span.toctext:not(:has(*)), span.toctext i', toc ).each( function() {
		$( this ).text( $( this ).text().replace( '<insert name here>', username ) );
	} );
}

function fixSearch() {
	var button = document.getElementById( 'searchSubmit' );

	if ( button ) {
		button.name = 'go';
	}
}

$( loadFunc );

function checkBlock() {
	if ( queryString( 'submitblock' ) == 'true' && document.getElementById( 'blockip' ) ) {
		document.getElementById( 'blockip' ).wpBlock.click();
	}
}

function catprefix() {
	if ( !document.getElementById( 'catnoprefix' ) ) {
		return;
	}

	var anchors = document.getElementById( 'mw-pages' ).getElementsByTagName( 'a' );
	for ( var i = 0; i < anchors.length; i++ ) {
		if ( anchors[i].firstChild.nodeValue.indexOf( ':' ) != -1 ) {
			anchors[i].firstChild.nodeValue = anchors[i].firstChild.nodeValue.substring( anchors[i].firstChild.nodeValue.indexOf( ':' ) + 1 );
		}
	}
}
$( catprefix );

/**
 * Adds Template:Tiedot to the information box on Special:Upload
 * @author Jack Phoenix <jack@countervandalism.net>
 * @author --miki--
 * @date June 7, 2010
 */
function addInformationToUploadForm() {
	$( '#wpUploadDescription' ).val( '{{Tiedot\n|huomio = \n|kuvaus = \n|lähde = \n|tekijä = \n|lisenssi = \n|muut versiot = \n}}' );
	$( '#mw-upload-form' ).bind( 'submit', function() {
		var wpLicense = document.getElementById( 'wpLicense' );
		if ( wpLicense.value !== '' ) {
			$( '#wpUploadDescription' ).val(
				$( '#wpUploadDescription' ).val().replace( '|lisenssi = ', '|lisenssi = ' + wpLicense.options[wpLicense.selectedIndex].title )
			);
			wpLicense.selectedIndex = 0;
		}
	});
}

// Only for Special:Upload and only when not reuploading a new version of an existing image
mw.loader.using( 'mediawiki.util', function() {
	if ( mw.config.get( 'wgCanonicalSpecialPageName' ) == 'Upload' && mw.util.getParamValue( 'wpForReUpload' ) === null ) {
		$( addInformationToUploadForm );
	}
} );

/**
 * Konami Code JavaScript from http://snipplr.com/view/15785/jquery-konami-code-listener/
 * Some fixes & MediaWikification by Jack Phoenix <jack@countervandalism.net>
 * @date February 5, 2010
 */
function konamiCode() {
	var kkeys = [],
		// up, up, down, down, left, right, left, right, B, A
		konami = '38,38,40,40,37,39,37,39,66,65';
	$( document ).on( 'keydown', function( e ) {
		kkeys.push( e.keyCode );
		if ( kkeys.toString().indexOf( konami ) >= 0 ) {
			var logoURL = 'http://upload.wikimedia.org/wikipedia/en/archive/b/bc/20100513062230%21Wiki.png';
			// Hide the current logo...
			mw.util.addCSS( '#p-logo a { display: none !important; }' );
			// ...and append the new one!
			mw.util.addCSS( '#p-logo {' +
				'background-image: url("' + logoURL + '") !important;' +
				'background-repeat: no-repeat !important;' +
				'background-position: 35% 50% !important;' +
				'display: block !important;' +
			'}' );
		}
	} );
}
$( konamiCode );

// </nowiki></pre>