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 / Plugins / Purple Service / CBPurpleAccount.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
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
/* 
 * Adium is the legal property of its developers, whose names are listed in the copyright file included
 * with this source distribution.
 * 
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
 * General Public License as published by the Free Software Foundation; either version 2 of the License,
 * or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
 * Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program; if not,
 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#import "CBPurpleAccount.h"

#import "PurpleService.h"

#import <libpurple/notify.h>
#import <libpurple/cmds.h>
#import <AdiumLibpurple/SLPurpleCocoaAdapter.h>
#import <Adium/AIAccount.h>
#import <Adium/AIChat.h>
#import <Adium/AIContentMessage.h>
#import <Adium/AIContentTopic.h>
#import <Adium/AIContentEvent.h>
#import <Adium/AIContentContext.h>
#import <Adium/AIContentNotification.h>
#import <Adium/AIHTMLDecoder.h>
#import <Adium/AIListContact.h>
#import <Adium/AIListGroup.h>
#import <Adium/AIListObject.h>
#import <Adium/AIMetaContact.h>
#import <Adium/AIService.h>
#import <Adium/AIServiceIcons.h>
#import <Adium/AIStatus.h>
#import <Adium/ESFileTransfer.h>
#import <Adium/AIWindowController.h>
#import <Adium/AIEmoticon.h>
#import <Adium/AIAccountControllerProtocol.h>
#import <Adium/AIChatControllerProtocol.h>
#import <Adium/AIContactControllerProtocol.h>
#import <Adium/AIContactObserverManager.h>
#import <Adium/AIContentControllerProtocol.h>
#import <Adium/AIInterfaceControllerProtocol.h>
#import <Adium/AIStatusControllerProtocol.h>
#import <AIUtilities/AIAttributedStringAdditions.h>
#import <AIUtilities/AIDictionaryAdditions.h>
#import <AIUtilities/AIMenuAdditions.h>
#import <AIUtilities/AIMutableOwnerArray.h>
#import <AIUtilities/AIStringAdditions.h>
#import <AIUtilities/AIApplicationAdditions.h>
#import <AIUtilities/AIObjectAdditions.h>
#import <AIUtilities/AIImageAdditions.h>
#import <AIUtilities/AIImageDrawingAdditions.h>
#import <AIUtilities/AIMutableStringAdditions.h>
#import <AIUtilities/AISystemNetworkDefaults.h>
#import <Adium/AdiumAuthorization.h>

#import "ESiTunesPlugin.h"
#import "AMPurpleTuneTooltip.h"
#import "adiumPurpleRequest.h"
#import "AIDualWindowInterfacePlugin.h"

#ifdef HAVE_CDSA
#import "AIPurpleCertificateViewer.h"
#endif

#define NO_GROUP						@"__NoGroup__"

#define	PREF_GROUP_ALIASES			@"Aliases"		//Preference group to store aliases in
#define NEW_ACCOUNT_DISPLAY_TEXT		AILocalizedString(@"<New Account>", "Placeholder displayed as the name of a new account")

#define	KEY_PRIVACY_OPTION	@"Privacy Option"

@interface CBPurpleAccount ()
- (NSString *)_mapIncomingGroupName:(NSString *)name;
- (NSString *)_mapOutgoingGroupName:(NSString *)name;
- (void)setTypingFlagOfChat:(AIChat *)inChat to:(NSNumber *)typingState;
- (void)_receivedMessage:(NSAttributedString *)attributedMessage inChat:(AIChat *)chat fromListContact:(AIListContact *)sourceContact flags:(PurpleMessageFlags)flags date:(NSDate *)date;
- (NSNumber *)shouldCheckMail;
- (void)configurePurpleAccountNotifyingTarget:(id)target selector:(SEL)selector;
- (void)continueConnectWithConfiguredPurpleAccount;
- (void)continueConnectWithConfiguredProxy;
- (void)continueRegisterWithConfiguredPurpleAccount;
- (void)promptForHostBeforeConnecting;
- (void)setAccountProfileTo:(NSAttributedString *)profile configurePurpleAccountContext:(NSInvocation *)inInvocation;
- (void)performAccountMenuAction:(NSMenuItem *)sender;

- (void)showServerCertificate;
@end

@implementation CBPurpleAccount

static SLPurpleCocoaAdapter *purpleAdapter = nil;

// The PurpleAccount currently associated with this Adium account
- (PurpleAccount*)purpleAccount
{
	//Create a purple account if one does not already exist
	if (!account) {
		[self createNewPurpleAccount];
		AILog(@"Created PurpleAccount 0x%x with UID %@, protocolPlugin %s", account, self.UID, [self protocolPlugin]);
	}
	
    return account;
}

- (SLPurpleCocoaAdapter *)purpleAdapter
{
	if (!purpleAdapter) {
		purpleAdapter = [[SLPurpleCocoaAdapter sharedInstance] retain];	
	}	
	return purpleAdapter;
}

// Subclasses must override this
- (const char*)protocolPlugin { return NULL; }

- (PurplePluginProtocolInfo *)protocolInfo
{
	PurplePlugin				*prpl;
	
	if ((prpl = purple_find_prpl(purple_account_get_protocol_id(account)))) {
		return PURPLE_PLUGIN_PROTOCOL_INFO(prpl);
	}
	
	return NULL;
}

// Contacts ------------------------------------------------------------------------------------------------
#pragma mark Contacts
- (void)newContact:(AIListContact *)theContact withName:(NSString *)inName
{

}

- (void)addContact:(AIListContact *)theContact toGroupName:(NSString *)groupName contactName:(NSString *)contactName
{
	//When a new contact is created, if we aren't already silent and delayed, set it  a second to cover our initial
	//status updates
	if (!silentAndDelayed) {
		[self silenceAllContactUpdatesForInterval:2.0];
		[[AIContactObserverManager sharedManager] delayListObjectNotificationsUntilInactivity];		
	}
	
	//If the name we were passed differs from the current formatted UID of the contact, it's itself a formatted UID
	//This is important since we may get an alias ("Evan Schoenberg") from the server but also want the formatted name
	if (![contactName isEqualToString:theContact.formattedUID] && ![contactName isEqualToString:theContact.UID]) {
		[theContact setValue:contactName
							 forProperty:@"FormattedUID"
							 notify:NotifyLater];
	}
	
	if (groupName && [groupName isEqualToString:@PURPLE_ORPHANS_GROUP_NAME]) {
		[theContact addRemoteGroupName:AILocalizedString(@"Orphans","Name for the orphans group")];
	} else if (groupName && [groupName length] != 0) {
		[theContact addRemoteGroupName:[self _mapIncomingGroupName:groupName]];
	} else {
		AILog(@"Got a nil group for %@",theContact);
	}
	
	[self gotGroupForContact:theContact];
}

- (void)removeContact:(AIListContact *)theContact fromGroupName:(NSString *)groupName
{
	NSParameterAssert(groupName != nil); //is this always true?
	NSParameterAssert(theContact != nil);
	[theContact removeRemoteGroupName:[self _mapIncomingGroupName:groupName]];
}

/*!
 * @brief Change the UID of a contact
 *
 * If we're just passed a formatted version of the current UID, don't change the UID but instead use the information
 * as the FormattedUID.  For example, we get sent this when an AIM contact's name formatting changes; we always want
 * to use a lowercase and space-free version for the UID, however.
 */
- (void)renameContact:(AIListContact *)theContact toUID:(NSString *)newUID
{
	//If the name we were passed differs from the current formatted UID of the contact, it's itself a formatted UID
	//This is important since we may get an alias ("Evan Schoenberg") from the server but also want the formatted name
	NSString	*normalizedUID = [self.service normalizeUID:newUID removeIgnoredCharacters:YES];
	
	if ([normalizedUID isEqualToString:theContact.UID]) {
		[theContact setValue:newUID
							 forProperty:@"FormattedUID"
							 notify:NotifyLater];		
	} else {
		[theContact setUID:newUID];		
	}
}

- (void)updateContact:(AIListContact *)theContact toAlias:(NSString *)purpleAlias
{
	if (![[purpleAlias compactedString] isEqualToString:[theContact.UID compactedString]]) {
		//Store this alias as the serverside display name so long as it isn't identical when unformatted to the UID
		[theContact setServersideAlias:purpleAlias
							  silently:silentAndDelayed];

	} else {
		//If it's the same characters as the UID, apply it as a formatted UID
		if (![purpleAlias isEqualToString:theContact.formattedUID] && 
			![purpleAlias isEqualToString:theContact.UID]) {
			[theContact setFormattedUID:purpleAlias
								 notify:NotifyLater];

			//Apply any changes
			[theContact notifyOfChangedPropertiesSilently:silentAndDelayed];
		}
	}
}

- (void)updateContact:(AIListContact *)theContact forEvent:(NSNumber *)event
{
}		


//Signed online
- (void)updateSignon:(AIListContact *)theContact withData:(void *)data
{
	[theContact setOnline:YES
				   notify:NotifyLater
				 silently:silentAndDelayed];

	[theContact notifyOfChangedPropertiesSilently:silentAndDelayed];
}

//Signed offline
- (void)updateSignoff:(AIListContact *)theContact withData:(void *)data
{
	[theContact setOnline:NO
				   notify:NotifyLater
				 silently:silentAndDelayed];
	
	[theContact notifyOfChangedPropertiesSilently:silentAndDelayed];
}

//Signon Time
- (void)updateSignonTime:(AIListContact *)theContact withData:(NSDate *)signonDate
{	
	[theContact setSignonDate:signonDate
					   notify:NotifyLater];
	
	//Apply any changes
	[theContact notifyOfChangedPropertiesSilently:silentAndDelayed];
}

/*!
 * @brief Status name to use for a Purple buddy
 */
- (NSString *)statusNameForPurpleBuddy:(PurpleBuddy *)buddy
{
	return nil;
}

/*!
 * @brief Status message for a contact
 */
- (NSAttributedString *)statusMessageForPurpleBuddy:(PurpleBuddy *)buddy
{
	PurplePresence		*presence = purple_buddy_get_presence(buddy);
	PurpleStatus		*status = (presence ? purple_presence_get_active_status(presence) : NULL);
	const char			*message = (status ? purple_status_get_attr_string(status, "message") : NULL);
	NSString			*statusMessage = nil;
	
	// Get the plugin's status message for this buddy if they don't have a status message
	if (!message) {
		PurplePluginProtocolInfo  *prpl_info = self.protocolInfo;
		
		if (prpl_info && prpl_info->status_text) {
			char *status_text = (prpl_info->status_text)(buddy);
			
			// Don't display "Offline" as a status message.
			if (status_text && strcmp(status_text, _("Offline")) != 0) {
				statusMessage = [NSString stringWithUTF8String:status_text];				
			}
			
			g_free(status_text);
		}
	} else {
		statusMessage = [NSString stringWithUTF8String:message];
	}
	
	return statusMessage ? [AIHTMLDecoder decodeHTML:statusMessage] : nil;
}

/*!
 * @brief Update the status message and away state of the contact
 */
- (void)updateStatusForContact:(AIListContact *)theContact toStatusType:(NSNumber *)statusTypeNumber statusName:(NSString *)statusName statusMessage:(NSAttributedString *)statusMessage isMobile:(BOOL)isMobile
{
	[theContact setStatusWithName:statusName
					   statusType:[statusTypeNumber integerValue]
						   notify:NotifyLater];
	[theContact setStatusMessage:statusMessage
						  notify:NotifyLater];
	[theContact setIsMobile:isMobile notify:NotifyLater];

	//Apply the change
	[theContact notifyOfChangedPropertiesSilently:silentAndDelayed];
}

//Idle time
- (void)updateWentIdle:(AIListContact *)theContact withData:(NSDate *)idleSinceDate
{
	[theContact setIdle:YES sinceDate:idleSinceDate notify:NotifyLater];

	//Apply any changes
	[theContact notifyOfChangedPropertiesSilently:silentAndDelayed];
}
- (void)updateIdleReturn:(AIListContact *)theContact withData:(void *)data
{
	[theContact setIdle:NO
			  sinceDate:nil
				 notify:NotifyLater];

	//Apply any changes
	[theContact notifyOfChangedPropertiesSilently:silentAndDelayed];
}
	
//Evil level (warning level)
- (void)updateEvil:(AIListContact *)theContact withData:(NSNumber *)evilNumber
{
	[theContact setWarningLevel:[evilNumber integerValue]
						 notify:NotifyLater];

	//Apply any changes
	[theContact notifyOfChangedPropertiesSilently:silentAndDelayed];
}


- (void)clearIconForContact:(AIListContact *)theContact
{
	[theContact setServersideIconData:nil
							   notify:NotifyLater];
	
	//Apply any changes
	[theContact notifyOfChangedPropertiesSilently:silentAndDelayed];	
}

//Buddy Icon
- (void)updateIcon:(AIListContact *)theContact withData:(NSData *)userIconData
{
	[NSObject cancelPreviousPerformRequestsWithTarget:self
											 selector:@selector(clearIconForContact:)
											   object:theContact];
	if (userIconData) {
		[theContact setServersideIconData:userIconData
								   notify:NotifyLater];
		
		//Apply any changes
		[theContact notifyOfChangedPropertiesSilently:silentAndDelayed];

	} else {
		/* We may receive an empty icon update just before an actual change. We don't want to flicker through no-icon.
		 * We therefore cancel empty icon updates when we receive a new icon, and we do the actual clearing on a delay in case
		 * this is what is about to happen.
		 */
		[self performSelector:@selector(clearIconForContact:)
				   withObject:theContact
				   afterDelay:10.0];
	}
}

- (NSString *)processedIncomingUserInfo:(NSString *)inString
{
	NSMutableString *returnString = nil;
	if ([inString rangeOfString:@"Purple could not find any information in the user's profile. The user most likely does not exist."].location != NSNotFound) {
		returnString = [[inString mutableCopy] autorelease];
		[returnString replaceOccurrencesOfString:@"Purple could not find any information in the user's profile. The user most likely does not exist."
									  withString:AILocalizedString(@"Adium could not find any information in the user's profile. This may not be a registered name.", "Message shown when a contact's profile can't be found")
										 options:NSLiteralSearch
										   range:NSMakeRange(0, [returnString length])];
	}
	
	return (returnString ? returnString : inString);
}

- (NSString *)webProfileStringForContact:(AIListContact *)contact
{
	return [NSString stringWithFormat:NSLocalizedString(@"View %@'s %@ web profile", nil), 
			contact.formattedUID, [contact.service shortDescription]];
}

