William Bowling is sharing code with you

Bitbucket is a code hosting site. Unlimited public and private repositories. Free for small teams.

Don't show this again

wbowling / adium (fork of adium / adium)

Fork of Adium for patches/improvements

Clone this repository (size: 338.7 MB): HTTPS / SSH
hg clone https://bitbucket.org/wbowling/adium
hg clone ssh://hg@bitbucket.org/wbowling/adium

adium / Source / AILogViewerWindowController.m

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
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
//
//  AILogViewerWindowController.m
//  Adium
//
//  Created by Evan Schoenberg on 3/24/06.
//

#import "AILogViewerWindowController.h"
#import "AIChatLog.h"
#import "AILogFromGroup.h"
#import "AILogToGroup.h"
#import "AILoggerPlugin.h"
#import "ESRankingCell.h" 
#import "AIXMLChatlogConverter.h"
#import "AILogDateFormatter.h"

#import <Adium/AIAccountControllerProtocol.h>
#import <Adium/AIChatControllerProtocol.h>
#import <Adium/AIContactControllerProtocol.h>
#import <Adium/AIContentControllerProtocol.h>
#import <Adium/AIMenuControllerProtocol.h>
#import <Adium/AIHTMLDecoder.h>
#import <Adium/AIInterfaceControllerProtocol.h>
#import <Adium/AIListContact.h>
#import <Adium/AIMetaContact.h>
#import <Adium/AIService.h>
#import <Adium/AIServiceIcons.h>
#import <Adium/AIUserIcons.h>
#import <Adium/KNShelfSplitView.h>
#import <AIUtilities/AIArrayAdditions.h>
#import <AIUtilities/AIAttributedStringAdditions.h>
#import <AIUtilities/AIDateFormatterAdditions.h>
#import <AIUtilities/AIFileManagerAdditions.h>
#import <AIUtilities/AIImageAdditions.h>
#import <AIUtilities/AIImageTextCell.h>
#import <AIUtilities/AIOutlineViewAdditions.h>
#import <AIUtilities/AISplitView.h>
#import <AIUtilities/AIStringAdditions.h>
#import <AIUtilities/AITableViewAdditions.h>
#import <AIUtilities/AITextAttributes.h>
#import <AIUtilities/AIToolbarUtilities.h>
#import <AIUtilities/AIApplicationAdditions.h>
#import <AIUtilities/AIDividedAlternatingRowOutlineView.h>

#define KEY_LOG_VIEWER_WINDOW_FRAME		@"Log Viewer Frame"
#define KEY_LOG_VIEWER_GROUP_STATE		@"Log Viewer Group State"	//Expand/Collapse state of groups
#define TOOLBAR_LOG_VIEWER				@"Log Viewer Toolbar"

#define MAX_LOGS_TO_SORT_WHILE_SEARCHING	10000	//Max number of logs we will live sort while searching
#define LOG_SEARCH_STATUS_INTERVAL			20	//1/60ths of a second to wait before refreshing search status

#define SEARCH_MENU						AILocalizedString(@"Search Menu",nil)
#define FROM							AILocalizedString(@"From",nil)
#define TO								AILocalizedString(@"To",nil)
#define DATE							AILocalizedString(@"Date",nil)
#define CONTENT							AILocalizedString(@"Content",nil)
#define DELETE							AILocalizedString(@"Delete",nil)
#define DELETEALL						AILocalizedString(@"Delete All",nil)
#define SEARCH							AILocalizedString(@"Search",nil)

#define HIDE_EMOTICONS					AILocalizedString(@"Hide Emoticons",nil)
#define SHOW_EMOTICONS					AILocalizedString(@"Show Emoticons",nil)
#define HIDE_TIMESTAMPS					AILocalizedString(@"Hide Timestamps",nil)
#define SHOW_TIMESTAMPS					AILocalizedString(@"Show Timestamps",nil)

#define IMAGE_EMOTICONS_OFF				@"emoticon32"
#define IMAGE_EMOTICONS_ON				@"emoticon32_transparent"
#define IMAGE_TIMESTAMPS_OFF			@"timestamp32"
#define IMAGE_TIMESTAMPS_ON				@"timestamp32_transparent"


#define	REFRESH_RESULTS_INTERVAL		1.0 //Interval between results refreshes while searching

@interface AILogViewerWindowController ()
- (id)initWithWindowNibName:(NSString *)windowNibName plugin:(id)inPlugin;
- (void)initLogFiltering;
- (void)displayLog:(AIChatLog *)log;
- (void)hilightOccurrencesOfString:(NSString *)littleString inString:(NSMutableAttributedString *)bigString firstOccurrence:(NSRange *)outRange;
- (void)sortCurrentSearchResultsForTableColumn:(NSTableColumn *)tableColumn direction:(BOOL)direction;
- (void)startSearchingClearingCurrentResults:(BOOL)clearCurrentResults;
- (void)buildSearchMenu;
- (NSMenuItem *)_menuItemWithTitle:(NSString *)title forSearchMode:(LogSearchMode)mode;
- (void)_logFilter:(NSString *)searchString searchID:(NSInteger)searchID mode:(LogSearchMode)mode;
- (void)installToolbar;
- (void)updateRankColumnVisibility;
- (void)openLogAtPath:(NSString *)inPath;
- (void)rebuildContactsList;
- (void)filterForContact:(AIListContact *)inContact;
- (void)filterForChatName:(NSString *)chatName withAccount:(AIAccount *)account;
- (void)selectCachedIndex;

- (NSAlert *)alertForDeletionOfLogCount:(NSUInteger)logCount;

- (void)_willOpenForContact;
- (void)_didOpenForContact;

- (void)deleteSelection:(id)sender;
@end

@implementation AILogViewerWindowController

static AILogViewerWindowController	*sharedLogViewerInstance = nil;
static NSInteger toArraySort(id itemA, id itemB, void *context);

+ (NSString *)nibName
{
	return @"LogViewer";	
}

+ (id)openForPlugin:(id)inPlugin
{
    if (!sharedLogViewerInstance) {
		sharedLogViewerInstance = [[self alloc] initWithWindowNibName:[self nibName] plugin:inPlugin];
	}

    [sharedLogViewerInstance showWindow:nil];
    
	return sharedLogViewerInstance;
}

+ (id)openLogAtPath:(NSString *)inPath plugin:(id)inPlugin
{
	[self openForPlugin:inPlugin];
	
	[sharedLogViewerInstance openLogAtPath:inPath];
	
	return sharedLogViewerInstance;
}

//Open the log viewer window to a specific contact's logs
+ (id)openForContact:(AIListContact *)inContact plugin:(id)inPlugin
{
    if (!sharedLogViewerInstance) {
		sharedLogViewerInstance = [[self alloc] initWithWindowNibName:[self nibName] plugin:inPlugin];
	}

	[sharedLogViewerInstance _willOpenForContact];
	[sharedLogViewerInstance showWindow:nil];
	[sharedLogViewerInstance filterForContact:inContact];
	[sharedLogViewerInstance _didOpenForContact];

    return sharedLogViewerInstance;
}

+ (id)openForChatName:(NSString *)inChatName withAccount:(AIAccount *)inAccount plugin:(id)inPlugin
{
	if (!sharedLogViewerInstance) {
		sharedLogViewerInstance = [[self alloc] initWithWindowNibName:[self nibName] plugin:inPlugin];
	}
	
	[sharedLogViewerInstance _willOpenForContact];
	[sharedLogViewerInstance showWindow:nil];
	[sharedLogViewerInstance filterForChatName:inChatName withAccount:inAccount];
	[sharedLogViewerInstance _didOpenForContact];
	
    return sharedLogViewerInstance;
}

//Returns the window controller if one exists
+ (id)existingWindowController
{
    return sharedLogViewerInstance;
}

//Close the log viewer window
+ (void)closeSharedInstance
{
    if (sharedLogViewerInstance) {
        [sharedLogViewerInstance closeWindow:nil];
    }
}

//init
- (id)initWithWindowNibName:(NSString *)windowNibName plugin:(id)inPlugin
{
	if((self = [super initWithWindowNibName:windowNibName])) {
		plugin = inPlugin;
		selectedColumn = nil;
		activeSearchID = 0;
		searching = NO;
		automaticSearch = YES;
		showEmoticons = NO;
		showTimestamps = YES;
		activeSearchString = nil;
		displayedLogArray = nil;
		windowIsClosing = NO;
		desiredContactsSourceListDeltaX = 0;

		blankImage = [[NSImage alloc] initWithSize:NSMakeSize(16,16)];

		sortDirection = YES;
		searchMode = LOG_SEARCH_CONTENT;

		headerDateFormatter = [[NSDateFormatter localizedDateFormatter] retain];

		currentSearchResults = [[NSMutableArray alloc] init];
		fromArray = [[NSMutableArray alloc] init];
		fromServiceArray = [[NSMutableArray alloc] init];
		logFromGroupDict = [[NSMutableDictionary alloc] init];
		toArray = [[NSMutableArray alloc] init];
		toServiceArray = [[NSMutableArray alloc] init];
		logToGroupDict = [[NSMutableDictionary alloc] init];
		resultsLock = [[NSRecursiveLock alloc] init];
		searchingLock = [[NSLock alloc] init];
		[searchingLock setName:@"LogSearchingLock"];
		contactIDsToFilter = [[NSMutableSet alloc] initWithCapacity:1];

		allContactsIdentifier = [[NSNumber numberWithInteger:-1] retain];

		undoManager = [[NSUndoManager alloc] init];
		currentSearchLock = [[NSLock alloc] init];
		[currentSearchLock setName:@"CurrentLogSearchLock"];
	}
	
	return self;
}

//dealloc
- (void)dealloc
{
	[filterDate release]; filterDate = nil;
	[currentSearchLock release]; currentSearchLock = nil;
	[resultsLock release];
	[searchingLock release];
	[fromArray release];
	[fromServiceArray release];
	[toArray release];
	[toServiceArray release];
	[currentSearchResults release];
	[selectedColumn release];
	[headerDateFormatter release];
	[displayedLogArray release];
	[blankImage release];
	[activeSearchString release];
	[contactIDsToFilter release];

	[logFromGroupDict release]; logFromGroupDict = nil;
	[logToGroupDict release]; logToGroupDict = nil;

	[filterForAccountName release]; filterForAccountName = nil;

	[horizontalRule release]; horizontalRule = nil;

	[adiumIcon release]; adiumIcon = nil;
	[adiumIconHighlighted release]; adiumIconHighlighted = nil;

	//We loaded	view_DatePicker from a nib manually, so we must release it
	[view_DatePicker release]; view_DatePicker = nil;

	[allContactsIdentifier release];
	[undoManager release]; undoManager = nil;

	[super dealloc];
}

//Init our log filtering tree
- (void)initLogFiltering
{
    NSMutableDictionary		*toDict = [NSMutableDictionary dictionary];
    NSString				*basePath = [AILoggerPlugin logBasePath];
    NSString				*fromUID, *serviceClass;

    //Process each account folder (/Logs/SERVICE.ACCOUNT_NAME/) - sorting by compare: will result in an ordered list
	//first by service, then by account name.
    for (NSString *folderName in [[[NSFileManager defaultManager] contentsOfDirectoryAtPath:basePath error:NULL] sortedArrayUsingSelector:@selector(compare:)]) {
		if (![folderName isEqualToString:@".DS_Store"]) { // avoid the directory info
			AILogFromGroup  *logFromGroup;
			NSMutableSet	*toSetForThisService;
			NSArray         *serviceAndFromUIDArray;
			
			/* Determine the service and fromUID - should be SERVICE.ACCOUNT_NAME
			 * Check against count to guard in case of old, malformed or otherwise odd folders & whatnot sitting in log base
			 */
			serviceAndFromUIDArray = [folderName componentsSeparatedByString:@"."];

			if ([serviceAndFromUIDArray count] >= 2) {
				serviceClass = [serviceAndFromUIDArray objectAtIndex:0];

				//Use substringFromIndex so we include the rest of the string in the case of a UID with a . in it
				fromUID = [folderName substringFromIndex:([serviceClass length] + 1)]; //One off for the '.'
			} else {
				//Fallback: blank non-nil serviceClass; folderName as the fromUID
				serviceClass = @"";
				fromUID = folderName;
			}

			logFromGroup = [[AILogFromGroup alloc] initWithPath:folderName fromUID:fromUID serviceClass:serviceClass];

			//Store logFromGroup on a key in the form "SERVICE.ACCOUNT_NAME"
			[logFromGroupDict setObject:logFromGroup forKey:folderName];

			//To processing
			if (!(toSetForThisService = [toDict objectForKey:serviceClass])) {
				toSetForThisService = [NSMutableSet set];
				[toDict setObject:toSetForThisService
						   forKey:serviceClass];
			}

			//Add the 'to' for each grouping on this account
			for (AILogToGroup *currentToGroup in [logFromGroup toGroupArray]) {
				NSString	*currentTo;

				if ((currentTo = [currentToGroup to])) {
					//Store currentToGroup on a key in the form "SERVICE.ACCOUNT_NAME/TARGET_CONTACT"
					[logToGroupDict setObject:currentToGroup forKey:[currentToGroup relativePath]];
				}
			}

			[logFromGroup release];
		}
	}

	[self rebuildContactsList];
}

- (void)rebuildContactsList
{
	NSInteger	oldCount = toArray.count;
	[toArray release]; toArray = [[NSMutableArray alloc] initWithCapacity:(oldCount ? oldCount : 20)];

	for (AILogFromGroup *logFromGroup in [logFromGroupDict objectEnumerator]) {
		//Add the 'to' for each grouping on this account
		for (AILogToGroup *currentToGroup in [logFromGroup toGroupArray]) {
			NSString	*currentTo;
			
			if ((currentTo = [currentToGroup to])) {
				NSString *serviceClass = [currentToGroup serviceClass];
				AIListObject *listObject = ((serviceClass && currentTo) ?
											[adium.contactController existingListObjectWithUniqueID:[AIListObject internalObjectIDForServiceID:serviceClass
																																			 UID:currentTo]] :
											nil);
				if (listObject && [listObject isKindOfClass:[AIListContact class]]) {
					AIListContact *parentContact = [(AIListContact *)listObject parentContact];
					if (![toArray containsObjectIdenticalTo:parentContact]) {
						[toArray addObject:parentContact];
					}
					
				} else {
					if (![toArray containsObject:currentToGroup]) {
						[toArray addObject:currentToGroup];
					}
				}
			}
		}		
	}
	
	[toArray sortUsingFunction:toArraySort context:NULL];
	[outlineView_contacts reloadData];

	if (!isOpeningForContact) {
		//If we're opening for a contact, the outline view selection will be changed in a moment anyways
		[self outlineViewSelectionDidChange:nil];
	}
}

- (NSString *)adiumFrameAutosaveName
{
	return KEY_LOG_VIEWER_WINDOW_FRAME;
}

