* Break long lines
[lhc/web/wiklou.git] / resources / mediawiki / mediawiki.js
1 /*
2 * JavaScript backwards-compatibility and support
3 */
4
5 // Implementation of string trimming functionality introduced natively in JavaScript 1.8.1
6 if ( typeof String.prototype.trim === 'undefined' ) {
7 // Add removing trailing and leading whitespace functionality cross-browser
8 // See also: http://blog.stevenlevithan.com/archives/faster-trim-javascript
9 String.prototype.trim = function() {
10 return this.replace( /^\s+|\s+$/g, '' );
11 };
12 }
13 if ( typeof String.prototype.trimLeft === 'undefined' ) {
14 String.prototype.trimLeft = function() {
15 return this.replace( /^\s\s*/, "" );
16 };
17 }
18 if ( typeof String.prototype.trimRight === 'undefined' ) {
19 String.prototype.trimRight = function() {
20 return this.replace(/\s\s*$/, "");
21 };
22 }
23
24 /*
25 * Prototype enhancements
26 */
27
28 // Capitalize the first character of the given string
29 if ( typeof String.prototype.ucFirst === 'undefined' ) {
30 String.prototype.ucFirst = function() {
31 return this.substr(0, 1).toUpperCase() + this.substr(1, this.length);
32 };
33 }
34
35 // Escape all RegExp special characters such that the result can be safely used
36 // in a RegExp as a literal.
37 if ( typeof String.prototype.escapeRE === 'undefined' ) {
38 String.prototype.escapeRE = function() {
39 return this.replace (/([\\{}()|.?*+^$\[\]])/g, "\\$1");
40 };
41 }
42
43 /*
44 * Core MediaWiki JavaScript Library
45 */
46
47 // Attach to window
48 window.mediaWiki = new ( function( $ ) {
49
50 /* Constants */
51
52 // This will not change until we are 100% ready to turn off legacy globals
53 var LEGACY_GLOBALS = true;
54
55 /* Private Members */
56
57 // List of messages that have been requested to be loaded
58 var messageQueue = {};
59
60 /* Prototypes */
61
62 /**
63 * An object which allows single and multiple get/set/exists functionality
64 * on a list of key / value pairs.
65 *
66 * @param {boolean} global Whether to get/set/exists values on the window
67 * object or a private object
68 */
69 function Map( global ) {
70 this.values = ( global === true ) ? window : {};
71 };
72
73 /**
74 * Gets the value of a key, or a list of key/value pairs for an array of keys.
75 *
76 * If called with no arguments, all values will be returned.
77 *
78 * @param {mixed} selection Key or array of keys to get values for
79 * @param {mixed} fallback Value to use in case key(s) do not exist (optional)
80 */
81 Map.prototype.get = function( selection, fallback ) {
82 if ( typeof selection === 'object' ) {
83 selection = $.makeArray( selection );
84 var results = {};
85 for ( var i = 0; i < selection.length; i++ ) {
86 results[selection[i]] = this.get( selection[i], fallback );
87 }
88 return results;
89 } else if ( typeof selection === 'string' ) {
90 if ( typeof this.values[selection] === 'undefined' ) {
91 if ( typeof fallback !== 'undefined' ) {
92 return fallback;
93 }
94 return null;
95 }
96 return this.values[selection];
97 }
98 return this.values;
99 };
100
101 /**
102 * Sets one or multiple key/value pairs.
103 *
104 * @param {mixed} selection Key or object of key/value pairs to set
105 * @param {mixed} value Value to set (optional, only in use when key is a string)
106 */
107 Map.prototype.set = function( selection, value ) {
108 if ( typeof selection === 'object' ) {
109 for ( var s in selection ) {
110 this.values[s] = selection[s];
111 }
112 } else if ( typeof selection === 'string' && typeof value !== 'undefined' ) {
113 this.values[selection] = value;
114 }
115 };
116
117 /**
118 * Checks if one or multiple keys exist.
119 *
120 * @param {mixed} key Key or array of keys to check
121 * @return {boolean} Existence of key(s)
122 */
123 Map.prototype.exists = function( selection ) {
124 if ( typeof keys === 'object' ) {
125 for ( var s = 0; s < selection.length; s++ ) {
126 if ( !( selection[s] in this.values ) ) {
127 return false;
128 }
129 }
130 return true;
131 } else {
132 return selection in this.values;
133 }
134 };
135
136 /**
137 * Message object, similar to Message in PHP
138 */
139 function Message( map, key, parameters ) {
140 this.format = 'parse';
141 this.map = map;
142 this.key = key;
143 this.parameters = typeof parameters === 'undefined' ? [] : $.makeArray( parameters );
144 };
145
146 /**
147 * Appends parameters for replacement
148 *
149 * @param {mixed} args First in a list of variadic arguments to append as message parameters
150 */
151 Message.prototype.params = function( parameters ) {
152 for ( var i = 0; i < parameters.length; i++ ) {
153 this.parameters[this.parameters.length] = parameters[i];
154 }
155 return this;
156 };
157
158 /**
159 * Converts message object to it's string form based on the state of format
160 *
161 * @return {string} String form of message
162 */
163 Message.prototype.toString = function() {
164 if ( !this.map.exists( this.key ) ) {
165 // Return <key> if key does not exist
166 return '<' + this.key + '>';
167 }
168 var text = this.map.get( this.key );
169 var parameters = this.parameters;
170 text = text.replace( /\$(\d+)/g, function( string, match ) {
171 var index = parseInt( match, 10 ) - 1;
172 return index in parameters ? parameters[index] : '$' + match;
173 } );
174 /* This should be fixed up when we have a parser
175 if ( this.format === 'parse' && 'language' in mediaWiki ) {
176 text = mediaWiki.language.parse( text );
177 }
178 */
179 return text;
180 };
181
182 /**
183 * Changes format to parse and converts message to string
184 *
185 * @return {string} String form of parsed message
186 */
187 Message.prototype.parse = function() {
188 this.format = 'parse';
189 return this.toString();
190 };
191
192 /**
193 * Changes format to plain and converts message to string
194 *
195 * @return {string} String form of plain message
196 */
197 Message.prototype.plain = function() {
198 this.format = 'plain';
199 return this.toString();
200 };
201
202 /**
203 * Checks if message exists
204 *
205 * @return {string} String form of parsed message
206 */
207 Message.prototype.exists = function() {
208 return this.map.exists( this.key );
209 };
210
211 /**
212 * User object
213 */
214 function User() {
215 this.options = new Map();
216 }
217
218 /* Public Members */
219
220 /*
221 * Dummy function which in debug mode can be replaced with a function that
222 * does something clever
223 */
224 this.log = function() { };
225
226 /*
227 * List of configuration values
228 *
229 * In legacy mode the values this object wraps will be in the global space
230 */
231 this.config = new Map( LEGACY_GLOBALS );
232
233 /*
234 * Information about the current user
235 */
236 this.user = new User();
237
238 /*
239 * Localization system
240 */
241 this.messages = new Map();
242
243 /* Public Methods */
244
245 /**
246 * Gets a message object, similar to wfMessage()
247 *
248 * @param {string} key Key of message to get
249 * @param {mixed} params First argument in a list of variadic arguments, each a parameter for $
250 * replacement
251 */
252 this.message = function( key, parameters ) {
253 // Support variadic arguments
254 if ( typeof parameters !== 'undefined' ) {
255 parameters = $.makeArray( arguments );
256 parameters.shift();
257 } else {
258 parameters = [];
259 }
260 return new Message( mediaWiki.messages, key, parameters );
261 };
262
263 /**
264 * Gets a message string, similar to wfMsg()
265 *
266 * @param {string} key Key of message to get
267 * @param {mixed} params First argument in a list of variadic arguments, each a parameter for $
268 * replacement
269 */
270 this.msg = function( key, parameters ) {
271 return mediaWiki.message.apply( mediaWiki.message, arguments ).toString();
272 };
273
274 /**
275 * Client-side module loader which integrates with the MediaWiki ResourceLoader
276 */
277 this.loader = new ( function() {
278
279 /* Private Members */
280
281 /**
282 * Mapping of registered modules
283 *
284 * The jquery module is pre-registered, because it must have already
285 * been provided for this object to have been built, and in debug mode
286 * jquery would have been provided through a unique loader request,
287 * making it impossible to hold back registration of jquery until after
288 * mediawiki.
289 *
290 * Format:
291 * {
292 * 'moduleName': {
293 * 'dependencies': ['required module', 'required module', ...], (or) function() {}
294 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
295 * 'script': function() {},
296 * 'style': 'css code string',
297 * 'messages': { 'key': 'value' },
298 * 'version': ############## (unix timestamp)
299 * }
300 * }
301 */
302 var registry = {};
303 // List of modules which will be loaded as when ready
304 var batch = [];
305 // List of modules to be loaded
306 var queue = [];
307 // List of callback functions waiting for modules to be ready to be called
308 var jobs = [];
309 // Flag indicating that requests should be suspended
310 var suspended = true;
311 // Flag inidicating that document ready has occured
312 var ready = false;
313
314 /* Private Methods */
315
316 function compare( a, b ) {
317 if ( a.length != b.length ) {
318 return false;
319 }
320 for ( var i = 0; i < b.length; i++ ) {
321 if ( $.isArray( a[i] ) ) {
322 if ( !compare( a[i], b[i] ) ) {
323 return false;
324 }
325 }
326 if ( a[i] !== b[i] ) {
327 return false;
328 }
329 }
330 return true;
331 };
332
333 /**
334 * Generates an ISO8601 "basic" string from a UNIX timestamp
335 */
336 function formatVersionNumber( timestamp ) {
337 function pad( a, b, c ) {
338 return [a < 10 ? '0' + a : a, b < 10 ? '0' + b : b, c < 10 ? '0' + c : c].join( '' );
339 }
340 var d = new Date()
341 d.setTime( timestamp * 1000 );
342 return [
343 pad( d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate() ), 'T',
344 pad( d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds() ), 'Z'
345 ].join( '' );
346 }
347
348 /**
349 * Recursively resolves dependencies and detects circular references
350 */
351 function recurse( module, resolved, unresolved ) {
352 if ( typeof registry[module] === 'undefined' ) {
353 throw new Error( 'Unknown dependency: ' + module );
354 }
355 // Resolves dynamic loader function and replaces it with its own results
356 if ( typeof registry[module].dependencies === 'function' ) {
357 registry[module].dependencies = registry[module].dependencies();
358 // Ensures the module's dependencies are always in an array
359 if ( typeof registry[module].dependencies !== 'object' ) {
360 registry[module].dependencies = [registry[module].dependencies];
361 }
362 }
363 // Tracks down dependencies
364 for ( var n = 0; n < registry[module].dependencies.length; n++ ) {
365 if ( $.inArray( registry[module].dependencies[n], resolved ) === -1 ) {
366 if ( $.inArray( registry[module].dependencies[n], unresolved ) !== -1 ) {
367 throw new Error(
368 'Circular reference detected: ' + module +
369 ' -> ' + registry[module].dependencies[n]
370 );
371 }
372 recurse( registry[module].dependencies[n], resolved, unresolved );
373 }
374 }
375 resolved[resolved.length] = module;
376 unresolved.splice( $.inArray( module, unresolved ), 1 );
377 }
378
379 /**
380 * Gets a list of module names that a module depends on in their proper dependency order
381 *
382 * @param mixed string module name or array of string module names
383 * @return list of dependencies
384 * @throws Error if circular reference is detected
385 */
386 function resolve( module, resolved, unresolved ) {
387 // Allow calling with an array of module names
388 if ( typeof module === 'object' ) {
389 var modules = [];
390 for ( var m = 0; m < module.length; m++ ) {
391 var dependencies = resolve( module[m] );
392 for ( var n = 0; n < dependencies.length; n++ ) {
393 modules[modules.length] = dependencies[n];
394 }
395 }
396 return modules;
397 } else if ( typeof module === 'string' ) {
398 // Undefined modules have no dependencies
399 if ( !( module in registry ) ) {
400 return [];
401 }
402 var resolved = [];
403 recurse( module, resolved, [] );
404 return resolved;
405 }
406 throw new Error( 'Invalid module argument: ' + module );
407 };
408
409 /**
410 * Narrows a list of module names down to those matching a specific
411 * state. Possible states are 'undefined', 'registered', 'loading',
412 * 'loaded', or 'ready'
413 *
414 * @param mixed string or array of strings of module states to filter by
415 * @param array list of module names to filter (optional, all modules
416 * will be used by default)
417 * @return array list of filtered module names
418 */
419 function filter( states, modules ) {
420 // Allow states to be given as a string
421 if ( typeof states === 'string' ) {
422 states = [states];
423 }
424 // If called without a list of modules, build and use a list of all modules
425 var list = [];
426 if ( typeof modules === 'undefined' ) {
427 modules = [];
428 for ( module in registry ) {
429 modules[modules.length] = module;
430 }
431 }
432 // Build a list of modules which are in one of the specified states
433 for ( var s = 0; s < states.length; s++ ) {
434 for ( var m = 0; m < modules.length; m++ ) {
435 if ( typeof registry[modules[m]] === 'undefined' ) {
436 // Module does not exist
437 if ( states[s] == 'undefined' ) {
438 // OK, undefined
439 list[list.length] = modules[m];
440 }
441 } else {
442 // Module exists, check state
443 if ( registry[modules[m]].state === states[s] ) {
444 // OK, correct state
445 list[list.length] = modules[m];
446 }
447 }
448 }
449 }
450 return list;
451 }
452
453 this.filter_ = filter;
454
455 /**
456 * Executes a loaded module, making it ready to use
457 *
458 * @param string module name to execute
459 */
460 function execute( module ) {
461 if ( typeof registry[module] === 'undefined' ) {
462 throw new Error( 'Module has not been registered yet: ' + module );
463 } else if ( registry[module].state === 'registered' ) {
464 throw new Error( 'Module has not been requested from the server yet: ' + module );
465 } else if ( registry[module].state === 'loading' ) {
466 throw new Error( 'Module has not completed loading yet: ' + module );
467 } else if ( registry[module].state === 'ready' ) {
468 throw new Error( 'Module has already been loaded: ' + module );
469 }
470 // Add style sheet to document
471 if ( typeof registry[module].style === 'string' && registry[module].style.length ) {
472 $( 'head' )
473 .append( '<style type="text/css">' + registry[module].style + '</style>' );
474 } else if ( typeof registry[module].style === 'object'
475 && !( registry[module].style instanceof Array ) )
476 {
477 for ( var media in registry[module].style ) {
478 $( 'head' ).append(
479 '<style type="text/css" media="' + media + '">' +
480 registry[module].style[media] +
481 '</style>'
482 );
483 }
484 }
485 // Add localizations to message system
486 if ( typeof registry[module].messages === 'object' ) {
487 mediaWiki.messages.set( registry[module].messages );
488 }
489 // Execute script
490 try {
491 registry[module].script();
492 registry[module].state = 'ready';
493 // Run jobs who's dependencies have just been met
494 for ( var j = 0; j < jobs.length; j++ ) {
495 if ( compare(
496 filter( 'ready', jobs[j].dependencies ),
497 jobs[j].dependencies ) )
498 {
499 if ( typeof jobs[j].ready === 'function' ) {
500 jobs[j].ready();
501 }
502 jobs.splice( j, 1 );
503 j--;
504 }
505 }
506 // Execute modules who's dependencies have just been met
507 for ( r in registry ) {
508 if ( registry[r].state == 'loaded' ) {
509 if ( compare(
510 filter( ['ready'], registry[r].dependencies ),
511 registry[r].dependencies ) )
512 {
513 execute( r );
514 }
515 }
516 }
517 } catch ( e ) {
518 mediaWiki.log( 'Exception thrown by ' + module + ': ' + e.message );
519 mediaWiki.log( e );
520 registry[module].state = 'error';
521 // Run error callbacks of jobs affected by this condition
522 for ( var j = 0; j < jobs.length; j++ ) {
523 if ( $.inArray( module, jobs[j].dependencies ) !== -1 ) {
524 if ( typeof jobs[j].error === 'function' ) {
525 jobs[j].error();
526 }
527 jobs.splice( j, 1 );
528 j--;
529 }
530 }
531 }
532 }
533
534 /**
535 * Adds a dependencies to the queue with optional callbacks to be run
536 * when the dependencies are ready or fail
537 *
538 * @param mixed string moulde name or array of string module names
539 * @param function ready callback to execute when all dependencies are ready
540 * @param function error callback to execute when any dependency fails
541 */
542 function request( dependencies, ready, error ) {
543 // Allow calling by single module name
544 if ( typeof dependencies === 'string' ) {
545 dependencies = [dependencies];
546 if ( dependencies[0] in registry ) {
547 for ( var n = 0; n < registry[dependencies[0]].dependencies.length; n++ ) {
548 dependencies[dependencies.length] =
549 registry[dependencies[0]].dependencies[n];
550 }
551 }
552 }
553 // Add ready and error callbacks if they were given
554 if ( arguments.length > 1 ) {
555 jobs[jobs.length] = {
556 'dependencies': filter(
557 ['undefined', 'registered', 'loading', 'loaded'],
558 dependencies ),
559 'ready': ready,
560 'error': error
561 };
562 }
563 // Queue up any dependencies that are undefined or registered
564 dependencies = filter( ['undefined', 'registered'], dependencies );
565 for ( var n = 0; n < dependencies.length; n++ ) {
566 if ( $.inArray( dependencies[n], queue ) === -1 ) {
567 queue[queue.length] = dependencies[n];
568 }
569 }
570 // Work the queue
571 mediaWiki.loader.work();
572 }
573
574 function sortQuery(o) {
575 var sorted = {}, key, a = [];
576 for ( key in o ) {
577 if ( o.hasOwnProperty( key ) ) {
578 a.push( key );
579 }
580 }
581 a.sort();
582 for ( key = 0; key < a.length; key++ ) {
583 sorted[a[key]] = o[a[key]];
584 }
585 return sorted;
586 }
587
588 /* Public Methods */
589
590 /**
591 * Requests dependencies from server, loading and executing when things when ready.
592 */
593 this.work = function() {
594 // Appends a list of modules to the batch
595 for ( var q = 0; q < queue.length; q++ ) {
596 // Only request modules which are undefined or registered
597 if ( !( queue[q] in registry ) || registry[queue[q]].state == 'registered' ) {
598 // Prevent duplicate entries
599 if ( $.inArray( queue[q], batch ) === -1 ) {
600 batch[batch.length] = queue[q];
601 // Mark registered modules as loading
602 if ( queue[q] in registry ) {
603 registry[queue[q]].state = 'loading';
604 }
605 }
606 }
607 }
608 // Clean up the queue
609 queue = [];
610 // After document ready, handle the batch
611 if ( !suspended && batch.length ) {
612 // Always order modules alphabetically to help reduce cache
613 // misses for otherwise identical content
614 batch.sort();
615 // Build a list of request parameters
616 var base = {
617 'skin': mediaWiki.config.get( 'skin' ),
618 'lang': mediaWiki.config.get( 'wgUserLanguage' ),
619 'debug': mediaWiki.config.get( 'debug' )
620 };
621 // Extend request parameters with a list of modules in the batch
622 var requests = [];
623 // Split into groups
624 var groups = {};
625 for ( var b = 0; b < batch.length; b++ ) {
626 var group = registry[batch[b]].group;
627 if ( !( group in groups ) ) {
628 groups[group] = [];
629 }
630 groups[group][groups[group].length] = batch[b];
631 }
632 for ( var group in groups ) {
633 // Calculate the highest timestamp
634 var version = 0;
635 for ( var g = 0; g < groups[group].length; g++ ) {
636 if ( registry[groups[group][g]].version > version ) {
637 version = registry[groups[group][g]].version;
638 }
639 }
640 requests[requests.length] = $.extend(
641 { 'modules': groups[group].join( '|' ), 'version': formatVersionNumber( version ) }, base
642 );
643 }
644 // Clear the batch - this MUST happen before we append the
645 // script element to the body or it's possible that the script
646 // will be locally cached, instantly load, and work the batch
647 // again, all before we've cleared it causing each request to
648 // include modules which are already loaded
649 batch = [];
650 // Asynchronously append a script tag to the end of the body
651 function request() {
652 var html = '';
653 for ( var r = 0; r < requests.length; r++ ) {
654 requests[r] = sortQuery( requests[r] );
655 // Build out the HTML
656 var src = mediaWiki.config.get( 'wgLoadScript' ) + '?' + $.param( requests[r] );
657 html += '<script type="text/javascript" src="' + src + '"></script>';
658 }
659 return html;
660 }
661 // Load asynchronously after doumument ready
662 if ( ready ) {
663 setTimeout( function() { $( 'body' ).append( request() ); }, 0 )
664 } else {
665 document.write( request() );
666 }
667 }
668 };
669
670 /**
671 * Registers a module, letting the system know about it and its
672 * dependencies. loader.js files contain calls to this function.
673 */
674 this.register = function( module, version, dependencies, group ) {
675 // Allow multiple registration
676 if ( typeof module === 'object' ) {
677 for ( var m = 0; m < module.length; m++ ) {
678 if ( typeof module[m] === 'string' ) {
679 mediaWiki.loader.register( module[m] );
680 } else if ( typeof module[m] === 'object' ) {
681 mediaWiki.loader.register.apply( mediaWiki.loader, module[m] );
682 }
683 }
684 return;
685 }
686 // Validate input
687 if ( typeof module !== 'string' ) {
688 throw new Error( 'module must be a string, not a ' + typeof module );
689 }
690 if ( typeof registry[module] !== 'undefined' ) {
691 throw new Error( 'module already implemeneted: ' + module );
692 }
693 // List the module as registered
694 registry[module] = {
695 'state': 'registered',
696 'group': typeof group === 'string' ? group : null,
697 'dependencies': [],
698 'version': typeof version !== 'undefined' ? parseInt( version ) : 0
699 };
700 if ( typeof dependencies === 'string' ) {
701 // Allow dependencies to be given as a single module name
702 registry[module].dependencies = [dependencies];
703 } else if ( typeof dependencies === 'object' || typeof dependencies === 'function' ) {
704 // Allow dependencies to be given as an array of module names
705 // or a function which returns an array
706 registry[module].dependencies = dependencies;
707 }
708 };
709
710 /**
711 * Implements a module, giving the system a course of action to take
712 * upon loading. Results of a request for one or more modules contain
713 * calls to this function.
714 */
715 this.implement = function( module, script, style, localization ) {
716 // Automaically register module
717 if ( typeof registry[module] === 'undefined' ) {
718 mediaWiki.loader.register( module );
719 }
720 // Validate input
721 if ( typeof script !== 'function' ) {
722 throw new Error( 'script must be a function, not a ' + typeof script );
723 }
724 if ( typeof style !== 'undefined'
725 && typeof style !== 'string'
726 && typeof style !== 'object' )
727 {
728 throw new Error( 'style must be a string or object, not a ' + typeof style );
729 }
730 if ( typeof localization !== 'undefined'
731 && typeof localization !== 'object' )
732 {
733 throw new Error( 'localization must be an object, not a ' + typeof localization );
734 }
735 if ( typeof registry[module] !== 'undefined'
736 && typeof registry[module].script !== 'undefined' )
737 {
738 throw new Error( 'module already implemeneted: ' + module );
739 }
740 // Mark module as loaded
741 registry[module].state = 'loaded';
742 // Attach components
743 registry[module].script = script;
744 if ( typeof style === 'string'
745 || typeof style === 'object' && !( style instanceof Array ) )
746 {
747 registry[module].style = style;
748 }
749 if ( typeof localization === 'object' ) {
750 registry[module].messages = localization;
751 }
752 // Execute or queue callback
753 if ( compare(
754 filter( ['ready'], registry[module].dependencies ),
755 registry[module].dependencies ) )
756 {
757 execute( module );
758 } else {
759 request( module );
760 }
761 };
762
763 /**
764 * Executes a function as soon as one or more required modules are ready
765 *
766 * @param mixed string or array of strings of modules names the callback
767 * dependencies to be ready before
768 * executing
769 * @param function callback to execute when all dependencies are ready (optional)
770 * @param function callback to execute when if dependencies have a errors (optional)
771 */
772 this.using = function( dependencies, ready, error ) {
773 // Validate input
774 if ( typeof dependencies !== 'object' && typeof dependencies !== 'string' ) {
775 throw new Error( 'dependencies must be a string or an array, not a ' +
776 typeof dependencies )
777 }
778 // Allow calling with a single dependency as a string
779 if ( typeof dependencies === 'string' ) {
780 dependencies = [dependencies];
781 }
782 // Resolve entire dependency map
783 dependencies = resolve( dependencies );
784 // If all dependencies are met, execute ready immediately
785 if ( compare( filter( ['ready'], dependencies ), dependencies ) ) {
786 if ( typeof ready === 'function' ) {
787 ready();
788 }
789 }
790 // If any dependencies have errors execute error immediately
791 else if ( filter( ['error'], dependencies ).length ) {
792 if ( typeof error === 'function' ) {
793 error();
794 }
795 }
796 // Since some dependencies are not yet ready, queue up a request
797 else {
798 request( dependencies, ready, error );
799 }
800 };
801
802 /**
803 * Loads an external script or one or more modules for future use
804 *
805 * @param {mixed} modules either the name of a module, array of modules,
806 * or a URL of an external script or style
807 * @param {string} type mime-type to use if calling with a URL of an
808 * external script or style; acceptable values are "text/css" and
809 * "text/javascript"; if no type is provided, text/javascript is
810 * assumed
811 */
812 this.load = function( modules, type ) {
813 // Validate input
814 if ( typeof modules !== 'object' && typeof modules !== 'string' ) {
815 throw new Error( 'dependencies must be a string or an array, not a ' +
816 typeof dependencies )
817 }
818 // Allow calling with an external script or single dependency as a string
819 if ( typeof modules === 'string' ) {
820 // Support adding arbitrary external scripts
821 if ( modules.substr( 0, 7 ) == 'http://'
822 || modules.substr( 0, 8 ) == 'https://' )
823 {
824 if ( type === 'text/css' ) {
825 $( 'head' )
826 .append( $( '<link rel="stylesheet" type="text/css" />' )
827 .attr( 'href', modules ) );
828 return true;
829 } else if ( type === 'text/javascript' || typeof type === 'undefined' ) {
830 var script = '<script type="text/javascript" src="' + modules + '"></script>';
831 if ( ready ) {
832 $( 'body' ).append( script );
833 } else {
834 document.write( script );
835 }
836 return true;
837 }
838 // Unknown type
839 return false;
840 }
841 // Called with single module
842 modules = [modules];
843 }
844 // Resolve entire dependency map
845 modules = resolve( modules );
846 // If all modules are ready, nothing dependency be done
847 if ( compare( filter( ['ready'], modules ), modules ) ) {
848 return true;
849 }
850 // If any modules have errors return false
851 else if ( filter( ['error'], modules ).length ) {
852 return false;
853 }
854 // Since some modules are not yet ready, queue up a request
855 else {
856 request( modules );
857 return true;
858 }
859 };
860
861 /**
862 * Flushes the request queue and begin executing load requests on demand
863 */
864 this.go = function() {
865 suspended = false;
866 mediaWiki.loader.work();
867 };
868
869 /**
870 * Changes the state of a module
871 *
872 * @param mixed module string module name or object of module name/state pairs
873 * @param string state string state name
874 */
875 this.state = function( module, state ) {
876 if ( typeof module === 'object' ) {
877 for ( var m in module ) {
878 mediaWiki.loader.state( m, module[m] );
879 }
880 return;
881 }
882 if ( !( module in registry ) ) {
883 mediaWiki.loader.register( module );
884 }
885 registry[module].state = state;
886 };
887
888 /**
889 * Gets the version of a module
890 *
891 * @param string module name of module to get version for
892 */
893 this.version = function( module ) {
894 if ( module in registry && 'version' in registry[module] ) {
895 return formatVersionNumber( registry[module].version );
896 }
897 return null;
898 }
899
900 /* Cache document ready status */
901
902 $(document).ready( function() { ready = true; } );
903 } )();
904
905 /* Extension points */
906
907 this.legacy = {};
908
909 } )( jQuery );
910
911 /* Auto-register from pre-loaded startup scripts */
912
913 if ( typeof startUp === 'function' ) {
914 startUp();
915 delete startUp;
916 }
917
918 // Alias $j to jQuery for backwards compatibility
919 window.$j = jQuery;
920 window.mw = mediaWiki;