File: view.php

package info (click to toggle)
moodle 1.6.3-2%2Betch3
  • links: PTS
  • area: main
  • in suites: etch
  • size: 37,172 kB
  • ctags: 51,688
  • sloc: php: 231,916; sql: 5,631; xml: 2,688; sh: 1,185; perl: 638; makefile: 48; pascal: 36
file content (2013 lines) | stat: -rw-r--r-- 112,096 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
<?PHP  // $Id: view.php,v 1.91.2.6 2006/09/08 18:01:12 mark-nielsen Exp $

/// This page prints a particular instance of lesson
/// (Replace lesson with the name of your module)

    require_once('../../config.php');
    require_once('locallib.php');
    require_once('lib.php');

    $id      = required_param('id', PARAM_INT);             // Course Module ID
    $pageid  = optional_param('pageid', NULL, PARAM_INT);   // Lesson Page ID
    $action  = optional_param('action', '', PARAM_ALPHA);
    $display = optional_param('display', 0, PARAM_INT);     // for teacherview action
    $mode    = optional_param('mode', '', PARAM_ALPHA);     // for eacherview action todo use user pref
    

    if (! $cm = get_coursemodule_from_id('lesson', $id)) {
        error('Course Module ID was incorrect');
    }

    if (! $course = get_record('course', 'id', $cm->course)) {
        error('Course is misconfigured');
    }

    if (! $lesson = get_record('lesson', 'id', $cm->instance)) {
        error('Course module is incorrect');
    }

    require_login($course->id, false, $cm);

    switch ($action) {
        case 'essayview':
        case 'essaygrade':
        case 'updategrade':
        case 'emailessay':
            if (!isteacheredit($course->id)) {
                error('You must be a teacher with editing rights to view this page');
            }
            break;
    }