- (NSMutableArray *)arrayOfDictionariesFromPurpleNotifyUserInfo:(PurpleNotifyUserInfo *)user_info forContact:(AIListContact *)contact
{
	GList *l;
	NSMutableArray *array = [NSMutableArray array];
	
	for (l = purple_notify_user_info_get_entries(user_info); l != NULL; l = l->next) {
		PurpleNotifyUserInfoEntry *user_info_entry = l->data;
		
		switch (purple_notify_user_info_entry_get_type(user_info_entry)) {
			case PURPLE_NOTIFY_USER_INFO_ENTRY_SECTION_HEADER:
				[array addObject:[NSDictionary dictionaryWithObjectsAndKeys:
								  [NSString stringWithUTF8String:purple_notify_user_info_entry_get_label(user_info_entry)], KEY_KEY,
								  [NSNumber numberWithInteger:AIUserInfoSectionHeader], KEY_TYPE,
								  nil]];
				
				break;
			case PURPLE_NOTIFY_USER_INFO_ENTRY_SECTION_BREAK:
				[array addObject:[NSDictionary dictionaryWithObjectsAndKeys:
								  [NSNumber numberWithInteger:AIUserInfoSectionBreak], KEY_TYPE,
								  nil]];
				break;
				
			case PURPLE_NOTIFY_USER_INFO_ENTRY_PAIR:
			{
				if (purple_notify_user_info_entry_get_label(user_info_entry) && purple_notify_user_info_entry_get_value(user_info_entry)) {
					[array addObject:[NSDictionary dictionaryWithObjectsAndKeys:
									  [NSString stringWithUTF8String:purple_notify_user_info_entry_get_label(user_info_entry)], KEY_KEY,
									  processPurpleImages([NSString stringWithUTF8String:purple_notify_user_info_entry_get_value(user_info_entry)], self), KEY_VALUE,
									  nil]];
					
				} else if (purple_notify_user_info_entry_get_label(user_info_entry)) {
					[array addObject:[NSDictionary dictionaryWithObject:
									  [NSString stringWithUTF8String:purple_notify_user_info_entry_get_label(user_info_entry)]
																 forKey:KEY_KEY]];
				} else if (purple_notify_user_info_entry_get_value(user_info_entry)) {
					NSMutableString	*value = [processPurpleImages([NSString stringWithUTF8String:purple_notify_user_info_entry_get_value(user_info_entry)],
																  self) mutableCopy];
					[value replaceOccurrencesOfString:@"<br>" withString:@"<br/>" options:(NSCaseInsensitiveSearch | NSLiteralSearch)];
					[value replaceOccurrencesOfString:@"<br />" withString:@"<br/>" options:(NSCaseInsensitiveSearch | NSLiteralSearch)];
					[value replaceOccurrencesOfString:@"<B>" withString:@"<b>" options:NSLiteralSearch];

					for (NSString *valuePair in [value componentsSeparatedByString:@"<br/><b>"]) {
						NSRange	firstStartBold = [valuePair rangeOfString:@"<b>"];
						NSRange	firstEndBold = [valuePair rangeOfString:@"</b>"];
						
						if (firstEndBold.length > 0) {
							// Chop off <b> from the beginning and :</b> from the end. The extra -1 is for the colon.
							[array addObject:[NSDictionary dictionaryWithObjectsAndKeys:
											  [valuePair substringWithRange:NSMakeRange(firstStartBold.length, firstEndBold.location-firstStartBold.length-1)], KEY_KEY,
											  [valuePair substringFromIndex:NSMaxRange(firstEndBold)], KEY_VALUE,
											  nil]];
						} else {
							[array addObject:[NSDictionary dictionaryWithObject:valuePair
																		forKey:KEY_VALUE]];
						}
					}
					[value release];
				}	
				break;
			}
		}
	}

	NSString *webProfileValue = [NSString stringWithFormat:@"%s</a>", _("View web profile")];
	
	NSInteger i;
	NSUInteger count = [array count];
	for (i = 0; i < count; i++) {
		NSDictionary *dict = [array objectAtIndex:i];
		NSString *value = [dict objectForKey:KEY_VALUE];
		if (value &&
			[value rangeOfString:webProfileValue options:(NSBackwardsSearch | NSAnchoredSearch | NSLiteralSearch)].location != NSNotFound) {
			NSMutableString *newValue = [[value mutableCopy] autorelease];
			[newValue replaceOccurrencesOfString:webProfileValue
									  withString:[self webProfileStringForContact:contact]
										 options:(NSBackwardsSearch | NSAnchoredSearch | NSLiteralSearch)];
			
			NSMutableDictionary *replacementDict = [dict mutableCopy];
			[replacementDict setObject:newValue forKey:KEY_VALUE];
			[array replaceObjectAtIndex:i withObject:replacementDict];
			[replacementDict release];

			/* There will only be 1 (at most) web profile link */
			break;
		}
	}
	
	return array;
}

- (void)updateUserInfo:(AIListContact *)theContact withData:(PurpleNotifyUserInfo *)user_info
{
	NSArray		*profileContents = [self arrayOfDictionariesFromPurpleNotifyUserInfo:user_info forContact:theContact];

	[theContact setProfileArray:profileContents
					notify:NotifyLater];
	
	[self openInspectorForContactInfo:theContact];
	
	//Apply any changes
	[theContact notifyOfChangedPropertiesSilently:silentAndDelayed];
}

/*!
 * @brief Open the info inspector when getting info
 */
- (void)openInspectorForContactInfo:(AIListContact *)theContact
{

}

/*!
 * @brief Purple removed a contact from the local blist
 *
 * This can happen in many situations:
 *	- For every contact on an account when the account signs off
 *	- For a contact as it is deleted by the user
 *	- For a contact as it is deleted by Purple (e.g. when Sametime refuses an addition because it is known to be invalid)
 *	- In the middle of the move process as a contact moves from one group to another
 *
 * We need not take any action; we'll be notified of changes by Purple as necessary.
 */
- (void)removeContact:(AIListContact *)theContact
{

}

//To allow root level buddies on protocols which don't support them, we map any buddies in a group
//named after this account's UID to the root group.  These functions handle the mapping.  Group names should
//be filtered through incoming before being sent to Adium - and group names from Adium should be filtered through
//outgoing before being used.
- (NSString *)_mapIncomingGroupName:(NSString *)name
{
	if (!name || ([[name compactedString] caseInsensitiveCompare:self.UID] == NSOrderedSame)) {
		return ADIUM_ROOT_GROUP_NAME;
	} else {
		return name;
	}
}
- (NSString *)_mapOutgoingGroupName:(NSString *)name
{
	if ([[name compactedString] caseInsensitiveCompare:ADIUM_ROOT_GROUP_NAME] == NSOrderedSame) {
		return self.UID;
	} else {
		return name;
	}
}

//Update the status of a contact (Request their profile)
- (void)delayedUpdateContactStatus:(AIListContact *)inContact
{
    //Request profile
	AILogWithSignature(@"");
	[purpleAdapter getInfoFor:inContact.UID onAccount:self];
}

- (void)requestAddContactWithUID:(NSString *)contactUID
{
	[adium.contactController requestAddContactWithUID:contactUID
												service:[self _serviceForUID:contactUID]
												account:self];
}

- (AIService *)_serviceForUID:(NSString *)contactUID
{
	return self.service;
}

- (void)gotGroupForContact:(AIListContact *)listContact {};

/*!
 * @brief Return the serverside icon for a contact
 */
- (NSData *)serversideIconDataForContact:(AIListContact *)contact
{
	PurpleBuddy		*buddy;
	NSData			*data = nil;

	if (self.purpleAccount &&
		(buddy = purple_find_buddy(account, [contact.UID UTF8String]))) {
		PurpleBuddyIcon *buddyIcon;
		BOOL			shouldUnref = NO;
		
		/* First, try to get a current buddy icon from the PurpleBuddy */
		buddyIcon = purple_buddy_get_icon(buddy);
		if (!buddyIcon) {
			/* Failing that, load one from the cache. We'll need to unreference the returned PurpleBuddyIcon
			 * when we're done.
			 */
			buddyIcon = purple_buddy_icons_find(account, [contact.UID UTF8String]);
			shouldUnref = YES;
		}
		
		if (buddyIcon) {
			const guchar	*iconData;
			size_t			len;
			
			iconData = purple_buddy_icon_get_data(buddyIcon, &len);
			
			if (iconData && len) {
				data = [NSData dataWithBytes:iconData length:len];
			}
			
			if (shouldUnref)
				purple_buddy_icon_unref(buddyIcon);
		}

	} else {
		AILogWithSignature(@"Could not get serverside icon data for %@. account is %p", contact, account);
	}
	
	return data;
}

/*!
 * @brief Libpurple manages a contact icon cache; we don't need to duplicate it.
 */
- (BOOL)managesOwnContactIconCache
{
	return YES;
}

/*********************/
/* AIAccount_Handles */
/*********************/
#pragma mark Contact List Editing

- (void)removeContacts:(NSArray *)objects fromGroups:(NSArray *)groups
{	
	for (AIListGroup *group in groups) {
		NSString *groupName = [self _mapOutgoingGroupName:group.UID];
	
		for (AIListContact *object in objects) {
			//Have the purple thread perform the serverside actions
			[purpleAdapter removeUID:object.UID onAccount:self fromGroup:groupName];
			
			//Remove it from Adium's list
			[object removeRemoteGroupName:groupName];
		}
	}
}

- (void)addContact:(AIListContact *)contact toGroup:(AIListGroup *)group
{
	NSString		*groupName = [self _mapOutgoingGroupName:group.UID];
	
	if(![group containsObject:contact]) {
		AILogWithSignature(@"%@ adding %@ to %@", self, [self _UIDForAddingObject:contact], groupName);
		
		NSString *alias = [contact.parentContact preferenceForKey:@"Alias"
						   group:PREF_GROUP_ALIASES];
		
		[purpleAdapter addUID:[self _UIDForAddingObject:contact] onAccount:self toGroup:groupName withAlias:alias];
		
		//Add it to Adium's list
		[contact addRemoteGroupName:group.UID]; //Use the non-mapped group name locally
	}
}

- (NSString *)_UIDForAddingObject:(AIListContact *)object
{
	return object.UID;
}

- (NSSet *)mappedGroupNamesFromGroups:(NSSet *)groups
{
	NSMutableSet *mappedNames = [NSMutableSet set];
	
	for (AIListGroup *group in groups) {
		[mappedNames addObject:[self _mapOutgoingGroupName:group.UID]];
	}
	
	return mappedNames;
}

- (void)moveListObjects:(NSArray *)objects fromGroups:(NSSet *)oldGroups toGroups:(NSSet *)groups
{
	NSSet *sourceMappedNames = [self mappedGroupNamesFromGroups:oldGroups];
	NSSet *destinationMappedNames = [self mappedGroupNamesFromGroups:groups];

	//Move the objects to it
	for (AIListContact *contact in objects) {
		if (![contact.remoteGroups intersectsSet:oldGroups] && oldGroups.count) {
			continue;
		}
		
		NSString *alias = [contact.parentContact preferenceForKey:@"Alias"
						   group:PREF_GROUP_ALIASES];
		
		//Tell the purple thread to perform the serverside operation
		[purpleAdapter moveUID:contact.UID onAccount:self fromGroups:sourceMappedNames toGroups:destinationMappedNames withAlias:alias];

		for (AIListGroup *group in oldGroups) {
			[contact removeRemoteGroupName:group.UID];
		}
		
		for (AIListGroup *group in groups) {
			[contact addRemoteGroupName:group.UID];
		}
	}		
}

- (void)renameGroup:(AIListGroup *)inGroup to:(NSString *)newName
{
	NSString		*groupName = [self _mapOutgoingGroupName:inGroup.UID];

	//Tell the purple thread to perform the serverside operation	
	[purpleAdapter renameGroup:groupName onAccount:self to:newName];

	//We must also update the remote grouping of all our contacts in that group
	for (AIListContact *contact in [adium.contactController allContactsInObject:inGroup onAccount:self]) {
		[contact removeRemoteGroupName:groupName];
		//Evan: should we use groupName or newName here?
		[contact addRemoteGroupName:newName];
	}
}

- (void)deleteGroup:(AIListGroup *)inGroup
{
	NSString		*groupName = [self _mapOutgoingGroupName:inGroup.UID];

	[purpleAdapter deleteGroup:groupName onAccount:self];
}

// Return YES if the contact list is editable
- (BOOL)contactListEditable
{
    return self.online;
}

- (id)authorizationRequestWithDict:(NSDictionary*)dict
{
	// We retain this in case libpurple wants to close the request early. It is freed below.
	return [[AdiumAuthorization showAuthorizationRequestWithDict:dict forAccount:self] retain];
}

- (void)authorizationWithDict:(NSDictionary *)infoDict response:(AIAuthorizationResponse)authorizationResponse
{
	if (account) {
		NSValue	*callback = nil;

		switch (authorizationResponse) {
			case AIAuthorizationAllowed:
				callback = [[[infoDict objectForKey:@"authorizeCB"] retain] autorelease];
				break;
			case AIAuthorizationDenied:
				callback = [[[infoDict objectForKey:@"denyCB"] retain] autorelease];
				break;
			case AIAuthorizationNoResponse:
				callback = nil;
				break;
		}
		
		//libpurple will remove its reference to the handle for this request, which is inDict, in response to this callback invocation
		if (callback) {
			[purpleAdapter doAuthRequestCbValue:callback withUserDataValue:[[[infoDict objectForKey:@"userData"] retain] autorelease]];

			/* Retained in -[self authorizationRequestWithDict:].  We kept it around before now in case libpurle wanted us to close it early, such as because the
			 * account disconnected.
			 */
			[infoDict release];
		} else {
			[purpleAdapter closeAuthRequestWithHandle:infoDict];
			
		}
	}
}

#pragma mark Group chat ignore
- (BOOL)accountManagesGroupChatIgnore
{
	return YES;
}

- (BOOL)contact:(AIListContact *)inContact isIgnoredInChat:(AIChat *)chat
{
	if (self.online && chat.isGroupChat) {
		return [purpleAdapter contact:inContact isIgnoredInChat:chat];
	} else {
		return NO;
	}
}

- (void)setContact:(AIListContact *)inContact ignored:(BOOL)inIgnored inChat:(AIChat *)chat
{
	if (self.online && chat.isGroupChat) {
		[purpleAdapter setContact:inContact ignored:inIgnored inChat:chat];
	}
}

