File: gmDemographicsWidgets.py

package info (click to toggle)
gnumed-client 0.2.2a-3
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 3,448 kB
  • ctags: 3,620
  • sloc: python: 32,178; sh: 231; makefile: 97
file content (2599 lines) | stat: -rw-r--r-- 90,573 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
"""Widgets dealing with patient demographics."""
#============================================================
# $Source: /sources/gnumed/gnumed/gnumed/client/wxpython/gmDemographicsWidgets.py,v $
# $Id: gmDemographicsWidgets.py,v 1.99 2006/08/10 07:19:05 ncq Exp $
__version__ = "$Revision: 1.99 $"
__author__ = "R.Terry, SJ Tan, I Haywood, Carlos Moro <cfmoro1976@yahoo.es>"
__license__ = 'GPL (details at http://www.gnu.org)'

# standard library
import time, string, sys, os

# 3rd party
import mx.DateTime as mxDT

import wx
import wx.wizard

# GNUmed specific
from Gnumed.wxpython import gmPlugin, gmPhraseWheel, gmGuiHelpers, gmDateTimeInput, gmRegetMixin
from Gnumed.pycommon import  gmGuiBroker,  gmLog, gmDispatcher, gmSignals, gmCfg, gmI18N, gmMatchProvider, gmPG
from Gnumed.business import gmDemographicRecord, gmPerson

# constant defs
_log = gmLog.gmDefLog
_cfg = gmCfg.gmDefCfgFile
_name_gender_map = None

DATE_FORMAT = '%Y-%m-%d'

#============================================================
def disable_identity(identity=None):
	# ask user for assurance
	go_ahead = gmGuiHelpers.gm_show_question (
		_('Are you sure you really, positively want\n'
		  'to disable the following patient ?\n'
		  '\n'
		  ' %s %s %s\n'
		  ' born %s\n'
		) % (
			identity['firstnames'],
			identity['lastnames'],
			identity['gender'],
			identity['dob']
		),
		_('Disabling patient')
	)
	if not go_ahead:
		return True

	# get admin connection
	conn = gmGuiHelpers.get_dbowner_connection (
		procedure = _('Disabling patient')
	)
	# - user cancelled
	if conn is False:
		return True
	# - error
	if conn is None:
		return False

	# now disable patient
	cmd = "update dem.identity set deleted=True where pk=%s"
	success, data = gmPG.run_commit2 (
		link_obj = 'demographics',
		queries = [(cmd, [identity['pk_identity']])]
	)
	if not success:
		err, msg = data
		gmGuiHelpers.gm_show_error (
			_('Cannot disable patient !\n'
			  '\n'
			  ' [%s]'
			) % msg,
			_('Disabling patient')
		)
		return False
	return True
#============================================================
class cGenderSelectionPhraseWheel(gmPhraseWheel.cPhraseWheel):
	"""Let user select a gender.
	"""

	_gender_map = None

	def __init__(self, *args, **kwargs):

		if cGenderSelectionPhraseWheel._gender_map is None:
			cmd = """
			select
				tag,
				l10n_label,
				sort_weight
			from
				dem.v_gender_labels
			order by sort_weight desc"""
			rows, idx = gmPG.run_ro_query('personalia', cmd, True)
			if rows is None:
				raise gmExceptions.gmConstructorError, 'cannot retrieve gender values from database'
			cGenderSelectionPhraseWheel._gender_map = {}
			for gender in rows:
				cGenderSelectionPhraseWheel._gender_map[gender[idx['tag']]] = {
					'data': gender[idx['tag']],
					'label': gender[idx['l10n_label']],
					'weight': gender[idx['sort_weight']]
				}

		mp = gmMatchProvider.cMatchProvider_FixedList(aSeq = cGenderSelectionPhraseWheel._gender_map.values())
		mp.setThresholds(1, 1, 3)

		kwargs['aMatchProvider'] = mp
		kwargs['aDelay'] = 50
		kwargs['selection_only'] = True
		gmPhraseWheel.cPhraseWheel.__init__ (
			self,
			*args,
			**kwargs
		)
#============================================================
# new patient wizard classes
#============================================================
class cBasicPatDetailsPage(wx.wizard.WizardPageSimple):
	"""
	Wizard page for entering patient's basic demographic information
	"""
	
	form_fields = (
			'firstnames', 'lastnames', 'nick', 'dob', 'gender', 'title', 'occupation',
			'address_number', 'zip_code', 'street', 'town', 'state', 'country', 'phone'
	)
	
	def __init__(self, parent, title):
		"""
		Creates a new instance of BasicPatDetailsPage
		@param parent - The parent widget
		@type parent - A wx.Window instance
		@param tile - The title of the page
		@type title - A StringType instance				
		"""
		wx.wizard.WizardPageSimple.__init__(self, parent) #, bitmap = gmGuiHelpers.gm_icon(_('oneperson'))
		self.__title = title
		self.__do_layout()
		self.__register_interests()
	#--------------------------------------------------------
	def __do_layout(self):
		# main panel (required for a correct propagation of validator calls)
		PNL_form = wx.Panel(self, -1)

		# last name
		STT_lastname = wx.StaticText(PNL_form, -1, _('Last name'))
		STT_lastname.SetForegroundColour('red')
		queries = []
		queries.append("select distinct lastnames, lastnames from dem.names where lastnames %(fragment_condition)s limit 25")
		mp = gmMatchProvider.cMatchProvider_SQL2('demographics', queries)
		mp.setThresholds(3, 5, 15)
		self.PRW_lastname = gmPhraseWheel.cPhraseWheel (
			parent = PNL_form,
			id = -1,
			aMatchProvider = mp
		)
		self.PRW_lastname.SetToolTipString(_('Required: lastname (family name)'))

		# first name
		STT_firstname = wx.StaticText(PNL_form, -1, _('First name'))
		STT_firstname.SetForegroundColour('red')
		queries = []
		cmd = """
			(select distinct firstnames, firstnames from dem.names where firstnames %(fragment_condition)s limit 20)
				union
			(select distinct name, name from dem.name_gender_map where name %(fragment_condition)s limit 20)"""
		queries.append(cmd)
		mp = gmMatchProvider.cMatchProvider_SQL2('demographics', queries)
		mp.setThresholds(3, 5, 15)
		self.PRW_firstname = gmPhraseWheel.cPhraseWheel (
			parent = PNL_form,
			id = -1,
			aMatchProvider = mp
		)
		self.PRW_firstname.SetToolTipString(_('Required: surname/given name/first name'))

		# nickname
		STT_nick = wx.StaticText(PNL_form, -1, _('Nick name'))
		queries = []
		cmd = """
			(select distinct preferred, preferred from dem.names where preferred %(fragment_condition)s limit 20)
				union
			(select distinct firstnames, firstnames from dem.names where firstnames %(fragment_condition)s limit 20)"""
		queries.append(cmd)
		mp = gmMatchProvider.cMatchProvider_SQL2('demographics', queries)
		mp.setThresholds(3, 5, 15)
		self.PRW_nick = gmPhraseWheel.cPhraseWheel (
			parent = PNL_form,
			id = -1,
			aMatchProvider = mp
		)
		self.PRW_nick.SetToolTipString(_("nick name, preferred name, call name, warrior name, artist name, alias"))

		# DOB
		STT_dob = wx.StaticText(PNL_form, -1, _('Date of birth'))
		STT_dob.SetForegroundColour('red')
		self.TTC_dob = gmDateTimeInput.cFuzzyTimestampInput (
			parent = PNL_form,
			id = -1
		)
		self.TTC_dob.SetToolTipString(_("required: date of birth, if unknown or aliasing wanted then invent one"))

		# gender
		STT_gender = wx.StaticText(PNL_form, -1, _('Gender'))
		STT_gender.SetForegroundColour('red')
		self.PRW_gender = cGenderSelectionPhraseWheel(parent = PNL_form, id=-1)
		self.PRW_gender.SetToolTipString(_("Required: gender of patient"))

		# title
		STT_title = wx.StaticText(PNL_form, -1, _('Title'))
		queries = []
		queries.append("select distinct title, title from dem.identity where title %(fragment_condition)s")
		mp = gmMatchProvider.cMatchProvider_SQL2('demographics', queries)
		mp.setThresholds(1, 3, 15)
		self.PRW_title = gmPhraseWheel.cPhraseWheel(
			parent = PNL_form,
			id = -1,
			aMatchProvider = mp
		)
		self.PRW_title.SetToolTipString(_("title of patient"))

		# zip code
		STT_zip_code = wx.StaticText(PNL_form, -1, _('Zip code'))
		queries = []
		queries.append("select distinct postcode, postcode from dem.street where postcode %(fragment_condition)s limit 50")
		mp = gmMatchProvider.cMatchProvider_SQL2('demographics', queries)
		mp.setThresholds(3, 5, 15)				
		self.PRW_zip_code = gmPhraseWheel.cPhraseWheel (
			parent = PNL_form,
			id = -1,
			aMatchProvider = mp
		)
		self.PRW_zip_code.SetToolTipString(_("primary/home address: zip code/postcode"))

		# street
		STT_street = wx.StaticText(PNL_form, -1, _('Street'))
		queries = []
		queries.append ("""
		select distinct on (s1,s2) s1, s2 from (
			select * from (
				select street as s1, street as s2, 1 as rank from dem.v_zip2data where street %(fragment_condition)s and zip ilike %%(zip)s
					union
				select name as s1, name as s2, 2 as rank from dem.street where name %(fragment_condition)s
			) as q1 order by rank, s1
		) as q2
		limit 50
		""")
		mp = gmMatchProvider.cMatchProvider_SQL2('demographics', queries)
		mp.setThresholds(3, 5, 15)				
		self.PRW_street = gmPhraseWheel.cPhraseWheel (
			parent = PNL_form,
			id = -1,
			aMatchProvider = mp
		)
		self.PRW_street.set_context(context='zip', val='%')
		self.PRW_street.SetToolTipString(_("primary/home address: name of street"))

		# address number
		STT_address_number = wx.StaticText(PNL_form, -1, _('Number'))
		self.TTC_address_number = wx.TextCtrl(PNL_form, -1)
		self.TTC_address_number.SetToolTipString(_("primary/home address: address number"))

		# town
		STT_town = wx.StaticText(PNL_form, -1, _('Town'))
		queries = []
		queries.append("""
		select distinct on (u1,u2) u1, u2 from (
			select * from (
				select urb as u1, urb as u2, 1 as rank from dem.v_zip2data where urb %(fragment_condition)s and zip ilike %%(zip)s
					union
				select name as u1, name as u2, 2 as rank from dem.urb where name %(fragment_condition)s
			) as t1 order by rank, u1
		) as q2
		limit 50
		""")
		mp = gmMatchProvider.cMatchProvider_SQL2('demographics', queries)
		mp.setThresholds(3, 5, 6)
		self.PRW_town = gmPhraseWheel.cPhraseWheel (
			parent = PNL_form,
			id = -1,
			aMatchProvider = mp
		)
		self.PRW_town.set_context(context='zip', val='%')
		self.PRW_town.SetToolTipString(_("primary/home address: town/village/dwelling/city/etc."))

		# state
		STT_state = wx.StaticText(PNL_form, -1, _('State'))
		queries = []
		queries.append("""
		select distinct on (code, name) code, name from (
			select * from (
					-- context: state name, country, zip
					select
						code_state as code, state as name, 1 as rank
					from dem.v_zip2data
					where
						state %(fragment_condition)s and l10n_country ilike %%(country)s and zip ilike %%(zip)s
				union
					-- context: state name and country
					select
						code as code, name as name, 2 as rank
					from dem.state
					where
						name %(fragment_condition)s and country in (select code from dem.country where name ilike %%(country)s)
				union
					-- context: state code, country, zip
					select
						code_state as code, state as name, 3 as rank
					from dem.v_zip2data
					where
						code_state %(fragment_condition)s and l10n_country ilike %%(country)s and zip ilike %%(zip)s
				union
					-- context: state code, country
					select
						code as code, name as name, 3 as rank
					from dem.state
					where
						code %(fragment_condition)s and country in (select code from dem.country where name ilike %%(country)s)
			) as q2 order by rank, name
		) as q1 limit 50""")
		mp = gmMatchProvider.cMatchProvider_SQL2 ('demographics', queries)
		mp.setThresholds(2, 5, 6)
		self.PRW_state = gmPhraseWheel.cPhraseWheel (
			parent = PNL_form,
			id = -1,
			aMatchProvider = mp,
			selection_only = True
		)
		self.PRW_state.set_context(context='zip', val='%')
		self.PRW_state.set_context(context='country', val='%')
		self.PRW_state.SetToolTipString(_("primary/home address: state"))

		# country
		# FIXME: default in config
		STT_country = wx.StaticText(PNL_form, -1, _('Country'))
		queries = []
		queries.append("""
		select distinct on (code, name) code, name from (
			select * from (
				-- localized to user
				select code_country as code, l10n_country as name, 1 as rank from dem.v_zip2data where l10n_country %(fragment_condition)s and zip ilike %%(zip)s
					union
				select code as code, _(name) as name, 2 as rank from dem.country where _(name) %(fragment_condition)s
					union
				-- non-localized
				select code_country as code, country as name, 3 as rank from dem.v_zip2data where country %(fragment_condition)s and zip ilike %%(zip)s
					union
				select code as code, name as name, 4 as rank from dem.country where name %(fragment_condition)s
			) as q2 order by rank, name
		) as q1 limit 25""")
		mp = gmMatchProvider.cMatchProvider_SQL2('demographics', queries)
		mp.setThresholds(2, 5, 15)
		self.PRW_country = gmPhraseWheel.cPhraseWheel (
			parent = PNL_form,
			id = -1,
			aMatchProvider = mp,
			selection_only = True
		)
		self.PRW_country.set_context(context='zip', val='%')
		self.PRW_country.SetToolTipString(_("primary/home address: country"))

		# phone
		STT_phone = wx.StaticText(PNL_form, -1, _('Phone'))
		self.TTC_phone = wx.TextCtrl(PNL_form, -1)
		self.TTC_phone.SetToolTipString(_("phone number at home"))

		# occupation
		STT_occupation = wx.StaticText(PNL_form, -1, _('Occupation'))
		queries = []
		queries.append("select distinct name, name from dem.occupation where name %(fragment_condition)s")
		mp = gmMatchProvider.cMatchProvider_SQL2('demographics', queries)
		mp.setThresholds(3, 5, 15)		
		self.PRW_occupation = gmPhraseWheel.cPhraseWheel (
			parent = PNL_form,
			id = -1,
			aMatchProvider = mp
		)
		self.PRW_occupation.SetToolTipString(_("primary occupation of the patient"))

		# form main validator
		self.form_DTD = cFormDTD(fields = self.__class__.form_fields)
		PNL_form.SetValidator(cBasicPatDetailsPageValidator(dtd = self.form_DTD))
				
		# layout input widgets
		SZR_input = wx.FlexGridSizer(cols = 2, rows = 15, vgap = 4, hgap = 4)
		SZR_input.AddGrowableCol(1)
		SZR_input.Add(STT_lastname, 0, wx.SHAPED)
		SZR_input.Add(self.PRW_lastname, 1, wx.EXPAND)
		SZR_input.Add(STT_firstname, 0, wx.SHAPED)
		SZR_input.Add(self.PRW_firstname, 1, wx.EXPAND)
		SZR_input.Add(STT_nick, 0, wx.SHAPED)
		SZR_input.Add(self.PRW_nick, 1, wx.EXPAND)
		SZR_input.Add(STT_dob, 0, wx.SHAPED)
		SZR_input.Add(self.TTC_dob, 1, wx.EXPAND)
		SZR_input.Add(STT_gender, 0, wx.SHAPED)
		SZR_input.Add(self.PRW_gender, 1, wx.EXPAND)
		SZR_input.Add(STT_title, 0, wx.SHAPED)
		SZR_input.Add(self.PRW_title, 1, wx.EXPAND)
		SZR_input.Add(STT_zip_code, 0, wx.SHAPED)
		SZR_input.Add(self.PRW_zip_code, 1, wx.EXPAND)
		SZR_input.Add(STT_street, 0, wx.SHAPED)
		SZR_input.Add(self.PRW_street, 1, wx.EXPAND)
		SZR_input.Add(STT_address_number, 0, wx.SHAPED)
		SZR_input.Add(self.TTC_address_number, 1, wx.EXPAND)
		SZR_input.Add(STT_town, 0, wx.SHAPED)
		SZR_input.Add(self.PRW_town, 1, wx.EXPAND)
		SZR_input.Add(STT_state, 0, wx.SHAPED)
		SZR_input.Add(self.PRW_state, 1, wx.EXPAND)
		SZR_input.Add(STT_country, 0, wx.SHAPED)
		SZR_input.Add(self.PRW_country, 1, wx.EXPAND)
		SZR_input.Add(STT_phone, 0, wx.SHAPED)
		SZR_input.Add(self.TTC_phone, 1, wx.EXPAND)
		SZR_input.Add(STT_occupation, 0, wx.SHAPED)
		SZR_input.Add(self.PRW_occupation, 1, wx.EXPAND)

		PNL_form.SetSizerAndFit(SZR_input)

		# layout page
		SZR_main = gmGuiHelpers.makePageTitle(self, self.__title)
		SZR_main.Add(PNL_form, 1, wx.EXPAND)
	#--------------------------------------------------------
	# event handling
	#--------------------------------------------------------
	def __register_interests(self):
		"""
		Configure enabled event signals
		"""
		# custom
		self.PRW_firstname.add_callback_on_lose_focus(self.on_name_set)
		self.PRW_country.add_callback_on_selection(self.on_country_selected)
		self.PRW_zip_code.add_callback_on_lose_focus(self.on_zip_set)
	#--------------------------------------------------------
	def on_country_selected(self, data):
		"""
		Set the states according to entered country.
		"""
		self.PRW_state.set_context(context='country', val=data)
		return True
	#--------------------------------------------------------
	def on_name_set(self):
		"""
		Set the gender according to entered firstname.
		Matches are fetched from existing records in backend.
		"""
		firstname = self.PRW_firstname.GetValue().strip()
		cmd = "select gender from dem.name_gender_map where name ilike %s"
		rows = gmPG.run_ro_query('personalia', cmd, False, firstname)
		if rows is None:
			_log.Log(gmLog.lErr, 'error retrieving gender for [%s]' % firstname)
			return False
		if len(rows) == 0:
			return True
		wx.CallAfter(self.PRW_gender.SetData, rows[0][0])
		return True
	#--------------------------------------------------------
	def on_zip_set(self):
		"""
		Set the street, town, state and country according to entered zip code.
		"""
		zip_code = self.PRW_zip_code.GetValue().strip()
		self.PRW_street.set_context(context='zip', val=zip_code)
		self.PRW_town.set_context(context='zip', val=zip_code)
		self.PRW_state.set_context(context='zip', val=zip_code)
		self.PRW_country.set_context(context='zip', val=zip_code)
		return True				
