~adamzammit/quexf/main

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
<?php

/*	Copyright Deakin University 2007,2008
 *	Written by Adam Zammit - adam.zammit@deakin.edu.au
 *	For the Deakin Computer Assisted Research Facility: http://www.deakin.edu.au/dcarf/
 *	
 *	This file is part of queXF
 *	
 *	queXF 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.
 *	
 *	queXF 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 queXF; if not, write to the Free Software
 *	Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */


//verifier

include_once("config.inc.php");
include_once("db.inc.php");
include("functions/functions.image.php");
include("functions/functions.xhtml.php");
include("functions/functions.database.php");
				

function bgidtocss($zoom,$fid,$pid)
{
	global $db;

	$sql = "SELECT MIN(b.tlx) as tlx,MIN(b.tly) as tly,MAX(b.brx) as brx,MAX(b.bry) as bry, b.pid as pid, bg.btid as btid, b.bgid as bgid
		FROM boxes as b, boxgroupstype as bg
		WHERE b.pid = '$pid'
		AND bg.bgid = b.bgid
		AND bg.btid > 0
		GROUP BY bg.bgid
		ORDER BY bg.sortorder ASC";

	$boxgroups = $db->GetAll($sql);

	$sql = "SELECT offx,offy,centroidx,centroidy,costheta,sintheta,scalex,scaley,width,height
		FROM formpages as f
		WHERE f.pid = $pid and f.fid = $fid";
	
	$row = $db->GetRow($sql);

	$sql = "SELECT b.bid
		FROM boxes as b, boxgroupstype as bg
		WHERE b.pid = '$pid'
		AND bg.bgid = b.bgid
		AND bg.btid > 0
		ORDER BY bg.sortorder ASC, b.bid ASC";

	$boxes = $db->GetAll($sql);

	$vis = "visible";

	if (!isset($row['offx']) && !isset($row['offy']))
	{ 
		$row = array();
		$row['offx'] = 0;
		$row['offy'] = 0;
		$row['centroidx'] = PAGE_WIDTH / 2;
		$row['centroidy'] = PAGE_HEIGHT / 2;
		$row['costheta'] = 1;
		$row['sintheta'] = 0;
		$row['scalex'] = 1;
		$row['scaley'] = 1;
	}

	//fix for upgrades
	if ($row['width'] == 0) $row['width'] = PAGE_WIDTH;
	if ($row['height'] == 0) $row['height'] = PAGE_HEIGHT;

	print "<form id=\"mainform\" method=\"post\" action=\"{$_SERVER['PHP_SELF']}\">";

  //display alignment markers
  $sql = "SELECT tlx,tly,trx,try,blx,bly,brx,bry FROM pages WHERE pid = $pid";
  $pmark = $db->GetRow($sql);
  print "<div id='tla' class='mydiv' style='top:" . $pmark['tly'] / $zoom . "px; left:" . $pmark['tlx'] / $zoom . "px; display:none;'><div id='tlaheader' class='mydivheader'>TL</div></div>";
  print "<div id='tra' class='mydiv' style='top:" . $pmark['try'] / $zoom . "px; left:" . $pmark['trx'] / $zoom . "px; display:none;'><div id='traheader' class='mydivheader'>TR</div></div>";
  print "<div id='bla' class='mydiv' style='top:" . $pmark['bly'] / $zoom . "px; left:" . $pmark['blx'] / $zoom . "px; display:none;'><div id='blaheader' class='mydivheader'>BL</div></div>";
  print "<div id='bra' class='mydiv' style='top:" . $pmark['bry'] / $zoom . "px; left:" . $pmark['brx'] / $zoom . "px; display:none;'><div id='braheader' class='mydivheader'>BR</div></div>";


	foreach ($boxgroups as $boxgroup)
	{
		$crop = applytransforms($boxgroup,$row);

		$bgid = $boxgroup['bgid'];

		//make box group display higher
		$ttop = ($crop['tly'] / $zoom) - DISPLAY_GAP;
		if ($ttop < 0) $ttop = 0;

		print "<div id=\"boxGroup_$bgid\" style=\"position:absolute; top:" . $ttop . "px; width:1px; height:1px; background-color: " . BOX_BACKGROUND_COLOUR . ";opacity:.0;\"></div>";


		print "<div id=\"boxGroupBox_$bgid\" onclick=\"groupChange('$bgid');\" style=\"position:absolute; top:" . $crop['tly'] / $zoom . "px; left:" . $crop['tlx'] / $zoom . "px; width:" . ($crop['brx'] - $crop['tlx'] ) / $zoom . "px; height:" . ($crop['bry'] - $crop['tly'] ) / $zoom . "px; background-color: " . BOX_GROUP_BACKGROUND_COLOUR . ";opacity:" .  BOX_GROUP_BACKGROUND_OPACITY . "; visibility: $vis;\"></div>";


		print "<div><input type=\"checkbox\" name=\"bgid$bgid\" id=\"bgid$bgid\" style=\"opacity:0.0; \"/></div>";

		$vis = "hidden";
	}


	foreach($boxes as $bi)
	{
		$bid = $bi['bid'];

		//if (!isset($_SESSION['boxes'][$bid])) break;

		$box = $_SESSION['boxes'][$bid];

		$val = $_SESSION['boxes'][$bid]['val'];
		$bbgid = $_SESSION['boxes'][$bid]['bgid'];
		$btid = $_SESSION['boxes'][$bid]['btid'];

		$box = applytransforms($box,$row);

		if ($btid == 1) //single
		{
				if ($val == 0) {$checked = ""; $colour = BOX_BACKGROUND_COLOUR; } else {$checked = "checked=\"checked\""; $colour = BOX_SELECT_COLOUR;}
				print "<div><input type=\"checkbox\" name=\"bid$bid\" id=\"checkBox$bid\" value=\"$bid\" style=\"position:absolute; top:" . $box['tly'] / $zoom . "px; left:" . $box['tlx'] / $zoom . "px; width:" . ($box['brx'] - $box['tlx'] ) / $zoom . "px; height:" . ($box['bry'] - $box['tly'] ) / $zoom . "px; opacity:0.0; \" onclick=\"radioUpdate('$bid','$bbgid'); \" $checked onkeypress=\"checkEnter(event,$bbgid,$bid)\"/></div>";
				print "<div id=\"checkImage$bid\" onkeypress=\"checkEnter(event,$bbgid,$bid)\" onclick=\"radioChange('$bid','$bbgid'); \" style=\"position:absolute; top:" . $box['tly'] / $zoom . "px; left:" . $box['tlx'] / $zoom . "px; width:" . ($box['brx'] - $box['tlx'] ) / $zoom . "px; height:" . ($box['bry'] - $box['tly'] ) / $zoom . "px; background-color: $colour;opacity:" .  BOX_OPACITY . "; \"></div>";
	
		}
		else if ($btid == 2) //multiple
		{
	
				if ($val == 0) {$checked = ""; $colour = BOX_BACKGROUND_COLOUR; } else {$checked = "checked=\"checked\""; $colour = BOX_SELECT_COLOUR;}
				print "<div><input type=\"checkbox\" name=\"bid$bid\" id=\"checkBox$bid\" value=\"$bid\" style=\"position:absolute; top:" . $box['tly'] / $zoom . "px; left:" . $box['tlx'] / $zoom . "px; width:" . ($box['brx'] - $box['tlx'] ) / $zoom . "px; height:" . ($box['bry'] - $box['tly'] ) / $zoom . "px; opacity:0.0; \" onclick=\"checkUpdate('$bid','$bbgid'); \" $checked onkeypress=\"checkEnter(event,$bbgid,$bid)\" /></div>";
				print "<div id=\"checkImage$bid\" onkeypress=\"checkEnter(event,$bbgid,$bid)\" onclick=\"checkChange('$bid','$bbgid'); \" style=\"position:absolute; top:" . $box['tly'] / $zoom . "px; left:" . $box['tlx'] / $zoom . "px; width:" . ($box['brx'] - $box['tlx'] ) / $zoom . "px; height:" . ($box['bry'] - $box['tly'] ) / $zoom . "px; background-color: $colour;opacity:" .  BOX_OPACITY . ";  \"></div>";

		}
		else if ($btid == 3 || $btid == 4) //text or number
		{
			$maxlength = "maxlength=\"1\"";
			$onkeypress = "onkeypress=\"textPress(this,event,$bbgid,$bid)\"";

			if ($btid == 4)
			{
				if (!is_numeric($val)) $val = "";
			}

            if ($val !== null) {
    			$val = htmlspecialchars($val);
            }
	
			print "<div><input type=\"text\" name=\"bid$bid\" id=\"textBox$bid\" value=\"$val\" $maxlength style=\"z-index: 1; position:absolute; top:" . (($box['tly'] / $zoom) + (($box['bry'] - $box['tly'] ) / $zoom)) . "px; left:" . $box['tlx'] / $zoom . "px; width:" . ($box['brx'] - $box['tlx'] ) / $zoom . "px; height:" . ($box['bry'] - $box['tly'] ) / $zoom . "px;\" onclick=\"\" onfocus=\"select()\" $onkeypress /></div>";

		
			print "<div id=\"textImage$bid\" style=\"position:absolute; top:" . $box['tly'] / $zoom . "px; left:" . $box['tlx'] / $zoom . "px; width:" . ($box['brx'] - $box['tlx'] ) / $zoom . "px; height:" . ($box['bry'] - $box['tly'] ) / $zoom . "px; background-color: " . BOX_BACKGROUND_COLOUR . "; text-align:center; font-weight:bold;\" onclick=\"textClick('$bid','$bbgid');\">$val</div>";
		}
		else if ($btid == 6 || $btid == 5)
		{
            if ($val !== null) {
			    $val = htmlspecialchars($val);
            }	
			print "<div><textarea name=\"bid$bid\" id=\"textBox$bid\" style=\"z-index: 1; position:absolute; top:" . (($box['tly'] / $zoom) + (($box['bry'] - $box['tly'] ) / $zoom)) . "px; left:" . $box['tlx'] / $zoom . "px; width:" . ($box['brx'] - $box['tlx'] ) / $zoom . "px; height:" . ($box['bry'] - $box['tly'] ) / $zoom . "px;\" onclick=\"\" onfocus=\"select()\" rows=\"20\" cols=\"80\">$val</textarea></div>";

		
			print "<div id=\"textImage$bid\" style=\"position:absolute; top:" . $box['tly'] / $zoom . "px; left:" . $box['tlx'] / $zoom . "px; width:" . ($box['brx'] - $box['tlx'] ) / $zoom . "px; height:" . ($box['bry'] - $box['tly'] ) / $zoom . "px; background-color: " . BOX_BACKGROUND_COLOUR . "; text-align:center; font-weight:bold;\" onclick=\"textClick('$bid','$bbgid');\">$val</div>";


		}
	}
	print "<div><input type=\"hidden\" name=\"piddone\" value=\"$pid\"/></div>";
	print "</form>";


}