//Chats ------------------------------------------------------------
#pragma mark Chats
- (void)removeUser:(NSString *)contactName fromChat:(AIChat *)chat
{
	if (!chat)
		return;
	
	AIListContact *contact = [self contactWithUID:contactName];
	[chat removeObject:contact];
	
	if (contact.isStranger && 
		![adium.chatController allGroupChatsContainingContact:contact.parentContact].count &&
		[adium.chatController existingChatWithContact:contact.parentContact]) {
		// The contact is a stranger, not in any more group chats, but we have a message with them open.
		// Set their status to unknown.
		
		[contact setStatusWithName:nil
						statusType:AIUnknownStatus
							notify:NotifyLater];
		
		[contact setValue:nil
			  forProperty:@"Online"
				   notify:NotifyLater];
		
		[contact notifyOfChangedPropertiesSilently:NO];
	}
}

- (void)removeUsersArray:(NSArray *)usersArray fromChat:(AIChat *)chat
{
	for (NSString *contactName in usersArray) {
		[self removeUser:contactName fromChat:chat];
	}
}

- (void)updateUserListForChat:(AIChat *)chat users:(NSArray *)users newlyAdded:(BOOL)newlyAdded
{
	NSMutableArray *newListObjects = [NSMutableArray array];
	
	for (NSDictionary *user in users) {
		AIListContact *contact = [self contactWithUID:[user objectForKey:@"UID"]];
		
		[contact setOnline:YES notify:NotifyNever silently:YES];
		
		[newListObjects addObject:contact];
	}
	
	[chat addParticipatingListObjects:newListObjects notify:newlyAdded];
	
	for (NSDictionary *user in users) {
		AIListContact *contact = [self contactWithUID:[user objectForKey:@"UID"]];
		
		[chat setFlags:(AIGroupChatFlags)[[user objectForKey:@"Flags"] integerValue] forContact:contact];
		
		if ([user objectForKey:@"Alias"]) {
			[chat setAlias:[user objectForKey:@"Alias"] forContact:contact];
			
			if (contact.isStranger) {
				[contact setServersideAlias:[user objectForKey:@"Alias"] silently:NO];
			}
		}
	}
	
	// Post an update notification now that we've modified the flags and names.
	[[NSNotificationCenter defaultCenter] postNotificationName:Chat_ParticipatingListObjectsChanged
														object:chat];
}

- (void)renameParticipant:(NSString *)oldUID newName:(NSString *)newUID newAlias:(NSString *)newAlias flags:(AIGroupChatFlags)flags inChat:(AIChat *)chat
{
	[chat removeSavedValuesForContactUID:oldUID];
	
	AIListContact *contact = [adium.contactController existingContactWithService:self.service account:self UID:oldUID];

	if (contact) {
		[adium.contactController setUID:newUID forContact:contact];
	} else {
		contact = [self contactWithUID:newUID];
	}

	[chat setFlags:flags forContact:contact];
	[chat setAlias:newAlias forContact:contact];
	
	if (contact.isStranger) {
		[contact setServersideAlias:newAlias silently:NO];
	}

	// Post an update notification since we modified the user entirely.
	[[NSNotificationCenter defaultCenter] postNotificationName:Chat_ParticipatingListObjectsChanged
														object:chat];
}

- (void)setAttribute:(NSString *)name value:(NSString *)value forContact:(AIListContact *)contact
{
	NSString *property = nil;
	
	if ([name isEqualToString:@"userhost"]) {
		property = @"User Host";
	} else if ([name isEqualToString:@"realname"]) {
		property = @"Real Name";
	} else {
		AILog(@"Unknown attribute: %@ value %@", name, value);
	}
	
	if (property) {
		// Callsite should notify.
		[contact setValue:value forProperty:property notify:NotifyLater];
	}
}


- (void)updateUser:(NSString *)user
		   forChat:(AIChat *)chat
			 flags:(AIGroupChatFlags)flags
			 alias:(NSString *)alias
		attributes:(NSDictionary *)attributes
{
	BOOL triggerUserlistUpdate = NO;
	
	AIListContact *contact = [self contactWithUID:user];
	
	AIGroupChatFlags oldFlags = [chat flagsForContact:contact];
	NSString *oldAlias = [chat aliasForContact:contact];
	
	// Trigger an update if the alias or flags (ignoring away state) changes.
	if ((alias && !oldAlias)
		|| (!alias && oldAlias)
		|| ![[chat aliasForContact:contact] isEqualToString:alias]
		|| (flags & ~AIGroupChatAway) != (oldFlags & ~AIGroupChatAway)) {
		triggerUserlistUpdate = YES;
	}

	[chat setAlias:alias forContact:contact];
	[chat setFlags:flags forContact:contact];
	
	// Away changes only come in after the initial one, so we're safe in only updating it here.
	if (contact.isStranger) {
		[contact setStatusWithName:nil
						statusType:((flags & AIGroupChatAway) == AIGroupChatAway) ? AIAwayStatusType : AIAvailableStatusType
							notify:NotifyLater];
	}

	for (NSString *key in attributes.allKeys) {
		[self setAttribute:key value:[attributes objectForKey:key] forContact:contact];
	}
	
	[contact notifyOfChangedPropertiesSilently:YES];
	
	// Post an update notification if we modified the flags; don't resort for away changes.
	if (triggerUserlistUpdate) {
		[[NSNotificationCenter defaultCenter] postNotificationName:Chat_ParticipatingListObjectsChanged
															object:chat];
	}
}

/*!
 * @brief Called by Purple code when a chat should be opened by the interface
 *
 * If the user sent an initial message, this will be triggered and have no effect.
 *
 * If a remote user sent an initial message, however, a chat will be created without being opened.  This call is our
 * cue to actually open chat.
 *
 * Another situation in which this is relevant is when we request joining a group chat; the chat should only be actually
 * opened once the server notifies us that we are in the room.
 *
 * This will ultimately call -[CBPurpleAccount openChat:] below if the chat was not previously open.
 */
- (void)addChat:(AIChat *)chat
{
	AILogWithSignature(@"");

	//Open the chat
	if ([chat isOpen]) {
		if ([chat boolValueForProperty:@"Rejoining Chat"]) {
			[self displayYouHaveConnectedInChat:chat];
			
			[chat setValue:nil forProperty:@"Rejoining Chat" notify:NotifyNever];
		}
	}

	[adium.interfaceController openChat:chat];
	
	[chat setValue:[NSNumber numberWithBool:YES] forProperty:@"Account Joined" notify:NotifyNow];
}

//Open a chat for Adium
- (BOOL)openChat:(AIChat *)chat
{
	/* The #if 0'd block below causes crashes in msn_tooltip_text() on MSN */
#if 0
	AIListContact	*listContact;
	
	//Obtain the contact's information if it's a stranger
	if ((listContact = chat.listObject) && (listContact.isStranger)) {
		[self delayedUpdateContactStatus:listContact];
	}
#endif
	
	AILog(@"purple openChat:%@ for %@",chat,chat.uniqueChatID);

	//Inform purple that we have opened this chat
	[purpleAdapter openChat:chat onAccount:self];
	
	//Created the chat successfully
	return YES;
}

- (BOOL)closeChat:(AIChat*)chat
{
	[purpleAdapter closeChat:chat];
	
	if (!chat.isGroupChat) {
		//Be sure any remaining typing flag is cleared as the chat closes
		[self setTypingFlagOfChat:chat to:nil];
	}
	
	AILog(@"purple closeChat:%@",chat.uniqueChatID);
	
    return YES;
}

- (void)chatWasDestroyed:(AIChat *)chat
{
	[adium.chatController accountDidCloseChat:chat];
}

- (void)chatJoinDidFail:(AIChat *)chat
{
	[adium.chatController accountDidCloseChat:chat];
}

/* 
 * @brief Rejoin a chat
 */
- (BOOL)rejoinChat:(AIChat *)chat
{
	[chat retain];

	PurpleConversation *conv = [[chat identifier] pointerValue];
	if (conv && conv->ui_data) {
		[(AIChat *)(conv->ui_data) release];
		conv->ui_data = NULL;
	}

	/* The identifier is how we associate a PurpleConversation with an AIChat.
	 * Clear the identifier so a new PurpleConversation will be made. The ChatCreationInfo for the chat is still around, so it can join.
	 */
	[chat setIdentifier:nil];
	
	[chat setValue:[NSNumber numberWithBool:YES] forProperty:@"Rejoining Chat" notify:NotifyNever];
	
	[purpleAdapter openChat:chat onAccount:self];

	[chat autorelease];

	//We don't get any immediate feedback as to our success; just return YES.
	return YES;
}

/*!
 * @brief A chat will be joined
 *
 * This gives the account a chance to update any information in the chat's creation dictionary if desired.
 *
 * @result The final chat creation dictionary to use.
 */
- (NSDictionary *)willJoinChatUsingDictionary:(NSDictionary *)chatCreationDictionary
{
	return chatCreationDictionary;
}

- (BOOL)chatCreationDictionary:(NSDictionary *)chatCreationDict isEqualToDictionary:(NSDictionary *)baseDict
{
	return [chatCreationDict isEqualToDictionary:baseDict];
}

- (NSDictionary *)extractChatCreationDictionaryFromConversation:(PurpleConversation *)conv
{
	AILog(@"%@ needs an implementation of extractChatCreationDictionaryFromConversation to handle rejoins, bookmarks, and invitations properly", NSStringFromClass([self class]));
	return nil;
}

- (AIChat *)chatWithContact:(AIListContact *)contact identifier:(id)identifier
{
	AIChat *chat = [adium.chatController chatWithContact:contact];
	[chat setIdentifier:identifier];

	return chat;
}


- (AIChat *)chatWithName:(NSString *)name identifier:(id)identifier
{
	return [adium.chatController chatWithName:name identifier:identifier onAccount:self chatCreationInfo:nil];
}

//Typing update in an IM
- (void)typingUpdateForIMChat:(AIChat *)chat typing:(NSNumber *)typingState
{
	[self setTypingFlagOfChat:chat
						   to:typingState];
}

//Multiuser chat update
- (void)convUpdateForChat:(AIChat *)chat type:(NSNumber *)type
{

}

/*!
 * @brief Called when we are informed that we left a multiuser chat
 */
- (void)leftChat:(AIChat *)chat
{
	[chat setValue:nil forProperty:@"Account Joined" notify:NotifyNow];
}

- (void)updateTopic:(NSString *)inTopic forChat:(AIChat *)chat withSource:(NSString *)source
{	
	// Update (not set) the chat's topic
	[chat updateTopic:inTopic withSource:[self contactWithUID:source]];
}

/*!
 * @brief Set a chat's topic
 *
 * This only has an effect on group chats.
 */
- (void)setTopic:(NSString *)topic forChat:(AIChat *)chat
{
	if (!chat.isGroupChat) {
		return;
	}
	
	PurplePluginProtocolInfo  *prpl_info = self.protocolInfo;
	
	if (prpl_info && prpl_info->set_chat_topic) {
		(prpl_info->set_chat_topic)(purple_account_get_connection(account),
									purple_conv_chat_get_id(purple_conversation_get_chat_data(convLookupFromChat(chat, self))),
									[topic UTF8String]);
	}
}


- (void)updateTitle:(NSString *)inTitle forChat:(AIChat *)chat
{
	[[chat displayArrayForKey:@"Display Name"] setObject:inTitle
											   withOwner:self];
}

- (void)updateForChat:(AIChat *)chat type:(NSNumber *)type
{
	AIChatUpdateType	updateType = [type integerValue];
	NSString			*key = nil;
	switch (updateType) {
		case AIChatTimedOut:
		case AIChatClosedWindow:
			break;
	}
	
	if (key) {
		[chat setValue:[NSNumber numberWithBool:YES] forProperty:key notify:NotifyNow];
		[chat setValue:nil forProperty:key notify:NotifyNever];
		
	}
}

- (void)errorForChat:(AIChat *)chat type:(NSNumber *)type
{
	[chat receivedError:type];
}

- (void)receivedIMChatMessage:(NSDictionary *)messageDict inChat:(AIChat *)chat
{
	PurpleMessageFlags		flags = [[messageDict objectForKey:@"PurpleMessageFlags"] integerValue];

	NSAttributedString		*attributedMessage;
	AIListContact			*listContact;
	
	listContact = chat.listObject;

	attributedMessage = [adium.contentController decodedIncomingMessage:[messageDict objectForKey:@"Message"]
															  fromContact:listContact
																onAccount:self];
	
	//Clear the typing flag of the chat since a message was just received
	[self setTypingFlagOfChat:chat to:nil];
	
	[self _receivedMessage:attributedMessage
					inChat:chat 
		   fromListContact:listContact
					 flags:flags
					  date:[messageDict objectForKey:@"Date"]];
}

- (void)receivedEventForChat:(AIChat *)chat
					 message:(NSString *)message
						date:(NSDate *)date
					   flags:(NSNumber *)flagsNumber
{
	PurpleMessageFlags flags = [flagsNumber integerValue];
	
	AIContentEvent *event = [AIContentEvent eventInChat:chat
											 withSource:nil
											destination:self
												   date:date
												message:[AIHTMLDecoder decodeHTML:message]
											   withType:@"purple"];
	
	event.filterContent = (flags & PURPLE_MESSAGE_NO_LINKIFY) != PURPLE_MESSAGE_NO_LINKIFY;
	
	[adium.contentController receiveContentObject:event];
}

- (void)receivedMultiChatMessage:(NSDictionary *)messageDict inChat:(AIChat *)chat
{	
	PurpleMessageFlags	flags = [[messageDict objectForKey:@"PurpleMessageFlags"] integerValue];
	NSAttributedString	*attributedMessage = [messageDict objectForKey:@"AttributedMessage"];;
	NSString			*source = [messageDict objectForKey:@"Source"];
	
	[self _receivedMessage:attributedMessage
					inChat:chat 
		   fromListContact:[self contactWithUID:source]
					 flags:flags
					  date:[messageDict objectForKey:@"Date"]];
}

- (void)_receivedMessage:(NSAttributedString *)attributedMessage inChat:(AIChat *)chat fromListContact:(AIListContact *)sourceContact flags:(PurpleMessageFlags)flags date:(NSDate *)date
{
	if ((flags & PURPLE_MESSAGE_DELAYED) == PURPLE_MESSAGE_DELAYED) {
		// Display delayed messages as context.

		AIContentContext *messageObject = [AIContentContext messageInChat:chat
															   withSource:sourceContact
															  destination:self
																	 date:date
																  message:attributedMessage
																autoreply:(flags & PURPLE_MESSAGE_AUTO_RESP) != 0];
		
		messageObject.trackContent = NO;
		
		[adium.contentController receiveContentObject:messageObject];
		
	} else {
		AIContentMessage *messageObject = [AIContentMessage messageInChat:chat
															   withSource:sourceContact
															  destination:self
																	 date:date
																  message:attributedMessage
																autoreply:(flags & PURPLE_MESSAGE_AUTO_RESP) != 0];
		
		[adium.contentController receiveContentObject:messageObject];	
	}
}