#============================================================
class cNewPatientWizard(wx.wizard.Wizard):
	"""
	Wizard to create a new patient.

	TODO:
	- write pages for different "themes" of patient creation
	- make it configurable which pages are loaded
	- make available sets of pages that apply to a country
	- make loading of some pages depend upon values in earlier pages, eg
	  when the patient is female and older than 13 include a page about
	  "female" data (number of kids etc)

	FIXME: use: wizard.FindWindowById(wx.ID_FORWARD).Disable()
	"""
	#--------------------------------------------------------
	def __init__(self, parent, title = _('Register new person'), subtitle = _('Basic demographic details') ):
		"""
		Creates a new instance of NewPatientWizard
		@param parent - The parent widget
		@type parent - A wx.Window instance
		"""
		id_wiz = wx.NewId()
		wx.wizard.Wizard.__init__(self, parent, id_wiz, title) #images.getWizTest1Bitmap()
		self.SetExtraStyle(wx.WS_EX_VALIDATE_RECURSIVELY)
		self.__subtitle = subtitle
		self.__do_layout()
	#--------------------------------------------------------
	def RunWizard(self, activate=False):
		"""Create new patient.

		activate, too, if told to do so (and patient successfully created)
		"""
		if not wx.wizard.Wizard.RunWizard(self, self.basic_pat_details):
			return False

		# retrieve DTD and create patient
		ident = create_identity_from_dtd(dtd = self.basic_pat_details.form_DTD)
		update_identity_from_dtd(identity = ident, dtd = self.basic_pat_details.form_DTD)
		link_contacts_from_dtd(identity = ident, dtd = self.basic_pat_details.form_DTD)
		link_occupation_from_dtd(identity = ident, dtd = self.basic_pat_details.form_DTD)

		if activate:
			pat = gmPerson.cPatient(identity = ident)
			gmPerson.gmCurrentPatient(patient = pat)

		return ident
	#--------------------------------------------------------
	# internal helpers
	#--------------------------------------------------------
	def __do_layout(self):
		"""Arrange widgets.
		"""
		# Create the wizard pages
		self.basic_pat_details = cBasicPatDetailsPage(self, self.__subtitle )
		self.FitToPage(self.basic_pat_details)
#============================================================
class cBasicPatDetailsPageValidator(wx.PyValidator):
	"""
	This validator is used to ensure that the user has entered all
	the required conditional values in the page (eg., to properly
	create an address, all the related fields must be filled).
	"""
	#--------------------------------------------------------
	def __init__(self, dtd):
		"""
		Validator initialization.
		@param dtd The object containing the data model.
		@type dtd A cFormDTD instance
		"""
		# initialize parent class
		wx.PyValidator.__init__(self)
		
		# validator's storage object
		self.form_DTD = dtd
	#--------------------------------------------------------
	def Clone(self):
		"""
		Standard cloner.
		Note that every validator must implement the Clone() method.
		"""
		return cBasicPatDetailsPageValidator(dtd = self.form_DTD)		# FIXME: probably need new instance of DTD ?
	#--------------------------------------------------------
	def Validate(self, parent = None):
		"""
		Validate the contents of the given text control.
		"""
		_pnl_form = self.GetWindow().GetParent()

		error = False

		# name fields
		if _pnl_form.PRW_lastname.GetValue().strip() == '':
			error = True
			wx.CallAfter(gmGuiHelpers.gm_beep_statustext, _('Must enter lastname.'))
			_pnl_form.PRW_lastname.SetBackgroundColour('pink')
			_pnl_form.PRW_lastname.Refresh()
		else:
			_pnl_form.PRW_lastname.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
			_pnl_form.PRW_lastname.Refresh()

		if _pnl_form.PRW_firstname.GetValue().strip() == '':
			error = True
			wx.CallAfter(gmGuiHelpers.gm_beep_statustext, _('Must enter first name.'))
			_pnl_form.PRW_firstname.SetBackgroundColour('pink')
			_pnl_form.PRW_firstname.Refresh()
		else:
			_pnl_form.PRW_firstname.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
			_pnl_form.PRW_firstname.Refresh()

		# gender
		if _pnl_form.PRW_gender.GetData() is None:
			error = True
			wx.CallAfter(gmGuiHelpers.gm_beep_statustext, _('Must select gender.'))
			_pnl_form.PRW_gender.SetBackgroundColour('pink')
			_pnl_form.PRW_gender.Refresh()
		else:
			_pnl_form.PRW_gender.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
			_pnl_form.PRW_gender.Refresh()

		# dob validation
		if not _pnl_form.TTC_dob.is_valid_timestamp():
			error = True
			msg = _('Cannot parse <%s> into proper timestamp.') % _pnl_form.TTC_dob.GetValue()
			wx.CallAfter(gmGuiHelpers.gm_beep_statustext, msg)
			_pnl_form.TTC_dob.SetBackgroundColour('pink')
			_pnl_form.TTC_dob.Refresh()
		else:
			_pnl_form.TTC_dob.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
			_pnl_form.TTC_dob.Refresh()
						
		# address		
		address_fields = (
			_pnl_form.TTC_address_number,
			_pnl_form.PRW_zip_code,
			_pnl_form.PRW_street,
			_pnl_form.PRW_town,
			_pnl_form.PRW_state,
			_pnl_form.PRW_country
		)
		is_any_field_filled = False
		for field in address_fields:
			if field.GetValue().strip() != '':
				is_any_field_filled = True
				field.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
				field.Refresh()
				continue
			if is_any_field_filled:
				error = True
				msg = _('To properly create an address, all the related fields must be filled in.')
				gmGuiHelpers.gm_show_error(msg, _('Required fields'), gmLog.lErr)
				field.SetBackgroundColour('pink')
				field.SetFocus()
				field.Refresh()

		return (not error)
	#--------------------------------------------------------
	def TransferToWindow(self):
		"""
		Transfer data from validator to window.
		The default implementation returns False, indicating that an error
		occurred.  We simply return True, as we don't do any data transfer.
		"""
		_pnl_form = self.GetWindow().GetParent()
		# fill in controls with values from self.form_DTD
		_pnl_form.PRW_gender.SetValue(self.form_DTD['gender'])
		_pnl_form.TTC_dob.SetValue(self.form_DTD['dob'])
		_pnl_form.PRW_lastname.SetValue(self.form_DTD['lastnames'])
		_pnl_form.PRW_firstname.SetValue(self.form_DTD['firstnames'])
		_pnl_form.PRW_title.SetValue(self.form_DTD['title'])
		_pnl_form.PRW_nick.SetValue(self.form_DTD['nick'])
		_pnl_form.PRW_occupation.SetValue(self.form_DTD['occupation'])
		_pnl_form.TTC_address_number.SetValue(self.form_DTD['address_number'])
		_pnl_form.PRW_street.SetValue(self.form_DTD['street'])
		_pnl_form.PRW_zip_code.SetValue(self.form_DTD['zip_code'])
		_pnl_form.PRW_town.SetValue(self.form_DTD['town'])
		_pnl_form.PRW_state.SetValue(self.form_DTD['state'])
		_pnl_form.PRW_country.SetValue(self.form_DTD['country'])
		_pnl_form.TTC_phone.SetValue(self.form_DTD['phone'])
		return True # Prevent wxDialog from complaining.	
	#--------------------------------------------------------
	def TransferFromWindow(self):
		"""
		Transfer data from window to validator.
		The default implementation returns False, indicating that an error
		occurred.  We simply return True, as we don't do any data transfer.
		"""
		# FIXME: should be called automatically
		if not self.GetWindow().GetParent().Validate():
			return False
		try:
			_pnl_form = self.GetWindow().GetParent()
			# fill in self.form_DTD with values from controls
			self.form_DTD['gender'] = _pnl_form.PRW_gender.GetData()
			self.form_DTD['dob'] = _pnl_form.TTC_dob.GetData()
			self.form_DTD['lastnames'] = _pnl_form.PRW_lastname.GetValue()
			self.form_DTD['firstnames'] = _pnl_form.PRW_firstname.GetValue()
			self.form_DTD['title'] = _pnl_form.PRW_title.GetValue()
			self.form_DTD['nick'] = _pnl_form.PRW_nick.GetValue()
			self.form_DTD['occupation'] = _pnl_form.PRW_occupation.GetValue()
			self.form_DTD['address_number'] = _pnl_form.TTC_address_number.GetValue()
			self.form_DTD['street'] = _pnl_form.PRW_street.GetValue()
			self.form_DTD['zip_code'] = _pnl_form.PRW_zip_code.GetValue()
			self.form_DTD['town'] = _pnl_form.PRW_town.GetValue()
			self.form_DTD['state'] = _pnl_form.PRW_state.GetData()
			self.form_DTD['country'] = _pnl_form.PRW_country.GetData()
			self.form_DTD['phone'] = _pnl_form.TTC_phone.GetValue()
		except:
			return False
		return True
