MDL-30899 moodle-core-notification Adding focus to non modal windows
[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+'"><label for="id_enrol_manual_assignable_roles">'+M.str.role.assignroles+'</label></div>')
93                                     .append(create('<select id="id_enrol_manual_assignable_roles"><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).on('click', function(){
153                 this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEHEADING).toggleClass(CSS.ACTIVE);
154                 this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEAREA).toggleClass(CSS.HIDDEN);
155                 if (this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEAREA).hasClass(CSS.HIDDEN)) {
156                     this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEHEADING).one('img').setAttribute('src', M.util.image_url(collapsedimage, 'moodle'));
157                 } else {
158                     this.get(UEP.BASE).one('.'+CSS.SEARCHOPTIONS+' .'+CSS.COLLAPSIBLEHEADING).one('img').setAttribute('src', M.util.image_url('t/expanded', 'moodle'));
159                 }
160             }, this);
162             this.populateAssignableRoles();
163             this.populateStartDates();
164             this.populateDuration();
165         },
166         populateAssignableRoles : function() {
167             this.on('assignablerolesloaded', function(){
168                 var roles = this.get(UEP.ASSIGNABLEROLES);
169                 var s = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.ROLE+' select');
170                 var v = this.get(UEP.DEFAULTROLE);
171                 var index = 0, count = 0;
172                 for (var i in roles) {
173                     count++;
174                     var option = create('<option value="'+i+'">'+roles[i]+'</option>');
175                     if (i == v) {
176                         index = count;
177                     }
178                     s.append(option);
179                 }
180                 s.set('selectedIndex', index);
181                 Y.one('#id_enrol_manual_assignable_roles').focus();
182             }, this);
183             this.getAssignableRoles();
184         },
185         populateStartDates : function() {
186             var select = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.STARTDATE+' select');
187             var defaultvalue = this.get(UEP.DEFAULTSTARTDATE);
188             var options = this.get(UEP.OPTIONSTARTDATE);
189             var index = 0, count = 0;
190             for (var i in options) {
191                 count++;
192                 var option = create('<option value="'+i+'">'+options[i]+'</option>');
193                 if (i == defaultvalue) {
194                     index = count;
195                 }
196                 select.append(option);
197             }
198             select.set('selectedIndex', index);
199         },
200         populateDuration : function() {
201             var select = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.DURATION+' select');
202             var defaultvalue = this.get(UEP.DEFAULTDURATION);
203             var index = 0, count = 0;
204             for (var i = 1; i <= 365; i++) {
205                 count++;
206                 var option = create('<option value="'+i+'">'+M.util.get_string('durationdays', 'enrol', i)+'</option>');
207                 if (i == defaultvalue) {
208                     index = count;
209                 }
210                 select.append(option);
211             }
212             select.set('selectedIndex', index);
213         },
214         getAssignableRoles : function(){
215             Y.io(M.cfg.wwwroot+'/enrol/ajax.php', {
216                 method:'POST',
217                 data:'id='+this.get(UEP.COURSEID)+'&action=getassignable&sesskey='+M.cfg.sesskey,
218                 on: {
219                     complete: function(tid, outcome, args) {
220                         try {
221                             var roles = Y.JSON.parse(outcome.responseText);
222                             this.set(UEP.ASSIGNABLEROLES, roles.response);
223                         } catch (e) {
224                             new M.core.exception(e);
225                         }
226                         this.getAssignableRoles = function() {
227                             this.fire('assignablerolesloaded');
228                         };
229                         this.getAssignableRoles();
230                     }
231                 },
232                 context:this
233             });
234         },
235         preSearch : function(e) {
236             this.search(null, false);
237             /*
238             var value = this.get(UEP.SEARCH).get('value');
239             if (value.length < 3 || value == this.get(UEP.LASTSEARCH)) {
240                 return;
241             }
242             this.set(UEP.LASTSEARCH, value);
243             if (this._searchTimeout) {
244                 clearTimeout(this._searchTimeout);
245                 this._searchTimeout = null;
246             }
247             var self = this;
248             this._searchTimeout = setTimeout(function(){
249                 self._searchTimeout = null;
250                 self.search(null, false);
251             }, 300);
252             */
253         },
254         show : function(e) {
255             e.preventDefault();
256             e.halt();
258             var base = this.get(UEP.BASE);
259             base.removeClass(CSS.HIDDEN);
260             var x = (base.get('winWidth') - 400)/2;
261             var y = (parseInt(base.get('winHeight'))-base.get('offsetHeight'))/2 + parseInt(base.get('docScrollY'));
262             if (y < parseInt(base.get('winHeight'))*0.1) {
263                 y = parseInt(base.get('winHeight'))*0.1;
264             }
265             base.setXY([x,y]);
267             if (this.get(UEP.USERS)===null) {
268                 this.search(e, false);
269             }
271             this._escCloseEvent = Y.on('key', this.hide, document.body, 'down:27', this);
272             var rolesselect = Y.one('#id_enrol_manual_assignable_roles');
273             if (rolesselect) {
274                 rolesselect.focus();
275             }
276         },
277         hide : function(e) {
278             if (this._escCloseEvent) {
279                 this._escCloseEvent.detach();
280                 this._escCloseEvent = null;
281             }
282             this.get(UEP.BASE).addClass(CSS.HIDDEN);
283             if (this.get(UEP.REQUIREREFRESH)) {
284                 window.location = this.get(UEP.URL);
285             }
286         },
287         search : function(e, append) {
288             if (e) {
289                 e.halt();
290                 e.preventDefault();
291             }
292             var on, params;
293             if (append) {
294                 this.set(UEP.PAGE, this.get(UEP.PAGE)+1);
295             } else {
296                 this.set(UEP.USERCOUNT, 0);
297                 this.set(UEP.PAGE, 0);
298             }
299             params = this.get(UEP.PARAMS);
300             params['sesskey'] = M.cfg.sesskey;
301             params['action'] = 'searchusers';
302             params['search'] = this.get(UEP.SEARCH).get('value');
303             params['page'] = this.get(UEP.PAGE);
304             if (this.get(UEP.MULTIPLE)) {
305                 alert('oh no there are multiple');
306             } else {
307                 var instance = this.get(UEP.INSTANCES)[0];
308                 params['enrolid'] = instance.id;
309             }
310             Y.io(M.cfg.wwwroot+this.get(UEP.AJAXURL), {
311                 method:'POST',
312                 data:build_querystring(params),
313                 on : {
314                     start : this.displayLoading,
315                     complete: this.processSearchResults,
316                     end : this.removeLoading
317                 },
318                 context:this,
319                 arguments:{
320                     append:append,
321                     enrolid:params['enrolid']
322                 }
323             });
324         },
325         displayLoading : function() {
326             this._loadingNode.removeClass(CSS.HIDDEN);
327         },
328         removeLoading : function() {
329             this._loadingNode.addClass(CSS.HIDDEN);
330         },
331         processSearchResults : function(tid, outcome, args) {
332             try {
333                 var result = Y.JSON.parse(outcome.responseText);
334                 if (result.error) {
335                     return new M.core.ajaxException(result);
336                 }
337             } catch (e) {
338                 new M.core.exception(e);
339             }
340             if (!result.success) {
341                 this.setContent = M.str.enrol.errajaxsearch;
342             }
343             var users;
344             if (!args.append) {
345                 users = create('<div class="'+CSS.USERS+'"></div>');
346             } else {
347                 users = this.get(UEP.BASE).one('.'+CSS.SEARCHRESULTS+' .'+CSS.USERS);
348             }
349             var count = this.get(UEP.USERCOUNT);
350             for (var i in result.response.users) {
351                 count++;
352                 var user = result.response.users[i];
353                 users.append(create('<div class="'+CSS.USER+' clearfix" rel="'+user.id+'"></div>')
354                     .addClass((count%2)?CSS.ODD:CSS.EVEN)
355                     .append(create('<div class="'+CSS.COUNT+'">'+count+'</div>'))
356                     .append(create('<div class="'+CSS.PICTURE+'"></div>')
357                         .append(create(user.picture)))
358                     .append(create('<div class="'+CSS.DETAILS+'"></div>')
359                         .append(create('<div class="'+CSS.FULLNAME+'">'+user.fullname+'</div>'))
360                         .append(create('<div class="'+CSS.EXTRAFIELDS+'">'+user.extrafields+'</div>')))
361                     .append(create('<div class="'+CSS.OPTIONS+'"></div>')
362                         .append(create('<input type="button" class="'+CSS.ENROL+'" value="'+M.str.enrol.enrol+'" />')))
363                 );
364             }
365             this.set(UEP.USERCOUNT, count);
366             if (!args.append) {
367                 var usersstr = (result.response.totalusers == '1')?M.str.enrol.ajaxoneuserfound:M.util.get_string('ajaxxusersfound','enrol', result.response.totalusers);
368                 var content = create('<div class="'+CSS.SEARCHRESULTS+'"></div>')
369                     .append(create('<div class="'+CSS.TOTALUSERS+'">'+usersstr+'</div>'))
370                     .append(users);
371                 if (result.response.totalusers > (this.get(UEP.PAGE)+1)*25) {
372                     var fetchmore = create('<div class="'+CSS.MORERESULTS+'"><a href="#">'+M.str.enrol.ajaxnext25+'</a></div>');
373                     fetchmore.on('click', this.search, this, true);
374                     content.append(fetchmore)
375                 }
376                 this.setContent(content);
377                 Y.delegate("click", this.enrolUser, users, '.'+CSS.USER+' .'+CSS.ENROL, this, args);
378             } else {
379                 if (result.response.totalusers <= (this.get(UEP.PAGE)+1)*25) {
380                     this.get(UEP.BASE).one('.'+CSS.MORERESULTS).remove();
381                 }
382             }
383         },
384         enrolUser : function(e, args) {
385             var user = e.currentTarget.ancestor('.'+CSS.USER);
386             var params = [];
387             params['id'] = this.get(UEP.COURSEID);
388             params['userid'] = user.getAttribute("rel");
389             params['enrolid'] = args.enrolid;
390             params['sesskey'] = M.cfg.sesskey;
391             params['action'] = 'enrol';
392             params['role'] = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.ROLE+' select').get('value');
393             params['startdate'] = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.STARTDATE+' select').get('value');
394             params['duration'] = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.DURATION+' select').get('value');
395             if (this.get(UEP.DISABLEGRADEHISTORY) != true) {
396                 params['recovergrades'] = this.get(UEP.BASE).one('#'+CSS.RECOVERGRADES).get('checked')?1:0;
397             } else {
398                 params['recovergrades'] = 0;
399             }
401             Y.io(M.cfg.wwwroot+this.get(UEP.AJAXURL), {
402                 method:'POST',
403                 data:build_querystring(params),
404                 on: {
405                     start : this.displayLoading,
406                     complete : function(tid, outcome, args) {
407                         try {
408                             var result = Y.JSON.parse(outcome.responseText);
409                             if (result.error) {
410                                 return new M.core.ajaxException(result);
411                             } else {
412                                 args.userNode.addClass(CSS.ENROLLED);
413                                 args.userNode.one('.'+CSS.ENROL).remove();
414                                 this.set(UEP.REQUIREREFRESH, true);
415                             }
416                         } catch (e) {
417                             new M.core.exception(e);
418                         }
419                     },
420                     end : this.removeLoading
421                 },
422                 context:this,
423                 arguments:{
424                     params : params,
425                     userNode : user
426                 }
427             });
429         },
430         setContent: function(content) {
431             this.get(UEP.BASE).one('.'+CSS.CONTENT+' .'+CSS.AJAXCONTENT).setContent(content);
432         }
433     }, {
434         NAME : UEP.NAME,
435         ATTRS : {
436             url : {
437                 validator : Y.Lang.isString
438             },
439             ajaxurl : {
440                 validator : Y.Lang.isString
441             },
442             base : {
443                 setter : function(node) {
444                     var n = Y.one(node);
445                     if (!n) {
446                         Y.fail(UEP.NAME+': invalid base node set');
447                     }
448                     return n;
449                 }
450             },
451             users : {
452                 validator : Y.Lang.isArray,
453                 value : null
454             },
455             courseid : {
456                 value : null
457             },
458             params : {
459                 validator : Y.Lang.isArray,
460                 value : []
461             },
462             instances : {
463                 validator : Y.Lang.isArray,
464                 setter : function(instances) {
465                     var i,ia = [], count=0;
466                     for (i in instances) {
467                         ia.push(instances[i]);
468                         count++;
469                     }
470                     this.set(UEP.MULTIPLE, (count>1));
471                 }
472             },
473             multiple : {
474                 validator : Y.Lang.isBool,
475                 value : false
476             },
477             page : {
478                 validator : Y.Lang.isNumber,
479                 value : 0
480             },
481             userCount : {
482                 value : 0,
483                 validator : Y.Lang.isNumber
484             },
485             requiresRefresh : {
486                 value : false,
487                 validator : Y.Lang.isBool
488             },
489             search : {
490                 setter : function(node) {
491                     var n = Y.one(node);
492                     if (!n) {
493                         Y.fail(UEP.NAME+': invalid search node set');
494                     }
495                     return n;
496                 }
497             },
498             lastPreSearchValue : {
499                 value : '',
500                 validator : Y.Lang.isString
501             },
502             strings  : {
503                 value : {},
504                 validator : Y.Lang.isObject
505             },
506             defaultRole : {
507                 value : 0
508             },
509             defaultStartDate : {
510                 value : 2,
511                 validator : Y.Lang.isNumber
512             },
513             defaultDuration : {
514                 value : ''
515             },
516             assignableRoles : {
517                 value : []
518             },
519             optionsStartDate : {
520                 value : []
521             },
522             disableGradeHistory : {
523                 value : 0
524             },
525             recoverGradesDefault : {
526                 value : ''
527             }
528         }
529     });
530     Y.augment(USERENROLLER, Y.EventTarget);
532     M.enrol_manual = M.enrol_manual || {};
533     M.enrol_manual.quickenrolment = {
534         init : function(cfg) {
535             new USERENROLLER(cfg);
536         }
537     }
539 }, '@VERSION@', {requires:['base','node', 'overlay', 'io-base', 'test', 'json-parse', 'event-delegate', 'dd-plugin', 'event-key', 'moodle-core-notification']});