MDL-33448 enrol_manual: Reduced JS get_string calls for the yui widget
[moodle.git] / enrol / manual / yui / quickenrolment / quickenrolment.js
1 YUI.add('moodle-enrol_manual-quickenrolment', function(Y) {
3     var UEP = {
4         NAME : 'Enrolment Manager',
5         /** Properties **/
6         BASE : 'base',
7         SEARCH : 'search',
8         PARAMS : 'params',
9         URL : 'url',
10         AJAXURL : 'ajaxurl',
11         MULTIPLE : 'multiple',
12         PAGE : 'page',
13         COURSEID : 'courseid',
14         USERS : 'users',
15         USERCOUNT : 'userCount',
16         REQUIREREFRESH : 'requiresRefresh',
17         LASTSEARCH : 'lastPreSearchValue',
18         INSTANCES : 'instances',
19         OPTIONSTARTDATE : 'optionsStartDate',
20         DEFAULTROLE : 'defaultRole',
21         DEFAULTSTARTDATE : 'defaultStartDate',
22         DEFAULTDURATION : 'defaultDuration',
23         ASSIGNABLEROLES : 'assignableRoles',
24         DISABLEGRADEHISTORY : 'disableGradeHistory',
25         RECOVERGRADESDEFAULT : 'recoverGradesDefault'
26     };
27     /** CSS classes for nodes in structure **/
28     var CSS = {
29         PANEL : 'user-enroller-panel',
30         WRAP : 'uep-wrap',
31         HEADER : 'uep-header',
32         CONTENT : 'uep-content',
33         AJAXCONTENT : 'uep-ajax-content',
34         SEARCHRESULTS : 'uep-search-results',
35         TOTALUSERS : 'totalusers',
36         USERS : 'users',
37         USER : 'user',
38         MORERESULTS : 'uep-more-results',
39         LIGHTBOX : 'uep-loading-lightbox',
40         LOADINGICON : 'loading-icon',
41         FOOTER : 'uep-footer',
42         ENROL : 'enrol',
43         ENROLLED : 'enrolled',
44         COUNT : 'count',
45         PICTURE : 'picture',
46         DETAILS : 'details',
47         FULLNAME : 'fullname',
48         EXTRAFIELDS : 'extrafields',
49         OPTIONS : 'options',
50         ODD  : 'odd',
51         EVEN : 'even',
52         HIDDEN : 'hidden',
53         RECOVERGRADES : 'recovergrades',
54         RECOVERGRADESTITLE : 'recovergradestitle',
55         SEARCHOPTIONS : 'uep-searchoptions',
56         COLLAPSIBLEHEADING : 'collapsibleheading',
57         COLLAPSIBLEAREA : 'collapsiblearea',
58         ENROLMENTOPTION : 'uep-enrolment-option',
59         SEARCHCONTROLS : 'uep-controls',
60         ROLE : 'role',
61         STARTDATE : 'startdate',
62         DURATION : 'duration',
63         ACTIVE : 'active',
64         SEARCH : 'uep-search',
65         CLOSE : 'close',
66         CLOSEBTN : 'close-button'
67     };
68     var create = Y.Node.create;
70     var USERENROLLER = function(config) {
71         USERENROLLER.superclass.constructor.apply(this, arguments);
72     };
73     Y.extend(USERENROLLER, Y.Base, {
74         _searchTimeout : null,
75         _loadingNode : null,
76         _escCloseEvent : null,
77         initializer : function(config) {
78             var recovergrades = null;
79             if (this.get(UEP.DISABLEGRADEHISTORY) != true) {
80                 recovergrades = create('<div class="'+CSS.ENROLMENTOPTION+' '+CSS.RECOVERGRADES+'"></div>')
81                     .append(create('<label class="'+CSS.RECOVERGRADESTITLE+'" for="'+CSS.RECOVERGRADES+'">'+M.str.enrol.recovergrades+'</label>'))
82                     .append(create('<input type="checkbox" id="'+CSS.RECOVERGRADES+'" name="'+CSS.RECOVERGRADES+'"'+ this.get(UEP.RECOVERGRADESDEFAULT) +' />'))
83             }
85             this.set(UEP.BASE, create('<div class="'+CSS.PANEL+' '+CSS.HIDDEN+'"></div>')
86                 .append(create('<div class="'+CSS.WRAP+'"></div>')
87                     .append(create('<div class="'+CSS.HEADER+' header"></div>')
88                         .append(create('<div class="'+CSS.CLOSE+'"></div>'))
89                         .append(create('<h2>'+M.str.enrol.enrolusers+'</h2>')))
90                     .append(create('<div class="'+CSS.CONTENT+'"></div>')
91                         .append(create('<div class="'+CSS.SEARCHCONTROLS+'"></div>')
92                             .append(create('<div class="'+CSS.ENROLMENTOPTION+' '+CSS.ROLE+'">'+M.str.role.assignroles+'</div>')
93                                     .append(create('<select><option value="">'+M.str.enrol.none+'</option></select>'))
94                             )
95                             .append(create('<div class="'+CSS.SEARCHOPTIONS+'"></div>')
96                                 .append(create('<div class="'+CSS.COLLAPSIBLEHEADING+'"><img alt="" />'+M.str.enrol.enrolmentoptions+'</div>'))
97                                 .append(create('<div class="'+CSS.COLLAPSIBLEAREA+' '+CSS.HIDDEN+'"></div>')
98                                     .append(recovergrades)
99                                     .append(create('<div class="'+CSS.ENROLMENTOPTION+' '+CSS.STARTDATE+'">'+M.str.moodle.startingfrom+'</div>')
100                                         .append(create('<select></select>')))
101                                     .append(create('<div class="'+CSS.ENROLMENTOPTION+' '+CSS.DURATION+'">'+M.str.enrol.enrolperiod+'</div>')
102                                         .append(create('<select><option value="0" selected="selected">'+M.str.enrol.unlimitedduration+'</option></select>')))
103                                 )
104                             )
105                         )
106                         .append(create('<div class="'+CSS.AJAXCONTENT+'"></div>'))
107                         .append(create('<div class="'+CSS.LIGHTBOX+' '+CSS.HIDDEN+'"></div>')
108                             .append(create('<img alt="loading" class="'+CSS.LOADINGICON+'" />')
109                                 .setAttribute('src', M.util.image_url('i/loading', 'moodle')))
110                             .setStyle('opacity', 0.5)))
111                     .append(create('<div class="'+CSS.FOOTER+'"></div>')
112                         .append(create('<div class="'+CSS.SEARCH+'"><label>'+M.str.enrol.usersearch+'</label></div>')
113                             .append(create('<input type="text" id="enrolusersearch" value="" />'))
114                         )
115                         .append(create('<div class="'+CSS.CLOSEBTN+'"></div>')
116                             .append(create('<input type="button" value="'+M.str.enrol.finishenrollingusers+'" />'))
117                         )
118                     )
119                 )
120             );
122             this.set(UEP.SEARCH, this.get(UEP.BASE).one('#enrolusersearch'));
123             Y.all('.enrol_manual_plugin input').each(function(node){
124                 if (node.getAttribute('type', 'submit')) {
125                     node.on('click', this.show, this);
126                 }
127             }, this);
128             this.get(UEP.BASE).one('.'+CSS.HEADER+' .'+CSS.CLOSE).on('click', this.hide, this);
129             this.get(UEP.BASE).one('.'+CSS.FOOTER+' .'+CSS.CLOSEBTN+' input').on('click', this.hide, this);
130             this._loadingNode = this.get(UEP.BASE).one('.'+CSS.CONTENT+' .'+CSS.LIGHTBOX);
131             var params = this.get(UEP.PARAMS);
132             params['id'] = this.get(UEP.COURSEID);
133             this.set(UEP.PARAMS, params);
135             Y.on('key', this.preSearch, this.get(UEP.SEARCH), 'down:13', this);
137             Y.one(document.body).append(this.get(UEP.BASE));
139             var base = this.get(UEP.BASE);
140             base.plug(Y.Plugin.Drag);
141             base.dd.addHandle('.'+CSS.HEADER+' h2');
142             base.one('.'+CSS.HEADER+' h2').setStyle('cursor', 'move');
144             var collapsedimage = 't/collapsed'; // ltr mode
145             if ( Y.one(document.body).hasClass('dir-rtl') ) {
146                 collapsedimage = 't/collapsed_rtl';
147             } else {
148                 collapsedimage = 't/collapsed';
149             }
151             this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEHEADING).one('img').setAttribute('src', M.util.image_url(collapsedimage, 'moodle'));
152             this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEHEADING).once('click', function() {
153                 // We want to do this just once, the first time the controls are shown.
154                 this.populateStartDates();
155                 this.populateDuration();
156             }, this);
157             this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEHEADING).on('click', function(){
158                 this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEHEADING).toggleClass(CSS.ACTIVE);
159                 this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEAREA).toggleClass(CSS.HIDDEN);
160                 if (this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEAREA).hasClass(CSS.HIDDEN)) {
161                     this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEHEADING).one('img').setAttribute('src', M.util.image_url(collapsedimage, 'moodle'));
162                 } else {
163                     this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEHEADING).one('img').setAttribute('src', M.util.image_url('t/expanded', 'moodle'));
164                 }
165             }, this);
166             this.populateAssignableRoles();
167         },
168         populateAssignableRoles : function() {
169             this.on('assignablerolesloaded', function(){
170                 var roles = this.get(UEP.ASSIGNABLEROLES);
171                 var s = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.ROLE+' select');
172                 var v = this.get(UEP.DEFAULTROLE);
173                 var index = 0, count = 0;
174                 for (var i in roles) {
175                     count++;
176                     var option = create('<option value="'+i+'">'+roles[i]+'</option>');
177                     if (i == v) {
178                         index = count;
179                     }
180                     s.append(option);
181                 }
182                 s.set('selectedIndex', index);
183             }, this);
184             this.getAssignableRoles();
185         },
186         populateStartDates : function() {
187             var select = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.STARTDATE+' select');
188             var defaultvalue = this.get(UEP.DEFAULTSTARTDATE);
189             var options = this.get(UEP.OPTIONSTARTDATE);
190             var index = 0, count = 0;
191             for (var i in options) {
192                 count++;
193                 var option = create('<option value="'+i+'">'+options[i]+'</option>');
194                 if (i == defaultvalue) {
195                     index = count;
196                 }
197                 select.append(option);
198             }
199             select.set('selectedIndex', index);
200         },
201         populateDuration : function() {
202             var select = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.DURATION+' select');
203             var defaultvalue = this.get(UEP.DEFAULTDURATION);
204             var index = 0, count = 0;
205             var durationdays = M.util.get_string('durationdays', 'enrol', '{a}');
206             for (var i = 1; i <= 365; i++) {
207                 count++;
208                 var option = create('<option value="'+i+'">'+durationdays.replace('{a}', i)+'</option>');
209                 if (i == defaultvalue) {
210                     index = count;
211                 }
212                 select.append(option);
213             }
214             select.set('selectedIndex', index);
215         },
216         getAssignableRoles : function(){
217             Y.io(M.cfg.wwwroot+'/enrol/ajax.php', {
218                 method:'POST',
219                 data:'id='+this.get(UEP.COURSEID)+'&action=getassignable&sesskey='+M.cfg.sesskey,
220                 on: {
221                     complete: function(tid, outcome, args) {
222                         try {
223                             var roles = Y.JSON.parse(outcome.responseText);
224                             this.set(UEP.ASSIGNABLEROLES, roles.response);
225                         } catch (e) {
226                             new M.core.exception(e);
227                         }
228                         this.getAssignableRoles = function() {
229                             this.fire('assignablerolesloaded');
230                         };
231                         this.getAssignableRoles();
232                     }
233                 },
234                 context:this
235             });
236         },
237         preSearch : function(e) {
238             this.search(null, false);
239             /*
240             var value = this.get(UEP.SEARCH).get('value');
241             if (value.length < 3 || value == this.get(UEP.LASTSEARCH)) {
242                 return;
243             }
244             this.set(UEP.LASTSEARCH, value);
245             if (this._searchTimeout) {
246                 clearTimeout(this._searchTimeout);
247                 this._searchTimeout = null;
248             }
249             var self = this;
250             this._searchTimeout = setTimeout(function(){
251                 self._searchTimeout = null;
252                 self.search(null, false);
253             }, 300);
254             */
255         },
256         show : function(e) {
257             e.preventDefault();
258             e.halt();
260             var base = this.get(UEP.BASE);
261             base.removeClass(CSS.HIDDEN);
262             var x = (base.get('winWidth') - 400)/2;
263             var y = (parseInt(base.get('winHeight'))-base.get('offsetHeight'))/2 + parseInt(base.get('docScrollY'));
264             if (y < parseInt(base.get('winHeight'))*0.1) {
265                 y = parseInt(base.get('winHeight'))*0.1;
266             }
267             base.setXY([x,y]);
269             if (this.get(UEP.USERS)===null) {
270                 this.search(e, false);
271             }
273             this._escCloseEvent = Y.on('key', this.hide, document.body, 'down:27', this);
274         },
275         hide : function(e) {
276             if (this._escCloseEvent) {
277                 this._escCloseEvent.detach();
278                 this._escCloseEvent = null;
279             }
280             this.get(UEP.BASE).addClass(CSS.HIDDEN);
281             if (this.get(UEP.REQUIREREFRESH)) {
282                 window.location = this.get(UEP.URL);
283             }
284         },
285         search : function(e, append) {
286             if (e) {
287                 e.halt();
288                 e.preventDefault();
289             }
290             var on, params;
291             if (append) {
292                 this.set(UEP.PAGE, this.get(UEP.PAGE)+1);
293             } else {
294                 this.set(UEP.USERCOUNT, 0);
295                 this.set(UEP.PAGE, 0);
296             }
297             params = this.get(UEP.PARAMS);
298             params['sesskey'] = M.cfg.sesskey;
299             params['action'] = 'searchusers';
300             params['search'] = this.get(UEP.SEARCH).get('value');
301             params['page'] = this.get(UEP.PAGE);
302             if (this.get(UEP.MULTIPLE)) {
303                 alert('oh no there are multiple');
304             } else {
305                 var instance = this.get(UEP.INSTANCES)[0];
306                 params['enrolid'] = instance.id;
307             }
308             Y.io(M.cfg.wwwroot+this.get(UEP.AJAXURL), {
309                 method:'POST',
310                 data:build_querystring(params),
311                 on : {
312                     start : this.displayLoading,
313                     complete: this.processSearchResults,
314                     end : this.removeLoading
315                 },
316                 context:this,
317                 arguments:{
318                     append:append,
319                     enrolid:params['enrolid']
320                 }
321             });
322         },
323         displayLoading : function() {
324             this._loadingNode.removeClass(CSS.HIDDEN);
325         },
326         removeLoading : function() {
327             this._loadingNode.addClass(CSS.HIDDEN);
328         },
329         processSearchResults : function(tid, outcome, args) {
330             try {
331                 var result = Y.JSON.parse(outcome.responseText);
332                 if (result.error) {
333                     return new M.core.ajaxException(result);
334                 }
335             } catch (e) {
336                 new M.core.exception(e);
337             }
338             if (!result.success) {
339                 this.setContent = M.str.enrol.errajaxsearch;
340             }
341             var users;
342             if (!args.append) {
343                 users = create('<div class="'+CSS.USERS+'"></div>');
344             } else {
345                 users = this.get(UEP.BASE).one('.'+CSS.SEARCHRESULTS+' .'+CSS.USERS);
346             }
347             var count = this.get(UEP.USERCOUNT);
348             for (var i in result.response.users) {
349                 count++;
350                 var user = result.response.users[i];
351                 users.append(create('<div class="'+CSS.USER+' clearfix" rel="'+user.id+'"></div>')
352                     .addClass((count%2)?CSS.ODD:CSS.EVEN)
353                     .append(create('<div class="'+CSS.COUNT+'">'+count+'</div>'))
354                     .append(create('<div class="'+CSS.PICTURE+'"></div>')
355                         .append(create(user.picture)))
356                     .append(create('<div class="'+CSS.DETAILS+'"></div>')
357                         .append(create('<div class="'+CSS.FULLNAME+'">'+user.fullname+'</div>'))
358                         .append(create('<div class="'+CSS.EXTRAFIELDS+'">'+user.extrafields+'</div>')))
359                     .append(create('<div class="'+CSS.OPTIONS+'"></div>')
360                         .append(create('<input type="button" class="'+CSS.ENROL+'" value="'+M.str.enrol.enrol+'" />')))
361                 );
362             }
363             this.set(UEP.USERCOUNT, count);
364             if (!args.append) {
365                 var usersstr = (result.response.totalusers == '1')?M.str.enrol.ajaxoneuserfound:M.util.get_string('ajaxxusersfound','enrol', result.response.totalusers);
366                 var content = create('<div class="'+CSS.SEARCHRESULTS+'"></div>')
367                     .append(create('<div class="'+CSS.TOTALUSERS+'">'+usersstr+'</div>'))
368                     .append(users);
369                 if (result.response.totalusers > (this.get(UEP.PAGE)+1)*25) {
370                     var fetchmore = create('<div class="'+CSS.MORERESULTS+'"><a href="#">'+M.str.enrol.ajaxnext25+'</a></div>');
371                     fetchmore.on('click', this.search, this, true);
372                     content.append(fetchmore)
373                 }
374                 this.setContent(content);
375                 Y.delegate("click", this.enrolUser, users, '.'+CSS.USER+' .'+CSS.ENROL, this, args);
376             } else {
377                 if (result.response.totalusers <= (this.get(UEP.PAGE)+1)*25) {
378                     this.get(UEP.BASE).one('.'+CSS.MORERESULTS).remove();
379                 }
380             }
381         },
382         enrolUser : function(e, args) {
383             var user = e.currentTarget.ancestor('.'+CSS.USER);
384             var params = [];
385             params['id'] = this.get(UEP.COURSEID);
386             params['userid'] = user.getAttribute("rel");
387             params['enrolid'] = args.enrolid;
388             params['sesskey'] = M.cfg.sesskey;
389             params['action'] = 'enrol';
390             params['role'] = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.ROLE+' select').get('value');
391             params['startdate'] = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.STARTDATE+' select').get('value');
392             params['duration'] = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.DURATION+' select').get('value');
393             if (this.get(UEP.DISABLEGRADEHISTORY) != true) {
394                 params['recovergrades'] = this.get(UEP.BASE).one('#'+CSS.RECOVERGRADES).get('checked')?1:0;
395             } else {
396                 params['recovergrades'] = 0;
397             }
399             Y.io(M.cfg.wwwroot+this.get(UEP.AJAXURL), {
400                 method:'POST',
401                 data:build_querystring(params),
402                 on: {
403                     start : this.displayLoading,
404                     complete : function(tid, outcome, args) {
405                         try {
406                             var result = Y.JSON.parse(outcome.responseText);
407                             if (result.error) {
408                                 return new M.core.ajaxException(result);
409                             } else {
410                                 args.userNode.addClass(CSS.ENROLLED);
411                                 args.userNode.one('.'+CSS.ENROL).remove();
412                                 this.set(UEP.REQUIREREFRESH, true);
413                             }
414                         } catch (e) {
415                             new M.core.exception(e);
416                         }
417                     },
418                     end : this.removeLoading
419                 },
420                 context:this,
421                 arguments:{
422                     params : params,
423                     userNode : user
424                 }
425             });
427         },
428         setContent: function(content) {
429             this.get(UEP.BASE).one('.'+CSS.CONTENT+' .'+CSS.AJAXCONTENT).setContent(content);
430         }
431     }, {
432         NAME : UEP.NAME,
433         ATTRS : {
434             url : {
435                 validator : Y.Lang.isString
436             },
437             ajaxurl : {
438                 validator : Y.Lang.isString
439             },
440             base : {
441                 setter : function(node) {
442                     var n = Y.one(node);
443                     if (!n) {
444                         Y.fail(UEP.NAME+': invalid base node set');
445                     }
446                     return n;
447                 }
448             },
449             users : {
450                 validator : Y.Lang.isArray,
451                 value : null
452             },
453             courseid : {
454                 value : null
455             },
456             params : {
457                 validator : Y.Lang.isArray,
458                 value : []
459             },
460             instances : {
461                 validator : Y.Lang.isArray,
462                 setter : function(instances) {
463                     var i,ia = [], count=0;
464                     for (i in instances) {
465                         ia.push(instances[i]);
466                         count++;
467                     }
468                     this.set(UEP.MULTIPLE, (count>1));
469                 }
470             },
471             multiple : {
472                 validator : Y.Lang.isBool,
473                 value : false
474             },
475             page : {
476                 validator : Y.Lang.isNumber,
477                 value : 0
478             },
479             userCount : {
480                 value : 0,
481                 validator : Y.Lang.isNumber
482             },
483             requiresRefresh : {
484                 value : false,
485                 validator : Y.Lang.isBool
486             },
487             search : {
488                 setter : function(node) {
489                     var n = Y.one(node);
490                     if (!n) {
491                         Y.fail(UEP.NAME+': invalid search node set');
492                     }
493                     return n;
494                 }
495             },
496             lastPreSearchValue : {
497                 value : '',
498                 validator : Y.Lang.isString
499             },
500             strings  : {
501                 value : {},
502                 validator : Y.Lang.isObject
503             },
504             defaultRole : {
505                 value : 0
506             },
507             defaultStartDate : {
508                 value : 2,
509                 validator : Y.Lang.isNumber
510             },
511             defaultDuration : {
512                 value : ''
513             },
514             assignableRoles : {
515                 value : []
516             },
517             optionsStartDate : {
518                 value : []
519             },
520             disableGradeHistory : {
521                 value : 0
522             },
523             recoverGradesDefault : {
524                 value : ''
525             }
526         }
527     });
528     Y.augment(USERENROLLER, Y.EventTarget);
530     M.enrol_manual = M.enrol_manual || {};
531     M.enrol_manual.quickenrolment = {
532         init : function(cfg) {
533             new USERENROLLER(cfg);
534         }
535     }
537 }, '@VERSION@', {requires:['base','node', 'overlay', 'io-base', 'test', 'json-parse', 'event-delegate', 'dd-plugin', 'event-key', 'moodle-enrol-notification']});