session_start();

$vid = get_vid();

if($vid == false){ print T_("Please log in"); exit;}

$fid = get_fid($vid);


if (isset($_GET['align']) && isset($_GET['fid']) && isset($_GET['pid']) )
{
	$pid = $_GET['pid'];

  //get the page id from the page table
  $sql = "SELECT * FROM pages
      WHERE pid = '$pid'";

    $page = $db->GetRow($sql);

  $zoom = floatval($_GET['zoom']);

    $offset = array();
    $offset[] = floatval($_GET['tlax']) * $zoom;
    $offset[] = floatval($_GET['tlay']) * $zoom;
    $offset[] = floatval($_GET['trax']) * $zoom;
    $offset[] = floatval($_GET['tray']) * $zoom;
    $offset[] = floatval($_GET['blax']) * $zoom;
    $offset[] = floatval($_GET['blay']) * $zoom;
    $offset[] = floatval($_GET['brax']) * $zoom;
    $offset[] = floatval($_GET['bray']) * $zoom;


  //calc transforms
        $transforms = detecttransforms(false,$page,$offset);

    unset($transforms['width']);
    unset($transforms['height']);
        //save image to db including offset
        $sql = "UPDATE formpages SET ";
							
							foreach($transforms as $key => $val)
								$sql .= " $key = $val,";

              $sql = substr($sql,0,-1);

              $sql .=  " WHERE pid = $pid AND fid = " . $_GET['fid'];

							$db->Execute($sql);
	
}


if (isset($_GET['centre']) && isset($_GET['fid']) && isset($_GET['pid']) )
{
	$pid = $_GET['pid'];

	$sql = "UPDATE formpages
		SET offx = 0, offy = 0, costheta = 1, sintheta = 0, scalex = 1, scaley = 1, `centroidy` = (SELECT height / 2 FROM pages WHERE pid = '$pid'), `centroidx` = (SELECT width / 2 FROM pages WHERE pid = '$pid') 
		WHERE fid = '$fid'
		AND pid = '$pid'";

	$db->Execute($sql);
}