#============================================================
class cFormDTD:
	"""
	Simple Data Transfer Dictionary class to make easy the trasfer of
	data between the form (view) and the business logic.

	Maybe later consider turning this into a standard dict by
	{}.fromkeys([key, key, ...], default) when it becomes clear that
	we really don't need the added potential of a full-fledged class.
	"""
	def __init__(self, fields):		
		"""
		Initialize the DTD with the supplied field names.
		@param fields The names of the fields.
		@type fields A TupleType instance.
		"""
		self.data = {}		
		for a_field in fields:
			self.data[a_field] = ''
		
	def __getitem__(self, attribute):
		"""
		Retrieve the value of the given attribute (key)
		@param attribute The attribute (key) to retrieve its value for.
		@type attribute a StringType instance.
		"""
		if not self.data[attribute]:
			return ''
		return self.data[attribute]

	def __setitem__(self, attribute, value):
		"""
		Set the value of a given attribute (key).
		@param attribute The attribute (key) to set its value for.
		@type attribute a StringType instance.		
		@param avaluee The value to set.
		@rtpe attribute a StringType instance.
		"""
		self.data[attribute] = value
	
	def __str__(self):
		"""
		Print string representation of the DTD object.
		"""
		return str(self.data)
#============================================================
# patient demographics editing classes
#============================================================
class cPatEditionNotebook(wx.Notebook):
	"""Notebook style widget displaying patient edition pages:

		-Identity
		-Contacts (addresses, phone numbers, etc)
		-Occupations
		...
	0.1: Basic set of fields (those in new patient wizard) structured in
	a notebook widget.
	Post 0.1: Improve the notebook patient edition widget supporting
	aditional (insurance, relatives, etc), complex and multiple elements
	(differet types of addresses, phones, etc).
	"""
	
	# fields in every page/form/validator
	ident_form_fields = (
			'firstnames', 'lastnames', 'nick', 'dob', 'gender', 'title'
	)
	contacts_form_fields = (
			'address_number', 'zip_code', 'street', 'town', 'state', 'country', 'phone'
	)
	occupations_form_fields = (
			'occupation',
	)
	#--------------------------------------------------------
	def __init__(self, parent, id, pos=wx.DefaultPosition, size=wx.DefaultSize):

		wx.Notebook.__init__ (
			self,
			parent = parent,
			id = id,
			pos = pos,
			size = size,
			style = wx.NB_TOP | wx.NB_MULTILINE | wx.NO_BORDER | wx.VSCROLL | wx.HSCROLL,
			name = self.__class__.__name__
		)
		self.SetExtraStyle(wx.WS_EX_VALIDATE_RECURSIVELY)

		self.ident_form_DTD = cFormDTD(fields = self.__class__.ident_form_fields)
		self.contacts_form_DTD = cFormDTD(fields = self.__class__.contacts_form_fields)		
		self.occupations_form_DTD = cFormDTD(fields = self.__class__.occupations_form_fields)
		# genders
		genders, idx = gmPerson.get_gender_list()
		self.__genders = []
		for gender in genders:
			self.__genders.append ({
				'data': gender[idx['tag']],
				'label': gender[idx['l10n_label']],
				'weight': gender[idx['sort_weight']]
			})
		self.__pat = gmPerson.gmCurrentPatient()
		self.__do_layout()
		self.__register_interests()
		self.SetSelection(0)
	#--------------------------------------------------------
	# public API
	#--------------------------------------------------------
	def save(self):
		for page_idx in range(self.GetPageCount()):
			page = self.GetPage(page_idx)
			page.save()
	#--------------------------------------------------------
	def refresh(self):
		"""
		Populate fields in pages with data from model.
		"""
		
		identity = self.__pat.get_identity()
		# refresh identity reference in pages
		for page_idx in range(self.GetPageCount()):
			page = self.GetPage(page_idx)
			page.set_identity(identity)

		# business class -> identity DTD
		txt = identity['gender']
		for gender in self.__genders:
			if gender['data'] == txt:
				txt = gender['label']
				break
		self.ident_form_DTD['gender'] = txt
#xxxxxxxxxxxxxxxxx
#check source of identity['dob'] == string
#xxxxxxxxxxxxxxxxx
		self.ident_form_DTD['dob'] = identity['dob']
		txt = ''
		if not identity['title'] is None:
			txt = identity['title']
		self.ident_form_DTD['title'] = txt
		
		# names
		active_name = identity.get_active_name()		
		self.ident_form_DTD['lastnames'] = active_name['last']
		self.ident_form_DTD['firstnames'] = active_name['first']		
		txt = ''
		if not active_name['preferred'] is None:
			txt = active_name['preferred']
		self.ident_form_DTD['nick'] = txt		

		# business class -> contacts DTD
		addresses = identity['addresses']
		if len(addresses) > 0:
			last_idx = len(addresses)-1
			self.contacts_form_DTD['address_number'] = addresses[last_idx]['number']
			self.contacts_form_DTD['street'] = addresses[last_idx]['street']
			self.contacts_form_DTD['zip_code'] = addresses[last_idx]['postcode']
			self.contacts_form_DTD['town'] = addresses[last_idx]['urb']
			self.contacts_form_DTD['state'] = addresses[last_idx]['state']
			self.contacts_form_DTD['country'] = addresses[last_idx]['country']
		else:
			self.contacts_form_DTD['address_number'] = ''
			self.contacts_form_DTD['street'] = ''
			self.contacts_form_DTD['zip_code'] = ''
			self.contacts_form_DTD['town'] = ''
			self.contacts_form_DTD['state'] = ''
			self.contacts_form_DTD['country'] = ''
		comms = identity['comms']
		if len(comms) > 0:
			for a_comm in comms:
				if a_comm['type'] == 'homephone':
					self.contacts_form_DTD['phone'] = a_comm['url']
					break
		else:
			self.contacts_form_DTD['phone'] = ''

		# business class -> occupations DTD
		occupations = identity['occupations']
		if len(occupations) > 0:
			last_idx = len(occupations)-1
			self.occupations_form_DTD['occupation'] = occupations[last_idx]['occupation']
		else:
			self.occupations_form_DTD['occupation'] = ''

		# Recursively calls TransferDataToWindow in notebook
		# children, thanks to wx.WS_EX_VALIDATE_RECURSIVELY
		self.TransferDataToWindow()

		return True
	#--------------------------------------------------------
	# internal API
	#--------------------------------------------------------
	def __do_layout(self):
		"""
		Build patient edition notebook pages.
		"""
		ident = self.__pat.get_identity()
		# identity page
		new_page = cPatIdentityPanel (
			parent = self,
			id = -1,
			dtd = self.ident_form_DTD,
			ident = ident
		)
		self.AddPage (
			page = new_page,
			text = _('Identity'),
			select = True
		)
		# contacts page
		label = _('Contacts')		
		new_page = cPatContactsPanel (
			parent = self,
			id = -1,
			dtd = self.contacts_form_DTD,
			ident = ident
		)
		self.AddPage (
			page = new_page,
			text = label,
			select = False
		)
		# occupations page
		label = _('Occupations')
		new_page = cPatOccupationsPanel (
			parent = self,
			id = -1,
			dtd = self.occupations_form_DTD,
			ident = ident
		)
		self.AddPage (
			page = new_page,
			text = label,
			select = False
		)
	#--------------------------------------------------------
	# event handling
	#--------------------------------------------------------
	def __register_interests(self):
		"""
		Configure enabled event signals
		"""
		# client internal signals
		gmDispatcher.connect(signal=gmSignals.pre_patient_selection(), receiver=self._on_pre_patient_selection)
		gmDispatcher.connect(signal=gmSignals.application_closing(), receiver=self._on_application_closing)
	#--------------------------------------------------------
	def _on_pre_patient_selection(self):
		"""Another patient is about to be activated."""
#		print "[%s]: another patient is about to become active" % self.__class__.__name__
#		print "need code to ask user about unsaved patient details"
		pass
	#--------------------------------------------------------
	def _on_application_closing(self):
#		print "[%s]: the application is closing down" % self.__class__.__name__
#		print "need code to  ask user about unsaved patient details"
		pass