//Setup the window before it is displayed
- (void)windowDidLoad
{
	suppressSearchRequests = YES;

	[super windowDidLoad];

	[plugin pauseIndexing];

	[[self window] setTitle:AILocalizedString(@"Chat Transcript Viewer",nil)];
    [textField_progress setStringValue:@""];

	//Autosave doesn't do anything yet
	[shelf_splitView setAutosaveName:@"LogViewer:Shelf"];
	[shelf_splitView setFrame:[[[self window] contentView] frame]];

	// Pull our main article/display split view out of the nib and position it in the shelf view
	[containingView_results retain];
	[containingView_results removeFromSuperview];
	[shelf_splitView setContentView:containingView_results];
	[containingView_results release];
	[tableView_results accessibilitySetOverrideValue:AILocalizedString(@"Transcripts", nil)
										forAttribute:NSAccessibilityRoleDescriptionAttribute];
	
	// Pull our source view out of the nib and position it in the shelf view
	[containingView_contactsSourceList retain];
	[containingView_contactsSourceList removeFromSuperview];
	[shelf_splitView setShelfView:containingView_contactsSourceList];
	[outlineView_contacts accessibilitySetOverrideValue:AILocalizedString(@"Contacts", nil)
										forAttribute:NSAccessibilityRoleDescriptionAttribute];
	[containingView_contactsSourceList release];

	//Set emoticon filtering
	showEmoticons = [[adium.preferenceController preferenceForKey:KEY_LOG_VIEWER_EMOTICONS
															  group:PREF_GROUP_LOGGING] boolValue];
	[[toolbarItems objectForKey:@"toggleemoticons"] setLabel:(showEmoticons ? HIDE_EMOTICONS : SHOW_EMOTICONS)];
	[[toolbarItems objectForKey:@"toggleemoticons"] setImage:[NSImage imageNamed:(showEmoticons ? IMAGE_EMOTICONS_ON : IMAGE_EMOTICONS_OFF) forClass:[self class]]];

	// Set timestamp filtering
	showTimestamps = [[adium.preferenceController preferenceForKey:KEY_LOG_VIEWER_TIMESTAMPS
															   group:PREF_GROUP_LOGGING] boolValue];
	[[toolbarItems objectForKey:@"toggletimestamps"] setLabel:(showTimestamps ? HIDE_TIMESTAMPS : SHOW_TIMESTAMPS)];
	[[toolbarItems objectForKey:@"toggletimestamps"] setImage:[NSImage imageNamed:(showTimestamps ? IMAGE_TIMESTAMPS_ON : IMAGE_TIMESTAMPS_OFF) forClass:[self class]]];

	//Toolbar
	[self installToolbar];	

	[outlineView_contacts setSelectionHighlightStyle:NSTableViewSelectionHighlightStyleSourceList];

	AIImageTextCell	*dataCell = [[AIImageTextCell alloc] init];
	NSTableColumn	*tableColumn = [[outlineView_contacts tableColumns] objectAtIndex:0];
	[tableColumn setDataCell:dataCell];
	[tableColumn setEditable:NO];
	[dataCell setFont:[NSFont systemFontOfSize:[NSFont smallSystemFontSize]]];
	[dataCell release];

	// Set the selector for doubleAction
	[outlineView_contacts setDoubleAction:@selector(openChatOnDoubleAction:)];
	
	//Localize tableView_results column headers
	[[[tableView_results tableColumnWithIdentifier:@"To"] headerCell] setStringValue:TO];
	[[[tableView_results tableColumnWithIdentifier:@"From"] headerCell] setStringValue:FROM];
	[[[tableView_results tableColumnWithIdentifier:@"Date"] headerCell] setStringValue:DATE];
	[self tableViewColumnDidResize:nil];

	[tableView_results sizeLastColumnToFit];

	//Prepare the search controls
	[self buildSearchMenu];
	if ([textView_content respondsToSelector:@selector(setUsesFindPanel:)]) {
		[textView_content setUsesFindPanel:YES];
	}

    //Sort by preference, defaulting to sorting by date
	NSString	*selectedTableColumnPref;
	if ((selectedTableColumnPref = [adium.preferenceController preferenceForKey:KEY_LOG_VIEWER_SELECTED_COLUMN
																		   group:PREF_GROUP_LOGGING])) {
		selectedColumn = [[tableView_results tableColumnWithIdentifier:selectedTableColumnPref] retain];
	}
	if (!selectedColumn) {
		selectedColumn = [[tableView_results tableColumnWithIdentifier:@"Date"] retain];
	}
	[self sortCurrentSearchResultsForTableColumn:selectedColumn direction:YES];

    //Prepare indexing and filter searching
	[plugin prepareLogContentSearching];
    [self initLogFiltering];

    //Begin our initial search
	[self setSearchMode:LOG_SEARCH_TO];

    [searchField_logs setStringValue:(activeSearchString ? activeSearchString : @"")];
	suppressSearchRequests = NO;

	if (!isOpeningForContact) {
		//If we're opening for a contact, we'll select it and then begin searching
		[self startSearchingClearingCurrentResults:YES];
	}
	
	[tableView_results setAutosaveName:@"LogViewerResults"];
	[tableView_results setAutosaveTableColumns:YES];

	[plugin resumeIndexing];
}

-(void)rebuildIndices
{
    //Rebuild the 'global' log indexes
    [logFromGroupDict release]; logFromGroupDict = [[NSMutableDictionary alloc] init];
    [toArray removeAllObjects]; //note: even if there are no logs, the name will remain [bug or feature?]
    [toServiceArray removeAllObjects];
    [fromArray removeAllObjects];
    [fromServiceArray removeAllObjects];
    
    [self initLogFiltering];
    
    [tableView_results reloadData];
    [self selectDisplayedLog];
}

//Called as the window closes
- (void)windowWillClose:(id)sender
{
	[super windowWillClose:sender];

	//Set preference for emoticon filtering
	[adium.preferenceController setPreference:[NSNumber numberWithBool:showEmoticons]
										 forKey:KEY_LOG_VIEWER_EMOTICONS
										  group:PREF_GROUP_LOGGING];
											
	// Set preference for timestamp filtering
	[adium.preferenceController setPreference:[NSNumber numberWithBool:showTimestamps]
																			 forKey:KEY_LOG_VIEWER_TIMESTAMPS
																				group:PREF_GROUP_LOGGING];
	
	//Set preference for selected column
	[adium.preferenceController setPreference:[selectedColumn identifier]
										 forKey:KEY_LOG_VIEWER_SELECTED_COLUMN
										  group:PREF_GROUP_LOGGING];

    /* Disable the search field.  If we don't disable the search field, it will often try to call its target action
     * after the window has closed (and we are gone).  I'm not sure why this happens, but disabling the field
     * before we close the window down seems to prevent the crash.
	 */
    [searchField_logs setEnabled:NO];
	
	/* Note that the window is closing so we don't take behaviors which could cause messages to the window after
	 * it was gone, like responding to a logIndexUpdated message
	 */
	windowIsClosing = YES;

    //Abort any in-progress searching and indexing, and wait for their completion
    [self stopSearching];
    [plugin cleanUpLogContentSearching];

	//Reset our column widths if needed
	[activeSearchString release]; activeSearchString = nil;
	[self updateRankColumnVisibility];
	
	[sharedLogViewerInstance autorelease]; sharedLogViewerInstance = nil;
	[toolbarItems autorelease]; toolbarItems = nil;
}

//Display --------------------------------------------------------------------------------------------------------------
#pragma mark Display
//Update log viewer progress string to reflect current status
- (void)updateProgressDisplay
{
    NSMutableString     *progress = nil;
    NSUInteger					indexNumber, indexTotal;
    BOOL				indexing;

    //We always convey the number of logs being displayed
    [resultsLock lock];
	NSUInteger count = [currentSearchResults count];
    if (activeSearchString && [activeSearchString length]) {
		[shelf_splitView setResizeThumbStringValue:[NSString stringWithFormat:((count != 1) ? 
																			   AILocalizedString(@"%lu matching transcripts",nil) :
																			   AILocalizedString(@"1 matching transcript",nil)),count]];
    } else {
		[shelf_splitView setResizeThumbStringValue:[NSString stringWithFormat:((count != 1) ? 
																			   AILocalizedString(@"%lu transcripts",nil) :
																			   AILocalizedString(@"1 transcript",nil)),count]];
		
		//We are searching, but there is no active search  string. This indicates we're still opening logs.
		if (searching) {
			progress = [[AILocalizedString(@"Opening transcripts",nil) mutableCopy] autorelease];			
		}
    }
    [resultsLock unlock];

	indexing = [plugin getIndexingProgress:&indexNumber outOf:&indexTotal];

    //Append search progress
    if (activeSearchString && [activeSearchString length]) {
		if (progress) {
			[progress appendString:@" - "];
		} else {
			progress = [NSMutableString string];
		}

		if (searching || indexing) {
			[progress appendString:[NSString stringWithFormat:AILocalizedString(@"Searching for '%@'",nil),activeSearchString]];
		} else {
			[progress appendString:[NSString stringWithFormat:AILocalizedString(@"Search for '%@' complete.",nil),activeSearchString]];			
		}
	}

    //Append indexing progress
    if (indexing) {
		if (progress) {
			[progress appendString:@" - "];
		} else {
			progress = [NSMutableString string];
		}
		
		[progress appendString:[NSString stringWithFormat:AILocalizedString(@"Indexing %lu of %lu transcripts",nil), indexNumber, indexTotal]];
    }
	
	if (progress && (searching || indexing || !(activeSearchString && [activeSearchString length]))) {
		[progress appendString:[NSString ellipsis]];	
	}

    //Enable/disable the searching animation
    if (searching || indexing) {
		[progressIndicator startAnimation:nil];
    } else {
		[progressIndicator stopAnimation:nil];
    }
    
    [textField_progress setStringValue:(progress ? progress : @"")];
}

//The plugin is informing us that the log indexing changed
- (void)logIndexingProgressUpdate
{
	//Don't do anything if the window is already closing
	if (!windowIsClosing) {
		[self updateProgressDisplay];
		
		//If we are searching by content, we should re-search without clearing our current results so the
		//the newly-indexed logs can be added without blanking the current table contents.
		if (searchMode == LOG_SEARCH_CONTENT && (activeSearchString && [activeSearchString length])) {
			if (searching) {
				//We're already searching; reattempt when done
				searchIDToReattemptWhenComplete = activeSearchID;
			} else {
				//We're not searching - restart the search immediately every 10 updates to utilize the newly indexed logs
				indexingUpdatesReceivedWhileSearching++;
				if ((indexingUpdatesReceivedWhileSearching % 10) == 0)
					[self startSearchingClearingCurrentResults:NO];
			}
		}
	}
}

//Refresh the results table
- (void)refreshResults
{
	[self updateProgressDisplay];

	[self refreshResultsSearchIsComplete:NO];
}

- (void)refreshResultsSearchIsComplete:(BOOL)searchIsComplete
{
    [resultsLock lock];
    NSInteger count = [currentSearchResults count];
    [resultsLock unlock];
	AILog(@"refreshResultsSearchIsComplete: %i (count is %i)",searchIsComplete,count);
    if (!searching || count <= MAX_LOGS_TO_SORT_WHILE_SEARCHING) {
		//Sort the logs correctly which will also reload the table
		[self resortLogs];
		
		if (searchIsComplete && automaticSearch) {
			//If search is complete, select the first log if requested and possible
			[self selectFirstLog];
			
		} else {
			BOOL oldAutomaticSearch = automaticSearch;

			//We don't want the above re-selection to change our automaticSearch tracking
			//(The only reason automaticSearch should change is in response to user action)
			automaticSearch = oldAutomaticSearch;
		}
    }
	
	if (searchIsComplete &&
		((activeSearchID == searchIDToReattemptWhenComplete) && !windowIsClosing)) {
		searchIDToReattemptWhenComplete = -1;
		[self startSearchingClearingCurrentResults:NO];
	}
	
	if(deleteOccurred)
		[self selectCachedIndex];

    //Update status
    [self updateProgressDisplay];
}

- (void)searchComplete
{
	[refreshResultsTimer invalidate]; [refreshResultsTimer release]; refreshResultsTimer = nil;
	[self refreshResultsSearchIsComplete:YES];
}

// Called on doubleAction to open a chat
-(void)openChatOnDoubleAction:(id)sender
{
	id item = [outlineView_contacts firstSelectedItem];
	if ([item isKindOfClass:[AIListContact class]]) {
		//Open a new message with the contact
		[adium.interfaceController setActiveChat:[adium.chatController openChatWithContact:(AIListContact *)item onPreferredAccount:YES]];
	}
}

