MediaWiki:Common.js: Difference between revisions

From Official Factorio Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
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. */
/**
* jQuery makeCollapsible
*
* Dual licensed:
* - CC BY 3.0 <http://creativecommons.org/licenses/by/3.0>
* - GPL2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
*
* @class jQuery.plugin.makeCollapsible
*/
( function ( $, mw ) {
/**
* Handler for a click on a collapsible toggler.
*
* @private
* @param {jQuery} $collapsible
* @param {string} action The action this function will take ('expand' or 'collapse').
* @param {jQuery|null} [$defaultToggle]
* @param {Object|undefined} [options]
*/
function toggleElement( $collapsible, action, $defaultToggle, options ) {
var $collapsibleContent, $containers, hookCallback;
options = options || {};
// Validate parameters
// $collapsible must be an instance of jQuery
if ( !$collapsible.jquery ) {
return;
}
if ( action !== 'expand' && action !== 'collapse' ) {
// action must be string with 'expand' or 'collapse'
return;
}
if ( $defaultToggle === undefined ) {
$defaultToggle = null;
}
if ( $defaultToggle !== null && !$defaultToggle.jquery ) {
// is optional (may be undefined), but if defined it must be an instance of jQuery.
// If it's not, abort right away.
// After this $defaultToggle is either null or a valid jQuery instance.
return;
}
// Trigger a custom event to allow callers to hook to the collapsing/expanding,
// allowing the module to be testable, and making it possible to
// e.g. implement persistence via cookies
$collapsible.trigger( action === 'expand' ? 'beforeExpand.info-collapsible' : 'beforeCollapse.info-collapsible' );
hookCallback = function () {
$collapsible.trigger( action === 'expand' ? 'afterExpand.info-collapsible' : 'afterCollapse.info-collapsible' );
};
// Handle different kinds of elements
if ( !options.plainMode && $collapsible.is( 'table' ) ) {
// Tables
// hide all rows
$containers = $collapsible.find( '> * > tr' );
if ( action === 'collapse' ) {
// Hide all table rows of this table
// Slide doesn't work with tables, but fade does as of jQuery 1.1.3
// http://stackoverflow.com/questions/467336#920480
$containers.hide();
hookCallback();
} else {
$containers.stop( true, true ).fadeIn().promise().done( hookCallback );
}
} else {
// Everything else: <div>, <p> etc.
$collapsibleContent = $collapsible.find( '> .info-collapsible-content' );
// If a collapsible-content is defined, act on it
if ( !options.plainMode && $collapsibleContent.length ) {
if ( action === 'collapse' ) {
$collapsibleContent.hide();
hookCallback();
} else {
$collapsibleContent.slideDown().promise().done( hookCallback );
}
// Otherwise assume this is a customcollapse with a remote toggle
// .. and there is no collapsible-content because the entire element should be toggled
} else {
if ( action === 'collapse' ) {
$collapsible.hide();
hookCallback();
} else {
if ( $collapsible.is( 'tr' ) || $collapsible.is( 'td' ) || $collapsible.is( 'th' ) ) {
$collapsible.fadeIn().promise().done( hookCallback );
} else {
$collapsible.slideDown().promise().done( hookCallback );
}
}
}
}
}
/**
* Handle clicking/keypressing on the collapsible element toggle and other
* situations where a collapsible element is toggled (e.g. the initial
* toggle for collapsed ones).
*
* @private
* @param {jQuery} $toggle the clickable toggle itself
* @param {jQuery} $collapsible the collapsible element
* @param {jQuery.Event|null} e either the event or null if unavailable
* @param {Object|undefined} options
*/
function togglingHandler( $toggle, $collapsible, e, options ) {
var wasCollapsed, $textContainer, collapseText, expandText;
options = options || {};
if ( e ) {
if (
e.type === 'click' &&
options.linksPassthru &&
e.target.nodeName.toLowerCase() === 'a' &&
$( e.target ).attr( 'href' ) &&
$( e.target ).attr( 'href' ) !== '#'
) {
// Don't fire if a link with href !== '#' was clicked, if requested  (for premade togglers by default)
return;
} else if ( e.type === 'keypress' && e.which !== 13 && e.which !== 32 ) {
// Only handle keypresses on the "Enter" or "Space" keys
return;
} else {
e.preventDefault();
e.stopPropagation();
}
}
// This allows the element to be hidden on initial toggle without fiddling with the class
if ( options.wasCollapsed !== undefined ) {
wasCollapsed = options.wasCollapsed;
} else {
wasCollapsed = $collapsible.hasClass( 'info-collapsed' );
}
// Toggle the state of the collapsible element (that is, expand or collapse)
$collapsible.toggleClass( 'info-collapsed', !wasCollapsed );
// Toggle the info-collapsible-toggle classes, if requested (for default and premade togglers by default)
if ( options.toggleClasses ) {
$toggle
.toggleClass( 'info-collapsible-toggle-collapsed', !wasCollapsed )
.toggleClass( 'info-collapsible-toggle-expanded', wasCollapsed );
}
// Toggle the text ("Show"/"Hide"), if requested (for default togglers by default)
//if ( options.toggleText ) {
// collapseText = options.toggleText.collapseText;
// expandText = options.toggleText.expandText;
// $textContainer = $toggle.find( '> a' );
// if ( !$textContainer.length ) {
// $textContainer = $toggle;
// }
// $textContainer.text( wasCollapsed ? collapseText : expandText );
//}
// And finally toggle the element state itself
toggleElement( $collapsible, wasCollapsed ? 'expand' : 'collapse', $toggle, options );
}
/**
* Enable collapsible-functionality on all elements in the collection.
*
* - Will prevent binding twice to the same element.
* - Initial state is expanded by default, this can be overridden by adding class
*  "info-collapsed" to the "info-collapsible" element.
* - Elements made collapsible have jQuery data "info-made-collapsible" set to true.
* - The inner content is wrapped in a "div.info-collapsible-content" (except for tables and lists).
*
* @param {Object} [options]
* @param {string} [options.collapseText] Text used for the toggler, when clicking it would
*  collapse the element. Default: the 'data-collapsetext' attribute of the
*  collapsible element or the content of 'collapsible-collapse' message.
* @param {string} [options.expandText] Text used for the toggler, when clicking it would
*  expand the element. Default: the 'data-expandtext' attribute of the
*  collapsible element or the content of 'collapsible-expand' message.
* @param {boolean} [options.collapsed] Whether to collapse immediately. By default
*  collapse only if the elements has the 'info-collapsible' class.
* @param {jQuery} [options.$customTogglers] Elements to be used as togglers
*  for this collapsible element. By default, if the collapsible element
*  has an id attribute like 'info-customcollapsible-XXX', elements with a
*  *class* of 'info-customtoggle-XXX' are made togglers for it.
* @param {boolean} [options.plainMode=false] Whether to use a "plain mode" when making the
*  element collapsible - that is, hide entire tables and lists (instead
*  of hiding only all rows but first of tables, and hiding each list
*  item separately for lists) and don't wrap other elements in
*  div.info-collapsible-content. May only be used with custom togglers.
* @return {jQuery}
* @chainable
*/
$.fn.makeCollapsible = function ( options ) {
options = options || {};
this.each( function () {
var $collapsible, collapseText, expandText, $caption, $toggle, actionHandler, buildDefaultToggleLink,
premadeToggleHandler, $toggleLink, $firstItem, collapsibleId, $customTogglers, firstval;
// Ensure class "info-collapsible" is present in case .makeCollapsible()
// is called on element(s) that don't have it yet.
$collapsible = $( this ).addClass( 'info-collapsible' );
// Return if it has been enabled already.
if ( $collapsible.data( 'info-made-collapsible' ) ) {
return;
} else {
$collapsible.data( 'info-made-collapsible', true );
}
// Use custom text or default?
collapseText = options.collapseText || $collapsible.attr( 'data-collapsetext' ) || info.msg( 'collapsible-collapse' );
expandText = options.expandText || $collapsible.attr( 'data-expandtext' ) || info.msg( 'collapsible-expand' );
// Default click/keypress handler and toggle link to use when none is present
actionHandler = function ( e, opts ) {
var defaultOpts = {
toggleClasses: true,
toggleText: { collapseText: collapseText, expandText: expandText }
};
opts = $.extend( defaultOpts, options, opts );
togglingHandler( $( this ), $collapsible, e, opts );
};
// Default toggle link. Only build it when needed to avoid jQuery memory leaks (event data).
buildDefaultToggleLink = function () {
return $( '<a>' )
.attr( {
role: 'button',
tabindex: 0
} )
.text( collapseText )
.wrap( '<span class="info-collapsible-toggle"></span>' )
.parent()
.prepend( '<span class="info-collapsible-bracket">[</span>' )
.append( '<span class="info-collapsible-bracket">]</span>' )
.on( 'click.info-collapsible keypress.info-collapsible', actionHandler );
};
// Default handler for clicking on premade toggles
premadeToggleHandler = function ( e, opts ) {
var defaultOpts = { toggleClasses: true, linksPassthru: true };
opts = $.extend( defaultOpts, options, opts );
togglingHandler( $( this ), $collapsible, e, opts );
};
// Check if this element has a custom position for the toggle link
// (ie. outside the container or deeper inside the tree)
if ( options.$customTogglers ) {
$customTogglers = $( options.$customTogglers );
} else {
collapsibleId = $collapsible.attr( 'id' ) || '';
if ( collapsibleId.indexOf( 'info-customcollapsible-' ) === 0 ) {
$customTogglers = $( '.' + collapsibleId.replace( 'info-customcollapsible', 'info-customtoggle' ) )
.addClass( 'info-customtoggle' );
}
}
// Add event handlers to custom togglers or create our own ones
if ( $customTogglers && $customTogglers.length ) {
actionHandler = function ( e, opts ) {
var defaultOpts = {};
opts = $.extend( defaultOpts, options, opts );
togglingHandler( $( this ), $collapsible, e, opts );
};
$toggleLink = $customTogglers
.on( 'click.info-collapsible keypress.info-collapsible', actionHandler )
.prop( 'tabIndex', 0 );
} else {
// If this is not a custom case, do the default: wrap the
// contents and add the toggle link. Different elements are
// treated differently.
if ( $collapsible.is( 'table' ) ) {
// If the table has a caption, collapse to the caption
// as opposed to the first row
$caption = $collapsible.find( '> caption' );
if ( $caption.length ) {
$toggle = $caption.find( '> .info-collapsible-toggle' );
// If there is no toggle link, add it to the end of the caption
if ( !$toggle.length ) {
$toggleLink = buildDefaultToggleLink().appendTo( $caption );
} else {
actionHandler = premadeToggleHandler;
$toggleLink = $toggle.on( 'click.info-collapsible keypress.info-collapsible', actionHandler )
.prop( 'tabIndex', 0 );
}
} else {
// The toggle-link will be in one of the cells (td or th) of the first row
$firstItem = $collapsible.find( 'tr:first th, tr:first td' );
$toggle = $firstItem.find( '> .info-collapsible-toggle' );
// If theres no toggle link, add it to the last cell
if ( !$toggle.length ) {
$toggleLink = buildDefaultToggleLink().prependTo( $firstItem.eq( -1 ) );
} else {
actionHandler = premadeToggleHandler;
$toggleLink = $toggle.on( 'click.info-collapsible keypress.info-collapsible', actionHandler )
.prop( 'tabIndex', 0 );
}
}
} else { // <div>, <p> etc.
// The toggle-link will be the first child of the element
$toggle = $collapsible.find( '> .info-collapsible-toggle' );
// If a direct child .content-wrapper does not exists, create it
if ( !$collapsible.find( '> .info-collapsible-content' ).length ) {
$collapsible.wrapInner( '<div class="info-collapsible-content"></div>' );
}
// If theres no toggle link, add it
if ( !$toggle.length ) {
$toggleLink = buildDefaultToggleLink().prependTo( $collapsible );
} else {
actionHandler = premadeToggleHandler;
$toggleLink = $toggle.on( 'click.info-collapsible keypress.info-collapsible', actionHandler )
.prop( 'tabIndex', 0 );
}
}
}
$( this ).data( 'info-collapsible', {
collapse: function () {
actionHandler.call( $toggleLink.get( 0 ), null, { instantHide: true, wasCollapsed: false } );
},
expand: function () {
actionHandler.call( $toggleLink.get( 0 ), null, { instantHide: true, wasCollapsed: true } );
},
toggle: function () {
actionHandler.call( $toggleLink.get( 0 ), null, null );
}
} );
// Initial state
if ( options.collapsed || $collapsible.hasClass( 'info-collapsed' ) ) {
// One toggler can hook to multiple elements, and one element can have
// multiple togglers. This is the sanest way to handle that.
actionHandler.call( $toggleLink.get( 0 ), null, { instantHide: true, wasCollapsed: false } );
}
} );
/**
* Fired after collapsible content has been initialized
*
* This gives an option to modify the collapsible behavior.
*
* @event wikipage_collapsibleContent
* @member mw.hook
* @param {jQuery} $content All the elements that have been made collapsible
*/
mw.hook( 'wikipage.collapsibleContent' ).fire( this );
return this;
};
/**
* @class jQuery
* @mixins jQuery.plugin.makeCollapsible
*/
}( jQuery, mediaWiki ) );
var globalToken;
var globalToken;