/// Print the page header

    if ($course->category) {
        $navigation = '<a href="../../course/view.php?id='. $course->id .'">'. $course->shortname .'</a> ->';
    } else {
        $navigation = '';
    }

    $strlessons = get_string('modulenameplural', 'lesson');
    $strlesson  = get_string('modulename', 'lesson');
    
    // moved the action up because I needed to know what the action will be before the header is printed
    if (empty($action)) {
        if (isteacher($course->id)) {
            $action = 'teacherview';
        } elseif  (time() < $lesson->available) {
            print_header($course->shortname .': '. format_string($lesson->name), $course->fullname,
                         $navigation .'<a href="index.php?id='. $course->id .'">'. $strlessons .'</a> -> '.
                         '<a href="view.php?id='. $cm->id .'">'. format_string($lesson->name,true) .'</a>', 
                         '', '', true, '', navmenu($course, $cm));
            print_simple_box_start('center');
            echo '<div align="center">';
            echo get_string('lessonopen', 'lesson', userdate($lesson->available)).'<br />';
            echo '<div class="lessonbutton standardbutton" style="padding: 5px;"><a href="../../course/view.php?id='. $course->id .'">'. get_string('returnmainmenu', 'lesson') .'</a></div>';
            echo '</div>';
            print_simple_box_end();
            print_footer($course);
            exit();
        } elseif (time() > $lesson->deadline) {
            print_header($course->shortname .': '. format_string($lesson->name), $course->fullname,
                         "$navigation <a href=\"index.php?id=$course->id\">$strlessons</a> -> <a href=\"view.php?id=$cm->id\">".format_string($lesson->name,true)."</a>", '', "", true,
                          '', navmenu($course, $cm));
            print_simple_box_start('center');
            echo '<div align="center">';
            echo get_string('lessonclosed', 'lesson', userdate($lesson->deadline)) .'<br />';
            echo '<div class="lessonbutton standardbutton" style="padding: 5px;"><a href="../../course/view.php?id='. $course->id. '">'. get_string('returnmainmenu', 'lesson') .'</a></div>';
            echo '</div>';
            print_simple_box_end();
            print_footer($course);
            exit();
        } elseif ($lesson->highscores && !$lesson->practice) {
            $action = 'highscores';
        } else {
            $action = 'navigation';
        }
    } 

    // changed the update_module_button and added another button when a teacher is checking the navigation of the lesson
    if (isteacheredit($course->id)) {
        $button = '<table><tr><td>';
        $button .= '<form target="'. $CFG->framename .'" method="get" action="'. $CFG->wwwroot .'/course/mod.php">'.
               '<input type="hidden" name="sesskey" value="'. $USER->sesskey .'" />'.
               '<input type="hidden" name="update" value="'. $cm->id .'" />'.
               '<input type="hidden" name="return" value="true" />'.
               '<input type="submit" value="'. get_string('editlessonsettings', 'lesson') .'" /></form>';
        if ($action == 'navigation' && $pageid != LESSON_EOL) {
            $currentpageid = $pageid;  // very important not to alter $pageid.
            if (empty($currentpageid)) {
                $currentpageid = get_field('lesson_pages', 'id', 'lessonid', $lesson->id, 'prevpageid', 0);
            }
            if (!empty($currentpageid)) {  // if still empty, then something is wrong
                $button .= '</td><td>'.
                       '<form target="'. $CFG->framename .'" method="get" action="'. $CFG->wwwroot .'/mod/lesson/lesson.php">'.
                       '<input type="hidden" name="id" value="'. $cm->id .'" />'.
                       '<input type="hidden" name="action" value="editpage" />'.
                       '<input type="hidden" name="redirect" value="navigation" />'.
                       '<input type="hidden" name="pageid" value="'. $currentpageid .'" />'.
                       '<input type="submit" value="'. get_string('editpagecontent', 'lesson') .'" /></form>';
            }
        }
        $button .= '</td></tr></table>';
    } else {
        $button = '';
    }

    print_header($course->shortname .': '. format_string($lesson->name), $course->fullname,
                 "$navigation <a href=\"index.php?id=$course->id\">$strlessons</a> -> <a href=\"view.php?id=$cm->id\">".format_string($lesson->name,true)."</a>", '', '', true,
                 $button, // took out update_module_button($cm->id, $course->id, $strlesson) and replaced it with $button
                  navmenu($course, $cm));

    if (isteacher($course->id)) {
        
        if ($action == 'teacherview' and $display) {
            // teacherview tab not selected when displaying a single page/question
            $currenttab = '';
        } else {
            $currenttab = $action;
        }
        include('tabs.php');
    }
    
    // set up some general variables
    $usehtmleditor = can_use_html_editor();
    $path = $CFG->wwwroot .'/course';

    /************** navigation **************************************/
    if ($action == 'navigation') {
        // password protected lesson code
        if ($lesson->usepassword && !isteacher($course->id)) {
            $correctpass = false;
            if ($password = optional_param('userpassword', '', PARAM_CLEAN)) {
                if ($lesson->password == md5(trim($password))) {
                    $USER->lessonloggedin[$lesson->id] = true;
                    $correctpass = true;
                }
            } elseif (isset($USER->lessonloggedin[$lesson->id])) {
                $correctpass = true;
            }

            if (!$correctpass) {
                print_simple_box_start('center');
                echo '<form name="password" method="post" action="view.php">' . "\n";
                echo '<input type="hidden" name="id" value="'. $cm->id .'" />' . "\n";
                echo '<input type="hidden" name="action" value="navigation" />' . "\n";
                if (optional_param('userpassword', 0, PARAM_CLEAN)) {
                    notify(get_string('loginfail', 'lesson'));
                }
                echo "<div align=\"center\">\n".
                    get_string('passwordprotectedlesson', 'lesson', format_string($lesson->name))."<br /><br />\n".
                    get_string('enterpassword', 'lesson')." <input type=\"password\" name=\"userpassword\" /><br /><br />\n";

                echo '<span class="lessonbutton standardbutton"><a href="'.$CFG->wwwroot.'/course/view.php?id='. $course->id .'">'. get_string('cancel', 'lesson') .'</a></span> '.
                    ' <span class="lessonbutton standardbutton"><a href="javascript:document.password.submit();">'. get_string('continue', 'lesson') .'</a></span>'.
                    "</div>\n";
                print_simple_box_end();
                exit();
            }
        }
    
        // this is called if a student leaves during a lesson
        if($pageid == LESSON_UNSEENBRANCHPAGE) {
                $pageid = lesson_unseen_question_jump($lesson->id, $USER->id, $pageid);
        }
        
        // display individual pages and their sets of answers
        // if pageid is EOL then the end of the lesson has been reached
               // for flow, changed to simple echo for flow styles, michaelp, moved lesson name and page title down
       $timedflag = false;
       $attemptflag = false;
        if (empty($pageid)) {
            // make sure there are pages to view
            if (!get_field('lesson_pages', 'id', 'lessonid', $lesson->id, 'prevpageid', 0)) {
                if (isstudent($course->id)) {
                    notify(get_string('lessonnotready', 'lesson', $course->teacher)); // a nice message to the student
                } else {
                    if (!count_records('lesson_pages', 'lessonid', $lesson->id)) {
                        redirect('view.php?id='.$cm->id); // no pages - redirect to add pages
                    } else {
                        notify(get_string('lessonpagelinkingbroken', 'lesson'));  // ok, bad mojo
                    }
                }
                print_footer($course);
                exit();
            }
            
            // check for dependencies
            if ($lesson->dependency and !isteacher($course->id)) {
                if ($dependentlesson = get_record('lesson', 'id', $lesson->dependency)) {
                    // lesson exists, so we can proceed            
                    $conditions = unserialize($lesson->conditions);
                    // assume false for all
                    $timespent = false;
                    $completed = false;
                    $gradebetterthan = false;
                    // check for the timespent condition
                    if ($conditions->timespent) {
                        if ($attempttimes = get_records_select('lesson_timer', "userid = $USER->id AND lessonid = $dependentlesson->id")) {
                            // go through all the times and test to see if any of them satisfy the condition
                            foreach($attempttimes as $attempttime) {
                                $duration = $attempttime->lessontime - $attempttime->starttime;
                                if ($conditions->timespent < $duration/60) {
                                    $timespent = true;
                                }
                            }
                        } 
                    } else {
                        $timespent = true; // there isn't one set
                    }
                    
                    // check for the gradebetterthan condition
                    if($conditions->gradebetterthan) {
                        if ($studentgrades = get_records_select('lesson_grades', "userid = $USER->id AND lessonid = $dependentlesson->id")) {
                            // go through all the grades and test to see if any of them satisfy the condition
                            foreach($studentgrades as $studentgrade) {
                                if ($studentgrade->grade >= $conditions->gradebetterthan) {
                                    $gradebetterthan = true;
                                }
                            }
                        }
                    } else {
                        $gradebetterthan = true; // there isn't one set
                    }
                
                    // check for the completed condition
                    if ($conditions->completed) {
                        if (count_records('lesson_grades', 'userid', $USER->id, 'lessonid', $dependentlesson->id)) {
                            $completed = true;
                        }
                    } else {
                        $completed = true; // not set
                    }
                
                    $errors = array();
                    // collect all of our error statements
                    if (!$timespent) {
                        $errors[] = get_string('timespenterror', 'lesson', $conditions->timespent);
                    }
                    if (!$completed) {
                        $errors[] = get_string('completederror', 'lesson');
                    }
                    if (!$gradebetterthan) {
                        $errors[] = get_string('gradebetterthanerror', 'lesson', $conditions->gradebetterthan);
                    }
                    if (!empty($errors)) {  // print out the errors if any
                        echo '<p>';
                        print_simple_box_start('center');
                        print_string('completethefollowingconditions', 'lesson', $dependentlesson->name);
                        echo '<p align="center">'.implode('<br />'.get_string('and', 'lesson').'<br />', $errors).'</p>';
                        print_simple_box_end();
                        echo '</p>';
                        print_footer($course);
                        exit();
                    } 
                }
            }
            add_to_log($course->id, 'lesson', 'start', 'view.php?id='. $cm->id, $lesson->id, $cm->id);
            // if no pageid given see if the lesson has been started
            if ($grades = get_records_select('lesson_grades', 'lessonid = '. $lesson->id .' AND userid = '. $USER->id,
                        'grade DESC')) {
                $retries = count($grades);
            } else {
                $retries = 0;
            }
            if ($retries) {
                $attemptflag = true;
            }
            
            if (isset($USER->modattempts[$lesson->id])) { 
                unset($USER->modattempts[$lesson->id]);  // if no pageid, then student is NOT reviewing
            }
            
            // if there are any questions have been answered correctly in this attempt
            if ($attempts = get_records_select('lesson_attempts', 
                        "lessonid = $lesson->id AND userid = $USER->id AND retry = $retries AND 
                        correct = 1", 'timeseen DESC')) {
                
                foreach ($attempts as $attempt) {
                    $jumpto = get_field('lesson_answers', 'jumpto', 'id', $attempt->answerid);
                    // convert the jumpto to a proper page id
                    if ($jumpto == 0) { // unlikely value!
                        $lastpageseen = $attempt->pageid;
                    } elseif ($jumpto == LESSON_NEXTPAGE) {
                        if (!$lastpageseen = get_field('lesson_pages', 'nextpageid', 'id', 
                                    $attempt->pageid)) {
                            // no nextpage go to end of lesson
                            $lastpageseen = LESSON_EOL;
                        }
                    } else {
                        $lastpageseen = $jumpto;
                    }
                    break; // only look at the latest correct attempt 
                }
            } else {
                $attempts = NULL;
            }

            if ($branchtables = get_records_select('lesson_branch', 
                                "lessonid = $lesson->id AND userid = $USER->id AND retry = $retries", 'timeseen DESC')) {
                // in here, user has viewed a branch table
                $lastbranchtable = current($branchtables);
                if ($attempts != NULL) {
                    foreach($attempts as $attempt) {
                        if ($lastbranchtable->timeseen > $attempt->timeseen) {
                            // branch table was viewed later than the last attempt
                            $lastpageseen = $lastbranchtable->pageid;
                        }
                        break;
                    }
                } else {
                    // hasnt answered any questions but has viewed a branch table
                    $lastpageseen = $lastbranchtable->pageid;
                }
            }
            //if ($lastpageseen != $firstpageid) {
            if (isset($lastpageseen) and count_records('lesson_attempts', 'lessonid', $lesson->id, 'userid', $USER->id, 'retry', $retries) > 0) {
                // get the first page
                if (!$firstpageid = get_field('lesson_pages', 'id', 'lessonid', $lesson->id,
                            'prevpageid', 0)) {
                    error('Navigation: first page not found');
                }
                if ($lesson->timed) {
                    if ($lesson->retake) {
                        print_simple_box('<p align="center">'. get_string('leftduringtimed', 'lesson') .'</p>', 'center');
                        echo '<div align="center" class="lessonbutton standardbutton">'.
                                  '<a href="view.php?id='.$cm->id.'&amp;action=navigation&amp;pageid='.$firstpageid.'&amp;startlastseen=no">'.
                                    get_string('continue', 'lesson').'</a></div>';
                    } else {
                        print_simple_box_start('center');
                        echo '<div align="center">';
                        echo get_string('leftduringtimednoretake', 'lesson');
                        echo '<br /><br /><div class="lessonbutton standardbutton"><a href="../../course/view.php?id='. $course->id .'">'. get_string('returntocourse', 'lesson') .'</a></div>';
                        echo '</div>';
                        print_simple_box_end();
                    }
                    
                } else {
                    print_simple_box("<p align=\"center\">".get_string('youhaveseen','lesson').'</p>',
                            "center");
                    
                    echo '<div align="center">';
                    echo '<span class="lessonbutton standardbutton">'.
                            '<a href="view.php?id='.$cm->id.'&amp;action=navigation&amp;pageid='.$lastpageseen.'&amp;startlastseen=yes">'.
                            get_string('yes').'</a></span>&nbsp;&nbsp;&nbsp;';
                    echo '<span class="lessonbutton standardbutton">'.
                            '<a href="view.php?id='.$cm->id.'&amp;action=navigation&amp;pageid='.$firstpageid.'&amp;startlastseen=no">'.
                            get_string('no').'</a></div>';
                    echo '</span>';
                }
                print_footer($course);
                exit();
            }
            
            if ($grades) {
                foreach ($grades as $grade) {
                    $bestgrade = $grade->grade;
                    break;
                }
                if (!$lesson->retake) {
                    print_simple_box_start('center');
                    echo "<div align=\"center\">";
                    echo get_string("noretake", "lesson");
                    echo "<br /><br /><div class=\"lessonbutton standardbutton\"><a href=\"../../course/view.php?id=$course->id\">".get_string('returntocourse', 'lesson').'</a></div>';
                    echo "</div>";
                    print_simple_box_end();
                    print_footer($course);
                    exit();
                      //redirect("../../course/view.php?id=$course->id", get_string("alreadytaken", "lesson"));
                // allow student to retake course even if they have the maximum grade
                // } elseif ($bestgrade == 100) {
                  //     redirect("../../course/view.php?id=$course->id", get_string("maximumgradeachieved",
                //                 "lesson"));
                }
            }
            // start at the first page
            if (!$pageid = get_field('lesson_pages', 'id', 'lessonid', $lesson->id, 'prevpageid', 0)) {
                    error('Navigation: first page not found');
            }
            /// This is the code for starting a timed test
            if(!isset($USER->startlesson[$lesson->id]) && !isteacher($course->id)) {
                $USER->startlesson[$lesson->id] = true;
                $startlesson = new stdClass;
                $startlesson->lessonid = $lesson->id;
                $startlesson->userid = $USER->id;
                $startlesson->starttime = time();
                $startlesson->lessontime = time();
                
                if (!insert_record('lesson_timer', $startlesson)) {
                    error('Error: could not insert row into lesson_timer table');
                }
                if ($lesson->timed) {
                    $timedflag = true;
                }
            }
            
            if (!empty($lesson->mediafile)) {
                // open our pop-up
                $url = '/mod/lesson/mediafile.php?id='.$cm->id;
                $name = 'lessonmediafile';
                $options = 'menubar=0,location=0,left=5,top=5,scrollbars,resizable,width='. $lesson->mediawidth .',height='. $lesson->mediaheight;
                echo "\n<script language=\"javascript\" type=\"text/javascript\">";
                echo "\n<!--\n";
                echo "     openpopup('$url', '$name', '$options', 0);";
                echo "\n-->\n";
                echo '</script>';
            }
        }
        
        if ($pageid != LESSON_EOL) {
            /// This is the code updates the lessontime for a timed test
            if ($startlastseen = optional_param('startlastseen', '', PARAM_ALPHA)) {  /// this deletes old records  not totally sure if this is necessary anymore
                if ($startlastseen == 'no') {
                    if ($grades = get_records_select('lesson_grades', "lessonid = $lesson->id AND userid = $USER->id",
                                'grade DESC')) {
                        $retries = count($grades);
                    } else {
                        $retries = 0;
                    }
                    if (!delete_records('lesson_attempts', 'userid', $USER->id, 'lessonid', $lesson->id, 'retry', $retries)) {
                        error('Error: could not delete old attempts');
                    }
                    if (!delete_records('lesson_branch', 'userid', $USER->id, 'lessonid', $lesson->id, 'retry', $retries)) {
                        error('Error: could not delete old seen branches');
                    }
                }
            }
            
            add_to_log($course->id, 'lesson', 'view', 'view.php?id='. $cm->id, $pageid, $cm->id);
            if (!$page = get_record('lesson_pages', 'id', $pageid)) {
                error('Navigation: the page record not found');
            }

            if ($page->qtype == LESSON_CLUSTER) {  //this only gets called when a user starts up a new lesson and the first page is a cluster page
                if (!isteacher($course->id)) {
                    // get new id
                    $pageid = lesson_cluster_jump($lesson->id, $USER->id, $pageid);
                    // get new page info
                    if (!$page = get_record('lesson_pages', 'id', $pageid)) {
                        error('Navigation: the page record not found');
                    }
                    add_to_log($course->id, 'lesson', 'view', 'view.php?id='. $cm->id, $pageid, $cm->id);
                } else {
                    // get the next page
                    $pageid = $page->nextpageid;
                    if (!$page = get_record('lesson_pages', 'id', $pageid)) {
                        error('Navigation: the page record not found');
                    }
                }
            } elseif ($page->qtype == LESSON_ENDOFCLUSTER) {
                if ($page->nextpageid == 0) {
                    $nextpageid = LESSON_EOL;
                } else {
                    $nextpageid = $page->nextpageid;
                }
                redirect("view.php?id=$cm->id&amp;action=navigation&amp;pageid=$nextpageid", get_string('endofclustertitle', 'lesson'));
            }
            
            
            // check to see if the user can see the left menu
            if (!isteacher($course->id)) {
                $lesson->displayleft = lesson_displayleftif($lesson);
            }
            
            // start of left menu
            if ($lesson->displayleft) {
               echo '<table><tr valign="top"><td>';
               // skip navigation link
               echo '<a href="#maincontent" class="skip">'.get_string('skip', 'lesson').'</a>';
               if($firstpageid = get_field('lesson_pages', 'id', 'lessonid', $lesson->id, 'prevpageid', 0)) {
                        // print the pages
                        echo "<div class=\"leftmenu_container\">\n";
                            echo '<div class="leftmenu_title">'.get_string('lessonmenu', 'lesson')."</div>\n";
                            echo '<div class="leftmenu_courselink">';
                            echo "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">".get_string("mainmenu", "lesson")."</a>\n";
                            echo "</div>\n";
                            echo "<div class=\"leftmenu_links\">\n";
                            lesson_print_tree_menu($lesson->id, $firstpageid, $cm->id);
                            echo "</div>\n";
                        echo "</div>\n";
                }
                if ($page->qtype == LESSON_BRANCHTABLE) {
                    $width = '';
                } else {
                    $width = ' width="100%" ';
                }
                echo '</td><td align="center" '.$width.'>';
                // skip to anchor
                echo '<a name="maincontent" id="maincontent" title="'.get_string('anchortitle', 'lesson').'"></a>';
            } elseif ($lesson->slideshow && $page->qtype == LESSON_BRANCHTABLE) {
                echo '<table align="center"><tr><td>';  // only want this if no left menu
            }

            // starts the slideshow div
            if($lesson->slideshow && $page->qtype == LESSON_BRANCHTABLE) { 
                echo "<table align=\"center\" width=\"100%\" border=\"0\"><tr><td>\n".
                     "<div class=\"slideshow\" style=\"
                        background-color: $lesson->bgcolor;
                        height: ".$lesson->height."px;
                        width: ".$lesson->width."px;
                        \">\n";
            } else {
                echo "<table align=\"center\" width=\"100%\" border=\"0\"><tr><td>\n";
                $lesson->slideshow = false; // turn off slide show for all pages other than LESSON_BRANTCHTABLE
            }

            // This is where several messages (usually warnings) are displayed
            // all of this is displayed above the actual page
            
            if (!empty($lesson->mediafile)) {
                $url = '/mod/lesson/mediafile.php?id='.$cm->id;
                $options = 'menubar=0,location=0,left=5,top=5,scrollbars,resizable,width='. $lesson->mediawidth .',height='. $lesson->mediaheight;
                $name = 'lessonmediafile';
                echo '<div align="right">';
                link_to_popup_window ($url, $name, get_string('mediafilepopup', 'lesson'), '', '', get_string('mediafilepopup', 'lesson'), $options);
                helpbutton("mediafilestudent", get_string("mediafile", "lesson"), "lesson");
                echo '</div>';
            }
            // clock code
            // get time information for this user
            if(!isteacher($course->id)) {
                if (!$timer = get_records_select('lesson_timer', "lessonid = $lesson->id AND userid = $USER->id", 'starttime')) {
                    error('Error: could not find records');
                } else {
                    $timer = array_pop($timer); // this will get the latest start time record
                }
            }
    
            $startlastseen = optional_param('startlastseen', '', PARAM_ALPHA);
            if ($startlastseen == 'yes') {  // continue a previous test, need to update the clock  (think this option is disabled atm)
                $timer->starttime = time() - ($timer->lessontime - $timer->starttime);
                $timer->lessontime = time();
            } else if ($startlastseen == 'no') {  // starting over
                // starting over, so reset the clock
                $timer->starttime = time();
                $timer->lessontime = time();
            }
                
            // for timed lessons, display clock
            if ($lesson->timed) {
                if(isteacher($course->id)) {
                    echo '<p align="center">'. get_string('teachertimerwarning', 'lesson') .'<p>';
                } else {
                    if ((($timer->starttime + $lesson->maxtime * 60) - time()) > 0) {
                        // code for the clock
                        print_simple_box_start("right", "150px", "#ffffff", 0);
                        echo "<table border=\"0\" valign=\"top\" align=\"center\" class=\"generaltable\" width=\"100%\" cellspacing=\"0\">".
                            "<tr><th valign=\"top\" class=\"generaltableheader\">".get_string("timeremaining", "lesson").
                            "</th></tr><tr><td align=\"center\" class=\"generaltablecell\">";
                        echo "<script language=\"javascript\">\n";
                            echo "var starttime = ". $timer->starttime . ";\n";
                            echo "var servertime = ". time() . ";\n";
                            echo "var testlength = ". $lesson->maxtime * 60 .";\n";
                            echo "document.write('<SCRIPT LANGUAGE=\"JavaScript\" SRC=\"timer.js\"><\/SCRIPT>');\n";
                            echo "window.onload = function () { show_clock(); }\n";
                        echo "</script>\n";
                        echo "</td></tr></table>";
                        print_simple_box_end();
                        echo "<br /><br /><br />";
                    } else {
                        redirect("view.php?id=$cm->id&amp;action=navigation&amp;pageid=".LESSON_EOL."&amp;outoftime=normal", get_string("outoftime", "lesson"));
                    }
                    // update clock when viewing a new page... no special treatment
                    if ((($timer->starttime + $lesson->maxtime * 60) - time()) < 60) {
                        echo "<p align=\"center\">".get_string('studentoneminwarning', 'lesson')."</p>";
                    }    
                    
                    if ($timedflag) {
                        print_simple_box(get_string('maxtimewarning', 'lesson', $lesson->maxtime), 'center');
                    }
                }
            }

            // update the clock
            if (!isteacher($course->id)) {
                $timer->lessontime = time();
                if (!update_record('lesson_timer', $timer)) {
                    error('Error: could not update lesson_timer table');
                }
            }
            
            if ($attemptflag) {
                print_heading(get_string('attempt', 'lesson', $retries + 1));
            }
                        
            // before we output everything check to see if the page is a EOB, if so jump directly 
            // to it's associated branch table
            if ($page->qtype == LESSON_ENDOFBRANCH) {
                if ($answers = get_records('lesson_answers', 'pageid', $page->id, 'id')) {
                    // print_heading(get_string('endofbranch', 'lesson'));
                    foreach ($answers as $answer) {
                        // just need the first answer
                        if ($answer->jumpto == LESSON_RANDOMBRANCH) {
                            $answer->jumpto = lesson_unseen_branch_jump($lesson->id, $USER->id);
                        } elseif ($answer->jumpto == LESSON_CLUSTERJUMP) {
                            if (!isteacher($course->id)) {
                                $answer->jumpto = lesson_cluster_jump($lesson->id, $USER->id, $pageid);
                            } else {
                                if ($page->nextpageid == 0) {  
                                    $answer->jumpto = LESSON_EOL;
                                } else {
                                    $answer->jumpto = $page->nextpageid;
                                }
                            }
                        } else if ($answer->jumpto == LESSON_NEXTPAGE) {
                            if ($page->nextpageid == 0) {  
                                $answer->jumpto = LESSON_EOL;
                            } else {
                                $answer->jumpto = $page->nextpageid;
                            }
                        } else if ($answer->jumpto == 0) {
                            $answer->jumpto = $page->id;
                        } else if ($answer->jumpto == LESSON_PREVIOUSPAGE) {
                            $answer->jumpto = $page->prevpageid;                            
                        }
                        redirect("view.php?id=$cm->id&amp;action=navigation&amp;pageid=$answer->jumpto");// REMOVED: , get_string("endofbranch", "lesson")
                        break;
                    } 
                    print_footer($course);
                    exit();
                } else {
                    error('Navigation: No answers on EOB');
                }
            }
                        
             ///  This is the warning msg for teachers to inform them that cluster and unseen does not work while logged in as a teacher
            if(isteacher($course->id)) {
                if (lesson_display_teacher_warning($lesson->id)) {
                    $warningvars->cluster = get_string('clusterjump', 'lesson');
                    $warningvars->unseen = get_string('unseenpageinbranch', 'lesson');
                    echo '<p align="center">'. get_string('teacherjumpwarning', 'lesson', $warningvars) .'</p>';
                }
            }
            
            /// This calculates and prints the ongoing score
            if ($lesson->ongoing and !empty($pageid)) {
                lesson_print_ongoing_score($lesson);
            }
            
            if ($page->qtype == LESSON_BRANCHTABLE) {
                if ($lesson->minquestions and isstudent($course->id)) {
                    // tell student how many questions they have seen, how many are required and their grade
                    $ntries = count_records("lesson_grades", "lessonid", $lesson->id, "userid", $USER->id);
                    
                    $gradeinfo = lesson_grade($lesson, $ntries);
                    
                    if ($gradeinfo->attempts) {
                        echo "<p align=\"center\">".get_string("numberofpagesviewed", "lesson", $gradeinfo->nquestions).
                                "; (".get_string("youshouldview", "lesson", $lesson->minquestions).")<br />";
                        // count the number of distinct correct pages
                        if ($gradeinfo->nquestions < $lesson->minquestions) {
                            $gradeinfo->nquestions = $lesson->minquestions;
                        }
                        echo get_string("numberofcorrectanswers", "lesson", $gradeinfo->earned)."<br />\n";
                        echo get_string("yourcurrentgradeis", "lesson", 
                                number_format($gradeinfo->grade * $lesson->grade / 100, 1)).
                            " (".get_string("outof", "lesson", $lesson->grade).")</p>\n";
                    }
                }
            }
               
            // now starting to print the page's contents   
            echo "<div align=\"center\">";            
            echo "<em><strong>";
            echo format_string($lesson->name) . "</strong></em>";
            if ($page->qtype == LESSON_BRANCHTABLE) {
                echo ":<br />";
                print_heading(format_string($page->title));
            }
            echo "</div><br />";
            
            if (!$lesson->slideshow) {
                $options = new stdClass;
                $options->noclean = true;
                print_simple_box('<div class="contents">'.
                                format_text($page->contents, FORMAT_MOODLE, $options).
                                '</div>', 'center');
            }
            echo "<br />\n";
            
            // this is for modattempts option.  Find the users previous answer to this page,
            //   and then display it below in answer processing
            if (isset($USER->modattempts[$lesson->id])) {            
                $retries = count_records('lesson_grades', "lessonid", $lesson->id, "userid", $USER->id);
                $retries--;
                if (! $attempts = get_records_select("lesson_attempts", "lessonid = $lesson->id AND userid = $USER->id AND pageid = $page->id AND retry = $retries", "timeseen")) {
                    error("Previous attempt record could not be found!");
                }
                $attempt = end($attempts);
            }
            
            // get the answers in a set order, the id order
            if ($answers = get_records("lesson_answers", "pageid", $page->id, "id")) {
                echo "<form name=\"answerform\" method =\"post\" action=\"lesson.php\">";
                echo "<input type=\"hidden\" name=\"id\" value=\"$cm->id\" />";
                echo "<input type=\"hidden\" name=\"action\" value=\"continue\" />";
                echo "<input type=\"hidden\" name=\"pageid\" value=\"$pageid\" />";
                echo "<input type=\"hidden\" name=\"sesskey\" value=\"".$USER->sesskey."\" />";
                if (!$lesson->slideshow) {
                    if ($page->qtype != LESSON_BRANCHTABLE) {
                        print_simple_box_start("center");
                    }                    
                    echo '<table width="100%">';
                }
                // default format text options
                $options = new stdClass;
                $options->para = false; // no <p></p>
                $options->noclean = true;
                switch ($page->qtype) {
                    case LESSON_SHORTANSWER :
                    case LESSON_NUMERICAL :
                        if (isset($USER->modattempts[$lesson->id])) {     
                            $value = "value=\"$attempt->useranswer\"";
                        } else {
                            $value = "";
                        }       
                        echo '<tr><td align="center"><label for="answer">'.get_string('youranswer', 'lesson').'</label>'.
                            ": <input type=\"text\" id=\"answer\" name=\"answer\" size=\"50\" maxlength=\"200\" $value />\n";
                        echo '</table>';
                        print_simple_box_end();
                        echo "<div align=\"center\" class=\"lessonbutton standardbutton\"><a href=\"javascript:document.answerform.submit();\">".
                             get_string("pleaseenteryouranswerinthebox", "lesson")."</a></div></p>\n";
                        break;
                    case LESSON_TRUEFALSE :
                        shuffle($answers);
                        $i = 0;
                        foreach ($answers as $answer) {
                            echo '<tr><td valign="top">';
                            if (isset($USER->modattempts[$lesson->id]) && $answer->id == $attempt->answerid) {
                                $checked = 'checked="checked"';
                            } else {
                                $checked = '';
                            } 
                            echo "<input type=\"radio\" id=\"answerid$i\" name=\"answerid\" value=\"{$answer->id}\" $checked />";
                            echo "</td><td>";
                            echo "<label for=\"answerid$i\">".format_text(trim($answer->answer), FORMAT_MOODLE, $options).'</label>';
                            echo '</td></tr>';
                            if ($answer != end($answers)) {
                                echo "<tr><td><br></td></tr>";                            
                            }
                            $i++;
                        }
                        echo '</table>';
                        print_simple_box_end();
                        echo "<div align=\"center\" class=\"lessonbutton standardbutton\"><a href=\"javascript:document.answerform.submit();\">".
                            get_string("pleasecheckoneanswer", "lesson")."</a></div>\n"; 
                        break;
                    case LESSON_MULTICHOICE :
                        $i = 0;
                        shuffle($answers);

                        foreach ($answers as $answer) {
                            echo '<tr><td valign="top">';
                            if ($page->qoption) {
                                $checked = '';
                                if (isset($USER->modattempts[$lesson->id])) {
                                    $answerids = explode(",", $attempt->useranswer);
                                    if (in_array($answer->id, $answerids)) {
                                        $checked = ' checked="checked"';
                                    } else {
                                        $checked = '';
                                    }
                                }
                                // more than one answer allowed 
                                echo "<input type=\"checkbox\" id=\"answerid$i\" name=\"answer[$i]\" value=\"{$answer->id}\"$checked />";
                            } else {
                                if (isset($USER->modattempts[$lesson->id]) && $answer->id == $attempt->answerid) {
                                    $checked = ' checked="checked"';
                                } else {
                                    $checked = '';
                                } 
                                // only one answer allowed
                                echo "<input type=\"radio\" id=\"answerid$i\" name=\"answerid\" value=\"{$answer->id}\"$checked />";
                            }
                            echo '</td><td>';
                            echo "<label for=\"answerid$i\" >".format_text(trim($answer->answer), FORMAT_MOODLE, $options).'</label>'; 
                            echo '</td></tr>';
                            if ($answer != end($answers)) {
                                echo '<tr><td><br></td></tr>';
                            } 
                            $i++;
                        }
                        echo '</table>';
                        print_simple_box_end();
                        if ($page->qoption) {
                            echo "<div align=\"center\" class=\"lessonbutton standardbutton\"><a href=\"javascript:document.answerform.submit();\">".
                                get_string("pleasecheckoneormoreanswers", "lesson")."</a></div>\n";
                        } else {
                            echo "<div align=\"center\" class=\"lessonbutton standardbutton\"><a href=\"javascript:document.answerform.submit();\">".
                                get_string("pleasecheckoneanswer", "lesson")."</a></div>\n";
                        }
                        break;
                        
                    case LESSON_MATCHING :
                        echo '<tr><td><table width="100%">';
                        // don't suffle answers (could be an option??)
                        foreach ($answers as $answer) {
                            // get all the response
                            if ($answer->response != NULL) {
                                $responses[] = trim($answer->response);
                            }
                        }
                        shuffle($responses);
                        $responses = array_unique($responses);
                        
                        $responseoptions = array();
                        foreach ($responses as $response) {
                            $responseoptions[htmlspecialchars(trim($response))] = $response;
                        }
                        
                        if (isset($USER->modattempts[$lesson->id])) {
                            $useranswers = explode(',', $attempt->useranswer);
                            $t = 0;
                        }
                        foreach ($answers as $answer) {
                            if ($answer->response != NULL) {
                                echo '<tr><td align="right">';
                                echo "<b><label for=\"menuresponse[$answer->id]\">".
                                        format_text($answer->answer,FORMAT_MOODLE,$options).
                                        '</label>: </b></td><td valign="bottom">';

                                if (isset($USER->modattempts[$lesson->id])) {
                                    $selected = htmlspecialchars(trim($answers[$useranswers[$t]]->response));  // gets the user's previous answer
                                    choose_from_menu ($responseoptions, "response[$answer->id]", $selected);
                                    $t++;
                                } else {
                                    choose_from_menu ($responseoptions, "response[$answer->id]");
                                }
                                echo '</td></tr>';
                                if ($answer != end($answers)) {
                                    echo '<tr><td><br /></td></tr>';
                                } 
                            }
                        }
                        echo '</table></table>';
                        print_simple_box_end();
                        echo "<div align=\"center\" class=\"lessonbutton standardbutton\"><a href=\"javascript:document.answerform.submit();\">".
                            get_string("pleasematchtheabovepairs", "lesson")."</a></div>\n";
                        break;
                    case LESSON_BRANCHTABLE :                        
                        $options = new stdClass;
                        $options->para = false;
                        $buttons = array('next' => array(), 'prev' => array(), 'other' => array());
                    /// seperate out next and previous jumps from the other jumps 
                        foreach ($answers as $answer) {
                            if ($answer->jumpto == LESSON_NEXTPAGE) {
                                $type = 'next';
                            } else if ($answer->jumpto == LESSON_PREVIOUSPAGE) {
                                $type = 'prev';
                            } else {
                                $type = 'other';
                            }
                            $buttons[$type][] = '<a href="javascript:document.answerform.jumpto.value='.$answer->jumpto.';document.answerform.submit();">'.
                                    strip_tags(format_text($answer->answer, FORMAT_MOODLE, $options)).'</a>';
                        }
                    
                    /// set the order and orientation (order is very important for the divs to work for horizontal!)
                        if ($page->layout) {
                            $orientation = 'horizontal';
                            $a = 'a';
                            $b = 'b';
                            $c = 'c';
                            $implode = ' ';
                            $implode2 = "\n    ";
                            if (empty($buttons['other'])) {
                                $buttons['other'][] = '&nbsp;';  // very critical! If nothing is in the middle, 
                                                                 // then the div style float left/right will not 
                                                                 // render properly with next/previous buttons
                            }
                        } else {
                            $orientation = 'vertical';
                            $a = 'c';
                            $b = 'a';
                            $c = 'b';
                            $implode = '<br /><br />';
                            $implode2 = "<br /><br />\n    ";
                        }
                        $buttonsarranged = array();
                        $buttonsarranged[$a] = '<span class="lessonbutton prevbutton prev'.$orientation.'">'.implode($implode, $buttons['prev']).'</span>';
                        $buttonsarranged[$b] = '<span class="lessonbutton nextbutton next'.$orientation.'">'.implode($implode, $buttons['next']).'</span>';
                        $buttonsarranged[$c] = '<span class="lessonbutton standardbutton standard'.$orientation.'">'.implode($implode, $buttons['other']).'</span>';
                        ksort($buttonsarranged); // sort by key
                        
                        $fullbuttonhtml = "\n<div class=\"branchbuttoncontainer\">\n    " . implode($implode2, $buttonsarranged). "\n</div>\n";
                    
                        if ($lesson->slideshow) {
                            echo '<div class="branchslidetop">' . $fullbuttonhtml . '</div>';
                            $options = new stdClass;
                            $options->noclean = true;
                            echo '<div class="contents">'.format_text($page->contents, FORMAT_MOODLE, $options)."</div>\n";
                            echo '</div><!--end slideshow div-->';
                            echo '<div class="branchslidebottom">' . $fullbuttonhtml . '</div>';
                        } else {
                            echo '<tr><td>';
                            print_simple_box($fullbuttonhtml, 'center');
                            echo '</td></tr></table>'; // ends the answers table
                        }
                        echo '<input type="hidden" name="jumpto" />';
                        
                        break;
                    case LESSON_ESSAY :
                        if (isset($USER->modattempts[$lesson->id])) {
                            $essayinfo = unserialize($attempt->useranswer);
                            $value = $essayinfo->answer;
                        } else {
                            $value = "";
                        }
                        echo '<tr><td align="center" valign="top" nowrap><label for="answer">'.get_string("youranswer", "lesson").'</label>:</td><td>'.
                             '<textarea id="answer" name="answer" rows="15" cols="60">'.$value."</textarea>\n";
                        echo '</td></tr></table>';
                        print_simple_box_end();
                        echo '<div align="center" class="lessonbutton standardbutton"><a href="javascript:document.answerform.submit();">'.
                             get_string("pleaseenteryouranswerinthebox", "lesson")."</a></div>\n";
                        break;
                }
                echo "</form>\n"; 
            } else {
                // a page without answers - find the next (logical) page
                echo "<form name=\"pageform\" method =\"post\" action=\"view.php\">\n";
                echo "<input type=\"hidden\" name=\"id\" value=\"$cm->id\" />\n";
                echo "<input type=\"hidden\" name=\"action\" value=\"navigation\" />\n";
                if ($lesson->nextpagedefault) {
                    // in Flash Card mode...
                    // ...first get number of retakes
                    $nretakes = count_records("lesson_grades", "lessonid", $lesson->id, "userid", $USER->id); 
                    // ...then get the page ids (lessonid the 5th param is needed to make get_records play)
                    $allpages = get_records("lesson_pages", "lessonid", $lesson->id, "id", "id,lessonid");
                    shuffle ($allpages);
                    $found = false;
                    if ($lesson->nextpagedefault == LESSON_UNSEENPAGE) {
                        foreach ($allpages as $thispage) {
                            if (!count_records("lesson_attempts", "pageid", $thispage->id, "userid", 
                                        $USER->id, "retry", $nretakes)) {
                                $found = true;
                                break;
                            }
                        }
                    } elseif ($lesson->nextpagedefault == LESSON_UNANSWEREDPAGE) {
                        foreach ($allpages as $thispage) {
                            if (!count_records_select("lesson_attempts", "pageid = $thispage->id AND
                                        userid = $USER->id AND correct = 1 AND retry = $nretakes")) {
                                $found = true;
                                break;
                            }
                        }
                    }
                    if ($found) {
                        $newpageid = $thispage->id;
                        if ($lesson->maxpages) {
                            // check number of pages viewed (in the lesson)
                            if (count_records("lesson_attempts", "lessonid", $lesson->id, "userid", $USER->id,
                                    "retry", $nretakes) >= $lesson->maxpages) {
                                $newpageid = LESSON_EOL;
                            }
                        }
                    } else {
                        $newpageid = LESSON_EOL;
                    }
                } else {
                    // in normal lesson mode...
                    if (!$newpageid = get_field("lesson_pages", "nextpageid", "id", $pageid)) {
                        // this is the last page - flag end of lesson
                        $newpageid = LESSON_EOL;
                    }
                }
                echo "<input type=\"hidden\" name=\"pageid\" value=\"$newpageid\" />\n";
                echo "<p align=\"center\"><input type=\"submit\" name=\"continue\" value=\"".
                     get_string("continue", "lesson")."\" /></p>\n";
                echo "</form>\n";
            }
            lesson_print_progress_bar($lesson, $course);
            echo "</table>\n"; 
        } else {
            // end of lesson reached work out grade
            
            // check to see if the student ran out of time
            $outoftime = optional_param('outoftime', '', PARAM_ALPHA);
            if ($lesson->timed && !isteacher($course->id)) {
                if ($outoftime == 'normal') {
                    print_simple_box(get_string("eolstudentoutoftime", "lesson"), "center");
                }
            }

            // Update the clock / get time information for this user
            if (!isteacher($course->id)) {
                unset($USER->startlesson[$lesson->id]);
                if (!$timer = get_records_select('lesson_timer', "lessonid = $lesson->id AND userid = $USER->id", 'starttime')) {
                    error('Error: could not find records');
                } else {
                    $timer = array_pop($timer); // this will get the latest start time record
                }
                $timer->lessontime = time();
                
                if (!update_record("lesson_timer", $timer)) {
                    error("Error: could not update lesson_timer table");
                }
            }
            
            add_to_log($course->id, "lesson", "end", "view.php?id=$cm->id", "$lesson->id", $cm->id);
            print_heading(get_string("congratulations", "lesson"));
            print_simple_box_start("center");
            $ntries = count_records("lesson_grades", "lessonid", $lesson->id, "userid", $USER->id);
            if (isset($USER->modattempts[$lesson->id])) {
                $ntries--;  // need to look at the old attempts :)
            }
            if (isstudent($course->id)) {
                
                $gradeinfo = lesson_grade($lesson, $ntries);
                
                if ($gradeinfo->attempts) {
                    if (!$lesson->custom) {
                        echo "<p align=\"center\">".get_string("numberofpagesviewed", "lesson", $gradeinfo->nquestions).
                            "</p>\n";
                        if ($lesson->minquestions) {
                            if ($gradeinfo->nquestions < $lesson->minquestions) {
                                // print a warning and set nviewed to minquestions
                                echo "<p align=\"center\">".get_string("youshouldview", "lesson", 
                                        $lesson->minquestions)."</p>\n";
                            }
                        }
                        echo "<p align=\"center\">".get_string("numberofcorrectanswers", "lesson", $gradeinfo->earned).
                            "</p>\n";
                    }
                    $a = new stdClass;
                    $a->score = $gradeinfo->earned;
                    $a->grade = $gradeinfo->total;
                    if ($gradeinfo->nmanual) {
                        $a->tempmaxgrade = $gradeinfo->total - $gradeinfo->manualpoints;
                        $a->essayquestions = $gradeinfo->nmanual;
                        echo "<div align=\"center\">".get_string("displayscorewithessays", "lesson", $a)."</div>";
                    } else {
                        echo "<div align=\"center\">".get_string("displayscorewithoutessays", "lesson", $a)."</div>";                        
                    }
                    echo "<p align=\"center\">".get_string("gradeis", "lesson", 
                            number_format($gradeinfo->grade * $lesson->grade / 100, 1)).
                        " (".get_string("outof", "lesson", $lesson->grade).")</p>\n";
                        
                    $grade->lessonid = $lesson->id;
                    $grade->userid = $USER->id;
                    $grade->grade = $gradeinfo->grade;
                    $grade->completed = time();
                    if (!$lesson->practice) {
                        if (isset($USER->modattempts[$lesson->id])) { // if reviewing, make sure update old grade record
                            if (!$grades = get_records_select("lesson_grades", "lessonid = $lesson->id and userid = $USER->id", "completed")) {
                                error("Could not find Grade Records");
                            }
                            $oldgrade = end($grades);
                            $grade->id = $oldgrade->id;
                            if (!$update = update_record("lesson_grades", $grade)) {
                                error("Navigation: grade not updated");
                            }
                        } else {
                            if (!$newgradeid = insert_record("lesson_grades", $grade)) {
                                error("Navigation: grade not inserted");
                            }
                        }
                    } else {
                        if (!delete_records("lesson_attempts", "lessonid", $lesson->id, "userid", $USER->id, "retry", $ntries)) {
                            error("Could not delete lesson attempts");
                        }
                    }
                } else {
                    if ($lesson->timed) {
                        if ($outoftime == 'normal') {
                            $grade = new stdClass;
                            $grade->lessonid = $lesson->id;
                            $grade->userid = $USER->id;
                            $grade->grade = 0;
                            $grade->completed = time();
                            if (!$lesson->practice) {
                                if (!$newgradeid = insert_record("lesson_grades", $grade)) {
                                    error("Navigation: grade not inserted");
                                }
                            }
                            echo get_string("eolstudentoutoftimenoanswers", "lesson");
                        }
                    } else {
                        echo get_string("welldone", "lesson");
                    }
                }   
            } else { 
                // display for teacher
                echo "<p align=\"center\">".get_string("displayofgrade", "lesson")."</p>\n";
            }
            print_simple_box_end(); //End of Lesson button to Continue.

            // after all the grade processing, check to see if "Show Grades" is off for the course
            // if yes, redirect to the course page
            if (!$course->showgrades) {
                redirect($CFG->wwwroot.'/course/view.php?id='.$course->id);
            }

            // high scores code
            if ($lesson->highscores && !isteacher($course->id) && !$lesson->practice) {
                echo "<div align=\"center\"><br>";
                if (!$grades = get_records_select("lesson_grades", "lessonid = $lesson->id", "completed")) {
                    echo get_string("youmadehighscore", "lesson", $lesson->maxhighscores)."<br>";
                    echo "<a href=\"view.php?id=$cm->id&amp;action=nameforhighscores\">".get_string("clicktopost", "lesson")."</a><br>";
                } else {
                    if (!$highscores = get_records_select("lesson_high_scores", "lessonid = $lesson->id")) {
                        echo get_string("youmadehighscore", "lesson", $lesson->maxhighscores)."<br>";
                        echo "<div class=\"lessonbutton standardbutton\"><a href=\"view.php?id=$cm->id&amp;action=nameforhighscores\">".get_string("clicktopost", "lesson")."</a></div><br/>";
                    } else {
                        // get all the high scores into an array
                        foreach ($highscores as $highscore) {
                            $grade = $grades[$highscore->gradeid]->grade;
                            $topscores[] = $grade;
                        }
                        // sort to find the lowest score
                        sort($topscores);
                        $lowscore = $topscores[0];
                        
                        if ($thegrade >= $lowscore || count($topscores) <= $lesson->maxhighscores) {
                            echo get_string("youmadehighscore", "lesson", $lesson->maxhighscores)."<br>";
                            echo "<div class=\"lessonbutton standardbutton\"><a href=\"view.php?id=$cm->id&amp;action=nameforhighscores\">".get_string("clicktopost", "lesson")."</a></div><br />";
                        } else {
                            echo get_string("nothighscore", "lesson", $lesson->maxhighscores)."<br>";
                        }
                    }
                }
                echo "<br /><div style=\"padding: 5px;\" class=\"lessonbutton standardbutton\"><a href=\"view.php?id=$cm->id&amp;action=highscores&link=1\">".get_string("viewhighscores", "lesson").'</a></div>';
                echo "</div>";                            
            }

            if ($lesson->modattempts && !isteacher($course->id)) {
                // make sure if the student is reviewing, that he/she sees the same pages/page path that he/she saw the first time
                // look at the attempt records to find the first QUESTION page that the user answered, then use that page id
                // to pass to view again.  This is slick cause it wont call the empty($pageid) code
                // $ntries is decremented above
                if (!$attempts = get_records_select("lesson_attempts", "lessonid = $lesson->id AND userid = $USER->id AND retry = $ntries", "timeseen")) {
                    $attempts = array();
                }
                $firstattempt = current($attempts);
                $pageid = $firstattempt->pageid;
                // IF the student wishes to review, need to know the last question page that the student answered.  This will help to make
                // sure that the student can leave the lesson via pushing the continue button.
                $lastattempt = end($attempts);
                $USER->modattempts[$lesson->id] = $lastattempt->pageid;
                echo "<div align=\"center\" style=\"padding: 5px;\" class=\"lessonbutton standardbutton\"><a href=\"view.php?id=$cm->id&amp;pageid=$pageid\">".get_string("reviewlesson", "lesson")."</a></div>\n"; 
            } elseif ($lesson->modattempts && isteacher($course->id)) {
                echo "<p align=\"center\">".get_string("modattemptsnoteacher", "lesson")."</p>";                
            }
            
            if ($lesson->activitylink) {
                if ($module = get_record('course_modules', 'id', $lesson->activitylink)) {
                    if ($modname = get_field('modules', 'name', 'id', $module->module))
                        if ($instance = get_record($modname, 'id', $module->instance)) {
                            echo "<div align=\"center\" style=\"padding: 5px;\" class=\"lessonbutton standardbutton\">".
                                    "<a href=\"$CFG->wwwroot/mod/$modname/view.php?id=$lesson->activitylink\">".
                                    get_string('activitylinkname', 'lesson', $instance->name)."</a></div>\n";
                        }
                }
            }

            echo "<div align=\"center\" style=\"padding: 5px;\" class=\"lessonbutton standardbutton\"><a href=\"../../course/view.php?id=$course->id\">".get_string("mainmenu", "lesson")."</a></div>\n"; // Back to the menu (course view).
            echo "<div align=\"center\" style=\"padding: 5px;\" class=\"lessonbutton standardbutton\"><a href=\"../../grade/index.php?id=$course->id\">".get_string("viewgrades", "lesson")."</a></div>\n"; //view grades
        }
        
        if ($lesson->displayleft || $lesson->slideshow) {  // this ends the table cell and table for the leftmenu or for slideshow
            echo "</td></tr></table>";
        } 
    }


    /*******************teacher view **************************************/
    elseif ($action == 'teacherview') {
        // set collapsed flag
        if ($mode == 'collapsed') {
            $collapsed = true;
        } else {
            $collapsed = false;
        }

        print_heading_with_help(format_string($lesson->name,true), "overview", "lesson");   

        // get number of pages
        $npages = count_records('lesson_pages', 'lessonid', $lesson->id);

        if (!$page = get_record_select("lesson_pages", "lessonid = $lesson->id AND prevpageid = 0")) {
            // if there are no pages give teacher the option to create a new page or a new branch table
            echo "<div align=\"center\">";
            if (isteacheredit($course->id)) {
                print_simple_box( "<table cellpadding=\"5\" border=\"0\">\n<tr><th>".get_string("whatdofirst", "lesson")."</th></tr><tr><td>".
                    "<a href=\"import.php?id=$cm->id&amp;pageid=0\">".
                    get_string("importquestions", "lesson")."</a></td></tr><tr><td>".
                    "<a href=\"importppt.php?id=$cm->id&amp;pageid=0\">".
                    get_string("importppt", "lesson")."</a></td></tr><tr><td>".
                    "<a href=\"lesson.php?id=$cm->id&amp;action=addbranchtable&amp;pageid=0&amp;firstpage=1\">".
                    get_string("addabranchtable", "lesson")."</a></td></tr><tr><td>".
                    "<a href=\"lesson.php?id=$cm->id&amp;action=addpage&amp;pageid=0&amp;firstpage=1\">".
                    get_string("addaquestionpage", "lesson")." ".get_string("here","lesson").
                    "</a></td></tr></table>\n");
            }
            echo '</div>';
        } else {
            // print the pages
            echo "<form name=\"lessonpages\" method=\"post\" action=\"view.php\">\n";
            echo "<input type=\"hidden\" name=\"id\" value=\"$cm->id\" />\n";
            echo "<input type=\"hidden\" name=\"action\" value=\"navigation\" />\n";
            echo "<input type=\"hidden\" name=\"pageid\" />\n";
            $branch = false;
            $singlePage = false;
            if($collapsed and !$display) {  
                echo "<div align=\"center\">\n";
                    echo "<table><tr><td>\n";
                    lesson_print_tree($page->id, $lesson, $cm->id);
                    echo "</td></tr></table>\n";
                echo "</div>\n";
            } else {
                if($display) {
                    while(true)
                    {
                        if($page->id == $display && $page->qtype == LESSON_BRANCHTABLE) {
                            $branch = true;
                            $singlePage = false;
                            break;
                        } elseif($page->id == $display) {
                            $branch = false;
                            $singlePage = true;    
                            break;
                        } elseif ($page->nextpageid) {
                            if (!$page = get_record("lesson_pages", "id", $page->nextpageid)) {
                                    error("Teacher view: Next page not found!");
                            }
                        } else {
                            // last page reached
                            break;
                        }
                    }
                    echo "<table align=\"center\" cellpadding=\"5\" border=\"0\" width=\"80%\">\n";
                    if (isteacheredit($course->id)) {
                        echo "<tr><td align=\"left\"><small><a href=\"import.php?id=$cm->id&amp;pageid=$page->prevpageid\">".
                            get_string("importquestions", "lesson")."</a> | ".
                            "<a href=\"lesson.php?id=$cm->id&amp;sesskey=".$USER->sesskey."&amp;action=addcluster&amp;pageid=$page->prevpageid\">".
                            get_string("addcluster", "lesson")."</a> | ".
                            "<a href=\"lesson.php?id=$cm->id&amp;sesskey=".$USER->sesskey."&amp;action=addendofcluster&amp;pageid=$page->prevpageid\">".
                            get_string("addendofcluster", "lesson")."</a> | ".
                            "<a href=\"lesson.php?id=$cm->id&amp;action=addbranchtable&amp;pageid=$page->prevpageid\">".
                            get_string("addabranchtable", "lesson")."</a> | ".
                            "<a href=\"lesson.php?id=$cm->id&amp;action=addpage&amp;pageid=$page->prevpageid\">".
                            get_string("addaquestionpage", "lesson")." ".get_string("here","lesson").
                            "</a></small></td></tr>\n";
                    }                  
                } else {   
                    echo "<table align=\"center\" cellpadding=\"5\" border=\"0\" width=\"80%\">\n";
                    if (isteacheredit($course->id)) {
                        echo "<tr><td align=\"left\"><small><a href=\"import.php?id=$cm->id&amp;pageid=0\">".
                            get_string("importquestions", "lesson")."</a> | ".
                            "<a href=\"lesson.php?id=$cm->id&amp;sesskey=".$USER->sesskey."&amp;action=addcluster&amp;pageid=0\">".
                            get_string("addcluster", "lesson")."</a> | ".
                            "<a href=\"lesson.php?id=$cm->id&amp;action=addbranchtable&amp;pageid=0\">".
                            get_string("addabranchtable", "lesson")."</a> | ".
                            "<a href=\"lesson.php?id=$cm->id&amp;action=addpage&amp;pageid=0\">".
                            get_string("addaquestionpage", "lesson")." ".get_string("here","lesson").
                            "</a></small></td></tr>\n";
                    }
                }
                /// end collapsed code    (note, there is an "}" below for an else above)
            while (true) {
                echo "<tr><td>\n";
                echo "<table width=\"100%\" border=\"1\" class=\"generalbox\"><tr><th colspan=\"2\">".format_string($page->title)."&nbsp;&nbsp;\n";
                if (isteacheredit($course->id)) {
                    if ($npages > 1) {
                        echo "<a title=\"".get_string("move")."\" href=\"lesson.php?id=$cm->id&amp;action=move&amp;pageid=$page->id\">\n".
                            "<img src=\"$CFG->pixpath/t/move.gif\" hspace=\"2\" height=\"11\" width=\"11\" border=\"0\" alt=\"move\" /></a>\n";
                    }
                    echo "<a title=\"".get_string("update")."\" href=\"lesson.php?id=$cm->id&amp;action=editpage&amp;pageid=$page->id\">\n".
                        "<img src=\"$CFG->pixpath/t/edit.gif\" hspace=\"2\" height=\"11\" width=\"11\" border=\"0\" alt=\"edit\" /></a>\n".
                        "<a title=\"".get_string("delete")."\" href=\"lesson.php?id=$cm->id&amp;sesskey=".$USER->sesskey."&amp;action=confirmdelete&amp;pageid=$page->id\">\n".
                        "<img src=\"$CFG->pixpath/t/delete.gif\" hspace=\"2\" height=\"11\" width=\"11\" border=\"0\" alt=\"delete\" /></a>\n";
                }
                echo "</th></tr>\n";             
                echo "<tr><td colspan=\"2\">\n";
                $options = new stdClass;
                $options->noclean = true;
                print_simple_box(format_text($page->contents, FORMAT_MOODLE, $options), "center");
                echo "</td></tr>\n";
                // get the answers in a set order, the id order
                if ($answers = get_records("lesson_answers", "pageid", $page->id, "id")) {
                    echo "<tr><td colspan=\"2\" align=\"center\"><b>\n";
                    switch ($page->qtype) {
                        case LESSON_ESSAY :
                            echo $LESSON_QUESTION_TYPE[$page->qtype];
                            break;
                        case LESSON_SHORTANSWER :
                            echo $LESSON_QUESTION_TYPE[$page->qtype];
                            if ($page->qoption) {
                                echo " - ".get_string("casesensitive", "lesson");
                            }
                            break;
                        case LESSON_MULTICHOICE :
                            echo $LESSON_QUESTION_TYPE[$page->qtype];
                            if ($page->qoption) {
                                echo " - ".get_string("multianswer", "lesson");
                            }
                            break;
                        case LESSON_MATCHING :
                            echo $LESSON_QUESTION_TYPE[$page->qtype];
                            echo get_string("firstanswershould", "lesson");
                            break;
                        case LESSON_TRUEFALSE :
                        case LESSON_NUMERICAL :
                            echo $LESSON_QUESTION_TYPE[$page->qtype];
                            break;
                        case LESSON_BRANCHTABLE :    
                            echo get_string("branchtable", "lesson");
                            break;
                        case LESSON_ENDOFBRANCH :
                            echo get_string("endofbranch", "lesson");
                            break;
                        case LESSON_CLUSTER :
                            echo get_string("clustertitle", "lesson");
                            break;
                        case LESSON_ENDOFCLUSTER :
                            echo get_string("endofclustertitle", "lesson");
                            break;
                    }
                    echo "</b></td></tr>\n";
                    $i = 1;
                    $n = 0;
                    foreach ($answers as $answer) {
                        switch ($page->qtype) {
                            case LESSON_MULTICHOICE:
                            case LESSON_TRUEFALSE:
                            case LESSON_SHORTANSWER:
                            case LESSON_NUMERICAL:
                                echo "<tr><td align=\"right\" valign=\"top\" width=\"20%\">\n";
                                if ($lesson->custom) {
                                    // if the score is > 0, then it is correct
                                    if ($answer->score > 0) {
                                        echo "<b><u>".get_string("answer", "lesson")." $i:</u></b> \n";
                                    } else {
                                        echo "<b>".get_string("answer", "lesson")." $i:</b> \n";
                                    }
                                } else {
                                    if (lesson_iscorrect($page->id, $answer->jumpto)) {
                                        // underline correct answers
                                        echo "<b><u>".get_string("answer", "lesson")." $i:</u></b> \n";
                                    } else {
                                        echo "<b>".get_string("answer", "lesson")." $i:</b> \n";
                                    }
                                }
                                $options = new stdClass;
                                $options->noclean = true;
                                echo "</td><td width=\"80%\">\n";
                                echo format_text($answer->answer, FORMAT_MOODLE, $options);
                                echo "</td></tr>\n";
                                echo "<tr><td align=\"right\" valign=\"top\"><b>".get_string("response", "lesson")." $i:</b> \n";
                                echo "</td><td>\n";
                                echo format_text($answer->response, FORMAT_MOODLE, $options); 
                                echo "</td></tr>\n";
                                break;                            
                            case LESSON_MATCHING:
                                $options = new stdClass;
                                $options->noclean = true;
                                if ($n < 2) {
                                    if ($answer->answer != NULL) {
                                        if ($n == 0) {
                                            echo "<tr><td align=\"right\" valign=\"top\"><b>".get_string("correctresponse", "lesson").":</b> \n";
                                            echo "</td><td>\n";
                                            echo format_text($answer->answer, FORMAT_MOODLE, $options); 
                                            echo "</td></tr>\n";
                                        } else {
                                            echo "<tr><td align=\"right\" valign=\"top\"><b>".get_string("wrongresponse", "lesson").":</b> \n";
                                            echo "</td><td>\n";
                                            echo format_text($answer->answer, FORMAT_MOODLE, $options); 
                                            echo "</td></tr>\n";
                                        }
                                    }
                                    $n++;
                                    $i--;
                                } else {
                                    echo "<tr><td align=\"right\" valign=\"top\" width=\"20%\">\n";
                                    if ($lesson->custom) {
                                        // if the score is > 0, then it is correct
                                        if ($answer->score > 0) {
                                            echo "<b><u>".get_string("answer", "lesson")." $i:</u></b> \n";
                                        } else {
                                            echo "<b>".get_string("answer", "lesson")." $i:</b> \n";
                                        }
                                    } else {
                                        if (lesson_iscorrect($page->id, $answer->jumpto)) {
                                            // underline correct answers
                                            echo "<b><u>".get_string("answer", "lesson")." $i:</u></b> \n";
                                        } else {
                                            echo "<b>".get_string("answer", "lesson")." $i:</b> \n";
                                        }
                                    }
                                    echo "</td><td width=\"80%\">\n";
                                    echo format_text($answer->answer, FORMAT_MOODLE, $options);
                                    echo "</td></tr>\n";
                                   echo "<tr><td align=\"right\" valign=\"top\"><b>".get_string("matchesanswer", "lesson")." $i:</b> \n";
                                    echo "</td><td>\n";
                                    echo format_text($answer->response, FORMAT_MOODLE, $options); 
                                    echo "</td></tr>\n";
                                }
                                break;
                            case LESSON_BRANCHTABLE:
                                $options = new stdClass;
                                $options->noclean = true;
                                echo "<tr><td align=\"right\" valign=\"top\" width=\"20%\">\n";
                                echo "<b>".get_string("description", "lesson")." $i:</b> \n";
                                echo "</td><td width=\"80%\">\n";
                                echo format_text($answer->answer, FORMAT_MOODLE, $options);
                                echo "</td></tr>\n";
                                break;
                        }
                        if ($answer->jumpto == 0) {
                            $jumptitle = get_string("thispage", "lesson");
                        } elseif ($answer->jumpto == LESSON_NEXTPAGE) {
                            $jumptitle = get_string("nextpage", "lesson");
                        } elseif ($answer->jumpto == LESSON_EOL) {
                            $jumptitle = get_string("endoflesson", "lesson");
                        } elseif ($answer->jumpto == LESSON_UNSEENBRANCHPAGE) {
                            $jumptitle = get_string("unseenpageinbranch", "lesson");
                        } elseif ($answer->jumpto == LESSON_PREVIOUSPAGE) {
                            $jumptitle = get_string("previouspage", "lesson");
                        } elseif ($answer->jumpto == LESSON_RANDOMPAGE) {
                            $jumptitle = get_string("randompageinbranch", "lesson");
                        } elseif ($answer->jumpto == LESSON_RANDOMBRANCH) {
                            $jumptitle = get_string("randombranch", "lesson");
                        } elseif ($answer->jumpto == LESSON_CLUSTERJUMP) {
                            $jumptitle = get_string("clusterjump", "lesson");
                        } else {
                            if (!$jumptitle = get_field("lesson_pages", "title", "id", $answer->jumpto)) {
                                $jumptitle = "<b>".get_string("notdefined", "lesson")."</b>";
                            }
                        }
                        $jumptitle = format_string($jumptitle,true);
                        if ($page->qtype == LESSON_MATCHING) {
                            if ($i == 1) {
                                echo "<tr><td align=\"right\" width=\"20%\"><b>".get_string("correctanswerscore", "lesson").":";
                                echo "</b></td><td width=\"80%\">\n";
                                echo "$answer->score</td></tr>\n";
                                echo "<tr><td align=\"right\" width=\"20%\"><b>".get_string("correctanswerjump", "lesson").":";
                                echo "</b></td><td width=\"80%\">\n";
                                echo "$jumptitle</td></tr>\n";
                            } elseif ($i == 2) {
                                echo "<tr><td align=\"right\" width=\"20%\"><b>".get_string("wronganswerscore", "lesson").":";
                                echo "</b></td><td width=\"80%\">\n";
                                echo "$answer->score</td></tr>\n";
                                echo "<tr><td align=\"right\" width=\"20%\"><b>".get_string("wronganswerjump", "lesson").":";
                                echo "</b></td><td width=\"80%\">\n";
                                echo "$jumptitle</td></tr>\n";
                            }
                        } else {
                            if ($lesson->custom and 
                                $page->qtype != LESSON_BRANCHTABLE and 
                                $page->qtype != LESSON_ENDOFBRANCH and
                                $page->qtype != LESSON_CLUSTER and 
                                $page->qtype != LESSON_ENDOFCLUSTER) {
                                echo "<tr><td align=\"right\" width=\"20%\"><b>".get_string("score", "lesson")." $i:";
                                echo "</b></td><td width=\"80%\">\n";
                                echo "$answer->score</td></tr>\n";
                            }
                            echo "<tr><td align=\"right\" width=\"20%\"><b>".get_string("jump", "lesson")." $i:";
                            echo "</b></td><td width=\"80%\">\n";
                            echo "$jumptitle</td></tr>\n";
                        }
                        $i++;
                    }
                    // print_simple_box_end();  // not sure if i commented this out... hehe
                    echo "<tr><td colspan=\"2\" align=\"center\">";
                    if ($page->qtype != LESSON_ENDOFBRANCH) {
                        echo "<input type=\"button\" value=\"";
                        if ($page->qtype == LESSON_BRANCHTABLE) {
                            echo get_string("checkbranchtable", "lesson");
                        } else {
                            echo get_string("checkquestion", "lesson");
                        }
                        echo "\" onclick=\"document.lessonpages.pageid.value=$page->id;".
                            "document.lessonpages.submit();\" />";
                    }
                    echo "&nbsp;</td></tr>\n";
                }
                echo "</table></td></tr>\n";
                if (isteacheredit($course->id)) {
                    echo "<tr><td align=\"left\"><small><a href=\"import.php?id=$cm->id&amp;pageid=$page->id\">".
                        get_string("importquestions", "lesson")."</a> | ".    
                         "<a href=\"lesson.php?id=$cm->id&amp;sesskey=".$USER->sesskey."&amp;action=addcluster&amp;pageid=$page->id\">".
                         get_string("addcluster", "lesson")."</a> | ".
                         "<a href=\"lesson.php?id=$cm->id&amp;sesskey=".$USER->sesskey."&amp;action=addendofcluster&amp;pageid=$page->id\">".
                         get_string("addendofcluster", "lesson")."</a> | ".
                         "<a href=\"lesson.php?id=$cm->id&amp;action=addbranchtable&amp;pageid=$page->id\">".
                        get_string("addabranchtable", "lesson")."</a><br />";
                    // the current page or the next page is an end of branch don't show EOB link
                    $nextqtype = 0; // set to anything else EOB
                    if ($page->nextpageid) {
                        $nextqtype = get_field("lesson_pages", "qtype", "id", $page->nextpageid);
                    }
                    if (($page->qtype != LESSON_ENDOFBRANCH) and ($nextqtype != LESSON_ENDOFBRANCH)) {
                        echo "<a href=\"lesson.php?id=$cm->id&amp;sesskey=".$USER->sesskey."&amp;action=addendofbranch&amp;pageid=$page->id\">".
                        get_string("addanendofbranch", "lesson")."</a> | ";
                    }
                    echo "<a href=\"lesson.php?id=$cm->id&amp;action=addpage&amp;pageid=$page->id\">".
                        get_string("addaquestionpage", "lesson")." ".get_string("here","lesson").
                        "</a></small></td></tr>\n";
                }
//                echo "<tr><td>\n";
                // check the prev links - fix (silently) if necessary - there was a bug in
                // versions 1 and 2 when add new pages. Not serious then as the backwards
                // links were not used in those versions
                if (isset($prevpageid)) {
                    if ($page->prevpageid != $prevpageid) {
                        // fix it
                        set_field("lesson_pages", "prevpageid", $prevpageid, "id", $page->id);
                        if ($CFG->debug) {
                            echo "<p>***prevpageid of page $page->id set to $prevpageid***";
                        }
                    }
                }
                $prevpageid = $page->id;
                // move to next page
                if($singlePage) {  // this will make sure only one page is displayed if needed
                    break;
                } elseif($branch && $page->qtype == LESSON_ENDOFBRANCH) {  // this will display a branch table and its contents
                    break;
                } elseif ($page->nextpageid) {
                    if (!$page = get_record("lesson_pages", "id", $page->nextpageid)) {
                        error("Teacher view: Next page not found!");
                    }
                } else {
                    // last page reached
                    break;
                }
            }
        } // end of else from above collapsed code!!!
        
            echo "</table></form>\n";
        } 
    }

    /*******************essay view **************************************/ // 6/29/04
    elseif ($action == 'essayview') {
        print_heading_with_help(format_string($lesson->name,true), "overview", "lesson");

        // get lesson pages that are essay
        if (!$pages = get_records_select("lesson_pages", "lessonid = $lesson->id AND qtype = ".LESSON_ESSAY)) {
            notify(get_string('noessayquestionsfound', 'lesson'));
            print_footer($course);
            exit();
        }
        
        // get only the attempts that are in response to essay questions
        $pageids = implode(",", array_keys($pages)); // all the pageids in comma seperated list
        if (!$essayattempts = get_records_select("lesson_attempts", "lessonid = $lesson->id AND pageid IN($pageids)")) {
            notify(get_string('noonehasanswered', 'lesson'));//error ("No one has answered essay questions yet...");
            print_footer($course);
            exit();
        }
        
        // get all the users who have taken this lesson, order by their last name
        if (!$users = get_records_sql("SELECT DISTINCT u.*
                                 FROM {$CFG->prefix}user u,
                                      {$CFG->prefix}lesson_attempts a
                                 WHERE a.lessonid = '$lesson->id' and
                                       u.id = a.userid
                                 ORDER BY u.lastname")) {
            error("Error: could not find users");
        }
        
        // group all the essays by userid
        $studentessays = array();
        foreach ($essayattempts as $essay) {
            // not very nice :) but basically
            // this organizes the essays so I know how many times a student answered an essay per try and per page
            $studentessays[$essay->userid][$essay->pageid][$essay->retry][] = $essay;            
        }

        $table = new stdClass;
        $table->head = array($course->students, get_string("essays", "lesson"), get_string("email", "lesson"));
        $table->align = array("left", "left", "left");
        $table->wrap = array("nowrap", "wrap", "nowrap");
        $table->width = "90%";
        $table->size = array("*", "70%", "*");             

        // get the student ids of the students who have answered the essay question
        $studentids = array_keys($studentessays);
        
        // cycle through all the ids
        foreach ($studentids as $id) {
            $studentname = fullname($users[$id], true);
            $essaylinks = array();
            
            // number of attempts on the lesson
            $attempts = count_records('lesson_grades', 'userid', $id, 'lessonid', $lesson->id);
            
            // go through each essay
            foreach ($studentessays[$id] as $page => $tries) {
                $count = 0;
                
                // go through each essay per page
                foreach($tries as $try) {
                    if ($count == $attempts) {
                        break;  // stop displaying essays (attempt not completed)
                    }
                    $count++;

                    // make sure they didn't answer it more than the max number of attmepts
                    if (count($try) > $lesson->maxattempts) {
                        $essay = $try[$lesson->maxattempts-1];
                    } else {
                        $essay = end($try);
                    }
                    $essayinfo = unserialize($essay->useranswer);
                    // different colors for all the states of an essay (graded, if sent, not graded)
                    if (!$essayinfo->graded) {
                        $style = "style='color:#DF041E;text-decoration:underline;'";
                    } elseif (!$essayinfo->sent) {
                        $style = "style='color:#006600;text-decoration:underline;'";
                    } else {
                        $style = "style='color:#999999;'";
                    }
                    // link for each essay
                    $essaylinks[] = "<a $style href=\"view.php?id=$cm->id&amp;action=essaygrade&attemptid=$essay->id\">".format_string($pages[$essay->pageid]->title,true)."</a>";
                }
            }
            // email link for this user
            $emaillink = "<a href=\"view.php?id=$cm->id&amp;action=emailessay&amp;userid=".$id."&amp;sesskey=".$USER->sesskey."\">".get_string("emailgradedessays", "lesson")."</a>";

            $table->data[] = array($studentname, implode(", ", $essaylinks), $emaillink);        
        }
        // email link for all users
        $emailalllink = "<a href=\"view.php?id=$cm->id&amp;action=emailessay&amp;sesskey=".$USER->sesskey."\">".get_string("emailallgradedessays", "lesson")."</a>";
        
        $table->data[] = array(" ", " ", $emailalllink);
        
        print_table($table);
    }
    
    /*******************grade essays **************************************/ // 6/29/04
    elseif ($action == 'essaygrade') {
        print_heading_with_help(format_string($lesson->name,true), "overview", "lesson");
        
        $attemptid = required_param('attemptid', PARAM_INT);

        if (!$essay = get_record("lesson_attempts", "id", $attemptid)) {
            error("Error: could not find attempt");
        }
        if (!$page = get_record("lesson_pages", "id", $essay->pageid)) {
            error("Error: could not find lesson pages");
        }
        if (!$student = get_record("user", "id", $essay->userid)) {
            error("Error: could not find users");
        }
        if (!$answer = get_record("lesson_answers", "lessonid", $lesson->id, "pageid", $page->id)) {
            error("Error: could not find answer");
        }


        echo "<form name=\"essaygrade\" method=\"post\" action=\"view.php\">\n";
        echo "<input type=\"hidden\" name=\"id\" value=\"$cm->id\" />\n";
        echo "<input type=\"hidden\" name=\"action\" />\n";
        echo "<input type=\"hidden\" name=\"attemptid\" value=\"$attemptid\" />\n";
        echo "<input type=\"hidden\" name=\"sesskey\" value=\"".$USER->sesskey."\" />\n";        
    
        // all tables will have these
        $table = new stdClass;
        $table->align = array("left");
        $table->wrap = array();
        $table->width = "70%";
        $table->size = array("100%");
        
        
        $table->head = array(get_string("question", "lesson"));
        $options = new stdClass;
        $options->noclean = true;
        $table->data[] = array(format_text($page->contents, FORMAT_MOODLE, $options));

        print_table($table);
        echo "<br />";

        unset($table->data);
        $essayinfo = unserialize($essay->useranswer);        

        $studentname = $student->firstname." ".$student->lastname;
        $table->head = array(get_string("studentresponse", "lesson", $studentname));
        $table->data[] = array(format_text(stripslashes($essayinfo->answer)));
        
        print_table($table);
        echo "<br />";
        
        unset($table->data);

        $table->head = array(get_string("comments", "lesson"));
        $table->data[] = array("<textarea id=\"answer\" name=\"response\" rows=\"15\" cols=\"60\">".$essayinfo->response."</textarea>\n");    
        $options = array();
        if ($lesson->custom) {
            for ($i=$answer->score; $i>=0; $i--) {
                $options[$i] = $i;
            }
        } else {
            $options[0] = "incorrect";
            $options[1] = "correct";
        }
        $table->data[] = array(get_string("essayscore", "lesson").": ".lesson_choose_from_menu($options, "score", $essayinfo->score, "", "", "", true));
                
        print_table($table);
        echo "<br />";
        echo "<table align=\"center\"><tr><td>";
        echo "<input type=\"button\" value=\"Cancel\" onclick=\"document.essaygrade.action.value='essayview';".
             "document.essaygrade.submit();\" />";
        echo "</td><td>";
        echo "<input type=\"button\" value=\"Submit Grade\" onclick=\"document.essaygrade.action.value='updategrade';".
             "document.essaygrade.submit();\" />";
        echo "</td></tr></table>";
        echo "</form>";
        
        
    }

    /*******************update grade**************************************/ // 6/29/04
    elseif ($action == 'updategrade') {
        print_heading_with_help(format_string($lesson->name,true), "overview", "lesson");
        
        confirm_sesskey();
        
        $form = data_submitted();
        
        if (!$essay = get_record("lesson_attempts", "id", clean_param($form->attemptid, PARAM_INT))) {
            error("Error: could not find essay");
        }

        if (!$grades = get_records_select("lesson_grades", "lessonid = $lesson->id and userid = $essay->userid", "completed", "*", $essay->retry, 1)) {
            error("Error: could not find grades");
        }
        
        $essayinfo = new stdClass;
        $essayinfo = unserialize($essay->useranswer);

        $essayinfo->graded = 1;
        $essayinfo->score = clean_param($form->score, PARAM_INT);
        $essayinfo->response = stripslashes_safe($form->response);
        $essayinfo->sent = 0;
        if (!$lesson->custom && $essayinfo->score == 1) {
            $essay->correct = 1;
        } else {
            $essay->correct = 0;
        }

        $essay->useranswer = addslashes(serialize($essayinfo));

        if (!update_record("lesson_attempts", $essay)) {
            error("Could not update essay score");
        }

        $grade = current($grades);

        $gradeinfo = lesson_grade($lesson, $essay->retry, $essay->userid);    
        $updategrade->id = $grade->id;
        $updategrade->grade = $gradeinfo->grade;
        if(update_record("lesson_grades", $updategrade)) {
            redirect("view.php?id=$cm->id&amp;action=essayview", get_string("updatesuccess", "lesson"));
        } else {
            echo get_string("updatefailed", "lesson")."!<br>";
            echo "<a href=\"view.php?id=$cm->id&amp;action=essayview\">".get_string("continue", "lesson")."</a>";
            exit();
        }
    }

    /*******************email essay **************************************/ // 6/29/04
    elseif ($action == 'emailessay') {
        print_heading_with_help(format_string($lesson->name,true), "overview", "lesson");
   
        confirm_sesskey();
    
        if ($userid = optional_param('userid', 0, PARAM_INT)) {
            $queryadd = " AND userid = ".$userid;
            if (! $users = get_records("user", "id", $userid)) {
                error("Error: could not find users");
            }
        } else {
            $queryadd = "";
            if (!$users = lesson_get_participants($lesson->id)) {
                error("Error: could not find users");
            }
        }
        
        // get lesson pages that are essay
        if (!$pages = get_records_select("lesson_pages", "lessonid = $lesson->id AND qtype = ".LESSON_ESSAY)) {
            error("Error: could not find lesson pages");
        }
        
        // get only the attempts that are in response to essay questions
        $pageids = implode(",", array_keys($pages)); // all the pageids in comma seperated list
        if (!$essayattempts = get_records_select("lesson_attempts", "lessonid = $lesson->id AND pageid IN($pageids)".$queryadd)) {
            error ("No one has answered essay questions yet...");
        }
        
        if (!$essayanswers = get_records_select("lesson_answers", "lessonid = $lesson->id AND pageid IN($pageids)", "", "pageid, score")) {
            error ("Could not find answer records.");
        }

        $options = new stdClass;
        $options->noclean = true;

        // NoticeFix  big fix, change $essay[]'s that use $USER to just $USER
        foreach ($essayattempts as $essay) {
            $essayinfo = unserialize($essay->useranswer);
            if ($essayinfo->graded && !$essayinfo->sent) {                
                $subject = get_string('essayemailsubject', 'lesson', format_string($pages[$essay->pageid]->title,true));
                $message = get_string('question', 'lesson').":<br>";
                $message .= format_text($pages[$essay->pageid]->contents, FORMAT_MOODLE, $options);
                $message .= "<br><br>";
                $message .= get_string('yourresponse', 'lesson').":<br>";
                $message .= format_text(stripslashes($essayinfo->answer));
                $message .= "<br><br>";
                $message .= get_string('commentswithname', 'lesson', $USER).":<br>";
                $message .= format_text(stripslashes($essayinfo->response), FORMAT_MOODLE, $options);
                $message .= "<br><br>";
                $grades = get_records_select("lesson_grades", "lessonid = $lesson->id and userid = $essay->userid", "completed", "*", $essay->retry, 1);
                $grade = current($grades);
                if ($lesson->custom) {
                    $points->score = $essayinfo->score;
                    $points->outof = $essayanswers[$essay->pageid]->score;
                    $message .= get_string("youhavereceived", "lesson", $points);
                } else {
                    $points->score = $essayinfo->score;
                    $points->outof = 1;
                    $message .= get_string("youhavereceived", "lesson", $points);
                }
                $message .= "<br><br>";
                $message .= get_string("yourgradeisnow", "lesson", $grade->grade)."%.";
                
                $plaintxt = format_text_email($message, FORMAT_HTML);

                if(email_to_user($users[$essay->userid], $USER, $subject, $plaintxt, $message)) {
                    $essayinfo->sent = 1;
                    $essay->useranswer = addslashes(serialize($essayinfo));
                    update_record("lesson_attempts", $essay);
                } else {
                    echo "Email Failed!<br>";
                    echo "<a href=\"view.php?id=$cm->id&amp;action=essayview\">".get_string("continue", "lesson")."</a>";
                    echo "</div>";
                    exit();
                }
            }
        }
        redirect("view.php?id=$cm->id&amp;action=essayview", get_string("emailsuccess", "lesson"));
    }

    /*******************high scores **************************************/
    elseif ($action == 'highscores') {
        print_heading_with_help(format_string($lesson->name,true), "overview", "lesson");

        if (!$grades = get_records_select("lesson_grades", "lessonid = $lesson->id", "completed")) {
            $grades = array();
        }
        
        print_heading(get_string("topscorestitle", "lesson", $lesson->maxhighscores), 'center', 4);

        if (!$highscores = get_records_select("lesson_high_scores", "lessonid = $lesson->id")) {
            print_heading(get_string("nohighscores", "lesson"), 'center', 3);
        } else {
            foreach ($highscores as $highscore) {
                $grade = $grades[$highscore->gradeid]->grade;
                $topscores[$grade][] = $highscore->nickname;
            }
            krsort($topscores);
                       
            $table = new stdClass;
            $table->align = array('center', 'left', 'right');
            $table->wrap = array();
            $table->width = "30%";
            $table->cellspacing = '10px';
            $table->size = array('*', '*', '*');
            
            $table->head = array(get_string("rank", "lesson"), $course->students, get_string("scores", "lesson"));
            
            $printed = 0;
            while (true) {
                $temp = current($topscores);
                $score = key($topscores);
                $rank = $printed + 1;
                sort($temp); 
                foreach ($temp as $student) {
                    $table->data[] = array($rank, $student, $score);
                }
                $printed++;
                if (!next($topscores) || !($printed < $lesson->maxhighscores)) { 
                    break;
                }
            }
            print_table($table);
        }
        
        if (!isteacher($course->id)) {  // teachers don't need the links
            echo '<div align="center">';
            if (optional_param('link', 0, PARAM_INT)) {
                echo "<br /><div class=\"lessonbutton standardbutton\"><a href=\"../../course/view.php?id=$course->id\">".get_string("returntocourse", "lesson")."</a></div>";
            } else {
                echo "<br /><span class=\"lessonbutton standardbutton\"><a href=\"../../course/view.php?id=$course->id\">".get_string("cancel", "lesson").'</a></span> '.
                    " <span class=\"lessonbutton standardbutton\"><a href=\"view.php?id=$cm->id&amp;action=navigation\">".get_string("startlesson", "lesson").'</a></span>';
            }
            echo "</div>";
        }
    }
    /*******************update high scores **************************************/
    elseif ($action == 'updatehighscores') {
        print_heading_with_help(format_string($lesson->name,true), "overview", "lesson");
    
        confirm_sesskey();

        if (!$grades = get_records_select("lesson_grades", "lessonid = $lesson->id", "completed")) {
            error("Error: could not find grades");
        }
        if (!$usergrades = get_records_select("lesson_grades", "lessonid = $lesson->id and userid = $USER->id", "completed DESC")) {
            error("Error: could not find grades");
        }
        echo "<div align=\"center\">";
        echo get_string("waitpostscore", "lesson")."<br>";
        
        foreach ($usergrades as $usergrade) {
            // get their latest grade
            $newgrade = $usergrade;
            break;
        }
        
        if ($pasthighscore = get_record_select("lesson_high_scores", "lessonid = $lesson->id and userid = $USER->id")) {
            $pastgrade = $grades[$pasthighscore->gradeid]->grade;
            if ($pastgrade >= $newgrade->grade) {
                redirect("view.php?id=$cm->id&amp;action=highscores&amp;link=1", "Update Successful");
            } else {
                // delete old and find out where new one goes
                if (!delete_records("lesson_high_scores", "id", $pasthighscore->id)) {
                    error("Error: could not delete old high score");
                }
            }
        }
        // find out if we need to delete any records
        if ($highscores = get_records_select("lesson_high_scores", "lessonid = $lesson->id")) {  // if no high scores... then just insert our new one
            foreach ($highscores as $highscore) {
                $grade = $grades[$highscore->gradeid]->grade;
                $topscores[$grade][] = $highscore->userid;
            }
            if (!(count($topscores) < $lesson->maxhighscores)) { // if the top scores list is not full then dont need to worry about removing old scores
                $scores = array_keys($topscores);
                $flag = true;                
                // see if the new score is already listed in the top scores list
                // if it is listed, then dont need to delete any records
                foreach ($scores as $score) {
                    if ($score = $newgrade->grade) {
                        $flag = false;
                    }
                }    
                if ($flag) { // if the score does not exist in the top scores list, then the lowest scores get thrown out.
                    ksort($topscores); // sort so the lowest score is first element
                    $lowscore = current($topscores);
                    // making a delete statement to delete all users with the lowest score
                    $deletestmt = 'lessonid = '. $lesson->id .' and userid = ';
                    $deletestmt .= current($lowscore);
                    while (next($lowscore)) {
                        $deletestmt .= " or userid = ".current($lowscore);
                    }
                    if (!delete_records_select('lesson_high_scores', $deletestmt)) {
                        /// not a big deal...
                        error('Did not delete extra high score(s)');
                    }
                }
            }
        }
        
        $newhighscore = new stdClass;
        $newhighscore->lessonid = $lesson->id;
        $newhighscore->userid = $USER->id;
        $newhighscore->gradeid = $newgrade->id;
        $newhighscore->nickname = optional_param('name', '', PARAM_CLEAN);
        
        if (!insert_record("lesson_high_scores", $newhighscore)) {
            error("Insert of new high score Failed!");
        }
        
        redirect("view.php?id=$cm->id&amp;action=highscores&amp;link=1", get_string("postsuccess", "lesson"));
        echo "</div>";
    }
    /*******************name for highscores **************************************/
    elseif ($action == 'nameforhighscores') {
        print_heading_with_help(format_string($lesson->name,true), "overview", "lesson");
        echo "<div align=\"center\">";
        if ($name = trim(optional_param('name', '', PARAM_CLEAN))) {
            if (lesson_check_nickname($name)) {
                redirect("view.php?id=$cm->id&amp;action=updatehighscores&amp;name=$name&amp;sesskey=".$USER->sesskey, get_string("nameapproved", "lesson"));
            } else {
                echo get_string("namereject", "lesson")."<br /><br />";
            }
        }
                
        echo "<form name=\"nickname\" method =\"post\" action=\"view.php\">";
        echo "<input type=\"hidden\" name=\"id\" value=\"$cm->id\" />";
        echo "<input type=\"hidden\" name=\"action\" value=\"nameforhighscores\" />";
        
        echo get_string("entername", "lesson").": <input type=\"text\" name=\"name\" maxlength=\"5\"><br />";
        echo "<input type=\"submit\" value=\"".get_string("submitname", "lesson")."\" />";
        echo "</form>";
        echo "</div>";
    }    
    /*************** no man's land **************************************/
    else {
        error("Fatal Error: Unknown Action: ".$action."\n");
    }
/// Finish the page
    print_footer($course);

?>