if (!empty($fid))
{
	$qid_desc = get_qid_description($fid);
	$qid = $qid_desc['qid'];
  $description = $qid_desc['description'];
  $double_entry = $qid_desc['double_entry'];
}

if (isset($_POST['supervisor'])) {

	$db->StartTrans();

  $sql = "UPDATE forms
		SET done = 2, assigned_vid = NULL, assigned = NULL, completed = NULL
		WHERE assigned_vid = '$vid'
		AND fid = '$fid'";

	$db->Execute($sql);

	unset($_SESSION['boxgroups']);
	unset($_SESSION['pages']);
	unset($_SESSION['boxes']);
	session_unset();

	$sql = "UPDATE verifiers
		SET currentfid = NULL
		WHERE vid = '$vid'";

	//print "$sql</br>";
	$db->Execute($sql);

	$db->CompleteTrans();

  $fid = false;

}
else if (isset($_POST['supervisorreturn'])) {

  $db->StartTrans();

  $sql = "UPDATE forms
		SET done = 0, assigned_vid = NULL, assigned = NULL, completed = NULL
		WHERE assigned_vid = '$vid'
		AND fid = '$fid'";

	$db->Execute($sql);

	unset($_SESSION['boxgroups']);
	unset($_SESSION['pages']);
	unset($_SESSION['boxes']);
	session_unset();

	$sql = "UPDATE verifiers
		SET currentfid = NULL
		WHERE vid = '$vid'";

	//print "$sql</br>";
	$db->Execute($sql);

	$db->CompleteTrans();

  $fid = false;



}
else if (isset($_POST['complete']) && isset($_SESSION['boxes'])) {

	
	foreach($_SESSION['boxes'] as $key => $box)
	{

		$sql = "";
		if ($box['btid'] == 1 || $box['btid'] == 2)
    {
      //delete old data
      if (DELETE_ON_VERIFICATION)
      {
        $db->Execute("DELETE FROM formboxverifychar WHERE vid = 0 AND bid = '$key' AND fid = '$fid'");
      }

      if ($box['val'] > 0)
      {
  			$sql = "INSERT INTO formboxverifychar (`vid`,`bid`,`fid`,`val`) VALUES ('$vid','$key','$fid','1')";
      }
		}
		if ($box['btid'] == 3 || $box['btid'] == 4)
		{
      //delete old data
      if (DELETE_ON_VERIFICATION)
      {
        $db->Execute("DELETE FROM formboxverifychar WHERE vid = 0 AND bid = '$key' AND fid = '$fid'");
      }

			if ($box['val'] == "" || $box['val'] == " ")
			{
				//$sql = "INSERT INTO formboxverifychar (`vid`,`bid`,`fid`,`val`) VALUES ('$vid','$key','$fid',NULL)";
			}else
			{
				$bval = $db->qstr($box['val']);
				$sql = "INSERT INTO formboxverifychar (`vid`,`bid`,`fid`,`val`) VALUES ('$vid','$key','$fid',$bval)";
			}
		}
		if ($box['btid'] == 6 || $box['btid'] == 5)
		{
			if ($box['val'] == "" || $box['val'] == " ")
			{
				//$sql = "INSERT INTO formboxverifytext (`vid`,`bid`,`fid`,`val`) VALUES ('$vid','$key','$fid',NULL)";
			}else
			{
				$bval = $db->qstr($box['val']);
				$sql = "INSERT INTO formboxverifytext (`vid`,`bid`,`fid`,`val`) VALUES ('$vid','$key','$fid',$bval)";
			}

    }
    if ($sql != "")
    {
  		$db->Execute($sql);
    }

    //Delete unneeded box data
    if (DELETE_ON_VERIFICATION)
    {
      $sql = "DELETE IGNORE FROM formboxes WHERE fid = '$fid' AND bid = '$key'";
      $db->Execute($sql);
    }

		//print "$sql</br>";
	}

	//make sure worklog and update occurs at the same time
	$db->StartTrans();

  $dstatus = 1;

  if ($double_entry) {
    $sql = "SELECT done
            FROM forms
            WHERE fid = '$fid'";
  
    $dstatus = $db->GetOne($sql);
  }

  if ($dstatus == 1 || $dstatus == 3) { //not double entry or double entry second go
    $sql = "UPDATE forms
		  SET done = 1, assigned = FROM_UNIXTIME({$_SESSION['assigned']}), completed = NOW()
  		WHERE assigned_vid = '$vid'
  		AND fid = '$fid'"; 
  } else if ($dstatus == 0) { //double entry, first go
     $sql = "UPDATE forms
      SET done = 3, 
      assigned_vid = NULL,
      assigned2 = FROM_UNIXTIME({$_SESSION['assigned']}), 
      completed2 = NOW(),
      assigned_vid2 = $vid
  		WHERE assigned_vid = '$vid'
  		AND fid = '$fid'";
  } 

  $db->Execute($sql);


  unset($_SESSION['boxgroups']);
	unset($_SESSION['pages']);
	unset($_SESSION['boxes']);
	session_unset();

	$sql = "UPDATE verifiers
		SET currentfid = NULL
		WHERE vid = '$vid'";

	//print "$sql</br>";
	$db->Execute($sql);

	$db->CompleteTrans();

  //only do RPC on final verification
  if ($dstatus == 1 || ($double_entry && $dstatus == 3)) {

    //if XMLRPC is set - upload this form via XMLRPC
    $sql = "SELECT rpc_server_url 
      FROM questionnaires
      WHERE qid = '$qid'";

    $rpc = $db->GetRow($sql);

    if (isset($rpc['rpc_server_url']) && !empty($rpc['rpc_server_url']))
    {
      //upload form via RPC
      include_once("functions/functions.output.php");
      uploadrpcJson($fid);
    }
  }

	$fid = false;
}


if (isset($_GET['review']))
{
	foreach($_SESSION['boxgroups'] as $key => $val)
	{
		$_SESSION['boxgroups'][$key]['done'] = 0;
	}
}

if (isset($_GET['clear']))
{
	unset($_SESSION['boxgroups']);
	unset($_SESSION['pages']);
	unset($_SESSION['boxes']);
	session_unset();
}

if (isset($_POST['assign']))
{
	session_unset();
	$fid = assign_to($vid);
	if ($fid == false) 
	{
    xhtml_head(T_("Verify: No more work"),true,false,false,"onload='document.form1.assign.focus();'");
		print "<p>" . T_("NO MORE WORK") . "</p>";
		print "<form name=\"form1\" action=\"" . $_SERVER['PHP_SELF'] . "\" method=\"post\"><input type=\"submit\" name=\"assign\" value=\"" . T_("Check for more work") . "\"/></form>";
		unset($_SESSION['boxgroups']);
		unset($_SESSION['boxes']);
		unset($_SESSION['pages']);	
		session_unset();
		xhtml_foot();
		exit();
	}
	//set assigned time session variable
	$_SESSION['assigned'] = time();
}