/*********************/
/* AIAccount_Content */
/*********************/
#pragma mark Content
- (void)sendTypingObject:(AIContentTyping *)inContentTyping
{
	AIChat *chat = inContentTyping.chat;

	if (!chat.isGroupChat) {
		[purpleAdapter sendTyping:inContentTyping.typingState inChat:chat];
	}
}

- (BOOL)sendMessageObject:(AIContentMessage *)inContentMessage
{
	PurpleMessageFlags		flags = PURPLE_MESSAGE_RAW;
	
	if ([inContentMessage isAutoreply]) {
		flags |= PURPLE_MESSAGE_AUTO_RESP;
	}

	[purpleAdapter sendEncodedMessage:[inContentMessage encodedMessage]
						 fromAccount:self
							  inChat:inContentMessage.chat
						   withFlags:flags];

	return YES;
}

- (BOOL)supportsSendingNotifications
{
	return (account ? ((PURPLE_PLUGIN_PROTOCOL_INFO(purple_find_prpl(purple_account_get_protocol_id(account)))->send_attention) != NULL) : NO);
}

- (BOOL)sendNotificationObject:(AIContentNotification *)inContentNotification
{
	[purpleAdapter sendNotificationOfType:[inContentNotification notificationType]
							  fromAccount:self
								   inChat:inContentNotification.chat];	
	
	return YES;
}

/*!
 * @brief Return the string encoded for sending to a remote contact
 *
 * We return nil if the string turns out to have been a / command.
 */
- (NSString *)encodedAttributedStringForSendingContentMessage:(AIContentMessage *)inContentMessage
{
	BOOL		didCommand = [purpleAdapter attemptPurpleCommandOnMessage:[inContentMessage.message string]
														 fromAccount:(AIAccount *)[inContentMessage source]
															  inChat:inContentMessage.chat];	
	
	return (didCommand ? nil : [super encodedAttributedStringForSendingContentMessage:inContentMessage]);
}

/*!
 * @brief Libpurple prints file transfer messages to the chat window. The Adium core therefore shouldn't.
 */
- (BOOL)accountDisplaysFileTransferMessages
{
	return YES;
}

/*!
 * @brief Available for sending content
 *
 * Returns YES if the contact is available for receiving content of the specified type.  If contact is nil, instead
 * check for the availiability to send any content of the given type.
 *
 * We override the default implementation to check -[self allowFileTransferWithListObject:] for file transfers
 *
 * @param inType A string content type
 * @param inContact The destination contact, or nil to check global availability
 */
- (BOOL)availableForSendingContentType:(NSString *)inType toContact:(AIListContact *)inContact
{
    if (self.online && [inType isEqualToString:CONTENT_FILE_TRANSFER_TYPE]) {
		if (inContact) {
			return ([self conformsToProtocol:@protocol(AIAccount_Files)] &&
					((inContact.online || inContact.isStranger) && [self allowFileTransferWithListObject:inContact]));
		} else {
			return [self conformsToProtocol:@protocol(AIAccount_Files)];
		}
	}

    return [super availableForSendingContentType:inType toContact:inContact];
}

- (BOOL)allowFileTransferWithListObject:(AIListObject *)inListObject
{
	PurplePluginProtocolInfo *prpl_info = self.protocolInfo;

	if (prpl_info && prpl_info->send_file)
		return (!prpl_info->can_receive_file || prpl_info->can_receive_file(purple_account_get_connection(account), [inListObject.UID UTF8String]));
	else
		return NO;
}

- (BOOL)supportsAutoReplies
{
	if (account && purple_account_get_connection(account)) {
		return ((purple_account_get_connection(account)->flags & PURPLE_CONNECTION_AUTO_RESP) != 0);
	}
	
	return NO;
}

- (BOOL)canSendOfflineMessageToContact:(AIListContact *)inContact
{
	PurplePluginProtocolInfo *prpl_info = self.protocolInfo;

	if (prpl_info && prpl_info->offline_message) {
		
		return (prpl_info->offline_message(purple_find_buddy(account, [inContact.UID UTF8String])));

	} else
		return NO;
	
}

#pragma mark Custom emoticons
- (void)chat:(AIChat *)inChat isWaitingOnCustomEmoticon:(NSString *)emoticonEquivalent
{
	AIEmoticon *emoticon;

	//Look for an existing emoticon with this equivalent
	for (emoticon in inChat.customEmoticons) {
		if ([[emoticon textEquivalents] containsObject:emoticonEquivalent]) break;
	}
	
	if (!emoticon) {
		emoticon = [AIEmoticon emoticonWithIconPath:nil
										equivalents:[NSArray arrayWithObject:emoticonEquivalent]
											   name:emoticonEquivalent
											   pack:nil];
		[inChat addCustomEmoticon:emoticon];			
	}
	
	if (![emoticon path]) {
		[emoticon setPath:[[NSBundle bundleForClass:[CBPurpleAccount class]] pathForResource:@"missing_image"
																					ofType:@"png"]];
	}
}

/*!
 * @brief Return the path at which to save an emoticon
 */
- (NSString *)_emoticonCachePathForEmoticon:(NSString *)emoticonEquivalent type:(AIBitmapImageFileType)fileType inChat:(AIChat *)inChat
{
	static unsigned long long emoticonID = 0;
    NSString    *filename = [NSString stringWithFormat:@"TEMP-CustomEmoticon_%@_%@_%qu.%@",
		[inChat uniqueChatID], emoticonEquivalent, emoticonID++, [NSImage extensionForBitmapImageFileType:fileType]];
    return [[adium cachesPath] stringByAppendingPathComponent:[filename safeFilenameString]];	
}


- (void)chat:(AIChat *)inChat setCustomEmoticon:(NSString *)emoticonEquivalent withImageData:(NSData *)inImageData
{
	/* XXX Note: If we can set outgoing emoticons, this method needs to be updated to mark emoticons as incoming
	 * and AIEmoticonController needs to be able to handle that.
	 */
	AIEmoticon	*emoticon;

	//Look for an existing emoticon with this equivalent
	for (emoticon in inChat.customEmoticons) {
		if ([[emoticon textEquivalents] containsObject:emoticonEquivalent]) break;
	}
	
	//Write out our image
	NSString	*path = [self _emoticonCachePathForEmoticon:emoticonEquivalent
													   type:[NSImage fileTypeOfData:inImageData]
													 inChat:inChat];
	[inImageData writeToFile:path
				  atomically:NO];

	if (emoticon) {
		//If we already have an emoticon, just update its path
		[emoticon setPath:path];

	} else {
		emoticon = [AIEmoticon emoticonWithIconPath:path
										equivalents:[NSArray arrayWithObject:emoticonEquivalent]
											   name:emoticonEquivalent
											   pack:nil];
		[inChat addCustomEmoticon:emoticon];
	}
}

- (void)chat:(AIChat *)inChat closedCustomEmoticon:(NSString *)emoticonEquivalent
{
	AIEmoticon	*emoticon;

	//Look for an existing emoticon with this equivalent
	for (emoticon in inChat.customEmoticons) {
		if ([[emoticon textEquivalents] containsObject:emoticonEquivalent]) break;
	}
	
	if (emoticon) {
		[[NSNotificationCenter defaultCenter] postNotificationName:@"AICustomEmoticonUpdated"
												  object:inChat
												userInfo:[NSDictionary dictionaryWithObject:emoticon
																					 forKey:@"AIEmoticon"]];
	} else {
		//This shouldn't happen; chat:setCustomEmoticon:withImageData: should have already been called.
		emoticon = [AIEmoticon emoticonWithIconPath:nil
										equivalents:[NSArray arrayWithObject:emoticonEquivalent]
											   name:emoticonEquivalent
											   pack:nil];
		NSLog(@"Warning: closed custom emoticon %@ without adding it to the chat", emoticon);
		AILog(@"Warning: closed custom emoticon %@ without adding it to the chat", emoticon);
	}
}

/*********************/
/* AIAccount_Privacy */
/*********************/
#pragma mark Privacy
- (BOOL)addListObject:(AIListObject *)inObject toPrivacyList:(AIPrivacyType)type
{
    if (type == AIPrivacyTypePermit)
        return (purple_privacy_permit_add(account,[inObject.UID UTF8String],FALSE));
    else
        return (purple_privacy_deny_add(account,[inObject.UID UTF8String],FALSE));
}

- (BOOL)removeListObject:(AIListObject *)inObject fromPrivacyList:(AIPrivacyType)type
{
    if (type == AIPrivacyTypePermit)
        return (purple_privacy_permit_remove(account,[inObject.UID UTF8String],FALSE));
    else
        return (purple_privacy_deny_remove(account,[inObject.UID UTF8String],FALSE));
}

- (NSArray *)listObjectsOnPrivacyList:(AIPrivacyType)type
{
	NSMutableArray	*array = [NSMutableArray array];
	if (account) {
		GSList			*list;
		GSList			*sourceList = ((type == AIPrivacyTypePermit) ? account->permit : account->deny);
		
		for (list = sourceList; (list != NULL); list=list->next) {
			[array addObject:[self contactWithUID:[NSString stringWithUTF8String:(char *)list->data]]];
		}
	}

	return array;
}

- (void)accountPrivacyList:(AIPrivacyType)type added:(NSString *)sourceUID
{
	//Can't really trust sourceUID to not be @"" or something silly like that
	if ([sourceUID length]) {
		//Get our contact
		AIListContact   *contact = [self contactWithUID:sourceUID];

		//Update Adium's knowledge of it
		[contact setIsBlocked:((type == AIPrivacyTypeDeny) ? YES : NO) updateList:NO];
	}
}

- (void)privacyPermitListAdded:(NSString *)sourceUID
{
	[self accountPrivacyList:AIPrivacyTypePermit added:sourceUID];
}

- (void)privacyDenyListAdded:(NSString *)sourceUID
{
	[self accountPrivacyList:AIPrivacyTypeDeny added:sourceUID];
}

- (void)accountPrivacyList:(AIPrivacyType)type removed:(NSString *)sourceUID
{
	//Can't really trust sourceUID to not be @"" or something silly like that
	if ([sourceUID length]) {
		if (!namesAreCaseSensitive) {
			sourceUID = [sourceUID compactedString];
		}

		//Get our contact, which must already exist for us to care about its removal
		AIListContact   *contact = [adium.contactController existingContactWithService:service
																				 account:self
																					 UID:sourceUID];
		
		if (contact) {			
			//Update Adium's knowledge of it
			[contact setIsBlocked:((type == AIPrivacyTypeDeny) ? NO : YES) updateList:NO];
		}
	}
}

- (void)privacyPermitListRemoved:(NSString *)sourceUID
{
	[self accountPrivacyList:AIPrivacyTypePermit removed:sourceUID];
}

- (void)privacyDenyListRemoved:(NSString *)sourceUID
{
	[self accountPrivacyList:AIPrivacyTypeDeny removed:sourceUID];
}

- (void)setPrivacyOptions:(AIPrivacyOption)option
{
	if (account && purple_account_get_connection(account)) {
		PurplePrivacyType privacyType;

		switch (option) {
			case AIPrivacyOptionAllowAll:
			default:
				privacyType = PURPLE_PRIVACY_ALLOW_ALL;
				break;
			case AIPrivacyOptionDenyAll:
				privacyType = PURPLE_PRIVACY_DENY_ALL;
				break;
			case AIPrivacyOptionAllowUsers:
				privacyType = PURPLE_PRIVACY_ALLOW_USERS;
				break;
			case AIPrivacyOptionDenyUsers:
				privacyType = PURPLE_PRIVACY_DENY_USERS;
				break;
			case AIPrivacyOptionAllowContactList:
				privacyType = PURPLE_PRIVACY_ALLOW_BUDDYLIST;
				break;
			
		}
		
		if (account->perm_deny != privacyType) {
			account->perm_deny = privacyType;
			serv_set_permit_deny(purple_account_get_connection(account));
			AILog(@"Set privacy options for %@ (%x %x) to %i",
				  self,account,purple_account_get_connection(account),account->perm_deny);

			[self setPreference:[NSNumber numberWithInteger:option]
						 forKey:KEY_PRIVACY_OPTION
						  group:GROUP_ACCOUNT_STATUS];			
		}
	} else {
		AILog(@"Couldn't set privacy options for %@ (%x %x)",self,account,purple_account_get_connection(account));
	}
}

- (AIPrivacyOption)privacyOptions
{
	AIPrivacyOption privacyOption = -1;
	
	if (account) {
		PurplePrivacyType privacyType = account->perm_deny;
		
		switch (privacyType) {
			case PURPLE_PRIVACY_ALLOW_ALL:
			default:
				privacyOption = AIPrivacyOptionAllowAll;
				break;
			case PURPLE_PRIVACY_DENY_ALL:
				privacyOption = AIPrivacyOptionDenyAll;
				break;
			case PURPLE_PRIVACY_ALLOW_USERS:
				privacyOption = AIPrivacyOptionAllowUsers;
				break;
			case PURPLE_PRIVACY_DENY_USERS:
				privacyOption = AIPrivacyOptionDenyUsers;
				break;
			case PURPLE_PRIVACY_ALLOW_BUDDYLIST:
				privacyOption = AIPrivacyOptionAllowContactList;
				break;
		}
	}
	AILog(@"%@: privacyOptions are %i",self,privacyOption);
	return privacyOption;
}

/*****************************************************/
/* File transfer / AIAccount_Files inherited methods */
/*****************************************************/
#pragma mark File Transfer
- (BOOL)canSendFolders
{
	return NO;
}