#============================================================
class cPatIdentityPanel(wx.Panel):
	"""
	Page containing patient identity edition fields.
	"""
	def __init__(self, parent, id, dtd=None, ident=None):
		"""
		Creates a new instance of cPatIdentityPanel
		@param parent - The parent widget
		@type parent - A wx.Window instance
		@param id - The widget id
		@type id - An integer
		@param dtd The object containing the data model.
		@type dtd A cFormDTD instance
		"""
		wx.Panel.__init__(self, parent, id)
		self.__dtd = dtd
		self.__ident = ident
		genders, idx = gmPerson.get_gender_list()
		self.__gender_map = {}
		for gender in genders:
			self.__gender_map[gender[idx['tag']]] = {
				'data': gender[idx['tag']],
				'label': gender[idx['l10n_label']],
				'weight': gender[idx['sort_weight']]
			}
		self.__do_layout()
		self.__register_interests()
	#--------------------------------------------------------
	def __do_layout(self):

		# FIXME: main panel, required for a correct propagation of validator calls.
		# If this panel doesn't exists and the validator is set
		# direclty to self, calling self.transferDataFromWindow
		# just returns true without the method in validator being
		# called. It seems that works for the children of self.
		PNL_form = wx.Panel(self, -1)

		# last name
		STT_lastname = wx.StaticText(PNL_form, -1, _('Last name'))
		STT_lastname.SetForegroundColour('red')
		queries = []
		queries.append("select distinct lastnames, lastnames from dem.names where lastnames %(fragment_condition)s")
		mp = gmMatchProvider.cMatchProvider_SQL2('demographics', queries)
		mp.setThresholds(3, 5, 15)
		self.PRW_lastname = gmPhraseWheel.cPhraseWheel (
			parent = PNL_form,
			id = -1,
			aMatchProvider = mp,
			validator = gmGuiHelpers.cTextWidgetValidator (
				message = _('Required: lastname (family name)'),
				non_empty = True,
				only_digits = False
			)
		)
		self.PRW_lastname.SetToolTipString(_("Required: lastname (family name)"))

		# first name
		STT_firstname = wx.StaticText(PNL_form, -1, _('First name'))
		STT_firstname.SetForegroundColour('red')
		queries = []
		cmd = """
			select distinct firstnames, firstnames from dem.names where firstnames %(fragment_condition)s
				union
			select distinct name, name from dem.name_gender_map where name %(fragment_condition)s"""
		queries.append(cmd)
		mp = gmMatchProvider.cMatchProvider_SQL2('demographics', queries=queries)
		mp.setThresholds(3, 5, 15)
		self.PRW_firstname = gmPhraseWheel.cPhraseWheel (
			parent = PNL_form,
			id = -1,
			aMatchProvider = mp,
			validator = gmGuiHelpers.cTextWidgetValidator (
				message = _('Required: surname/given name/first name'),
				non_empty = True,
				only_digits = False
			)
		)
		self.PRW_firstname.SetToolTipString(_("Required: surname/given name/first name"))

		# nickname
		STT_nick = wx.StaticText(PNL_form, -1, _('Nick name'))
		queries = []
		cmd = """
			select distinct preferred, preferred from dem.names where preferred %(fragment_condition)s
				union
			select distinct firstnames, firstnames from dem.names where firstnames %(fragment_condition)s"""
		queries.append(cmd)
		mp = gmMatchProvider.cMatchProvider_SQL2('demographics', queries=queries)
		mp.setThresholds(3, 5, 15)
		self.PRW_nick = gmPhraseWheel.cPhraseWheel (
			parent = PNL_form,
			id = -1,
			aMatchProvider = mp
		)
		self.PRW_nick.SetToolTipString(_("nick name, preferred name, call name, warrior name, artist name, alias"))

		# DOB
		STT_dob = wx.StaticText(PNL_form, -1, _('Date of birth'))
		STT_dob.SetForegroundColour('red')
		self.TTC_dob = gmDateTimeInput.cFuzzyTimestampInput(parent = PNL_form, id = -1)
		self.TTC_dob.SetToolTipString(_("required: date of birth, if unknown or aliasing wanted then invent one (Y-m-d)"))

		# gender
		STT_gender = wx.StaticText(PNL_form, -1, _('Gender'))
		STT_gender.SetForegroundColour('red')
		self.PRW_gender = cGenderSelectionPhraseWheel(parent = PNL_form, id=-1)
		self.PRW_gender.SetToolTipString(_("Required: gender of patient"))

		# title
		STT_title = wx.StaticText(PNL_form, -1, _('Title'))
		queries = []
		queries.append("select distinct title, title from dem.identity where title %(fragment_condition)s")
		mp = gmMatchProvider.cMatchProvider_SQL2('demographics', queries=queries)
		mp.setThresholds(1, 3, 15)
		self.PRW_title = gmPhraseWheel.cPhraseWheel (
			parent = PNL_form,
			id = -1,
			aMatchProvider = mp
		)
		self.PRW_title.SetToolTipString(_("title of patient"))

		# Set validator for identity form
		PNL_form.SetValidator(cPatIdentityPanelValidator(dtd = self.__dtd))
		
		# layout input widgets
		SZR_input = wx.FlexGridSizer(cols = 2, rows = 15, vgap = 4, hgap = 4)
		SZR_input.AddGrowableCol(1)
		SZR_input.Add(STT_lastname, 0, wx.SHAPED)
		SZR_input.Add(self.PRW_lastname, 1, wx.EXPAND)
		SZR_input.Add(STT_firstname, 0, wx.SHAPED)
		SZR_input.Add(self.PRW_firstname, 1, wx.EXPAND)
		SZR_input.Add(STT_nick, 0, wx.SHAPED)
		SZR_input.Add(self.PRW_nick, 1, wx.EXPAND)
		SZR_input.Add(STT_dob, 0, wx.SHAPED)
		SZR_input.Add(self.TTC_dob, 1, wx.EXPAND)
		SZR_input.Add(STT_gender, 0, wx.SHAPED)
		SZR_input.Add(self.PRW_gender, 1, wx.EXPAND)
		SZR_input.Add(STT_title, 0, wx.SHAPED)
		SZR_input.Add(self.PRW_title, 1, wx.EXPAND)
		PNL_form.SetSizerAndFit(SZR_input)
		# layout page
		SZR_main = wx.BoxSizer(wx.VERTICAL)
		SZR_main.Add(PNL_form, 1, wx.EXPAND)
		self.SetSizer(SZR_main)
	#--------------------------------------------------------
	# event handling
	#--------------------------------------------------------
	def __register_interests(self):
		"""
		Configure enabled event signals
		"""
		# custom
		self.PRW_firstname.add_callback_on_lose_focus(self.on_name_set)
	#--------------------------------------------------------
	def on_name_set(self):
		"""
		Set the gender according to entered firstname.
		Matches are fetched from existing records in backend.
		"""
		firstname = self.PRW_firstname.GetValue().strip()
		cmd = "select gender from dem.name_gender_map where name ilike %s"
		rows = gmPG.run_ro_query('personalia', cmd, False, firstname)
		if rows is None:
			_log.Log(gmLog.lErr, 'error retrieving gender for [%s]' % firstname)
			return False
		if len(rows) == 0:
			return True
		wx.CallAfter(self.PRW_gender.SetData, rows[0][0])
		return True
	#--------------------------------------------------------
	# public API
	#--------------------------------------------------------		
	def set_identity(self, identity):
		self.__ident = identity
		
	def save(self):
		msg = _("Data in Identity section can't be saved.\nPlease, correct any invalid input.")
		if not self.Validate():
			gmGuiHelpers.gm_show_error(msg, _('Identity invalid input'), gmLog.lErr)
			return False
		if not self.TransferDataFromWindow():
			gmGuiHelpers.gm_show_error(msg, _('Identity invalid input'), gmLog.lErr)					
			return False
		if not update_identity_from_dtd(identity = self.__ident, dtd = self.__dtd):
			msg = _("An error happened while saving Identity section.\nPlease, refresh and check all the data.")
			gmGuiHelpers.gm_show_error(msg, _('Identity saving error'), gmLog.lErr)
			return False
		return True
#============================================================		
class cPatIdentityPanelValidator(wx.PyValidator):
	"""
	This validator is used to ensure that the user has entered all
	the required conditional values in patient identity page.
	"""
	#--------------------------------------------------------
	def __init__(self, dtd):
		"""
		Validator initialization.
		@param dtd The object containing the data model.
		@type dtd A cFormDTD instance
		"""
		wx.PyValidator.__init__(self)
		self.__dtd = dtd
	#--------------------------------------------------------
	def Clone(self):
		"""
		Standard cloner.
		Note that every validator must implement the Clone() method.
		"""
		return cPatIdentityPanelValidator(dtd = self.__dtd)		# FIXME: probably need new instance of DTD ?
	#--------------------------------------------------------
	def TransferToWindow(self):
		"""
		Transfer data from validator to window.
		The default implementation returns False, indicating that an error
		occurred.  We simply return True, as we don't do any data transfer.
		"""
		try:
			pageCtrl = self.GetWindow().GetParent()
			pageCtrl.PRW_gender.SetValue(self.__dtd['gender'])
			pageCtrl.TTC_dob.SetValue(self.__dtd['dob'].Format(DATE_FORMAT))
			pageCtrl.PRW_lastname.SetValue(self.__dtd['lastnames'])
			pageCtrl.PRW_firstname.SetValue(self.__dtd['firstnames'])
			pageCtrl.PRW_title.SetValue(self.__dtd['title'])
			pageCtrl.PRW_nick.SetValue(self.__dtd['nick'])
		except:
			_log.LogException('cannot transfer dtd to form', sys.exc_info(), verbose=0)
			return False
		return True
	#--------------------------------------------------------
	def Validate(self, parent = None):
		"""Validate the contents of the given text control.
		"""
		pageCtrl = self.GetWindow().GetParent()
		# dob validation
		if not pageCtrl.TTC_dob.is_valid_timestamp():
			msg = _('Cannot parse <%s> into proper timestamp.')
			gmGuiHelpers.gm_show_error(msg, _('Invalid date'), gmLog.lErr)
			pageCtrl.TTC_dob.SetBackgroundColour('pink')
			pageCtrl.TTC_dob.Refresh()
			pageCtrl.TTC_dob.SetFocus()
			return False
		pageCtrl.TTC_dob.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
		pageCtrl.TTC_dob.Refresh()

		return True
	#--------------------------------------------------------
	def TransferFromWindow(self):
		"""
		Transfer data from window to validator.
		The default implementation returns False, indicating that an error
		occurred.  We simply return True, as we don't do any data transfer.
		"""
		try:
			pageCtrl = self.GetWindow().GetParent()
			# fill in self.__dtd with values from controls
			self.__dtd['gender'] = pageCtrl.PRW_gender.GetData()
			self.__dtd['dob'] = pageCtrl.TTC_dob.GetData()
			self.__dtd['lastnames'] = pageCtrl.PRW_lastname.GetValue()
			self.__dtd['firstnames'] = pageCtrl.PRW_firstname.GetValue()
			self.__dtd['title'] = pageCtrl.PRW_title.GetValue()
			self.__dtd['nick'] = pageCtrl.PRW_nick.GetValue()
		except:
			return False
		return True