if ($fid == false)
{
	xhtml_head(T_("Verify: Assign form"),true,array("css/table.css"),false,"onload='document.form1.assign.focus();'");
	print "<div id=\"links\">";
	print "<p>" . T_("There is no form currently assigned to you") . "</p>";
//	print "<p><a href=\"" . $_SERVER['PHP_SELF'] . "?assign=assign\" onclick=\"document.getElementById('links').style.visibility='hidden'; document.getElementById('wait').style.visibility='visible';\">" . T_("Assign next form") . "</a></p>";
  print "<form name=\"form1\" action=\"" . $_SERVER['PHP_SELF'] . "\" method=\"post\"><input type=\"submit\" name=\"assign\" onclick=\"document.getElementById('links').style.visibility='hidden'; document.getElementById('wait').style.visibility='visible';\"  value=\"" . T_("Assign next form") . "\"/></form>";
	print "</div>";
	print "<div id=\"wait\" style=\"visibility: hidden;\">
<p>" .  T_("Assigning next form: Please wait...") . "</p>
</div>";

	
	//display performance information for each assigned questionnaire
	$sql = "SELECT vq.qid, q.description 
		FROM verifierquestionnaire as vq, questionnaires as q
		WHERE vq.vid = '$vid'
		AND q.qid = vq.qid";

	$prs = $db->GetAll($sql);

  foreach($prs as $pr)
	{
		$pqid = $pr['qid'];
		$pdes = $pr['description'];

		$sql = "SELECT count(*) as rem
			FROM forms
			WHERE qid = '$pqid'
			AND done IN (0,2)";

		$remain = $db->GetOne($sql);

		$sql = "SELECT count(*) as ver
			FROM forms
			WHERE qid = '$pqid'
			AND done IN (3)";

		$verify = $db->GetOne($sql);

		$sql = "SELECT q.description as qu, v.description as ve,f.qid,f.assigned_vid as vid , count( * ) AS c, count( * ) / ( SUM( TIMESTAMPDIFF(
			SECOND , f.assigned, f.completed ) ) /3600 ) AS CPH, (
			(
			
			SELECT count( pid )
			FROM pages
			WHERE qid = f.qid
			) * count( * )
			) / ( SUM( TIMESTAMPDIFF(
			SECOND , f.assigned, f.completed ) ) /3600 ) AS PPH
			FROM forms AS f
			JOIN questionnaires as q on (f.qid = q.qid)
			JOIN verifiers as v on (v.vid = f.assigned_vid)
			WHERE f.qid = '$pqid'
			GROUP BY f.qid, f.assigned_vid
			ORDER BY CPH DESC";

		$prss = $db->GetAll($sql);

		print "<h3>$pdes</h3>";
		xhtml_table($prss,array('ve','c','CPH','PPH'),array(T_("Operator"),T_("Completed Forms"),T_("Completions Per Hour"),T_("Pages Per Hour")),"tclass",array
("vid" => $vid));
		print "<p>" . T_("Remain to verify") . ": $remain</p>";
		print "<p>" . T_("Waiting for double entry") . ": $verify</p>";
	}

	xhtml_foot();
	exit();
}

$qid_desc = get_qid_description($fid);
$qid = $qid_desc['qid'];
$description = $qid_desc['description'];
$double_entry = $qid_desc['double_entry'];

if (!isset($_SESSION['boxes'])) {
	//nothing yet known about this form

  $ovid = 0;

  $sql = "SELECT done,assigned_vid2
          FROM forms
          WHERE fid = $fid";
  
  $dstatus = $db->GetRow($sql);

  if ($dstatus['done'] == 3)
    $ovid = $dstatus['assigned_vid2'];

	$sql = "SELECT b.bid as bid, b.tlx as tlx, b.tly as tly, b.brx as brx, b.bry as bry, b.pid as pid, bg.btid as btid, b.bgid as bgid, $fid as fid, bg.sortorder as sortorder, fb.filled, CASE WHEN d.fid IS NOT NULL THEN d.val ELSE c.val END as val
		FROM boxes AS b
		JOIN boxgroupstype as bg ON (bg.bgid = b.bgid AND bg.btid > 0)
    JOIN pages as p ON (p.pid = b.pid AND p.qid = '$qid')
    LEFT JOIN formboxes as fb ON (fb.bid = b.bid AND fb.fid = '$fid')
		LEFT JOIN formboxverifychar AS c ON (c.fid = '$fid' AND c.vid = '$ovid' AND c.bid = b.bid)
		LEFT JOIN formboxverifytext AS d ON (d.fid = '$fid' AND d.vid = '$ovid' AND d.bid = b.bid)
		ORDER BY bg.sortorder ASC";

	
	$sql2 = "SELECT b.bgid,0 as done,MIN(b.pid) as pid,bg.varname,bg.btid
		FROM boxes as b, boxgroupstype as bg, pages as p
		WHERE p.pid = b.pid
		AND bg.bgid = b.bgid
		AND p.qid = '$qid' 
		AND bg.btid > 0
		GROUP BY bg.bgid
		ORDER BY bg.sortorder ASC";

	$sql3 = "SELECT b.pid,MIN(b.bgid) as bgid,0 as done, fp.width, fp.height, fp.fid
		FROM boxes as b
		JOIN pages as p ON (p.qid = '$qid' AND b.pid = p.pid)
		JOIN boxgroupstype as bg ON (bg.bgid = b.bgid)
		LEFT JOIN formpages as fp ON (fp.fid = '$fid' AND fp.pid = p.pid)
		GROUP BY b.pid
		ORDER BY MIN(bg.sortorder) ASC";

  $a = $db->GetAssoc($sql);
	if (empty($a)) 
	{
    xhtml_head(T_("Verify: No more work"),true,false,false,"onload='document.form1.assign.focus();'");
		print "<p>" . T_("NO MORE WORK") . "</p>";
		print "<form name=\"form1\" action=\"" . $_SERVER['PHP_SELF'] . "\" method=\"post\"><input type=\"submit\" name=\"assign\" value=\"" . T_("Check for more work") . "\"/></form>";
		//print "<p><a href=\"" . $_SERVER['PHP_SELF'] . "?assign=assign\">" . T_("Check for more work") . "</a></p>";
		unset($_SESSION['boxgroups']);
		unset($_SESSION['pages']);
		unset($_SESSION['boxes']);
		session_unset();
		xhtml_foot();
		exit();
	}

	$b = $db->GetAssoc($sql2);
	$c = $db->GetAssoc($sql3);


	$_SESSION['boxes'] = $a;
	$_SESSION['boxgroups'] = $b;
	$_SESSION['pages'] = $c;
	$_SESSION['assigned'] = time();


  if (SINGLE_CHOICE_AUTOMATIC_VERIFICATION)
  {
  
    //see if any boxes should be automatically marked as verified
  
    //search for single choice boxes (btid == 1), within box groups where > 1 box is available
    //if there is one and only one box within the filled range, and val is set as 1, then mark as done
  
    $tmpt = current($a);
    //set to first bgid
    $tmpbgid = $tmpt['bgid'];
    $tmpgroup = array();
    foreach($_SESSION['boxes'] as $key => $val)
    {
      if ($val['bgid'] != $tmpbgid)
      { 
        //check the number of boxes in this group that fall within the restrictions
        $within = 0;
        $withinkey = 0;
        $withincount = 0;
        foreach($tmpgroup as $tkey => $tval)
        {
          if ($tval['filled'] < SINGLE_CHOICE_MIN_FILLED && $tval['filled'] > SINGLE_CHOICE_MAX_FILLED)
          {
            $within++;
            $withinkey = $tkey;
          }
          $withincount++;
        }
  
        //if one box within and also this is the selected box - mark this box group as done
        if ($withincount > 1 && $within == 1 && $_SESSION['boxes'][$withinkey]['val'] == 1)
        {
          $_SESSION['boxgroups'][$_SESSION['boxes'][$withinkey]['bgid']]['done'] = 1;
        }
  
        $tmpbgid = $val['bgid'];
        $tmpgroup = array();
      }
  
      //only for single choice boxes
      if ($val['btid'] == 1)
      {
        $tmpgroup[$key] = $val;
      }
    }
  }
}