//Create a protocol-specific xfer object, set it up as requested, and begin sending
- (void)_beginSendOfFileTransfer:(ESFileTransfer *)fileTransfer
{
	PurpleXfer *xfer = [self newOutgoingXferForFileTransfer:fileTransfer];
	
	if (xfer) {
		//Associate the fileTransfer and the xfer with each other
		[fileTransfer setAccountData:[NSValue valueWithPointer:xfer]];
		xfer->ui_data = [fileTransfer retain];
		
		//Set the filename
		purple_xfer_set_local_filename(xfer, [[fileTransfer localFilename] UTF8String]);
		purple_xfer_set_filename(xfer, [[[fileTransfer localFilename] lastPathComponent] UTF8String]);
		
		/*
		 Request that the transfer begins.
		 We will be asked to accept it via:
			- (void)acceptFileTransferRequest:(ESFileTransfer *)fileTransfer
		 below.
		 */
		[purpleAdapter xferRequest:xfer];
		[fileTransfer setStatus: Waiting_on_Remote_User_FileTransfer];
	}
}
//By default, protocols can not create PurpleXfer objects
- (PurpleXfer *)newOutgoingXferForFileTransfer:(ESFileTransfer *)fileTransfer
{
	PurpleXfer				*newPurpleXfer = NULL;

	if (account && purple_account_get_connection(account)) {
		PurplePluginProtocolInfo  *prpl_info = self.protocolInfo;

		if (prpl_info && prpl_info->new_xfer) {
			char *destsn = (char *)[[[fileTransfer contact] UID] UTF8String];
			newPurpleXfer = (prpl_info->new_xfer)(purple_account_get_connection(account), destsn);
		}
	}

	return newPurpleXfer;
}

/* 
 * @brief The account requested that we received a file.
 *
 * Set up the ESFileTransfer and query the fileTransferController for a save location.
 * 
 */
- (void)requestReceiveOfFileTransfer:(ESFileTransfer *)fileTransfer
{
	AILog(@"File transfer request received: %@",fileTransfer);
	[adium.fileTransferController receiveRequestForFileTransfer:fileTransfer];
}

//Create an ESFileTransfer object from an xfer
- (ESFileTransfer *)newFileTransferObjectWith:(NSString *)destinationUID
										 size:(unsigned long long)inSize
							   remoteFilename:(NSString *)remoteFilename
{
	AIListContact   *contact = [self contactWithUID:destinationUID];
    ESFileTransfer	*fileTransfer;
	
	fileTransfer = [adium.fileTransferController newFileTransferWithContact:contact
																   forAccount:self
																		 type:Unknown_FileTransfer]; 
	[fileTransfer setSize:inSize];
	[fileTransfer setRemoteFilename:remoteFilename];
	
    return fileTransfer;
}

//Update an ESFileTransfer object progress
- (void)updateProgressForFileTransfer:(ESFileTransfer *)fileTransfer percent:(NSNumber *)percent bytesSent:(NSNumber *)bytesSent
{
	CGFloat percentDone = [percent doubleValue];
    [fileTransfer setPercentDone:percentDone bytesSent:[bytesSent unsignedLongValue]];
}

//The local side cancelled the transfer.  We probably already have this status set, but set it just in case.
- (void)fileTransferCancelledLocally:(ESFileTransfer *)fileTransfer
{
	if (![fileTransfer isStopped]) {
		[fileTransfer setStatus:Cancelled_Local_FileTransfer];
	}
}

//The remote side cancelled the transfer, the fool. Update our status.
- (void)fileTransferCancelledRemotely:(ESFileTransfer *)fileTransfer
{
	if (![fileTransfer isStopped]) {
		[fileTransfer setStatus:Cancelled_Remote_FileTransfer];
	}
}

- (void)destroyFileTransfer:(ESFileTransfer *)fileTransfer
{
	AILog(@"Destroy file transfer %@",fileTransfer);
	[fileTransfer release];
}

//Accept a send or receive ESFileTransfer object, beginning the transfer.
//Subsequently inform the fileTransferController that the fun has begun.
- (void)acceptFileTransferRequest:(ESFileTransfer *)fileTransfer
{
    AILog(@"Accepted file transfer %@",fileTransfer);
	
	PurpleXfer		*xfer;
	PurpleXferType	xferType;
	
	xfer = [[fileTransfer accountData] pointerValue];

    xferType = purple_xfer_get_type(xfer);
    if (xferType == PURPLE_XFER_SEND) {
        [fileTransfer setFileTransferType:Outgoing_FileTransfer];

    } else if (xferType == PURPLE_XFER_RECEIVE) {
        [fileTransfer setFileTransferType:Incoming_FileTransfer];
		[fileTransfer setSize:purple_xfer_get_size(xfer)];
    }
    
    //accept the request
	[purpleAdapter xferRequestAccepted:xfer withFileName:[fileTransfer localFilename]];
	
	[fileTransfer setStatus:Accepted_FileTransfer];
}

//User refused a receive request.  Tell purple; we don't release the ESFileTransfer object
//since that will happen when the xfer is destroyed.  This will end up calling back on
//- (void)fileTransfercancelledLocally:(ESFileTransfer *)fileTransfer
- (void)rejectFileReceiveRequest:(ESFileTransfer *)fileTransfer
{
	PurpleXfer	*xfer = [[fileTransfer accountData] pointerValue];
	if (xfer) {
		[purpleAdapter xferRequestRejected:xfer];
	}
}

//Cancel a file transfer in progress.  Tell purple; we don't release the ESFileTransfer object
//since that will happen when the xfer is destroyed.  This will end up calling back on
//- (void)fileTransfercancelledLocally:(ESFileTransfer *)fileTransfer
- (void)cancelFileTransfer:(ESFileTransfer *)fileTransfer
{
	PurpleXfer	*xfer = [[fileTransfer accountData] pointerValue];
	if (xfer) {
		[purpleAdapter xferCancel:xfer];
	}	
}

//Account Connectivity -------------------------------------------------------------------------------------------------
#pragma mark Connect
//Connect this account (Our password should be in the instance variable 'password' all ready for us)
- (void)connect
{
	finishedConnectProcess = NO;

	[super connect];

	//Ensure we have a purple account if one does not already exist
	[self purpleAccount];
	
	//Make sure our settings are correct
	if ([self connectivityBasedOnNetworkReachability] &&
		![self.host length]) {
		//If we use the network for connectivity, and we don't have a host, we need to get ourselves one. Prompt for it!
		[self promptForHostBeforeConnecting];
	} else {
		[self configurePurpleAccountNotifyingTarget:self selector:@selector(continueConnectWithConfiguredPurpleAccount)];
	}
}

- (void)unregister
{
	finishedConnectProcess = NO;

	[purpleAdapter unregisterAccount:self];
}

static void prompt_host_cancel_cb(CBPurpleAccount *self) {
	[self disconnect];
}


static void prompt_host_ok_cb(CBPurpleAccount *self, const char *host) {
	if(host && *host) {
		[self setPreference:[NSString stringWithUTF8String:host]
					 forKey:KEY_CONNECT_HOST
					  group:GROUP_ACCOUNT_STATUS];	

		[self configurePurpleAccountNotifyingTarget:self selector:@selector(continueConnectWithConfiguredPurpleAccount)];
	} else {
		prompt_host_cancel_cb(self);
	}
}

- (void)promptForHostBeforeConnecting
{
	purple_request_input(NULL, [[NSString stringWithFormat:AILocalizedString(@"%@ (%@) Setup", "first %@ is an account name; second is a service. This is a title for a window"),
								self.formattedUID, [self.service shortDescription]] UTF8String],
						 [AILocalizedString(@"No Server Specified", nil) UTF8String],
						 [[NSString stringWithFormat:AILocalizedString(@"No server has been configured for the %@ account %@. Please enter one below to connect", nil),
						   [self.service longDescription], self.formattedUID] UTF8String],
						 /* default value */ "", /* multiline */ FALSE, /* masked */ FALSE, /* hint */ NULL,
						 [AILocalizedString(@"Connect", "Button title to connect; this is a verb") UTF8String], G_CALLBACK(prompt_host_ok_cb),
						 [AILocalizedString(@"Cancel", nil) UTF8String], G_CALLBACK(prompt_host_cancel_cb),
						 /* account */ NULL, /* who */ NULL, /* conv */ NULL,
						 self);
						 
}


- (void)continueConnectWithConfiguredPurpleAccount
{
	//Configure libpurple's proxy settings; continueConnectWithConfiguredProxy will be called once we are ready
	[self configureAccountProxyNotifyingTarget:self selector:@selector(continueConnectWithConfiguredProxy)];
}

- (void)continueConnectWithConfiguredProxy
{
	//Set password and connect
	purple_account_set_password(account, [password UTF8String]);

	//Set our current status state after filtering its statusMessage as appropriate. This will take us online in the process.
	AIStatus	*statusState = [self valueForProperty:@"StatusState"];
	if (!statusState || (statusState.statusType == AIOfflineStatusType)) {
		statusState = [adium.statusController defaultInitialStatusState];
	}

	AILog(@"Adium: Connect: %@ initiating connection using status state %@ (%@).",self.UID,statusState,
			  [statusState statusMessageString]);

	[self autoRefreshingOutgoingContentForStatusKey:@"StatusState"
										   selector:@selector(gotFilteredStatusMessage:forStatusState:)
											context:statusState];
}

//Make sure our settings are correct; notify target/selector when we're finished
- (void)configurePurpleAccountNotifyingTarget:(id)target selector:(SEL)selector
{
	NSInvocation	*contextInvocation;
	
	//Perform the synchronous configuration activities (subclasses may want to take action in this function)
	[self configurePurpleAccount];
	
	contextInvocation = [NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]];
	
	[contextInvocation setTarget:target];
	[contextInvocation setSelector:selector];
	[contextInvocation retainArguments];

	//Set the text profile BEFORE beginning the connect process, to avoid problems with setting it while the
	//connect occurs. Once that's done, contextInvocation will be invoked, continuing the configurePurpleAccount process.
	[self autoRefreshingOutgoingContentForStatusKey:@"TextProfile" 
										   selector:@selector(setAccountProfileTo:configurePurpleAccountContext:)
											context:contextInvocation];
}

/*!
 * @brief The server name to be passed to libpurple
 * By default, this is the host as seen by the rest of Adium.  Subclasses may choose to override this if
 * some trickery is desired between what is told to libpurple and what the rest of Adium sees.
 */
- (NSString *)hostForPurple
{
	return self.host;
}

//Synchronous purple account configuration activites, always performed after an account is created.
//This is a definite subclassing point so prpls can apply their own account settings.
- (void)configurePurpleAccount
{
	NSString	*hostName;
	NSInteger			portNumber;

	//Host (server)
	hostName = [self hostForPurple];
	if (hostName && [hostName length]) {
		purple_account_set_string(account, "server", [hostName UTF8String]);
	}
	
	//Port
	portNumber = [self port];
	if (portNumber) {
		purple_account_set_int(account, "port", portNumber);
	}
	
	//E-mail checking
	purple_account_set_check_mail(account, [[self shouldCheckMail] boolValue]);
	
	//Custom Emoticons
	BOOL customEmoticons = [[self preferenceForKey:KEY_DISPLAY_CUSTOM_EMOTICONS group:GROUP_ACCOUNT_STATUS] boolValue];
	purple_account_set_bool(account, "custom_smileys", customEmoticons);
	
	//Update a few properties before we begin connecting.  Libpurple will send these automatically
    [self updateStatusForKey:KEY_USER_ICON];
}

/*!
 * @brief Configure libpurple's proxy settings using the current system values
 *
 * target/selector are used rather than a hardcoded callback (or getProxyConfigurationNotifyingTarget: directly) because this allows code reuse
 * between the connect and register processes, which are similar in their need for proxy configuration
 */
- (void)configureAccountProxyNotifyingTarget:(id)target selector:(SEL)selector
{
	NSInvocation		*invocation; 

	//Configure the invocation we will use when we are done configuring
	invocation = [NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]];
	[invocation setSelector:selector];
	[invocation setTarget:target];
	
	[self getProxyConfigurationNotifyingTarget:self
									  selector:@selector(retrievedProxyConfiguration:context:)
									   context:invocation];
}

/*!
 * @brief Callback for -[self getProxyConfigurationNotifyingTarget:selector:context:]
 */
- (void)retrievedProxyConfiguration:(NSDictionary *)proxyConfig context:(NSInvocation *)invocation
{
	PurpleProxyInfo		*proxy_info;
	
	AdiumProxyType  	proxyType = [[proxyConfig objectForKey:@"AdiumProxyType"] integerValue];
	
	proxy_info = purple_proxy_info_new();
	purple_account_set_proxy_info(account, proxy_info);

	PurpleProxyType		purpleAccountProxyType;
	
	switch (proxyType) {
		case Adium_Proxy_HTTP:
		case Adium_Proxy_Default_HTTP:
			purpleAccountProxyType = PURPLE_PROXY_HTTP;
			break;
		case Adium_Proxy_SOCKS4:
		case Adium_Proxy_Default_SOCKS4:
			purpleAccountProxyType = PURPLE_PROXY_SOCKS4;
			break;
		case Adium_Proxy_SOCKS5:
		case Adium_Proxy_Default_SOCKS5:
			purpleAccountProxyType = PURPLE_PROXY_SOCKS5;
			break;
		case Adium_Proxy_None:
		default:
			purpleAccountProxyType = PURPLE_PROXY_NONE;
			break;
	}
	
	purple_proxy_info_set_type(proxy_info, purpleAccountProxyType);

	if (proxyType != Adium_Proxy_None) {
		purple_proxy_info_set_host(proxy_info, (char *)[[proxyConfig objectForKey:@"Host"] UTF8String]);
		purple_proxy_info_set_port(proxy_info, [[proxyConfig objectForKey:@"Port"] integerValue]);

		purple_proxy_info_set_username(proxy_info, (char *)[[proxyConfig objectForKey:@"Username"] UTF8String]);
		purple_proxy_info_set_password(proxy_info, (char *)[[proxyConfig objectForKey:@"Password"] UTF8String]);
		
		AILog(@"Connecting with proxy type %i and proxy host %@",proxyType, [proxyConfig objectForKey:@"Host"]);
	}

	[invocation invoke];
}

//Sublcasses should override to provide a string for each progress step
- (NSString *)connectionStringForStep:(NSInteger)step { return nil; };

/*!
 * @brief Should the account's status be updated as soon as it is connected?
 *
 * If YES, the StatusState and IdleSince properties will be told to update as soon as the account connects.
 * This will allow the account to send its status information to the server upon connecting.
 *
 * If this information is already known by the account at the time it connects and further prompting to send it is
 * not desired, return NO.
 *
 * libpurple should already have been told of our status before connecting began.
 */
- (BOOL)updateStatusImmediatelyAfterConnecting
{
	return NO;
}