#============================================================
class cPatContactsPanel(wx.Panel):
	"""
	Page containing patient contacts edition fields.
	"""
		
	def __init__(self, parent, id, dtd=None, ident=None):
		"""
		Creates a new instance of BasicPatDetailsPanel
		@param parent - The parent widget
		@type parent - A wx.Window instance
		@param id - The widget id
		@type id - An integer
		@param dtd The object containing the data model.
		@type dtd A cFormDTD instance
		"""
		wx.Panel.__init__(self, parent, id)		
		self.__dtd = dtd
		self.__ident = ident
		if os.environ.has_key ("LANG"):
			self.locale = os.environ['LANG']
		else:
			self.locale = 'unknown'
		self.__do_layout()
		self.__register_interests()
	#--------------------------------------------------------
	def __do_number (self):
		
		# address number
		STT_address_number = wx.StaticText(self.PNL_form, -1, _('Number'))
		self.TTC_address_number = wx.TextCtrl(self.PNL_form, -1)
		self.TTC_address_number.SetToolTipString(_("primary/home address: address number"))
		self.SZR_input.Add(STT_address_number, 0, wx.SHAPED)
		self.SZR_input.Add(self.TTC_address_number, 1, wx.EXPAND)

	def __do_zip (self):
			
		# zip code
		STT_zip_code = wx.StaticText(self.PNL_form, -1, _('Zip code'))
		queries = []
		queries.append("select distinct postcode, postcode from dem.street where postcode %(fragment_condition)s")
		mp = gmMatchProvider.cMatchProvider_SQL2('demographics', queries=queries)
		mp.setThresholds(3, 5, 15)				
		self.PRW_zip_code = gmPhraseWheel.cPhraseWheel (
			parent = self.PNL_form,
			id = -1,
			aMatchProvider = mp
		)
		self.PRW_zip_code.SetToolTipString(_("primary/home address: zip code/postcode"))
		self.SZR_input.Add(STT_zip_code, 0, wx.SHAPED)
		self.SZR_input.Add(self.PRW_zip_code, 1, wx.EXPAND)

	def __do_street (self):
				
		# street
		STT_street = wx.StaticText(self.PNL_form, -1, _('Street'))
		queries = []
		queries.append("""
		select distinct on (s1,s2) s1, s2 from (
			select * from (
				select street as s1, street as s2, 1 as rank from dem.v_zip2data where street %(fragment_condition)s and zip ilike %%(zip)s
					union
				select name as s1, name as s2, 2 as rank from dem.street where name %(fragment_condition)s
			) as q1 order by rank, s1
		) as q2
		""")
		mp = gmMatchProvider.cMatchProvider_SQL2('demographics', queries=queries)
		mp.setThresholds(3, 5, 15)				
		self.PRW_street = gmPhraseWheel.cPhraseWheel (
			parent = self.PNL_form,
			id = -1,
			aMatchProvider = mp
		)
		self.PRW_street.set_context(context='zip', val='%')
		self.PRW_street.SetToolTipString(_("primary/home address: name of street"))
		self.SZR_input.Add(STT_street, 0, wx.SHAPED)
		self.SZR_input.Add(self.PRW_street, 1, wx.EXPAND)


	def __do_town (self):
		
		# town
		STT_town = wx.StaticText(self.PNL_form, -1, _('Town'))
		queries = []
		queries.append("""
		select distinct on (u1,u2) u1, u2 from (
			select * from (		
				select urb as u1, urb as u2, 1 as rank from dem.v_zip2data where urb %(fragment_condition)s and zip ilike %%(zip)s
					union
				select name as u1, name as u2, 2 as rank from dem.urb where name %(fragment_condition)s
			) as t1 order by rank, u1
		) as q2
		""")
		mp = gmMatchProvider.cMatchProvider_SQL2('demographics', queries=queries)
		mp.setThresholds(3, 5, 6)
		self.PRW_town = gmPhraseWheel.cPhraseWheel (
			parent = self.PNL_form,
			id = -1,
			aMatchProvider = mp
		)
		self.PRW_town.set_context(context='zip', val='%')
		self.PRW_town.SetToolTipString(_("primary/home address: town/village/dwelling/city/etc."))
		
		self.SZR_input.Add(STT_town, 0, wx.SHAPED)
		self.SZR_input.Add(self.PRW_town, 1, wx.EXPAND)

	def __do_state_country (self):
		# state
		# FIXME: default in config
		STT_state = wx.StaticText(self.PNL_form, -1, _('State'))
		STT_state.SetForegroundColour('red')
		queries = []
		queries.append("""
		select distinct on (code,name) code, name from (
			select * from (				
				select code_state as code, state as name, 1 as rank from dem.v_zip2data where state %(fragment_condition)s and l10n_country ilike %%(country)s and zip ilike %%(zip)s
					union
				select
					code as code, name as name, 2 as rank
				from dem.state
				where
					name %(fragment_condition)s and country in (select code from dem.country where name ilike %%(country)s)
			) as q1 order by rank, name
		) as q2				
		""")
		mp = gmMatchProvider.cMatchProvider_SQL2 ('demographics', queries)
		mp.setThresholds(3, 5, 6)
		self.PRW_state = gmPhraseWheel.cPhraseWheel (
			parent = self.PNL_form,
			id = -1,
			aMatchProvider = mp,
			selection_only = True
		)
		self.PRW_state.set_context(context='zip', val='%')
		self.PRW_state.set_context(context='country', val='%')
		self.PRW_state.SetToolTipString(_("primary/home address: state"))

		# country
		# FIXME: default in config
		STT_country = wx.StaticText(self.PNL_form, -1, _('Country'))
		queries = []
		queries.append("""
		select distinct on (code,name) code, name from (
			select * from (						
				select code_country as code, l10n_country as name, 1 as rank from dem.v_zip2data where l10n_country %(fragment_condition)s and zip ilike %%(zip)s
					union
				select code as code, _(name) as name, 2 as rank from dem.country where _(name) %(fragment_condition)s
			) as q1 order by rank, name
		) as q2								
		""")
		mp = gmMatchProvider.cMatchProvider_SQL2('demographics', queries)
		mp.setThresholds(2, 5, 15)
		self.PRW_country = gmPhraseWheel.cPhraseWheel (
			parent = self.PNL_form,
			id = -1,
			aMatchProvider = mp,
			selection_only = True
		)
		self.PRW_country.set_context(context='zip', val='%')
		self.PRW_country.SetToolTipString(_("primary/home address: country"))
		self.SZR_input.Add(STT_state, 0, wx.SHAPED)
		self.SZR_input.Add(self.PRW_state, 1, wx.EXPAND)
		self.SZR_input.Add(STT_country, 0, wx.SHAPED)
		self.SZR_input.Add(self.PRW_country, 1, wx.EXPAND)

	def __do_phones (self):
		
		# phone
		STT_phone = wx.StaticText(self.PNL_form, -1, _('Phone'))
		self.TTC_phone = wx.TextCtrl(self.PNL_form, -1)
		self.TTC_phone.SetToolTipString(_("phone number at home"))
		self.SZR_input.Add(STT_phone, 0, wx.SHAPED)
		self.SZR_input.Add(self.TTC_phone, 1, wx.EXPAND)

	def __do_layout(self):
		# FIXME: main panel, required for a correct propagation of validator calls.
		# If this panel doesn't exists and the validator is set
		# direclty to self, calling self.transferDataFromWindow
		# just returns true without the method in validator being
		# called. It seems that works for the children of self.

		self.PNL_form = wx.Panel(self, -1)
		# layout input widgets
		self.SZR_input = wx.FlexGridSizer(cols = 2, rows = 15, vgap = 4, hgap = 4)
		self.SZR_input.AddGrowableCol(1)
		if self.locale[:5] == 'en_AU':
			self.__do_number ()
			self.__do_street ()
			self.__do_town ()
			self.__do_zip ()
			self.__do_state_country ()
			self.__do_phones ()
		else:
			self.__do_zip ()
			self.__do_street ()
			self.__do_number ()
			self.__do_town ()
			self.__do_state_country ()
			self.__do_phones ()
		# Set validator for identity form
		self.PNL_form.SetValidator(cPatContactsPanelValidator(dtd = self.__dtd))
		
		self.PNL_form.SetSizerAndFit(self.SZR_input)
		
		# layout page
		SZR_main = wx.BoxSizer(wx.VERTICAL)
		SZR_main.Add(self.PNL_form, 1, wx.EXPAND)
		self.SetSizer(SZR_main)
	#--------------------------------------------------------
	# event handling
	#--------------------------------------------------------
	def __register_interests(self):
		"""
		Configure enabled event signals
		"""
		# custom
		if self.locale[:5] == 'en_AU':
			self.PRW_town.add_callback_on_selection (self.on_town_set)
		else:
			self.PRW_country.add_callback_on_selection(self.on_country_selected)
			self.PRW_zip_code.add_callback_on_lose_focus(self.on_zip_set)
	#--------------------------------------------------------
	def on_country_selected(self, data):
		"""
		Set the states according to entered country.
		"""
		if data is None:
			data = '%'
		self.PRW_state.set_context(context='country', val=data)
		return True
	#--------------------------------------------------------
	def on_zip_set(self):
		"""
		Set the street, town, state and country according to entered zip code.
		"""
		zip_code = self.PRW_zip_code.GetValue()
		self.PRW_street.set_context(context='zip', val=zip_code)
		self.PRW_town.set_context(context='zip', val=zip_code)
		self.PRW_state.set_context(context='zip', val=zip_code)
		self.PRW_country.set_context(context='zip', val=zip_code)
		return True
	#--------------------------------------------------------
	def on_town_set (self, data):
		"""
		Set postcode, country and state in accordance with the town
		"""
		zip, state_id, state, country_id, country = gmDemographicRecord.get_town_data (self.PRW_town.GetValue ())
		if zip:
			self.PRW_state.SetValue (state, state_id)
			self.PRW_zip_code.SetValue (zip)
			self.PRW_country.SetValue (country, country_id)
			self.TTC_phone.SetFocus ()
	#--------------------------------------------------------
	# public API
	#--------------------------------------------------------			
	def set_identity(self, identity):
		self.__ident = identity
			
	def save(self):
		msg = _("Data in Contacts section can't be saved.\nPlease, correct any invalid input.")
		if not self.Validate():
			gmGuiHelpers.gm_show_error(msg, _('Contacts invalid input'), gmLog.lErr)
			return False
		if not self.TransferDataFromWindow():
			gmGuiHelpers.gm_show_error(msg, _('Contacts invalid input'), gmLog.lErr)			
			return False
		if not link_contacts_from_dtd(identity = self.__ident, dtd = self.__dtd):
			msg = _("An error happened while saving Contacts section.\nPlease, refresh and check all the data.")
			gmGuiHelpers.gm_show_error(msg, _('Contacts saving error'), gmLog.lErr)
			return False
		return True		
#============================================================		
class cPatContactsPanelValidator(wx.PyValidator):
	"""
	This validator is used to ensure that the user has entered all
	the required conditional values in patietn contacts page.
	"""
	#--------------------------------------------------------
	def __init__(self, dtd):
		"""
		Validator initialization.
		@param dtd The object containing the data model.
		@type dtd A cFormDTD instance
		"""
		# initialize parent class
		wx.PyValidator.__init__(self)
		
		# validator's storage object
		self.form_DTD = dtd
	#--------------------------------------------------------
	def Clone(self):
		"""
		Standard cloner.
		Note that every validator must implement the Clone() method.
		"""
		return cPatContactsPanelValidator(dtd = self.form_DTD)		# FIXME: probably need new instance of DTD ?
	#--------------------------------------------------------
	def Validate(self, parent = None):
		"""
		Validate the contents of the given text control.
		"""
		pageCtrl = self.GetWindow().GetParent()
		address_fields = (
			pageCtrl.TTC_address_number,
			pageCtrl.PRW_zip_code,
			pageCtrl.PRW_street,
			pageCtrl.PRW_town,
			pageCtrl.PRW_state,
			pageCtrl.PRW_country
		)
		# validate required fields
		is_any_field_filled = False
		for field in address_fields:
			if len(field.GetValue()) > 0:
				is_any_field_filled = True
				field.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
				field.Refresh()
				continue
			if is_any_field_filled:
				msg = _('To properly create an address, all the related fields must be filled in.')
				gmGuiHelpers.gm_show_error(msg, _('Required fields'), gmLog.lErr)
				field.SetBackgroundColour('pink')
				field.SetFocus()
				field.Refresh()
				return False
		return True
	#--------------------------------------------------------
	def TransferToWindow(self):
		"""
		Transfer data from validator to window.
		The default implementation returns False, indicating that an error
		occurred.  We simply return True, as we don't do any data transfer.
		"""
		pageCtrl = self.GetWindow().GetParent()
		# fill in controls with values from self.form_DTD
		pageCtrl.TTC_address_number.SetValue(self.form_DTD['address_number'])
		pageCtrl.PRW_street.SetValue(self.form_DTD['street'])
		pageCtrl.PRW_zip_code.SetValue(self.form_DTD['zip_code'])
		pageCtrl.PRW_town.SetValue(self.form_DTD['town'])
		pageCtrl.PRW_country.SetValue(self.form_DTD['country'])
		pageCtrl.PRW_state.SetValue(self.form_DTD['state'])
		pageCtrl.TTC_phone.SetValue(self.form_DTD['phone'])
		return True # Prevent wxDialog from complaining.	
	#--------------------------------------------------------
	def TransferFromWindow(self):
		"""
		Transfer data from window to validator.
		The default implementation returns False, indicating that an error
		occurred.  We simply return True, as we don't do any data transfer.
		"""
		try:
			pageCtrl = self.GetWindow().GetParent()
			# fill in self.form_DTD with values from controls
			self.form_DTD['address_number'] = pageCtrl.TTC_address_number.GetValue()
			self.form_DTD['street'] = pageCtrl.PRW_street.GetValue()
			self.form_DTD['zip_code'] = pageCtrl.PRW_zip_code.GetValue()
			self.form_DTD['town'] = pageCtrl.PRW_town.GetValue()
			if not pageCtrl.PRW_state.GetData() is None:
				self.form_DTD['state'] = pageCtrl.PRW_state.GetData()
			if not pageCtrl.PRW_country.GetData() is None:
				self.form_DTD['country'] = pageCtrl.PRW_country.GetData()
			self.form_DTD['phone'] = pageCtrl.TTC_phone.GetValue()
		except:
			return False
		return True
