equilibrium /duties.php

Language PHP Lines 1831
MD5 Hash 4fff853d547692b32e0448f1da902296 Estimated Cost $36,996 (why?)
Repository https://github.com/obenauer/equilibrium.git View Raw File View Project SPDX
   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
<?php
// Copyright 2008, St. Jude Children's Research Hospital.
// Written by Dr. John Obenauer, john.obenauer@stjude.org.

// This file is part of Equilibrium.  Equilibrium is free software:
// you can redistribute it and/or modify it under the terms of the
// GNU General Public License as published by the Free Software
// Foundation, either version 2 of the License, or (at your option)
// any later version.

// Equilibrium is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Equilibrium.  If not, see <http://www.gnu.org/licenses/>.

require("check_login.php");
require_once("config.php");

// Check for passed arguments
if (isset($_REQUEST['action'])) {
    $action = $_REQUEST['action'];
} else {
    $action = "";
}

if (isset($_REQUEST['status'])) {
    $status = $_REQUEST['status'];
} else {
    $status = "Active";
}

if (isset($_REQUEST['staff'])) {
    $staff = $_REQUEST['staff'];
} else {
    if ($_SESSION['SESSION_STAFF'] == "Y") {
        $staff = $_SESSION['SESSION_USERID'];
    } else {
        $staff = 0;
    }
}

if (isset($_REQUEST['maxresults'])) {
    $maxresults = $_REQUEST['maxresults'];
    if ($maxresults == 0) {
        $maxresults = 10;
    }
} else {
    $maxresults = 10;
}

if (isset($_REQUEST['page'])) {
    $page = $_REQUEST['page'];
} else {
    $page = 1;
}

if (isset($_REQUEST['cmd'])) {
    $cmd = $_REQUEST['cmd'];
} else {
    $cmd = "";
}

if (isset($_REQUEST['title'])) {
    $title = $_REQUEST['title'];
} else {
    $title = "";
}

if (isset($_REQUEST['dtype'])) {
    $dtype = $_REQUEST['dtype'];
} else {
    $dtype = "";
}

if (isset($_REQUEST['description'])) {
    $description = $_REQUEST['description'];
} else {
    $description = "";
}

if (isset($_REQUEST['client'])) {
    $client = $_REQUEST['client'];
} else {
    $client = "";
}

if (isset($_REQUEST['contact'])) {
    $contact = $_REQUEST['contact'];
} else {
    $contact = "";
}

if (isset($_REQUEST['enterdate'])) {
    $enterdate = $_REQUEST['enterdate'];
} else {
    $enterdate = "";
}

if (isset($_REQUEST['project'])) {
    $project = $_REQUEST['project'];
} else {
    $project = 0;
}

if (isset($_REQUEST['duty'])) {
    $duty = $_REQUEST['duty'];
} else {
    $duty = 0;
}

if (isset($_REQUEST['visibility'])) {
    $visibility = $_REQUEST['visibility'];
} else {
    $visibility = 'Public';
}

if (isset($_REQUEST['fromdate'])) {
    $fromdate = $_REQUEST['fromdate'];
} else {
    // Default: one month ago
    $prevmonth = mktime(0, 0, 0, date("m") - 1, date("d"), date("Y"));
    $fromdate = date("Y", $prevmonth) . "-" . date("m", $prevmonth) . "-" .    
        date("d", $prevmonth);
}

if (isset($_REQUEST['todate'])) {
    $todate = $_REQUEST['todate'];
} else {
    // Default: today's date
    $todate = date('Y') . "-" . date('m') . "-" . date('d');
}

if (isset($_REQUEST['newstatus'])) {
    $newstatus = $_REQUEST['newstatus'];
} else {
    $newstatus = "";
}

if (isset($_REQUEST['comment'])) {
    $comment = $_REQUEST['comment'];
} else {
    $comment = "";
}

if (isset($_REQUEST['submitter'])) {
    $submitter = $_REQUEST['submitter'];
} else {
    $submitter = "";
}

if (isset($_REQUEST['dirtree'])) {
    $dirtree = $_REQUEST['dirtree'];
} else {
    $dirtree = "";
}

if (isset($_FILES['filename'])) {
    $filename = $_FILES['filename']['name'];
} else {
    $filename = "";
}

if (isset($_REQUEST['existingfile'])) {
    $existingfile = $_REQUEST['existingfile'];
} else {
    $existingfile = "";
}

if (isset($_REQUEST['filecat'])) {
    $filecat = $_REQUEST['filecat'];
} else {
    $filecat = "";
}

if (isset($_REQUEST['filedesc'])) {
    $filedesc = $_REQUEST['filedesc'];
} else {
    $filedesc = "";
}

if (isset($_REQUEST['file_id'])) {
    $file_id = $_REQUEST['file_id'];
} else {
    $file_id = "";
}

if (isset($_REQUEST['order'])) {
    $order = $_REQUEST['order'];
} else {
    $order = "";
}

if (isset($_REQUEST['edit_priv'])) {
    $edit_priv = $_REQUEST['edit_priv'];
} else {
    $edit_priv = "N";
}

if (isset($_REQUEST['todostatus'])) {
    $todostatus = $_REQUEST['todostatus'];
} else {
    $todostatus = "Pending";
}

if (isset($_REQUEST['priority'])) {
    $priority = $_REQUEST['priority'];
} else {
    $priority = "High";
}

if (isset($_REQUEST['calmode'])) {
    $calmode = $_REQUEST['calmode'];
} else {
    $calmode = 0;
}

if (isset($_REQUEST['firstname'])) {
    $firstname = $_REQUEST['firstname'];
} else {
    $firstname = "";
}

if (isset($_REQUEST['lastname'])) {
    $lastname = $_REQUEST['lastname'];
} else {
    $lastname = "";
}

if (isset($_REQUEST['email'])) {
    $email = $_REQUEST['email'];
} else {
    $email = "";
}

if (isset($_REQUEST['departmenttext'])) {
    $departmenttext = $_REQUEST['departmenttext'];
} else {
    $departmenttext = "";
}

if (isset($_REQUEST['assistants'])) {
    $assistants = $_REQUEST['assistants'];
} else {
    $assistants = "";
}
// Declare PHP functions
require("equilibrium.php");