- (void)didConnect
{
	finishedConnectProcess = YES;

	[super didConnect];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(iTunesDidUpdate:) name:Adium_iTunesTrackChangedNotification object:nil];

	//Silence updates
	[self silenceAllContactUpdatesForInterval:18.0];
	[[AIContactObserverManager sharedManager] delayListObjectNotificationsUntilInactivity];
	
	//Clear any previous disconnection error
	[self setLastDisconnectionError:nil];

	if (unregisterAfterConnecting)
		[self unregister];
}

//Our account has connected
- (void)accountConnectionConnected
{
	AILog(@"************ %@ CONNECTED ***********",self.UID);
	[self didConnect];
}

- (void)accountConnectionProgressStep:(NSNumber *)step percentDone:(NSNumber *)connectionProgressPrecent
{
	NSString	*connectionProgressString = [self connectionStringForStep:[step integerValue]];

	[self setValue:connectionProgressString forProperty:@"ConnectionProgressString" notify:NO];
	[self setValue:connectionProgressPrecent forProperty:@"ConnectionProgressPercent" notify:NO];	

	//Apply any changes
	[self notifyOfChangedPropertiesSilently:NO];
	
	AILog(@"************ %@ --step-- %i",self.UID,[step integerValue]);
}

/*!
 * @brief Name to use when creating a PurpleAccount for this CBPurpleAccount
 *
 * By default, we just use the formattedUID.  Subclasses can override this to provide other handling,
 * such as appending \@mac.com if necessary for dotMac accounts.
 */
- (const char *)purpleAccountName
{
	return [self.formattedUID UTF8String];
}

- (void)setPurpleAccount:(PurpleAccount *)inAccount
{
	account = inAccount;
}

- (void)createNewPurpleAccount
{
	//Ensure libpurple is loaded and initialized
	[self purpleAdapter];
	
	//If loading libpurple didn't set an account for us, tell it to create one
	if (!account)
		[[self purpleAdapter] addAdiumAccount:self];

	//-[SLPurpleCocoaAdapter addAdiumAccount:] should have immediately called back on setPurpleAccount. It's bad if it didn't.
	if (account) {
		AILog(@"Created PurpleAccount 0x%x with UID %@ and protocolPlugin %s", account, self.UID, [self protocolPlugin]);
	} else {
		AILog(@"Unable to create Libpurple account with name %s and protocol plugin %s",
			  self.purpleAccountName, [self protocolPlugin]);
		NSLog(@"Unable to create Libpurple account with name %s and protocol plugin %s",
			  self.purpleAccountName, [self protocolPlugin]);
	}
}

/*!
 * @brief Returns a PurpleSslConnection for a given account.
 */
- (PurpleSslConnection *)secureConnection
{
	return NULL;
}

#pragma mark Disconnect

/*!
 * @brief Disconnect this account
 */
- (void)disconnect
{
	if (self.online || [self boolValueForProperty:@"Connecting"]) {
		//As per AIAccount's documentation, call super's implementation
		[super disconnect];

		[[AIContactObserverManager sharedManager] delayListObjectNotificationsUntilInactivity];

		//Tell libpurple to disconnect
		[purpleAdapter disconnectAccount:self];
	}
}

- (void)setLastDisconnectionReason:(PurpleConnectionError)reason
{
	lastDisconnectionReason = reason;
}

- (PurpleConnectionError)lastDisconnectionReason
{
	return lastDisconnectionReason;
}

/*!
 * @brief Our account was unexpectedly disconnected with an error message
 */
- (void)accountConnectionReportDisconnect:(NSString *)text withReason:(PurpleConnectionError)reason
{
	[self setLastDisconnectionError:text];
	[self setLastDisconnectionReason:reason];

	if (reason == PURPLE_CONNECTION_ERROR_AUTHENTICATION_FAILED)
		[self serverReportedInvalidPassword];

	//We are disconnecting
    [self setValue:[NSNumber numberWithBool:YES] forProperty:@"Disconnecting" notify:NotifyNow];
	
	AILog(@"%@ accountConnectionReportDisconnect: %@",self,lastDisconnectionError);
}

- (void)accountConnectionNotice:(NSString *)connectionNotice
{
    [adium.interfaceController handleErrorMessage:[NSString stringWithFormat:AILocalizedString(@"%@ (%@) : Connection Notice",nil),self.formattedUID,[service description]]
                                    withDescription:connectionNotice];
}

- (void)didDisconnect
{
	//Clear properties which don't make sense for a disconnected account
	[self setValue:nil forProperty:@"TextProfile" notify:NO];
	
	//Apply any changes
	[self notifyOfChangedPropertiesSilently:NO];
	
	[[NSNotificationCenter defaultCenter] removeObserver:self
										  name:Adium_iTunesTrackChangedNotification
										object:nil];
	[tuneinfo release];
	tuneinfo = nil;
	
	if (deletePurpleAccountAfterDisconnecting) {
		deletePurpleAccountAfterDisconnecting = FALSE;

		[[self purpleAdapter] removeAdiumAccount:self];
	}

	[super didDisconnect];
}
/*!
 * @brief Our account has disconnected
 *
 * This is called after the account disconnects for any reason
 */
- (void)accountConnectionDisconnected
{
	//Report that we disconnected
	AILog(@"%@: Telling the core we disconnected", self);
	[self didDisconnect];
}

- (AIReconnectDelayType)shouldAttemptReconnectAfterDisconnectionError:(NSString **)disconnectionError
{
	AIReconnectDelayType reconnectDelayType;

	if ([self lastDisconnectionReason] == PURPLE_CONNECTION_ERROR_AUTHENTICATION_FAILED) {
		[self setLastDisconnectionError:AILocalizedString(@"Incorrect username or password","Error message displayed when the server reports username or password as being incorrect.")];
		reconnectDelayType = AIReconnectImmediately;

	} else if ([self lastDisconnectionReason] == PURPLE_CONNECTION_ERROR_INVALID_USERNAME) {
		[self setLastDisconnectionError:AILocalizedString(@"The name you entered is not registered. Check to ensure you typed it correctly.", nil)];
		reconnectDelayType = AIReconnectNever;

	} else if (disconnectionError && ([*disconnectionError isEqualToString:[NSString stringWithUTF8String:_("SSL Handshake Failed")]] ||
									  [*disconnectionError isEqualToString:[NSString stringWithUTF8String:_("SSL Connection Failed")]])) {
		/* This particular message comes with PURPLE_CONNECTION_ERROR_ENCRYPTION_ERROR, which is a 'fatal' error according to libpurple. Other problems
		 * with that message may be fatal, but this one isn't.
		 */
		reconnectDelayType = AIReconnectNormally;

	} else if (purple_connection_error_is_fatal([self lastDisconnectionReason])) {
		reconnectDelayType = AIReconnectNever;

	} else {
		reconnectDelayType = AIReconnectNormally;
	}

	return reconnectDelayType;
}

#pragma mark Registering
- (void)performRegisterWithPassword:(NSString *)inPassword
{
	//Save the new password
	if (inPassword && ![password isEqualToString:inPassword]) {
		[password release]; password = [inPassword retain];
	}

	//Ensure we have a purple account if one does not already exist
	[self purpleAccount];
	
	//We are connecting
	[self setValue:[NSNumber numberWithBool:YES] forProperty:@"Connecting" notify:NotifyNow];
	
	//Make sure our settings are correct
	[self configurePurpleAccountNotifyingTarget:self selector:@selector(continueRegisterWithConfiguredPurpleAccount)];
}

- (void)continueRegisterWithConfiguredProxy
{
	//Set password and connect
	purple_account_set_password(account, [password UTF8String]);
	
	AILog(@"Adium: Register: %@ initiating connection.",self.UID);
	
	[purpleAdapter registerAccount:self];
}

- (void)continueRegisterWithConfiguredPurpleAccount
{
	//Configure libpurple's proxy settings; continueConnectWithConfiguredProxy will be called once we are ready
	[self configureAccountProxyNotifyingTarget:self selector:@selector(continueRegisterWithConfiguredProxy)];
}

- (void)purpleAccountRegistered:(BOOL)success
{
	if (success && [self.service accountViewController]) {
		NSString *username = (purple_account_get_username(account) ? [NSString stringWithUTF8String:purple_account_get_username(account)] : [NSNull null]);
		NSString *pw = (purple_account_get_password(account) ? [NSString stringWithUTF8String:purple_account_get_password(account)] : [NSNull null]);

		[[NSNotificationCenter defaultCenter] postNotificationName:AIAccountUsernameAndPasswordRegisteredNotification
												  object:self
												userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
													username, @"username",
													pw, @"password",
													nil]];
	}
}

//Account Status ------------------------------------------------------------------------------------------------------
#pragma mark Account Status
//Properties this account supports
- (NSSet *)supportedPropertyKeys
{
	static NSMutableSet *supportedPropertyKeys = nil;
	
	if (!supportedPropertyKeys) {
		supportedPropertyKeys = [[NSMutableSet alloc] initWithObjects:
			@"IdleSince",
			@"IdleManuallySet",
			@"TextProfile",
			@"DefaultUserIconFilename",
			KEY_ACCOUNT_CHECK_MAIL,
			nil];
		[supportedPropertyKeys unionSet:[super supportedPropertyKeys]];
		
	}

	return supportedPropertyKeys;
}

//Update our status
- (void)updateStatusForKey:(NSString *)key
{    
	[super updateStatusForKey:key];
	
    //Now look at keys which only make sense if we have an account
	if (account) {
		AILog(@"%@: Updating status for key: %@",self, key);

		if ([key isEqualToString:@"IdleSince"]) {
			NSDate	*idleSince = [self preferenceForKey:@"IdleSince" group:GROUP_ACCOUNT_STATUS];
			
			if (!idleSince) {
				idleSince = [adium.preferenceController preferenceForKey:@"IdleSince" group:GROUP_ACCOUNT_STATUS];
			}
			
			[self setAccountIdleSinceTo:idleSince];
							
		} else if ([key isEqualToString:@"TextProfile"]) {
			[self autoRefreshingOutgoingContentForStatusKey:key selector:@selector(setAccountProfileTo:) context:nil];

		} else if ([key isEqualToString:KEY_ACCOUNT_CHECK_MAIL]) {
			//Update the mail checking setting if the account is already made (if it isn't, we'll set it when it is made)
			if (account) {
				[purpleAdapter setCheckMail:[self shouldCheckMail]
							  forAccount:self];
			}
		}
	}
}

/*!
 * @brief Return the purple status type to be used for a status
 *
 * Most subclasses should override this method; these generic values may be appropriate for others.
 *
 * Active services provided nonlocalized status names.  An AIStatus is passed to this method along with a pointer
 * to the status message.  This method should handle any status whose statusNname this service set as well as any statusName
 * defined in  AIStatusController.h (which will correspond to the services handled by Adium by default).
 * It should also handle a status name not specified in either of these places with a sane default, most likely by loooking at
 * statusState.statusType for a general idea of the status's type.
 *
 * @param statusState The status for which to find the purple status ID
 * @param arguments Prpl-specific arguments which will be passed with the state. Message is handled automatically.
 *
 * @result The purple status ID
 */
- (const char *)purpleStatusIDForStatus:(AIStatus *)statusState
							arguments:(NSMutableDictionary *)arguments
{
	char	*statusID = NULL;
	
	switch (statusState.statusType) {
		case AIAvailableStatusType:
			statusID = "available";
			break;
		case AIAwayStatusType:
			statusID = "away";
			break;
			
		case AIInvisibleStatusType:
			statusID = "invisible";
			break;
			
		case AIOfflineStatusType:
			statusID = "offline";
			break;
	}
	
	return statusID;
}

- (BOOL)shouldAddMusicalNoteToNowPlayingStatus
{
	return YES;
}

- (BOOL)shouldSetITMSLinkForNowPlayingStatus
{
	return NO;
}

- (NSDictionary *)purpleSongInfoDictionary
{
	NSMutableDictionary *arguments = nil;

	if (tuneinfo && [[tuneinfo objectForKey:ITUNES_PLAYER_STATE] isEqualToString:@"Playing"]) {
		arguments = [NSMutableDictionary dictionary];
		
		NSString *artist = [tuneinfo objectForKey:ITUNES_ARTIST];
		NSString *name = [tuneinfo objectForKey:ITUNES_NAME];
		
		[arguments setObject:(artist ? artist : @"") forKey:[NSString stringWithUTF8String:PURPLE_TUNE_ARTIST]];
		[arguments setObject:(name ? name : @"") forKey:[NSString stringWithUTF8String:PURPLE_TUNE_TITLE]];
		[arguments setObject:([tuneinfo objectForKey:ITUNES_ALBUM] ? [tuneinfo objectForKey:ITUNES_ALBUM] : @"") forKey:[NSString stringWithUTF8String:PURPLE_TUNE_ALBUM]];
		[arguments setObject:([tuneinfo objectForKey:ITUNES_GENRE] ? [tuneinfo objectForKey:ITUNES_GENRE] : @"") forKey:[NSString stringWithUTF8String:PURPLE_TUNE_GENRE]];
		[arguments setObject:([tuneinfo objectForKey:ITUNES_TOTAL_TIME] ? [tuneinfo objectForKey:ITUNES_TOTAL_TIME]:[NSNumber numberWithInteger:-1]) forKey:[NSString stringWithUTF8String:PURPLE_TUNE_TIME]];
		[arguments setObject:([tuneinfo objectForKey:ITUNES_YEAR] ? [tuneinfo objectForKey:ITUNES_YEAR]:[NSNumber numberWithInteger:-1]) forKey:[NSString stringWithUTF8String:PURPLE_TUNE_YEAR]];
		[arguments setObject:([tuneinfo objectForKey:ITUNES_STORE_URL] ? [tuneinfo objectForKey:ITUNES_STORE_URL] : @"") forKey:[NSString stringWithUTF8String:PURPLE_TUNE_URL]];
		
		[arguments setObject:[NSString stringWithFormat:@"%@%@%@", (name ? name : @""), (name && artist ? @" - " : @""), (artist ? artist : @"")]
					  forKey:[NSString stringWithUTF8String:PURPLE_TUNE_FULL]];
	}

	return arguments;
}

- (void)iTunesDidUpdate:(NSNotification*)notification {
	[tuneinfo release];
	tuneinfo = [[notification object] retain];

	/* Only if we're including the information in all statuses do we need to do an update;
	 * if we just have a 'now playing' status, the dynamic stats update will call
	 * -[self setStatusState:usingStatusMessage:] in a moment.
	 */	 
	[purpleAdapter setSongInformation:(shouldIncludeNowPlayingInformationInAllStatuses ? [self purpleSongInfoDictionary] : nil) onAccount:self];
}