//Displays the contents of the specified log in our window
- (void)displayLogs:(NSArray *)logArray;
{	
    NSMutableAttributedString	*displayText = nil;
	NSAttributedString			*finalDisplayText = nil;
	NSRange						scrollRange = NSMakeRange(0,0);
	BOOL						appendedFirstLog = NO;

    if (![logArray isEqualToArray:displayedLogArray]) {
		[displayedLogArray release];
		displayedLogArray = [logArray copy];
	}

	if ([logArray count] > 1) {
		displayText = [[NSMutableAttributedString alloc] init];
	}

	AIChatLog	 *theLog;
	NSString	 *logBasePath = [AILoggerPlugin logBasePath];
	AILog(@"Displaying %@",logArray);
	for (theLog in logArray) {
		NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
		
		if (displayText) {
			if (!horizontalRule) {
				#define HORIZONTAL_BAR			0x2013
				#define HORIZONTAL_RULE_LENGTH	18
				
				const unichar separatorUTF16[HORIZONTAL_RULE_LENGTH] = {
					HORIZONTAL_BAR, HORIZONTAL_BAR, HORIZONTAL_BAR, HORIZONTAL_BAR, HORIZONTAL_BAR, HORIZONTAL_BAR,
					HORIZONTAL_BAR, HORIZONTAL_BAR, HORIZONTAL_BAR, HORIZONTAL_BAR, HORIZONTAL_BAR, HORIZONTAL_BAR,
					HORIZONTAL_BAR, HORIZONTAL_BAR, HORIZONTAL_BAR, HORIZONTAL_BAR, HORIZONTAL_BAR, HORIZONTAL_BAR
				};
				horizontalRule = [[NSString alloc] initWithCharacters:separatorUTF16 length:HORIZONTAL_RULE_LENGTH];
			}	
			
			[displayText appendString:[NSString stringWithFormat:@"%@%@\n%@ - %@\n%@\n\n",
				(appendedFirstLog ? @"\n" : @""),
				horizontalRule,
				[headerDateFormatter stringFromDate:[theLog date]],
				[theLog to],
				horizontalRule]
					   withAttributes:[[AITextAttributes textAttributesWithFontFamily:@"Helvetica" traits:NSBoldFontMask size:12] dictionary]];
		}
		
		if ([[theLog relativePath] hasSuffix:@".AdiumHTMLLog"] || [[theLog relativePath] hasSuffix:@".html"] || [[theLog relativePath] hasSuffix:@".html.bak"]) {
			//HTML log
			NSURL *logURL = [NSURL fileURLWithPath:[logBasePath stringByAppendingPathComponent:[theLog relativePath]]];
			NSString *logFileText = [NSString stringWithContentsOfURL:logURL encoding:NSUTF8StringEncoding error:NULL];
			NSAttributedString *attributedLogFileText = [AIHTMLDecoder decodeHTML:logFileText];

			if (showEmoticons) {
				attributedLogFileText = [adium.contentController filterAttributedString:attributedLogFileText
																		  usingFilterType:AIFilterMessageDisplay
																				direction:AIFilterOutgoing
																				  context:nil];						
			}			

			if (displayText) {
				[displayText appendAttributedString:attributedLogFileText];
			} else {
				displayText = [attributedLogFileText mutableCopy];
			}

		} else if ([[theLog relativePath] hasSuffix:@".chatlog"]){
			//XML log
			NSString *logFullPath = [logBasePath stringByAppendingPathComponent:[theLog relativePath]];
			
			BOOL isDir;
			if ([[NSFileManager defaultManager] fileExistsAtPath:logFullPath isDirectory:&isDir]) {
				/* If we have a chatLog bundle, we want to get the text content for the xml file inside */
				if (isDir) logFullPath = [logFullPath stringByAppendingPathComponent:
										 [[[logFullPath lastPathComponent] stringByDeletingPathExtension] stringByAppendingPathExtension:@"xml"]];
			}

			NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
									 [NSNumber numberWithBool:showTimestamps], @"showTimestamps",
									 [NSNumber numberWithBool:showEmoticons], @"showEmoticons", 
									 nil];
			NSAttributedString *attributedLogFileText = [AIXMLChatlogConverter readFile:logFullPath withOptions:options];
			if (attributedLogFileText) {
				if (displayText)
					[displayText appendAttributedString:attributedLogFileText];
				else
					displayText = [attributedLogFileText mutableCopy];
			}

		} else {
			//Fallback: Plain text log
			NSURL *logURL = [NSURL fileURLWithPath:[logBasePath stringByAppendingPathComponent:[theLog relativePath]]];
			NSString *logFileText = [NSString stringWithContentsOfURL:logURL encoding:NSUTF8StringEncoding error:NULL];
			if (logFileText) {
				AITextAttributes *textAttributes = [AITextAttributes textAttributesWithFontFamily:@"Helvetica" traits:0 size:12];
				NSAttributedString *attributedLogFileText = [[[NSAttributedString alloc] initWithString:logFileText 
																							 attributes:[textAttributes dictionary]] autorelease];
				if (showEmoticons) {
					attributedLogFileText = [adium.contentController filterAttributedString:attributedLogFileText
																			  usingFilterType:AIFilterMessageDisplay
																					direction:AIFilterOutgoing
																					  context:nil];						
				}
				
				if (displayText) {
					[displayText appendAttributedString:attributedLogFileText];
				} else {
					displayText = [attributedLogFileText mutableCopy];
				}
			}
		}
		
		appendedFirstLog = YES;
		
		[pool release];
	}
	
	if (displayText && [displayText length]) {
		//Add pretty formatting to links
		[displayText addFormattingForLinks];

		//If we are searching by content, highlight the search results
		if ((searchMode == LOG_SEARCH_CONTENT) && [activeSearchString length]) {
			NSString					*searchWord;
			NSMutableArray				*searchWordsArray = [[activeSearchString componentsSeparatedByString:@" "] mutableCopy];
			NSScanner					*scanner = [NSScanner scannerWithString:activeSearchString];
			
			//Look for an initial quote
			NSAutoreleasePool *pool = nil;
			while (![scanner isAtEnd]) {
				[pool release];
				pool = [[NSAutoreleasePool alloc] init];
				
				[scanner scanUpToString:@"\"" intoString:NULL];
				
				//Scan past the quote
				if (![scanner scanString:@"\"" intoString:NULL]) {
					[pool release]; pool = nil;
					continue;
				}
				
				NSString *quotedString;
				//And a closing one
				if (![scanner isAtEnd] &&
					[scanner scanUpToString:@"\"" intoString:&quotedString]) {
					//Scan past the quote
					[scanner scanString:@"\"" intoString:NULL];
					/* If a string within quotes is found, remove the words from the quoted string and add the full string
					 * to what we'll be highlighting.
					 *
					 * We'll use indexOfObject: and removeObjectAtIndex: so we only remove _one_ instance. Otherwise, this string:
					 * "killer attack ninja kittens" OR ninja
					 * wouldn't highlight the word ninja by itself.
					 */
					NSArray *quotedWords = [quotedString componentsSeparatedByString:@" "];
					NSInteger quotedWordsCount = [quotedWords count];
					
					for (NSInteger i = 0; i < quotedWordsCount; i++) {
						NSString	*quotedWord = [quotedWords objectAtIndex:i];
						if (i == 0) {
							//Originally started with a quote, so put it back on
							quotedWord = [@"\"" stringByAppendingString:quotedWord];
						}
						if (i == quotedWordsCount - 1) {
							//Originally ended with a quote, so put it back on
							quotedWord = [quotedWord stringByAppendingString:@"\""];
						}
						NSInteger searchWordsIndex = [searchWordsArray indexOfObject:quotedWord];
						if (searchWordsIndex != NSNotFound) {
							[searchWordsArray removeObjectAtIndex:searchWordsIndex];
						} else {
							NSLog(@"displayLog: Couldn't find %@ in %@", quotedWord, searchWordsArray);
						}
					}
					
					//Add the full quoted string
					[searchWordsArray addObject:quotedString];
				}
			}

			BOOL shouldScrollToWord = NO;
			scrollRange = NSMakeRange([displayText length],0);

			for (searchWord in searchWordsArray) {
				NSRange     occurrence;
				
				//Check against and/or.  We don't just remove it from the array because then we couldn't check case insensitively.
				if (([searchWord caseInsensitiveCompare:@"and"] != NSOrderedSame) &&
					([searchWord caseInsensitiveCompare:@"or"] != NSOrderedSame)) {
					[self hilightOccurrencesOfString:searchWord inString:displayText firstOccurrence:&occurrence];
					
					//We'll want to scroll to the first occurrance of any matching word or words
					if (occurrence.location < scrollRange.location) {
						scrollRange = occurrence;
						shouldScrollToWord = YES;
					}
				}
			}
			
			//If we shouldn't be scrolling to a new range, we want to scroll to the top
			if (!shouldScrollToWord) scrollRange = NSMakeRange(0, 0);
			
			[searchWordsArray release];
		}
		
		finalDisplayText = displayText;
	}

	if (finalDisplayText) {
		[[textView_content textStorage] setAttributedString:finalDisplayText];

		//Set this string and scroll to the top/bottom/occurrence
		if ((searchMode == LOG_SEARCH_CONTENT) || automaticSearch) {
			[textView_content scrollRangeToVisible:scrollRange];
		} else {
			[textView_content scrollRangeToVisible:NSMakeRange(0,0)];
		}

	} else {
		//No log selected, empty the view
		[textView_content setString:@""];
	}

	[displayText release];
}

- (void)displayLog:(AIChatLog *)theLog
{
	[self displayLogs:(theLog ? [NSArray arrayWithObject:theLog] : nil)];
}

//Reselect the displayed log (Or another log if not possible)
- (void)selectDisplayedLog
{
    NSInteger     firstIndex = NSNotFound;
    
    /* Is the log we had selected still in the table?
	 * (When performing an automatic search, we ignore the previous selection.  This ensures that we always
     * end up with the newest log selected, even when a search takes multiple passes/refreshes to complete).
	 */
	if (!automaticSearch) {
		[resultsLock lock];
		[tableView_results selectItemsInArray:displayedLogArray usingSourceArray:currentSearchResults];
		[resultsLock unlock];
		
		firstIndex = [[tableView_results selectedRowIndexes] firstIndex];
	}

	if (firstIndex != NSNotFound) {
		[tableView_results scrollRowToVisible:[[tableView_results selectedRowIndexes] firstIndex]];
    } else {
        if (useSame == YES && sameSelection > 0) {
            [tableView_results selectRowIndexes:[NSIndexSet indexSetWithIndex:sameSelection] byExtendingSelection:NO];
        } else {
            [self selectFirstLog];
        }
    }

    useSame = NO;
}

- (void)selectFirstLog
{
	AIChatLog   *theLog = nil;
	
	//If our selected log is no more, select the first one in the list
	[resultsLock lock];
	if ([currentSearchResults count] != 0) {
		theLog = [currentSearchResults objectAtIndex:0];
	}
	[resultsLock unlock];
	
	//Change the table selection to this new log
	//We need a little trickery here.  When we change the row, the table view will call our tableViewSelectionDidChange: method.
	//This method will clear the automaticSearch flag, and break any scroll-to-bottom behavior we have going on for the custom
	//search.  As a quick hack, I've added an ignoreSelectionChange flag that can be set to inform our selectionDidChange method
	//that we instantiated this selection change, and not the user.
	ignoreSelectionChange = YES;
	[tableView_results selectRowIndexes:[NSIndexSet indexSetWithIndex:0] byExtendingSelection:NO];
	[tableView_results scrollRowToVisible:0];
	ignoreSelectionChange = NO;

	[self displayLog:theLog];  //Manually update the displayed log
}

//Highlight the occurences of a search string within a displayed log
- (void)hilightOccurrencesOfString:(NSString *)littleString inString:(NSMutableAttributedString *)bigString firstOccurrence:(NSRange *)outRange
{
    NSInteger					location = 0;
    NSRange				searchRange, foundRange;
    NSString			*plainBigString = [bigString string];
	NSUInteger			plainBigStringLength = [plainBigString length];
	NSMutableDictionary *attributeDictionary = nil;

    outRange->location = NSNotFound;

    //Search for the little string in the big string
    while (location != NSNotFound && location < plainBigStringLength) {
        searchRange = NSMakeRange(location, plainBigStringLength-location);
        foundRange = [plainBigString rangeOfString:littleString options:NSCaseInsensitiveSearch range:searchRange];
		
		//Bold and color this match
        if (foundRange.location != NSNotFound) {
			if (outRange->location == NSNotFound) *outRange = foundRange;

			if (!attributeDictionary) {
				attributeDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
					[NSFont boldSystemFontOfSize:14], NSFontAttributeName,
					[NSColor yellowColor], NSBackgroundColorAttributeName,
					nil];
			}
			[bigString addAttributes:attributeDictionary
							   range:foundRange];
        }

        location = NSMaxRange(foundRange);
    }
}


//Sorting --------------------------------------------------------------------------------------------------------------
#pragma mark Sorting
- (void)resortLogs
{
	NSString *identifier = [selectedColumn identifier];

    //Resort the data
	[resultsLock lock];
    if ([identifier isEqualToString:@"To"]) {
		[currentSearchResults sortUsingSelector:(sortDirection ? @selector(compareToReverse:) : @selector(compareTo:))];
		
    } else if ([identifier isEqualToString:@"From"]) {
        [currentSearchResults sortUsingSelector:(sortDirection ? @selector(compareFromReverse:) : @selector(compareFrom:))];
		
    } else if ([identifier isEqualToString:@"Date"]) {
        [currentSearchResults sortUsingSelector:(sortDirection ? @selector(compareDateReverse:) : @selector(compareDate:))];
		
    } else if ([identifier isEqualToString:@"Rank"]) {
	    [currentSearchResults sortUsingSelector:(sortDirection ? @selector(compareRankReverse:) : @selector(compareRank:))];

	} else if ([identifier isEqualToString:@"Service"]) {
	    [currentSearchResults sortUsingSelector:(sortDirection ? @selector(compareServiceReverse:) : @selector(compareService:))];
	}
	
    [resultsLock unlock];

    //Reload the data
    [tableView_results reloadData];

    //Reapply the selection
    [self selectDisplayedLog];	
}

//Sorts the selected log array and adjusts the selected column
- (void)sortCurrentSearchResultsForTableColumn:(NSTableColumn *)tableColumn direction:(BOOL)direction
{
    //If there already was a sorted column, remove the indicator image from it.
    if (selectedColumn && selectedColumn != tableColumn) {
        [tableView_results setIndicatorImage:nil inTableColumn:selectedColumn];
    }
    
    //Set the indicator image in the newly selected column
    [tableView_results setIndicatorImage:[NSImage imageNamed:(direction ? @"NSDescendingSortIndicator" : @"NSAscendingSortIndicator")]
                           inTableColumn:tableColumn];
    
    //Set the highlighted table column.
    [tableView_results setHighlightedTableColumn:tableColumn];
    [selectedColumn release]; selectedColumn = [tableColumn retain];
    sortDirection = direction;
	
	[self resortLogs];
}

//Searching ------------------------------------------------------------------------------------------------------------
#pragma mark Searching
//(Jag)Change search string
- (void)controlTextDidChange:(NSNotification *)notification
{
    if (searchMode != LOG_SEARCH_CONTENT) {
		[self updateSearch:nil];
    }
}

//Change search string (Called by searchfield)
- (IBAction)updateSearch:(id)sender
{
    automaticSearch = NO;
    [self setSearchString:[[[searchField_logs stringValue] copy] autorelease]];
	AILog(@"updateSearch calling startSearching");
    [self startSearchingClearingCurrentResults:YES];
}

//Change search mode (Called by mode menu)
- (IBAction)selectSearchType:(id)sender
{
    automaticSearch = NO;

	//First, update the search mode to the newly selected type
    [self setSearchMode:[sender tag]]; 
	
	//Then, ensure we are ready to search using the current string
	[self setSearchString:activeSearchString];

	//Now we are ready to start searching
	AILog(@"selectSearchType calling startSearching");
    [self startSearchingClearingCurrentResults:YES];
}

//Begin a specific search
- (void)setSearchString:(NSString *)inString mode:(LogSearchMode)inMode
{
    automaticSearch = YES;
	//Apply the search mode first since the behavior of setSearchString changes depending on the current mode
    [self setSearchMode:inMode];
    [self setSearchString:inString];

	AILog(@"setSearchString:mode: calling startSearching");
    [self startSearchingClearingCurrentResults:YES];
}