function display_duty_form($action, $duty, $errormsg, $params) {

    require_once("config.php");
    global $background_color;
    global $heading_color;
    global $display_client_contact;
    global $client_organization_label;

    // Only the assigned staff or administrators can edit this duty, unless it's not assigned
    if (($_SESSION['SESSION_ADMIN'] == "Y") || ($staff == $_SESSION['SESSION_USERID']) 
        || ($staff == 0)) {
        $edit_priv = "Y";
    } else {
        $edit_priv = "N";
    }
    
    // If parameters were passed, use those
    if ($params) {
        $title = $params['title'];
        $dtype = $params['dtype'];
        $description = $params['description'];
        $staff = $params['staff'];
        $client = $params['client'];
        $contact = $params['contact'];
        $enterdate = $params['enterdate'];
        $visibility = $params['visibility'];
        $status = $params['status'];
        $firstname = $params['firstname'];
        $lastname = $params['lastname'];
        $email = $params['email'];
        $departmenttext = $params['departmenttext'];
        $assistants = $params['assistants'];

        if ($enterdate == "0000-00-00") {
            $enterdate = "";
        }
    } else {
    
        // If adding, initialize variables
        if ($action == "add") {
            $title = "";
            $dtype = 0;
            $description = "";
            if ($_SESSION['SESSION_ADMIN'] == "Y") {
                if ($_SESSION['SESSION_STAFF'] == "Y") {
                    $staff = $_SESSION['SESSION_USERID'];
                } else {
                    $staff = 0;
                }
            } else {
                if ($_SESSION['SESSION_STAFF'] == "Y") {
                    $staff = $_SESSION['SESSION_USERID'];    
                } else {
                    $staff = 0;
                }
            }
            $client = 0;
            $contact = "";
            //$enterdate = date("F") . " " . date("j") . ", " . date("Y");
            $enterdate = date("m") . "/" . date("d") . "/" . date("Y");
            $status = "Active";
            $icon = 0;
        
        } else if ($action == "edit") {
        
            // For editing, retrieve existing fields from database
            $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
                or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
            mysql_select_db(DB_DATABASE);
            $get_fields = mysql_query("select d.title, t.duty_type_id, d.description, " .
                "u.user_id, c.client_id, d.contact, d.visibility, " .
                "d.date_entered, d.status, d.icon_id from duties as d " .
                "left join duty_types as t on d.duty_type_id = t.duty_type_id " .
                "left join users as u on d.staff_assigned = u.user_id " .
                "left join clients as c on d.client_id = c.client_id " .
                "where d.duty_id = \"$duty\" ");
            if ($row = mysql_fetch_array($get_fields)) {
                $title = $row['title'];
                $dtype = $row['duty_type_id'];
                $description = $row['description'];
                $staff = $row['user_id'];
                $client = $row['client_id'];
                $contact = $row['contact'];
                $enterdate = standard_date($row['date_entered']);
                $visibility = $row['visibility'];
                $status = $row['status'];
                $icon = $row['icon_id'];
            } else {
                printf("Error: unable to retrieve this duty from database.<br>\n");
            }
            mysql_free_result($get_fields);

            // Get list of assistants, if any
            $assistants = array();
            $get_assistants = mysql_query("select staff_id from assistants " .
                "where duty_id = \"$duty\" ");
            while ($row = mysql_fetch_array($get_assistants, MYSQL_ASSOC)) {
                array_push($assistants, $row['staff_id']);
            }
            mysql_free_result($get_assistants);
            mysql_close($conn);
        
        }

    }

    // If this is a private duty, make sure user has access
    if (($visibility == "Private") && ($_SESSION['SESSION_USERID'] != $staff)) {
        printf("<p>This is a private duty.  Only its owner has access to this page.</p>\n");
        printf("<p>Return to <a href='duties.php'>Duties page</a>.</p>\n");
        return;
    }
    
    // Add/Edit duty form
    printf("<form action='duties.php' method='post' name='duty'>\n");
    printf("<table cellpadding='10'><tr valign='top'><td width='50%%'>\n");
    //printf("<div id='project_left'>\n");
    
    printf("<table>\n");

    // Duty title
    printf("<tr><td>Title</td>\n");
    printf("<td><input type='text' name='title' style='{width: 25em}' value=\"$title\"></td></tr>\n");
    
    // Duty type
    printf("<tr><td>Type</td>\n");
    printf("<td><select name='dtype' id='dtype' size='1' onChange=\"document.getElementById('dtypedesc').firstChild.nodeValue = dtypedescs[document.getElementById('dtype').selectedIndex];\">\n");

    // Retrieve duty type names and descriptions from database
    $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
        or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
    mysql_select_db(DB_DATABASE);
    $get_types = mysql_query("select duty_type_id, name, description from duty_types " .
        "order by duty_type_id asc ");
    printf("<option value='0' selected>\n");
    $dutytypedesclist = array();
    $dutytypedesclist[0] = "Select a type for this duty.";
    $ndutytypes = 1;
    while ($row = mysql_fetch_array($get_types)) {
        if ($dtype == $row[0]) {
            printf("<option value='$row[0]' selected>$row[1]\n");            
        } else {
            printf("<option value='$row[0]'>$row[1]\n");            
        }
        $dutytypedesclist[$ndutytypes] = "$row[2]";
        $ndutytypes++;
    }
    mysql_free_result($get_types);
    mysql_close($conn);
    
    printf("</select></td></tr>\n");
    
    // Create JavaScript array of duty type descriptions
    printf("<script language='JavaScript'>\n");
    printf("var dtypedescs = new Array(%d);\n", $ndutytypes);
    for ($i = 0; $i < $ndutytypes; $i++) {
        printf("dtypedescs[$i] = '$dutytypedesclist[$i]';\n");
    }
    printf("</script>\n");
    if ($dtype == "") {
        $dtype = 0;
    }
    printf("<tr><td colspan='2'><div id='dtypedesc'>$dutytypedesclist[$dtype]</div></td></tr>\n");

    // Duty description
    printf("<tr><td colspan='2'>Description</td>\n");
    printf("<tr><td colspan='2'><textarea name='description' class='description' rows='6' cols='60'>" .
        "$description</textarea></td></tr>\n");
    
    printf("</table>\n");

    //printf("</div><div id='project_right'>\n");
    printf("</td><td width='50%%'>\n");
    
    printf("<table>\n");

    // Assigned staff member -- default is whoever's logged in
    printf("<tr><td align='right'>Assigned to: &nbsp; </td>");

    // Only administrators can assign duties to other people
    if ($_SESSION['SESSION_ADMIN'] == "Y") {
        printf("<td><select name='staff' size='1'>\n");
    
        $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
            or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
        mysql_select_db(DB_DATABASE);
        $get_staff = mysql_query("select user_id, first_name, last_name from users " .
            "where staff_flag = \"Y\" order by last_name ");
        if ($staff == 0) {
            printf("<option value='0' selected>\n");
        } else {
            printf("<option value='0'>\n");
        }
        $displayed_user = "";
        while ($row = mysql_fetch_array($get_staff)) {
            if ($staff == $row[0]) {
                printf("<option value='$row[0]' selected>$row[1] $row[2]\n");
                $displayed_user = "$row[1] $row[2]";
            } else {
                printf("<option value='$row[0]'>$row[1] $row[2]\n");
            }
            
        }
        mysql_free_result($get_staff);
        mysql_close($conn);
        printf("</select></td></tr>\n");
    
    } else {

        if ($staff == 0) {
            printf("<td><select name='staff' size='1'>\n");
            printf("<option value='0' selected>\n");
            printf("<option value='%d'>%s\n", $_SESSION['SESSION_USERID'], $_SESSION['SESSION_USER']);
            printf("</select></td></tr>\n");

        } else {
            printf("<td>%s\n", $_SESSION['SESSION_USER']);
            printf("<input type='hidden' name='staff' value='$staff'>");
            printf("</td></tr>\n");

        }
    }
    
    // Assisting staff
    printf("<tr><td align='right'>Assisting: &nbsp; </td>");

    // Only administrators can assign projects to other people
    printf("<td><select name='assistants[]' size='4' multiple>\n");

    $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
        or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
    mysql_select_db(DB_DATABASE);
    $get_staff = mysql_query("select user_id, first_name, last_name from users " .
        "where staff_flag = \"Y\" order by last_name ");
    if (isset($assistants)) {
        printf("<option value='0'>(None)\n");
    } else {
        printf("<option value='0' selected>(None)\n");
    }
    $selectedstaff = 0;
    while ($row = mysql_fetch_array($get_staff)) {
        if (isset($assistants)) {
            foreach ($assistants as $s) {
                if ($s == $row[0]) {
                    $selectedstaff = 1;
                    break;
                }
            }
        }
        if ($selectedstaff) {
            printf("<option value='$row[0]' selected>$row[1] $row[2]\n");
        } else {
            printf("<option value='$row[0]'>$row[1] $row[2]\n");
        }      
        $selectedstaff = 0;      
    }
    mysql_free_result($get_staff);
    mysql_close($conn);
    printf("</select></td></tr>\n");
    
    // Visibility
    printf("<tr><td align='right'>Visibility: &nbsp; </td>");
    printf("<td><select name='visibility' size='1'>\n");
    if ($visibility == 'Private') {
        printf("<option value='Public'>Public\n");
        printf("<option value='Private' selected>Private\n");
    } else {
        printf("<option value='Public' selected>Public\n");
        printf("<option value='Private'>Private\n");
    }
    
    // Duty status
    $statuslist = array("Active", "Inactive");
    printf("<tr><td align='right'>Status: &nbsp; </td>");
    printf("<td><select name='status' size='1'>\n");
    for ($i = 0; $i < count($statuslist); $i++) {
        if ($status == $statuslist[$i]) {
            printf("<option value='$statuslist[$i]' selected>$statuslist[$i]\n");
        } else {
            printf("<option value='$statuslist[$i]'>$statuslist[$i]\n");
        }
    }
    printf("</select></td></tr>\n");

    // Contact person
    if ($display_client_contact == "Y") {
        printf("<tr><td align='right'>Contact: &nbsp; </td>");
        printf("<td><input type='text' name='contact' size='20' value='$contact'></td></tr>\n");
    }

    // Existing client / New client selection
    printf("<tr><td colspan='2' align='center'><font id='exclabel' onclick='clientflag " .
        "= \"Existing Client\"; toggle_client_div(clientflag);' style='font-weight: bold'>");
    printf("Existing Client</font> / ");
    printf("<font id='newclabel' onclick='clientflag = \"New Client\"; toggle_client_div(clientflag);' style='font-weight: normal' >New Client</font></td></tr>\n");

    // Existing client form
    printf("<tr><td colspan='2'><div id='exc_div'>\n");
    printf("Client: &nbsp; <select name='client' size='1'>\n");
    printf("<option value='0' selected>\n");
    
    $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
        or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
    mysql_select_db(DB_DATABASE);

    // First list faculty members the logged-in user has worked for before
    $get_past_clients = mysql_query("select h.client_id, count(*) as countval, c.first_name, c.last_name " .
        "from client_history as h, clients as c where h.client_id = c.client_id " .
        "and h.staff_id = \"" . $_SESSION['SESSION_USERID'] . "\" group by h.client_id order by countval desc ");
    while ($row = mysql_fetch_array($get_past_clients)) {
        printf("<option value='$row[0]' style='background-color: %s;'>$row[2] $row[3]\n", $heading_color);
    }
    mysql_free_result($get_past_clients);
    printf("<option value='0'>-----------------------\n");

    // Now list all faculty members
    $get_clients = mysql_query("select client_id, first_name, last_name from clients " .
        "order by last_name, first_name ");
    while ($row = mysql_fetch_array($get_clients)) {
        if ($client == $row[0]) {
            printf("<option value='$row[0]' selected>$row[1] $row[2]\n");
        } else {
            printf("<option value='$row[0]'>$row[1] $row[2]\n");
        }
    }
    mysql_free_result($get_clients);
    mysql_close($conn);
    
    printf("</select><br>\n");

    printf("</div>\n");

    // New client form
    printf("<div id='newc_div' style='display:none'>\n");
    printf("<table>\n");
    printf("<tr><td>First Name: &nbsp; </td><td><input type='text' name='firstname' value='' size='20'></td></tr>\n");
    printf("<tr><td>Last Name: &nbsp; </td><td><input type='text' name='lastname' value='' size='20'></td></tr>\n");
    printf("<tr><td>Email: &nbsp; </td><td><input type='text' name='email' value='' size='20'></td></tr>\n");
    printf("<tr><td>$client_organization_label: &nbsp; </td><td>");

    // Department combo box
    printf("<input type='text' id='departmenttext' name='departmenttext' size='17' style='width: 160'>\n");
    printf("<input type='button' hidefocus='1' value='&#9660;' ");
    printf("style='height:23; width:22; font-family: helvetica;' ");
    printf("onclick=\"JavaScript:menuActivate('departmenttext', 'combodiv', 'combosel')\">\n");
    printf("<div id='combodiv' style='position:absolute; display:none; top:0px; ");
    printf("left:0px; z-index:10000' onmouseover=\"javascript:oOverMenu='combodiv';\" ");
    printf("onmouseout=\"javascript:oOverMenu=false;\">\n");
    printf("<select size='10' id='departmentsel' style='width: 160; border-style: none' ");
    printf("onclick=\"JavaScript:textSet('departmenttext',this.options[selectedIndex].text);\" ");
    printf("onkeypress=\"JavaScript:comboKey('departmenttext', this);\">\n");

    // List all departments
    $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
        or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
    mysql_select_db(DB_DATABASE);
    $get_depts = mysql_query("select department_id, name from departments " .
        "order by name asc ");
    while ($row = mysql_fetch_array($get_depts)) {
        printf("<option value='$row[0]'>$row[1]</option>\n");
    }
    mysql_free_result($get_depts);
    mysql_close($conn);
    printf("</select></div>\n");
    printf("</td></tr>\n");

    printf("</table>\n");
    printf("</div></td></tr>\n");
    
    // Only show date forms when editing projects
    if ($action == "edit") {

        // Date entered
        printf("<tr><td align='right'>Date entered: &nbsp; </td><td>\n");
        show_date_form('enterdate', $enterdate);
        printf("</td></tr>\n");
        
    }
    
    printf("</table>\n");

    // Print validation error message, if any
    if ($errormsg) {
        printf("$errormsg");
    }

    //printf("</div>\n");
    printf("</td></tr></table>\n");
    
    if ($action == "add") {
        printf("<input type='hidden' name='cmd' value='insert'>\n");
        printf("<input type='submit' value='Submit duty'>\n");
    } else if ($action == "edit") {
        printf("<input type='hidden' name='cmd' value='update'>\n");
        printf("<input type='hidden' name='duty' value='$duty'>\n");
        printf("<input type='submit' value='Update duty'>\n");
    }
    printf("</form>\n");

}