/*!
 * @brief Should a status message be set when using the default "Away" state?
 */
- (BOOL)shouldSetStatusMessageForDefaultAwayState
{
	return YES;
}

/*!
 * @brief Perform the setting of a status state
 *
 * Sets the account to a passed status state.  The account should set itself to best possible status given the return
 * values of statusState's accessors.  The passed statusMessage has been filtered; it should be used rather than
 * statusState.statusMessage, which returns an unfiltered statusMessage.
 *
 * @param statusState The state to enter
 * @param statusMessage The filtered status message to use.
 */
- (void)setStatusState:(AIStatus *)statusState usingStatusMessage:(NSAttributedString *)statusMessage
{
	NSString			*encodedStatusMessage;
	NSMutableDictionary	*arguments = [[NSMutableDictionary alloc] init];

	//Get the purple status type from this class or subclasses, which may also potentially modify or nullify our statusMessage
	const char *statusID = [self purpleStatusIDForStatus:statusState
											 arguments:arguments];

	if (![statusMessage length] &&
		(statusState.statusType == AIAwayStatusType) &&
		statusState.statusName &&
		(!statusID || ((strcmp(statusID, "away") == 0) && [self shouldSetStatusMessageForDefaultAwayState]))) {
		/* If we don't have a status message, and the status type is away for a non-default away such as "Do Not Disturb", and we're only setting
		 * a default away state becuse we don't know a better one for this service, get a default
		 * description of this away state. This allows, for example, an AIM user to set the "Do Not Disturb" type provided by her ICQ account
		 * and have the away message be set appropriately.
		 */
		statusMessage = [NSAttributedString stringWithString:[adium.statusController descriptionForStateOfStatus:statusState]];
	}

	BOOL isNowPlayingStatus = ([statusState specialStatusType] == AINowPlayingSpecialStatusType);
	if (isNowPlayingStatus && [statusMessage length]) {
		if ([self shouldAddMusicalNoteToNowPlayingStatus]) {
#define MUSICAL_NOTE_AND_SPACE [NSString stringWithUTF8String:"\xe2\x99\xab "]
			NSMutableAttributedString *temporaryStatusMessage;
			temporaryStatusMessage = [[[NSMutableAttributedString alloc] initWithString:MUSICAL_NOTE_AND_SPACE] autorelease];
			[temporaryStatusMessage appendAttributedString:statusMessage];
			
			statusMessage = temporaryStatusMessage;
		}
		
		if ([self shouldSetITMSLinkForNowPlayingStatus]) {
			//Grab the message's subtext, which is the song link if we're using the Current iTunes Track status
			NSString *itmsStoreLink	= [statusMessage attribute:@"AIMessageSubtext" atIndex:0 effectiveRange:NULL];
			if (itmsStoreLink) {
				[arguments setObject:itmsStoreLink
							  forKey:@"itmsurl"];
			}
		}
		
		NSDictionary *purpleSongInfoDictionary = [self purpleSongInfoDictionary];
		if (purpleSongInfoDictionary)
			[arguments addEntriesFromDictionary:purpleSongInfoDictionary];
	}

	//Encode the status message if we have one
	encodedStatusMessage = (statusMessage ? 
							[self encodedAttributedString:statusMessage
										   forStatusState:statusState]  :
							nil);
	if (encodedStatusMessage) {
		[arguments setObject:encodedStatusMessage
					  forKey:@"message"];
	}

	[self setStatusState:statusState
				statusID:statusID
				isActive:[NSNumber numberWithBool:YES] /* We're only using exclusive states for now... I hope.  */
			   arguments:arguments];
	
	[arguments release];
}

/*!
 * @brief Perform the actual setting of a state
 *
 * This is called by setStatusState.  It allows subclasses to perform any other behaviors, such as modifying a display
 * name, which are called for by the setting of the state; most of the processing has already been done, however, so
 * most subclasses will not need to implement this.
 *
 * @param statusState The AIStatus which is being set
 * @param statusID The Purple-sepcific statusID we are setting
 * @param isActive An NSNumber with a bool YES if we are activating (going to) the passed state, NO if we are deactivating (going away from) the passed state.
 * @param arguments Purple-specific arguments specified by the account. It must contain only NSString objects and keys.
 */
- (void)setStatusState:(AIStatus *)statusState statusID:(const char *)statusID isActive:(NSNumber *)isActive arguments:(NSMutableDictionary *)arguments
{
	[purpleAdapter setStatusID:statusID
				   isActive:isActive
				  arguments:arguments
				  onAccount:self];
}

//Set our idle (Pass nil for no idle)
- (void)setAccountIdleSinceTo:(NSDate *)idleSince
{
	[purpleAdapter setIdleSinceTo:idleSince onAccount:self];
	
	//We now should update our idle property
	[self setValue:([idleSince timeIntervalSinceNow] ? idleSince : nil)
				   forProperty:@"IdleSince"
				   notify:NotifyNow];
}

//Set the profile, then invoke the passed invocation to return control to the target/selector specified
//by a configurePurpleAccountNotifyingTarget:selector: call.
- (void)setAccountProfileTo:(NSAttributedString *)profile configurePurpleAccountContext:(NSInvocation *)inInvocation
{
	[self setAccountProfileTo:profile];
	
	[inInvocation invoke];
}

//Set our profile immediately on the purpleAdapter
- (void)setAccountProfileTo:(NSAttributedString *)profile
{
	if (!profile || ![[profile string] isEqualToString:[[self valueForProperty:@"TextProfile"] string]]) {
		NSString 	*profileHTML = nil;
		
		//Convert the profile to HTML, and pass it to libpurple
		if (profile) {
			profileHTML = [self encodedAttributedString:profile forListObject:nil];
		}
		
		[purpleAdapter setInfo:profileHTML onAccount:self];
		
		//We now have a profile
		[self setValue:profile forProperty:@"TextProfile" notify:NotifyNow];
	}
}

/*!
 * @brief Set our user image
 *
 * Pass nil for no image. This resizes and converts the image as needed for our protocol.
 * After setting it with purple, it sets it within Adium; if this is not called, the image will
 * show up neither locally nor remotely.
 */
- (void)setAccountUserImage:(NSImage *)image withData:(NSData *)originalData;
{
	if (account) {
		NSData		*imageData = originalData;
		NSSize		imageSize = (image ? [image size] : NSZeroSize);
		NSData		*buddyIconData = nil;

		/* Now pass libpurple the new icon. Check to be sure our image doesn't have an NSZeroSize size,
		 * which would indicate currupt data */
		if (image && !NSEqualSizes(NSZeroSize, imageSize)) {
			PurplePluginProtocolInfo  *prpl_info = self.protocolInfo;

			AILog(@"Original image of size %f %f",imageSize.width,imageSize.height);

			if (prpl_info && (prpl_info->icon_spec.format)) {
				BOOL		smallEnough, prplScales;
				NSUInteger	i;
				
				/* We need to scale it down if:
				 *	1) The prpl needs to scale before it sends to the server or other buddies AND
				 *	2) The image is larger than the maximum size allowed by the protocol
				 * We ignore the minimum required size, as scaling up just leads to pixellated images.
				 */
				smallEnough =  (prpl_info->icon_spec.max_width >= imageSize.width &&
								prpl_info->icon_spec.max_height >= imageSize.height);
					
				prplScales = (prpl_info->icon_spec.scale_rules & PURPLE_ICON_SCALE_SEND) || (prpl_info->icon_spec.scale_rules & PURPLE_ICON_SCALE_DISPLAY);

				if (prplScales && !smallEnough) {
					gint width = (gint)imageSize.width;
					gint height = (gint)imageSize.height;
					
					purple_buddy_icon_get_scale_size(&prpl_info->icon_spec, &width, &height);
					//Determine the scaled size.  If it's too big, scale to the largest permissable size
					image = [image imageByScalingToSize:NSMakeSize(width, height)];

					/* Our original data is no longer valid, since we had to scale to a different size */
					imageData = nil;
					AILog(@"%@: Scaled image to size %@", self, NSStringFromSize([image size]));
				}

				if (!buddyIconData) {
					char		**prpl_formats =  g_strsplit(prpl_info->icon_spec.format,",",0);

					//Look for gif first if the image is animated
					NSImageRep	*imageRep = [image bestRepresentationForDevice:nil] ;
					if ([imageRep isKindOfClass:[NSBitmapImageRep class]] &&
						[[(NSBitmapImageRep *)imageRep valueForProperty:NSImageFrameCount] integerValue] > 1) {
						
						for (i = 0; prpl_formats[i]; i++) {
							if (strcmp(prpl_formats[i],"gif") == 0) {
								/* Try to use our original data.  If we had to scale, imageData will have been set
								* to nil and we'll continue below to convert the image. */
								AILog(@"l33t script kiddie animated GIF!!111");
								
								buddyIconData = imageData;
								if (buddyIconData)
									break;
							}
						}
					}
					
					if (!buddyIconData) {
						for (i = 0; prpl_formats[i]; i++) {
							if (strcmp(prpl_formats[i],"png") == 0) {
								buddyIconData = [image PNGRepresentation];
								if (buddyIconData)
									break;
								
							} else if ((strcmp(prpl_formats[i],"jpeg") == 0) || (strcmp(prpl_formats[i],"jpg") == 0)) {								
								buddyIconData = [image JPEGRepresentationWithCompressionFactor:1.0];
								if (buddyIconData)
									break;
								
							} else if ((strcmp(prpl_formats[i],"tiff") == 0) || (strcmp(prpl_formats[i],"tif") == 0)) {
								buddyIconData = [image TIFFRepresentation];
								if (buddyIconData)
									break;
								
							} else if (strcmp(prpl_formats[i],"gif") == 0) {
								buddyIconData = [image GIFRepresentation];
								if (buddyIconData)
									break;
								
							} else if (strcmp(prpl_formats[i],"bmp") == 0) {
								buddyIconData = [image BMPRepresentation];
								if (buddyIconData)
									break;
								
							}						
						}
						
						size_t maxSize = prpl_info->icon_spec.max_filesize;
						if (maxSize > 0 && ([buddyIconData length] > maxSize)) {
							AILog(@"Image %i is larger than %i!",[buddyIconData length],maxSize);
							for (i = 0; prpl_formats[i]; i++) {
								if ((strcmp(prpl_formats[i],"jpeg") == 0) || (strcmp(prpl_formats[i],"jpg") == 0)) {
									buddyIconData = [image JPEGRepresentationWithMaximumByteSize:maxSize];
								}
							}
						}
					}	
					//Cleanup
					g_strfreev(prpl_formats);
				}
			}
		}

		AILogWithSignature(@"%@ setting icon data of length %i", self, [buddyIconData length]);
		[purpleAdapter setBuddyIcon:buddyIconData onAccount:self];
	}
	
	[super setAccountUserImage:image withData:originalData];
}

#pragma mark Group Chat
- (BOOL)inviteContact:(AIListContact *)inContact toChat:(AIChat *)inChat withMessage:(NSString *)inviteMessage
{
	[purpleAdapter inviteContact:inContact toChat:inChat withMessage:inviteMessage];
	
	return YES;
}

#pragma mark Buddy Menu Items
//Action of a dynamically-generated contact menu item
- (void)performContactMenuAction:(NSMenuItem *)sender
{
	NSDictionary		*dict = [sender representedObject];
	
	[purpleAdapter performContactMenuActionFromDict:dict forAccount:self];
}

/*!
 * @brief Utility method when generating buddy-specific menu items
 *
 * Adds the menu item for act to a growing array of NSMenuItems.  If act has children (a submenu), this method is used recursively
 * to generate the submenu containing each child menu item.
 */