//form data already here

//if data submitted, store it to local session
if (isset($_POST['piddone']))
{
	$pid = intval($_POST['piddone']);

	foreach($_POST as $getkey => $getval)
	{
		//print "SUBMIT Key: $getkey Val: $getval<br/>";
		if (strncmp($getkey,'bgid',4) == 0)
		{
			$bgid = intval(substr($getkey,4));
			if ($getval == "on") $getval = 1;
			$_SESSION['boxgroups'][$bgid]['done'] = $getval;

			//destroy existing data in this box group...
			$sql = "SELECT bid
				FROM boxes
				WHERE bgid = '$bgid'";
		
			$b = $db->GetAll($sql);

			foreach($b as $bb)
			{
				$_SESSION['boxes'][$bb['bid']]['val'] = "";
			}



		}
	}


	//store retrieved data
	foreach($_POST as $getkey => $getval)
	{
		//print "SUBMIT Key: $getkey Val: $getval<br/>";
		if (strncmp($getkey,'bid',3) == 0)
		{
			$bid = intval(substr($getkey,3));
			$_SESSION['boxes'][$bid]['val'] = $getval;
		}
	}


}

$bgid = "";
$pid = "";
$destroypage = 0;

//move to a specific page
if (isset($_GET['pid']))
{
	$pid = intval($_GET['pid']);
	//destroy "done" for this page
	$destroypage = 1;
}
else
{
	//get next page to work on
	foreach($_SESSION['boxgroups'] as $key => $val)
	{
		if ($val['done'] == 0)
		{
			$bgid = $key;
			break;
		}
	}
}


if ($bgid != "")
{
	$sql = "SELECT pid
		FROM boxes
		WHERE bgid = '$bgid'";
	
	$bggg = $db->GetRow($sql);
	
	$pid = $bggg['pid'];
}
else if ($pid == "") 
{
	//we are done
//	xhtml_head(T_("Verify: Done"));
  xhtml_head(T_("Verify: Done"),true,false,false,"onload='document.form1.complete.focus();'");
	print "<p>" . T_("The required fields have been filled") . "</p>";
	print "<div id=\"links\">";
  print "<form name=\"form1\" action=\"" . $_SERVER['PHP_SELF'] . "\" method=\"post\"><input type=\"submit\" name=\"complete\" onclick=\"document.getElementById('links').style.visibility='hidden'; document.getElementById('wait').style.visibility='visible';\"  value=\"" . T_("Submit completed form to database") . "\"/></form>";
//	print "<p><a href=\"" . $_SERVER['PHP_SELF'] . "?complete=complete\" onclick=\"document.getElementById('links').style.visibility='hidden'; document.getElementById('wait').style.visibility='visible';\">" . T_("Submit completed form to database") . "</a></p>";
	print "<p><a href=\"" . $_SERVER['PHP_SELF'] . "?review=review#boxGroup\" onclick=\"document.getElementById('links').style.visibility='hidden'; document.getElementById('wait').style.visibility='visible';\">" . T_("Review all questions again") . "</a></p>";
	print "<p><a href=\"" . $_SERVER['PHP_SELF'] . "?clear=clear#boxGroup\" onclick=\"document.getElementById('links').style.visibility='hidden'; document.getElementById('wait').style.visibility='visible';\">" . T_("Clear all entered data and review again") . "</a></p></div>";

	print "<div id=\"wait\" style=\"visibility: hidden;\"><p>" .  T_("Submitting: Please wait...") . "</p></div>";
	xhtml_foot();

	exit();
}	
	



print "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
      <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title><?php echo T_("Verifier"); ?> - <?php print "QID:$qid FID:$fid DESC:$description"; ?></title>
<script type="text/javascript">

/* <![CDATA[ */

var bgiddone = new Array();
var bgidbid = new Array();
var bgidtype = new Array();
var curbgid = 0;
var pagedone = 0;
var newwindow;

<?php

//print order variable
$sql = "SELECT boxgroupstype.bgid
	FROM boxgroupstype
	JOIN boxes ON boxes.bgid = boxgroupstype.bgid
  WHERE boxgroupstype.pid = '$pid'
  AND boxgroupstype.btid > 0
	GROUP BY boxgroupstype.bgid
	ORDER BY boxgroupstype.sortorder ASC";
		
$b = $db->GetAll($sql);
			
print "bgidorder = new Array(";
		
$s = "";
		
foreach($b as $bb)
{
	$s .= "'{$bb['bgid']}',";
}
		
$s = substr($s,0,strlen($s) - 1);
		
print "$s);\n";