Revision as of 12:27, 21 April 2017

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



/**
 * jQuery makeCollapsible
 *
 * Dual licensed:
 * - CC BY 3.0 <http://creativecommons.org/licenses/by/3.0>
 * - GPL2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
 *
 * @class jQuery.plugin.makeCollapsible
 */
( function ( $, mw ) {

	/**
	 * Handler for a click on a collapsible toggler.
	 *
	 * @private
	 * @param {jQuery} $collapsible
	 * @param {string} action The action this function will take ('expand' or 'collapse').
	 * @param {jQuery|null} [$defaultToggle]
	 * @param {Object|undefined} [options]
	 */
	function toggleElement( $collapsible, action, $defaultToggle, options ) {
		var $collapsibleContent, $containers, hookCallback;
		options = options || {};

		// Validate parameters

		// $collapsible must be an instance of jQuery
		if ( !$collapsible.jquery ) {
			return;
		}
		if ( action !== 'expand' && action !== 'collapse' ) {
			// action must be string with 'expand' or 'collapse'
			return;
		}
		if ( $defaultToggle === undefined ) {
			$defaultToggle = null;
		}
		if ( $defaultToggle !== null && !$defaultToggle.jquery ) {
			// is optional (may be undefined), but if defined it must be an instance of jQuery.
			// If it's not, abort right away.
			// After this $defaultToggle is either null or a valid jQuery instance.
			return;
		}

		// Trigger a custom event to allow callers to hook to the collapsing/expanding,
		// allowing the module to be testable, and making it possible to
		// e.g. implement persistence via cookies
		$collapsible.trigger( action === 'expand' ? 'beforeExpand.info-collapsible' : 'beforeCollapse.info-collapsible' );
		hookCallback = function () {
			$collapsible.trigger( action === 'expand' ? 'afterExpand.info-collapsible' : 'afterCollapse.info-collapsible' );
		};

		// Handle different kinds of elements

		if ( !options.plainMode && $collapsible.is( 'table' ) ) {
			// Tables
			// hide all rows
			$containers = $collapsible.find( '> * > tr' );
			if ( action === 'collapse' ) {
				// Hide all table rows of this table
				// Slide doesn't work with tables, but fade does as of jQuery 1.1.3
				// http://stackoverflow.com/questions/467336#920480
				$containers.hide();
				hookCallback();
			} else {
				$containers.stop( true, true ).fadeIn().promise().done( hookCallback );
			}
		} else {
			// Everything else: <div>, <p> etc.
			$collapsibleContent = $collapsible.find( '> .info-collapsible-content' );

			// If a collapsible-content is defined, act on it
			if ( !options.plainMode && $collapsibleContent.length ) {
				if ( action === 'collapse' ) {
					$collapsibleContent.hide();
					hookCallback();
				} else {
					$collapsibleContent.slideDown().promise().done( hookCallback );
				}

			// Otherwise assume this is a customcollapse with a remote toggle
			// .. and there is no collapsible-content because the entire element should be toggled
			} else {
				if ( action === 'collapse' ) {
					$collapsible.hide();
					hookCallback();
				} else {
					if ( $collapsible.is( 'tr' ) || $collapsible.is( 'td' ) || $collapsible.is( 'th' ) ) {
						$collapsible.fadeIn().promise().done( hookCallback );
					} else {
						$collapsible.slideDown().promise().done( hookCallback );
					}
				}
			}
		}
	}

	/**
	 * Handle clicking/keypressing on the collapsible element toggle and other
	 * situations where a collapsible element is toggled (e.g. the initial
	 * toggle for collapsed ones).
	 *
	 * @private
	 * @param {jQuery} $toggle the clickable toggle itself
	 * @param {jQuery} $collapsible the collapsible element
	 * @param {jQuery.Event|null} e either the event or null if unavailable
	 * @param {Object|undefined} options
	 */
	function togglingHandler( $toggle, $collapsible, e, options ) {
		var wasCollapsed, $textContainer, collapseText, expandText;
		options = options || {};

		if ( e ) {
			if (
				e.type === 'click' &&
				options.linksPassthru &&
				e.target.nodeName.toLowerCase() === 'a' &&
				$( e.target ).attr( 'href' ) &&
				$( e.target ).attr( 'href' ) !== '#'
			) {
				// Don't fire if a link with href !== '#' was clicked, if requested  (for premade togglers by default)
				return;
			} else if ( e.type === 'keypress' && e.which !== 13 && e.which !== 32 ) {
				// Only handle keypresses on the "Enter" or "Space" keys
				return;
			} else {
				e.preventDefault();
				e.stopPropagation();
			}
		}

		// This allows the element to be hidden on initial toggle without fiddling with the class
		if ( options.wasCollapsed !== undefined ) {
			wasCollapsed = options.wasCollapsed;
		} else {
			wasCollapsed = $collapsible.hasClass( 'info-collapsed' );
		}

		// Toggle the state of the collapsible element (that is, expand or collapse)
		$collapsible.toggleClass( 'info-collapsed', !wasCollapsed );

		// Toggle the info-collapsible-toggle classes, if requested (for default and premade togglers by default)
		if ( options.toggleClasses ) {
			$toggle
				.toggleClass( 'info-collapsible-toggle-collapsed', !wasCollapsed )
				.toggleClass( 'info-collapsible-toggle-expanded', wasCollapsed );
		}

		// Toggle the text ("Show"/"Hide"), if requested (for default togglers by default)
		//if ( options.toggleText ) {
		//	collapseText = options.toggleText.collapseText;
		//	expandText = options.toggleText.expandText;

		//	$textContainer = $toggle.find( '> a' );
		//	if ( !$textContainer.length ) {
		//		$textContainer = $toggle;
		//	}
		//	$textContainer.text( wasCollapsed ? collapseText : expandText );
		//}

		// And finally toggle the element state itself
		toggleElement( $collapsible, wasCollapsed ? 'expand' : 'collapse', $toggle, options );
	}

	/**
	 * Enable collapsible-functionality on all elements in the collection.
	 *
	 * - Will prevent binding twice to the same element.
	 * - Initial state is expanded by default, this can be overridden by adding class
	 *   "info-collapsed" to the "info-collapsible" element.
	 * - Elements made collapsible have jQuery data "info-made-collapsible" set to true.
	 * - The inner content is wrapped in a "div.info-collapsible-content" (except for tables and lists).
	 *
	 * @param {Object} [options]
	 * @param {string} [options.collapseText] Text used for the toggler, when clicking it would
	 *   collapse the element. Default: the 'data-collapsetext' attribute of the
	 *   collapsible element or the content of 'collapsible-collapse' message.
	 * @param {string} [options.expandText] Text used for the toggler, when clicking it would
	 *   expand the element. Default: the 'data-expandtext' attribute of the
	 *   collapsible element or the content of 'collapsible-expand' message.
	 * @param {boolean} [options.collapsed] Whether to collapse immediately. By default
	 *   collapse only if the elements has the 'info-collapsible' class.
	 * @param {jQuery} [options.$customTogglers] Elements to be used as togglers
	 *   for this collapsible element. By default, if the collapsible element
	 *   has an id attribute like 'info-customcollapsible-XXX', elements with a
	 *   *class* of 'info-customtoggle-XXX' are made togglers for it.
	 * @param {boolean} [options.plainMode=false] Whether to use a "plain mode" when making the
	 *   element collapsible - that is, hide entire tables and lists (instead
	 *   of hiding only all rows but first of tables, and hiding each list
	 *   item separately for lists) and don't wrap other elements in
	 *   div.info-collapsible-content. May only be used with custom togglers.
	 * @return {jQuery}
	 * @chainable
	 */
	$.fn.makeCollapsible = function ( options ) {
		options = options || {};

		this.each( function () {
			var $collapsible, collapseText, expandText, $caption, $toggle, actionHandler, buildDefaultToggleLink,
				premadeToggleHandler, $toggleLink, $firstItem, collapsibleId, $customTogglers, firstval;

			// Ensure class "info-collapsible" is present in case .makeCollapsible()
			// is called on element(s) that don't have it yet.
			$collapsible = $( this ).addClass( 'info-collapsible' );

			// Return if it has been enabled already.
			if ( $collapsible.data( 'info-made-collapsible' ) ) {
				return;
			} else {
				$collapsible.data( 'info-made-collapsible', true );
			}

			// Use custom text or default?
			collapseText = options.collapseText || $collapsible.attr( 'data-collapsetext' ) || info.msg( 'collapsible-collapse' );
			expandText = options.expandText || $collapsible.attr( 'data-expandtext' ) || info.msg( 'collapsible-expand' );

			// Default click/keypress handler and toggle link to use when none is present
			actionHandler = function ( e, opts ) {
				var defaultOpts = {
					toggleClasses: true,
					toggleText: { collapseText: collapseText, expandText: expandText }
				};
				opts = $.extend( defaultOpts, options, opts );
				togglingHandler( $( this ), $collapsible, e, opts );
			};
			// Default toggle link. Only build it when needed to avoid jQuery memory leaks (event data).
			buildDefaultToggleLink = function () {
				return $( '<a>' )
					.attr( {
						role: 'button',
						tabindex: 0
					} )
					.text( collapseText )
					.wrap( '<span class="info-collapsible-toggle"></span>' )
						.parent()
						.prepend( '<span class="info-collapsible-bracket">[</span>' )
						.append( '<span class="info-collapsible-bracket">]</span>' )
						.on( 'click.info-collapsible keypress.info-collapsible', actionHandler );
			};

			// Default handler for clicking on premade toggles
			premadeToggleHandler = function ( e, opts ) {
				var defaultOpts = { toggleClasses: true, linksPassthru: true };
				opts = $.extend( defaultOpts, options, opts );
				togglingHandler( $( this ), $collapsible, e, opts );
			};

			// Check if this element has a custom position for the toggle link
			// (ie. outside the container or deeper inside the tree)
			if ( options.$customTogglers ) {
				$customTogglers = $( options.$customTogglers );
			} else {
				collapsibleId = $collapsible.attr( 'id' ) || '';
				if ( collapsibleId.indexOf( 'info-customcollapsible-' ) === 0 ) {
					$customTogglers = $( '.' + collapsibleId.replace( 'info-customcollapsible', 'info-customtoggle' ) )
						.addClass( 'info-customtoggle' );
				}
			}

			// Add event handlers to custom togglers or create our own ones
			if ( $customTogglers && $customTogglers.length ) {
				actionHandler = function ( e, opts ) {
					var defaultOpts = {};
					opts = $.extend( defaultOpts, options, opts );
					togglingHandler( $( this ), $collapsible, e, opts );
				};

				$toggleLink = $customTogglers
					.on( 'click.info-collapsible keypress.info-collapsible', actionHandler )
					.prop( 'tabIndex', 0 );

			} else {
				// If this is not a custom case, do the default: wrap the
				// contents and add the toggle link. Different elements are
				// treated differently.

				if ( $collapsible.is( 'table' ) ) {

					// If the table has a caption, collapse to the caption
					// as opposed to the first row
					$caption = $collapsible.find( '> caption' );
					if ( $caption.length ) {
						$toggle = $caption.find( '> .info-collapsible-toggle' );

						// If there is no toggle link, add it to the end of the caption
						if ( !$toggle.length ) {
							$toggleLink = buildDefaultToggleLink().appendTo( $caption );
						} else {
							actionHandler = premadeToggleHandler;
							$toggleLink = $toggle.on( 'click.info-collapsible keypress.info-collapsible', actionHandler )
								.prop( 'tabIndex', 0 );
						}
					} else {
						// The toggle-link will be in one of the cells (td or th) of the first row
						$firstItem = $collapsible.find( 'tr:first th, tr:first td' );
						$toggle = $firstItem.find( '> .info-collapsible-toggle' );

						// If theres no toggle link, add it to the last cell
						if ( !$toggle.length ) {
							$toggleLink = buildDefaultToggleLink().prependTo( $firstItem.eq( -1 ) );
						} else {
							actionHandler = premadeToggleHandler;
							$toggleLink = $toggle.on( 'click.info-collapsible keypress.info-collapsible', actionHandler )
								.prop( 'tabIndex', 0 );
						}
					}
				} else { // <div>, <p> etc.

					// The toggle-link will be the first child of the element
					$toggle = $collapsible.find( '> .info-collapsible-toggle' );

					// If a direct child .content-wrapper does not exists, create it
					if ( !$collapsible.find( '> .info-collapsible-content' ).length ) {
						$collapsible.wrapInner( '<div class="info-collapsible-content"></div>' );
					}

					// If theres no toggle link, add it
					if ( !$toggle.length ) {
						$toggleLink = buildDefaultToggleLink().prependTo( $collapsible );
					} else {
						actionHandler = premadeToggleHandler;
						$toggleLink = $toggle.on( 'click.info-collapsible keypress.info-collapsible', actionHandler )
							.prop( 'tabIndex', 0 );
					}
				}
			}

			$( this ).data( 'info-collapsible', {
				collapse: function () {
					actionHandler.call( $toggleLink.get( 0 ), null, { instantHide: true, wasCollapsed: false } );
				},
				expand: function () {
					actionHandler.call( $toggleLink.get( 0 ), null, { instantHide: true, wasCollapsed: true } );
				},
				toggle: function () {
					actionHandler.call( $toggleLink.get( 0 ), null, null );
				}
			} );

			// Initial state
			if ( options.collapsed || $collapsible.hasClass( 'info-collapsed' ) ) {
				// One toggler can hook to multiple elements, and one element can have
				// multiple togglers. This is the sanest way to handle that.
				actionHandler.call( $toggleLink.get( 0 ), null, { instantHide: true, wasCollapsed: false } );
			}

		} );

		/**
		 * Fired after collapsible content has been initialized
		 *
		 * This gives an option to modify the collapsible behavior.
		 *
		 * @event wikipage_collapsibleContent
		 * @member mw.hook
		 * @param {jQuery} $content All the elements that have been made collapsible
		 */
		mw.hook( 'wikipage.collapsibleContent' ).fire( this );

		return this;
	};

	/**
	 * @class jQuery
	 * @mixins jQuery.plugin.makeCollapsible
	 */

}( jQuery, mediaWiki ) );