//Begin the current search
- (void)startSearchingClearingCurrentResults:(BOOL)clearCurrentResults
{
    NSDictionary    *searchDict;

	if (suppressSearchRequests) return;
	AILog(@"Starting a search for %@",activeSearchString);

    //Once all searches have exited, we can start a new one
	if (clearCurrentResults) {
		[resultsLock lock];
		//Stop any existing searches inside of resultsLock so we won't get any additions results added that we don't want
		[self stopSearching];

		[currentSearchResults release]; currentSearchResults = [[NSMutableArray alloc] init];
		[resultsLock unlock];
	} else {
	    //Stop any existing searches
		[self stopSearching];	
	}

	searching = YES;
	indexingUpdatesReceivedWhileSearching = 0;
    searchDict = [NSDictionary dictionaryWithObjectsAndKeys:
		[NSNumber numberWithInteger:activeSearchID], @"ID",
		[NSNumber numberWithInteger:searchMode], @"Mode",
		activeSearchString, @"String",
		[plugin logContentIndex], @"SearchIndex",
		nil];
    [NSThread detachNewThreadSelector:@selector(filterLogsWithSearch:) toTarget:self withObject:searchDict];
    
	//Update the table periodically while the logs load.
	[refreshResultsTimer invalidate]; [refreshResultsTimer release];
	refreshResultsTimer = [[NSTimer scheduledTimerWithTimeInterval:REFRESH_RESULTS_INTERVAL
															target:self
														  selector:@selector(refreshResults)
														  userInfo:nil
														   repeats:YES] retain];
}

//Abort any active searches
- (void)stopSearching
{
	[currentSearchLock lock];
	if (currentSearch) {
		SKSearchCancel(currentSearch);
		CFRelease(currentSearch); currentSearch = nil;
	}
	[currentSearchLock unlock];
	
	[refreshResultsTimer invalidate]; [refreshResultsTimer release]; refreshResultsTimer = nil;

	//Increase the active search ID so any existing searches stop, and then
	//wait for any active searches to finish and release the lock
	activeSearchID++;
}

//Set the active search mode (Does not invoke a search)
- (void)setSearchMode:(LogSearchMode)inMode
{
	NSTextFieldCell	*cell = [searchField_logs cell];
	
    searchMode = inMode;
	
	//Clear any filter from the table if it's the current mode, as well
	switch (searchMode) {
		case LOG_SEARCH_FROM:
			[cell setPlaceholderString:AILocalizedString(@"Search From","Placeholder for searching logs from an account")];
			break;

		case LOG_SEARCH_TO:
			[cell setPlaceholderString:AILocalizedString(@"Search To","Placeholder for searching logs with/to a contact")];
			break;
			
		case LOG_SEARCH_DATE:
			[cell setPlaceholderString:AILocalizedString(@"Search by Date","Placeholder for searching logs by date")];
			break;

		case LOG_SEARCH_CONTENT:
			[cell setPlaceholderString:AILocalizedString(@"Search Content","Placeholder for searching logs by content")];
			break;
	}

	[self updateRankColumnVisibility];
    [self buildSearchMenu];
}

- (void)updateRankColumnVisibility
{
	NSTableColumn	*resultsColumn = [tableView_results tableColumnWithIdentifier:@"Rank"];
	
	if ((searchMode == LOG_SEARCH_CONTENT) && ([activeSearchString length])) {
		//Add the resultsColumn and resize if it should be shown but is not at present
		if (!resultsColumn) {	
			NSArray			*tableColumns;

			//Set up the results column
			resultsColumn = [[[NSTableColumn alloc] initWithIdentifier:@"Rank"] autorelease];
			[[resultsColumn headerCell] setTitle:AILocalizedString(@"Rank",nil)];
			[resultsColumn setDataCell:[[[ESRankingCell alloc] init] autorelease]];
			
			//Add it to the table
			[tableView_results addTableColumn:resultsColumn];

			//Make it half again as large as the desired width from the @"Rank" header title
			[resultsColumn sizeToFit];
			[resultsColumn setWidth:([resultsColumn width] * 1.5)];
			
			tableColumns = [tableView_results tableColumns];
			if ([tableColumns indexOfObject:resultsColumn] > 0) {
				NSTableColumn	*nextDoorNeighbor;

				//Adjust the column to the results column's left so results is now visible
				nextDoorNeighbor = [tableColumns objectAtIndex:([tableColumns indexOfObject:resultsColumn] - 1)];
				[nextDoorNeighbor setWidth:[nextDoorNeighbor width]-[resultsColumn width]];
			}
		}
	} else {
		//Remove the resultsColumn and resize if it should not be shown but is at present
		if (resultsColumn) {
			NSArray			*tableColumns;

			tableColumns = [tableView_results tableColumns];
			if ([tableColumns indexOfObject:resultsColumn] > 0) {
				NSTableColumn	*nextDoorNeighbor;

				//Adjust the column to the results column's left to take up the space again
				tableColumns = [tableView_results tableColumns];
				nextDoorNeighbor = [tableColumns objectAtIndex:([tableColumns indexOfObject:resultsColumn] - 1)];
				[nextDoorNeighbor setWidth:[nextDoorNeighbor width]+[resultsColumn width]];
			}

			//Remove it
			[tableView_results removeTableColumn:resultsColumn];
		}
	}
}

//Set the active search string (Does not invoke a search)
- (void)setSearchString:(NSString *)inString
{
    if (![[searchField_logs stringValue] isEqualToString:inString]) {
		[searchField_logs setStringValue:(inString ? inString : @"")];
    }
	
	//Use autorelease so activeSearchString can be passed back to here
	if (activeSearchString != inString) {
		[activeSearchString release];
		activeSearchString = [inString retain];
	}

	[self updateRankColumnVisibility];
}

//Build the search mode menu
- (void)buildSearchMenu
{
    NSMenu  *cellMenu = [[[NSMenu allocWithZone:[NSMenu menuZone]] initWithTitle:SEARCH_MENU] autorelease];
    [cellMenu addItem:[self _menuItemWithTitle:FROM forSearchMode:LOG_SEARCH_FROM]];
    [cellMenu addItem:[self _menuItemWithTitle:TO forSearchMode:LOG_SEARCH_TO]];
    [cellMenu addItem:[self _menuItemWithTitle:DATE forSearchMode:LOG_SEARCH_DATE]];
    [cellMenu addItem:[self _menuItemWithTitle:CONTENT forSearchMode:LOG_SEARCH_CONTENT]];

	[[searchField_logs cell] setSearchMenuTemplate:cellMenu];
}

- (void)_willOpenForContact
{
	isOpeningForContact = YES;
}

- (void)_didOpenForContact
{
	isOpeningForContact = NO;
}

/*!
 * @brief Focus the log viewer on a particular contact
 *
 * If the contact is within a metacontact, the metacontact will be focused.
 */
- (void)filterForContact:(AIListContact *)inContact
{
	AIListContact *parentContact = [inContact parentContact];

	if (!isOpeningForContact) {
		/* Ensure the contacts list includes this contact, since only existing AIListContacts are to be used
		* (with AILogToGroup objects used if an AIListContact isn't available) but that situation may have changed
		* with regard to inContact since the log viewer opened.
		*
		* If we're opening initially, the list is guaranteed fresh.
		*/
		[self rebuildContactsList];
	}

	//If the search mode is currently the TO field, switch it to content, which is what it should now intuitively do
	if (searchMode == LOG_SEARCH_TO) {
		[self setSearchMode:LOG_SEARCH_CONTENT];
		
		//Update our search string to ensure we're configured for content searching
		[self setSearchString:activeSearchString];
	}

	//Changing the selection will start a new search
	[outlineView_contacts selectItemsInArray:[NSArray arrayWithObject:(parentContact ? (id)parentContact : (id)allContactsIdentifier)]];
	NSUInteger selectedRow = [[outlineView_contacts selectedRowIndexes] firstIndex];
	if (selectedRow != NSNotFound) {
		[outlineView_contacts scrollRowToVisible:selectedRow];
	}
}

- (void)filterForChatName:(NSString *)chatName withAccount:(AIAccount *)account
{
	if (!isOpeningForContact) {
		// See above.
		[self rebuildContactsList];
	}
	
	AILogToGroup *logToGroup = [logToGroupDict objectForKey:[[NSString stringWithFormat:@"%@.%@",
															  account.service.serviceID,
															  account.UID.safeFilenameString]
															 stringByAppendingPathComponent:chatName]];

	//Changing the selection will start a new search
	[outlineView_contacts selectItemsInArray:[NSArray arrayWithObject:(logToGroup ?: (id)allContactsIdentifier)]];
	NSUInteger selectedRow = [[outlineView_contacts selectedRowIndexes] firstIndex];
	if (selectedRow != NSNotFound) {
		[outlineView_contacts scrollRowToVisible:selectedRow];
	}
}

/*!
 * @brief Returns a menu item for the search mode menu
 */