- (void)addMenuItemForMenuAction:(PurpleMenuAction *)act forListContact:(AIListContact *)inContact purpleBuddy:(PurpleBuddy *)buddy toArray:(NSMutableArray *)menuItemArray withServiceIcon:(NSImage *)serviceIcon
{
	NSDictionary	*dict;
	NSMenuItem		*menuItem;
	NSString		*title;
				
	//If titleForContactMenuLabel:forContact: returns nil, we don't add the menuItem
	if (act &&
		act->label &&
		(title = [self titleForContactMenuLabel:act->label
									 forContact:inContact])) { 
		menuItem = [[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:title
																		target:self
																		action:@selector(performContactMenuAction:)
																 keyEquivalent:@""];
		[menuItem setImage:serviceIcon];

		if (act->data) {
			dict = [NSDictionary dictionaryWithObjectsAndKeys:
				[NSValue valueWithPointer:act->callback],@"PurpleMenuActionCallback",
				/* act->data may be freed by purple_menu_action_free() before we use it, I'm afraid... */
				[NSValue valueWithPointer:act->data],@"PurpleMenuActionData",
				[NSValue valueWithPointer:buddy],@"PurpleBuddy",
				nil];
		} else {
			dict = [NSDictionary dictionaryWithObjectsAndKeys:
				[NSValue valueWithPointer:act->callback],@"PurpleMenuActionCallback",
				[NSValue valueWithPointer:buddy],@"PurpleBuddy",
				nil];			
		}
		
		[menuItem setRepresentedObject:dict];
		
		//If there is a submenu, generate and set it
		if (act->children) {
			NSMutableArray	*childrenArray = [NSMutableArray array];
			GList			*l, *ll;
			//Add a NSMenuItem for each child
			for (l = ll = act->children; l; l = l->next) {
				[self addMenuItemForMenuAction:(PurpleMenuAction *)l->data
								forListContact:inContact
									 purpleBuddy:buddy
									   toArray:childrenArray
							   withServiceIcon:serviceIcon];
			}
			g_list_free(act->children);

			if ([childrenArray count]) {
				NSMenu		 *submenu = [[NSMenu alloc] init];
				
				for (NSMenuItem *childMenuItem in childrenArray) {
					[submenu addItem:childMenuItem];
				}
				
				[menuItem setSubmenu:submenu];
				[submenu release];
			}
		}

		[menuItemArray addObject:menuItem];
		[menuItem release];
	}

	purple_menu_action_free(act);
}

//Returns an array of menuItems specific for this contact based on its account and potentially status
- (NSArray *)menuItemsForContact:(AIListContact *)inContact
{
	NSMutableArray			*menuItemArray = nil;

	if (account && purple_account_is_connected(account)) {
		PurplePluginProtocolInfo  *prpl_info = self.protocolInfo;
		GList					*l, *ll;
		PurpleBuddy				*buddy;
		
		//Find the PurpleBuddy
		buddy = purple_find_buddy(account, [inContact.UID UTF8String]);
		
		if (prpl_info && prpl_info->blist_node_menu && buddy) {
			NSImage	*serviceIcon = [AIServiceIcons serviceIconForService:self.service
																	type:AIServiceIconSmall
															   direction:AIIconNormal];
			
			menuItemArray = [NSMutableArray array];

			//Add a NSMenuItem for each node action specified by the prpl
			for (l = ll = prpl_info->blist_node_menu((PurpleBlistNode *)buddy); l; l = l->next) {
				[self addMenuItemForMenuAction:(PurpleMenuAction *)l->data
								forListContact:inContact
									 purpleBuddy:buddy
									   toArray:menuItemArray
							   withServiceIcon:serviceIcon];
			}
			g_list_free(ll);
			
			//Don't return an empty array
			if (![menuItemArray count]) menuItemArray = nil;
		}
	}
	
	return menuItemArray;
}

//Subclasses may override to provide a localized label and/or prevent a specified label from being shown
- (NSString *)titleForContactMenuLabel:(const char *)label forContact:(AIListContact *)inContact
{
	return [NSString stringWithUTF8String:label];
}

/*!
* @brief Menu items for the account's actions
 *
 * Returns an array of menu items for account-specific actions.  This is the best place to add protocol-specific
 * actions that aren't otherwise supported by Adium.  It will only be queried if the account is online.
 * @return NSArray of NSMenuItem instances for this account
 */
- (NSArray *)accountActionMenuItems
{
	NSMutableArray			*menuItemArray = nil;
	
	if (account && purple_account_is_connected(account)) {
		PurplePlugin *plugin = purple_account_get_connection(account)->prpl;
		
		if (PURPLE_PLUGIN_HAS_ACTIONS(plugin)) {
			GList	*l, *actions;
			
			actions = PURPLE_PLUGIN_ACTIONS(plugin, purple_account_get_connection(account));

			//Avoid adding separators between nonexistant items (i.e. items which Purple shows but we don't)
			BOOL	addedAnAction = NO;
			for (l = actions; l; l = l->next) {
				
				if (l->data) {
					PurplePluginAction	*action;
					NSDictionary		*dict;
					NSMenuItem			*menuItem;
					NSString			*title;
					
					action = (PurplePluginAction *) l->data;
					
					//If titleForAccountActionMenuLabel: returns nil, we don't add the menuItem
					if (action &&
						action->label &&
						(title = [self titleForAccountActionMenuLabel:action->label])) {

						action->plugin = plugin;
						action->context = purple_account_get_connection(account);

						menuItem = [[[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:title
																						 target:self
																						 action:@selector(performAccountMenuAction:)
																				  keyEquivalent:@""] autorelease];
						dict = [NSDictionary dictionaryWithObjectsAndKeys:
							[NSValue valueWithPointer:action->callback], @"PurplePluginActionCallback",
							[NSValue valueWithPointer:action->user_data], @"PurplePluginActionCallbackUserData",
							nil];
						
						[menuItem setRepresentedObject:dict];
						
						if (!menuItemArray) menuItemArray = [NSMutableArray array];
						
						[menuItemArray addObject:menuItem];
						addedAnAction = YES;
					} 
					
					purple_plugin_action_free(action);
					
				} else {
					if (addedAnAction) {
						[menuItemArray addObject:[NSMenuItem separatorItem]];
						addedAnAction = NO;
					}
				}
			} /* end for */
			
			g_list_free(actions);
		}
	}
	
#ifdef HAVE_CDSA
	if([self encrypted] && [self secureConnection]) {
		if (menuItemArray.count) {
			[menuItemArray addObject:[NSMenuItem separatorItem]];
		}
		
		NSMenuItem *showCertificateMenuItem = [[[NSMenuItem alloc] initWithTitle:AILocalizedString(@"Show Server Certificate",nil)
																		 target:self
																		 action:@selector(showServerCertificate) 
																  keyEquivalent:@""] autorelease];
		
		[menuItemArray addObject:showCertificateMenuItem];
	}
#endif

	return menuItemArray;
}

#ifdef HAVE_CDSA
/*!
 * @brief Shows the SSL certificate for the connection.
 */
- (void)showServerCertificate
{
	CFArrayRef certificates = [[self purpleAdapter] copyServerCertificates:[self secureConnection]];
	
	[AIPurpleCertificateViewer displayCertificateChain:certificates forAccount:self];
	
	CFRelease(certificates);
}
#endif

//Action of a dynamically-generated contact menu item
- (void)performAccountMenuAction:(NSMenuItem *)sender
{
	NSDictionary		*dict = [sender representedObject];

	[purpleAdapter performAccountMenuActionFromDict:dict forAccount:self];
}

//Subclasses may override to provide a localized label and/or prevent a specified label from being shown
- (NSString *)titleForAccountActionMenuLabel:(const char *)label
{
	if ((strcmp(label, _("Change Password...")) == 0) || (strcmp(label, _("Change Password")) == 0)) {
		return [[NSString stringWithFormat:AILocalizedString(@"Change Password", "Menu item title for changing the password of an account")] stringByAppendingEllipsis];
	} else {
		return [NSString stringWithUTF8String:label];
	}
}

/********************************/
/* AIAccount subclassed methods */
/********************************/
#pragma mark AIAccount Subclassed Methods
- (void)initAccount
{
	NSDictionary	*defaults = [NSDictionary dictionaryNamed:[NSString stringWithFormat:@"PurpleDefaults%@",self.service.serviceID]
													 forClass:[self class]];
	
	if (defaults) {
		[adium.preferenceController registerDefaults:defaults
											  forGroup:GROUP_ACCOUNT_STATUS
												object:self];
	} else {
		AILog(@"Failed to load defaults for %@",[NSString stringWithFormat:@"PurpleDefaults%@",self.service.serviceID]);
	}
	
	//Defaults
	[self setLastDisconnectionError:nil];
	
	permittedContactsArray = [[NSMutableArray alloc] init];
	deniedContactsArray = [[NSMutableArray alloc] init];

	//We will create a purpleAccount the first time we attempt to connect
	account = NULL;

	//Observe preferences changes
	[adium.preferenceController registerPreferenceObserver:self forGroup:PREF_GROUP_ALIASES];
	[adium.preferenceController registerPreferenceObserver:self forGroup:PREF_GROUP_DUAL_WINDOW_INTERFACE];
}

- (BOOL)allowAccountUnregistrationIfSupportedByLibpurple
{
	return YES;
}

/*!
 * @brief The account will be deleted, we should ask the user for confirmation. If the prpl supports it, we can also remove
 * the account from the server (if the user wants us to do that)
 */
- (NSAlert*)alertForAccountDeletion
{
	PurplePluginProtocolInfo *prpl_info = self.protocolInfo;

	//Ensure libpurple has been loaded, since we need to know whether we can unregister this account
	[self purpleAdapter];

	if (prpl_info && 
		prpl_info->unregister_user &&
		[self allowAccountUnregistrationIfSupportedByLibpurple]) {
		return [NSAlert alertWithMessageText:AILocalizedString(@"Delete Account",nil)
							   defaultButton:AILocalizedString(@"Delete",nil)
							 alternateButton:AILocalizedString(@"Cancel",nil)
								 otherButton:AILocalizedString(@"Delete & Unregister",nil)
				   informativeTextWithFormat:AILocalizedString(@"Delete the account %@? You can also optionally unregister the account on the server if possible.",nil), ([self.formattedUID length] ? self.formattedUID : NEW_ACCOUNT_DISPLAY_TEXT)];		

	} else {
		return [super alertForAccountDeletion];
	}
}

- (void)alertForAccountDeletion:(id<AIAccountControllerRemoveConfirmationDialog>)dialog didReturn:(NSInteger)returnCode
{
	PurplePluginProtocolInfo *prpl_info = self.protocolInfo;
	
	if (prpl_info && 
		prpl_info->unregister_user) {
		switch (returnCode) {
			case NSAlertOtherReturn:
				// delete & unregister
				if (self.online)
					[self unregister];
				else {
					unregisterAfterConnecting = YES;
					[self setShouldBeOnline:YES];
				}
			
				// further progress happens in -unregisteredAccount:
				break;
			case NSAlertDefaultReturn:
				// delete without unregistering
				[self performDelete];
				break;
			default:
				// cancel
				break;
		}
		
	} else {
		switch(returnCode) {
			case NSAlertDefaultReturn:
				[self performDelete];
				break;
			default:
				// cancel
				break;
		}
	}
	
	//Release dialog as required by AIAccount's documentation since we didn't call super's implementation.
	[dialog release];
}

- (void)unregisteredAccount:(BOOL)success {
	if (success) {
		/* We're not going to be online, but we *must* not disconnect within this run loop,
		 * as libpurple may still have Things To Do with the connection and it has no concept of reference
		 * counting with which to survive the disconnection. Performing a deletion would set us offline,
		 * so wait until the next run loop.
		 */
		[self performSelector:@selector(performDelete)
				   withObject:nil
				   afterDelay:0];
	}
}

/*!
 * @brief The account's UID changed
 */
- (void)didChangeUID
{
	//Only need to take action if we have a created PurpleAccount already
	if (account != NULL) {
		//Remove our current account
		[[self purpleAdapter] removeAdiumAccount:self];
		
		//Clear the reference to the PurpleAccount... it'll be created when needed
		account = NULL;
	}
}

/*!
 * @brief The account will be deleted; it has already been told to disconnect
 */
- (void)willBeDeleted
{	
	if (self.online) {
		//Wait until we are finished disconnecting before removing ourselves from libpurple.
		deletePurpleAccountAfterDisconnecting = TRUE;

	} else {
		[[self purpleAdapter] removeAdiumAccount:self];
	}

	[super willBeDeleted];
}

- (void)dealloc
{	
	[adium.preferenceController unregisterPreferenceObserver:self];

	[permittedContactsArray release];
	[deniedContactsArray release];
	
    [super dealloc];
}

- (NSString *)unknownGroupName {
    return (@"Unknown");
}

- (NSDictionary *)defaultProperties { return [NSDictionary dictionary]; }

- (NSString *)encodedAttributedString:(NSAttributedString *)inAttributedString forStatusState:(AIStatus *)statusState
{
	return [self encodedAttributedString:inAttributedString forListObject:nil];	
}

- (void)preferencesChangedForGroup:(NSString *)group key:(NSString *)key
							object:(AIListObject *)object preferenceDict:(NSDictionary *)prefDict firstTime:(BOOL)firstTime
{
	[super preferencesChangedForGroup:group key:key object:object preferenceDict:prefDict firstTime:firstTime];

	if ([group isEqualToString:PREF_GROUP_ALIASES]) {
		//If the notification object is a listContact belonging to this account, update the serverside information
		if ((account != nil) && 
			([self shouldSetAliasesServerside]) &&
			([key isEqualToString:@"Alias"])) {

			NSString *alias = [object preferenceForKey:@"Alias"
												 group:PREF_GROUP_ALIASES 
								];

			if ([object isKindOfClass:[AIMetaContact class]]) {
				for(AIListContact *containedListContact in (AIMetaContact *)object) {
					if (containedListContact.account == self) {
						[purpleAdapter setAlias:alias forUID:containedListContact.UID onAccount:self];
					}
				}
				
			} else if ([object isKindOfClass:[AIListContact class]]) {
				if ([(AIListContact *)object account] == self) {
					[purpleAdapter setAlias:alias forUID:object.UID onAccount:self];
				}
			}
		}
	} else if ([group isEqualToString:PREF_GROUP_DUAL_WINDOW_INTERFACE]) {
		openPsychicChats = [[prefDict objectForKey:KEY_PSYCHIC] boolValue];

	} else if ([group isEqualToString:GROUP_ACCOUNT_STATUS]) {
		BOOL oldNowPlaying = shouldIncludeNowPlayingInformationInAllStatuses;
		
		shouldIncludeNowPlayingInformationInAllStatuses = [[self preferenceForKey:KEY_BROADCAST_MUSIC_INFO group:GROUP_ACCOUNT_STATUS] boolValue];

		if (oldNowPlaying && !shouldIncludeNowPlayingInformationInAllStatuses) {
			/* Clear any existing song info immediately if we're no longer supposed to broadcast it */
			[purpleAdapter setSongInformation:nil onAccount:self];
		}
	}
}

/*!
 * @brief When the account is edited, update our libpurple preferences.
 */
- (void)accountEdited
{
	// We only need to re-configure if we're online or connecting. If we're offline, our next connect will do this.
	if (self.online || [self boolValueForProperty:@"Connecting"]) {
		AILog(@"Re-configuring purple account due to preference changes.");
		[self configurePurpleAccount];
	}
}

#pragma mark Actions for chats

/***************************/
/* Account private methods */
/***************************/
#pragma mark Private
- (void)setTypingFlagOfChat:(AIChat *)chat to:(NSNumber *)typingStateNumber
{
	NSAssert(!chat.isGroupChat, @"Chat cannot be a group chat for typing.");
	
    AITypingState currentTypingState = [chat integerValueForProperty:KEY_TYPING];
	AITypingState newTypingState = [typingStateNumber integerValue];
	
    if (currentTypingState != newTypingState) {
		if (newTypingState == AITyping && openPsychicChats && ![chat isOpen]) {
			[adium.interfaceController openChat:chat];
			
			/*
			 * Use the Libpurple "psychic" tagline. If this is found to be confusing, we should switch to your own version.
			 * The upside of using theirs is that clever gimmicky translations already exist.
			 */
			NSMutableString *forceString = [[NSString stringWithUTF8String:_("You feel a disturbance in the force...")] mutableCopy];
			[forceString replaceOccurrencesOfString:@"..."
										 withString:[NSString ellipsis]
											options:NSLiteralSearch];
			AIContentEvent *statusMessage = [AIContentEvent eventInChat:chat
															 withSource:chat.listObject
															destination:self
																   date:[NSDate date]
																message:[NSAttributedString stringWithString:forceString]
															   withType:@"psychic"];
			
			// Don't log the psychic message.
			statusMessage.postProcessContent = NO;
			
			[forceString release];

			[adium.contentController receiveContentObject:statusMessage];
		}
		
		[chat setValue:(newTypingState ? typingStateNumber : nil)
					   forProperty:KEY_TYPING
					   notify:NotifyNow];
    }
}

- (NSNumber *)shouldCheckMail
{
	return [self preferenceForKey:KEY_ACCOUNT_CHECK_MAIL group:GROUP_ACCOUNT_STATUS];
}

- (BOOL)shouldSetAliasesServerside
{
	return NO;
}

@end