Merge branch 'MDL-58454-master' of git://github.com/junpataleta/moodle
[moodle.git] / lib / javascript-static.js
bloba4296ee3aca9a51693371947a0c25cdfe8bb356b
1 // Miscellaneous core Javascript functions for Moodle
2 // Global M object is initilised in inline javascript
4 /**
5  * Add module to list of available modules that can be loaded from YUI.
6  * @param {Array} modules
7  */
8 M.yui.add_module = function(modules) {
9     for (var modname in modules) {
10         YUI_config.modules[modname] = modules[modname];
11     }
12     // Ensure thaat the YUI_config is applied to the main YUI instance.
13     Y.applyConfig(YUI_config);
15 /**
16  * The gallery version to use when loading YUI modules from the gallery.
17  * Will be changed every time when using local galleries.
18  */
19 M.yui.galleryversion = '2010.04.21-21-51';
21 /**
22  * Various utility functions
23  */
24 M.util = M.util || {};
26 /**
27  * Language strings - initialised from page footer.
28  */
29 M.str = M.str || {};
31 /**
32  * Returns url for images.
33  * @param {String} imagename
34  * @param {String} component
35  * @return {String}
36  */
37 M.util.image_url = function(imagename, component) {
39     if (!component || component == '' || component == 'moodle' || component == 'core') {
40         component = 'core';
41     }
43     var url = M.cfg.wwwroot + '/theme/image.php';
44     if (M.cfg.themerev > 0 && M.cfg.slasharguments == 1) {
45         if (!M.cfg.svgicons) {
46             url += '/_s';
47         }
48         url += '/' + M.cfg.theme + '/' + component + '/' + M.cfg.themerev + '/' + imagename;
49     } else {
50         url += '?theme=' + M.cfg.theme + '&component=' + component + '&rev=' + M.cfg.themerev + '&image=' + imagename;
51         if (!M.cfg.svgicons) {
52             url += '&svg=0';
53         }
54     }
56     return url;
59 M.util.in_array = function(item, array){
60     for( var i = 0; i<array.length; i++){
61         if(item==array[i]){
62             return true;
63         }
64     }
65     return false;
68 /**
69  * Init a collapsible region, see print_collapsible_region in weblib.php
70  * @param {YUI} Y YUI3 instance with all libraries loaded
71  * @param {String} id the HTML id for the div.
72  * @param {String} userpref the user preference that records the state of this box. false if none.
73  * @param {String} strtooltip
74  */
75 M.util.init_collapsible_region = function(Y, id, userpref, strtooltip) {
76     Y.use('anim', function(Y) {
77         new M.util.CollapsibleRegion(Y, id, userpref, strtooltip);
78     });
81 /**
82  * Object to handle a collapsible region : instantiate and forget styled object
83  *
84  * @class
85  * @constructor
86  * @param {YUI} Y YUI3 instance with all libraries loaded
87  * @param {String} id The HTML id for the div.
88  * @param {String} userpref The user preference that records the state of this box. false if none.
89  * @param {String} strtooltip
90  */
91 M.util.CollapsibleRegion = function(Y, id, userpref, strtooltip) {
92     // Record the pref name
93     this.userpref = userpref;
95     // Find the divs in the document.
96     this.div = Y.one('#'+id);
98     // Get the caption for the collapsible region
99     var caption = this.div.one('#'+id + '_caption');
101     // Create a link
102     var a = Y.Node.create('<a href="#"></a>');
103     a.setAttribute('title', strtooltip);
105     // Get all the nodes from caption, remove them and append them to <a>
106     while (caption.hasChildNodes()) {
107         child = caption.get('firstChild');
108         child.remove();
109         a.append(child);
110     }
111     caption.append(a);
113     // Get the height of the div at this point before we shrink it if required
114     var height = this.div.get('offsetHeight');
115     var collapsedimage = 't/collapsed'; // ltr mode
116     if (right_to_left()) {
117         collapsedimage = 't/collapsed_rtl';
118     } else {
119         collapsedimage = 't/collapsed';
120     }
121     if (this.div.hasClass('collapsed')) {
122         // Add the correct image and record the YUI node created in the process
123         this.icon = Y.Node.create('<img src="'+M.util.image_url(collapsedimage, 'moodle')+'" alt="" />');
124         // Shrink the div as it is collapsed by default
125         this.div.setStyle('height', caption.get('offsetHeight')+'px');
126     } else {
127         // Add the correct image and record the YUI node created in the process
128         this.icon = Y.Node.create('<img src="'+M.util.image_url('t/expanded', 'moodle')+'" alt="" />');
129     }
130     a.append(this.icon);
132     // Create the animation.
133     var animation = new Y.Anim({
134         node: this.div,
135         duration: 0.3,
136         easing: Y.Easing.easeBoth,
137         to: {height:caption.get('offsetHeight')},
138         from: {height:height}
139     });
141     // Handler for the animation finishing.
142     animation.on('end', function() {
143         this.div.toggleClass('collapsed');
144         var collapsedimage = 't/collapsed'; // ltr mode
145         if (right_to_left()) {
146             collapsedimage = 't/collapsed_rtl';
147             } else {
148             collapsedimage = 't/collapsed';
149             }
150         if (this.div.hasClass('collapsed')) {
151             this.icon.set('src', M.util.image_url(collapsedimage, 'moodle'));
152         } else {
153             this.icon.set('src', M.util.image_url('t/expanded', 'moodle'));
154         }
155     }, this);
157     // Hook up the event handler.
158     a.on('click', function(e, animation) {
159         e.preventDefault();
160         // Animate to the appropriate size.
161         if (animation.get('running')) {
162             animation.stop();
163         }
164         animation.set('reverse', this.div.hasClass('collapsed'));
165         // Update the user preference.
166         if (this.userpref) {
167             M.util.set_user_preference(this.userpref, !this.div.hasClass('collapsed'));
168         }
169         animation.run();
170     }, this, animation);
174  * The user preference that stores the state of this box.
175  * @property userpref
176  * @type String
177  */
178 M.util.CollapsibleRegion.prototype.userpref = null;
181  * The key divs that make up this
182  * @property div
183  * @type Y.Node
184  */
185 M.util.CollapsibleRegion.prototype.div = null;
188  * The key divs that make up this
189  * @property icon
190  * @type Y.Node
191  */
192 M.util.CollapsibleRegion.prototype.icon = null;
195  * Makes a best effort to connect back to Moodle to update a user preference,
196  * however, there is no mechanism for finding out if the update succeeded.
198  * Before you can use this function in your JavsScript, you must have called
199  * user_preference_allow_ajax_update from moodlelib.php to tell Moodle that
200  * the udpate is allowed, and how to safely clean and submitted values.
202  * @param String name the name of the setting to udpate.
203  * @param String the value to set it to.
204  */
205 M.util.set_user_preference = function(name, value) {
206     YUI().use('io', function(Y) {
207         var url = M.cfg.wwwroot + '/lib/ajax/setuserpref.php?sesskey=' +
208                 M.cfg.sesskey + '&pref=' + encodeURI(name) + '&value=' + encodeURI(value);
210         // If we are a developer, ensure that failures are reported.
211         var cfg = {
212                 method: 'get',
213                 on: {}
214             };
215         if (M.cfg.developerdebug) {
216             cfg.on.failure = function(id, o, args) {
217                 alert("Error updating user preference '" + name + "' using ajax. Clicking this link will repeat the Ajax call that failed so you can see the error: ");
218             }
219         }
221         // Make the request.
222         Y.io(url, cfg);
223     });
227  * Prints a confirmation dialog in the style of DOM.confirm().
229  * @method show_confirm_dialog
230  * @param {EventFacade} e
231  * @param {Object} args
232  * @param {String} args.message The question to ask the user
233  * @param {Function} [args.callback] A callback to apply on confirmation.
234  * @param {Object} [args.scope] The scope to use when calling the callback.
235  * @param {Object} [args.callbackargs] Any arguments to pass to the callback.
236  * @param {String} [args.cancellabel] The label to use on the cancel button.
237  * @param {String} [args.continuelabel] The label to use on the continue button.
238  */
239 M.util.show_confirm_dialog = function(e, args) {
240     var target = e.target;
241     if (e.preventDefault) {
242         e.preventDefault();
243     }
245     YUI().use('moodle-core-notification-confirm', function(Y) {
246         var confirmationDialogue = new M.core.confirm({
247             width: '300px',
248             center: true,
249             modal: true,
250             visible: false,
251             draggable: false,
252             title: M.util.get_string('confirmation', 'admin'),
253             noLabel: M.util.get_string('cancel', 'moodle'),
254             question: args.message
255         });
257         // The dialogue was submitted with a positive value indication.
258         confirmationDialogue.on('complete-yes', function(e) {
259             // Handle any callbacks.
260             if (args.callback) {
261                 if (!Y.Lang.isFunction(args.callback)) {
262                     Y.log('Callbacks to show_confirm_dialog must now be functions. Please update your code to pass in a function instead.',
263                             'warn', 'M.util.show_confirm_dialog');
264                     return;
265                 }
267                 var scope = e.target;
268                 if (Y.Lang.isObject(args.scope)) {
269                     scope = args.scope;
270                 }
272                 var callbackargs = args.callbackargs || [];
273                 args.callback.apply(scope, callbackargs);
274                 return;
275             }
277             var targetancestor = null,
278                 targetform = null;
280             if (target.test('a')) {
281                 window.location = target.get('href');
283             } else if ((targetancestor = target.ancestor('a')) !== null) {
284                 window.location = targetancestor.get('href');
286             } else if (target.test('input') || target.test('button')) {
287                 targetform = target.ancestor('form', true);
288                 if (!targetform) {
289                     return;
290                 }
291                 if (target.get('name') && target.get('value')) {
292                     targetform.append('<input type="hidden" name="' + target.get('name') +
293                                     '" value="' + target.get('value') + '">');
294                     if (typeof M.core_formchangechecker !== 'undefined') {
295                         M.core_formchangechecker.set_form_submitted();
296                     }
297                 }
298                 targetform.submit();
300             } else if (target.test('form')) {
301                 if (typeof M.core_formchangechecker !== 'undefined') {
302                     M.core_formchangechecker.set_form_submitted();
303                 }
304                 target.submit();
306             } else {
307                 Y.log("Element of type " + target.get('tagName') +
308                         " is not supported by the M.util.show_confirm_dialog function. Use A, INPUT, BUTTON or FORM",
309                         'warn', 'javascript-static');
310             }
311         }, this);
313         if (args.cancellabel) {
314             confirmationDialogue.set('noLabel', args.cancellabel);
315         }
317         if (args.continuelabel) {
318             confirmationDialogue.set('yesLabel', args.continuelabel);
319         }
321         confirmationDialogue.render()
322                 .show();
323     });
326 /** Useful for full embedding of various stuff */
327 M.util.init_maximised_embed = function(Y, id) {
328     var obj = Y.one('#'+id);
329     if (!obj) {
330         return;
331     }
333     var get_htmlelement_size = function(el, prop) {
334         if (Y.Lang.isString(el)) {
335             el = Y.one('#' + el);
336         }
337         // Ensure element exists.
338         if (el) {
339             var val = el.getStyle(prop);
340             if (val == 'auto') {
341                 val = el.getComputedStyle(prop);
342             }
343             val = parseInt(val);
344             if (isNaN(val)) {
345                 return 0;
346             }
347             return val;
348         } else {
349             return 0;
350         }
351     };
353     var resize_object = function() {
354         obj.setStyle('display', 'none');
355         var newwidth = get_htmlelement_size('maincontent', 'width') - 35;
357         if (newwidth > 500) {
358             obj.setStyle('width', newwidth  + 'px');
359         } else {
360             obj.setStyle('width', '500px');
361         }
363         var headerheight = get_htmlelement_size('page-header', 'height');
364         var footerheight = get_htmlelement_size('page-footer', 'height');
365         var newheight = parseInt(Y.one('body').get('docHeight')) - footerheight - headerheight - 100;
366         if (newheight < 400) {
367             newheight = 400;
368         }
369         obj.setStyle('height', newheight+'px');
370         obj.setStyle('display', '');
371     };
373     resize_object();
374     // fix layout if window resized too
375     Y.use('event-resize', function (Y) {
376         Y.on("windowresize", function() {
377             resize_object();
378         });
379     });
383  * Breaks out all links to the top frame - used in frametop page layout.
384  */
385 M.util.init_frametop = function(Y) {
386     Y.all('a').each(function(node) {
387         node.set('target', '_top');
388     });
389     Y.all('form').each(function(node) {
390         node.set('target', '_top');
391     });
395  * @deprecated since Moodle 3.3
396  */
397 M.util.init_toggle_class_on_click = function(Y, id, cssselector, toggleclassname, togglecssselector) {
398     throw new Error('M.util.init_toggle_class_on_click can not be used any more. Please use jQuery instead.');
402  * Initialises a colour picker
404  * Designed to be used with admin_setting_configcolourpicker although could be used
405  * anywhere, just give a text input an id and insert a div with the class admin_colourpicker
406  * above or below the input (must have the same parent) and then call this with the
407  * id.
409  * This code was mostly taken from my [Sam Hemelryk] css theme tool available in
410  * contrib/blocks. For better docs refer to that.
412  * @param {YUI} Y
413  * @param {int} id
414  * @param {object} previewconf
415  */
416 M.util.init_colour_picker = function(Y, id, previewconf) {
417     /**
418      * We need node and event-mouseenter
419      */
420     Y.use('node', 'event-mouseenter', function(){
421         /**
422          * The colour picker object
423          */
424         var colourpicker = {
425             box : null,
426             input : null,
427             image : null,
428             preview : null,
429             current : null,
430             eventClick : null,
431             eventMouseEnter : null,
432             eventMouseLeave : null,
433             eventMouseMove : null,
434             width : 300,
435             height :  100,
436             factor : 5,
437             /**
438              * Initalises the colour picker by putting everything together and wiring the events
439              */
440             init : function() {
441                 this.input = Y.one('#'+id);
442                 this.box = this.input.ancestor().one('.admin_colourpicker');
443                 this.image = Y.Node.create('<img alt="" class="colourdialogue" />');
444                 this.image.setAttribute('src', M.util.image_url('i/colourpicker', 'moodle'));
445                 this.preview = Y.Node.create('<div class="previewcolour"></div>');
446                 this.preview.setStyle('width', this.height/2).setStyle('height', this.height/2).setStyle('backgroundColor', this.input.get('value'));
447                 this.current = Y.Node.create('<div class="currentcolour"></div>');
448                 this.current.setStyle('width', this.height/2).setStyle('height', this.height/2 -1).setStyle('backgroundColor', this.input.get('value'));
449                 this.box.setContent('').append(this.image).append(this.preview).append(this.current);
451                 if (typeof(previewconf) === 'object' && previewconf !== null) {
452                     Y.one('#'+id+'_preview').on('click', function(e){
453                         if (Y.Lang.isString(previewconf.selector)) {
454                             Y.all(previewconf.selector).setStyle(previewconf.style, this.input.get('value'));
455                         } else {
456                             for (var i in previewconf.selector) {
457                                 Y.all(previewconf.selector[i]).setStyle(previewconf.style, this.input.get('value'));
458                             }
459                         }
460                     }, this);
461                 }
463                 this.eventClick = this.image.on('click', this.pickColour, this);
464                 this.eventMouseEnter = Y.on('mouseenter', this.startFollow, this.image, this);
465             },
466             /**
467              * Starts to follow the mouse once it enter the image
468              */
469             startFollow : function(e) {
470                 this.eventMouseEnter.detach();
471                 this.eventMouseLeave = Y.on('mouseleave', this.endFollow, this.image, this);
472                 this.eventMouseMove = this.image.on('mousemove', function(e){
473                     this.preview.setStyle('backgroundColor', this.determineColour(e));
474                 }, this);
475             },
476             /**
477              * Stops following the mouse
478              */
479             endFollow : function(e) {
480                 this.eventMouseMove.detach();
481                 this.eventMouseLeave.detach();
482                 this.eventMouseEnter = Y.on('mouseenter', this.startFollow, this.image, this);
483             },
484             /**
485              * Picks the colour the was clicked on
486              */
487             pickColour : function(e) {
488                 var colour = this.determineColour(e);
489                 this.input.set('value', colour);
490                 this.current.setStyle('backgroundColor', colour);
491             },
492             /**
493              * Calculates the colour fromthe given co-ordinates
494              */
495             determineColour : function(e) {
496                 var eventx = Math.floor(e.pageX-e.target.getX());
497                 var eventy = Math.floor(e.pageY-e.target.getY());
499                 var imagewidth = this.width;
500                 var imageheight = this.height;
501                 var factor = this.factor;
502                 var colour = [255,0,0];
504                 var matrices = [
505                     [  0,  1,  0],
506                     [ -1,  0,  0],
507                     [  0,  0,  1],
508                     [  0, -1,  0],
509                     [  1,  0,  0],
510                     [  0,  0, -1]
511                 ];
513                 var matrixcount = matrices.length;
514                 var limit = Math.round(imagewidth/matrixcount);
515                 var heightbreak = Math.round(imageheight/2);
517                 for (var x = 0; x < imagewidth; x++) {
518                     var divisor = Math.floor(x / limit);
519                     var matrix = matrices[divisor];
521                     colour[0] += matrix[0]*factor;
522                     colour[1] += matrix[1]*factor;
523                     colour[2] += matrix[2]*factor;
525                     if (eventx==x) {
526                         break;
527                     }
528                 }
530                 var pixel = [colour[0], colour[1], colour[2]];
531                 if (eventy < heightbreak) {
532                     pixel[0] += Math.floor(((255-pixel[0])/heightbreak) * (heightbreak - eventy));
533                     pixel[1] += Math.floor(((255-pixel[1])/heightbreak) * (heightbreak - eventy));
534                     pixel[2] += Math.floor(((255-pixel[2])/heightbreak) * (heightbreak - eventy));
535                 } else if (eventy > heightbreak) {
536                     pixel[0] = Math.floor((imageheight-eventy)*(pixel[0]/heightbreak));
537                     pixel[1] = Math.floor((imageheight-eventy)*(pixel[1]/heightbreak));
538                     pixel[2] = Math.floor((imageheight-eventy)*(pixel[2]/heightbreak));
539                 }
541                 return this.convert_rgb_to_hex(pixel);
542             },
543             /**
544              * Converts an RGB value to Hex
545              */
546             convert_rgb_to_hex : function(rgb) {
547                 var hex = '#';
548                 var hexchars = "0123456789ABCDEF";
549                 for (var i=0; i<3; i++) {
550                     var number = Math.abs(rgb[i]);
551                     if (number == 0 || isNaN(number)) {
552                         hex += '00';
553                     } else {
554                         hex += hexchars.charAt((number-number%16)/16)+hexchars.charAt(number%16);
555                     }
556                 }
557                 return hex;
558             }
559         };
560         /**
561          * Initialise the colour picker :) Hoorah
562          */
563         colourpicker.init();
564     });
567 M.util.init_block_hider = function(Y, config) {
568     Y.use('base', 'node', function(Y) {
569         M.util.block_hider = M.util.block_hider || (function(){
570             var blockhider = function() {
571                 blockhider.superclass.constructor.apply(this, arguments);
572             };
573             blockhider.prototype = {
574                 initializer : function(config) {
575                     this.set('block', '#'+this.get('id'));
576                     var b = this.get('block'),
577                         t = b.one('.title'),
578                         a = null,
579                         hide,
580                         show;
581                     if (t && (a = t.one('.block_action'))) {
582                         hide = Y.Node.create('<img />')
583                             .addClass('block-hider-hide')
584                             .setAttrs({
585                                 alt:        config.tooltipVisible,
586                                 src:        this.get('iconVisible'),
587                                 tabIndex:   0,
588                                 'title':    config.tooltipVisible
589                             });
590                         hide.on('keypress', this.updateStateKey, this, true);
591                         hide.on('click', this.updateState, this, true);
593                         show = Y.Node.create('<img />')
594                             .addClass('block-hider-show')
595                             .setAttrs({
596                                 alt:        config.tooltipHidden,
597                                 src:        this.get('iconHidden'),
598                                 tabIndex:   0,
599                                 'title':    config.tooltipHidden
600                             });
601                         show.on('keypress', this.updateStateKey, this, false);
602                         show.on('click', this.updateState, this, false);
604                         a.insert(show, 0).insert(hide, 0);
605                     }
606                 },
607                 updateState : function(e, hide) {
608                     M.util.set_user_preference(this.get('preference'), hide);
609                     if (hide) {
610                         this.get('block').addClass('hidden');
611                         this.get('block').one('.block-hider-show').focus();
612                     } else {
613                         this.get('block').removeClass('hidden');
614                         this.get('block').one('.block-hider-hide').focus();
615                     }
616                 },
617                 updateStateKey : function(e, hide) {
618                     if (e.keyCode == 13) { //allow hide/show via enter key
619                         this.updateState(this, hide);
620                     }
621                 }
622             };
623             Y.extend(blockhider, Y.Base, blockhider.prototype, {
624                 NAME : 'blockhider',
625                 ATTRS : {
626                     id : {},
627                     preference : {},
628                     iconVisible : {
629                         value : M.util.image_url('t/switch_minus', 'moodle')
630                     },
631                     iconHidden : {
632                         value : M.util.image_url('t/switch_plus', 'moodle')
633                     },
634                     block : {
635                         setter : function(node) {
636                             return Y.one(node);
637                         }
638                     }
639                 }
640             });
641             return blockhider;
642         })();
643         new M.util.block_hider(config);
644     });
648  * @var pending_js - The keys are the list of all pending js actions.
649  * @type Object
650  */
651 M.util.pending_js = [];
652 M.util.complete_js = [];
655  * Register any long running javascript code with a unique identifier.
656  * This is used to ensure that Behat steps do not continue with interactions until the page finishes loading.
658  * All calls to M.util.js_pending _must_ be followed by a subsequent call to M.util.js_complete with the same exact
659  * uniqid.
661  * This function may also be called with no arguments to test if there is any js calls pending.
663  * The uniqid specified may be any Object, including Number, String, or actual Object; however please note that the
664  * paired js_complete function performs a strict search for the key specified. As such, if using an Object, the exact
665  * Object must be passed into both functions.
667  * @param   {Mixed}     uniqid Register long-running code against the supplied identifier
668  * @return  {Number}    Number of pending items
669  */
670 M.util.js_pending = function(uniqid) {
671     if (typeof uniqid !== 'undefined') {
672         M.util.pending_js.push(uniqid);
673     }
675     return M.util.pending_js.length;
678 // Start this asap.
679 M.util.js_pending('init');
682  * Register listeners for Y.io start/end so we can wait for them in behat.
683  */
684 YUI.add('moodle-core-io', function(Y) {
685     Y.on('io:start', function(id) {
686         M.util.js_pending('io:' + id);
687     });
688     Y.on('io:end', function(id) {
689         M.util.js_complete('io:' + id);
690     });
691 }, '@VERSION@', {
692     condition: {
693         trigger: 'io-base',
694         when: 'after'
695     }
699  * Unregister some long running javascript code using the unique identifier specified in M.util.js_pending.
701  * This function must be matched with an identical call to M.util.js_pending.
703  * @param   {Mixed}     uniqid Register long-running code against the supplied identifier
704  * @return  {Number}    Number of pending items remaining after removing this item
705  */
706 M.util.js_complete = function(uniqid) {
707     // Use the Y.Array.indexOf instead of the native because some older browsers do not support
708     // the native function. Y.Array polyfills the native function if it does not exist.
709     var index = Y.Array.indexOf(M.util.pending_js, uniqid);
710     if (index >= 0) {
711         M.util.complete_js.push(M.util.pending_js.splice(index, 1));
712     } else {
713         window.console.log("Unable to locate key for js_complete call", uniqid);
714     }
716     return M.util.pending_js.length;
720  * Returns a string registered in advance for usage in JavaScript
722  * If you do not pass the third parameter, the function will just return
723  * the corresponding value from the M.str object. If the third parameter is
724  * provided, the function performs {$a} placeholder substitution in the
725  * same way as PHP get_string() in Moodle does.
727  * @param {String} identifier string identifier
728  * @param {String} component the component providing the string
729  * @param {Object|String} a optional variable to populate placeholder with
730  */
731 M.util.get_string = function(identifier, component, a) {
732     var stringvalue;
734     if (M.cfg.developerdebug) {
735         // creating new instance if YUI is not optimal but it seems to be better way then
736         // require the instance via the function API - note that it is used in rare cases
737         // for debugging only anyway
738         // To ensure we don't kill browser performance if hundreds of get_string requests
739         // are made we cache the instance we generate within the M.util namespace.
740         // We don't publicly define the variable so that it doesn't get abused.
741         if (typeof M.util.get_string_yui_instance === 'undefined') {
742             M.util.get_string_yui_instance = new YUI({ debug : true });
743         }
744         var Y = M.util.get_string_yui_instance;
745     }
747     if (!M.str.hasOwnProperty(component) || !M.str[component].hasOwnProperty(identifier)) {
748         stringvalue = '[[' + identifier + ',' + component + ']]';
749         if (M.cfg.developerdebug) {
750             Y.log('undefined string ' + stringvalue, 'warn', 'M.util.get_string');
751         }
752         return stringvalue;
753     }
755     stringvalue = M.str[component][identifier];
757     if (typeof a == 'undefined') {
758         // no placeholder substitution requested
759         return stringvalue;
760     }
762     if (typeof a == 'number' || typeof a == 'string') {
763         // replace all occurrences of {$a} with the placeholder value
764         stringvalue = stringvalue.replace(/\{\$a\}/g, a);
765         return stringvalue;
766     }
768     if (typeof a == 'object') {
769         // replace {$a->key} placeholders
770         for (var key in a) {
771             if (typeof a[key] != 'number' && typeof a[key] != 'string') {
772                 if (M.cfg.developerdebug) {
773                     Y.log('invalid value type for $a->' + key, 'warn', 'M.util.get_string');
774                 }
775                 continue;
776             }
777             var search = '{$a->' + key + '}';
778             search = search.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
779             search = new RegExp(search, 'g');
780             stringvalue = stringvalue.replace(search, a[key]);
781         }
782         return stringvalue;
783     }
785     if (M.cfg.developerdebug) {
786         Y.log('incorrect placeholder type', 'warn', 'M.util.get_string');
787     }
788     return stringvalue;
792  * Set focus on username or password field of the login form.
793  * @deprecated since Moodle 3.3.
794  */
795 M.util.focus_login_form = function(Y) {
796     Y.log('M.util.focus_login_form no longer does anything. Please use jquery instead.', 'warn', 'javascript-static.js');
800  * Set focus on login error message.
801  * @deprecated since Moodle 3.3.
802  */
803 M.util.focus_login_error = function(Y) {
804     Y.log('M.util.focus_login_error no longer does anything. Please use jquery instead.', 'warn', 'javascript-static.js');
808  * Adds lightbox hidden element that covers the whole node.
810  * @param {YUI} Y
811  * @param {Node} the node lightbox should be added to
812  * @retun {Node} created lightbox node
813  */
814 M.util.add_lightbox = function(Y, node) {
815     var WAITICON = {'pix':"i/loading_small",'component':'moodle'};
817     // Check if lightbox is already there
818     if (node.one('.lightbox')) {
819         return node.one('.lightbox');
820     }
822     node.setStyle('position', 'relative');
823     var waiticon = Y.Node.create('<img />')
824     .setAttrs({
825         'src' : M.util.image_url(WAITICON.pix, WAITICON.component)
826     })
827     .setStyles({
828         'position' : 'relative',
829         'top' : '50%'
830     });
832     var lightbox = Y.Node.create('<div></div>')
833     .setStyles({
834         'opacity' : '.75',
835         'position' : 'absolute',
836         'width' : '100%',
837         'height' : '100%',
838         'top' : 0,
839         'left' : 0,
840         'backgroundColor' : 'white',
841         'textAlign' : 'center'
842     })
843     .setAttribute('class', 'lightbox')
844     .hide();
846     lightbox.appendChild(waiticon);
847     node.append(lightbox);
848     return lightbox;
852  * Appends a hidden spinner element to the specified node.
854  * @param {YUI} Y
855  * @param {Node} the node the spinner should be added to
856  * @return {Node} created spinner node
857  */
858 M.util.add_spinner = function(Y, node) {
859     var WAITICON = {'pix':"i/loading_small",'component':'moodle'};
861     // Check if spinner is already there
862     if (node.one('.spinner')) {
863         return node.one('.spinner');
864     }
866     var spinner = Y.Node.create('<img />')
867         .setAttribute('src', M.util.image_url(WAITICON.pix, WAITICON.component))
868         .addClass('spinner')
869         .addClass('iconsmall')
870         .hide();
872     node.append(spinner);
873     return spinner;
877  * @deprecated since Moodle 3.3.
878  */
879 function checkall() {
880     throw new Error('checkall can not be used any more. Please use jQuery instead.');
884  * @deprecated since Moodle 3.3.
885  */
886 function checknone() {
887     throw new Error('checknone can not be used any more. Please use jQuery instead.');
891  * @deprecated since Moodle 3.3.
892  */
893 function select_all_in_element_with_id(id, checked) {
894     throw new Error('select_all_in_element_with_id can not be used any more. Please use jQuery instead.');
898  * @deprecated since Moodle 3.3.
899  */
900 function select_all_in(elTagName, elClass, elId) {
901     throw new Error('select_all_in can not be used any more. Please use jQuery instead.');
905  * @deprecated since Moodle 3.3.
906  */
907 function deselect_all_in(elTagName, elClass, elId) {
908     throw new Error('deselect_all_in can not be used any more. Please use jQuery instead.');
912  * @deprecated since Moodle 3.3.
913  */
914 function confirm_if(expr, message) {
915     throw new Error('confirm_if can not be used any more.');
919  * @deprecated since Moodle 3.3.
920  */
921 function findParentNode(el, elName, elClass, elId) {
922     throw new Error('findParentNode can not be used any more. Please use jQuery instead.');
925 function unmaskPassword(id) {
926     var pw = document.getElementById(id);
927     var chb = document.getElementById(id+'unmask');
929     // MDL-30438 - The capability to changing the value of input type is not supported by IE8 or lower.
930     // Replacing existing child with a new one, removed all yui properties for the node.  Therefore, this
931     // functionality won't work in IE8 or lower.
932     // This is a temporary fixed to allow other browsers to function properly.
933     if (Y.UA.ie == 0 || Y.UA.ie >= 9) {
934         if (chb.checked) {
935             pw.type = "text";
936         } else {
937             pw.type = "password";
938         }
939     } else {  //IE Browser version 8 or lower
940         try {
941             // first try IE way - it can not set name attribute later
942             if (chb.checked) {
943               var newpw = document.createElement('<input type="text" autocomplete="off" name="'+pw.name+'">');
944             } else {
945               var newpw = document.createElement('<input type="password" autocomplete="off" name="'+pw.name+'">');
946             }
947             newpw.attributes['class'].nodeValue = pw.attributes['class'].nodeValue;
948         } catch (e) {
949             var newpw = document.createElement('input');
950             newpw.setAttribute('autocomplete', 'off');
951             newpw.setAttribute('name', pw.name);
952             if (chb.checked) {
953               newpw.setAttribute('type', 'text');
954             } else {
955               newpw.setAttribute('type', 'password');
956             }
957             newpw.setAttribute('class', pw.getAttribute('class'));
958         }
959         newpw.id = pw.id;
960         newpw.size = pw.size;
961         newpw.onblur = pw.onblur;
962         newpw.onchange = pw.onchange;
963         newpw.value = pw.value;
964         pw.parentNode.replaceChild(newpw, pw);
965     }
969  * @deprecated since Moodle 3.3.
970  */
971 function filterByParent(elCollection, parentFinder) {
972     throw new Error('filterByParent can not be used any more. Please use jQuery instead.');
976  * @deprecated since Moodle 3.3, but shouldn't be used in earlier versions either.
977  */
978 function fix_column_widths() {
979     Y.log('fix_column_widths() no longer does anything. Please remove it from your code.', 'warn', 'javascript-static.js');
983  * @deprecated since Moodle 3.3, but shouldn't be used in earlier versions either.
984  */
985 function fix_column_width(colName) {
986     Y.log('fix_column_width() no longer does anything. Please remove it from your code.', 'warn', 'javascript-static.js');
991    Insert myValue at current cursor position
992  */
993 function insertAtCursor(myField, myValue) {
994     // IE support
995     if (document.selection) {
996         myField.focus();
997         sel = document.selection.createRange();
998         sel.text = myValue;
999     }
1000     // Mozilla/Netscape support
1001     else if (myField.selectionStart || myField.selectionStart == '0') {
1002         var startPos = myField.selectionStart;
1003         var endPos = myField.selectionEnd;
1004         myField.value = myField.value.substring(0, startPos)
1005             + myValue + myField.value.substring(endPos, myField.value.length);
1006     } else {
1007         myField.value += myValue;
1008     }
1012  * Increment a file name.
1014  * @param string file name.
1015  * @param boolean ignoreextension do not extract the extension prior to appending the
1016  *                                suffix. Useful when incrementing folder names.
1017  * @return string the incremented file name.
1018  */
1019 function increment_filename(filename, ignoreextension) {
1020     var extension = '';
1021     var basename = filename;
1023     // Split the file name into the basename + extension.
1024     if (!ignoreextension) {
1025         var dotpos = filename.lastIndexOf('.');
1026         if (dotpos !== -1) {
1027             basename = filename.substr(0, dotpos);
1028             extension = filename.substr(dotpos, filename.length);
1029         }
1030     }
1032     // Look to see if the name already has (NN) at the end of it.
1033     var number = 0;
1034     var hasnumber = basename.match(/^(.*) \((\d+)\)$/);
1035     if (hasnumber !== null) {
1036         // Note the current number & remove it from the basename.
1037         number = parseInt(hasnumber[2], 10);
1038         basename = hasnumber[1];
1039     }
1041     number++;
1042     var newname = basename + ' (' + number + ')' + extension;
1043     return newname;
1047  * Return whether we are in right to left mode or not.
1049  * @return boolean
1050  */
1051 function right_to_left() {
1052     var body = Y.one('body');
1053     var rtl = false;
1054     if (body && body.hasClass('dir-rtl')) {
1055         rtl = true;
1056     }
1057     return rtl;
1060 function openpopup(event, args) {
1062     if (event) {
1063         if (event.preventDefault) {
1064             event.preventDefault();
1065         } else {
1066             event.returnValue = false;
1067         }
1068     }
1070     // Make sure the name argument is set and valid.
1071     var nameregex = /[^a-z0-9_]/i;
1072     if (typeof args.name !== 'string') {
1073         args.name = '_blank';
1074     } else if (args.name.match(nameregex)) {
1075         // Cleans window name because IE does not support funky ones.
1076         if (M.cfg.developerdebug) {
1077             alert('DEVELOPER NOTICE: Invalid \'name\' passed to openpopup(): ' + args.name);
1078         }
1079         args.name = args.name.replace(nameregex, '_');
1080     }
1082     var fullurl = args.url;
1083     if (!args.url.match(/https?:\/\//)) {
1084         fullurl = M.cfg.wwwroot + args.url;
1085     }
1086     if (args.fullscreen) {
1087         args.options = args.options.
1088                 replace(/top=\d+/, 'top=0').
1089                 replace(/left=\d+/, 'left=0').
1090                 replace(/width=\d+/, 'width=' + screen.availWidth).
1091                 replace(/height=\d+/, 'height=' + screen.availHeight);
1092     }
1093     var windowobj = window.open(fullurl,args.name,args.options);
1094     if (!windowobj) {
1095         return true;
1096     }
1098     if (args.fullscreen) {
1099         // In some browser / OS combinations (E.g. Chrome on Windows), the
1100         // window initially opens slighly too big. The width and heigh options
1101         // seem to control the area inside the browser window, so what with
1102         // scroll-bars, etc. the actual window is bigger than the screen.
1103         // Therefore, we need to fix things up after the window is open.
1104         var hackcount = 100;
1105         var get_size_exactly_right = function() {
1106             windowobj.moveTo(0, 0);
1107             windowobj.resizeTo(screen.availWidth, screen.availHeight);
1109             // Unfortunately, it seems that in Chrome on Ubuntu, if you call
1110             // something like windowobj.resizeTo(1280, 1024) too soon (up to
1111             // about 50ms) after the window is open, then it actually behaves
1112             // as if you called windowobj.resizeTo(0, 0). Therefore, we need to
1113             // check that the resize actually worked, and if not, repeatedly try
1114             // again after a short delay until it works (but with a limit of
1115             // hackcount repeats.
1116             if (hackcount > 0 && (windowobj.innerHeight < 10 || windowobj.innerWidth < 10)) {
1117                 hackcount -= 1;
1118                 setTimeout(get_size_exactly_right, 10);
1119             }
1120         }
1121         setTimeout(get_size_exactly_right, 0);
1122     }
1123     windowobj.focus();
1125     return false;
1128 /** Close the current browser window. */
1129 function close_window(e) {
1130     if (e.preventDefault) {
1131         e.preventDefault();
1132     } else {
1133         e.returnValue = false;
1134     }
1135     window.close();
1139  * Tranfer keyboard focus to the HTML element with the given id, if it exists.
1140  * @param controlid the control id.
1141  */
1142 function focuscontrol(controlid) {
1143     var control = document.getElementById(controlid);
1144     if (control) {
1145         control.focus();
1146     }
1150  * Transfers keyboard focus to an HTML element based on the old style style of focus
1151  * This function should be removed as soon as it is no longer used
1152  */
1153 function old_onload_focus(formid, controlname) {
1154     if (document.forms[formid] && document.forms[formid].elements && document.forms[formid].elements[controlname]) {
1155         document.forms[formid].elements[controlname].focus();
1156     }
1159 function build_querystring(obj) {
1160     return convert_object_to_string(obj, '&');
1163 function build_windowoptionsstring(obj) {
1164     return convert_object_to_string(obj, ',');
1167 function convert_object_to_string(obj, separator) {
1168     if (typeof obj !== 'object') {
1169         return null;
1170     }
1171     var list = [];
1172     for(var k in obj) {
1173         k = encodeURIComponent(k);
1174         var value = obj[k];
1175         if(obj[k] instanceof Array) {
1176             for(var i in value) {
1177                 list.push(k+'[]='+encodeURIComponent(value[i]));
1178             }
1179         } else {
1180             list.push(k+'='+encodeURIComponent(value));
1181         }
1182     }
1183     return list.join(separator);
1187  * @deprecated since Moodle 3.3.
1188  */
1189 function stripHTML(str) {
1190     throw new Error('stripHTML can not be used any more. Please use jQuery instead.');
1193 function updateProgressBar(id, percent, msg, estimate) {
1194     var event,
1195         el = document.getElementById(id),
1196         eventData = {};
1198     if (!el) {
1199         return;
1200     }
1202     eventData.message = msg;
1203     eventData.percent = percent;
1204     eventData.estimate = estimate;
1206     try {
1207         event = new CustomEvent('update', {
1208             bubbles: false,
1209             cancelable: true,
1210             detail: eventData
1211         });
1212     } catch (exception) {
1213         if (!(exception instanceof TypeError)) {
1214             throw exception;
1215         }
1216         event = document.createEvent('CustomEvent');
1217         event.initCustomEvent('update', false, true, eventData);
1218         event.prototype = window.Event.prototype;
1219     }
1221     el.dispatchEvent(event);
1224 M.util.help_popups = {
1225     setup : function(Y) {
1226         Y.one('body').delegate('click', this.open_popup, 'a.helplinkpopup', this);
1227     },
1228     open_popup : function(e) {
1229         // Prevent the default page action
1230         e.preventDefault();
1232         // Grab the anchor that was clicked
1233         var anchor = e.target.ancestor('a', true);
1234         var args = {
1235             'name'          : 'popup',
1236             'url'           : anchor.getAttribute('href'),
1237             'options'       : ''
1238         };
1239         var options = [
1240             'height=600',
1241             'width=800',
1242             'top=0',
1243             'left=0',
1244             'menubar=0',
1245             'location=0',
1246             'scrollbars',
1247             'resizable',
1248             'toolbar',
1249             'status',
1250             'directories=0',
1251             'fullscreen=0',
1252             'dependent'
1253         ]
1254         args.options = options.join(',');
1256         openpopup(e, args);
1257     }
1261  * Custom menu namespace
1262  */
1263 M.core_custom_menu = {
1264     /**
1265      * This method is used to initialise a custom menu given the id that belongs
1266      * to the custom menu's root node.
1267      *
1268      * @param {YUI} Y
1269      * @param {string} nodeid
1270      */
1271     init : function(Y, nodeid) {
1272         var node = Y.one('#'+nodeid);
1273         if (node) {
1274             Y.use('node-menunav', function(Y) {
1275                 // Get the node
1276                 // Remove the javascript-disabled class.... obviously javascript is enabled.
1277                 node.removeClass('javascript-disabled');
1278                 // Initialise the menunav plugin
1279                 node.plug(Y.Plugin.NodeMenuNav);
1280             });
1281         }
1282     }
1286  * Used to store form manipulation methods and enhancments
1287  */
1288 M.form = M.form || {};
1291  * Converts a nbsp indented select box into a multi drop down custom control much
1292  * like the custom menu. Can no longer be used.
1293  * @deprecated since Moodle 3.3
1294  */
1295 M.form.init_smartselect = function() {
1296     throw new Error('M.form.init_smartselect can not be used any more.');
1300  * Initiates the listeners for skiplink interaction
1302  * @param {YUI} Y
1303  */
1304 M.util.init_skiplink = function(Y) {
1305     Y.one(Y.config.doc.body).delegate('click', function(e) {
1306         e.preventDefault();
1307         e.stopPropagation();
1308         var node = Y.one(this.getAttribute('href'));
1309         node.setAttribute('tabindex', '-1');
1310         node.focus();
1311         return true;
1312     }, 'a.skip');