var globalToken;

function getToken() {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'query',
            meta: 'tokens',
            bot: true
        },
        async: false,
        dataType: 'json',
        type: 'POST',
        success: function( data ) {
           globalToken = data.query.tokens.csrftoken;
        },
        error: function( xhr ) {
            console.log("Failed to perform null edit");
        }
    });
}

/*** Language template ***/
if($(".languages-flags .flag").length == 0) {
 console.log("Not showing languages bar because there's no other language's version of this page.");
 $(".languages-container").hide();
}

//Spoiler template JavaScript
$(".spoiler-container .button").click(function() {
  $(this).siblings(".text").toggle("slow");
});

var wantedPagesListsLocation = "User:TheWombatGuru/WantedPages"

$("#create-wanted-pages-list").click(function(){
    getToken();
    createWantedPagesLists();
});

function createWantedPagesLists() {
    var wantedPages = getWantedPages();
    wantedPages = wantedPages.sort(compare);

    splitWantedPagesIntoDifferentLanguages(wantedPages);
};

function splitWantedPagesIntoDifferentLanguages(wantedPages) {
  var czechWantedPages = []; 
  var germanWantedPages = [];
  var spanishWantedPages = [];
  var frenchWantedPages = [];
  var italianWantedPages = [];
  var japaneseWantedPages = [];
  var dutchWantedPages = [];
  var polishWantedPages = [];
  var portugueseWantedPages = [];
  var russianWantedPages = [];
  var swedishWantedPages = [];
  var ukrainianWantedPages = [];
  var chineseWantedPages = [];
  var wantedFiles = [];
  var wantedTemplates = [];
  var otherWantedPages = [];

  for (var i = 0; i < wantedPages.length; i++) {
    switch (wantedPages[i].title.slice(-3)) {//"/cs", "/de", "/es", "/fr", "/it", "/ja", "/nl", "/pl", "/-br", "/ru", "/sv", "/uk", "/zh"
      case "/cs": czechWantedPages.push(wantedPages[i]); break;
      case "/de": germanWantedPages.push(wantedPages[i]); break;
      case "/es": spanishWantedPages.push(wantedPages[i]); break;
      case "/fr": frenchWantedPages.push(wantedPages[i]); break;
      case "/it": italianWantedPages.push(wantedPages[i]); break;
      case "/ja": japaneseWantedPages.push(wantedPages[i]); break;
      case "/nl": dutchWantedPages.push(wantedPages[i]); break;
      case "/pl": polishWantedPages.push(wantedPages[i]); break;
      case "-br": portugueseWantedPages.push(wantedPages[i]); break;
      case "/ru": russianWantedPages.push(wantedPages[i]); break;
      case "/sv": swedishWantedPages.push(wantedPages[i]); break;
      case "/uk": ukrainianWantedPages.push(wantedPages[i]); break;
      case "/zh": chineseWantedPages.push(wantedPages[i]); break;
      default: if (wantedPages[i].title.slice(0, 5) == "File:") {wantedFiles.push(wantedPages[i])} else if (wantedPages[i].title.slice(0, 9) == "Template:") {wantedTemplates.push(wantedPages[i])} else {otherWantedPages.push(wantedPages[i])}; break;
    }
  }

  createWantedPagesPage("cs", czechWantedPages, "Czech");
  createWantedPagesPage("de", germanWantedPages, "German");
  createWantedPagesPage("es", spanishWantedPages, "Spanish");
  createWantedPagesPage("fr", frenchWantedPages, "French");
  createWantedPagesPage("it", italianWantedPages, "Italian");
  createWantedPagesPage("ja", japaneseWantedPages, "Japanese");
  createWantedPagesPage("nl", dutchWantedPages, "Dutch");
  createWantedPagesPage("pl", polishWantedPages, "Polish");
  createWantedPagesPage("pt-br", portugueseWantedPages, "Portuguese");
  createWantedPagesPage("ru", russianWantedPages, "Russian");
  createWantedPagesPage("sv", swedishWantedPages, "Swedish");
  createWantedPagesPage("uk", ukrainianWantedPages, "Ukrainian");
  createWantedPagesPage("zh", chineseWantedPages, "Chinese");

  createWantedPagesPage("file", wantedFiles, "Files");
  createWantedPagesPage("template", wantedTemplates, "Templates");
  createWantedPagesPage("other", otherWantedPages, "Other");
}

