Let the annoying commence.
[edumed.git] / wtem / static / wtem / wtem.js
1 $(function() {
2
3     var to_submit;
4
5     $('form').submit(function(e) {
6         //e.preventDefault();
7         to_submit = {};
8         spinner.show();
9
10         $('.exercise-wtem').each(function() {
11             var el = $(this);
12             if(el.hasClass('exercise')) {
13                 handlers.edumed(el);
14             } else {
15                 var type = el.attr('data-type');
16                 if(handlers[type]) {
17                     handlers[type](el);
18                 }
19             }
20         });
21         $('input[name=answers]').val(JSON.stringify(to_submit));
22     });
23
24     var push_answer = function(el, answer) {
25         to_submit[el.attr('data-id')] = answer
26     };
27
28     var handlers = {
29         edumed: function(el) {
30             var exercise = el.data('exercise'),
31                 to_push = {},
32                 open_part;
33             if(exercise.get_answers) {
34                 to_push.closed_part = exercise.get_answers()[0];
35             }
36             open_part = el.find('.open_part')
37             if(open_part.length) {
38                 to_push.open_part = open_part.find('textarea').val();
39             }
40
41             push_answer(el, to_push);
42         },
43
44         open: function(el) {
45             var textareas = el.find('textarea'),
46                 to_push;
47             if(textareas.length === 1) {
48                 to_push = el.find('textarea').val();
49             } else {
50                 to_push = [];
51                 textareas.each(function() {
52                     var textarea = $(this);
53                     to_push.push({'id': textarea.attr('data-field-id'), 'text': textarea.val()});
54                 });
55             }
56             push_answer(el, to_push);
57         }
58     }
59
60     var sms_handler = function() {
61         var textarea = $(this),
62             label_suffix = textarea.parent().find('.label_suffix'),
63             left = 140 - textarea.val().length;
64             to_insert = '(pozostaƂo: ' + left + ')';
65         if(left < 0) {
66             to_insert = '<span style="color:red">' + to_insert + '</span>';
67         }
68         label_suffix.html(to_insert);
69     };
70
71     $('#wtem_sms').change(sms_handler).keyup(sms_handler);
72
73     var spinner = $('.wtem_spinner');
74     spinner.hide();
75 });