#============================================================
class cPatOccupationsPanel(wx.Panel):
	"""
	Page containing patient occupations edition fields.
	"""
	def __init__(self, parent, id, dtd=None, ident=None):
		"""
		Creates a new instance of BasicPatDetailsPage
		@param parent - The parent widget
		@type parent - A wx.Window instance
		@param id - The widget id
		@type id - An integer
		@param dtd The object containing the data model.
		@type dtd A cFormDTD instance
		"""
		wx.Panel.__init__(self, parent, id)
		self.__dtd = dtd
		self.__ident = ident
		self.__do_layout()
	#--------------------------------------------------------
	def __do_layout(self):
		# FIXME: main panel, required for a correct propagation of validator calls.
		# If this panel doesn't exists and the validator is set
		# direclty to self, calling self.transferDataFromWindow
		# just returns true without the method in validator being
		# called. It seems that works for the children of self.
		PNL_form = wx.Panel(self, -1)		
		# occupation
		STT_occupation = wx.StaticText(PNL_form, -1, _('Occupation'))
		queries = []
		queries.append("select distinct name, name from dem.occupation where name %(fragment_condition)s")
		mp = gmMatchProvider.cMatchProvider_SQL2('demographics', queries=queries)
		mp.setThresholds(3, 5, 15)		
		self.PRW_occupation = gmPhraseWheel.cPhraseWheel (
			parent = PNL_form,
			id = -1,
			aMatchProvider = mp
		)
		self.PRW_occupation.SetToolTipString(_("primary occupation of the patient"))

		# Set validator for identity form
		PNL_form.SetValidator(cPatOccupationsPanelValidator(dtd = self.__dtd))

		# layout input widgets
		SZR_input = wx.FlexGridSizer(cols = 2, rows = 15, vgap = 4, hgap = 4)
		SZR_input.AddGrowableCol(1)				
		SZR_input.Add(STT_occupation, 0, wx.SHAPED)
		SZR_input.Add(self.PRW_occupation, 1, wx.EXPAND)
		PNL_form.SetSizerAndFit(SZR_input)
		
		# layout page
		SZR_main = wx.BoxSizer(wx.VERTICAL)
		SZR_main.Add(PNL_form, 1, wx.EXPAND)
		self.SetSizer(SZR_main)				
	#--------------------------------------------------------
	def set_identity(self, identity):
		self.__ident = identity
			
	def save(self):
		msg = _("Data in Occupations section can't be saved.\nPlease, correct any invalid input.")
		if not self.Validate():
			gmGuiHelpers.gm_show_error(msg, _('Occupations invalid input'), gmLog.lErr)			
			return False		
		if not self.TransferDataFromWindow():
			gmGuiHelpers.gm_show_error(msg, _('Occupations invalid input'), gmLog.lErr)			
			return False
		if not link_occupation_from_dtd(identity = self.__ident, dtd = self.__dtd):
			msg = _("An error happened while saving Occupations section.\nPlease, refresh and check all the data.")
			gmGuiHelpers.gm_show_error(msg, _('Occupations saving error'), gmLog.lErr)
			return False
		return True		
#============================================================		
class cPatOccupationsPanelValidator(wx.PyValidator):
	"""
	This validator is used to ensure that the user has entered all
	the required conditional values in patient occupations page.
	"""
	#--------------------------------------------------------
	def __init__(self, dtd):
		"""
		Validator initialization.
		@param dtd The object containing the data model.
		@type dtd A cFormDTD instance
		"""
		wx.PyValidator.__init__(self)
		self.form_DTD = dtd
	#--------------------------------------------------------
	def Clone(self):
		"""
		Standard cloner.
		Note that every validator must implement the Clone() method.
		"""
		return cPatOccupationsPanelValidator(dtd = self.form_DTD)		# FIXME: probably need new instance of DTD ?
	#--------------------------------------------------------
	def Validate(self, parent = None):
		"""Validate the contents of the given text control.
		"""
		return True
	#--------------------------------------------------------
	def TransferToWindow(self):
		"""
		Transfer data from validator to window.
		The default implementation returns False, indicating that an error
		occurred.  We simply return True, as we don't do any data transfer.
		"""
		pageCtrl = self.GetWindow().GetParent()
		# fill in controls with values from self.form_DTD		
		pageCtrl.PRW_occupation.SetValue(self.form_DTD['occupation'])
		return True # Prevent wxDialog from complaining.	
	#--------------------------------------------------------
	def TransferFromWindow(self):
		"""
		Transfer data from window to validator.
		The default implementation returns False, indicating that an error
		occurred.  We simply return True, as we don't do any data transfer.
		"""
		try:
			pageCtrl = self.GetWindow().GetParent()
			# fill in self.form_DTD with values from controls
			self.form_DTD['occupation'] = pageCtrl.PRW_occupation.GetValue()
		except:
			return False
		return True
#============================================================
class cNotebookedPatEditionPanel(wx.Panel, gmRegetMixin.cRegetOnPaintMixin):
	"""
	Notebook based patient edition panel.
	Composed of: notebooked patient details; restore and save buttons
	"""
	#--------------------------------------------------------
	def __init__(self, parent, id):
		"""
		Contructs a new instance of patient edition panel

		@param parent: Wx parent widget
		@param id: Wx widget id
		"""
		# Call parents constructors
		wx.Panel.__init__ (
			self,
			parent = parent,
			id = id,
			pos = wx.DefaultPosition,
			size = wx.DefaultSize,
			style = wx.NO_BORDER
		)
		gmRegetMixin.cRegetOnPaintMixin.__init__(self)
		self.__pat = gmPerson.gmCurrentPatient()
		# ui construction and event handling set up
		self.__do_layout()
		self.__register_interests()
	#--------------------------------------------------------
	# public API
	#--------------------------------------------------------
	#--------------------------------------------------------
	# internal helpers
	#--------------------------------------------------------
	def __do_layout(self):
		"""
		Arrange widgets.
		"""

		# - patient edition notebook
		self.__patient_notebook = cPatEditionNotebook(self, -1)
		# - buttons
		self.__BTN_restore = wx.Button(self, -1, _('&Restore'))
		self.__BTN_restore.SetToolTipString(_('restore fields with current values from backend'))

		self.__BTN_save = wx.Button(self, -1, _('&Save'))
		self.__BTN_save.SetToolTipString(_('save patient information'))

		# - arrange
		szr_btns = wx.BoxSizer(wx.HORIZONTAL)
		szr_btns.Add(self.__BTN_restore, 0, wx.SHAPED)
		szr_btns.Add(self.__BTN_save, 0, wx.SHAPED)

		szr_main = wx.BoxSizer(wx.VERTICAL)
		szr_main.Add(self.__patient_notebook, 1, wx.EXPAND)
		szr_main.Add(szr_btns)
		self.SetSizerAndFit(szr_main)
	#--------------------------------------------------------
	# event handling
	#--------------------------------------------------------
	def __register_interests(self):
		"""Configure enabled event signals
		"""
		# wxPython events
		wx.EVT_BUTTON(self.__BTN_save, self.__BTN_save.GetId(), self._on_save)
		wx.EVT_BUTTON(self.__BTN_restore, self.__BTN_restore.GetId(), self._on_restore)
		# internal signals
		gmDispatcher.connect(signal=gmSignals.post_patient_selection(), receiver=self._on_post_patient_selection)
	#--------------------------------------------------------
	def _on_post_patient_selection(self):
		"""Patient changed."""
		self._schedule_data_reget()
	#--------------------------------------------------------
	def _on_save(self, event):
		"""Save data to backend and close editor.
		"""		
		# FIXME 0.1: Refresh values from backend rather than from the
		# original version of the DTD, so data integrity
		# can be assured. Currenlty, pat.get_identity() is
		# returning its version before save_payload().
		# FIXME post 0.1: internal signal
		if not self.__patient_notebook.save():
			#self.__patient_notebook.refresh()
			return False

		#self.__patient_notebook.refresh()
		return True
	#--------------------------------------------------------
	def _on_restore(self, event):
		"""
		Restore patient edition form with values originally
		fetched from backed, prior to any modification by
		the user.
		"""
		self.__patient_notebook.refresh()
		return True
	#--------------------------------------------------------
	# reget mixin API
	#--------------------------------------------------------
	def _populate_with_data(self):
		"""
		Populate fields in pages with data from model.
		"""
		if self.__patient_notebook.refresh():
			return True
		return False
#============================================================				
def create_identity_from_dtd(dtd=None):
	"""
	Register a new patient, given the data supplied in the 
	Data Transfer Dictionary object.

	@param basic_details_DTD Data Transfer Dictionary encapsulating all the
	supplied data.
	@type basic_details_DTD A cFormDTD instance.
	"""
	new_identity = gmPerson.create_identity (
		gender = dtd['gender'],
		dob = dtd['dob'].timestamp,
		lastnames = capitalize_first(dtd['lastnames']),
		firstnames = capitalize_first(dtd['firstnames'])
	)
	if new_identity is None:
		_log.Log(gmLog.lErr, 'cannot create identity from %s' % str(dtd))
		return None
	_log.Log(gmLog.lData, 'identity created: %s' % new_identity)
	
	return new_identity
#============================================================
def update_identity_from_dtd(identity, dtd=None):
	"""
	Update patient details with data supplied by
	Data Transfer Dictionary object.

	@param basic_details_DTD Data Transfer Dictionary encapsulating all the
	supplied data.
	@type basic_details_DTD A cFormDTD instance.
	"""
	# identity
	if identity['gender'] != dtd['gender']:
		identity['gender'] = dtd['gender']
	if identity['dob'] != dtd['dob'].timestamp:
		identity['dob'] = dtd['dob'].timestamp
	if len(dtd['title']) > 0 and identity['title'] != capitalize_first(dtd['title']):
		identity['title'] = capitalize_first(dtd['title'])
	# FIXME: error checking
	# FIXME: we need a trigger to update the values of the
	# view, identity['keys'], eg. lastnames and firstnames
	# are not refreshed.
	identity.save_payload()
	# names
	# FIXME: proper handling of "active"
	if identity['firstnames'] != capitalize_first(dtd['firstnames']) or identity['lastnames'] != capitalize_first(dtd['lastnames']):
		identity.add_name(firstnames = capitalize_first(dtd['firstnames']), lastnames = capitalize_first(dtd['lastnames']), active = True, nickname = None)
	# nickname
	if len(dtd['nick']) > 0 and identity['preferred'] != capitalize_first(dtd['nick']):
		identity.set_nickname(nickname = capitalize_first(dtd['nick']))

	return True
#============================================================				
def link_contacts_from_dtd(identity, dtd=None):
	"""
	Update patient details with data supplied by
	Data Transfer Dictionary object.

	@param basic_details_DTD Data Transfer Dictionary encapsulating all the
	supplied data.
	@type basic_details_DTD A cFormDTD instance.
	"""

	# current addresses in backend
	addresses = identity['addresses']
	last_idx = -1
	if len(addresses) > 0:
		last_idx = len(addresses) - 1

	# form addresses
	input_number = dtd['address_number']
	input_street = capitalize_first(dtd['street'])
	input_postcode = dtd['zip_code']
	input_urb = capitalize_first(dtd['town'])
	input_state = dtd['state']
	input_country = dtd['country']
	if len(input_number) > 0 and len(input_street) > 0 and len(input_postcode) > 0 and len (input_state) > 0 and \
	 len(input_country) > 0 and len(input_urb) > 0 and (last_idx == -1 or (input_number != addresses[last_idx]['number'] or input_street != addresses[last_idx]['street'] or
	 input_postcode != addresses[last_idx]['postcode'] or input_urb  != addresses[last_idx]['urb'] or
	 input_state != addresses[last_idx]['state_code'] or input_country != addresses[last_idx]['country_code'])):
		identity.link_address (
			number = input_number,
			street = input_street,
			postcode = input_postcode,
			urb = input_urb,
			state = input_state,
			country = input_country
		)

	input_phone = dtd['phone']
	if len(input_phone) > 0:
		identity.link_communication (
			comm_medium = 'homephone',
			url = input_phone,
			is_confidential = False
		)

	# FIXME: error checking
	identity.save_payload()
	return True
#============================================================				
def link_occupation_from_dtd(identity, dtd=None):
	"""
	Update patient details with data supplied by
	Data Transfer Dictionary object.

	@param basic_details_DTD Data Transfer Dictionary encapsulating all the
	supplied data.
	@type basic_details_DTD A cFormDTD instance.
	"""

	occupations = identity['occupations']
	last_idx = -1
	if len(occupations) > 0:
		last_idx = len(occupations) -1
	input_occupation = dtd['occupation']
	if len(input_occupation) > 0 and (last_idx == -1 or occupations[last_idx]['occupation'] !=input_occupation):
		identity.link_occupation(occupation = input_occupation)
	return True	
#============================================================
def get_name_gender_map():
	"""
	Build from backend a cached dictionary of pairs 'firstname' : gender_tag
	"""	
	global _name_gender_map
	if _name_gender_map is None:
		#cmd = "select lower(name), gender from dem.name_gender_map"
		cmd = "select name, gender from dem.name_gender_map"
		rows = gmPG.run_ro_query('personalia', cmd, False)
		if rows is None:
			_log.Log(gmLog.lPanic, 'cannot retrieve name-gender map from database')
			return {}
		_name_gender_map = {}
		for row in rows:
			_name_gender_map[row[0].lower()] = row[1]
	return _name_gender_map