function createWantedPagesPage(location, wantedPages, language) {
  var formattedWantedPages = "Number of wanted pages in " + language + ": " + wantedPages.length + "\n{|class=wikitable\n!#\n!Page\n!Links to this page";

  for (var i = 0; i < wantedPages.length; i++) {
    formattedWantedPages = formattedWantedPages.concat("\n|-\n|" + (i + 1) + "\n|[https://wiki.factorio.com/index.php?title=" + encodeURI(wantedPages[i].title) + " " + wantedPages[i].title + "]\n|[https://wiki.factorio.com/index.php?title=Special:WhatLinksHere/" + encodeURI(wantedPages[i].title) + " " + wantedPages[i].value + "]");
  }

  formattedWantedPages = formattedWantedPages.concat("\n|}");

  createPage(wantedPagesListsLocation + "/" + location, formattedWantedPages, "(BOT) - Update the list of wanted pages for " + language + ".");
}

function performNullEdit(pageTitle, summary) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'edit',
            title: pageTitle,
            section: 0,
            text: "",
            token: globalToken,
            summary: summary,
            bot: true
        },
        async: false,
        dataType: 'json',
        type: 'POST',
        success: function( data ) {
           console.log("Performed null edit");
        },
        error: function( xhr ) {
            console.log("Failed to perform null edit");
        }
    });
}