- (NSMenuItem *)_menuItemWithTitle:(NSString *)title forSearchMode:(LogSearchMode)mode
{
    NSMenuItem  *menuItem = [[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:title 
																				 action:@selector(selectSearchType:) 
																		  keyEquivalent:@""];
    [menuItem setTag:mode];
    [menuItem setState:(mode == searchMode ? NSOnState : NSOffState)];
    
    return [menuItem autorelease];
}

#pragma mark Filtering search results

- (BOOL)chatLogMatchesDateFilter:(AIChatLog *)inChatLog
{
	BOOL matchesDateFilter;

	switch (filterDateType) {
		case AIDateTypeAfter:
			matchesDateFilter = ([[inChatLog date] timeIntervalSinceDate:filterDate] > 0);
			break;
		case AIDateTypeBefore:
			matchesDateFilter = ([[inChatLog date] timeIntervalSinceDate:filterDate] < 0);
			break;
		case AIDateTypeExactly:
			matchesDateFilter = [inChatLog isFromSameDayAsDate:filterDate];
			break;
		default:
			matchesDateFilter = YES;
			break;
	}

	return matchesDateFilter;
}


NSArray *pathComponentsForDocument(SKDocumentRef inDocument)
{
	CFURLRef	url = SKDocumentCopyURL(inDocument);
	if (!url) {
		AILogWithSignature(@"Could not get url for %p", inDocument);
		return nil;
	}

	NSString	*logPath = [(NSURL *)url path];
	if (!logPath)
		AILogWithSignature(@"Could not get path for %@", url);
	NSArray		*pathComponents = [logPath pathComponents];

	CFRelease(url);

	return pathComponents;
}


/*!
 * @brief Should a search display a document with the given information?
 */
- (BOOL)searchShouldDisplayDocument:(SKDocumentRef)inDocument pathComponents:(NSArray *)pathComponents testDate:(BOOL)testDate
{
	BOOL shouldDisplayDocument = YES;

	if ([contactIDsToFilter count]) {
		//Determine the path components if we weren't supplied them
		if (!pathComponents) pathComponents = pathComponentsForDocument(inDocument);

		NSUInteger numPathComponents = [pathComponents count];
		
		NSArray *serviceAndFromUIDArray = [[pathComponents objectAtIndex:numPathComponents-3] componentsSeparatedByString:@"."];
		NSString *serviceClass = (([serviceAndFromUIDArray count] >= 2) ? [serviceAndFromUIDArray objectAtIndex:0] : @"");

		NSString *contactName = [pathComponents objectAtIndex:(numPathComponents-2)];

		shouldDisplayDocument = [contactIDsToFilter containsObject:[[NSString stringWithFormat:@"%@.%@",serviceClass,contactName] compactedString]];
	} 
	
	if (shouldDisplayDocument && testDate && (filterDateType != AIDateTypeAnyDate)) {
		if (!pathComponents) pathComponents = pathComponentsForDocument(inDocument);

		NSUInteger	numPathComponents = [pathComponents count];
		NSString		*toPath = [NSString stringWithFormat:@"%@/%@",
			[pathComponents objectAtIndex:numPathComponents-3],
			[pathComponents objectAtIndex:numPathComponents-2]];
		NSString		*relativePath = [NSString stringWithFormat:@"%@/%@",toPath,[pathComponents objectAtIndex:numPathComponents-1]];
		AIChatLog		*theLog;
		
		theLog = [[logToGroupDict objectForKey:toPath] logAtPath:relativePath];
		
		shouldDisplayDocument = [self chatLogMatchesDateFilter:theLog];
	}

	return shouldDisplayDocument;
}

//Threaded filter/search methods ---------------------------------------------------------------------------------------
#pragma mark Threaded filter/search methods

/*!
 * @brief Perform a content search of the indexed logs
 *
 * This uses the 10.4+ asynchronous search functions.
 * Google-like search syntax (phrase, prefix/suffix, boolean, etc. searching) is automatically supported.
 */
- (void)_logContentFilter:(NSString *)searchString searchID:(NSInteger)searchID onSearchIndex:(SKIndexRef)logSearchIndex
{
	CGFloat			largestRankingValue = 0;
	SKSearchRef		thisSearch;
    Boolean			more = true;
    UInt32			totalCount = 0;
	
	[currentSearchLock lock];
	if (currentSearch) {
		SKSearchCancel(currentSearch);
		CFRelease(currentSearch); currentSearch = NULL;
	}
	
	NSMutableString *wildcardedSearchString = [NSMutableString string];
	for (NSString *searchComponent in [searchString componentsSeparatedByString:@" "]) {
		if ([searchComponent rangeOfString:@"*"].location == NSNotFound) {
			//If the user specifies particular wildcard behavior, respect it
			[wildcardedSearchString appendFormat:@"*%@* ", searchComponent];
		} else
			[wildcardedSearchString appendFormat:@"%@ ", searchComponent];
	}
	
	thisSearch = SKSearchCreate(logSearchIndex,
								(CFStringRef)wildcardedSearchString,
								kSKSearchOptionDefault);
	currentSearch = (thisSearch ? (SKSearchRef)CFRetain(thisSearch) : NULL);
	[currentSearchLock unlock];
	
	//Retrieve matches as long as more are pending
    while (more && currentSearch) {
#define BATCH_NUMBER 100
        SKDocumentID	foundDocIDs[BATCH_NUMBER];
        float			foundScores[BATCH_NUMBER];
        SKDocumentRef	foundDocRefs[BATCH_NUMBER];
		
        CFIndex foundCount = 0;
        CFIndex i;
		
        more = SKSearchFindMatches (
									thisSearch,
									BATCH_NUMBER,
									foundDocIDs,
									foundScores,
									0.5, // maximum time before func returns, in seconds
									&foundCount
									);
		
        totalCount += foundCount;
		
        SKIndexCopyDocumentRefsForDocumentIDs (
											   logSearchIndex,
											   foundCount,
											   foundDocIDs,
											   foundDocRefs
											   );
        for (i = 0; ((i < foundCount) && (searchID == activeSearchID)) ; i++) {
			SKDocumentRef	document = foundDocRefs[i];
					if (!document) {
						AILogWithSignature(@"SearchKit returned NULL document for ID %ld", (long)foundDocIDs[i]);
						totalCount--;
						continue;
					}
			CFURLRef		url = SKDocumentCopyURL(document);
			if (!url) {
				AILogWithSignature(@"No URL for document %p", document);
				totalCount--;
				continue;
			}
			/*
			 * Nasty implementation note: As of 10.4.7 and all previous versions, a path longer than 1024 bytes (PATH_MAX)
			 * will cause CFURLCopyFileSystemPath() to crash [ultimately in CFGetAllocator()].  This is the case for all
			 * Cocoa applications...
			 */
			NSString *logPath = [(NSURL *)url path];
			if (!logPath) 
				AILogWithSignature(@"Could not get path for %@. ", url);
			
			NSArray	 *pathComponents = [(NSString *)logPath pathComponents];
			
			/* Handle chatlogs-as-bundles, which have an xml file inside our target .chatlog path */
			if ([[[pathComponents lastObject] pathExtension] caseInsensitiveCompare:@"xml"] == NSOrderedSame)
				pathComponents = [pathComponents subarrayWithRange:NSMakeRange(0, [pathComponents count] - 1)];
			
			//Don't test for the date now; we'll test once we've found the AIChatLog if we make it that far
			if ([self searchShouldDisplayDocument:document pathComponents:pathComponents testDate:NO]) {
				NSUInteger	numPathComponents = [pathComponents count];
				NSString		*toPath = [NSString stringWithFormat:@"%@/%@",
										   [pathComponents objectAtIndex:numPathComponents-3],
										   [pathComponents objectAtIndex:numPathComponents-2]];
				NSString		*path = [NSString stringWithFormat:@"%@/%@",toPath,[pathComponents objectAtIndex:numPathComponents-1]];
				AIChatLog		*theLog;
				
				/* Add the log - if our index is currently out of date (for example, a log was just deleted) 
				 * we may get a null log, so be careful.
				 */
				theLog = [[logToGroupDict objectForKey:toPath] logAtPath:path];
				if (!theLog) {
					AILog(@"_logContentFilter: %x's key %@ yields %@; logAtPath:%@ gives %@",logToGroupDict,toPath,[logToGroupDict objectForKey:toPath],path,theLog);
				}
				[resultsLock lock];
				if ((theLog != nil) &&
					(![currentSearchResults containsObjectIdenticalTo:theLog]) &&
					[self chatLogMatchesDateFilter:theLog] &&
					(searchID == activeSearchID)) {
					[theLog setRankingValueOnArbitraryScale:foundScores[i]];
					
					//SearchKit does not normalize ranking scores, so we track the largest we've found and use it as 1.0
					if (foundScores[i] > largestRankingValue) largestRankingValue = foundScores[i];
					
					[currentSearchResults addObject:theLog];
				} else {
					//Didn't get a valid log, so decrement our totalCount which is tracking how many logs we found
					totalCount--;
				}
				[resultsLock unlock];					
				
			} else {
				//Didn't add this log, so decrement our totalCount which is tracking how many logs we found
				totalCount--;
			}
			
			//if (logPath) CFRelease(logPath);
			if (url) CFRelease(url);
			if (document) CFRelease(document);
        }
		
		//Scale all logs' ranking values to the largest ranking value we've seen thus far
		[resultsLock lock];
		for (i = 0; ((i < totalCount) && (searchID == activeSearchID)); i++) {
			AIChatLog	*theLog = [currentSearchResults objectAtIndex:i];
			[theLog setRankingPercentage:([theLog rankingValueOnArbitraryScale] / largestRankingValue)];
		}
		[resultsLock unlock];
		
		[self performSelectorOnMainThread:@selector(updateProgressDisplay)
							   withObject:nil
							waitUntilDone:NO];
		
		if (searchID != activeSearchID) {
			more = FALSE;
		}
    }
	
	//Ensure current search isn't released in two places simultaneously
	[currentSearchLock lock];
	if (currentSearch) {
		CFRelease(currentSearch);
		currentSearch = NULL;
	}
	[currentSearchLock unlock];
	
	if (thisSearch) CFRelease(thisSearch);
}

//Search the logs, filtering out any matching logs into the currentSearchResults
- (void)filterLogsWithSearch:(NSDictionary *)searchInfoDict
{
    NSAutoreleasePool       *pool = [[NSAutoreleasePool alloc] init];
    NSInteger                     mode = [[searchInfoDict objectForKey:@"Mode"] integerValue];
    NSInteger                     searchID = [[searchInfoDict objectForKey:@"ID"] integerValue];
    NSString                *searchString = [searchInfoDict objectForKey:@"String"];

    if (searchID == activeSearchID) { //If we're still supposed to go
		searching = YES;
		AILog(@"filterLogsWithSearch (search ID %i): %@",searchID,searchInfoDict);
		//Search
		[plugin pauseIndexing];
		if (searchString && [searchString length]) {
			switch (mode) {
				case LOG_SEARCH_FROM:
				case LOG_SEARCH_TO:
				case LOG_SEARCH_DATE:
					[self _logFilter:searchString
							searchID:searchID
								mode:mode];
					break;
				case LOG_SEARCH_CONTENT:
					[self _logContentFilter:searchString
								   searchID:searchID
							  onSearchIndex:(SKIndexRef)[searchInfoDict objectForKey:@"SearchIndex"]];
					break;
			}
		} else {
			[self _logFilter:nil
					searchID:searchID
						mode:mode];
		}
		
		//Refresh
		searching = NO;
		[plugin resumeIndexing];
		[self performSelectorOnMainThread:@selector(searchComplete) withObject:nil waitUntilDone:NO];
		AILog(@"filterLogsWithSearch (search ID %i): finished",searchID);
    }
	
    //Cleanup
    [pool release];
}

//Perform a filter search based on source name, destination name, or date
- (void)_logFilter:(NSString *)searchString searchID:(NSInteger)searchID mode:(LogSearchMode)mode
{
    UInt32		lastUpdate = TickCount();
    
    NSCalendarDate	*searchStringDate = nil;
	
	if ((mode == LOG_SEARCH_DATE) && (searchString != nil)) {
		searchStringDate = [[NSDate dateWithNaturalLanguageString:searchString]  dateWithCalendarFormat:nil timeZone:nil];
	}
	
    //Walk through every 'from' group
    for (AILogFromGroup *fromGroup in [logFromGroupDict objectEnumerator]) {
		if (searchID != activeSearchID) break;
		
		//When searching in LOG_SEARCH_FROM, we only proceed into matching groups
		if ((mode != LOG_SEARCH_FROM) ||
			(!searchString) || 
			([[fromGroup fromUID] rangeOfString:searchString options:NSCaseInsensitiveSearch].location != NSNotFound)) {

			//Walk through every 'to' group
			for (AILogToGroup *toGroup in [fromGroup toGroupArray]) {
				if (searchID != activeSearchID) break;

				/* When searching in LOG_SEARCH_TO, we only proceed into matching groups
				 * For all other search modes, we always proceed here so long as either:
				 *	a) We are not filtering for specific contact names or
				 *	b) The contact name matches one of the names in contactIDsToFilter
				 */
				if ((![contactIDsToFilter count] || [contactIDsToFilter containsObject:[[NSString stringWithFormat:@"%@.%@",[toGroup serviceClass],[toGroup to]] compactedString]]) &&
				   ((mode != LOG_SEARCH_TO) ||
				   (!searchString) || 
				   ([[toGroup to] rangeOfString:searchString options:NSCaseInsensitiveSearch].location != NSNotFound))) {
					
					//Walk through every log
					for (AIChatLog *theLog in [toGroup logEnumerator]) {
						if (searchID != activeSearchID) break;

						/* When searching in LOG_SEARCH_DATE, we must have matching dates
						 * For all other search modes, we always proceed here
						 */
						if ((mode != LOG_SEARCH_DATE) ||
						   (!searchString) ||
						   (searchStringDate && [theLog isFromSameDayAsDate:searchStringDate])) {

							if ([self chatLogMatchesDateFilter:theLog]) {
								//Add the log
								[resultsLock lock];
								[currentSearchResults addObject:theLog];
								[resultsLock unlock];							
								
								//Update our status
								if (lastUpdate == 0 || TickCount() > lastUpdate + LOG_SEARCH_STATUS_INTERVAL) {
									[self performSelectorOnMainThread:@selector(updateProgressDisplay)
														   withObject:nil
														waitUntilDone:NO];
									lastUpdate = TickCount();
								}
							}
						}
					}
				}
			}	    
		}
    }
}

//Search results table view --------------------------------------------------------------------------------------------
#pragma mark Search results table view
//Since this table view's source data will be accessed from within other threads, we need to lock before
//accessing it.  We also must be very sure that an incorrect row request is handled silently, since this
//can occur if the array size is changed during the reload.
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
    NSInteger count;
    
    [resultsLock lock];
    count = [currentSearchResults count];
    [resultsLock unlock];
    
    return count;
}


- (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    NSString	*identifier = [tableColumn identifier];

	if ([identifier isEqualToString:@"Rank"] && row >= 0 && row < [currentSearchResults count]) {
		AIChatLog       *theLog = [currentSearchResults objectAtIndex:row];
		
		[aCell setPercentage:[theLog rankingPercentage]];
	}
}

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    NSString	*identifier = [tableColumn identifier];
    id          value = nil;
    
    [resultsLock lock];
    if (row < 0 || row >= [currentSearchResults count]) {
		if ([identifier isEqualToString:@"Service"]) {
			value = blankImage;
		} else {
			value = @"";
		}
		
	} else {
		AIChatLog       *theLog = [currentSearchResults objectAtIndex:row];

		if ([identifier isEqualToString:@"To"]) {
			// Get ListObject for to-UID
			AIListObject *listObject = [adium.contactController existingListObjectWithUniqueID:[AIListObject internalObjectIDForServiceID:[theLog serviceClass]
																																		UID:[theLog to]]];
			if (listObject) {
				//Use the longDisplayName, following the user's contact list preferences as this is presumably how she wants to view contacts' names.
				if (![listObject.displayName isEqualToString:listObject.UID]) {
					value = [NSString stringWithFormat:@"%@ (%@)", listObject.displayName, listObject.UID];
				} else {
					value = listObject.formattedUID;
				}

			} else {
				//No username available
				value = [theLog to];
			}
			
		} else if ([identifier isEqualToString:@"From"]) {
			value = [theLog from];
			
		} else if ([identifier isEqualToString:@"Date"]) {
			value = [theLog date];
			
		} else if ([identifier isEqualToString:@"Service"]) {
			NSString	*serviceClass;
			NSImage		*image;
			
			serviceClass = [theLog serviceClass];
			image = [AIServiceIcons serviceIconForService:[adium.accountController firstServiceWithServiceID:serviceClass]
													 type:AIServiceIconSmall
												direction:AIIconNormal];
			value = (image ? image : blankImage);
		}
    }
    [resultsLock unlock];
    
    return value;
}

- (void)tableViewSelectionDidChange:(NSNotification *)notification
{
	[NSObject cancelPreviousPerformRequestsWithTarget:self
											 selector:@selector(tableViewSelectionDidChangeDelayed)
											   object:nil];
	
	[self performSelector:@selector(tableViewSelectionDidChangeDelayed)
			   withObject:nil
			   afterDelay:0.05];
}

- (void)tableViewSelectionDidChangeDelayed
{
    if (!ignoreSelectionChange) {
		NSArray		*selectedLogs;
		
		//Update the displayed log
		automaticSearch = NO;
		
		[resultsLock lock];
		selectedLogs = [tableView_results selectedItemsFromArray:currentSearchResults];
		[resultsLock unlock];
		
		[self displayLogs:selectedLogs];
    }
}

//Sort the log array & reflect the new column
- (void)tableView:(NSTableView*)tableView didClickTableColumn:(NSTableColumn *)tableColumn
{    
    [self sortCurrentSearchResultsForTableColumn:tableColumn
                                   direction:(selectedColumn == tableColumn ? !sortDirection : sortDirection)];
}

- (void)tableViewDeleteSelectedRows:(NSTableView *)tableView
{
	[resultsLock lock];
	NSArray *selectedLogs = [tableView_results selectedItemsFromArray:currentSearchResults];
	[resultsLock unlock];
	
	if ([selectedLogs count] > 0) {
		NSAlert *alert = [self alertForDeletionOfLogCount:[selectedLogs count]];
		[alert beginSheetModalForWindow:[self window] 
						  modalDelegate:self 
						 didEndSelector:@selector(deleteLogsAlertDidEnd:returnCode:contextInfo:) 
							contextInfo:[selectedLogs retain]];
	}
}