#============================================================
def capitalize_first(txt):
	txt_lst = txt.split()
	if len(txt_lst) > 0:
		txt_lst[0] = txt_lst[0].capitalize()
		txt = ' '.join(txt_lst)
	return txt
#============================================================
class TestWizardPanel(wx.Panel):   
	"""
	Utility class to test the new patient wizard.
	"""
	#--------------------------------------------------------
	def __init__(self, parent, id):
		"""
		Create a new instance of TestPanel.
		@param parent The parent widget
		@type parent A wx.Window instance
		"""
		wx.Panel.__init__(self, parent, id)
		wizard = cNewPatientWizard(self)
		print wizard.RunWizard()
#============================================================
if __name__ == "__main__":
	
	try:
		
		# obtain patient
		patient = gmPerson.ask_for_patient()
		if patient is None:
			print "No patient. Exiting gracefully..."
			sys.exit(0)
		gmPerson.set_active_patient(patient=patient)
	
		a = cFormDTD(fields = cBasicPatDetailsPage.form_fields)
		
		app1 = wx.PyWidgetTester(size = (800, 600))
		app1.SetWidget(cNotebookedPatEditionPanel, -1)
		#app1.SetWidget(TestWizardPanel, -1)
		app1.MainLoop()
	
	except StandardError:
		_log.LogException("unhandled exception caught !", sys.exc_info(), 1)
		# but re-raise them
		raise
	