function purgeWhatLinksHere(pageTitle) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: "json",
            action: 'query',
            list: "backlinks",
            bltitle: pageTitle,
            bllimit: 500
        },
        async: true,
        type: 'GET',
        success: function( data ) {
            console.log(data);
            for (var i = 0; i < data.query.backlinks.length; i++) {
                purgePage(data.query.backlinks[i].title);
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed.' );
            console.log("Failed purging");
        }
    });
}

function purgePage(pageTitle) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            action: 'purge',
            forcelinkupdate: true,
            titles: pageTitle,
            prop: "info"
        },
        async: true,
        type: 'GET',
        success: function( data ) {
            console.log("purging " + pageTitle);
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed.' );
            console.log("Failed purging");
        }
    });
}

function compare(a,b) {
  if (parseInt(a.value) > parseInt(b.value))
    return -1;
  if (parseInt(a.value) < parseInt(b.value))
    return 1;
  if (a.title < b.title)
    return -1;
  if (a.title > b.title)
    return 1;
  return 0;
}

function createPage(pageTitle, content, summary) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'edit',
            title: pageTitle,
            text: content,
            token: globalToken,
            summary: summary,
            bot: true
        },
        async: false,
        dataType: 'json',
        type: 'POST',
        success: function( data ) {
           console.log("created page");
        },
        error: function( xhr ) {
            console.log("failed to create page");
        }
    });
}