- (void)tableViewColumnDidResize:(NSNotification *)aNotification
{
	NSTableColumn *dateTableColumn = [tableView_results tableColumnWithIdentifier:@"Date"];

	if (!aNotification ||
		([[aNotification userInfo] objectForKey:@"NSTableColumn"] == dateTableColumn)) {
		NSDateFormatter *dateFormatter;
		NSCell			*cell = [dateTableColumn dataCell];

		[cell setObjectValue:[NSDate date]];

		CGFloat width = [dateTableColumn width];

#define NUMBER_TIME_STYLES	2
#define NUMBER_DATE_STYLES	4
		NSDateFormatterStyle timeFormatterStyles[NUMBER_TIME_STYLES] = { NSDateFormatterShortStyle, NSDateFormatterNoStyle};
		NSDateFormatterStyle formatterStyles[NUMBER_DATE_STYLES] = { NSDateFormatterFullStyle, NSDateFormatterLongStyle, NSDateFormatterMediumStyle, NSDateFormatterShortStyle };
		CGFloat requiredWidth;

		dateFormatter = [cell formatter];
		if (!dateFormatter) {
			dateFormatter = [[[AILogDateFormatter alloc] init] autorelease];
			[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
			[cell setFormatter:dateFormatter];
		}
		
		requiredWidth = width + 1;
		for (NSInteger i = 0; (i < NUMBER_TIME_STYLES) && (requiredWidth > width); i++) {
			[dateFormatter setTimeStyle:timeFormatterStyles[i]];

			for (NSInteger j = 0; (j < NUMBER_DATE_STYLES) && (requiredWidth > width); j++) {
				[dateFormatter setDateStyle:formatterStyles[j]];
				requiredWidth = [cell cellSizeForBounds:NSMakeRect(0,0,1e6,1e6)].width;
				//Require a bit of space so the date looks comfortable. Very long dates relative to the current date can still overflow...
				requiredWidth += 3;					
			}
		}
	}
}

- (IBAction)toggleEmoticonFiltering:(id)sender
{
	showEmoticons = !showEmoticons;
	[sender setLabel:(showEmoticons ? HIDE_EMOTICONS : SHOW_EMOTICONS)];
	[sender setImage:[NSImage imageNamed:(showEmoticons ? IMAGE_EMOTICONS_ON : IMAGE_EMOTICONS_OFF) forClass:[self class]]];

	[self displayLogs:displayedLogArray];
}

- (IBAction)toggleTimestampFiltering:(id)sender
{
	showTimestamps = !showTimestamps;
	[sender setLabel:(showTimestamps ? HIDE_TIMESTAMPS : SHOW_TIMESTAMPS)];
	[sender setImage:[NSImage imageNamed:(showTimestamps ? IMAGE_TIMESTAMPS_ON : IMAGE_TIMESTAMPS_OFF) forClass:[self class]]];

	[self displayLogs:displayedLogArray];
}

#pragma mark Outline View Data source
- (id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item
{
	if (!item) {
		if (index == 0) {
			return allContactsIdentifier;

		} else {
			return [toArray objectAtIndex:index-1]; //-1 for the All item, which is index 0
		}

	} else {
		if ([item isKindOfClass:[AIMetaContact class]]) {
			return [[(AIMetaContact *)item listContactsIncludingOfflineAccounts] objectAtIndex:index];
		}
	}
	
	return nil;
}

- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item
{
	return (!item || 
			([item isKindOfClass:[AIMetaContact class]] && ([[(AIMetaContact *)item listContactsIncludingOfflineAccounts] count] > 1)) ||
			[item isKindOfClass:[NSArray class]]);
}

- (NSInteger)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item
{
	if (!item) {
		return [toArray count] + 1; //+1 for the All item

	} else if ([item isKindOfClass:[AIMetaContact class]]) {
		NSUInteger count = [[(AIMetaContact *)item listContactsIncludingOfflineAccounts] count];
		if (count > 1)
			return count;
		else
			return 0;

	} else {
		return 0;
	}
}

- (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
{
	Class itemClass = [item class];

	if (itemClass == [AIMetaContact class]) {
		return [(AIMetaContact *)item longDisplayName];
		
	} else if (itemClass == [AIListContact class]) {
		if ([(AIListContact *)item parentContact] != item) {
			//This contact is within a metacontact - always show its UID
			return [(AIListContact *)item formattedUID];
		} else {
			return [(AIListContact *)item longDisplayName];
		} 
		
	} else if (itemClass == [AILogToGroup class]) {
		return [(AILogToGroup *)item to];
		
	} else if (itemClass == [allContactsIdentifier class]) {
		NSUInteger contactCount = [toArray count];
		return [NSString stringWithFormat:AILocalizedString(@"All (%@)", nil),
			((contactCount == 1) ?
			 AILocalizedString(@"1 Contact", nil) :
			 [NSString stringWithFormat:AILocalizedString(@"%lu Contacts", nil), contactCount])]; 

	} else if (itemClass == [NSString class]) {
		return item;

	} else {
		NSLog(@"%@: no idea",item);
		return nil;
	}
}

- (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
{
	if ([item isKindOfClass:[AIMetaContact class]] &&
		[[(AIMetaContact *)item listContactsIncludingOfflineAccounts] count] > 1) {
		/* If the metacontact contains a single contact, fall through (isKindOfClass:[AIListContact class]) and allow using of a service icon.
		 * If it has multiple contacts, use no icon unless a user icon is present.
		 */
		NSImage *image = [AIUserIcons listUserIconForContact:(AIListContact *)item
														size:NSMakeSize(16,16)];
		if (!image) image = [[[NSImage alloc] initWithSize:NSMakeSize(16, 16)] autorelease];

		[cell setImage:image];

	} else if ([item isKindOfClass:[AIListContact class]]) {
		NSImage	*image = [AIUserIcons listUserIconForContact:(AIListContact *)item
														size:NSMakeSize(16,16)];
		if (!image) image = [AIServiceIcons serviceIconForObject:(AIListContact *)item
															type:AIServiceIconSmall
													   direction:AIIconFlipped];
		[cell setImage:image];

	} else if ([item isKindOfClass:[AILogToGroup class]]) {
		[cell setImage:[AIServiceIcons serviceIconForService:[adium.accountController firstServiceWithServiceID:[(AILogToGroup *)item serviceClass]]
														type:AIServiceIconSmall
												   direction:AIIconNormal]];
		
	} else if ([item isKindOfClass:[allContactsIdentifier class]]) {
		if ([[outlineView arrayOfSelectedItems] containsObjectIdenticalTo:item] &&
			([[self window] isKeyWindow] && ([[self window] firstResponder] == self))) {
			if (!adiumIconHighlighted) {
				adiumIconHighlighted = [[NSImage imageNamed:@"adiumHighlight"
												   forClass:[self class]] retain];
			}

			[cell setImage:adiumIconHighlighted];

		} else {
			if (!adiumIcon) {
				adiumIcon = [[NSImage imageNamed:@"adium"
										forClass:[self class]] retain];
			}

			[cell setImage:adiumIcon];
		}

	} else if ([item isKindOfClass:[NSString class]]) {
		[cell setImage:nil];
		
	} else {
		NSLog(@"%@: no idea",item);
		[cell setImage:nil];
	}	
}

/*
 * @brief Is item supposed to have a divider below?
 *
 */
- (AIDividerPosition)outlineView:(NSOutlineView*)outlineView dividerPositionForItem:(id)item
{
	if ([item isKindOfClass:[allContactsIdentifier class]]) {
		return AIDividerPositionBelow;
	} else {
		return AIDividerPositionNone;
	}
}

- (void)outlineViewDeleteSelectedRows:(NSTableView *)tableView
{
	[self deleteSelection:nil];
}


- (void)outlineViewSelectionDidChange:(NSNotification *)notification
{
	[NSObject cancelPreviousPerformRequestsWithTarget:self
											 selector:@selector(outlineViewSelectionDidChangeDelayed)
											   object:nil];
	
	[self performSelector:@selector(outlineViewSelectionDidChangeDelayed)
			   withObject:nil
			   afterDelay:0.05];
}

- (void)outlineViewSelectionDidChangeDelayed
{
	NSArray *selectedItems = [outlineView_contacts arrayOfSelectedItems];

	[contactIDsToFilter removeAllObjects];

	if ([selectedItems count] && ![selectedItems containsObject:allContactsIdentifier]) {
		id		item;

		for (item in selectedItems) {
			if ([item isKindOfClass:[AIMetaContact class]]) {
				for (AIListContact *contact in [(AIMetaContact *)item listContactsIncludingOfflineAccounts]) {
					[contactIDsToFilter addObject:
						[[[NSString stringWithFormat:@"%@.%@", contact.service.serviceID, contact.UID] compactedString] safeFilenameString]];
				}
				
			} else if ([item isKindOfClass:[AIListContact class]]) {
				[contactIDsToFilter addObject:
					[[[NSString stringWithFormat:@"%@.%@",((AIListContact *)item).service.serviceID,((AIListContact *)item).UID] compactedString] safeFilenameString]];
				
			} else if ([item isKindOfClass:[AILogToGroup class]]) {
				[contactIDsToFilter addObject:[[NSString stringWithFormat:@"%@.%@",[(AILogToGroup *)item serviceClass],[(AILogToGroup *)item to]] compactedString]]; 
			}
		}
	}
	
	[self startSearchingClearingCurrentResults:YES];
}

- (NSMenu *)outlineView:(NSOutlineView *)outlineView menuForEvent:(NSEvent *)theEvent;
{
	if (outlineView == outlineView_contacts) {
		NSInteger clickedRow = [outlineView_contacts rowAtPoint:[outlineView_contacts convertPoint:[theEvent locationInWindow]
																					fromView:nil]];
		id item = [outlineView_contacts itemAtRow:clickedRow];

		//If we have a To group, see if we can make a contact out of it
		if ([item isKindOfClass:[AILogToGroup class]]) {
			if ([(AILogToGroup *)item to] && [(AILogToGroup *)item serviceClass]) {
				//We need a service with ther right service ID
				AIService *service = [adium.accountController firstServiceWithServiceID:[(AILogToGroup *)item serviceClass]];
				if (service) {
					//Next, we want an online account
					AIAccount *account = nil;
					for (account in [adium.accountController accountsCompatibleWithService:service]) {
						if (account.online) break;
					}
					
					if (account) {
						//Finally, make a contact
						item = [adium.contactController contactWithService:service
																	 account:account
																		 UID:[(AILogToGroup *)item to]];
					}
					
				}
			}
		}

		if ([item isKindOfClass:[AIListContact class]]) {
			NSArray			*locationsArray = [NSArray arrayWithObjects:
				[NSNumber numberWithInteger:Context_Contact_Message],
				[NSNumber numberWithInteger:Context_Contact_Manage],
				[NSNumber numberWithInteger:Context_Contact_Action],
				[NSNumber numberWithInteger:Context_Contact_ListAction],
				[NSNumber numberWithInteger:Context_Contact_NegativeAction],
				[NSNumber numberWithInteger:Context_Contact_Additions], nil];

			return [adium.menuController contextualMenuWithLocations:locationsArray
														 forListObject:(AIListContact *)item];
		}
	}
	
	return nil;
}

static NSInteger toArraySort(id itemA, id itemB, void *context)
{
	NSString *nameA = [sharedLogViewerInstance outlineView:nil objectValueForTableColumn:nil byItem:itemA];
	NSString *nameB = [sharedLogViewerInstance outlineView:nil objectValueForTableColumn:nil byItem:itemB];
	NSComparisonResult result = [nameA caseInsensitiveCompare:nameB];
	if (result == NSOrderedSame) result = [nameA compare:nameB];

	return result;
}

- (void)draggedDividerRightBy:(CGFloat)deltaX
{	
	desiredContactsSourceListDeltaX = deltaX;
	[splitView_contacts_results resizeSubviewsWithOldSize:[splitView_contacts_results frame].size];
	desiredContactsSourceListDeltaX = 0;
}

/*
- (void)splitView:(NSSplitView *)sender resizeSubviewsWithOldSize:(NSSize)oldSize
{
	if ((sender == splitView_contacts_results) &&
		desiredContactsSourceListDeltaX != 0) {
		float dividerThickness = [sender dividerThickness];

		NSRect newFrame = [sender frame];		
		NSRect leftFrame = [containingView_contactsSourceList frame]; 
		NSRect rightFrame = [containingView_results frame];

		leftFrame.size.width += desiredContactsSourceListDeltaX; 
		leftFrame.size.height = newFrame.size.height;
		leftFrame.origin = NSMakePoint(0,0);

		rightFrame.size.width = newFrame.size.width - leftFrame.size.width - dividerThickness;
		rightFrame.size.height = newFrame.size.height;
		rightFrame.origin.x = leftFrame.size.width + dividerThickness;

		[containingView_contactsSourceList setFrame:leftFrame];
		[containingView_contactsSourceList setNeedsDisplay:YES];
		[containingView_results setFrame:rightFrame];
		[containingView_results setNeedsDisplay:YES];

	} else {
		//Perform the default implementation
		[sender adjustSubviews];
	}
}
*/

//Window Toolbar -------------------------------------------------------------------------------------------------------
#pragma mark Window Toolbar

- (void)installToolbar
{	
	[NSBundle loadNibNamed:[self dateItemNibName] owner:self];

    NSToolbar 		*toolbar = [[[NSToolbar alloc] initWithIdentifier:TOOLBAR_LOG_VIEWER] autorelease];
    NSToolbarItem	*toolbarItem;
	
    [toolbar setDelegate:self];
    [toolbar setDisplayMode:NSToolbarDisplayModeIconAndLabel];
    [toolbar setSizeMode:NSToolbarSizeModeRegular];
    [toolbar setVisible:YES];
    [toolbar setAllowsUserCustomization:YES];
    [toolbar setAutosavesConfiguration:YES];
    toolbarItems = [[NSMutableDictionary alloc] init];

	//Delete Logs
	[AIToolbarUtilities addToolbarItemToDictionary:toolbarItems
                                        withIdentifier:@"delete"
                                                 label:DELETE
                                          paletteLabel:DELETE
                                               toolTip:AILocalizedString(@"Delete the selection",nil)
                                                target:self
                                       settingSelector:@selector(setImage:)
                                           itemContent:[NSImage imageNamed:@"remove" forClass:[self class]]
                                                action:@selector(deleteSelection:)
                                                  menu:nil];
	
	//Search
	[self window]; //Ensure the window is loaded, since we're pulling the search view from our nib
	toolbarItem = [AIToolbarUtilities toolbarItemWithIdentifier:@"search"
														  label:SEARCH
												   paletteLabel:SEARCH
														toolTip:AILocalizedString(@"Search or filter logs",nil)
														 target:self
												settingSelector:@selector(setView:)
													itemContent:view_SearchField
														 action:@selector(updateSearch:)
														   menu:nil];
	if ([toolbarItem respondsToSelector:@selector(setVisibilityPriority:)]) {
		[toolbarItem setVisibilityPriority:(NSToolbarItemVisibilityPriorityHigh + 1)];
	}
	[toolbarItem setMinSize:NSMakeSize(130, NSHeight([view_SearchField frame]))];
	[toolbarItem setMaxSize:NSMakeSize(230, NSHeight([view_SearchField frame]))];
	[toolbarItems setObject:toolbarItem forKey:[toolbarItem itemIdentifier]];

	toolbarItem = [AIToolbarUtilities toolbarItemWithIdentifier:DATE_ITEM_IDENTIFIER
														  label:AILocalizedString(@"Date", nil)
												   paletteLabel:AILocalizedString(@"Date", nil)
														toolTip:AILocalizedString(@"Filter logs by date",nil)
														 target:self
												settingSelector:@selector(setView:)
													itemContent:view_DatePicker
														 action:nil
														   menu:nil];
	if ([toolbarItem respondsToSelector:@selector(setVisibilityPriority:)]) {
		[toolbarItem setVisibilityPriority:NSToolbarItemVisibilityPriorityHigh];
	}
	[toolbarItem setMinSize:[view_DatePicker frame].size];
	[toolbarItem setMaxSize:[view_DatePicker frame].size];
	[toolbarItems setObject:toolbarItem forKey:[toolbarItem itemIdentifier]];

	//Toggle Emoticons
	[AIToolbarUtilities addToolbarItemToDictionary:toolbarItems
									withIdentifier:@"toggleemoticons"
											 label:(showEmoticons ? HIDE_EMOTICONS : SHOW_EMOTICONS)
									  paletteLabel:AILocalizedString(@"Show/Hide Emoticons",nil)
										   toolTip:AILocalizedString(@"Show or hide emoticons in logs",nil)
											target:self
								   settingSelector:@selector(setImage:)
									   itemContent:[NSImage imageNamed:(showEmoticons ? IMAGE_EMOTICONS_ON : IMAGE_EMOTICONS_OFF) forClass:[self class]]
											action:@selector(toggleEmoticonFiltering:)
											  menu:nil];
	// Toggle Timestamps
	[AIToolbarUtilities addToolbarItemToDictionary:toolbarItems
																	withIdentifier:@"toggletimestamps"
																					 label:(showTimestamps ? HIDE_TIMESTAMPS : SHOW_TIMESTAMPS)
																		paletteLabel:AILocalizedString(@"Show/Hide Timestamps", nil)
																				 toolTip:AILocalizedString(@"Show or hide timestamps in logs", nil)
																				  target:self
																 settingSelector:@selector(setImage:)
																		 itemContent:[NSImage imageNamed:(showTimestamps ? IMAGE_TIMESTAMPS_ON : IMAGE_TIMESTAMPS_OFF) forClass:[self class]]
																					action:@selector(toggleTimestampFiltering:)
																						menu:nil];

	[[self window] setToolbar:toolbar];

	[self configureDateFilter];
}

- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
{
    return [AIToolbarUtilities toolbarItemFromDictionary:toolbarItems withIdentifier:itemIdentifier];
}

- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar*)toolbar
{
    return [NSArray arrayWithObjects:DATE_ITEM_IDENTIFIER, NSToolbarFlexibleSpaceItemIdentifier,
		@"delete", @"toggleemoticons", @"toggletimestamps", NSToolbarPrintItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
		@"search", nil];
}

- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar*)toolbar
{
    return [[toolbarItems allKeys] arrayByAddingObjectsFromArray:
		[NSArray arrayWithObjects:NSToolbarSeparatorItemIdentifier,
			NSToolbarSpaceItemIdentifier,
			NSToolbarFlexibleSpaceItemIdentifier,
			NSToolbarCustomizeToolbarItemIdentifier, 
			NSToolbarPrintItemIdentifier, nil]];
}

- (void)toolbarWillAddItem:(NSNotification *)notification
{
	NSToolbarItem *item = [[notification userInfo] objectForKey:@"item"];
	if ([[item itemIdentifier] isEqualToString:NSToolbarPrintItemIdentifier]) {
		[item setTarget:self];
		[item setAction:@selector(adiumPrint:)];
	}
}

#pragma mark Date filter

/*!
 * @brief Returns a menu item for the date type filter menu
 */
- (NSMenuItem *)_menuItemForDateType:(AIDateType)dateType dict:(NSDictionary *)dateTypeTitleDict
{
    NSMenuItem  *menuItem = [[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:[dateTypeTitleDict objectForKey:[NSNumber numberWithInteger:dateType]] 
																				 action:@selector(selectDateType:) 
																		  keyEquivalent:@""];
    [menuItem setTag:dateType];
    
    return [menuItem autorelease];
}

- (NSInteger)daysSinceStartOfWeekGivenToday:(NSCalendarDate *)today
{
	NSInteger todayDayOfWeek = [today dayOfWeek];

	//Try to look at the iCal preferences if possible
	if (!iCalFirstDayOfWeekDetermined) {
		CFPropertyListRef iCalFirstDayOfWeek = CFPreferencesCopyAppValue(CFSTR("first day of week"),CFSTR("com.apple.iCal"));
		if (iCalFirstDayOfWeek) {
			//This should return a CFNumberRef... we're using another app's prefs, so make sure.
			if (CFGetTypeID(iCalFirstDayOfWeek) == CFNumberGetTypeID()) {
				firstDayOfWeek = [(NSNumber *)iCalFirstDayOfWeek integerValue];
			}

			CFRelease(iCalFirstDayOfWeek);
		}

		//Don't check again
		iCalFirstDayOfWeekDetermined = YES;
	}

	return ((todayDayOfWeek >= firstDayOfWeek) ? (todayDayOfWeek - firstDayOfWeek) : ((todayDayOfWeek + 7) - firstDayOfWeek));
}

/*!
 * @brief Select the date type
 */
- (void)selectDateType:(id)sender
{
	[self selectedDateType:[sender tag]];
	[self startSearchingClearingCurrentResults:YES];
}

#pragma mark Open Log

- (void)openLogAtPath:(NSString *)inPath
{
	AIChatLog   *chatLog = nil;
	NSString	*basePath = [AILoggerPlugin logBasePath];

	//inPath should be in a folder of the form SERVICE.ACCOUNT_NAME/CONTACT_NAME/log.extension
	NSArray		*pathComponents = [inPath pathComponents];
	NSInteger			lastIndex = [pathComponents count];
	NSString	*logName = [pathComponents objectAtIndex:--lastIndex];
	NSString	*contactName = [pathComponents objectAtIndex:--lastIndex];
	NSString	*serviceAndAccountName = [pathComponents objectAtIndex:--lastIndex];	
	NSString		*relativeToGroupPath = [serviceAndAccountName stringByAppendingPathComponent:contactName];

	NSString	*serviceID = [[serviceAndAccountName componentsSeparatedByString:@"."] objectAtIndex:0];
	//Filter for logs from the contact associated with the log we're loading
	[self filterForContact:[adium.contactController contactWithService:[adium.accountController firstServiceWithServiceID:serviceID]
																 account:nil
																	 UID:contactName]];
	
	NSString *canonicalBasePath = [basePath stringByStandardizingPath];
	NSString *canonicalInPath = [inPath stringByStandardizingPath];

	if ([canonicalInPath hasPrefix:[canonicalBasePath stringByAppendingString:@"/"]]) {
		AILogToGroup	*logToGroup = [logToGroupDict objectForKey:[serviceAndAccountName stringByAppendingPathComponent:contactName]];
		
		chatLog = [logToGroup logAtPath:[relativeToGroupPath stringByAppendingPathComponent:logName]];
		
	} else {
		/* Different Adium user... this sucks. We're given a path like this:
		 *	/Users/evands/Application Support/Adium 2.0/Users/OtherUser/Logs/AIM.Tekjew/HotChick001/HotChick001 (3-30-2005).AdiumLog
		 * and we want to make it relative to our current user's logs folder, which might be
		 *  /Users/evands/Application Support/Adium 2.0/Users/Default/Logs
		 *
		 * To achieve this, add a "/.." for each directory in our current user's logs folder, then add the full path to the log.
		 */
		NSString	*fakeRelativePath = @"";
		
		//Use .. to get back to the root from the base path
		NSInteger componentsOfBasePath = [[canonicalBasePath pathComponents] count];
		for (NSInteger i = 0; i < componentsOfBasePath; i++) {
			fakeRelativePath = [fakeRelativePath stringByAppendingPathComponent:@".."];
		}
		
		//Now add the path from the root to the actual log
		fakeRelativePath = [fakeRelativePath stringByAppendingPathComponent:canonicalInPath];
		chatLog = [[[AIChatLog alloc] initWithPath:fakeRelativePath
											  from:[serviceAndAccountName substringFromIndex:([serviceID length] + 1)] //One off for the '.'
												to:contactName
									  serviceClass:serviceID] autorelease];
	}

	//Now display the requested log
	if (chatLog) {
		[self displayLog:chatLog];
	}
}

#pragma mark Printing

- (void)adiumPrint:(id)sender
{
	NSTextView			*printView;
    NSPrintOperation    *printOperation;
    NSPrintInfo			*printInfo = [NSPrintInfo sharedPrintInfo];

    [printInfo setHorizontalPagination:NSFitPagination];
    [printInfo setHorizontallyCentered:NO];
    [printInfo setVerticallyCentered:NO];
    
	printView = [[NSTextView alloc] initWithFrame:[[NSPrintInfo sharedPrintInfo] imageablePageBounds]];
    [printView setVerticallyResizable:YES];
    [printView setHorizontallyResizable:NO];
	
    [[printView textStorage] setAttributedString:[textView_content textStorage]];
	
    printOperation = [NSPrintOperation printOperationWithView:printView printInfo:printInfo];
    [printOperation runOperationModalForWindow:[self window] delegate:nil
								didRunSelector:NULL contextInfo:NULL];
	[printView release];
}

- (BOOL)validatePrintMenuItem:(NSMenuItem *)menuItem
{
	return ([displayedLogArray count] > 0);
}

- (BOOL)validateToolbarItem:(NSToolbarItem *)theItem
{
	if ([[theItem itemIdentifier] isEqualToString:NSToolbarPrintItemIdentifier]) {
		return [self validatePrintMenuItem:nil];

	} else {
		return YES;
	}
}

- (void)selectCachedIndex
{
	NSInteger numberOfRows = [tableView_results numberOfRows];
	
	if (cachedSelectionIndex <  numberOfRows) {
		[tableView_results selectRowIndexes:[NSIndexSet indexSetWithIndex:cachedSelectionIndex]
					   byExtendingSelection:NO];
	} else {
		if (numberOfRows)
			[tableView_results selectRowIndexes:[NSIndexSet indexSetWithIndex:(numberOfRows-1)]
						   byExtendingSelection:NO];			
	}

	if (numberOfRows) {
		[tableView_results scrollRowToVisible:[[tableView_results selectedRowIndexes] firstIndex]];
	}

	deleteOccurred = NO;
}

#pragma mark Deletion

/*!
 * @brief Get an NSAlert to request deletion of multiple logs
 */
- (NSAlert *)alertForDeletionOfLogCount:(NSUInteger)logCount
{
	NSAlert *alert = [[NSAlert alloc] init];
	[alert setMessageText:AILocalizedString(@"Delete Logs?",nil)];
	[alert setInformativeText:[NSString stringWithFormat:
		AILocalizedString(@"Are you sure you want to send %lu logs to the Trash?",nil), logCount]];
	[alert addButtonWithTitle:DELETE]; 
	[alert addButtonWithTitle:AILocalizedString(@"Cancel",nil)];
	
	return [alert autorelease];
}

/*!
 * @brief Undo the deletion of one or more AIChatLogs
 *
 * The logs will be marked for readdition to the index
 */
- (void)restoreDeletedLogs:(NSArray *)deletedLogs
{
	AIChatLog		*aLog;
	NSFileManager	*fileManager = [NSFileManager defaultManager];
	NSString		*trashPath = [fileManager findFolderOfType:kTrashFolderType inDomain:kUserDomain createFolder:NO];

	for (aLog in deletedLogs) {
		NSString *logPath = [[AILoggerPlugin logBasePath] stringByAppendingPathComponent:[aLog relativePath]];
		
		[fileManager createDirectoryAtPath:[logPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:NULL];
		
		[fileManager moveItemAtPath:[trashPath stringByAppendingPathComponent:[logPath lastPathComponent]]
							 toPath:logPath 
							  error:NULL];
		
		[plugin markLogDirtyAtPath:logPath];
	}
	
	[self rebuildIndices];
}

- (void)deleteLogsAlertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode  contextInfo:(void *)contextInfo;
{
	NSArray *selectedLogs = (NSArray *)contextInfo;
	if (returnCode == NSAlertFirstButtonReturn) {
		[resultsLock lock];
		
		AIChatLog		*aLog;
		NSMutableSet	*logPaths = [NSMutableSet set];
		
		cachedSelectionIndex = [[tableView_results selectedRowIndexes] firstIndex];
		
		for (aLog in selectedLogs) {
			NSString *logPath = [[AILoggerPlugin logBasePath] stringByAppendingPathComponent:[aLog relativePath]];
			
			[[NSNotificationCenter defaultCenter] postNotificationName:ChatLog_WillDelete object:aLog userInfo:nil];
			AILogToGroup	*logToGroup = [logToGroupDict objectForKey:[[aLog relativePath] stringByDeletingLastPathComponent]];

			// Success will be unused in deployment builds as AILog turns to nothing
#ifdef DEBUG_BUILD
			BOOL success = [logToGroup trashLog:aLog];
			AILog(@"Trashing %@: %i",[aLog relativePath], success);
#else
			[logToGroup trashLog:aLog];
#endif
			//Clear the to group out if it no longer has anything of interest
			if ([logToGroup logCount] == 0) {
				AILogFromGroup	*logFromGroup = [logFromGroupDict objectForKey:[[[aLog relativePath] stringByDeletingLastPathComponent] stringByDeletingLastPathComponent]];
				[logFromGroup removeToGroup:logToGroup];
			}

			[logPaths addObject:logPath];
			[currentSearchResults removeObjectIdenticalTo:aLog];
		}
		
		[plugin removePathsFromIndex:logPaths];
		
		[undoManager registerUndoWithTarget:self
								   selector:@selector(restoreDeletedLogs:)
									 object:selectedLogs];
		[undoManager setActionName:DELETE];
		
		[resultsLock unlock];
		[tableView_results reloadData];
		
		deleteOccurred = YES;
		
		[self rebuildContactsList];
		[self updateProgressDisplay];
	}
	[selectedLogs release];
}

/*!
 * @brief Delete logs
 *
 * If two or more logs are passed, confirmation will be requested.
 * This operation registers with the window controller's undo manager.
 *
 * @param selectedLogs An NSArray of logs to delete
 */
- (void)deleteLogs:(NSArray *)selectedLogs
{	
	if ([selectedLogs count] > 1) {
		NSAlert *alert = [self alertForDeletionOfLogCount:[selectedLogs count]];
		[alert beginSheetModalForWindow:[self window]
						  modalDelegate:self
						 didEndSelector:@selector(deleteLogsAlertDidEnd:returnCode:contextInfo:)
							contextInfo:[selectedLogs retain]];
	} else if ([selectedLogs count] == 1) {
		[self deleteLogsAlertDidEnd:nil
						 returnCode:NSAlertFirstButtonReturn
						contextInfo:[selectedLogs retain]];
	}
}

/*!
 * @brief Returns a set of all selected to groups on all accounts
 *
 * @param totalLogCount If non-NULL, will be set to the total number of logs on return
 */
- (NSArray *)allSelectedToGroups:(NSInteger *)totalLogCount
{
    NSEnumerator        *fromEnumerator;
    AILogFromGroup      *fromGroup;
	NSMutableArray		*allToGroups = [NSMutableArray array];

	if (totalLogCount) *totalLogCount = 0;

    //Walk through every 'from' group
    fromEnumerator = [logFromGroupDict objectEnumerator];
    while ((fromGroup = [fromEnumerator nextObject])) {
		NSEnumerator        *toEnumerator;
		AILogToGroup        *toGroup;

		//Walk through every 'to' group
		toEnumerator = [[fromGroup toGroupArray] objectEnumerator];
		while ((toGroup = [toEnumerator nextObject])) {
			if (![contactIDsToFilter count] || [contactIDsToFilter containsObject:[[NSString stringWithFormat:@"%@.%@",[toGroup serviceClass],[toGroup to]] compactedString]]) {
				if (totalLogCount) {
					*totalLogCount += [toGroup logCount];
				}
				
				[allToGroups addObject:toGroup];
			}
		}
	}

	return allToGroups;
}

/*!
 * @brief Undo the deletion of one or more AILogToGroups and their associated logs
 *
 * The logs will be marked for readdition to the index
 */
- (void)restoreDeletedToGroups:(NSArray *)toGroups
{
	AILogToGroup	*toGroup;
	NSFileManager	*fileManager = [NSFileManager defaultManager];
	NSString		*trashPath = [fileManager findFolderOfType:kTrashFolderType inDomain:kUserDomain createFolder:NO];
	NSString		*logBasePath = [AILoggerPlugin logBasePath];

	for (toGroup in toGroups) {
		NSString *toGroupPath = [logBasePath stringByAppendingPathComponent:[toGroup relativePath]];

		[fileManager createDirectoryAtPath:[toGroupPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:NULL];
		if ([fileManager fileExistsAtPath:toGroupPath]) {
			AILog(@"Removing path %@ to make way for %@",
				  toGroupPath,[trashPath stringByAppendingPathComponent:[toGroupPath lastPathComponent]]);
			[fileManager removeItemAtPath:toGroupPath
									error:NULL];
		}
		[fileManager moveItemAtPath:[trashPath stringByAppendingPathComponent:[toGroupPath lastPathComponent]]
							 toPath:toGroupPath
							  error:NULL];
		
		NSEnumerator *logEnumerator = [toGroup logEnumerator];
		AIChatLog	 *aLog;
	
		while ((aLog = [logEnumerator nextObject])) {
			[plugin markLogDirtyAtPath:[logBasePath stringByAppendingPathComponent:[aLog relativePath]]];
		}
	}
	
	[self rebuildIndices];	
}

- (void)deleteSelectedContactsFromSourceListAlertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo;
{
	NSArray *allSelectedToGroups = (NSArray *)contextInfo;
	if (returnCode == NSAlertFirstButtonReturn) {
		AILogToGroup	*logToGroup;
		NSMutableSet	*logPaths = [NSMutableSet set];
		
		for (logToGroup in allSelectedToGroups) {
			NSEnumerator *logEnumerator;
			AIChatLog	 *aLog;
			
			logEnumerator = [logToGroup logEnumerator];
			while ((aLog = [logEnumerator nextObject])) {
				NSString *logPath = [[AILoggerPlugin logBasePath] stringByAppendingPathComponent:[aLog relativePath]];
				[logPaths addObject:logPath];
			}
			
			AILogFromGroup	*logFromGroup = [logFromGroupDict objectForKey:[NSString stringWithFormat:@"%@.%@",[logToGroup serviceClass],[logToGroup from]]];
			[logFromGroup removeToGroup:logToGroup];
		}
		
		[plugin removePathsFromIndex:logPaths];
		
		[undoManager registerUndoWithTarget:self
								   selector:@selector(restoreDeletedToGroups:)
									 object:allSelectedToGroups];
		[undoManager setActionName:DELETE];
		
		[self rebuildIndices];
		[self updateProgressDisplay];
	}
	
	[allSelectedToGroups release];
}

/*!
 * @brief Delete entirely the logs of all contacts selected in the source list
 *
 * Confirmation by the user will be required.
 *
 * Note: A single item in the source list may have multiple associated AILogToGroups.
 */
- (void)deleteSelectedContactsFromSourceList
{
	NSInteger totalLogCount;
	NSArray *allSelectedToGroups = [self allSelectedToGroups:&totalLogCount];

	if (totalLogCount > 1) {
		NSAlert *alert = [self alertForDeletionOfLogCount:totalLogCount];
		[alert beginSheetModalForWindow:[self window]
						  modalDelegate:self
						 didEndSelector:@selector(deleteSelectedContactsFromSourceListAlertDidEnd:returnCode:contextInfo:)
							contextInfo:[allSelectedToGroups retain]];
	} else {
		[self deleteSelectedContactsFromSourceListAlertDidEnd:nil
												   returnCode:NSAlertFirstButtonReturn
												  contextInfo:[allSelectedToGroups retain]];
	}
}

/*!
 * @brief Delete the current selection
 *
 * If the contacts outline view is selected, one or more contacts' logs will be trashed.
 * If anything else is selected, the currently selected search result logs will be trashed.
 */
- (void)deleteSelection:(id)sender
{
	if ([[self window] firstResponder] == outlineView_contacts) {
		[self deleteSelectedContactsFromSourceList];
		
	} else {
		[resultsLock lock];
		NSArray *selectedLogs = [tableView_results selectedItemsFromArray:currentSearchResults];
		[resultsLock unlock];
		
		[self deleteLogs:selectedLogs];
	}
}

#pragma mark Undo
/*!
 * @brief Supply our undo manager when we are within the responder chain
 */
- (NSUndoManager *)windowWillReturnUndoManager:(NSWindow *)sender
{
	return undoManager;
}

#pragma mark Gestures
/*!
 * @brief Responds to a swipe gesture
 *
 * This is a private method added in AppKit 949.18.0.
 */
- (void)swipeWithEvent:(NSEvent *)inEvent
{
	NSTableView *targetTableView;
	NSInteger changeValue, nextSelected;

	if ([inEvent deltaY] == 0) {
		// For horizontal swipes, switch between individual logs.
		targetTableView = tableView_results;
		changeValue = [inEvent deltaX];
		// Lock the results when we're dealing with the logs tableView
		[resultsLock lock];
	} else {
		// For vertical swipes, switch between contacts.
		targetTableView = outlineView_contacts;
		changeValue = [inEvent deltaY];
	}
	
	// Swipe; +1f is left/up, -1f is right/down
	
	// Find the index of the next row to select.
	if (changeValue == -1) {
		// Going to the right.
		nextSelected = [[targetTableView selectedRowIndexes] lastIndex] + 1;
	} else {
		// Going to the left.
		nextSelected = [[targetTableView selectedRowIndexes] firstIndex] - 1;
	}
	
	// Loop around in circles.
	if (nextSelected >= [targetTableView numberOfRows]) {
		nextSelected = 0;
	} else if (nextSelected < 0) {
		nextSelected = [targetTableView numberOfRows]-1;
	}
	
	// Select either the next row or the previous row.
	[targetTableView selectRowIndexes:[NSIndexSet indexSetWithIndex:nextSelected]
				 byExtendingSelection:NO];
	
	[targetTableView scrollRowToVisible:nextSelected];
	
	if ([inEvent deltaY] == 0)
		[resultsLock unlock];		
}

#pragma mark Transcript services special-casing
NSString *handleSpecialCasesForUIDAndServiceClass(NSString *contactUID, NSString *serviceClass)
{
	/* Jabber and its specified derivative services need special handling;
	 * this is cross-contamination from ESPurpleJabberAccount.
	 */
	if ([serviceClass isEqualToString:@"Jabber"] ||
		[serviceClass isEqualToString:@"GTalk"] ||
		[serviceClass isEqualToString:@"LiveJournal"]) {
		
		if ([contactUID hasSuffix:@"@gmail.com"] ||
			[contactUID hasSuffix:@"@googlemail.com"]) {
			serviceClass = @"GTalk";
			
		} else if ([contactUID hasSuffix:@"@livejournal.com"]){
			serviceClass = @"LiveJournal";
			
		} else {
			serviceClass = @"Jabber";
		}	
		
		/* OSCAR and its specified derivative services need special handling;
		 *  this is cross-contamination from CBPurpleOscarAccount.
		 */
	} else if ([serviceClass isEqualToString:@"AIM"] ||
			   [serviceClass isEqualToString:@"ICQ"] ||
			   [serviceClass isEqualToString:@"Mac"] ||
			   [serviceClass isEqualToString:@"MobileMe"]) {
		const char	firstCharacter = ([contactUID length] ? [contactUID characterAtIndex:0] : '\0');
		
		//Determine service based on UID
		if ([contactUID hasSuffix:@"@mac.com"]) {
			serviceClass = @"Mac";
		} else if ([contactUID hasSuffix:@"@me.com"]) {
			serviceClass = @"MobileMe";
		} else if (firstCharacter && (firstCharacter >= '0' && firstCharacter <= '9')) {
			serviceClass = @"ICQ";
		} else {
			serviceClass = @"AIM";
		}
	}
	
	return serviceClass;
}

#pragma mark Date type menu

- (void)configureDateFilter
{
	firstDayOfWeek = 0; /* Sunday */
	iCalFirstDayOfWeekDetermined = NO;
	
	[popUp_dateFilter setMenu:[self dateTypeMenu]];
	NSInteger index = [popUp_dateFilter indexOfItemWithTag:AIDateTypeAnyDate];
	if(index != NSNotFound)
		[popUp_dateFilter selectItemAtIndex:index];
	[self selectedDateType:AIDateTypeAnyDate];
	
	[datePicker setDateValue:[NSDate date]];
}

- (IBAction)selectDate:(id)sender
{
	[filterDate release];
	filterDate = [[[datePicker dateValue] dateWithCalendarFormat:nil timeZone:nil] retain];
	
	[self startSearchingClearingCurrentResults:YES];
}

- (NSMenu *)dateTypeMenu
{
	NSDictionary *dateTypeTitleDict = [NSDictionary dictionaryWithObjectsAndKeys:
									   AILocalizedString(@"Any Date", nil), [NSNumber numberWithInteger:AIDateTypeAnyDate],
									   AILocalizedString(@"Today", nil), [NSNumber numberWithInteger:AIDateTypeToday],
									   AILocalizedString(@"Since Yesterday", nil), [NSNumber numberWithInteger:AIDateTypeSinceYesterday],
									   AILocalizedString(@"This Week", nil), [NSNumber numberWithInteger:AIDateTypeThisWeek],
									   AILocalizedString(@"Within Last 2 Weeks", nil), [NSNumber numberWithInteger:AIDateTypeWithinLastTwoWeeks],
									   AILocalizedString(@"This Month", nil), [NSNumber numberWithInteger:AIDateTypeThisMonth],
									   AILocalizedString(@"Within Last 2 Months", nil), [NSNumber numberWithInteger:AIDateTypeWithinLastTwoMonths],
									   nil];
	NSMenu	*dateTypeMenu = [[NSMenu alloc] init];
	AIDateType dateType;
	
	[dateTypeMenu addItem:[self _menuItemForDateType:AIDateTypeAnyDate dict:dateTypeTitleDict]];
	[dateTypeMenu addItem:[NSMenuItem separatorItem]];
	
	for (dateType = AIDateTypeToday; dateType < AIDateTypeExactly; dateType++) {
		[dateTypeMenu addItem:[self _menuItemForDateType:dateType dict:dateTypeTitleDict]];
	}
	
	dateTypeTitleDict = [NSDictionary dictionaryWithObjectsAndKeys:
									   AILocalizedString(@"Exactly", nil), [NSNumber numberWithInteger:AIDateTypeExactly],
									   AILocalizedString(@"Before", nil), [NSNumber numberWithInteger:AIDateTypeBefore],
									   AILocalizedString(@"After", nil), [NSNumber numberWithInteger:AIDateTypeAfter],
									   nil];
	
	[dateTypeMenu addItem:[NSMenuItem separatorItem]];		
	
	for (dateType = AIDateTypeExactly; dateType <= AIDateTypeAfter; dateType++) {
		[dateTypeMenu addItem:[self _menuItemForDateType:dateType dict:dateTypeTitleDict]];
	}
	
	return [dateTypeMenu autorelease];
}

/*!
 * @brief A new date type was selected
 *
 * The date picker will be hidden/revealed as appropriate.
 * This does not start a search
 */ 
- (void)selectedDateType:(AIDateType)dateType
{
	BOOL			showDatePicker = NO;
	
	NSCalendarDate	*today = [NSCalendarDate date];
	
	[filterDate release]; filterDate = nil;
	
	switch (dateType) {
		case AIDateTypeAnyDate:
			filterDateType = AIDateTypeAnyDate;
			break;
			
		case AIDateTypeToday:
			filterDateType = AIDateTypeExactly;
			filterDate = [today retain];
			break;
			
		case AIDateTypeSinceYesterday:
			filterDateType = AIDateTypeAfter;
			filterDate = [[today dateByAddingYears:0
											months:0
											  days:-1
											 hours:-[today hourOfDay]
										   minutes:-[today minuteOfHour]
										   seconds:-([today secondOfMinute] + 1)] retain];
			break;
			
		case AIDateTypeThisWeek:
			filterDateType = AIDateTypeAfter;
			filterDate = [[today dateByAddingYears:0
											months:0
											  days:-[self daysSinceStartOfWeekGivenToday:today]
											 hours:-[today hourOfDay]
										   minutes:-[today minuteOfHour]
										   seconds:-([today secondOfMinute] + 1)] retain];
			break;
			
		case AIDateTypeWithinLastTwoWeeks:
			filterDateType = AIDateTypeAfter;
			filterDate = [[today dateByAddingYears:0
											months:0
											  days:-14
											 hours:-[today hourOfDay]
										   minutes:-[today minuteOfHour]
										   seconds:-([today secondOfMinute] + 1)] retain];
			break;
			
		case AIDateTypeThisMonth:
			filterDateType = AIDateTypeAfter;
			filterDate = [[[NSCalendarDate date] dateByAddingYears:0
															months:0
															  days:-[today dayOfMonth]
															 hours:0
														   minutes:0
														   seconds:-1] retain];
			break;
			
		case AIDateTypeWithinLastTwoMonths:
			filterDateType = AIDateTypeAfter;
			filterDate = [[[NSCalendarDate date] dateByAddingYears:0
															months:-1
															  days:-[today dayOfMonth]
															 hours:0
														   minutes:0
														   seconds:-1] retain];			
			break;
			
		default:
			break;
	}		
	
	switch (dateType) {
		case AIDateTypeExactly:
			filterDateType = AIDateTypeExactly;
			filterDate = [[[datePicker dateValue] dateWithCalendarFormat:nil timeZone:nil] retain];
			showDatePicker = YES;
			break;
			
		case AIDateTypeBefore:
			filterDateType = AIDateTypeBefore;
			filterDate = [[[datePicker dateValue] dateWithCalendarFormat:nil timeZone:nil] retain];
			showDatePicker = YES;
			break;
			
		case AIDateTypeAfter:
			filterDateType = AIDateTypeAfter;
			filterDate = [[[datePicker dateValue] dateWithCalendarFormat:nil timeZone:nil] retain];
			showDatePicker = YES;
			break;
			
		default:
			showDatePicker = NO;
			break;
	}
	
	BOOL updateSize = NO;
	if (showDatePicker && [datePicker isHidden]) {
		[datePicker setHidden:NO];		
		updateSize = YES;
		
	} else if (!showDatePicker && ![datePicker isHidden]) {
		[datePicker setHidden:YES];
		updateSize = YES;
	}
	
	if (updateSize) {
		NSEnumerator *enumerator = [[[[self window] toolbar] items] objectEnumerator];
		NSToolbarItem *toolbarItem;
		while ((toolbarItem = [enumerator nextObject])) {
			if ([[toolbarItem itemIdentifier] isEqualToString:DATE_ITEM_IDENTIFIER]) {
				NSSize newSize = NSMakeSize(([datePicker isHidden] ? 180 : 290), NSHeight([view_DatePicker frame]));
				[toolbarItem setMinSize:newSize];
				[toolbarItem setMaxSize:newSize];
				break;
			}
		}		
	}
}

- (NSString *)dateItemNibName
{
	return @"LogViewerDateFilter";
}

@end