//print array of done/not done box groups for this page
//print all bgid box groups for this page containing a list of boxes in that box group
foreach($_SESSION['boxgroups'] as $key => $val)
{
	if ($val['pid'] == $pid)
	{
		if ($val['done'] == 0 || $destroypage == 1)
			print "bgiddone[$key] = 0;\n";
		else
			print "bgiddone[$key] = 1;\n";

		print "bgidtype[$key] = {$val['btid']};\n";

		$sql = "SELECT bid
			FROM boxes
			WHERE bgid = '$key'";

		$b = $db->GetAll($sql);
	
		print "bgidbid[$key] = new Array(";

		$s = "";

		foreach($b as $bb)
		{
			$s .= "'{$bb['bid']}',";
		}


		$s = substr($s,0,strlen($s) - 1);
	
		print "$s);\n";




	}
}
?>

function allDone()
{
        for (var i=0; i < bgidorder.length; i++)
        {
                x = bgidorder[i];
                bgiddone[x] = 1;
                document.getElementById('bgid' + x ).checked = 'checked';
                document.getElementById('bgid' + x ).val = '1';
        }
        document.forms.namedItem("mainform").submit();
}

function showAlign()
{
  document.getElementById('tla').style.display = 'block';
  document.getElementById('tra').style.display = 'block';
  document.getElementById('bla').style.display = 'block';
  document.getElementById('bra').style.display = 'block';
  document.getElementById('acceptalign').style.display = 'block';
}

function acceptAlign(pid,fid,zoom)
{
 window.location='verifyjs.php?align=align&pid=' + pid + '&fid=' + fid + '&zoom=' + zoom + 
                   '&tlax=' + document.getElementById('tla').style.left +
                   '&tlay=' + document.getElementById('tla').style.top  +
                   '&trax=' + document.getElementById('tra').style.left +
                   '&tray=' + document.getElementById('tra').style.top +
                   '&blax=' + document.getElementById('bla').style.left +
                   '&blay=' + document.getElementById('bla').style.top +
                   '&brax=' + document.getElementById('bra').style.left +
                   '&bray=' + document.getElementById('bra').style.top;
}


function nextTask()
{
	var done = 0;
	var focusdone = 0;

	for (var i=0; i < bgidorder.length; i++)
	{
		x = bgidorder[i];
		document.getElementById('boxGroupBox_' + x ).style.visibility = 'hidden';

		if (bgidtype[x] == 3 || bgidtype[x] == 4 || bgidtype[x] == 5 || bgidtype[x] == 6)
		{	
			for (y in bgidbid[x])
			{
				document.getElementById('textImage' + bgidbid[x][y]).style.visibility = 'visible';
				document.getElementById('textBox' + bgidbid[x][y]).style.visibility = 'hidden';
				document.getElementById('textImage' + bgidbid[x][y]).innerHTML = document.getElementById('textBox' + bgidbid[x][y]).value;
			}
		}

		if (bgiddone[x] == 0 && done == 0)
		{
			curbgid = x;

			if (bgidtype[x] == 3 || bgidtype[x] == 4 || bgidtype[x] == 5 || bgidtype[x] == 6)
			{	
				for (y in bgidbid[x])
				{
					document.getElementById('textImage' + bgidbid[x][y]).style.visibility = 'hidden';
					document.getElementById('textBox' + bgidbid[x][y]).style.visibility = 'visible';
					if (focusdone == 0)
					{
						focusText(bgidbid[x][y]);
						focusdone = 1;
					}

				}
			}else
			{
				if (focusdone == 0)
				{
					focusRadio();
					focusdone = 1;
				}
			}


			document.getElementById('boxGroupBox_' + x ).style.visibility = 'visible';
			document.getElementById('content').scrollTop = document.getElementById('boxGroupBox_' + x).offsetTop - <?php echo DISPLAY_GAP;?>;
		 	done = 1;
		}
	}

	if (done == 0)
	{
		//if (pagedone == 1)
			document.forms.namedItem("mainform").submit();
		//else
		//	pagedone = 1;
	}



}

function previous() {

	if (curbgid == 0) return;

	prev = 0;

	for (var i=0; i < bgidorder.length; i++)
	{
		x = bgidorder[i];
		if (x == curbgid) break;
		prev = x;
	}

	if (prev == 0) return;

	bgiddone[prev] = 0;
}


function detectEvent(e) {
	var evt = e || event;

	if (evt.ctrlKey && !evt.altKey)
	{
		previous();
		nextTask();
		return false;
	}

	if (evt.keyCode == 91 || evt.keyCode == 92 || evt.keyCode == 113)
	{
		images = document.getElementsByTagName('img');
		poptastic(images[0].src + '&zoom');
		return false;
	}

	if(evt.keyCode != 13){ //if generated character code is equal to ascii 13 (if enter key)
		return document.defaultAction;
		
	}


	if (curbgid != 0)
	{
		bgiddone[curbgid] = 1;
		document.getElementById('bgid' + curbgid ).checked = 'checked';
		document.getElementById('bgid' + curbgid ).val = '1';
	}

	nextTask();

	return false;
}


function focusRadio()
{
	//alert('curbgid: ' + curbgid + ' bgidbid: ' + bgidbid[curbgid]);
	document.getElementById('checkBox' + bgidbid[curbgid][0]).focus();
	document.getElementById('checkBox' + bgidbid[curbgid][0]).select();

	for (y in bgidbid[curbgid])
	{
		z = bgidbid[curbgid][y];

		box = document.getElementById('checkBox' + z);
		image = document.getElementById('checkImage' + z);

		if (box.checked)
		{
			box.focus();
			box.select();
		}
	}


}



function checkFocus(bid,bgid) {

	if (curbgid != bgid)
	{
		//goto selected bgid	
		bgiddone[bgid] = 0;
		nextTask();
		return;
	}


	for (x in bgidbid[bgid])
	{
		x = bgidbid[bgid][x];

		box = document.getElementById('checkBox' + x);
		image = document.getElementById('checkImage' + x);

		if (x == bid)
		{
			box.focus();
			if (box.checked)
			{
				image.style.backgroundColor='<?php echo BOX_SELECT_COLOUR; ?>';
			} else {
				image.style.backgroundColor='<?php echo BOX_FOCUS_COLOUR; ?>';
			}
		} else {
			if (box.checked)
			{
				image.style.backgroundColor='<?php echo BOX_SELECT_COLOUR; ?>';
			} else {
				image.style.backgroundColor='<?php echo BOX_BACKGROUND_COLOUR; ?>';
			}
	
		}
	}

}


function groupChange(bgid) {

	if (curbgid != bgid)
	{
		//goto selected bgid	
		bgiddone[bgid] = 0;
		nextTask();
		return;
	}

	//else do nothing
	return;

}