function getWantedPages() {
   var wantedPages = [];

   $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'query',
            list: 'querypage',
            qppage: 'Wantedpages',
            qplimit: '5000',
        },
        async: false,
        dataType: 'json',
        type: 'GET',
        success: function( data ) {
            var results = data.query.querypage.results;
            for (var i = 0; i < results.length; i++) {
               var pageObject = new WantedPage(results[i].title, results[i].value);
               var alreadyInArray = false;
               for (var j = 0; j < wantedPages.length; j++) {
                 if (wantedPages[j].title == pageObject.title) {
                    alreadyInArray = true;
                 }
               }
               if (!alreadyInArray) {
                 wantedPages.push(pageObject);
               }
               if (pageObject.title == "Rocket defense/it") {
               }
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed. Category' );
        }
  });

$.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'query',
            list: 'querypage',
            qppage: 'Wantedpages',
            qplimit: '5000',
            qpoffset: '3000',
        },
        async: false,
        dataType: 'json',
        type: 'GET',
        success: function( data ) {
            var results = data.query.querypage.results;
            for (var i = 0; i < results.length; i++) {
               var pageObject = new WantedPage(results[i].title, results[i].value);
               var alreadyInArray = false;
               for (var j = 0; j < wantedPages.length; j++) {
                 if (wantedPages[j].title == pageObject.title) {
                    alreadyInArray = true;
                 }
               }
               if (!alreadyInArray) {
                 wantedPages.push(pageObject);
               }
               if (pageObject.title == "Rocket defense/it") {
               }
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed. Category' );
        }
  });
  return wantedPages;
};