function display_duty_details($duty) {

    require_once("config.php");
    global $background_color;
    global $heading_color;

    // Initialize variables
    $title = "";
    $dtype = 0;
    $description = "";
    $staff = $_SESSION['SESSION_USERID'];
    $client = 0;
    $contact = "";
    $enterdate = "";
    $status = "";
    $visibility = "";
    $icon = 0;

    // Retrieve existing fields from database
    $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
        or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
    mysql_select_db(DB_DATABASE);
    $get_fields = mysql_query("select d.title, t.name, d.description, " .
        "u.first_name, u.last_name, c.first_name as client_first, " .
        "c.last_name as client_last, d.contact, d.visibility, " .
        "d.date_entered, d.status, d.icon_id from duties as d " .
        "left join duty_types as t on d.duty_type_id = t.duty_type_id " .
        "left join users as u on d.staff_assigned = u.user_id " .
        "left join clients as c on d.client_id = c.client_id " .
        "where d.duty_id = \"$duty\" ");
    if ($row = mysql_fetch_array($get_fields)) {
        $title = $row['title'];
        $dtype = $row['name'];
        $description = $row['description'];
        $displayed_user = $row['first_name'] . " " . $row['last_name'];
        $client = $row['client_first'] . " " . $row['client_last'];
        $contact = $row['contact'];
        $enterdate = pretty_date($row['date_entered']);
        $status = $row['status'];
        $visibility = $row['visibility'];
        $icon = $row['icon_id'];
    } else {
        printf("Error: unable to retrieve this duty from database.<br>\n");
    }
    mysql_free_result($get_fields);

    // Get list of assistants, if any
    $assistants = array();
    $get_assistants = mysql_query("select staff_id from assistants " .
        "where duty_id = \"$duty\" ");
    while ($row = mysql_fetch_array($get_assistants, MYSQL_ASSOC)) {
        array_push($assistants, $row['staff_id']);
    }
    mysql_free_result($get_assistants);
    mysql_close($conn);

    // Only the assigned staff or administrators can edit this project, unless it's not assigned
    if (($_SESSION['SESSION_ADMIN'] == "Y") || ($displayed_user == $_SESSION['SESSION_USER']) 
        || (trim($displayed_user) == "")) {
        $edit_priv = "Y";
    } else {
        $edit_priv = "N";
    }

    // If this is a private duty, make sure user has access
    if (($visibility == "Private") && ($_SESSION['SESSION_USERID'] != $staff)) {
        printf("<p>This is a private duty.  Only its owner has access to this page.</p>\n");
        printf("<p>Return to <a href='duties.php'>Duties page</a>.</p>\n");
        return;
    }
    
    // Page heading
    printf("<h2>Duty Details: $title</h2>\n");
        
    // Button: Add New Duty
    printf("<table><tr>\n");
    if (($_SESSION['SESSION_ADMIN'] == "Y") || ($_SESSION['SESSION_STAFF'] == "Y")) {
        printf("<td><form action='duties.php' method='post'>\n");
        printf("<input type='hidden' name='action' value='add'><input type='submit' value='Add New Duty'></form></td>\n");
    }
    // Button: Edit This Duty
    if ($edit_priv == "Y") {
        printf("<td><form action='duties.php' method='post'>\n");
        printf("<input type='hidden' name='action' value='edit'>\n");
        printf("<input type='hidden' name='duty' value='$duty'>\n");
        printf("<input type='submit' value='Edit This Duty'></form></td>\n");
    }
    printf("</tr></table>\n");
        
    // Duty description
    $description = ereg_replace("%", "%%", $description);
    printf("<p>$description</p>\n");
    
    printf("<table cellpadding='10'><tr valign='top'><td width='50%%'>\n");
    //printf("<table cellpadding='10'><tr valign='top'><td>\n");
    
    printf("<table>\n");

    // Duty type
    printf("<tr><td>Type: &nbsp; </td>\n");
    printf("<td class='values' style='border: 1px solid $heading_color;'>$dtype<br></td></tr>\n");

    // Assigned staff member
    printf("<tr><td>Assigned to: &nbsp; </td>");
    printf("<td class='values' style='border: 1px solid $heading_color;'>$displayed_user<br></td></tr>\n");
    
    // Assisting staff
    if (isset($assistants)) {

        // Get staff list
        $stafflist = array();
        $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
            or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
        mysql_select_db(DB_DATABASE);
        $get_staff = mysql_query("select user_id, first_name, last_name from users " .
            "order by last_name asc, first_name asc ");
        while ($row = mysql_fetch_array($get_staff, MYSQL_ASSOC)) {
            $stafflist[$row['user_id']] = $row['first_name'] . " " . $row['last_name'];
        }
        mysql_free_result($get_staff);
        mysql_close($conn);

        // Display assistants
        $firstassistant = 1;
        foreach ($assistants as $s) {
            if ($firstassistant) {
                printf("<tr><td>Assisting: &nbsp; </td>");
                printf("<td class='values' style='border: 1px solid " .
                    "$heading_color;'>$stafflist[$s]<br></td></tr>\n");
                $firstassistant = 0;
            } else {
                printf("<tr><td><br></td>");
                printf("<td class='values' style='border: 1px solid " .
                    "$heading_color;'>$stafflist[$s]<br></td></tr>\n");
            }
        }
    }

    // Client
    printf("<tr><td>Client PI: &nbsp; </td>");
    printf("<td class='values' style='border: 1px solid $heading_color;'>$client<br></td></tr>\n");
    
    // Contact person
    printf("<tr><td>Contact: &nbsp; </td>");
    printf("<td class='values' style='border: 1px solid $heading_color;'>$contact<br></td></tr>\n");

    // Visibility
    printf("<tr><td>Visibility: &nbsp; </td>");
    if ($visibility == "Private") {
        printf("<td class='values' style='border: 1px solid $heading_color; background-color: $heading_color'>$visibility<br></td></tr>\n");
    } else {
        printf("<td class='values' style='border: 1px solid $heading_color;'>$visibility<br></td></tr>\n");
    }

    printf("</table>\n");

    //printf("</div><div id='project_right'>\n");
    printf("</td><td width='50%%' valign='top'>\n");
    //printf("</td><td valign='bottom'>\n");
    
    printf("<table>\n");

    // Date entered
    printf("<tr><td align='right'>Date entered: &nbsp; </td>");
    printf("<td class='values' style='border: 1px solid $heading_color;'>$enterdate<br></td></tr>\n");

    // Duty status
    printf("<tr><td align='right'>Status: &nbsp; </td>");
    printf("<td class='values' style='border: 1px solid $heading_color;'>$status<br></td></tr>\n");
    
    // Duty icon
    printf("<tr><td align='right'>Icon: &nbsp; </td>");
    if ($icon == 0) {
        printf("<td class='values' style='border: 1px solid $heading_color;'>None<br></td></tr>\n");
    } else {
        printf("<td class='values' style='border: 1px solid $heading_color;'><img src='icons18/icon_%d.png'><br></td></tr>\n", $icon);
    }

    printf("</table>\n");

    printf("</td></tr></table>\n");

    return;
}