function radioChange(bid,bgid) {

	if (curbgid != bgid)
	{
		//goto selected bgid	
		bgiddone[bgid] = 0;
		nextTask();
		return;
	}


	for (x in bgidbid[bgid])
	{
		x = bgidbid[bgid][x];

		box = document.getElementById('checkBox' + x);
		image = document.getElementById('checkImage' + x);

		if (x == bid)
		{
			if (box.checked)
			{
				box.checked = '';
				image.style.backgroundColor='<?php echo BOX_BACKGROUND_COLOUR; ?>';
			} else {
				box.checked = 'checked';
				image.style.backgroundColor='<?php echo BOX_SELECT_COLOUR; ?>';
				box.focus();
			}
		} else {

			box.checked = '';
			image.style.backgroundColor='<?php echo BOX_BACKGROUND_COLOUR; ?>';
		}
	}

}

function radioUpdate(bid,bgid) {

	for (x in bgidbid[bgid])
	{
		x = bgidbid[bgid][x];

		box = document.getElementById('checkBox' + x);
		image = document.getElementById('checkImage' + x);


		if (x == bid)
		{
			if (box.checked)
			{
				box.checked = 'checked';
				image.style.backgroundColor='<?php echo BOX_SELECT_COLOUR; ?>';
			} else {
				box.checked = '';
				image.style.backgroundColor='<?php echo BOX_BACKGROUND_COLOUR; ?>';
			}
		} else {
			box.checked = '';
			image.style.backgroundColor='<?php echo BOX_BACKGROUND_COLOUR; ?>';
		}
	}

}

//change the checkbox status and the replacement image
function checkChange(bid,bgid) {

	if (curbgid != bgid)
	{
		//goto selected bgid
		bgiddone[bgid] = 0;
		nextTask();		
		return;
	}


	box = document.getElementById('checkBox' + bid);
	image = document.getElementById('checkImage' + bid);

	if(box.checked) {
		box.checked = '';
		image.style.backgroundColor='<?php echo BOX_BACKGROUND_COLOUR; ?>';
	} else {
		box.checked = 'checked';
		image.style.backgroundColor='<?php echo BOX_SELECT_COLOUR; ?>';
		box.focus();
	}
}


//change the checkbox status and the replacement image
function textClick(bid,bgid) {

	if (curbgid != bgid)
	{
		//goto selected bgid	
		bgiddone[bgid] = 0;
		nextTask();
		return;
	}


}



function checkUpdate(bid,bgid) {

	box = document.getElementById('checkBox' + bid);
	image = document.getElementById('checkImage' + bid);

	if(box.checked) {
		image.style.backgroundColor='<?php echo BOX_SELECT_COLOUR; ?>';
		box.focus();
	} else {
		image.style.backgroundColor='<?php echo BOX_BACKGROUND_COLOUR; ?>';
	}


}



function checkEnter(e,bgid,bid){ //e is event object passed from function invocation
	var characterCode //literal character code will be stored in this variable
	var whi = 0;
	var current = 0;
	var next = 0;
	var prev = 0;
	var select = 0;

	if (e.keyCode == 16) return false; //ignore uppercase/shift

	characterCode = e.keyCode; //character code is contained in IE's keyCode property
	whi = e.which;
		//alert(e.which);

	if (whi >= 49 && whi <= 57) //keys 1-9 select appropriate box
	{
		cv = 0;
		for (y in bgidbid[bgid])
		{
			select = bgidbid[bgid][y];
			if (cv == (whi - 49))
			{
				break;
			}
			cv++;
		}
	
		if (bgidtype[bgid] == 1)
		{
			radioChange(select,bgid);
		}
		else if (bgidtype[bgid] == 2)
		{
			checkChange(select,bgid);
		}
	
		return true;
	}

	for (y in bgidbid[bgid])
	{
		if (current != 0)
		{
			next = bgidbid[bgid][y];
			break;
		}
				
		if (bgidbid[bgid][y] == bid)
		{
			current = bid;
		}else
		{
			prev = bgidbid[bgid][y];
		}
	}

	if (next == 0) next = current;
	if (prev == 0) prev = current;

	//alert('next: ' + next + ' current: ' + current + ' prev: ' + prev + ' bgid: ' + bgid + ' ccode: ' + characterCode);

	if(characterCode == 39 || characterCode == 40){ 
		checkFocus(next,bgid);
	}else if (characterCode == 37 || characterCode == 38){
		checkFocus(prev,bgid);	
	}


	return true;
}



function textPress(th,e,bgid,bid){ //e is event object passed from function invocation
	var characterCode //literal character code will be stored in this variable
	var current = 0;
	var next = 0;
	var prev = 0;

	if (e.keyCode == 16) return false; //ignore uppercase/shift
	if (e.keyCode == 13) return false; //ignore uppercase/shift

	characterCode = e.keyCode //character code is contained in IE's keyCode property


	for (y in bgidbid[bgid])
	{
		if (current != 0)
		{
			next = bgidbid[bgid][y];
			break;
		}
				
		if (bgidbid[bgid][y] == bid)
		{
			current = bid;
		}else
		{
			prev = bgidbid[bgid][y];
		}
	}

	if (next == 0) next = current;
	if (prev == 0) prev = current;

	if(characterCode >= 37 && characterCode <= 40){ //if generated character code is equal to ascii 13 (if enter key)
		//
	}
	else if (characterCode == 8){
		focusText(prev);
	}
	else
	{
		focusText(next);
	}

	return true;
}

function focusText(field)
{
	if (document.getElementById('textBox'+field))
	{
    	window.setTimeout(function () {
			document.getElementById('textBox'+field).focus();
			document.getElementById('textBox'+field).select();
		}, 0);
	}
}

function poptastic(url)
{
	newwindow=window.open(url,'name','height=600,width=350,resizable=yes,scrollbars=yes,toolbar=no,status=no');
	if (window.focus) {newwindow.focus()}
}


function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    /* if present, the header is where you move the DIV from:*/
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
    
  } else {
    /* otherwise, move the DIV from anywhere inside the DIV:*/
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;
  }
}



function init() {
	dragElement(document.getElementById("tla"));
	dragElement(document.getElementById("tra"));
	dragElement(document.getElementById("bla"));
	dragElement(document.getElementById("bra"));
	document['onkeydown'] = detectEvent;
	nextTask();
//	focusText(0);

//	for(var i=0; i < inputs.length; i++)
//	{
//		if (inputs[i].checked)
//		{
//			inputs[i].focus();
//		}
//	}

}


window.onload = init;

/* ]]> */
</script>
<style type="text/css">

