mod quiz + questions MDL-22370 convert JavaScript to YUI3 and modules.
[moodle.git] / question / flags.js
CommitLineData
ff065f96
TH
1// This script, and the YUI libraries that it needs, are inluded by
2// the $PAGE->requires->js calls in question_get_html_head_contributions in lib/questionlib.php.
3
4M.core_question_flags = {
5 flagattributes: null,
6 actionurl: null,
7 listeners: [],
8
9 init: function(Y, actionurl, flagattributes) {
10 M.core_question_flags.flagattributes = flagattributes;
11 M.core_question_flags.actionurl = actionurl;
12
13 Y.all('div.questionflag').each(function(flagdiv, i) {
14 var checkbox = flagdiv.one('input.questionflagcheckbox');
15 if (!checkbox) {
16 return;
17 }
18
19 var input = Y.Node.create('<input type="hidden" />');
20 input.set('id', checkbox.get('id'));
21 input.set('name', checkbox.get('name'));
22 input.set('value', checkbox.get('checked') ? 1 : 0);
23
24 // Create an image input to replace the img tag.
25 var image = Y.Node.create('<input type="image" class="questionflagimage" />');
26 M.core_question_flags.update_flag(input, image);
27
28 checkbox.remove();
29 flagdiv.one('label').remove();
30 flagdiv.append(input);
31 flagdiv.append(image);
32 });
33
34 Y.delegate('click', function(e) {
35 var input = this.previous('input');
36 input.set('value', 1 - input.get('value'));
37 M.core_question_flags.update_flag(input, this);
38 var postdata = this.previous('input.questionflagpostdata').get('value') +
39 input.get('value')
40
41 e.halt();
42 Y.io(M.core_question_flags.actionurl , {method: 'POST', 'data': postdata});
43 M.core_question_flags.fire_listeners(postdata);
44 }, document.body, 'input.questionflagimage');
45
46 },
47
48 update_flag: function(input, image) {
49 image.setAttrs(M.core_question_flags.flagattributes[input.get('value')]);
50 },
51
52 add_listener: function(listener) {
53 M.core_question_flags.listeners.push(listener);
54 },
55
56 fire_listeners: function(postdata) {
57 for (var i = 0; i < M.core_question_flags.listeners.length; i++) {
58 M.core_question_flags.listeners[i](
59 postdata.match(/\baid=(\d+)\b/)[1],
60 postdata.match(/\bqid=(\d+)\b/)[1],
61 postdata.match(/\bnewstate=(\d+)\b/)[1]
62 );
63 }
64 }
65};