function show_duty_files($duty) {

    global $heading_color;
    
    $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
        or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
    mysql_select_db(DB_DATABASE);
    $get_files = mysql_query("select file_id, file_type, file_name, description, " .
        "upload_date, upload_time, file_path from files where duty_id = \"$duty\" " .
        "order by upload_time ");
    if (mysql_num_rows($get_files)) {
        while ($row = mysql_fetch_array($get_files, MYSQL_ASSOC)) {
            printf("<a href=\"%s/%s\">%s</a>, %s \n", $row['file_path'], 
                $row['file_name'], $row['file_name'], $row['description']);
            if ($row['file_type']) {
                printf("(%s, %s) \n", $row['file_type'], 
                    short_date($row['upload_date']));
            } else {
                printf("(%s) &nbsp; \n", short_date($row['upload_date']));
            }
            printf("<img height='16' src='images/delete.png' title='Delete' " .
                "onclick='show_item(\"confirm_" . $row['file_id'] . "\");'><br>\n");

            // Div to confirm deletion
            printf("<div class='confirm' id='confirm_" . $row['file_id'] . 
                "' ><font color='red'>" .
                "<center>Are you sure you want to delete this file?</font><br>");
            printf("<form action='duties.php#file_input' method='post'>\n");
            printf("<input type='hidden' name='file_id' value='%d'>\n", 
                $row['file_id']);
            printf("<input type='hidden' name='dirtree' value='%s'>\n", 
                $row['file_path']);
            printf("<input type='hidden' name='existingfile' value='%s'>\n", 
                $row['file_name']);
            printf("<input type='hidden' name='cmd' value='deletefile'>\n");
            printf("<input type='hidden' name='duty' value='$duty'>\n");
            printf("<input type='submit' value='Confirm Deletion'>  &nbsp; &nbsp; ");
            printf("<input type='button' value='Cancel' onclick='hide_item(\"confirm_" . 
                $row['file_id'] . "\");'></center><br>");
            printf("</form>\n</div>\n");

        }

    } else {
        printf("<p>No files uploaded for this duty.</p>\n");
    }

    mysql_free_result($get_files);
    mysql_close($conn);
    
    return;
}