.mydiv {
    position: absolute;
    z-index: 9;
    background-color: #f1f1f1;
    background-image: url('css/arrow.png');
    text-align: center;
    border: 1px solid #d3d3d3;
}

.mydivheader {
    padding: 10px;
    cursor: move;
    z-index: 10;
    color: black;
}

#topper {
  position : fixed;
  width : 100%;
  height : 5%;
  top : 0;
  right : 0;
  bottom : auto;
  left : 0;
  border-bottom : 2px solid #cccccc;
  overflow : auto;
	text-align:center;
}

#header {
  position : fixed;
  width : 15%;
  height : 95%;
  top : 5%;
  right : 0;
  bottom : auto;
  left : 0;
  border-bottom : 2px solid #cccccc;
  overflow : auto;
}
#content {
  position : fixed;
  top : 5%;
  left : 15%;
  bottom : auto;
  width : 85%;
  height : 100%;
  color : #000000;
  overflow : auto;
}

#note {
  width : 100%;
  height : 200px;
}

#supervisor {
  width : 100%;
  height : 200px;
}

.embeddedobject {
  width:100%;
  height:100%;
}


</style>
</head>
<body>



<?php

$zoom = 1;
if (isset($_GET['zoom'])) $zoom = intval($_GET['zoom']);


print "<div id=\"content\">";

if ($pid == "")
{
	//no more to do:
	print "<p>" . T_("The required fields have been filled") . "</p>";
	print "<div id=\"links\">";
	print "<p><a href=\"" . $_SERVER['PHP_SELF'] . "?complete=complete\" onclick=\"document.getElementById('links').style.visibility='hidden'; document.getElementById('wait').style.visibility='visible';\">" . T_("Submit completed form to database") . "</a></p>";
	print "<p><a href=\"" . $_SERVER['PHP_SELF'] . "?review=review#boxGroup\" onclick=\"document.getElementById('links').style.visibility='hidden'; document.getElementById('wait').style.visibility='visible';\">" . T_("Review all questions again") . "</a></p>";
	print "<p><a href=\"" . $_SERVER['PHP_SELF'] . "?clear=clear#boxGroup\" onclick=\"document.getElementById('links').style.visibility='hidden'; document.getElementById('wait').style.visibility='visible';\">" . T_("Clear all entered data and review again") . "</a></p></div>";

	print "<div id=\"wait\" style=\"visibility: hidden;\">
<p>" . T_("Submitting: Please wait...") . "</p>
</div>";

}
else
{
	
	//show content
	if (empty($_SESSION['pages'][$pid]['fid'])) //if page missing
	{
		print "<div style=\"position:relative;\"><div style=\"width:" . PAGE_WIDTH / (PAGE_WIDTH/DISPLAY_PAGE_WIDTH) . "px; height:" . PAGE_HEIGHT / (PAGE_WIDTH/DISPLAY_PAGE_WIDTH) . "px;\">" . T_("Page is missing from scan") . "</div>";
		$pw =PAGE_WIDTH;
	}
	else
	{
		print "<div style=\"position:relative;\"><img src=\"showpage.php?pid=$pid&amp;fid=$fid\" style=\"width:" . DISPLAY_PAGE_WIDTH . "px;\" alt=\"" . T_("Image of page") . " $pid, " . T_("form") . " $fid\" />";
		$pw = $_SESSION['pages'][$pid]['width'];
		if (empty($pw)) $pw = PAGE_WIDTH;
	}
	bgidtocss(($pw/DISPLAY_PAGE_WIDTH),$fid,$pid);
	print "</div>";
	print "</div>";

	//show list of bgid for this fid
	print "<div id=\"header\">";
	
	print "<p>Q:$qid F:$fid P:$pid</p>";
	print "<p><a href=\"" . $_SERVER['PHP_SELF'] . "?pid=$pid&amp;fid=$fid&amp;centre=centre\">" . T_("Centre Page") . "</a></p>";
	print "<p><a href=\"javascript:void(0)\" onclick=\"allDone();\">" . T_("Accept page") . "</a></p>";
	print "<p><a href=\"javascript:void(0)\" onclick=\"showAlign();\">" . T_("Align page") . "</a></p>";
	print "<p style='display:none' id='acceptalign'><a href=\"javascript:void(0)\" onclick=\"acceptAlign($pid,$fid," . ($pw/DISPLAY_PAGE_WIDTH) . ");\">" . T_("Accept alignment of page") . "</a></p>";

  print "<div id='note'><object class='embeddedobject' id='mainobj' data='pagenote.php?pid=$pid&amp;fid=$fid&amp;vid=$vid' standby='" . T_("Loading panel...") . "' type='application/xhtml+xml'><div>" . T_("Error, try with Firefox") . "</div></object></div>";

  $sql = "SELECT count(*)
          FROM supervisorquestionnaire
          WHERE qid = $qid and vid != $vid";

  $sq = $db->GetOne($sql);

  if ($sq > 0) {
    print "<div id='supervisor'>";
    print "<form method='post' action='?' name='formsuper' id='formsuper'>";
    print "<input type=\"submit\" name=\"supervisor\" value=\"" . T_("Assign to supervisor") . "\"/>";
    print "</form><div>";
  }

  $sql = "SELECT count(*)
          FROM supervisorquestionnaire
          WHERE qid = $qid and vid = $vid";

  $sq = $db->GetOne($sql);

  if ($sq > 0) {
    print "<div id='supervisor'>";
    print "<form method='post' action='?' name='formsuper' id='formsuper'>";
    print "<input type=\"submit\" name=\"supervisorreturn\" value=\"" . T_("Refer back to regular verifier") . "\"/>";
    print "</form><div>";
  }
	
	foreach($_SESSION['boxgroups'] as $key => $val)
	{
		if ($val['pid'] == $pid)
		{
			//if ($bgid == $key)
				print "<strong>{$val['varname']}</strong><br/>";
			//else
			//	print "<a id=\"link$key\" href=\"" . $_SERVER['PHP_SELF'] . "?bgid=$key&amp;fid=$fid#boxGroup\">{$val['varname']}</a><br/>";
		}	
	}
	
print "</div>";

//show list of pid for this fid
	print "<div id=\"topper\">";


	//print_r($_SESSION['pages']);

	$count = 1;	
	foreach($_SESSION['pages'] as $key => $val)
	{
		if ($pid == $key)
			print "<strong>$count</strong>";
		else
			print " <a href=\"" . $_SERVER['PHP_SELF'] . "?pid=$key&amp;fid=$fid#boxGroup\">$count</a> ";
		$count++;

	}
	
print "</div>";


}


?>


</body></html>