#	app2 = wx.PyWidgetTester(size = (800, 600))
#	app2.SetWidget(DemographicDetailWindow, -1)
#	app2.MainLoop()
#============================================================
# $Log: gmDemographicsWidgets.py,v $
# Revision 1.99  2006/08/10 07:19:05  ncq
# - remove import of gmPatientHolder
#
# Revision 1.98  2006/08/01 22:03:18  ncq
# - cleanup
# - add disable_identity()
#
# Revision 1.97  2006/07/21 21:34:04  ncq
# - proper header/subheader for new *person* wizard (not *patient*)
#
# Revision 1.96  2006/07/19 20:29:50  ncq
# - import cleanup
#
# Revision 1.95  2006/07/04 14:12:48  ncq
# - add some phrasewheel sanity LIMITs
# - use gender phrasewheel in pat modify, too
#
# Revision 1.94  2006/06/28 22:15:01  ncq
# - make cGenderSelectionPhraseWheel self-sufficient and use it, too
#
# Revision 1.93  2006/06/28 14:09:17  ncq
# - more cleanup
# - add cGenderSelectionPhraseWheel() and start using it
#
# Revision 1.92  2006/06/20 10:04:40  ncq
# - removed reams of crufty code
#
# Revision 1.91  2006/06/20 09:42:42  ncq
# - cTextObjectValidator -> cTextWidgetValidator
# - add custom invalid message to text widget validator
# - variable renaming, cleanup
# - fix demographics validation
#
# Revision 1.90  2006/06/15 15:37:55  ncq
# - properly handle DOB in new-patient wizard
#
# Revision 1.89  2006/06/12 18:31:31  ncq
# - must create *patient* not person from new patient wizard
#   if to be activated as patient :-)
#
# Revision 1.88  2006/06/09 14:40:24  ncq
# - use fuzzy.timestamp for create_identity()
#
# Revision 1.87  2006/06/05 21:33:03  ncq
# - Sebastian is too good at finding bugs, so fix them:
#   - proper queries for new-patient wizard phrasewheels
#   - properly validate timestamps
#
# Revision 1.86  2006/06/04 22:23:03  ncq
# - consistently use l10n_country
#
# Revision 1.85  2006/06/04 21:38:49  ncq
# - make state red as it's mandatory
#
# Revision 1.84  2006/06/04 21:31:44  ncq
# - allow characters in phone URL
#
# Revision 1.83  2006/06/04 21:16:27  ncq
# - fix missing dem. prefixes
#
# Revision 1.82  2006/05/28 20:49:44  ncq
# - gmDateInput -> cFuzzyTimestampInput
#
# Revision 1.81  2006/05/15 13:35:59  ncq
# - signal cleanup:
#   - activating_patient -> pre_patient_selection
#   - patient_selected -> post_patient_selection
#
# Revision 1.80  2006/05/14 21:44:22  ncq
# - add get_workplace() to gmPerson.gmCurrentProvider and make use thereof
# - remove use of gmWhoAmI.py
#
# Revision 1.79  2006/05/12 12:18:11  ncq
# - whoami -> whereami cleanup
# - use gmCurrentProvider()
#
# Revision 1.78  2006/05/04 09:49:20  ncq
# - get_clinical_record() -> get_emr()
# - adjust to changes in set_active_patient()
# - need explicit set_active_patient() after ask_for_patient() if wanted
#
# Revision 1.77  2006/01/18 14:14:39  sjtan
#
# make reusable
#
# Revision 1.76  2006/01/10 14:22:24  sjtan
#
# movement to schema dem
#
# Revision 1.75  2006/01/09 10:46:18  ncq
# - yet more schema quals
#
# Revision 1.74  2006/01/07 17:52:38  ncq
# - several schema qualifications
#
# Revision 1.73  2005/10/19 09:12:40  ncq
# - cleanup
#
# Revision 1.72  2005/10/09 08:10:22  ihaywood
# ok, re-order the address widgets "the hard way" so tab-traversal works correctly.
#
# minor bugfixes so saving address actually works now
#
# Revision 1.71  2005/10/09 02:19:40  ihaywood
# the address widget now has the appropriate widget order and behaviour for australia
# when os.environ["LANG"] == 'en_AU' (is their a more graceful way of doing this?)
#
# Remember our postcodes work very differently.
#
# Revision 1.70  2005/09/28 21:27:30  ncq
# - a lot of wx2.6-ification
#
# Revision 1.69  2005/09/28 19:47:01  ncq
# - runs until login dialog
#
# Revision 1.68  2005/09/28 15:57:48  ncq
# - a whole bunch of wx.Foo -> wx.Foo
#
# Revision 1.67  2005/09/27 20:44:58  ncq
# - wx.wx* -> wx.*
#
# Revision 1.66  2005/09/26 18:01:50  ncq
# - use proper way to import wx26 vs wx2.4
# - note: THIS WILL BREAK RUNNING THE CLIENT IN SOME PLACES
# - time for fixup
#
# Revision 1.65  2005/09/25 17:30:58  ncq
# - revert back to wx2.4 style import awaiting "proper" wx2.6 importing
#
# Revision 1.64  2005/09/25 01:00:47  ihaywood
# bugfixes
#
# remember 2.6 uses "import wx" not "from wxPython import wx"
# removed not null constraint on clin_encounter.rfe as has no value on instantiation
# client doesn't try to set clin_encounter.description as it doesn't exist anymore
#
# Revision 1.63  2005/09/24 09:17:27  ncq
# - some wx2.6 compatibility fixes
#
# Revision 1.62  2005/09/12 15:09:00  ncq
# - make first tab display first in demographics editor
#
# Revision 1.61  2005/09/04 07:29:53  ncq
# - allow phrasewheeling states by abbreviation in new-patient wizard
#
# Revision 1.60  2005/08/14 15:36:54  ncq
# - fix phrasewheel queries for country matching
#
# Revision 1.59  2005/08/08 08:08:35  ncq
# - cleanup
#
# Revision 1.58  2005/07/31 14:48:44  ncq
# - catch exceptions in TransferToWindow
#
# Revision 1.57  2005/07/24 18:54:18  ncq
# - cleanup
#
# Revision 1.56  2005/07/04 11:26:50  ncq
# - re-enable auto-setting gender from firstname, and speed it up, too
#
# Revision 1.55  2005/07/02 18:20:22  ncq
# - allow English input of country as well, regardless of locale
#
# Revision 1.54  2005/06/29 15:03:32  ncq
# - some cleanup
#
# Revision 1.53  2005/06/28 14:38:21  cfmoro
# Integration fixes
#
# Revision 1.52  2005/06/28 14:12:55  cfmoro
# Integration in space fixes
#
# Revision 1.51  2005/06/28 13:11:05  cfmoro
# Fixed bug: when updating patient details the dob was converted from date to str type
#
# Revision 1.50  2005/06/14 19:51:27  cfmoro
# auto zip in patient wizard and minor cleanups
#
# Revision 1.49  2005/06/14 00:34:14  cfmoro
# Matcher provider queries revisited
#
# Revision 1.48  2005/06/13 01:18:24  cfmoro
# Improved input system support by zip, country
#
# Revision 1.47  2005/06/12 22:12:35  ncq
# - prepare for staged (constrained) queries in demographics
#
# Revision 1.46  2005/06/10 23:22:43  ncq
# - SQL2 match provider now requires query *list*
#
# Revision 1.45  2005/06/09 01:56:41  cfmoro
# Initial code on zip -> (auto) address
#
# Revision 1.44  2005/06/09 00:26:07  cfmoro
# PhraseWheels in patient editor. Tons of cleanups and validator fixes
#
# Revision 1.43  2005/06/08 22:03:02  cfmoro
# Restored phrasewheel gender in wizard
#
# Revision 1.42  2005/06/08 01:25:42  cfmoro
# PRW in wizards state and country. Validator fixes
#
# Revision 1.41  2005/06/04 10:17:51  ncq
# - cleanup, cSmartCombo, some comments
#
# Revision 1.40  2005/06/03 15:50:38  cfmoro
# State and country combos y patient edition
#
# Revision 1.39  2005/06/03 13:37:45  cfmoro
# States and country combo selection. SmartCombo revamped. Passing country and state codes instead of names
#
# Revision 1.38  2005/06/03 00:56:19  cfmoro
# Validate dob in patient wizard
#
# Revision 1.37  2005/06/03 00:37:33  cfmoro
# Validate dob in patient identity page
#
# Revision 1.36  2005/06/03 00:01:41  cfmoro
# Key fixes in new patient wizard
#
# Revision 1.35  2005/06/02 23:49:21  cfmoro
# Gender use SmartCombo, several fixes
#
# Revision 1.34  2005/06/02 23:26:41  cfmoro
# Name auto-selection in new patient wizard
#
# Revision 1.33  2005/06/02 12:17:25  cfmoro
# Auto select gender according to firstname
#
# Revision 1.32  2005/05/28 12:18:01  cfmoro
# Capitalize name, street, etc
#
# Revision 1.31  2005/05/28 12:00:53  cfmoro
# Trigger FIXME to reflect changes in v_basic_person
#
# Revision 1.30  2005/05/28 11:45:19  cfmoro
# Retrieve names from identity cache, so refreshing will be reflected
#
# Revision 1.29  2005/05/25 23:03:02  cfmoro
# Minor fixes
#
# Revision 1.28  2005/05/24 19:57:14  ncq
# - cleanup
# - make cNotebookedPatEditionPanel a gmRegetMixin child instead of cPatEditionNotebook
#
# Revision 1.27  2005/05/23 12:01:08  cfmoro
# Create/update comms
#
# Revision 1.26  2005/05/23 11:16:18  cfmoro
# More cleanups and test functional fixes
#
# Revision 1.25  2005/05/23 09:20:37  cfmoro
# More cleaning up
#
# Revision 1.24  2005/05/22 22:12:06  ncq
# - cleaning up patient edition notebook
#
# Revision 1.23  2005/05/19 16:06:50  ncq
# - just silly cleanup, as usual
#
# Revision 1.22  2005/05/19 15:25:53  cfmoro
# Initial logic to update patient details. Needs fixing.
#
# Revision 1.21  2005/05/17 15:09:28  cfmoro
# Reloading values from backend in repopulate to properly reflect patient activated
#
# Revision 1.20  2005/05/17 14:56:02  cfmoro
# Restore values from model to window action function
#
# Revision 1.19  2005/05/17 14:41:36  cfmoro
# Notebooked patient editor initial code
#
# Revision 1.18  2005/05/17 08:04:28  ncq
# - some cleanup
#
# Revision 1.17  2005/05/14 14:56:41  ncq
# - add Carlos' DTD code
# - numerous fixes/robustification
# move occupation down based on user feedback
#
# Revision 1.16  2005/05/05 06:25:56  ncq
# - cleanup, remove _() in log statements
# - re-ordering in new patient wizard due to user feedback
# - add <activate> to RunWizard(): if true activate patient after creation
#
# Revision 1.15  2005/04/30 20:31:03  ncq
# - first-/lastname were switched around when saving identity into backend
#
# Revision 1.14  2005/04/28 19:21:18  cfmoro
# zip code streamlining
#
# Revision 1.13  2005/04/28 16:58:45  cfmoro
# Removed fixme, was dued to log buffer
#
# Revision 1.12  2005/04/28 16:24:47  cfmoro
# Remove last references to town zip code
#
# Revision 1.11  2005/04/28 16:21:17  cfmoro
# Leave town zip code out and street zip code optional as in schema
#
# Revision 1.10  2005/04/25 21:22:17  ncq
# - some cleanup
# - make cNewPatientWizard inherit directly from wxWizard as it should IMO
#
# Revision 1.9  2005/04/25 16:59:11  cfmoro
# Implemented patient creation. Added conditional validator
#
# Revision 1.8  2005/04/25 08:29:24  ncq
# - combobox items must be strings
#
# Revision 1.7  2005/04/23 06:34:11  cfmoro
# Added address number and street zip code missing fields
#
# Revision 1.6  2005/04/18 19:19:54  ncq
# - wrong field order in some match providers
#
# Revision 1.5  2005/04/14 18:26:19  ncq
# - turn gender input into phrase wheel with fixed list
# - some cleanup
#
# Revision 1.4  2005/04/14 08:53:56  ncq
# - cIdentity moved
# - improved tooltips and phrasewheel thresholds
#
# Revision 1.3  2005/04/12 18:49:04  cfmoro
# Added missing fields and matcher providers
#
# Revision 1.2  2005/04/12 16:18:00  ncq
# - match firstnames against name_gender_map, too
#
# Revision 1.1  2005/04/11 18:09:55  ncq
# - offers demographic widgets
#
# Revision 1.62  2005/04/11 18:03:32  ncq
# - attach some match providers to first new-patient wizard page
#
# Revision 1.61  2005/04/10 12:09:17  cfmoro
# GUI implementation of the first-basic (wizard) page for patient details input
#
# Revision 1.60  2005/03/20 17:49:45  ncq
# - improve split window handling, cleanup
#
# Revision 1.59  2005/03/06 09:21:08  ihaywood
# stole a couple of icons from Richard's demo code
#
# Revision 1.58  2005/03/06 08:17:02  ihaywood
# forms: back to the old way, with support for LaTeX tables
#
# business objects now support generic linked tables, demographics
# uses them to the same functionality as before (loading, no saving)
# They may have no use outside of demographics, but saves much code already.
#
# Revision 1.57  2005/02/22 10:21:33  ihaywood
# new patient
#
# Revision 1.56  2005/02/20 10:45:49  sjtan
#
# kwargs syntax error.
#
# Revision 1.55  2005/02/20 10:15:16  ihaywood
# some tidying up
#
# Revision 1.54  2005/02/20 09:46:08  ihaywood
# demographics module with load a patient with no exceptions
#
# Revision 1.53  2005/02/18 11:16:41  ihaywood
# new demographics UI code won't crash the whole client now ;-)
# still needs much work
# RichardSpace working
#
# Revision 1.52  2005/02/03 20:19:16  ncq
# - get_demographic_record() -> get_identity()
#
# Revision 1.51  2005/02/01 10:16:07  ihaywood
# refactoring of gmDemographicRecord and follow-on changes as discussed.
#
# gmTopPanel moves to gmHorstSpace
# gmRichardSpace added -- example code at present, haven't even run it myself
# (waiting on some icon .pngs from Richard)
#
# Revision 1.50  2005/01/31 10:37:26  ncq
# - gmPatient.py -> gmPerson.py
#
# Revision 1.49  2004/12/18 13:45:51  sjtan
#
# removed timer.
#
# Revision 1.48  2004/10/20 11:20:10  sjtan
# restore imports.
#
# Revision 1.47  2004/10/19 21:34:25  sjtan
# dir is direction, and this is checked
#
# Revision 1.46  2004/10/19 21:29:25  sjtan
# remove division by zero problem, statement occurs later after check for non-zero.
#
# Revision 1.45  2004/10/17 23:49:21  sjtan
#
# the timer autoscroll idea.
#
# Revision 1.44  2004/10/17 22:26:42  sjtan
#
# split window new look Richard's demographics ( his eye for gui design is better
# than most of ours). Rollback if vote no.
#
# Revision 1.43  2004/10/16 22:42:12  sjtan
#
# script for unitesting; guard for unit tests where unit uses gmPhraseWheel; fixup where version of wxPython doesn't allow
# a child widget to be multiply inserted (gmDemographics) ; try block for later versions of wxWidgets that might fail
# the Add (.. w,h, ... ) because expecting Add(.. (w,h) ...)
#
# Revision 1.42  2004/09/10 10:51:14  ncq
# - improve previous checkin comment
#
# Revision 1.41  2004/09/10 10:41:38  ncq
# - remove dead import
# - lots of cleanup (whitespace, indention, style, local vars instead of instance globals)
# - remove an extra sizer, waste less space
# - translate strings
# - from wxPython.wx import * -> from wxPython import wx
#   Why ? Because we can then do a simple replace wx. -> wx. for 2.5 code.
#
# Revision 1.40  2004/08/24 14:29:58  ncq
# - some cleanup, not there yet, though
#
# Revision 1.39  2004/08/23 10:25:36  ncq
# - Richards work, removed pat photo, store column sizes
#
# Revision 1.38  2004/08/20 13:34:48  ncq
# - getFirstMatchingDBSet() -> getDBParam()
#
# Revision 1.37  2004/08/18 08:15:21  ncq
# - check if column size for patient list is missing
#
# Revision 1.36  2004/08/16 13:32:19  ncq
# - rework of GUI layout by R.Terry
# - save patient list column width from right click popup menu
#
# Revision 1.35  2004/07/30 13:43:33  sjtan
#
# update import
#
# Revision 1.34  2004/07/26 12:04:44  sjtan
#
# character level immediate validation , as per Richard's suggestions.
#
# Revision 1.33  2004/07/20 01:01:46  ihaywood
# changing a patients name works again.
# Name searching has been changed to query on names rather than v_basic_person.
# This is so the old (inactive) names are still visible to the search.
# This is so when Mary Smith gets married, we can still find her under Smith.
# [In Australia this odd tradition is still the norm, even female doctors
# have their medical registration documents updated]
#
# SOAPTextCtrl now has popups, but the cursor vanishes (?)
#
# Revision 1.32  2004/07/18 20:30:53  ncq
# - wxPython.true/false -> Python.True/False as Python tells us to do
#
# Revision 1.31  2004/06/30 15:09:47  shilbert
# - more wxMAC fixes
#
# Revision 1.30  2004/06/29 22:48:47  shilbert
# - one more wxMAC fix
#
# Revision 1.29  2004/06/27 13:42:26  ncq
# - further Mac fixes - maybe 2.5 issues ?
#
# Revision 1.28  2004/06/23 21:26:28  ncq
# - kill dead code, fixup for Mac
#
# Revision 1.27  2004/06/20 17:28:34  ncq
# - The Great Butchering begins
# - remove dead plugin code
# - rescue binoculars xpm to artworks/
#
# Revision 1.26  2004/06/17 11:43:12  ihaywood
# Some minor bugfixes.
# My first experiments with wxGlade
# changed gmPhraseWheel so the match provider can be added after instantiation
# (as wxGlade can't do this itself)
#
# Revision 1.25  2004/06/13 22:31:48  ncq
# - gb['main.toolbar'] -> gb['main.top_panel']
# - self.internal_name() -> self.__class__.__name__
# - remove set_widget_reference()
# - cleanup
# - fix lazy load in _on_patient_selected()
# - fix lazy load in ReceiveFocus()
# - use self._widget in self.GetWidget()
# - override populate_with_data()
# - use gb['main.notebook.raised_plugin']
#
# Revision 1.24  2004/05/27 13:40:22  ihaywood
# more work on referrals, still not there yet
#
# Revision 1.23  2004/05/25 16:18:12  sjtan
#
# move methods for postcode -> urb interaction to gmDemographics so gmContacts can use it.
#
# Revision 1.22  2004/05/25 16:00:34  sjtan
#
# move common urb/postcode collaboration  to business class.
#
# Revision 1.21  2004/05/23 11:13:59  sjtan
#
# some data fields not in self.input_fields , so exclude them
#
# Revision 1.20  2004/05/19 11:16:09  sjtan
#
# allow selecting the postcode for restricting the urb's picklist, and resetting
# the postcode for unrestricting the urb picklist.
#
# Revision 1.19  2004/03/27 04:37:01  ihaywood
# lnk_person2address now lnk_person_org_address
# sundry bugfixes
#
# Revision 1.18  2004/03/25 11:03:23  ncq
# - getActiveName -> get_names
#
# Revision 1.17  2004/03/15 15:43:17  ncq
# - cleanup imports
#
# Revision 1.16  2004/03/09 07:34:51  ihaywood
# reactivating plugins
#
# Revision 1.15  2004/03/04 11:19:05  ncq
# - put a comment as to where to handle result from setCOB
#
# Revision 1.14  2004/03/03 23:53:22  ihaywood
# GUI now supports external IDs,
# Demographics GUI now ALPHA (feature-complete w.r.t. version 1.0)
# but happy to consider cosmetic changes
#
# Revision 1.13  2004/03/03 05:24:01  ihaywood
# patient photograph support
#
# Revision 1.12  2004/03/02 23:57:59  ihaywood
# Support for full range of backend genders
#
# Revision 1.11  2004/03/02 10:21:10  ihaywood
# gmDemographics now supports comm channels, occupation,
# country of birth and martial status
#
# Revision 1.10  2004/02/25 09:46:21  ncq
# - import from pycommon now, not python-common
#
# Revision 1.9  2004/02/18 06:30:30  ihaywood
# Demographics editor now can delete addresses
# Contacts back up on screen.
#
# Revision 1.8  2004/01/18 21:49:18  ncq
# - comment out debugging code
#
# Revision 1.7  2004/01/04 09:33:32  ihaywood
# minor bugfixes, can now create new patients, but doesn't update properly
#
# Revision 1.6  2003/11/22 14:47:24  ncq
# - use addName instead of setActiveName
#
# Revision 1.5  2003/11/22 12:29:16  sjtan
#
# minor debugging; remove _newPatient flag attribute conflict with method name newPatient.
#
# Revision 1.4  2003/11/20 02:14:42  sjtan
#
# use global module function getPostcodeByUrbId() , and renamed MP_urb_by_zip.
#
# Revision 1.3  2003/11/19 23:11:58  sjtan
#
# using local time tuple conversion function; mxDateTime object sometimes can't convert to int.
# Changed to global module.getAddressTypes(). To decide: mechanism for postcode update when
# suburb selected ( not back via gmDemographicRecord.getPostcodeForUrbId(), ? via linked PhraseWheel matchers ?)
#
# Revision 1.2  2003/11/18 16:46:02  ncq
# - sync with method name changes
#
# Revision 1.1  2003/11/17 11:04:34  sjtan
#
# added.
#
# Revision 1.1  2003/10/23 06:02:40  sjtan
#
# manual edit areas modelled after r.terry's specs.
#
# Revision 1.26  2003/04/28 12:14:40  ncq
# - use .internal_name()
#
# Revision 1.25  2003/04/25 11:15:58  ncq
# cleanup
#
# Revision 1.24  2003/04/05 00:39:23  ncq
# - "patient" is now "clinical", changed all the references
#
# Revision 1.23  2003/04/04 20:52:44  ncq
# - start disentanglement with top pane:
#   - remove patient search/age/allergies/patient details
#
# Revision 1.22  2003/03/29 18:27:14  ncq
# - make age/allergies read-only, cleanup
#
# Revision 1.21  2003/03/29 13:50:09  ncq
# - adapt to new "top row" panel
#
# Revision 1.20  2003/03/28 16:43:12  ncq
# - some cleanup in preparation of inserting the patient searcher
#
# Revision 1.19  2003/02/09 23:42:50  ncq
# - date time conversion to age string does not work, set to 20 for now, fix soon
#
# Revision 1.18  2003/02/09 12:05:02  sjtan
#
#
# wx.BasePlugin is unnecessarily specific.
#
# Revision 1.17  2003/02/09 11:57:42  ncq
# - cleanup, cvs keywords
#
# old change log:
#	10.06.2002 rterry initial implementation, untested
#	30.07.2002 rterry images put in file