// Commands that don't generate HTML output
switch($cmd) {
    case "insert":

        $enterdate = ugly_date($enterdate);

        // Validate submitted data
        if ((!trim($title)) || (!trim($dtype)) || (!trim($description))) {
        //if ((!trim($title)) || (!trim($description))) {

            // Missing fields; return to form
            $errormsg = "<p><font color='red'>* A title, type, and description are required for each duty.</font></p>\n";
            $activepage = "Duties";
            require("header.php");
            printf("<h2>Add New Duty</h2>\n");
    
            if (($_SESSION['SESSION_ADMIN'] == "Y") || ($_SESSION['SESSION_STAFF'] == "Y")) {
                $enterdate = standard_date($enterdate);
                $params['title'] = $title;
                $params['dtype'] = $dtype;
                $params['description'] = $description;
                $params['staff'] = $staff;
                $params['client'] = $client;
                $params['contact'] = $contact;
                $params['enterdate'] = $enterdate;
                $params['visibility'] = $visibility;
                $params['status'] = $status;
                $params['firstname'] = $firstname;
                $params['lastname'] = $lastname;
                $params['email'] = $email;
                $params['departmenttext'] = $departmenttext;
                $params['assistants'] = $assistants;
                display_duty_form("add", 0, "$errormsg", $params);
            } else {
                printf("<h3>Add New Duty -- Not Authorized</h3>");
                printf("<p>Only staff members and administrators can add new duties.</p>\n");
                printf("<p>Contact $admin_name (<a href='mailto:$admin_email'>" .
                    "$admin_email)</a> to enable your user account to add duties.</p>\n");
                require("footer.php");
            }

            exit;

        } else {

            // Data passes inspection; pick an icon for this duty
            $icons = array();
            for ($i = 0; $i < $number_icons; $i++) {
                $icons[$i] = 0;
            }
            $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)
                or die ("Cannot connect to database. " . mysql_error() . 
                "\n<br>");
            mysql_select_db (DB_DATABASE);
            $get_used_icons = mysql_query("select icon_id, count(*) as countval from icon_usage " .
                //"group by icon_id order by icon_id asc, countval asc ");
                "group by icon_id order by countval asc ");
            $defaulticon = 0;
            if (mysql_num_rows($get_used_icons) == 0) {
                $icon = 1;
            } else {
                while ($row = mysql_fetch_array($get_used_icons)) {
                    if (!$defaulticon) {
                        $defaulticon = $row[0]; // default icon is least used one
                    }
                    $icons[$row[0]] = $row[1];
                }
            }
            mysql_free_result($get_used_icons);
            mysql_close($conn);
            $foundzero = 0;
            $iconstart = mt_rand(1, $number_icons);
            if ($iconstart < ($number_icons / 2)) {

                // If randomly chosen start position is closer to the
                // beginning of the icon list, go toward the end to
                // look for zeroes
                for ($i = $iconstart; $i <= $number_icons; $i++) {
                    if ($icons[$i] == 0) {
                        // Find first zero, and use that icon
                        $icon = $i;
                        $foundzero = 1;
                        break;
                    }
                }
            } else {

                // If randomly chosen start position is closer to the
                // end of the icon list, go toward the beginning to
                // look for zeroes
                for ($i = $iconstart; $i >= 1; $i--) {
                    if ($icons[$i] == 0) {
                        // Find first zero, and use that icon
                        $icon = $i;
                        $foundzero = 1;
                        break;
                    }
                }
            }
            if (!$foundzero) {
                $icon = $defaulticon;  // If no zero-used icons found, pick least-used one
            }

            // Was a new client entered?
            if (($firstname) || ($lastname)) {
                $new_client_flag = 1;
                $dept_id = 0;
                $client = 0;

                // Check if a new client department was specified
                $departmenttext = trim($departmenttext);
                //printf("departmenttext = $departmenttext<br>\n");
                if ($departmenttext) {
    
                    // Get list of departments
                    $department_ids = array();
                    $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
                        or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
                    mysql_select_db (DB_DATABASE);
                    $get_depts = mysql_query("select department_id, name from departments order by name asc ");
                    while ($row = mysql_fetch_array($get_depts, MYSQL_ASSOC)) {
                        $department_ids[strtoupper($row['name'])] = $row['department_id'];
                    }
                    mysql_close($conn);
        
                    // Is this department already in the database?
                    if ($department_ids[strtoupper($departmenttext)]) {
                        // Yes, it is
                        $dept_id = $department_ids[strtoupper($departmenttext)];
                        //printf("Known: dept_id = $dept_id<br>\n");
                    } else {
                        // No; add it
                        $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
                            or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
                        mysql_select_db (DB_DATABASE);
                        $get_depts = mysql_query("insert into departments (name) values (\"$departmenttext\" ) ");
                        $dept_id = mysql_insert_id($conn);
                        //printf("New: dept_id = $dept_id<br>\n");
                        mysql_close($conn);
                    }
        
                }

                // Add client to database
                $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
                    or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
                mysql_select_db (DB_DATABASE);
                if ($dept_id) {
                    $get_depts = mysql_query("insert into clients (first_name, last_name, email, department_id) values (\"$firstname\", \"$lastname\", \"$email\", \"$dept_id\")  ");
                } else {
                    $get_depts = mysql_query("insert into clients (first_name, last_name, email) values (\"$firstname\", \"$lastname\", \"$email\" ) ");
                }
                $client = mysql_insert_id($conn);

            }

            // Add new duty to database
            $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
                or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
            mysql_select_db (DB_DATABASE);
            $title = mysql_real_escape_string($title);
            $description = mysql_real_escape_string($description);
            $start_trans = mysql_query("start transaction ");
            $add_duty = mysql_query("insert into duties " .
                "(title, duty_type_id, description, staff_assigned, client_id, " .
                "contact, date_entered, status, icon_id) " .
                "values (\"$title\", \"$dtype\", \"$description\", \"$staff\", " .
                "\"$client\", \"$contact\", curdate(), \"$status\", \"$icon\") ");
            $duty = mysql_insert_id($conn);

            // If assistants were specified, add them to assistants table
            if (isset($assistants)) {
                foreach ($assistants as $s) {
                    $add_assistant = mysql_query("insert into assistants " .
                        "(project_id, duty_id, staff_id) values " .
                        "(\"0\", \"$duty\", \"$s\") ");
                }
            }

            // Add current values to duty history
            $add_history = mysql_query("insert into duty_history " .
                "(duty_id, status, " .
                "modification_date, modification_time) " .
                "values (\"$duty\", \"$status\", " .
                "curdate(), now()) ");

            // Insert this duty in client history
            $add_client = mysql_query("insert into client_history " .
                "(staff_id, client_id, duty_id, client_entered_date, client_entered_time) " .
                "values (\"$staff\", \"$client\", \"$duty\", curdate(), now()) ");

            // Insert the selected icon into the icon usage table
            $add_icon = mysql_query("insert into icon_usage " .
                "(icon_id, duty_id) " .
                "values (\"$icon\", \"$duty\") ");

            // Commit transaction
            $stop_trans = mysql_query("commit ");
            if (!$stop_trans) {
                require("header.php");
                printf("<p>Error adding duty \"$title\": %s</p>\n", mysql_error());
                require("footer.php");
                mysql_close($conn);
                exit;
            }
            mysql_close($conn);

            // Send user to duty detail page
            header("Location: duties.php?action=view&duty=$duty");
            exit();

        }

        break;

    case "update":

        // Validate submitted data
        if ((!trim($title)) || (!trim($dtype)) || (!trim($description))) {

            // Missing fields; return to form
            $errormsg = "<p><font color='red'>* A title, type, and description are required for each duty.</font></p>\n";
            $activepage = "Duties";
            require("header.php");
            printf("<h2>Edit Duty</h2>\n");
    
            if (($_SESSION['SESSION_ADMIN'] == "Y") || ($_SESSION['SESSION_STAFF'] == "Y")) {
                $params['title'] = $title;
                $params['dtype'] = $dtype;
                $params['description'] = $description;
                $params['staff'] = $staff;
                $params['client'] = $client;
                $params['contact'] = $contact;
                $params['enterdate'] = $enterdate;
                $params['visibility'] = $visibility;
                $params['status'] = $status;
                $params['firstname'] = $firstname;
                $params['lastname'] = $lastname;
                $params['email'] = $email;
                $params['departmenttext'] = $departmenttext;
                $params['assistants'] = $assistants;
                display_duty_form("edit", $duty, "$errormsg", $params);
            } else {
                printf("<h3>Edit Duty -- Not Authorized</h3>");
                printf("<p>Only staff members and administrators can edit duties.</p>\n");
                printf("<p>Contact $admin_name (<a href='mailto:$admin_email'>" .
                    "$admin_email)</a> to enable your user account to edit duties.</p>\n");
                require("footer.php");
            }

            exit;

        } else {

            // Data passes inspection; update duty in database
            $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
                or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
            mysql_select_db (DB_DATABASE);
            $title = mysql_real_escape_string($title);
            $description = mysql_real_escape_string($description);
            $start_trans = mysql_query("start transaction ");

            // Was a new client entered?
            if (($firstname) || ($lastname)) {
                $new_client_flag = 1;
                $dept_id = 0;
                $client = 0;

                // Check if a new client department was specified
                $departmenttext = trim($departmenttext);
                //printf("departmenttext = $departmenttext<br>\n");
                if ($departmenttext) {
    
                    // Get list of departments
                    $department_ids = array();
                    $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
                        or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
                    mysql_select_db (DB_DATABASE);
                    $get_depts = mysql_query("select department_id, name from departments order by name asc ");
                    while ($row = mysql_fetch_array($get_depts, MYSQL_ASSOC)) {
                        $department_ids[strtoupper($row['name'])] = $row['department_id'];
                    }
                    mysql_close($conn);
        
                    // Is this department already in the database?
                    if ($department_ids[strtoupper($departmenttext)]) {
                        // Yes, it is
                        $dept_id = $department_ids[strtoupper($departmenttext)];
                        //printf("Known: dept_id = $dept_id<br>\n");
                    } else {
                        // No; add it
                        $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
                            or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
                        mysql_select_db (DB_DATABASE);
                        $get_depts = mysql_query("insert into departments (name) values (\"$departmenttext\" ) ");
                        $dept_id = mysql_insert_id($conn);
                        //printf("New: dept_id = $dept_id<br>\n");
                        mysql_close($conn);
                    }
        
                }

                // Add client to database
                $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
                    or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
                mysql_select_db (DB_DATABASE);
                if ($dept_id) {
                    $get_depts = mysql_query("insert into clients (first_name, last_name, email, department_id) values (\"$firstname\", \"$lastname\", \"$email\", \"$dept_id\")  ");
                } else {
                    $get_depts = mysql_query("insert into clients (first_name, last_name, email) values (\"$firstname\", \"$lastname\", \"$email\" ) ");
                }
                $client = mysql_insert_id($conn);

            }

            // Convert date formats to MySQL
            $enterdate = mysql_date($enterdate);

            // Check what the existing duty status is
            $check_status = mysql_query("select status from duties " .
                "where duty_id = \"$duty\" ");
            if ($row = mysql_fetch_array($check_status)) {
                $starting_status = $row[0];
            } else {
                $starting_status = "";
            }
            mysql_free_result($check_status);
            
            // Update duty fields
            $edit_duty = mysql_query("update duties " .
                "set title = \"$title\", duty_type_id = \"$dtype\", " .
                "description = \"$description\", staff_assigned = \"$staff\", client_id = \"$client\", " .
                "contact = \"$contact\", date_entered = \"$enterdate\", " .
                "status = \"$status\", visibility = \"$visibility\" " .
                "where duty_id = \"$duty\" ");
                
            // If assistants were specified, add them to assistants table
            if (isset($assistants)) {
                // Delete previous assistants for this project to avoid duplication
                $delete_assistant = mysql_query("delete from assistants " .
                    "where duty_id = \"$duty\" ");
                // Add new assistants
                foreach ($assistants as $s) {
                    $add_assistant = mysql_query("insert into assistants " .
                        "(project_id, duty_id, staff_id) values " .
                        "(\"0\", \"$duty\", \"$s\") ");
                }
            }

            // Update duty history if status changed
            if ($starting_status != $status) {
                $edit_history = mysql_query("insert into duty_history " .
                    "(duty_id, status, modification_date, modification_time) " .
                    "values (\"$duty\", \"$status\", curdate(), now()) ");
            }

            // Commit transaction
            $stop_trans = mysql_query("commit ");
            if (!$stop_trans) {
                require("header.php");
                printf("<p>Error updating duty: %s</p>\n", mysql_error());
                require("footer.php");
                mysql_close($conn);
                exit;
            }
            mysql_close($conn);

            // Send user to duty detail page
            header("Location: duties.php?action=view&duty=$duty");
            exit();

        }

        break;

    case "updatecommentlist":
        // create TasksList object
        //$myTasksList = new TasksList();
        // read parameters
        $action = $_GET['action'];
        $content = $_GET['content'];
        $project = $_GET['project'];
        // clear the output
        //if(ob_get_length()) ob_clean();
        // headers are sent to prevent browsers from caching
        
        //header('Expires: Fri, 25 Dec 1980 00:00:00 GMT'); // time in the past
        //header('Last-Modified: ' . gmdate( 'D, d M Y H:i:s') . 'GMT');
        //header('Cache-Control: no-cache, must-revalidate');
        //header('Pragma: no-cache');
        //header('Content-Type: text/html');
        // execute the client request and return the updated tasks list
        //echo $myTasksList->Process($content, $action, $project);
        echo process_comment_changes($content, $action, $project);

        break;

    case "addcomment":

        // Add comment to comments table
        $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
            or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
        mysql_select_db (DB_DATABASE);
        $comment = mysql_real_escape_string($comment);
        $add_comment = mysql_query("insert into comments " .
            "(duty_id, comment_text, submitter_id, submit_date, submit_time) " .
            "values (\"$duty\", \"$comment\", \"$submitter\", curdate(), now()) ");

        // Print error message if there's a problem
        if (!$add_comment) {
            $activepage = "Projects";
            require("header.php");
            printf("<p>Error adding comment: %s</p>\n", mysql_error());
            require("footer.php");
            mysql_close($conn);
            exit;
        }
        mysql_close($conn);

        // Return user to duty details page
        header("Location: duties.php?action=view&duty=$duty");
        break;

    case "uploadfile":

        if ($filename) {

            $dirtree = "$upload_dir/D" . $duty;
            if (!file_exists($dirtree)) {
                mkdir($dirtree);
                chmod($dirtree, 0775);
            }

            // Save uploaded file to file path
            if (!file_exists("$dirtree/$filename")) {
                $try_upload = move_uploaded_file($_FILES['filename']['tmp_name'], 
                    "$dirtree/$filename");
                if (!$try_upload) {
                    $activepage = "Duties";
                    require("header.php");
                    printf("<p>The file upload failed.</p>\n");
                    require("footer.php");
                }
                chmod("$dirtree/$filename", 0775);
            } else {
                $activepage = "Duties";
                require("header.php");
                printf("<p>File upload aborted: A file with this name ($dirtree/$filename) already exists.</p>\n");
                require("footer.php");
                exit;
            }

            if ((!$filecat) || ($filecat == "Null") || ($filecat == NULL)) {
    
                // Insert file into files table
                $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
                    or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
                mysql_select_db (DB_DATABASE);
                $add_file = mysql_query("insert into files " .
                    "(duty_id, file_name, file_path, description, uploaded_by, upload_date, upload_time) " .
                    "values (\"$duty\", \"$filename\", \"$dirtree\", \"$filedesc\", \"$submitter\", " .
                    "curdate(), now()) ");
        
                // Print error message if there's a problem
                if (!$add_file) {
                    $activepage = "Duties";
                    require("header.php");
                    printf("<p>Error uploading file: %s</p>\n", mysql_error());
                    require("footer.php");
                    mysql_close($conn);
                    exit;
                }
                mysql_close($conn);
    
            } else {
    
                // Insert file into files table
                $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
                    or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
                mysql_select_db (DB_DATABASE);
                $add_file = mysql_query("insert into files " .
                    "(duty_id, file_name, file_path, file_type, description, uploaded_by, " .
                    "upload_date, upload_time) values (\"$duty\", \"$filename\", \"$dirtree\", " .
                    "\"$filecat\", \"$filedesc\", \"$submitter\", curdate(), now()) ");
        
                // Print error message if there's a problem
                if (!$add_file) {
                    $activepage = "Duties";
                    require("header.php");
                    printf("<p>Error uploading file: %s</p>\n", mysql_error());
                    require("footer.php");
                    mysql_close($conn);
                    exit;
                }
                mysql_close($conn);
    
            }

        } else {
            
            // No filename specified; show error
            $activepage = "Duties";
            require("header.php");
            printf("<p>Error: No filename specified for upload.</p>\n");
            printf("<p>Back to <a href='duties.php?action=view&duty=$duty'>duty page</a>.</p>");
            require("footer.php");
            exit;

        }

        // Return user to duty details page
        header("Location: duties.php?action=view&duty=$duty");

        break;

    case "deletefile":

        // Check if file exists
        if (file_exists("$dirtree/$existingfile")) {

            // Delete file from filesystem
            $err = unlink("$dirtree/$existingfile");
            if (!$err) {
                $activepage = "Duties";
                require("header.php");
                printf("<p>Error deleting file: Could not be removed from filesystem.</p>\n");
                require("footer.php");
                exit;

            }
        }

        // Delete file from files table
        $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
            or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
        mysql_select_db (DB_DATABASE);
        $delete_file = mysql_query("delete from files " .
            "where file_id = \"$file_id\"; ");

        // Print error message if there's a problem
        if (!$delete_file) {
            $activepage = "Duties";
            require("header.php");
            printf("<p>Error deleting file: %s</p>\n", mysql_error());
            require("footer.php");
            mysql_close($conn);
            exit;
        }
        mysql_close($conn);

        // Return user to project details page
        header("Location: duties.php?action=view&duty=$duty");

        break;

}

