-
Notifications
You must be signed in to change notification settings - Fork 56
/
custom_form.js
executable file
·1848 lines (1712 loc) · 66 KB
/
custom_form.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Taken from jquery-migrate since toggle() was removed in jQuery 1.9
$j.fn.clicktoggle = function( fn, fn2 ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || $j.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( $j._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
$j._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.on("click", toggler );
};
//Defining the master 'list' for form elements
var formElements={
'Generic':{
textField:{'disp_name':'Single Line Text - Short','ques':''},
longTextField:{'disp_name':'Single Line Text - Long','ques':''},
longAns:{'disp_name':'Long Answer','ques':''},
reallyLongAns:{'disp_name':'Really Long Answer','ques':''},
radio:{'disp_name':'Radio Button Group','ques':'Pick an option'},
dropdown:{'disp_name':'Dropdown List','ques':'Pick an option'},
multiselect:{'disp_name':'Multiple Select', 'ques':'Pick some options'},
checkboxes:{'disp_name':'Checkbox Group', 'ques':'Pick some options'},
numeric:{'disp_name':'Numeric Field','ques':''},
date:{'disp_name':'Date','ques':'Date'},
time:{'disp_name':'Time','ques':'Time'},
file:{'disp_name':'File', 'ques':'Upload a file'},
radio_yesno: {'disp_name': 'Yes/No Field', 'ques': 'Choose Yes or No'},
'boolean': {'disp_name': 'Boolean Field', 'ques': ''},
null_boolean: {'disp_name': 'Null Boolean Field', 'ques':''}
},
'Personal':
{
phone:{'disp_name':'Phone no.','ques':'Your phone no.'},
email:{'disp_name':'Email','ques':'Your email'},
state:{'disp_name':'State','ques':'Your state'},
gender:{'disp_name':'Gender','ques':'Your gender'},
pronoun:{'disp_name':'Pronouns','ques':'Your preferred pronouns'}
},
'NotReallyFields': {
instructions: {'disp_name': 'Instructions', 'ques': ''},
section:{'disp_name':'Section', 'ques':'Section'},
page:{'disp_name':'Page', 'ques':'Section'},
}
/*'Personal':{
name:{'disp_name':'Name','ques':'Your name', 'field_type':'custom', 'field_options':{}},
gender:{'disp_name':'Gender','ques':'Gender', 'field_type':'radio', 'field_options':{'options':'Male|Female'}},
pronoun:{'disp_name':'Pronouns','ques':'Pronouns', 'field_type':'textField', 'field_options':{}},
phone:{'disp_name':'Phone no.','ques':'Phone no.', 'field_type':'textField', 'field_options':{}},
email:{'disp_name':'Email','ques':'Email', 'field_type':'textField', 'field_options':{}},
address:{'disp_name':'Address','ques':'Address', 'field_type':'custom', 'field_options':{}},
state:{'disp_name':'State','ques':'State', 'field_type':'dropdown', 'field_options':{'options':''}},
city:{'disp_name':'City','ques':'City', 'field_type':'textField', 'field_options':{}}
},
'Program':{}*/
};
var getKeys = function(obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys;
}
var default_categories = getKeys(formElements);
var inDefaultCategory = function(field_type) {
for (var catname in formElements)
{
for (var catlabel in formElements[catname])
{
if (field_type == catlabel)
return true;
}
}
return false;
}
var only_fkey_models=[];
var model_instance_cache={};
var modules={};
var elemTypes = {
// Stores the available types of form objects, and their number in the form
'textField':0,
'longTextField':0,
'longAns':0,
'reallyLongAns':0,
'radio':0,
'dropdown':0,
'multiselect':0,
'checkboxes':0,
'numeric':0,
'date':0,
'time':0,
'file':0,
'name':0,
'gender':0,
'pronoun':0,
'phone':0,
'email':0,
'address':0,
'state':0,
'city':0,
'courses':0,
'radio_yesno': 0,
'boolean': 0,
'null_boolean': 0,
'instructions': 0
};
var currElemType, currElemIndex, optionCount=1, formTitle="Form",$prevField, $currField, secCount=1, $currSection, pageCount=1, $currPage, disabled_fields=[];
var perms={};
$j(document).ready(function() {
//Assigning event handlers
$j('#button_add').on("click", function(){insertField($j('#elem_selector').val())});
$j('#submit').on("click", submit);
$j('#input_form_title').on('change', updateTitle);
$j('#input_form_description').on('change', updateDesc);
$j('#id_main_perm').on("change", onChangeMainPerm);
$j('#id_prog_belong').on("change", onChangeProgBelong);
$j('#links_id_main').on("change", onChangeMainLink);
$j('#links_id_specify').on("change", onChangeLinksSpecify);
$j('#links_id_pick').on("change", onChangeLinksProgram);
$j('#links_id_tl').on("change", onChangeLinksTL);
$j('#id_modify').on("change", function(){
if($j(this).prop('checked'))
$j('#submit').val('Modify Form');
else $j('#submit').val('Create Form');
});
$j('#cat_selector').on("change", function(){onSelectCategory($j(this).val());});
$j('#elem_selector').on("change", function(){onSelectElem($j('#elem_selector').val());});
$j('#main_cat_spec').on("change", onChangeMainCatSpec);
$j('#id_perm_program').on("change", onChangePermProg);
$j('#base_form').on("change", onChangeBase);
$currSection=$j('#section_0');
$currPage=$j('#page_0');
// Make the initial section editable
$j('#section_0').parent().on("mouseover", function(e) {
if($j(e.target).is('.outline, .outline > hr, .section, .section_header, .section_text, .section_button')){
if($j(this).hasClass('field_selected'))
return;
$j(this).addClass('field_hover');
$j(this).children(".wrapper_button").addClass("wrapper_button_hover");
}
}).on("mouseout", function() {
if($j(this).hasClass('field_selected'))
return;
$j(this).removeClass('field_hover');
$j(this).children(".wrapper_button").removeClass("wrapper_button_hover");
}).clicktoggle(function(){onSelectField($j(this), $j.data(this, 'data'));}, function(){deSelectField($j(this));});
$j('#section_0').parent().data('data', {attrs: {}, field_type: 'section', question_text: 'Section', help_text: 'Enter a short description about the section', parent_id:-1});
$j('.wrapper_button').on("click", function(e){removeField($j(this)); e.stopPropagation();});
// Make the initial page selectable
$j("#page_0").on("mouseover", function(e) {
if($j(e.target).is('.form_preview, .preview_button')){
if($j(this).hasClass('field_selected'))
return;
$j(this).addClass('field_hover');
$j(this).children(".wrapper_button").addClass("wrapper_button_hover");
}
}).on("mouseout", function() {
if($j(this).hasClass('field_selected'))
return;
$j(this).removeClass('field_hover');
$j(this).children(".wrapper_button").removeClass("wrapper_button_hover");
}).on("click", function(){
$j('.form_preview').removeClass('page_selected');
$currPage=$j(this);
$currPage.addClass('page_selected');
// If the current section is in another section, switch to the first section in this page
if(!$currPage[0].contains($currSection[0])){
$currSection=$currPage.find(".section:first");
$j('.outline').removeClass('section_selected');
$currSection.parent().addClass('section_selected');
}
// If the currently selected field
if($currField && !$currPage[0].contains($currField[0])){
var $field=$currField;
$field.trigger("click");
$field.removeClass('field_hover');
$field.children(".wrapper_button").removeClass("wrapper_button_hover");
}
});
//csrf stuff
$j(document).ajaxSend(function(event, xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function sameOrigin(url) {
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
// or any other URL that isn't scheme relative or absolute i.e relative.
!(/^(\/\/|http:|https:).*/.test(url));
}
function safeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
xhr.setRequestHeader("X-CSRFToken", getCookie('esp_csrftoken'));
}
});
//end of csrf stuff
$j('#form_toolbox').accordion({heightStyle:'content', icons:{}, collapsible: true});
$j.data($currPage[0], 'data', {'parent_id':-1});
//Getting field information from server, and constructing the form-builder
constructBuilder();
//Initializing UI
//initUI();
if(edit_form != -1){
$j("#base_form").val(edit_form).trigger("change");
createFromBase();
$j("#create_text").html("Modifying existing form:");
$j("#base_form").prop('disabled', true);
$j("#create_from_base").hide();
$j("#id_modify").prop('checked', true).trigger("change");
}
});
var getFieldCategory=function(field_type) {
//Returns the category for this field
var cat="";
$j.each(formElements, function(category, fields){
if(field_type in fields){
cat=category;
return false; //break out
}
});
return cat;
}
var constructBuilder = function(){
//Constructs the form builder with field information from the server
$j.ajax({
url:'/customforms/builddata/',
type:'GET',
dataType:'json',
async:false,
success: function(field_data) {
only_fkey_models.push.apply(only_fkey_models, field_data['only_fkey_models']);
//Putting in link fields
$j.each(field_data['link_fields'], function(category, fields){
formElements[category]={};
model_instance_cache[category]={'options':{}, 'selected_inst':"-1", 'selected_cat':'-1'};
$j.extend(formElements[category], fields);
});
initUI();
}
});
};
var clearCatOptions=function() {
$j('#cat_instance_sel').html('').hide();
$j('#cat_spec_options').hide();
};
var initUI=function(){
//Sets up the initial options
var options_html="";
//Generating options for the category selector
$j.each(formElements,function(idx,el){
if(!$j.isEmptyObject(el))
options_html+="<option value="+idx+">"+idx+"</option>";
});
$j('#cat_selector').html(options_html);
//Putting in options for the "Links" tab
options_html='<option value="-1">None</option>';
$j.each(only_fkey_models, function(idx, el){
options_html+="<option value="+el+">"+el+"</option>";
});
$j('#links_id_main').html(options_html);
onSelectCategory('Generic');
onSelectElem('textField');
perms={};
clearPermsArea();
$j('#id_modify_wrapper').hide();
clearLinksArea();
clearCatOptions();
};
var clearPermsArea=function(){
//Initializes the permissions area
$j('#id_prog_belong').prop('checked', false).parent().hide();
$j('#id_perm_program').val("-1").hide();
$j('#id_sub_perm').children().remove();
$j('#id_sub_perm').parent().hide();
};
var clearLinksArea=function(){
//Clears up the links area
$j('#links_id_specify').val('userdef').parent().hide();
$j('#links_id_pick').empty().parent().hide();
$j('#links_id_tl').parent().hide();
$j('#links_id_module').empty().parent().hide();
};
var onChangeMainLink=function(){
clearLinksArea();
if($j('#links_id_main').val()!='-1')
$j('#links_id_specify').parent().show();
else $j('#links_id_specify').parent().hide();
};
var onChangeLinksSpecify=function(){
if($j('#links_id_specify').val()=='particular'){
$j.ajax({
url:'/customforms/getlinks/',
data:{'link_model':$j('#links_id_main').val()},
type:'GET',
dataType:'json',
async:false,
success: function(link_objects) {
var html_str='';
$j.each(link_objects, function(idx, data){
html_str+='<option value="'+data.id+'">'+data.name+'</option>';
});
$j('#links_id_pick').html(html_str);
$j('#links_id_pick').change().parent().show();
if($j("#links_id_main").val()=="Program"){
$j('#links_id_tl').parent().show();
$j('#links_id_module').parent().show();
}
}
});
}
else{
$j('#links_id_pick').html('');
$j('#links_id_pick').parent().hide();
$j('#links_id_tl').parent().hide();
$j('#links_id_module').html('');
$j('#links_id_module').parent().hide();
}
};
var onChangeLinksProgram=function(){
$j.ajax({
url:'/customforms/getmodules/',
data:{'program':$j('#links_id_pick').val()},
type:'GET',
dataType:'json',
async:false,
success: function(mods) {
modules = mods;
onChangeLinksTL();
}
});
}
var onChangeLinksTL=function(){
var html_str='';
if(modules[$j('#links_id_tl').val()].length > 0){
$j.each(modules[$j('#links_id_tl').val()], function(id, tup){
html_str+='<option value="'+tup[0]+'">'+tup[1]+'</option>';
});
$j('#links_id_module').html(html_str);
$j('#links_id_module_help_text').hide();
} else {
if($j('#links_id_tl').val() == 'learn'){
html_str = 'You must enable the Student Custom Form module first.';
} else {
html_str = 'You must enable the Teacher Custom Form and/or Teacher Logistics Quiz module(s) first.';
}
$j('#links_id_module').empty();
$j('#links_id_module_help_text').html(html_str).show();
}
}
var getPerms=function(prog_id){
//Queries the server for perms related to the currently selected program
if(prog_id!="-1"){
$j.ajax({
url:'/customforms/getperms/',
data:{'prog_id':prog_id},
type:'GET',
dataType:'json',
async:false,
success: function(retval) {
//console.log(retval);
perms=retval;
populatePerms(perms);
}
});
}
else perms={};
};
var setPerms=function(){
//Sets the permission options based on selected values
var prog_id=$j('#id_perm_program').val();
if(prog_id=="-1")
return;
if($j.isEmptyObject(perms))
getPerms(prog_id);
else populatePerms(perms);
};
var populatePerms=function(perm_opts){
var options=[], main_perm, options_string='';
main_perm=$j('#id_main_perm').val();
if(main_perm!="none"){
if(main_perm=='Teacher') options=perm_opts['teachers'];
else if(main_perm=='Student') options=perm_opts['students'];
$j.each(options, function(idx, el){
options_string+='<option value='+el[0]+'>'+el[1]+'</option>';
});
$j('#id_sub_perm').html(options_string).parent().show();
}
};
var onChangeMainPerm=function(){
clearPermsArea();
var main_perm=$j(this).val();
if(main_perm!='none'){
$j('#id_prog_belong').parent().show();
}
};
var onChangeProgBelong=function(){
var belongs=$j(this).prop('checked');
if(belongs){
$j('#id_perm_program').show();
}
else {
$j('#id_sub_perm').parent().hide();
$j('#id_perm_program').val("-1").hide();
}
};
var onChangePermProg=function(){
var prog=$j('#id_perm_program');
if(prog!="-1"){
setPerms();
$j('#id_sub_perm').parent().show();
}
else
$j('#id_sub_perm').parent().hide();
};
var onChangeMainCatSpec=function() {
//Fetches instances from the server, populates values etc.
//Used to set up options for non-generic categories
$j("#cat_instance_sel").html('');
var main_cat_spec=$j("#main_cat_spec").val(), curr_category=$j("#cat_selector").val(), options_html="";
if(main_cat_spec != "automatic") {
if($j.isEmptyObject(model_instance_cache[curr_category]['options'])){
//Fetch values from the server, and store in the cache
$j.ajax({
url:'/customforms/getlinks/',
data:{'link_model':curr_category},
type:'GET',
dataType:'json',
async:false,
success: function(link_objects) {
$j.each(link_objects, function(idx, data){
model_instance_cache[curr_category]['options'][data.id]=data.name;
});
}
});
}
//Set options from the cache
$j.each(model_instance_cache[curr_category]['options'], function(idx, el){
options_html+="<option value="+idx+">"+el+"</option>";
});
$j("#cat_instance_sel").html(options_html);
//If this option has been set previously, fetch it from the cache and set it
if(model_instance_cache[curr_category]['selected_inst'] != "-1")
$j("#cat_instance_sel").val(model_instance_cache[curr_category]['selected_inst']);
//Show the instance selector
$j("#cat_instance_sel").show();
}
else
$j("#cat_instance_sel").hide();
};
var createLabel=function(labeltext, required, help_text) {
//Returns an HTML-formatted label, with a red * if the question is required
var str='';
str+='<div class="field_label">'+labeltext;
if(!([':','?','.','!'].includes(labeltext.charAt(labeltext.length - 1))))
str+=':';
if(required) str+='<span class="asterisk">'+'*'+'</span>';
str+='</div>';
if(help_text) str+=' <img src="/media/default_images/question_mark.jpg" class="qmark" title="' + help_text + '">'
str+='<br>';
return str;
};
var removeField = function(field) {
//removes the selected element from the form by performing .remove() on the wrapper div
if(field.parent().hasClass('field_selected')){
deSelectField(field.parent());
}
if(field.parent().hasClass('outline')){
//Never remove the last section of a page
if(field.parent().siblings('.outline').length == 0){
alert("You can't delete the only section of this page!");
return;
}
}
if(field.parent().hasClass('form_preview')){
//Never remove the last page
if($j('.form_preview').length == 1){
alert("You can't delete the only page of this form!");
return;
}
//If it's a page, remove the page-break text as well
field.parent().prev().remove();
}
field.parent().remove();
};
var addOption=function(option_text, field_type, correct=false) {
//adds an option in the form toolbox
var $option,$wrap_option;
$wrap_option=$j('<div></div>').addClass('option_element');
// Add radio buttons and checkboxes to indicate correct answers
if(['radio', 'dropdown', 'multiselect', 'checkboxes'].includes(field_type)){
var correct_answer = $j('<input>',{type:'checkbox', name: field_type + '_correct_answer', checked: correct, title: "Correct answer?"});
if(field_type == 'radio' || field_type == 'dropdown'){
correct_answer.on("click", function() {
if(this.checked){
$j('[name=' + field_type + '_correct_answer]').not($j(this)).prop('checked', false);
}
});
}
correct_answer.appendTo($wrap_option);
}
$option=$j('<input>').attr({
type:"text",
value:option_text
});
$option.appendTo($wrap_option);
$j('<input>',{type:'button',value:'+'}).on("click", function(){addOption('', field_type)}).appendTo($wrap_option);
$j('<input>',{type:'button',value:'-'}).on("click", removeOption).appendTo($wrap_option);
$wrap_option.appendTo($j('#multi_options'));
};
var removeOption=function() {
//removes an option from the radio group, but never remove the last option
if($j('#multi_options').children(".option_element").length > 1){
$j(this).parent().remove();
}
};
var generateOptions=function(field_type) {
//Generates the options input fields for multi-select form fields
for(i=1;i<=3;i++) {
addOption('', field_type);
}
};
var getFirst=function(category){
//returns some item corresponding to category
var retval="";
$j.each(formElements[category], function(idx, el){retval=idx; return false;});
return retval;
};
var showCategorySpecificOptions=function(category){
//Shows options related to the current category.
//For instance, for linked fields, it shows options for selecting the queryset.
clearCatOptions();
// Don't show anything unless the selected category came from a linked model
for (var c in default_categories)
{
if (default_categories[c] == category)
return;
}
//Show the category-specific options
$j('#cat_spec_options').show();
//Set any-predefined values
if(category in model_instance_cache){
if(model_instance_cache[category]['selected_cat']!="-1"){
$j('#main_cat_spec').val(model_instance_cache[category]['selected_cat']);
onChangeMainCatSpec();
}
}
};
var populateFieldsSelector=function(category){
//Populates the Field selector with the appropriate form fields
var fields_list=formElements[category], options_html="";
if(fields_list.length == 0)
return;
//Generating Options list
$j.each(fields_list, function(index,elem){
var disp_name="";
if(category!="Generic" && elem['required'])
disp_name=elem['disp_name']+"**";
else disp_name=elem['disp_name'];
options_html+="<option value="+index;
if(disabled_fields.includes(index))
options_html+=' disabled style="color: lightgrey"';
options_html+=">"+disp_name+"</option>";
});
//Populating options for the Field Selector
$j("#elem_selector").html(options_html);
};
var onSelectCategory=function(category) {
//Handles selection of a particular category
populateFieldsSelector(category);
//'Initializing' form builder with first field element
onSelectElem(getFirst(category));
showCategorySpecificOptions(category);
};
var clearSpecificOptions=function() {
//Removes previous field-specific options, if any
var $multi_options=$j('#multi_options'),$other_options=$j('#other_options');
if($multi_options.children().length!=0)
$multi_options.empty();
if($other_options.children().length!=0)
$other_options.empty();
};
var addSpecificOptions=function(elem, options) {
//Adds in specific options for some fields
var limits, frag, $div;
if(elem=='numeric'){
if(options && options!='')
limits=options.split(',');
else limits=[0,10];
frag='<div class="toolboxText">';
frag+='<p>Min <input type="number" id="id_minVal" value="'+limits[0]+'">';
frag+=' Max <input type="number" id="id_maxVal" value="'+limits[1]+'">';
frag+='</p></div>';
$div=$j(frag);
$div.appendTo($j('#other_options'));
}
else if(elem=='textField' || elem=='longTextField' || elem=='longAns' || elem=='reallyLongAns'){
if(options && options!=''){
limits=options.split(',');
} else if(elem=='textField'){
limits=[0,30];
} else if(elem=='longTextField'){
limits=[0,60];
} else {
limits=['',''];
}
frag='<div id="text_limits" class="toolboxText">';
frag+='Characters';
frag+='<p>Min <input type="number" id="text_min"';
var limit_min, limit_max;
if(elem=='textField'){
frag+='min="0" max="30"';
limit_min = Math.min(30, limits[0]);
limit_max = Math.min(30, limits[1]);
} else if(elem=='longTextField'){
frag+='min="0" max="60"';
limit_min = Math.min(60, limits[0]);
limit_max = Math.min(60, limits[1]);
} else {
limit_min = limits[0];
limit_max = limits[1];
}
frag+=' value="'+limit_min+'"> ';
frag+='Max <input type="number" id="text_max"';
if(elem=='textField'){
frag+='min="0" max="30"';
} else if(elem=='longTextField'){
frag+='min="0" max="60"';
}
frag+=' value="'+limit_max+'"></p>';
frag+='</div>';
var $div=$j(frag);
$div.appendTo($j('#other_options'));
}
};
var addCorrectnessOptions = function(elem) {
/* Display a field that lets the form author specify a "correct" answer
for supported field types */
// TODO: Convert the correct answer selector into a replica of the field
// that the user will see. For now, they have to know kung fu.
if (elem == 'dropdown')
{
frag = '<div id="dropdown_correctness_options" class="toolboxText">';
frag += '<p>(select checkbox above for correct answer)</p></div>';
var $div = $j(frag);
$div.appendTo($j('#other_options'));
}
else if (elem == 'radio')
{
frag = '<div id="radio_correctness_options" class="toolboxText">';
frag += '<p>(select checkbox above for correct answer)</p></div>';
var $div = $j(frag);
$div.appendTo($j('#other_options'));
}
else if (['textField', 'longTextField'].includes(elem))
{
frag = '<div id="' + elem + '_correctness_options" class="toolboxText">';
frag += '<p>Correct answer:<br>';
frag += '<input type="text" id="' + elem + '_correct_answer" value="">';
frag += '</p></div>';
var $div = $j(frag);
$div.appendTo($j('#other_options'));
}
else if (['longAns', 'reallyLongAns'].includes(elem))
{
frag = '<div id="' + elem + '_correctness_options" class="toolboxText">';
frag += '<p>Correct answer:<br>';
frag += '<textarea id="' + elem + '_correct_answer" value=""></textarea>';
frag += '</p></div>';
var $div = $j(frag);
$div.appendTo($j('#other_options'));
}
else if (elem == 'numeric')
{
frag = '<div id="numeric_correctness_options" class="toolboxText">';
frag += '<p>Correct answer:<br>';
frag += '<input type="number" id="numeric_correct_answer" value="">';
frag += '</p></div>';
var $div = $j(frag);
$div.appendTo($j('#other_options'));
}
else if (elem == 'checkboxes')
{
frag = '<div id="checkboxes_correctness_options" class="toolboxText">';
frag += '<p>(select checkbox(es) above for correct answer(s))</p></div>';
var $div = $j(frag);
$div.appendTo($j('#other_options'));
}
else if (elem == 'multiselect')
{
frag = '<div id="multiselect_correctness_options" class="toolboxText">';
frag += '<p>(select checkbox(es) above for correct answer(s))</p></div>';
var $div = $j(frag);
$div.appendTo($j('#other_options'));
}
else if (elem == 'radio_yesno')
{
frag = '<div id="radio_yesno_correctness_options" class="toolboxText">';
frag += '<p>Correct answer:<br>';
frag += '<select id="radio_yesno_correct_answer">'
frag += '<option value=""></option>'
frag += '<option value="T">Yes</option>'
frag += '<option value="F">No</option>'
frag += '</select></p></div>';
var $div = $j(frag);
$div.appendTo($j('#other_options'));
}
else if (elem == 'null_boolean')
{
frag = '<div id="null_boolean_correctness_options" class="toolboxText">';
frag += '<p>Correct answer:<br>';
frag += '<select id="null_boolean_correct_answer">'
frag += '<option value=""></option>'
frag += '<option value="Unknown">Unknown</option>'
frag += '<option value="Yes">Yes</option>'
frag += '<option value="No">No</option>'
frag += '</select></p></div>';
var $div = $j(frag);
$div.appendTo($j('#other_options'));
}
else if (elem == 'date')
{
frag = '<div id="' + elem + '_correctness_options" class="toolboxText">';
frag += '<p>Correct answer:<br>';
frag += '<input type="' + elem + '" id="' + elem + '_correct_answer" value="">';
frag += '</p></div>';
var $div = $j(frag);
$div.appendTo($j('#other_options'));
}
else if (elem == 'time')
{
frag = '<div id="' + elem + '_correctness_options" class="toolboxText">';
frag += '<p>Correct answer (HH:MM in 24-hour time):<br>';
frag += '<input type="text" id="' + elem + '_correct_answer" value="">';
frag += '</p></div>';
var $div = $j(frag);
$div.appendTo($j('#other_options'));
}
}
var onSelectElem = function(item) {
//Generates the properties fields when a form item is selected from the list
//Remove previous field-specific options, if any
clearSpecificOptions();
$j('#id_instructions').val('');
$j('#id_required').prop('checked','');
if($j('div.field_selected').length){
onSelectField($j('div.field_selected'), $j.data($j('div.field_selected')[0], 'data'), item);
} else {
var currCategory=$j('#cat_selector').val();
var $option,$wrap_option,i, question_text=formElements[currCategory][item]['ques'], $button=$j('#button_add');
//Defining actions for generic elements
if(item=='textField' || item=='longTextField' || item=='longAns' || item=='reallyLongAns')
addSpecificOptions(item, '');
else if(item=="radio" || item=="dropdown" || item=="multiselect" || item=="checkboxes")
generateOptions(item);
else if(item=="numeric")
addSpecificOptions(item, '');
else if(item=='section'){
$j('#id_instructions').val('Enter a short description about the section');
}
else if(item=='page'){
$j('#id_instructions').val('Enter a short description about the section');
}
// Add validation options
if (item in formElements['Generic'])
{
addCorrectnessOptions(item);
}
//Set 'Required' to a sensible default
setRequired(item);
$j('#id_question').val(question_text);
$prevField=$currSection.children(":last");
if($button.val()!='Add to Form')
$button.val('Add to Form').html('Add Field to Form').off('click').on("click", function(){insertField($j('#elem_selector').val())});
}
};
var setRequired=function(item){
//Sets the 'Required' option according to item
$j('#id_required').attr('disabled', false);
$j('.toolboxText').show();
//For 'section' and 'page', disable 'Required'
if(item=='page' || item=='section' || item in formElements['NotReallyFields']){
$j('#id_required').attr('disabled', true);
$j('.toolboxText').hide();
}
//Set 'Required' as checked for custom fields that are required on the model
if(!(item in formElements['Generic'])){
//Get the options for this item, and set 'Required' accordingly
$j.each(formElements, function(cat, flds){
if(item in flds){
if(flds[item]['required'])
$j('#id_required').prop('checked', true).attr('disabled', true);
return false; //break out
}
});
}
};
var updateField=function() {
var curr_field_type=$j.data($currField[0],'data').field_type;
var field_type=$j('#elem_selector')[0].value;
var curr_field_id=$j.data($currField[0],'data').parent_id;
if(curr_field_type=='section' && field_type=='section'){
var $field_data = $currField.data('data')
$field_data.question_text = $j('#id_question').val()
$currField.find('h2').html($j('#id_question').val());
$field_data.help_text = $j('#id_instructions').val()
$currField.children('p.field_text').html($j('#id_instructions').val());
$currField.data('data', $field_data);
return;
}
$prevField=$currField.prev();
$currField.remove();
$currField=addElement(field_type,$prevField);
$currField.trigger("click");
$j.data($currField[0],'data').parent_id = curr_field_id;
};
var onSelectField=function($elem, field_data, ftype=null) {
/*
Handles clicks on field wrappers.
Also called by rebuild(..) to recreate a form from metadata
*/
//Open the field panel if not already open
$j('#header_fields.ui-accordion-header-collapsed').trigger("click");
//De-selecting any previously selected field
if($j('div.field_selected').length == 0 || !$elem.hasClass('field_selected')){
var $divs = $j('div.field_selected');
$divs.trigger("click");
$divs.removeClass('field_hover');
$divs.children(".wrapper_button").removeClass("wrapper_button_hover");
}
clearSpecificOptions();
var $wrap=$elem, $button=$j('#button_add'), options;
if(ftype == null) ftype=field_data.field_type;
//Select the current field and category in the field and category selectors
if(ftype in formElements['Generic']){
$j('#cat_selector').val('Generic');
// Don't allow changing a field into a page or section (instructions are ok, though)
disabled_fields=['page', 'section'];
populateFieldsSelector('Generic');
$j('#elem_selector').val(ftype);
}
else if(ftype in formElements['Personal']){
$j('#cat_selector').val('Personal');
populateFieldsSelector('Personal');
$j('#elem_selector').val(ftype);
}
else {
//link field
var curr_cat=getFieldCategory(ftype);
$j('#cat_selector').val(curr_cat);
populateFieldsSelector(curr_cat);
$j('#elem_selector').val(ftype);
showCategorySpecificOptions(curr_cat);
}
// Don't allow changing sections or pages to other field types
if(['section','page'].includes(ftype)){
$j('#cat_selector').prop('disabled', true);;
$j('#elem_selector').prop('disabled', true);;
}
if($wrap.length !=0){
$wrap.removeClass('field_hover').addClass('field_selected');
$wrap.children('.wrapper_button').addClass('wrapper_button_hover');
$currField=$wrap;
if($currField.hasClass('outline')){
$currSection=$currField.find('.section');
$j('.outline').removeClass('section_selected');
$currField.addClass('section_selected');
} else {
$currSection=$wrap.parent('.section');
$j('.outline').removeClass('section_selected');
$currSection.parent().addClass('section_selected');
}
$currPage=$currField.parents('.form_preview');
$j('.form_preview').removeClass('page_selected');
$currPage.addClass('page_selected');
$prevField=$wrap.prev('div.field_wrapper');
}
if(ftype!='section')
$j("#id_required").prop('checked',field_data.required);