liuyn
2024-03-11 a87f1c3df03078814ee97ad0c8ac200a232419e9
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
global virtual with sharing class SurveyAndQuestionController{// extends SurveyAndQuestionController{
  
    public List<SelectOption> questionTypeOptions { get; set; }
    
    public String  showBasicValues                { get; set; }
    public String  showSingleSelect               { get; set; }
    public String  showSingleSelectPreview        { get; set; }
    public String  showMultiSelect                { get; set; }
    public String  showMultiSelectPreview         { get; set; }
    public String  showFreeText                   { get; set; }
    public String  showFreeTextPreview            { get; set; }
    public String  showRowQuestion                { get; set; }
    public String  showRowQuestionPreview         { get; set; }
    public String  showSingleText                 { get; set; }
    public String  showSingleTextPreview          { get; set; }
    public String  showPicklist                   { get; set; }
    public String  showPicklistPreview            { get; set; }
    public String  showScale                      { get; set; }
    public String  showScalePreview               { get; set; }
    public String  showMail                       { get; set; }
    public String  showMailPreview                { get; set; }
    public String  showPhone                      { get; set; }
    public String  showPhonePreview               { get; set; }
    public String  showSelectQuestionType         { get; set; }
    
    public List<SelectOption> singleOptions       { get; set; }
    public List<SelectOption> multiOptions        { get; set; }
    public List<SelectOption> rowOptions          { get; set; }
    public List<SelectOption> pickOptions         { get; set; }
    public List<SelectOption> scaleOptions        { get; set; }
    
    public String  questionReference              { get; set; }
    public String  reportId                       { get; set; }
    private Boolean saveAndNew;
    private String  surveyRef;
    private String surveyOrderNumber;
    private Survey_Question__c questionToUpdate;
    /***/
    public String  qQuestion                      { get; set; }
    public Boolean qRequired                      { get; set; }
    public String  qChoices                       { get; set; }
    public String  qMinLabel                      { get; set; }
    public String  qMaxLabel                      { get; set; }
    
    public String surveyName                  { get; set; }
    public String surveyHeader                { get; set; }
    public String surveyId                    { get; set; }
    public String renderSurveyPreview         { get; set; }
    public String questionName                { get; set; }
    public String questionType                { get; set; }
    public Boolean questionRequired           { get; set; }
    public List<question> allQuestions        { get; set; }
    public List<String> responses             { get; set; }
    public Integer allQuestionsSize           { get; set; }
    public String  templateURL                { get; set; }
    public String  surveyThankYouText         { get; set; }
    public String  surveyThankYouURL          { get; set; }
    public String  caseId                     { get; set; }
    public List<String> newOrder {get;set;}
    public String newOrderW {get;set;}
  
    public  SurveyAndQuestionController (ApexPages.StandardController stdController) {
        /**/
        // Get url parameters
        surveyId = Apexpages.currentPage().getParameters().get('id');
        caseId   = Apexpages.currentPage().getParameters().get('caId');
        newOrder = new List<String>();
        if (caseId == null || caseId.length() < 5) {
            caseId = 'none';
        }
        // By default the preview is not showing up
        renderSurveyPreview = 'false';
    
        if (surveyId != null) { 
            // Retrieve all necessary information to be displayed on the page
            allQuestions = new List<question>();
            setSurveyNameAndThankYou(surveyId);
        }
        /**/
        surveyRef = surveyId;
        setupQuestionTypeOptions();
        resetViewsToFalse(true);
        showSelectQuestionType = 'False';
        ReportFinderUtil rfu = new ReportFinderUtil();
        reportId = rfu.findReportId('Survey with Questions and Responses');
    }
  
    //test constructor and calls within it
    private static TestMethod void testCreateQuestionController() {
        SurveyTestingUtil tu = new SurveyTestingUtil();
        Apexpages.currentPage().getParameters().put('id',tu.surveyId);
        Apexpages.Standardcontroller std;
        SurveyAndQuestionController cqc = new SurveyAndQuestionController(std);
        cqc.addQuestion();
        cqc.getNewQuestionNum();
        cqc.makeNewQuestionLink();
        System.assert(cqc.surveyId == tu.surveyId);
    }
 
    //if you are using a developement org you will need to manually add your Pod.
    /* legacy
    public Pagereference updateUrl(){
      Survey__c survey = [select Name, Id, URL__c from Survey__c where id = :surveyId];  
      Site subSite = [select Subdomain, id from Site limit 1];
      if(survey.URL__c.contains(subSite.Subdomain))
        return null;
      else
        return updateDomain(survey, subSite);
    }
    */
    /*
    legacy
    private Pagereference updateDomain(Survey__c survey, Site subSite){
      String surveyUrl = survey.URL__c;
      String subdomainReplace = 'http://'+subSite.Subdomain;
      //surveyUrl = surveyUrl.replaceFirst('*.', subdomainReplace);
      surveyUrl = surveyUrl.substring(surveyUrl.indexOf('.'), surveyUrl.length());
      surveyUrl = subdomainReplace + surveyUrl;
      try{
          survey.URL__c = surveyUrl;
          update survey;
      }catch(Exception e){
          system.debug(e);
      }
      setSurveyNameAndThankYou(surveyId);
      return null;
    }
    */
 
    public Pagereference makeNewQuestionLink() {
        questionReference = null;
        resetViewsToFalse(true);
        return null;
    }
 
    public Pagereference editQuestion() {
system.debug('questionReference:'+questionReference);
        if (questionReference == null)
            return null;
        setupEditQuestion();
        showSelectQuestionType = 'True';
        return null;
    }
 
    public Pagereference addQuestion() {
        showSelectQuestionType = 'True';
        resetViewsToFalse(true);
        return null;
    }
 
    private void setupEditQuestion() {
        questionToUpdate = 
                [Select Type__c, Question__c, Id, Choices__c, Required__c, 
                        OrderNumber__c, Survey__c, Name, MinLabel__c, MaxLabel__c
                   From Survey_Question__c 
                  where Id = :questionReference];
        questionType = questionToUpdate.Type__c;
        setupQuestionFields();
        setupEditFields(questionToUpdate);
    }
 
    private void setupEditFields(Survey_Question__c q) {
        qQuestion = q.Question__c;
        qRequired = q.Required__c;
        qChoices = q.Choices__c;
        qMinLabel = q.MinLabel__c;
        qMaxLabel = q.MaxLabel__c;
        surveyRef = q.Survey__c;
    }
 
    private void setupQuestionTypeOptions() {
        
        //get picklist values
        Schema.DescribeFieldResult fieldResult = Survey_Question__c.Type__c.getDescribe();
        List<Schema.PicklistEntry>  ple = fieldResult.getPicklistValues();
        
        //set/add them to selectOption list
        questionTypeOptions = new List<SelectOption>();
        questionTypeOptions.add(new SelectOption('', System.Label.LABS_SF_SELECTTYPE));
        for(Schema.PicklistEntry pe: ple) {
            questionTypeOptions.add(new SelectOption(pe.getLabel(), pe.getValue()));
        }
    }
 
    //test constructor and calls within it
    private static TestMethod void testEditQuestion() {
        SurveyTestingUtil tu = new SurveyTestingUtil();
        Apexpages.currentPage().getParameters().put('id',tu.surveyId);
        Apexpages.Standardcontroller std;
        SurveyAndQuestionController cqc = new SurveyAndQuestionController(std);
        cqc.editQuestion();
        cqc.questionReference = tu.questionIds[0];
        cqc.editQuestion();
        cqc.questionReference = tu.questionIds[1];
        cqc.editQuestion();
        cqc.questionReference = tu.questionIds[2];
        cqc.editQuestion();
        cqc.questionReference = tu.questionIds[3];
        System.assert(cqc.editQuestion()==null);
        
    }
    
    private void resetViewsToFalse(Boolean clearFields){
        showSingleSelect =        'False';
        showSingleSelectPreview = 'False';
        showMultiSelect =         'False';
        showMultiSelectPreview=   'False';
        showFreeText =            'False';
        showFreeTextPreview =     'False';
        showRowQuestion =         'False';
        showRowQuestionPreview =  'False';
        showSingleText =          'False';
        showSingleTextPreview =   'False';
        showScale =               'False';
        showScalePreview =        'False';
        showPicklist =            'False';
        showPicklistPreview =     'False';
        showMail =                'False';
        showMailPreview =         'False';
        showPhone =               'False';
        showPhonePreview =        'False';
        
        qRequired =                true;
        if (clearFields) {
            qChoices =            '';
            qQuestion =           '';
            qMinLabel =           '';
            qMaxLabel =           '';
        }
    }
 
    public Pagereference setupQuestionFields() {
        resetViewsToFalse(true);
        if(questionType=='Multi-Select--Vertical'){
            showMultiSelect='True';
        }
        else if(questionType == 'Single Select--Vertical'){
            showSingleSelect = 'True';
        }
        else if(questionType == 'Free Text'){
            showFreeText = 'True';
        }
        else if(questionType == 'Single Select--Horizontal'){
            showRowQuestion = 'True';
        }
        else if(questionType == 'Single Text'){
            showSingleText = 'True';
        }
        else if(questionType == 'Scale'){
            showScale = 'True';
        }
        else if(questionType == 'Picklist'){
            showPicklist = 'True';
        }
        else if(questionType == 'Mail'){
            showMail = 'True';
        }
        else if(questionType == 'Phone'){
            showPhone = 'True';
        }
        return null;
    }
 
    public Pagereference saveAndNewQuestion(){
        saveAndNew = True;
        if(questionReference == null || questionReference.length() <5)
            return saveNewQuestion();
        else 
            return updateQuestion();
    }
 
    //test the saving of new questions
    private static TestMethod void testsaveAndNewQuestion(){
        SurveyTestingUtil tu = new SurveyTestingUtil();
        Apexpages.currentPage().getParameters().put('id',tu.surveyId);
        Apexpages.Standardcontroller std;
        SurveyAndQuestionController cqc = new SurveyAndQuestionController(std);
        //test saving new question
        cqc.qQuestion = 'THIS IS A NEW QUESTION';
        cqc.qChoices = '1\\n2\\n3\\3';
        cqc.qRequired=true;
        cqc.questionType='Single Select--Vertical';
        cqc.saveAndNewQuestion();
        System.assertEquals(5, cqc.getNewQuestionNum());
        //edit existing question
        SurveyAndQuestionController cqcI = new SurveyAndQuestionController(std);
        cqcI.questionReference = tu.questionIds[0];
        cqcI.editQuestion();
        cqcI.qQuestion = 'THIS IS A NEW QUESTION THAT IS EXTRA LONG SO THE NAME SHORTENING CALL WILL BE USED, THIS SHOULD BE LONG ENOUGH NOW THIS IS A NEW';
        cqcI.qChoices = '1\\n2\\n3\\3';
        cqcI.qRequired=true;
        cqcI.questionType='Single Select--Vertical';
        cqcI.saveAndNewQuestion();
        System.assertEquals(5, cqcI.getNewQuestionNum());
    }
 
    public Pagereference controllerSavQuestion(){
        if(questionReference == null || questionReference.length() <5){
            return saveNewQuestion();
        }
        else{ 
            return updateQuestion();
        }
    }
 
    private static TestMethod void testsavesaveQuestion(){
        SurveyTestingUtil tu = new SurveyTestingUtil();
        Apexpages.currentPage().getParameters().put('id',tu.surveyId);
        Apexpages.Standardcontroller std;
        SurveyAndQuestionController cqc = new SurveyAndQuestionController(std);
        //test saving new question
        cqc.qQuestion = 'THIS IS A NEW QUESTION';
        cqc.qChoices = '1\\n2\\n3\\3';
        cqc.qRequired=true;
        cqc.questionType='Single Select--Vertical';
        cqc.controllerSavQuestion();
        System.assertEquals(5, cqc.getNewQuestionNum());
        //edit existing question
        SurveyAndQuestionController cqcI = new SurveyAndQuestionController(std);
        cqcI.questionReference = tu.questionIds[0];
        cqcI.editQuestion();
        cqcI.qQuestion = 'THIS IS A NEW QUESTION THAT IS EXTRA LONG SO THE NAME SHORTENING CALL WILL BE USED, THIS SHOULD BE LONG ENOUGH NOW';
        cqcI.qChoices = '1\\n2\\n3\\3';
        cqcI.qRequired=true;
        cqcI.questionType='Single Select--Vertical';
        cqcI.controllerSavQuestion();
        System.assertEquals(5, cqcI.getNewQuestionNum());
    }
 
    private Pagereference updateQuestion(){
        //questionToUpdate is setup in an earlier call to editQuestion()
        questionToUpdate.Name = questionToName(qQuestion);
        questionToUpdate.Choices__c = qChoices;
        questionToUpdate.Required__c = qRequired;
        questionToUpdate.Type__c = questionType;
        questionToUpdate.Question__c = qQuestion;
        questionToUpdate.MinLabel__c = qMinLabel;
        questionToUpdate.MaxLabel__c = qMaxLabel;
        try{
            update questionToUpdate;
            resetViewsToFalse(true);
            deleteOldResponses(questionToUpdate.id);
            questionReference = null;
        }catch(Exception e){
            System.debug(e);
            Apexpages.addMessages(e);
        }
        
        return saveOrUpdateReturn();
    }
    
    private void deleteOldResponses(String qId){
        List <SurveyQuestionResponse__c> sResponses = [select id, Survey_Question__c from SurveyQuestionResponse__c where Survey_Question__c = :qId];
        if(sResponses != null)
         delete sResponses;
    }
    
    private Pagereference saveOrUpdateReturn(){
        setupQuestionList();
        Pagereference pr = new Pagereference('/apex/SurveyPage?id='+surveyRef);
        questionType = '';
        if(saveAndNew != null && saveAndNew == true){
            saveAndNew = False;
            showSelectQuestionType = 'True';
            return pr;
        }
        else{
            showSelectQuestionType = 'False';
            return pr; 
        }
    }
 
    private Integer getNewQuestionNum(){
        if(allQuestions == null)
         return 0;
        else{
         return allQuestions.size();
        }
    }
 
    private Pagereference saveNewQuestion(){ 
        Survey_Question__c newQuestion = new Survey_Question__c();
        newQuestion.Survey__c = surveyRef;
        newQuestion.Name = questionToName(qQuestion);
        newQuestion.Choices__c = qChoices;
        newQuestion.Required__c = qRequired;
        newQuestion.Type__c = questionType;
        newQuestion.OrderNumber__c = getNewQuestionNum();
        newQuestion.Question__c = qQuestion;
        newQuestion.MinLabel__c = qMinLabel;
        newQuestion.MaxLabel__c = qMaxLabel;
        resetViewsToFalse(true);
        try{
            insert newQuestion;
        }catch(Exception e){
            System.debug(e);
        }
        return saveOrUpdateReturn();
    }
    
    private String questionToName(String q){
        if(q.length()<75)
            return q;
        else
            return q.substring(0, 75)+'...';
    }
    
    public Pagereference previewQuestion() {
        if (questionType == 'Multi-Select--Vertical') {
            showMultiSelectPreview = 'True';
            multiOptions = stringToSelectOptions(qChoices);
        }
        else if(questionType == 'Single Select--Vertical'){
            showSingleSelectPreview = 'True';
            singleOptions = stringToSelectOptions(qChoices);
        }
        else if(questionType == 'Single Select--Horizontal'){
            showRowQuestionPreview = 'True';
            rowOptions = stringToSelectOptions(qChoices);
        }
        else if(questionType == 'Picklist'){
            showPicklistPreview = 'True';
            pickOptions = stringToSelectOptions(qChoices);
        }
        else if(questionType =='Free Text'){
            showFreeTextPreview = 'True';
        }
        else if(questionType == 'Single Text'){
            showSingleTextPreview = 'True';
        }
        else if(questionType == 'Scale'){
            showScalePreview = 'True';
            scaleOptions = stringToSelectOptions(qChoices);
        }
        else if(questionType == 'Mail'){
            showMailPreview = 'True';
        }
        else if(questionType == 'Phone'){
            showPhonePreview = 'True';
        }
        return null;
    }
 
 
     //test constructor and calls within it
    private static TestMethod void testPreviewQuestion(){
        SurveyTestingUtil tu = new SurveyTestingUtil();
        Apexpages.currentPage().getParameters().put('id',tu.surveyId);
        Apexpages.Standardcontroller std;
        SurveyAndQuestionController cqc = new SurveyAndQuestionController(std);
        
        cqc.questionReference = tu.questionIds[0];
        cqc.editQuestion();
        cqc.previewQuestion();
 
        cqc.questionReference = tu.questionIds[1];
        cqc.editQuestion();
        cqc.previewQuestion();
        
        cqc.questionReference = tu.questionIds[2];
        cqc.editQuestion();
        System.assert(cqc.previewQuestion()==null);
        
        cqc.questionReference = tu.questionIds[3];
        cqc.editQuestion();
        System.assert(cqc.previewQuestion()==null);
        
    }
 
    
    private List<SelectOption> stringToSelectOptions(String str){
        List<String> strList = str.split('\\r|\n');
        List<SelectOption> returnVal = new List<SelectOption>();
        for(String s: strList) {
            returnVal.add(new SelectOption(s, s));
        }
        return returnVal;
        
    }
/****/
 
    /* Called during the setup of the page. 
       Retrieve questions and responses from DB and inserts them in 2 lists. */
    public Integer setupQuestionList(){
        /*allQuestions.clear();
        List<Survey_Question__c> allQuestionsObject = 
                    [Select Type__c, Id, Survey__c, Required__c, 
                    Question__c, OrderNumber__c, Name, Choices__c
                    From Survey_Question__c  
                    WHERE Survey__c =: surveyId
                    order by OrderNumber__c];
        for (Survey_Question__c q : allQuestionsObject){
            question theQ = new question(q);
            allQuestions.add(theQ);
        }
        //responses = getResponses();//taken out because it was SOQL heavy//*/
        getAQuestion();
        return allQuestions.size();
    }
    
    
     /** Sets the survey's name variable
      *  param: sID The survey ID as specified in the DB
      */
    public void setSurveyNameAndThankYou(String sId){
        Survey__c s = [SELECT Name, Id, URL__c, thankYouText__c, thankYouLink__c, Survey_Header__c FROM Survey__c WHERE Id =:sId];
        surveyName = s.Name;
        surveyHeader = s.Survey_Header__c;
        templateURL = s.URL__c+'id='+sId;//+'&cId={!Contact.Id}'+'&caId='+'{!Case.id}';
        surveyThankYouText = s.thankYouText__c;
        surveyThankYouURL = s.thankYouLink__c;
    }
  
//------------------------------------------------------------------------------//   
    public Pagereference updateSurveyName(){
        Survey__c s = [SELECT Name, Id, URL__c, thankYouText__c, thankYouLink__c FROM Survey__c WHERE Id =:surveyId];
        s.Name = surveyName;
        try{
            update s;
        }catch (Exception e){
            Apexpages.addMessages(e);
        }
        return null;
    } 
    
    private static Testmethod void testUpdateSurveyName() {
        SurveyTestingUtil tu = new SurveyTestingUtil();
        Apexpages.currentPage().getParameters().put('id',tu.surveyId);  
        Apexpages.Standardcontroller stc; 
        SurveyAndQuestionController vsc = new SurveyAndQuestionController(stc);
        vsc.surveyName = 'new name';
        system.assert(vsc.updateSurveyName() == null);
    }
//------------------------------------------------------------------------------//    
    public Pagereference updateSurveyThankYouAndLink(){
        Survey__c s = [SELECT Name, Id, URL__c, thankYouText__c, thankYouLink__c FROM Survey__c WHERE Id =:surveyId];
        s.thankYouText__c = surveyThankYouText;
        s.thankYouLink__c = surveyThankYouURL;
        try{
            update s;
        }catch(Exception e){
            Apexpages.addMessages(e);
        }
        return null;
    }
    
    private static Testmethod void testupdateSurveyThankYouAndLink() {
        SurveyTestingUtil tu = new SurveyTestingUtil();
        Apexpages.currentPage().getParameters().put('id',tu.surveyId);    
        Apexpages.Standardcontroller stc; 
        SurveyAndQuestionController vsc = new SurveyAndQuestionController(stc);
        vsc.surveyThankYouText = 'new stuff';
        vsc.surveyThankYouURL = 'more new stff';
        system.assert(vsc.updateSurveyThankYouAndLink()==null);
    }
    
    public PageReference updateOrderList() {
        if (newOrderW.length() <= 0) {
            return null;
        }
        
        newOrderW = newOrderW.substring(0, newOrderW.length() -1);
        
        List<String> idsToUpdate = newOrderW.split(',',-1);
        List<Survey_Question__c> qsToUpdate = new List<Survey_Question__c>();
        
        Map<Id,Survey_Question__c> questionMap = new Map<Id,Survey_Question__c>([select Id, OrderNumber__c from Survey_Question__c where Id in :idsToUpdate]);
        Survey_Question__c sqToUpdate;
        
        for (Integer i = 0; i < idsToUpdate.size(); i++) {
            sqToUpdate = questionMap.get(idsToUpdate.get(i));
            sqToUpdate.OrderNumber__c = i;
            qsToUpdate.add(sqToUpdate);
        }
        update qsToUpdate;
        return null;
    }
 
//------------------------------------------------------------------------------//  
    /** When requested from the page - when the user clicks on 'Update Order' -
        this function will reorganize the list so that it is displayed in the new order
     */
    public Pagereference refreshQuestionList(){
        setupQuestionList();
        return null;
    }
 
//------------------------------------------------------------------------------//  
    private static Testmethod void testRefreshQuestionList() {
        SurveyTestingUtil tu = new SurveyTestingUtil();
        Apexpages.currentPage().getParameters().put('id',tu.surveyId);
        Apexpages.Standardcontroller stc; 
        SurveyAndQuestionController vsc = new SurveyAndQuestionController(stc);
        vsc.getAQuestion();
        
        // Retrieve questions for this survey
        List<Survey_Question__c> sq = new List<Survey_Question__c>();
        sq = [Select id, orderNumber__c from Survey_Question__c];
        
        // get question with orderNumber 1
        Survey_Question__c first = [Select id, orderNumber__c from Survey_Question__c Where orderNumber__c =: 1 and Survey__c =: tu.surveyId];
        System.assert(first.orderNumber__c == 1 );    
       
        // Specify the new order
        vsc.newOrderW = vsc.allQuestions[2].id + ',' +
        vsc.allQuestions[0].id + ',' +
        vsc.allQuestions[1].id + ',' +
        vsc.allQuestions[3].id + ',';
        
        vsc.updateOrderList();
              
        // Verify that the question with order 1 is not the same as the one retrieved previously
        Survey_Question__c second = [Select id, orderNumber__c from Survey_Question__c Where orderNumber__c =: 1 and Survey__c =: tu.surveyId];
        System.assert(second.id != first.id);
        
        // update the question list, and make sure it has been modified as well
        vsc.refreshQuestionList();
        System.assert(vsc.allQuestions[1].id != first.id);
    }
//------------------------------------------------------------------------------//    
 
 
//------------------------------------------------------------------------------//    
    /** Redirects the page that displays the detailed results of the survey, 
        from all users who took the survey.
     */
    public PageReference resultPage() {
        return new PageReference('/apex/ResultsPage?id='+surveyId);
    }
 
//------------------------------------------------------------------------------//      
    public Pagereference deleteRefresh(){
        if (questionReference!= null ) {
            Survey_Question__c sq = [Select Id, Name FROM Survey_Question__c WHERE Id =: questionReference];
            delete sq;  
            questionReference = null;  
        }
        allQuestions.clear();
        Double j = 0.0;
        List<Survey_Question__c> allQuestionsObject = 
                    [Select Type__c, Id, Survey__c, Required__c, 
                    Question__c, OrderNumber__c, Name, Choices__c, 
                    MinLabel__c, MaxLabel__c
                    From Survey_Question__c  
                    WHERE Survey__c =: surveyId
                    order by OrderNumber__c];
        for (Integer i =0; i< allQuestionsObject.size(); i++) {
            allQuestionsObject[i].OrderNumber__c= j;
            question theQ = new question(allQuestionsObject[i]);
            allQuestions.add(theQ);
            j = j + 1.0;
        }
        responses = getResponses();
        try {
            update allQuestionsObject;
        } catch(Exception e) {
            Apexpages.addMessages(e);
        }
        return saveOrUpdateReturn();
    }
 
//------------------------------------------------------------------------------//    
    private static TestMethod void testDeleteQuestion() {
        SurveyTestingUtil tu = new SurveyTestingUtil();
        Apexpages.currentPage().getParameters().put('id',tu.surveyId);
        Apexpages.Standardcontroller stc; 
        SurveyAndQuestionController vsc = new SurveyAndQuestionController(stc);
        
        
        // Get a question to delete
        Survey_Question__c sq = [Select id, orderNumber__c from Survey_Question__c Where orderNumber__c =: 1 and Survey__c =: tu.surveyId];
        vsc.questionReference = sq.Id;
        vsc.deleteRefresh();
        
        Survey_Question__c sq2 = [Select id, orderNumber__c from Survey_Question__c Where orderNumber__c =: 1 and Survey__c =: tu.surveyId];
        System.assert(sq.Id != sq2.Id);
    }
//------------------------------------------------------------------------------//  
 
//------------------------------------------------------------------------------//  
 
    /** 
     */
    public List<String> getResponses() {
        List<SurveyQuestionResponse__c> qr = [Select Survey_Question__c, SurveyTaker__c, Response__c, Name From SurveyQuestionResponse__c limit 100];
        List<String> resp = new List<String>();
        for (SurveyQuestionResponse__c r : qr) {
            resp.add(r.Response__c);
        }
        
        return resp;
    }
 
    /** Class: question
     *  Retrieves the question information and puts it in the question object
     */
    public class question{
        public String   name                   { get; set; }
        public String   id                     { get; set; }
        public String   question               { get; set; }
        public String   orderNumber            { get; set; }
        public String   choices                { get; set; }
        public String   minLabel               { get; set; }
        public String   maxLabel               { get; set; }
        public List<SelectOption> singleOptions{ get; set; }
        public List<SelectOption> multiOptions { get; set; }
        public List<SelectOption> rowOptions   { get; set; }
        public List<SelectOption> pickOptions  { get; set; }
        public List<SelectOption> scaleOptions { get; set; }
        public Boolean  required               { get; set; }
        public String   questionType           { get; set; }  
        public String   surveyName             { get; set; }
        public String   renderFreeText         { get; set; }
        public String   renderSelectRadio      { get; set; }
        public String   renderSelectCheckboxes { get; set; } 
        public String   renderSelectRow        { get; set; }
        public String   renderSingleText       { get; set; }
        public String   renderScale            { get; set; }
        public String   renderPickList         { get; set; }
        public String   renderMail             { get; set; }
        public String   renderPhone            { get; set; }
        public List<String> responses          { get; set; }
        //public String   singleOptionsForChart  { get; set; }
        public String   qResultsForChart       { get; set; } 
        public List<String> strList            { get; set; } // The question's option as a list of string
        public List<Integer> resultsCounts     { get; set; } // The count of each response to a question's choices
        public boolean  noData                 { get; set; }
      
        /** Fills up the question object
         *  param:  Survey_Question__c 
         */
        public question(Survey_Question__c sq) {
            name = sq.Name;
            id = sq.Id;
            System.debug('in Question found one with id '+id);
            question = sq.Question__c;
            orderNumber = String.valueOf(sq.OrderNumber__c+1);
            choices = sq.Choices__c;
            minLabel = sq.MinLabel__c;
            maxLabel = sq.MaxLabel__c;
            
            required = sq.Required__c;
            questionType = sq.Type__c;
            //singleOptionsForChart = ' ';
            clearAllRenderFlg();
            
            if (sq.Type__c == 'Multi-Select--Vertical') {
                renderSelectCheckboxes='true';
                multiOptions = stringToSelectOptions(choices, false);
            }
            else if (sq.Type__c == 'Single Select--Vertical') {
                renderSelectRadio='true';
                singleOptions = stringToSelectOptions(choices, false);
            }
            else if (sq.Type__c == 'Single Select--Horizontal') {
                renderSelectRow = 'true';
                rowOptions = stringToSelectOptions(choices, false);
            }
            else if (sq.Type__c == 'Picklist') {
                renderPicklist='true';
                pickOptions = stringToSelectOptions(choices, true);
            }
            else if (sq.Type__c == 'Free Text') {
                renderFreeText = 'true';
            }
            else if (sq.Type__c == 'Single Text') {
                renderSingleText = 'true';
            }
            else if (sq.Type__c == 'Scale') {
                renderScale = 'true';
                scaleOptions = stringToSelectOptions(choices, false);
            }
            else if (sq.Type__c == 'Mail') {
                renderMail = 'true';
            }
            else if (sq.Type__c == 'Phone') {
                renderPhone = 'true';
            }
            //responses= getResponses();
        }
        
        private void clearAllRenderFlg() {
            renderSelectRadio      = 'false';
            renderSelectCheckboxes = 'false';
            renderSelectRow        = 'false';
            renderPickList         = 'false';
            renderFreeText         = 'false';
            renderSingleText       = 'false';
            renderScale            = 'false';
            renderMail             = 'false';
            renderPhone            = 'false';
        }
      
        /** Splits up the string as given by the user and adds each option
         *  to a list to be displayed as option on the Visualforce page
         *  param: str String as submitted by the user
         *  returns the List of SelectOption for the visualforce page
         */  
        private List<SelectOption> stringToSelectOptions(String str, Boolean isPicklist) {
            if (String.isBlank(str) == true) {
                return new List<SelectOption>();
            }
            strList = str.split('\\r|\n');
 
            List<SelectOption> returnVal = new List<SelectOption>();
            if (isPicklist) {
                returnVal.add(new SelectOption('', System.Label.LABS_SF_SELECTTYPE));
            }
            
            for(String s: strList) {
                if (String.isBlank(s) == false) {
                    returnVal.add(new SelectOption(s,s));
                    //if (s != 'null' && s!= null) {
                        //String sBis = s.replace(' ', '%20');
                        //singleOptionsForChart += s.trim()+'|';
                    //}
                }
            }
            //singleOptionsForChart = singleOptionsForChart.substring(0, singleOptionsForChart.length()-1);
            return returnVal;
        } 
    }
    
    /** Fills up the List of questions to be displayed on the Visualforce page
     */ 
    public List<question> getAQuestion() {
        List<Survey_Question__c> allQuestionsObject = 
                    [Select s.Type__c, s.Id, s.Survey__c, s.Required__c, s.Question__c, 
                    s.OrderNumber__c, s.Name, s.Choices__c, 
                    s.MinLabel__c, s.MaxLabel__c
                    From Survey_Question__c s 
                    WHERE s.Survey__c =: surveyId ORDER BY s.OrderNumber__c];
        allQuestions = new List<question>();
        
        Double old_OrderNumber = 0;
        Double new_OrderNumber;
        Double difference = 0;
        /* Make sure that the order number follow each other (after deleting a question, orders might not do so) */
        for (Survey_Question__c q : allQuestionsObject){ 
            new_OrderNumber = q.OrderNumber__c;
            difference = new_OrderNumber - old_OrderNumber - 1;
            if (difference > 0) {
                Double dd = double.valueOf(difference);
                Integer newOrderInt = dd.intValue();
                q.OrderNumber__c -= Integer.valueOf(newOrderInt); 
            }
            old_OrderNumber = q.OrderNumber__c;
            question theQ = new question(q);
            allQuestions.add(theQ);
        }
        allQuestionsSize = allQuestions.size();
        return allQuestions;
    } 
}