switch($action) {

    case "add":

        // Start HTML and declare Javascript functions
        $activepage = "Duties";
        require("header.php");

        // Page heading
        printf("<h2>Add New Duty</h2>\n");

        if (($_SESSION['SESSION_ADMIN'] == "Y") || ($_SESSION['SESSION_STAFF'] == "Y")) {
        
            display_duty_form($action, 0, "", "");

        } else {
            
            printf("<h3>Add New Duty -- Not Authorized</h3>");
            printf("<p>Only staff members and administrators can add new duties.</p>\n");
            printf("<p>Contact $admin_name (<a href='mailto:$admin_email'>" .
                "$admin_email)</a> to enable your user account to add duties.</p>\n");
        }

        // End page
        require("footer.php");
        break;

    case "edit":

        // Start HTML and declare Javascript functions
        $activepage = "Duties";
        require("header.php");

        // Page heading
        printf("<h2>Edit Duty</h2>\n");

        if (($_SESSION['SESSION_ADMIN'] == "Y") || ($_SESSION['SESSION_STAFF'] == "Y")) {
        
            display_duty_form($action, $duty, "", "");

        } else {
            
            printf("<h3>Edit Duty -- Not Authorized</h3>");
            printf("<p>Only staff members and administrators can edit duties.</p>\n");
            printf("<p>Contact $admin_name (<a href='mailto:$admin_email'>" .
                "$admin_email)</a> to enable your user account to edit duties.</p>\n");
        }

        // End page
        require("footer.php");
        break;

    case "view":

        // Start HTML and declare Javascript functions
        $activepage = "Duties";
        require("header.php");

        // DEBUG
        //printf("<p>cmd = $cmd, action = $action</p>\n");

        display_duty_details($duty);

        // Only the assigned staff or administrators can edit this duty, unless it's not assigned
        $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
            or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
        mysql_select_db(DB_DATABASE);
        $get_user = mysql_query("select u.first_name, u.last_name from duties as d " .
            "left join users as u on d.staff_assigned = u.user_id " .
            "where d.duty_id = \"$duty\" ");
        if ($row = mysql_fetch_array($get_user)) {
            $displayed_user = "$row[0] $row[1]";
        } else {
            printf("Error: unable to retrieve user for this duty from database.<br>\n");
        }
        mysql_free_result($get_user);
        mysql_close($conn);
        if (($_SESSION['SESSION_ADMIN'] == "Y") || ($displayed_user == $_SESSION['SESSION_USER']) 
            || (trim($displayed_user) == "")) {
            $edit_priv = "Y";
        } else {
            $edit_priv = "N";
        }

        // Fill Javascript arrays with open projects and active duties
        fill_pdlist_arrays($staff, $projects, $project_ids, $duties, $duty_ids);
        
        // To-do items
        printf("<h2>To Do Items</h2>\n");
        if ($edit_priv == "Y") {
            printf("<div>\n<input type='text' id='txtNewItem' name='txtNewItem' " .
                "size='80%%' maxlength='255' onkeydown='handleItemKey(event, " .
                "\"$staff\", \"$status\", \"$todostatus\", \"$priority\", " .
                "\"$calmode\", \"0\", \"$duty\", \"0\", \"0\", \"$page\", " .
                "\"$maxresults\");'>\n");
            printf("<input type='button' name='submit' value='Add item' " .
                "onclick='modify_todo(\"txtNewItem\", \"additem\", \"$staff\", " .
                "\"$status\", \"$todostatus\", \"0\", \"$duty\", \"0\", \"0\", " .
                "\"$page\", \"$maxresults\");'>\n</div><br>\n");
        }
        printf("<div id='todo_section'>\n");
        printf(build_two_lists($staff, $status, "All", $calmode, '0', $duty,
            '0', '0', $page, $maxresults));
        printf("</div>\n");
        
        // Comments
        printf("<h2>Comments</h2>\n");
        if ($edit_priv == "Y") {
            
            printf("<textarea name='txtNewEntry' id='txtNewEntry' rows='3' cols='100' class='description'></textarea><br>\n");
            printf("<input type='button' name='submit' value='Submit comment' " .
                "onclick='modify_comment(\"txtNewEntry\", \"addcomment\", \"$staff\", " .
                "\"0\", \"$duty\", \"$fromdate\", \"$todate\", \"1\", \"$page\", " .
                "\"$maxresults\");'>\n<br>\n");
                
        }
    
        // Show existing comments
        $commentlist = build_commentlist($staff, $project, $duty, 
            $fromdate, $todate, 0, $page, $maxresults);
        printf($commentlist);
        //printf("%s", show_project_comments($project, $edit_priv));

        // Files
        printf("<a name='file_input'><h2>Files</h2></a>\n");
        if ($edit_priv == "Y") {
            printf("<form action='duties.php#file_input' method='post' enctype='multipart/form-data'>\n");
            printf("<table><tr>");
            printf("<td><label>Upload file: </label></td>\n");
            printf("<td><input type='file' name='filename' value='' size='50'></td></tr>\n");
            printf("<td><label>Category: </label></td>\n");
            printf("<td><select name='filecat'>\n");
            printf("<option value='Null' selected>\n");
            printf("<option value='Report'>Report\n");
            printf("<option value='Program'>Program\n");
            printf("<option value='Protocol'>Protocol\n");
            printf("</select></td></tr>\n");
            printf("<td colspan='2'><label>File description (optional): </label><br>\n");
            printf("<input type='text' name='filedesc' value='' size='60'>\n");
            printf("<input type='hidden' name='duty' value='$duty'></td></tr>\n");
            printf("<input type='hidden' name='submitter' value='%d'>\n", $_SESSION['SESSION_USERID']);
            printf("<input type='hidden' name='cmd' value='uploadfile'></td></tr>\n");
            printf("<tr><td colspan='2'><input type='submit' name='submit' value='Upload file'></td></tr>\n");
            printf("</table></form>\n");
        }

        // Show uploaded files
        show_duty_files($duty);

        printf("<br><br>\n");

        // Make to-do list sortable
        if ($edit_priv == "Y") {
            printf("<script type='text/javascript'>\n");
            //printf("Sortable.create('pendingTasksList', {tag:'div',handle:'draghandle'});\n");
            printf("Sortable.create('Pending_todolist', {tag:'div',handle:'draghandle'});\n");
        
            // Put focus on to-do box
            printf("document.getElementById('txtNewItem').value = '';\n");
            printf("document.getElementById('txtNewItem').focus();\n");
            printf("</script>\n");
        }

        // End page
        require("footer.php");
        break;

    default: // Default action: list projects

        // Start HTML and declare Javascript functions
        $activepage = "Duties";
        require("header.php");

        // Page heading
        printf("<h2>Duty List</h2>\n");

        // Button: Add New Project
        if (($_SESSION['SESSION_ADMIN'] == "Y") || ($_SESSION['SESSION_STAFF'] == "Y")) {
            printf("<form action='duties.php' method='post'>\n");
            printf("<input type='hidden' name='action' value='add'><input type='submit' value='Add New Duty'></form>\n");
        }
        
        // Show main controls
        $fields = array('Staff', 'Dstatus', 'Results');
        $values = array($staff, $status, $maxresults);
        printf("<form action='duties.php' method='get' name='viewform'>\n");
        $displayed_user = display_controls($fields, $values);
        printf("</form>\n");

        // Only the assigned staff or administrators can edit this duty, unless it's not assigned
        if (($_SESSION['SESSION_ADMIN'] == "Y") || ($displayed_user == $_SESSION['SESSION_USER'])) {
//            || (trim($displayed_user) == "")) {
            $edit_priv = "Y";
        } else {
            $edit_priv = "N";
        }

        if ($staff == 0) {
        
            if ($status == "All") {
                
                $query = "select d.duty_id, d.title, d.description, " .
                    "c.last_name as clientname, u.first_name, u.last_name, d.date_entered, d.status, " .
                    "d.icon_id from duties as d " .
                    "left join clients as c on d.client_id = c.client_id " .
                    "left join users as u on d.staff_assigned = u.user_id " .
                    "order by d.date_entered desc ";

            } else if ($status == "Open") {

                $query = "select d.duty_id, d.title, d.description, " .
                    "c.last_name as clientname, u.first_name, u.last_name, d.date_entered, d.status, " .
                    "d.icon_id from duties as d " .
                    "left join clients as c on d.client_id = c.client_id " .
                    "left join users as u on d.staff_assigned = u.user_id " .
                    "where d.status in (\"Pending\", \"Active\", \"Suspended\") " . 
                    "order by d.date_entered desc ";

            } else {

                $query = "select d.duty_id, d.title, d.description, " .
                    "c.last_name as clientname, u.first_name, u.last_name, d.date_entered, d.status, " .
                    "d.icon_id from duties as d " .
                    "left join clients as c on d.client_id = c.client_id " .
                    "left join users as u on d.staff_assigned = u.user_id " .
                    "where d.status = \"$status\" " . 
                    "order by d.date_entered desc ";
            }
        
        } else {
        
            if ($status == "All") {
            
                $query = "select distinct d.duty_id, d.title, d.description, " .
                    "c.last_name as clientname, u.first_name, u.last_name, d.date_entered, d.status, " .
                    "d.icon_id from duties as d " .
                    "left join clients as c on d.client_id = c.client_id " .
                    "left join users as u on d.staff_assigned = u.user_id " .
                    "left join assistants as s on d.duty_id = s.duty_id " .
                    "where (d.staff_assigned = \"$staff\" or s.staff_id = \"$staff\" ) " . 
                    "order by d.date_entered desc ";

            } else if ($status == "Open") {

                $query = "select distinct d.duty_id, d.title, d.description, " .
                    "c.last_name as clientname, u.first_name, u.last_name, d.date_entered, d.status, " .
                    "d.icon_id from duties as d " .
                    "left join clients as c on d.client_id = c.client_id " .
                    "left join users as u on d.staff_assigned = u.user_id " .
                    "left join assistants as s on d.duty_id = s.duty_id " .
                    "where d.status in (\"Pending\", \"Active\", \"Suspended\") " . 
                    "and (d.staff_assigned = \"$staff\" or s.staff_id = \"$staff\" ) " .
                    "order by d.date_entered desc ";

            } else {
            
                $query = "select distinct d.duty_id, d.title, d.description, " .
                    "c.last_name as clientname, u.first_name, u.last_name, d.date_entered, d.status, " .
                    "d.icon_id from duties as d " .
                    "left join clients as c on d.client_id = c.client_id " .
                    "left join users as u on d.staff_assigned = u.user_id " .
                    "left join assistants as s on d.duty_id = s.duty_id " .
                    "where d.status = \"$status\" " .
                    "and (d.staff_assigned = \"$staff\" or s.staff_id = \"$staff\") " . 
                    "order by d.date_entered desc ";
                    
            }
            
        }
        
        // Retrieve projects from database
        $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
            or die ("Cannot connect to database. " . mysql_error() . "\n<br>");
        mysql_select_db (DB_DATABASE);
        $get_duties_full = mysql_query($query);
        //printf("Query = $query<br>\n");
        $get_duties = mysql_query($query . "limit " . (($page - 1) * $maxresults) .
            ", $maxresults ");    
        if (mysql_num_rows($get_duties_full) == 0) {
            if ($displayed_user == "All") {
                if ($status == "All") {
                    printf("<b>No duties found in database.</b><br>\n");
                } else {
                    printf("<b>No " . strtolower($status) . " duties found in database.</b><br>\n");
                }
            } else {
                if ($status == "All") {
                    printf("<b>No duties found for $displayed_user.</b><br>\n");
                } else {
                    printf("<b>No " . strtolower($status) . " duties found for $displayed_user.</b><br>\n");
                }
            }
        } else {
        
            // Show page numbers for results
            $page_url = "duties.php?staff=$staff&status=$status&todostatus=" .
                "$todostatus&priority=$priority&calmode=$calmode";
            printf("%s\n", page_results(mysql_num_rows($get_duties_full), 
                $page, $maxresults, $page_url));

            printf("<table cellpadding='5' class='duty'>");
            printf("<tr><td><br></th>\n");
            printf("<th>Duty</th>\n");
            printf("<th>Description</th>\n");
            if ($displayed_user == "All") {
                printf("<th>Staff</th>\n");
            }
            //printf("<th>Requested</th>\n");
            printf("<th>Activity</th>\n");
            printf("<th>Entered</th></tr>\n");
            $rowcount = 0;
            while ($row = mysql_fetch_array($get_duties, MYSQL_ASSOC))
            {
                printf("<tr valign='top'>");

                // Icon
                printf("<td><img src='icons18/icon_%d.png'></td>\n", $row['icon_id']);

                // Duty title
                printf("<td><a href='duties.php?action=view&duty=%d'>%s</a></td>\n", 
                    $row['duty_id'], $row['title']);

                // Description
                printf("<td>%s", $row['description']);
                if ($row['clientname']) {
                    printf(" (<i>%s</i>)", $row['clientname']);
                }
                printf("</td>\n");

                // Staff (only if all users are being displayed)
                if ($displayed_user == "All") {
                    printf("<td align='center'>%s", substr($row['first_name'], 0, 1) . substr($row['last_name'], 0, 1));

                    // Display assistants, if any
                    $get_assistants = mysql_query("select u.first_name, u.last_name " .
                        "from users as u, assistants as s where u.user_id = s.staff_id " .
                        "and s.duty_id = \"" . $row['duty_id'] . "\" ");
                    while ($arow = mysql_fetch_array($get_assistants, MYSQL_ASSOC)) {
                        printf(", %s", substr($arow['first_name'], 0, 1) . 
                            substr($arow['last_name'], 0, 1));
                    }
                    mysql_free_result($get_assistants);
                    printf("</td>\n");
                }

                // Activity
                $get_todos = mysql_query("select t.todo_id from todos as t, " .
                    "duties as d where t.duty_id = d.duty_id " .
                    "and t.completed = 'Y' " .
                    "and d.duty_id = '" . $row['duty_id'] . "' ");
                $ntodos = mysql_num_rows($get_todos);
                mysql_free_result($get_todos);
                $get_comments = mysql_query("select c.comment_id from comments as c, " .
                    "duties as d where c.duty_id = d.duty_id " .
                    "and d.duty_id = '" . $row['duty_id'] . "' ");
                $ncomments = mysql_num_rows($get_comments);
                mysql_free_result($get_comments);
                $activity = $ntodos + $ncomments;
                printf("<td align='center'>$activity</td>\n");

                // Date entered
                if (($row['date_entered']) && ($row['date_entered'] != "0000-00-00") && ($row['date_entered'] != "NULL")) {
                    printf("<td>%s</td>\n", shorter_date($row['date_entered']));
                } else {
                    printf("<td><br></td>\n");
                }

                printf("</tr>\n");
                
            }
            printf("</table>");
        }

        mysql_free_result($get_duties);
        mysql_free_result($get_duties_full);
        mysql_close($conn);
        // End page
        require("footer.php");
        break;
}

?>
Back to Top