function WantedPage(pageTitle, pageValue) {
   this.title = pageTitle;
   this.value = pageValue;
}


/* OLD INFOBOX CONVERSION TOOLS */
/*function targetAllPagesInCategory(category) {
    var languageSuffixes = ["/fr", "/ru", "/de"]; //, "/cs", "/de", "/es", "/fr", "/it", "/nl", "/pl", "/pt-br", "/ru", "/sv", "/uk", "/zh", ""];
    for (var j = 0; j < languageSuffixes.length; j++) {
      $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'query',
            list: 'categorymembers',
            cmtitle: (category + languageSuffixes[j]),
            cmlimit: 500
        },
        dataType: 'json',
        type: 'GET',
        success: function( data ) {
            var pages = data.query.categorymembers;
            for (var i = 0; i < pages.length; i++) {
                    //purgePage(pages[i].title);
                    extractPageInfo(pages[i].title, "9c28a1344a20bf189fda7d58339e518257f2dd9b+\\");
                
            }

            if ( data && data.query && data.query.result == 'Success' ) {
                window.location.reload(); // reload page if edit was successful
            } else if ( data && data.error ) {
                //alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info + 'Category' );
            } else {
                //alert( 'Error: Unknown result from API. Category' );
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed. Category' );
        }
    });
  }
}

function extractPageInfo(pageTitle, token) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'query',
            titles: pageTitle,
            prop: 'revisions',
            rvprop: 'content'
        },
        async: false,
        dataType: 'json',
        type: 'GET',
        success: function( data ) {
            var pages = data.query.pages;
            var revisions = pages[Object.keys(pages)[0]].revisions[0];
            var content = revisions[Object.keys(revisions)[2]]
            var title = pages[Object.keys(pages)[0]].title;
            createNewInfoboxPage(title, content, token);
            if ( data && data.query && data.query.result == 'Success' ) {
                window.location.reload(); // reload page if edit was successful
            } else if ( data && data.error ) {
                //alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info );
            } else {
                //alert( 'Error: Unknown result from API.' );
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed.' );
        }
    });
}

function createNewInfoboxPage(page, contentOfMainPage, token) {
    var infoboxText = getInfoboxFromFullPageContent(contentOfMainPage);

    var infoboxPageTitle = page.replace(/\/(de|fr|nl|it|es|ru|pt\-br|cs|pl|sv|uk|zh)/g, function(piece) {return "";}).concat("/infobox");
    var oldPageRevisedText = getOldPageRevisedText(page, contentOfMainPage, infoboxPageTitle);	
    removeInfoboxFromMain(page, oldPageRevisedText, token);

    if (infoboxText != null) {
      if (/\/(de|fr|nl|it|es|ru|pt\-br|cs|pl|sv|uk|zh)/g.test(page)) {
        return;
      }
      var newPageTitle = page.concat("/infobox");
      var convertedInfoboxText = convertInfobox(infoboxText, token);
      createPage(newPageTitle, convertedInfoboxText, token, page, contentOfMainPage);
    }
}

function getOldPageRevisedText(pageTitle, content, infoboxPageTitle) {
    content = content.replace(/{{\bCombat\b(\s+(\||{).+)+\s}}/gi, function (piece) {
        return "{{:" + infoboxPageTitle + "}}";
    });
    return content;
}

function removeInfoboxFromMain(pageTitle, content, token) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'edit',
            title: pageTitle,
            text: content,
            bot: true,
            token: token,
            summary: "(BOT) - Replaced old infobox with a link to the /infobox subpage"
        },
        async: false,
        dataType: 'json',
        type: 'POST',
        success: function( data ) {
            if ( data && data.edit && data.edit.result == 'Success' ) {
                window.location.reload(); // reload page if edit was successful
            } else if ( data && data.error ) {
                //alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info );
            } else {
                //alert( 'Error: Unknown result from API.' );
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed.' );
        }
    })
};

function getInfoboxFromFullPageContent(contentOfPage) {
    var matches = contentOfPage.match(/{{\bCombat\b(\s+\|.+)+\s}}/gi);
if (matches != null && matches.length > 0) {
 infoboxText = matches[0];
} else {
 infoboxText = null;
}
    return infoboxText;
}

function convertInfobox(text) {
    text = text.replace(/{{(\w+)/g, function (piece, $1) {
        var returnText = "{{Infobox\n| category = ";

        $1 = $1.toLowerCase();

        switch ($1) {
            case "item":
                returnText = returnText.concat("Items");
                break;
            case "machinery":
                returnText = returnText.concat("Machinery");
                break;
            case "combat":
                returnText = returnText.concat("Combat");
                break;
            case "technology":
                returnText = returnText.concat("Technology");
        }

        switch ($1) {
            case "machinery":
                returnText = returnText.concat("\n| category-name = Machine");
                break;
            case "item":
                returnText = returnText.concat("\n| category-name = Item");
                break;
        }

        return returnText;
    });

    text = text.replace("stack_size", "stack-size");
    text = text.replace("poweroutput", "power-output");
    text = text.replace("input", "recipe");
    text = text.replace("raw", "total-raw");
    text = text.replace("technologies", "required-technologies");
    text = text.replace("costmultiplier", "cost-multiplier");
    text = text.replace("requirements", "required-technologies");
    text = text.replace("walkingspeed", "walking-speed");
    text = text.replace("storagesize", "storage-size");
    text = text.replace("gridsize", "grid-size");
    text = text.replace("shootingspeed", "shooting-speed");
    text = text.replace("damagebonus", "damage-bonus");
    text = text.replace("clustersize", "cluster-size");
    text = text.replace("aoesize", "area-of-effect-size");
    text = text.replace("magazinesize", "magazine-size");
    text = text.replace("recharge", "robot-recharge-rate");
    text = text.replace("rechargebuffer", "internal-buffer-recharge-rate");
    text = text.replace("wirereach", "wire-reach");
    text = text.replace("craftingspeed", "crafting-speed");
    text = text.replace("smeltingspeed", "smelting-speed");
    text = text.replace("miningpower", "mining-power");
    text = text.replace("miningspeed", "mining-speed");
    text = text.replace("miningarea", "mining-area");
    text = text.replace("supplyarea", "supply-area");
    text = text.replace("constructionarea", "construction-area");
    text = text.replace("lifetime", "lifespan");
    text = text.replace("inventorysizebonus", "inventory-size-bonus");
    text = text.replace("gridsize", "grid-size");
    text = text.replace("boosttechs", "boosting-technologies");
    text = text.replace("allowstech", "allows");
    text = text.replace("storage", "storage-size");
    text = text.replace(/\|\s*\brecipe\b\s*=\s*(.+)\n\|\s*\boutput\b\s*=\s*(.+)/g, function (piece, $1, $2) {
        return "| recipe = " + $1 + " = " + $2;
    });

    text = text.concat("<noinclude>[[Category:Infobox page]]</noinclude>");

    return text;
}

function createPage(pageTitle, content, token, page, contentOfMainPage) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'edit',
            title: pageTitle,
            text: content,
            bot: true,
            createonly: true,
            token: token,
            summary: "(BOT) - Created infobox sub page for " + page
        },
        async: false,
        dataType: 'json',
        type: 'POST',
        success: function( data ) {
           
            if ( data && data.edit && data.edit.result == 'Success' ) {
                window.location.reload(); // reload page if edit was successful
            } else if ( data && data.error ) {
                //alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info );
            } else {
                //alert( 'Error: Unknown result from API.' );
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed.' );
        }
    });
}*/
/* END OF OLD INFOBOX CONVERSION TOOL */