This file is indexed.

/usr/share/amsn/chatwindow.tcl is in amsn-data 0.98.9-1ubuntu3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
#########################################
#    Chat Window code abstraction       #
#           By Alberto D�z            #
#########################################

::Version::setSubversionId {$Id: chatwindow.tcl 12355 2012-01-01 23:07:09Z kakaroto $}

package require framec
package require scalable-bg

namespace eval ::ChatWindow {

	#///////////////////////////////////////////////////////////////////////////////
	# Namespace variables, relative to chat windows' data. In the code are accessible
	# through '::namespace::variable' syntax (to avoid local instances of the variable
	# and have the scope more clear).

	# As ::ChatWindow::winid is the index used in the
	# window widgets for chat windows, we only initialize
	# it at the first time, to avoid problems with proc
	# reload_files wich will cause some bugs related to
	# winid being 0 after some windows have been created.
	if { $initialize_amsn == 1  } {
		variable chat_ids
		variable first_message
		variable msg_windows
		variable new_message_on
		variable recent_message
		variable titles
		variable windows [list]
		variable winid 0
		variable containers
		variable containerwindows
		variable tab2win
		variable win2tab
		variable containercurrent
		variable containerid 0
		variable scrolling
		variable macbouncewindows [list]
                variable trayblinkwindows [list]
	}
	#///////////////////////////////////////////////////////////////////////////////


 	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::rotext -- Read Only text widget via snit
	# Changes must be made by "ins" and "del", not "insert" and "delete".
	# Leave the window state as "normal" so cut and paste work on all platforms.
	# From example on http://wiki.tcl.tk/3963
	::snit::widgetadaptor rotext {
		constructor {args} {
			# Turn off the insert cursor
			#installhull using text $self -insertwidth 0
			# DDG the $self gaves an error at least with 0.97 onwards
			installhull using text -insertwidth 0

			# Apply an options passed at creation time.
			$self configurelist $args
		}

		# Disable the insert and delete methods, to make this readonly.
		method insert {args} {}
		method delete {args} {}

		# Enable roinsert and rodelete as synonyms, so the program can insert and
		# delete.
		delegate method roinsert to hull as insert
		delegate method rodelete to hull as delete

		# Pass all other methods and options to the real text widget, so
		# that the remaining behavior is as expected.
		delegate method * to hull
		delegate option * to hull
	}
	#///////////////////////////////////////////////////////////////////////////////



	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::Change (chatid, newchatid)
	# This proc is called from the protocol layer when a private chat changes into a
	# conference, right after a JOI command comes from the SB. It means that the window
	# assigned to $chatid should now be related to $newchatid. ::ChatWindow::Change 
	# will return the new chatid if the change is OK (no other window for that name 
	# exists), or the old chatid if the change is not right
	# Arguments:
	# - chatid => Is the name of the chat that was a single private before.
	# - newchatid => Is the new id of the chat for the conference
	proc Change { chatid newchatid } {
		set win_name [::ChatWindow::For $chatid]

		if { $win_name == 0 } {
			# Old window window does not exists, so just accept the change, no worries
			status_log "::ChatWindow::Change: Window doesn't exist (probably invited to a conference)\n"
			return $newchatid
		}

		if { [::ChatWindow::For $newchatid] != 0} {
			#Old window existed, probably a conference, but new one exists too, so we can't
			#just allow that messages shown in old window now are shown in a different window,
			#that wouldn't be nice, so don't allow change
			status_log "conference wants to become private, but there's already a window\n"
			return $chatid
		}

		#So, we had an old window for chatid, but no window for newchatid, so the window will
		#change it's assigned chat
		::ChatWindow::UnsetFor $chatid $win_name
		::ChatWindow::SetFor $newchatid $win_name

		status_log "::ChatWindow::Change: changing $chatid into $newchatid\n"

		return $newchatid
	}
	#///////////////////////////////////////////////////////////////////////////////


	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::GetTopFrame (window)
	# Returns the path to the top frame (containing "To: ...") for a given window 
	# Arguments:
	#  - window => Is the chat window widget (.msg_n - Where n is an integer)
	proc GetTopFrame { window } {
		return $window.top
	}
	#///////////////////////////////////////////////////////////////////////////////

	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::GetOutFrame (window)
	# Returns the path to the output frame in a given window 
	# Arguments:
	#  - window => Is the chat window widget (.msg_n - Where n is an integer)
	proc GetOutFrame { window } {
		return $window.f.out
	}
	#///////////////////////////////////////////////////////////////////////////////

	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::GetInFrame (window)
	# Returns the path to the input frame in a given window 
	# Arguments:
	#  - window => Is the chat window widget (.msg_n - Where n is an integer)
	proc GetInFrame { window } {
		return $window.f.bottom
	}
	#///////////////////////////////////////////////////////////////////////////////

	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::GetOutText (window)
	# Returns the path to the output text widget in a given window
	# Arguments:
	#  - window => Is the chat window widget (.msg_n - Where n is an integer)
	proc GetOutText { window } {
		return [GetOutFrame $window].scroll.text
	}
	#///////////////////////////////////////////////////////////////////////////////

	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::GetDisplayPicturesFrame (window)
	# Returns the path to the output DP frame in a given window
	# Arguments:
	#  - window => Is the chat window widget (.msg_n - Where n is an integer)
	proc GetOutDisplayPicturesFrame { window } {
		# We check if the frame exists instead of checking the 'old_dpframe' option
		# is set because we might change the option and it will cause a bug for
		# existing chat windows
		if {[winfo exists [GetOutFrame $window].f.sw.sf] } {
			return [[GetOutFrame $window].f.sw.sf getframe]
		} else {
			return [GetOutFrame $window].f
		}
	}
	#///////////////////////////////////////////////////////////////////////////////


	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::GetInputDP (window)
	# Returns the path to the input DP in a given window
	# Arguments:
	#  - window => Is the chat window widget (.msg_n - Where n is an integer)
	proc GetInDisplayPictureFrame { window } {
		return [GetInFrame $window].f
	}
	#///////////////////////////////////////////////////////////////////////////////

	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::GetInputText (window)
	# Returns the path to the input text widget in a given window 
	# Arguments:
	#  - window => Is the chat window widget (.msg_n - Where n is an integer)
	proc GetInputText { window } {
		return [[GetLeftFrame $window].in getinnerframe].text
	}
	#///////////////////////////////////////////////////////////////////////////////

	proc GetLeftFrame { window } {
		return [GetInFrame $window].left
	}

	proc GetButtonBarForWin { window } {
		return [GetLeftFrame $window].buttons
	}

	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::GetStatusText (window)
	# Returns the path to the statusbar text widget in a given window 
	# Arguments:
	#  - window => Is the chat window widget (.msg_n - Where n is an integer)
	proc GetStatusText { window } {
		return [$window.statusbar getinnerframe].status
	}
	#///////////////////////////////////////////////////////////////////////////////


	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::GetStatusCharsTypedText (window)
	# Returns the path to the statusbar text widget in a given window 
	# Arguments:
	#  - window => Is the chat window widget (.msg_n - Where n is an integer)
	proc GetStatusCharsTypedText { window } {
		return [$window.statusbar getinnerframe].charstyped
	}
	#///////////////////////////////////////////////////////////////////////////////


	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::Clear (window)
	# Deletes all the text in the chat window's input widget
	# Arguments:
	#  - window => Is the chat window widget (.msg_n - Where n is an integer)
	proc Clear { window } {
		set window [::ChatWindow::getCurrentTab $window]
		[::ChatWindow::GetOutText $window] rodelete 0.0 end
	}
	#///////////////////////////////////////////////////////////////////////////////


	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::Close (window)
	# Called when a window is about to be closed, for example when we press ESC.
	# Arguments:
	#  - window => Is the window widget destroyed (.msg_n - Where n is an integer)
	proc Close { window } {
		if { $::ChatWindow::recent_message($window) == 1  && [::config::getKey recentmsg] == 1} {
			status_log "Recent message exists\n" white
			set ::ChatWindow::recent_message($window) 0
		} else {
			set idx [lsearch $::ChatWindow::windows $window]
			if { $idx != -1 } {
				set ::ChatWindow::windows [lreplace $::ChatWindow::windows $idx $idx]
			}
			destroy $window
		        ChatWindowDestroyed $window

		}
		
	}

	proc ContainerClose { window } {
		variable win2tab
		variable containerwindows

		set current [GetCurrentWindow $window]
		set currenttab [set win2tab($current)]

		if { [::ChatWindow::CountTabs $window] == 1 } {
			::ChatWindow::CloseTab $currenttab
			return
		}
		# Check for on-going SIP call
		foreach win [set containerwindows($window)] {
			if {[::amsn::SIPchatidExistsInList [Name $win]]} {
				status_log " we can't close, there's a sip call running ..." green
				if {[$::farsight IsVideo] } {
					::amsn::infoMsg [trans closeorcallvideo]
				} else {
					::amsn::infoMsg [trans closeorcall]
				}
				return
			}
		}
		
		if {[::config::getKey closeChatWindowWithTabs 0] == 1} {
			::ChatWindow::CloseAll $window
			destroy $window
		} elseif {[::config::getKey closeChatWindowWithTabs 0] == 2} {
			::ChatWindow::CloseTab $currenttab
		} else {
			set result [::amsn::customMessageBox [trans closeall] yesnocancel question [trans title] $window 1 1 "ContainerClose"]
			set answer [lindex $result 0]
			set rememberAnswer [lindex $result 1]
			
			if {$rememberAnswer == 1} {
				if {$answer == "yes"} {
					::config::setKey closeChatWindowWithTabs 1
				} elseif {$answer == "no"} {
					::config::setKey closeChatWindowWithTabs 0
				}
			}
			
			if { $answer == "yes" } {
				::ChatWindow::CloseAll $window
				destroy $window
			}
			if { $answer == "no" } {
				::ChatWindow::CloseTab $currenttab
			}
		}
	}

	proc DetachAll { w } {
		variable containerwindows
		variable containers
		variable containercurrent

		if {![info exists containerwindows($w)] || [winfo toplevel $w] != $w} {
			return
		}

		status_log "detaching containerwindows $w\n" red
		foreach window [set containerwindows($w)] {
			status_log "destroy $window\n" red
			DetachTab [set ::ChatWindow::win2tab($window)]
		}

		status_log "unsetting containerwindow and containercurrent\n" red
		unset containerwindows($w)
		unset containercurrent($w)

		status_log "unsetting containers array...\n" red
		foreach { key value } [array get containers] {
			if { $value == $w } {
				status_log "found containers $key $value\n" red
				unset containers($key)
			}
		}

		destroy $w
	        ChatWindowDestroyed $w
		
	}

	proc CountTabs { w } {
		return [llength [set ::ChatWindow::containerwindows($w)]]
	}

	proc CloseAllWindows {{force 0}} {
		variable windows
		variable containerwindows

		# check if there are still conversations open
		set winopen 0
		foreach win $windows {
			if {[winfo exists $win]} {
				set winopen 1
				break
			}
		}
		
		if {$force == 0} {
			if {$winopen == 1} {
				# ask whether those windows should be closed or not
				if {[::config::getKey closeChatWindowsAfterLogout 0] == 2} {
					return 1
				} elseif {[::config::getKey closeChatWindowsAfterLogout 0] != 1} {
					set result [::amsn::customMessageBox [trans closechatwindows] yesnocancel question [trans title] "" 1 1]
					set answer [lindex $result 0]
					set rememberAnswer [lindex $result 1]

					if {$rememberAnswer == 1} {
						if {$answer == "yes"} {
							::config::setKey closeChatWindowsAfterLogout 1
						} elseif {$answer == "no"} {
							::config::setKey closeChatWindowsAfterLogout 2
						}
					}

					if {$answer == "no"} {
						return 1
					} elseif {$answer == "cancel"} {
						return 0
					}
				}
			} else {
				return 1
			}
		}

		foreach win $windows {
			if {![winfo exists $win]} {
				continue
			}
			set upwin [winfo toplevel $win]

			if {[info exists containerwindows($upwin)]} {
				# this is a tabbed window, so closing all tabs does the trick
				CloseAll $upwin
				destroy $upwin
			} else {
				# this seems to be a normal window, so close the usual way
				Close $upwin
			}
		}

		set windows [list]

		return 1
	}

	proc CloseAll { w } {
		variable containerwindows
		variable containers
		variable containercurrent

		if {![info exists containerwindows($w)] || [winfo toplevel $w] != $w} {
			return
		}

		status_log "destroying containerwindows $w\n" red
		foreach window [set containerwindows($w)] {
			status_log "destroy $window\n" red
			destroy $window
		}

		status_log "unsetting containerwindow and containercurrent\n" red
		unset containerwindows($w)
		unset containercurrent($w)

		status_log "unsetting containers array...\n" red
		foreach { key value } [array get containers] {
			if { $value == $w } {
				status_log "found containers $key $value\n" red
				unset containers($key)
			}
		}
	}

	#///////////////////////////////////////////////////////////////////////////////


	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::Closed (window, path)
	# Called when a window and its children are destroyed. When the main window is
	# destroyed ($window == $path) then it tells the protocol layer to leave the
	# chat related to $window, and unsets variables used for that window.
	# Arguments:
	#  - window => Is the window widget destroyed (.msg_n - Where n is an integer)
	#  - path => Is the parent widget of the destroyed childrens (the window)
	proc Closed { window path } {

		#Only run when the parent window close event comes
		if { "$window" != "$path" } {
			return 0
		}

		set chatid [::ChatWindow::Name $window]

		if { $chatid == 0 } {
			status_log "VERY BAD ERROR in ::ChatWindow::Closed!!!\n" red
			return 0
		}

                if { [::OIM_GUI::IsOIM $chatid] == 1} {
                    if {[::abook::getKeepLogs $chatid]} {
                        ::log::StopLog $chatid
                    }
                } else {
                    foreach user_login [::MSN::usersInChat $chatid] {
                        if {[::abook::getKeepLogs $user_login]} {
                            ::log::StopLog $user_login
                        }
                    }
                }

		set evPar(chatid) chatid
		::plugins::PostEvent chatwindow_closed evPar

		::ChatWindow::UnsetFor $chatid $window
		unset ::ChatWindow::titles(${window})
		unset ::ChatWindow::first_message(${window})
		unset ::ChatWindow::recent_message(${window})

		#Delete images if not in use
		catch {destroy [GetInDisplayPictureFrame $window]}
		
		#Could be cleaner, but this works, destroying unused vars, saving mem
		catch {
			global [GetInputText ${window}]
			unset [GetInputText ${window}]
		}
		
		
		::MSN::leaveChat $chatid
		
		catch { unset ::amsn::lastchatwith(${chatid}) }
		if {[OnMac]} {
			MacBounceDone $window
		}
                TrayBlinkStop $window
	}
	#///////////////////////////////////////////////////////////////////////////////


	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::Configured (window)
	# This proc is called when we resize the window, it stores the new size in config
	# Arguments:
	#  - window => Is the chat window widget (.msg_n - Where n is an integer)
	proc Configured { window } {
		#only run this if the window is the outer window
		if { ![string equal $window [winfo toplevel $window]]} { return }

		set chatid [::ChatWindow::Name $window]

		if { $chatid != 0 } {
			after cancel [list ::ChatWindow::TopUpdate $chatid]
			after 200 [list ::ChatWindow::TopUpdate $chatid]
		}

		if { [::config::getKey savechatwinsize] } {
			if { [wm state $window] == "zoomed" } {
				::config::setKey winmaximized 1
			} elseif { [wm state $window] == "normal" } {
				::config::setKey winmaximized 0

				set geometry [wm geometry $window]
				set pos_start [string first "+" $geometry]

				::config::setKey winchatsize  [string range $geometry 0 [expr {$pos_start-1}]]
			}
		}
	}
	#///////////////////////////////////////////////////////////////////////////////

	proc ContainerConfigured { window } {

	
		#only run this if the window is the outer window
		if { ![string equal $window [winfo toplevel $window]]} { return }

		set chatid [::ChatWindow::Name $window]

		if { $chatid != 0 } {
			after cancel [list ::ChatWindow::TopUpdate $chatid]
			after 200 [list ::ChatWindow::TopUpdate $chatid]
		}

		set geometry [wm geometry $window]
		set pos_start [string first "+" $geometry]
		#Look if the window changed size with the configure

		if {[::config::getKey wincontainersize] != "[string range $geometry 0 [expr {$pos_start-1}]]"} {
			set sizechanged 1
		} else {
			set sizechanged 0
		}

		#Save size of current container
		if { [::config::getKey savechatwinsize] } {
			if { [wm state $window] == "zoomed" } {
				if { [::config::getKey winmaximized] != 1 } {
					::config::setKey winmaximized 1
					set sizechanged 1
				}
			} elseif { [wm state $window] == "normal" } {
				if { [::config::getKey winmaximized] != 0 } {
					::config::setKey winmaximized 0
					set sizechanged 1
				}

				::config::setKey wincontainersize  [string range $geometry 0 [expr {$pos_start-1}]]
			}
		}
	
		#If the window changed size use checkfortoomanytabs
		after cancel [list ::ChatWindow::CheckForTooManyTabs $window 0]
		if { [winfo exists ${window}.bar] && $sizechanged} {
			after 100 [list ::ChatWindow::CheckForTooManyTabs $window 0]
		}

	}

        proc TrayBlinkStart { window } {
            if { [OnWin] } { return }
            variable trayblinkwindows
            if { [::config::getKey blinktray] == 0 } {
		    if {[llength $trayblinkwindows] > 0} {
			    set trayblinkwindows [list]
			    after cancel ::ChatWindow::TrayBlink 0
			    after cancel ::ChatWindow::TrayBlink 1
			    statusicon_proc [::MSN::myStatusIs]
		    }
	        return
            }
            set idx [lsearch [set trayblinkwindows] $window]
            if {$idx == -1} {
                lappend trayblinkwindows $window
                after cancel ::ChatWindow::TrayBlink 0
                after cancel ::ChatWindow::TrayBlink 1
                ::ChatWindow::TrayBlink 1
            }
        }

        proc TrayBlinkStop { window } {
            if { [OnWin] } { return }
            variable trayblinkwindows
            set idx [lsearch [set trayblinkwindows] $window]
            if {$idx >= 0} {
                set trayblinkwindows [lreplace [set trayblinkwindows] $idx $idx]
                if { [llength $trayblinkwindows] == 0 } {
	            after cancel ::ChatWindow::TrayBlink 0
                    after cancel ::ChatWindow::TrayBlink 1
                    statusicon_proc [::MSN::myStatusIs]
                }
            }
        }

        proc TrayBlink { blink } {
            if { [OnWin] } { return }
            variable trayblinkwindows
            if { [::config::getKey blinktray] == 0 } {
                return
            }
            if { $blink == 0 } {
                statusicon_proc [::MSN::myStatusIs]
                after [::skin::getKey trayblink_delay] ::ChatWindow::TrayBlink 1
            } else {
                statusicon_blink_proc [::MSN::myStatusIs]
                after [::skin::getKey trayblink_delay]  ::ChatWindow::TrayBlink 0
            }
            if { [llength $trayblinkwindows] == 0 } {
                after cancel ::ChatWindow::TrayBlink 0
                after cancel ::ChatWindow::TrayBlink 1
                statusicon_proc [::MSN::myStatusIs]
            }
        }

	proc MacKeepBouncing { } {
		if {[catch {::carbon::notification "" 1} res]} {
			status_log $res
		}
		after 2000 ::ChatWindow::MacKeepBouncing
	}

	proc MacBounce { } {
		if { [::config::getKey dockbounce] == "never" } {
			return
		}

		set found 0
		foreach after_id [after info] {
			set cmd [lindex [after info $after_id] 0]
			if {$cmd == "::ChatWindow::MacKeepBouncing" } {
				set found 1
				break
			}
		}

		if {$found == 0 } {
			MacKeepBouncing
		}
		if { [::config::getKey dockbounce] == "once" } {
			MacBounceStop
		}
	}

	proc MacBounceStop { } {
		after cancel ::ChatWindow::MacKeepBouncing
		catch {::carbon::endNotification}
	}

	proc MacBounceStart { window } {
		variable macbouncewindows
                set idx [lsearch [set macbouncewindows] $window]
                if {$idx == -1 } {
			lappend macbouncewindows $window
			MacBounce
		}
	}

	proc MacBounceDone { window } {
		variable macbouncewindows
                set idx [lsearch [set macbouncewindows] $window]
		if {$idx >= 0 } {
	                set macbouncewindows [lreplace [set macbouncewindows] $idx $idx]
		}
		if {[llength $macbouncewindows] > 0 } {
			MacBounce
		} else {
			MacBounceStop
		}
	}


	proc MacRaiseWindows { } {
                variable macbouncewindows

		if {[llength $macbouncewindows] > 0 } {
			set win [lindex $macbouncewindows 0]
			if {[catch {wm state $win normal}]} {
				MacBounceDone $win
				MacRaiseWindows
			} else {
				raise $win
			}
			return 1
		} else {
			return 0
		}
	}


	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::Flicker (chatid, [count])
	# Called when a window must flicker, and called by itself to produce the flickering
	# effect. It will flicker the window until it gets the focus.
	# Arguments:
	#  - chatid => Is the name of the chat to flicker (a passport login)
	#  - count => [NOT REQUIRED] Can be any number, it's just used in self calls
	proc Flicker {chatid {count 0}} {
	
		if { [::ChatWindow::For $chatid] != 0 } {
			set window [::ChatWindow::For $chatid]
		} else {
			if { [winfo exists $chatid] } { 
				set window $chatid
			} else {
				return 0
			}
		}

		set ::ChatWindow::titles($window) [EscapeTitle [set ::ChatWindow::titles($window)]] 


		set container [GetContainerFromWindow $window]
		if { $container != "" } {
			FlickerTab $window 
			Flicker $container
			return
		}

		if { [::config::getKey flicker] == 0 } {
			if { [string first $window [focus]] != 0 } {
				catch {wm title ${window} "*$::ChatWindow::titles($window)"} res
				set ::ChatWindow::new_message_on(${window}) "asterisk"
				bind ${window} <FocusIn> "::ChatWindow::GotFocus ${window}"
				if {[OnMac]} {
					MacBounceStart $window
				}
                                TrayBlinkStart $window
			}
			return 0
		}

		after cancel ::ChatWindow::Flicker $chatid 0
		after cancel ::ChatWindow::Flicker $chatid 1

		if { [string first $window [focus]] != 0 } {

			# If user uses Windows, call winflash to flash the window, this is done by
			# calling the winflash proc that should be created by the flash.dll extension
			# so we do it in a catch statement, if it fails. Then load the extension before
			# calling winflash. If this one or the first one were successful, we add a bind
			# on FocusIn to call the winflash with the -state 0 option to disable it and we return.
                        TrayBlinkStart $window
			if { [OnWin] } {
				if { [catch {winflash $window -count 5} ] } {
					if { ![catch { 
						package require winflash
						winflash $window -count 5
					} ] } {
						bind $window <FocusIn> [list ::ChatWindow::GotFocusUnflash ${window}]
						return
					}
				} else {
					bind $window <FocusIn> [list ::ChatWindow::GotFocusUnflash ${window}]
					return
				}
			} elseif { [OnLinux] } {
				#if on the X window system
				if { [catch {linflash $window}] } {
					if { ![catch { 
						package require linflash
						linflash $window
					} ] } {
						bind $window <FocusIn> [list ::ChatWindow::GotFocusUnflash ${window}]
						return
					} else {
						
						# in case it didn't work, but we were able to set the 'urgency'
						# hint, we must unset it even if it failed, 
						# but still fallback to the flickering of the title.
						bind $window <FocusIn> [list ::ChatWindow::GotFocusUnflash ${window}]
					}
				} else {
					bind $window <FocusIn> [list ::ChatWindow::GotFocusUnflash ${window}]
					return
				}
			} elseif { [OnMac] } {
				#Dock Bouncing on Mac OS X
				MacBounceStart $window

			}
		

			set count  [expr {( $count +1 ) % 2}]

			if {![catch {
				if { $count == 1 } {
					wm title ${window} "[trans newmsg]"
				} else {
					wm title ${window} "$::ChatWindow::titles($window)"
				}
			} res]} {
				after 300 ::ChatWindow::Flicker $chatid $count
			}
			set ::ChatWindow::new_message_on(${window}) "flicker"
			
		} else {
			catch {wm title ${window} "$::ChatWindow::titles($window)"} res
			catch {unset ::ChatWindow::new_message_on(${window})}
			if {[OnMac]} {
				MacBounceDone $window
			}
                        TrayBlinkStop $window
		}
	}
	#///////////////////////////////////////////////////////////////////////////////


	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::For (chatid)
	# Returns the name of the window (.msg_n) that should show the messages and 
	# information related to the chat 'chatid'.
	# Arguments:
	#  - chatid => Is the chat id of the window, the passport account of the buddy
	proc For { chatid } {
		if { [info exists ::ChatWindow::msg_windows($chatid)]} {
			return $::ChatWindow::msg_windows($chatid)
		}
		return 0
	}
	#///////////////////////////////////////////////////////////////////////////////


	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::GotFocus (window)
	# Called when a window with a new msg gets the focus and goes back to its title
	# Arguments:
	#  - window => Is the window widget focused (.msg_n - Where n is an integer)
	proc GotFocus { window } {
		if { [info exists ::ChatWindow::new_message_on(${window})] && \
			$::ChatWindow::new_message_on(${window}) == "asterisk" } {
			unset ::ChatWindow::new_message_on(${window})
			catch {wm title ${window} "[EscapeTitle $::ChatWindow::titles(${window})]"} res
			bind ${window} <FocusIn> ""
			if {[OnMac]} {
				MacBounceDone $window
			}
                        TrayBlinkStop $window
		}
	}
	#///////////////////////////////////////////////////////////////////////////////

        proc GotFocusUnflash { window } {
            bind ${window} <FocusIn> ""
            if {[OnUnix]} {
                catch { linunflash $window }
            } elseif {[OnWin]} {
		    #catch { winflash $window -state 0 }
            }
            TrayBlinkStop $window
        }

	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::MacPosition
	# To place the ::ChatWindow::Open at the right place on Mac OS X, because the
	# window manager will put all the windows in bottom left after some time.
	# Arguments:
 	proc MacPosition { window } {
 		#To know where the window manager want to put the window in X and Y
 		set window [winfo toplevel $window]
 		set x_pos [winfo x $window]
 		set y_pos [winfo y $window]
 		
		#Determine the maximum place in Y to place a window
 		#Height of the screen - height of the window
 		set y_max [expr {[winfo vrootheight $window] - [winfo height $window]}]
 		#If the position of the window in y is greater than the maximum
 		#Then move the window upwards by the size of the window
 		if { $y_pos > $y_max } { 
			set y_pos [expr {$y_pos - [winfo height $window]}] 
		}
 		#If the result is smaller than 25 (on small screen) then use 25 
 		if { $y_pos < 25 } {
			set y_pos 25
		}
		
		#Determine the maximum place in X to place a window
		#Width of screen - width of window
		set x_max [expr {[winfo vrootwidth $window] - [winfo width $window]}]
 		#If the position of the window in x is greater than the maximum
 		#Then move the window to the left by the size of the window
		if { $x_pos > $x_max } {
			set x_pos [expr {$x_pos - [winfo width $window]}]
		}

		if { $x_pos < 2 } {
			set x_pos 2
		}
						
 		#Replace the window to the new position on the screen 	
 		wm geometry $window +${x_pos}+${y_pos}
	}
	#///////////////////////////////////////////////////////////////////////////////


	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::MakeFor (chatid, [msg ""], [usr_name ""])
	# Opens a window if it did not existed, and if it is the first message it adds
	# the message to a notify window (::amsn::notifyAdd), and plays sound if enabled
	# Arguments:
	#  - chatid => Is the chat id of the window, the passport account of the buddy
	#  - [msg ""] => [NOT REQUIRED] The message sent to us (first message)
	#  - [usr_name ""] => [NOT REQUIRED] Is the user who sends the message
	proc MakeFor { chatid {msg ""} {usr_name ""} } {
		set lastfocus [focus]
		set win_name [::ChatWindow::For $chatid]

		set new_window 0

		if { [::MSN::usersInChat $chatid] == $chatid && $usr_name == "" } {
			set usr_name $chatid
		}

		# If there wasn't a window created and assigned to $chatid, let's create one
		# through ::ChatWindow::Open and assign it to $chatid with ::ChatWindow::SetFor
		if { $win_name == 0 } {
			set new_window 1

			if { [UseContainer] == 0 } {

				set win_name [::ChatWindow::Open]

				::ChatWindow::SetFor $chatid $win_name

			} else {

				set container [::ChatWindow::GetContainerFor $chatid]

				set win_name [::ChatWindow::Open $container]
	
				::ChatWindow::SetFor $chatid $win_name
	
				::ChatWindow::NameTabButton $win_name $chatid

				set_balloon $::ChatWindow::win2tab($win_name) "--command--::ChatWindow::SetNickText $chatid"
				::ChatWindow::SwitchToTab $container [::ChatWindow::GetCurrentWindow $container]


			}
			#update idletasks

			::ChatWindow::TopUpdate $chatid

			if { [winfo exists [GetOutDisplayPicturesFrame $win_name].dps] } {
				::amsn::ShowOrHidePicture
				::amsn::ShowOrHideTopPicture
				::amsn::UpdatePictures $win_name
			} else {
				if { [::config::getKey showdisplaypic] && $usr_name != ""} {
					::amsn::ChangePicture $win_name [::skin::getDisplayPicture $usr_name] [trans showuserpic $usr_name]
				} else {
					::amsn::ChangePicture $win_name [::skin::getDisplayPicture $usr_name] [trans showuserpic $usr_name] nopack
				}
			}
		}

		set top_win [winfo toplevel $win_name]

		# PostEvent 'new_conversation' to notify plugins that the window was created
		if { $::ChatWindow::first_message($win_name) == 1 } {
			set evPar(chatid) chatid
			set evPar(usr_name) usr_name
			::plugins::PostEvent new_conversation evPar
		}

		# If this is the first message, and no focus on window, then show notify
		if { $::ChatWindow::first_message($win_name) == 1 && $msg != "" } {
			set ::ChatWindow::first_message($win_name) 0
	

		
			if { [::config::getKey newmsgwinstate] == 0 } {
				if { [winfo exists .bossmode] } {
					set ::BossMode(${win_name}) "normal"
					wm state ${top_win} withdraw
				} else {
					if { [::config::getKey winmaximized 0] == 1 } {
						wm state ${top_win} zoomed
					} else {
						wm state ${top_win} normal
					}
				}

				wm deiconify ${top_win}

				if { [OnMac] } {
					::ChatWindow::MacPosition ${top_win}
				} else {
					raise ${top_win}
				}
				
			} else {
				# Iconify the window unless it was raised by the user already.
				if { [wm state $top_win] != "normal" && [wm state $top_win] != "zoomed" } {
					if { [winfo exists .bossmode] } {
						set ::BossMode(${top_win}) "iconic"
						wm state ${top_win} withdraw
					} else {
						wm state ${top_win} iconic
					}
				}
			}
			if { [string first ${win_name} [focus]] != 0} {
				if { ([::config::getKey notifymsg] == 1 && [::abook::getContactData $chatid notifymsg -1] != 0) ||
				[::abook::getContactData $chatid notifymsg -1] == 1 } {
					::amsn::notifyAdd "$msg" "::amsn::chatUser $chatid" "" message
					#Regive focus on Mac OS X / TkAqua
					if { [OnMac] } {
						after 1000 "catch {focus -force $lastfocus}"
					}
				}
			}
		} elseif { $::ChatWindow::first_message($win_name) == 1 && $msg == "" } {
			#If it's not a message event, then it's a window creation (user joins to chat)
			if { [::config::getKey newchatwinstate] == 0 } {
				if { [winfo exists .bossmode] } {
					set ::BossMode(${top_win}) "normal"
					wm state ${top_win} withdraw
				} else {
					if { [::config::getKey winmaximized 0] == 1 } {
						wm state ${top_win} zoomed
					} else {
						wm state ${top_win} normal
					}
				}

				wm deiconify ${top_win}

				if { [OnMac] } {
					::ChatWindow::MacPosition ${top_win}
				} else {
					raise ${top_win}
				}
			} else {
				#Container for tabs might be non-iconified
				if { [wm state $top_win] != "normal" } {
					if { [winfo exists .bossmode] } {
						set ::BossMode(${top_win}) "iconic"
						wm state ${top_win} withdraw
					} else {
						wm state ${top_win} iconic
					}
				}
			}
		}

		if { $new_window == 1 || [::config::getKey sound_on_first_message 0] == 0 } {
			#If no focus, and it's a message event, do something to the window
			if { (([::config::getKey soundactive] == "1" && $usr_name != [::config::getKey login]) || \
				  [string first ${win_name} [focus]] != 0) && ($msg != "" || [::config::getKey sound_on_first_message 0] == 1)} {
				play_sound type.wav
			}
		}

		return $win_name
	}
	#///////////////////////////////////////////////////////////////////////////////


	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::Name (window)
	# This proc returns the user login (chatid) of the buddy in that chat.
	# Arguments:
	#  - window => Is the chat window widget (.msg_n - Where n is an integer)
	proc Name { window } {
		if { [info exists ::ChatWindow::chat_ids($window)]} {
			return $::ChatWindow::chat_ids($window)
		}
		return 0
	}
	#///////////////////////////////////////////////////////////////////////////////

	# ::ChatWindow::getAllChatIds
	# Returns a list of all chatids of all open windows

	proc getAllChatIds { } {

		set chatids ""
		foreach win_name [array names ::ChatWindow::chat_ids] {
			lappend chatids [::ChatWindow::Name $win_name]
		}
		return $chatids
	}


	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::Open () 
	# Creates a new chat window and returns its name (.msg_n - Where n is winid)
	proc Open { {container ""} } {

		#calling procs check for [UseContainer] as they have to give the container's path]
		if { $container == "" } {
			set w [CreateTopLevelWindow]
	
			set mainmenu [CreateMainMenu $w]
			$w conf -menu $mainmenu

			if { ![OnMac] } {
			    # Bind, add new container to list of CWs and restore old setting for the show/hide CW menus
			    bind $w <Control-m> "::ChatWindow::ShowHideChatWindowMenus $w 1"
			    NewChatWindowCreated $w $mainmenu
			    ShowHideChatWindowMenus $w 0
			}

			#Send a postevent for the creation of menu
			set evPar(window_name) "$w"
			set evPar(menu_name) "$mainmenu"
			::plugins::PostEvent chatmenu evPar

			#bind on configure for saving the window shape
			bind $w <Configure> "::ChatWindow::Configured %W"

		} else {
			set w [CreateTabbedWindow $container]
		} 

		set copypastemenu [CreateCopyPasteMenu $w]
		set copymenu [CreateCopyMenu $w]


		# Create the window's elements
		set top [CreateTopFrame $w]
		set statusbar [CreateStatusBar $w]
		set paned [CreatePanedWindow $w]

		# Pack them

		if {[::skin::getKey chat_show_topframe]} {
			pack $top -side top -expand false -fill x -padx [::skin::getKey chat_top_padx]\
				 -pady [::skin::getKey chat_top_pady]
		}

		if {[::skin::getKey chat_show_statusbarframe]} {
			pack $statusbar -side bottom -expand false -fill x\
				-padx [::skin::getKey chat_status_padx] -pady [::skin::getKey chat_status_pady]
		}
		pack $paned -side top -expand true -fill both -padx [::skin::getKey chat_paned_padx]\
		 -pady [::skin::getKey chat_paned_pady]

		focus [::ChatWindow::GetInputText $w]
		
		# Sets the font size to the one stored in our configuration file
		change_myfontsize [::config::getKey textsize] $w


		# Set the properties of this chat window in our ::ChatWindow namespace
		# variables to be accessible from other procs in the namespace
		set ::ChatWindow::titles($w) ""
		set ::ChatWindow::first_message($w) 1
		set ::ChatWindow::recent_message($w) 0
		lappend ::ChatWindow::windows "$w"


		# PostEvent 'new_chatwindow' to notify plugins that the window was created
		set evPar(win) "$w"
		::plugins::PostEvent new_chatwindow evPar

		if { $container != "" } {
			AddWindowToContainer $container $w
		} else {
			searchdialog $w.search 
		        $w.search hide 
		        $w.search bindwindow $w 
       		 	$w.search configure -searchin [::ChatWindow::GetOutText $w]

			if { ![OnMac] } {
				::ChatWindow::MacPosition $w
			}
		}

		return "$w"
	}
	#///////////////////////////////////////////////////////////////////////////////

	
	proc CloseTabInContainer { container } {
		set win [::ChatWindow::GetCurrentWindow $container]
		set tab [set ::ChatWindow::win2tab($win)]
		::ChatWindow::CloseTab $tab
		
	}

	proc CreateNewContainer { } { 
		set container [CreateContainerWindow]
		set mainmenu [CreateMainMenu $container]
		$container configure -menu $mainmenu

		if { ![OnMac] } {
		    # Bind, add new container to list of CWs and restore old setting for the show/hide CW menus
		    bind $container <Control-m> "::ChatWindow::ShowHideChatWindowMenus $container 1"
		    NewChatWindowCreated $container $mainmenu
		    ShowHideChatWindowMenus $container 0
		}

		#Change Close item menu because the behavior is not the same with tabs
		$container.menu.msn delete "[trans close]"
		if { [OnMac] } {
			$container.menu.msn add command -label "[trans close]" \
				-command "::ChatWindow::CloseTabInContainer $container" -accelerator "Command-W"
		} else {
			$container.menu.msn add command -label "[trans close]" \
				-command "::ChatWindow::CloseTabInContainer $container"
		}
		

		#we bind <Escape> to close the current tab
		#set current [GetCurrentWindow $container]
		#set currenttab [set win2tab($current)]
		#bind $container <<Escape>> "::ChatWindow::CloseTab \[set ::ChatWindow::win2tab(\[::ChatWindow::GetCurrentWindow $container\])\]"
		if {[::config::getKey escape_close_cw 1] == 1} {
			bind $container <<Escape>> [list ::ChatWindow::CloseTabInContainer $container]
		}
		
		#Send a postevent for the creation of menu
		set evPar(window_name) "$container"
		set evPar(menu_name) "$mainmenu"
		::plugins::PostEvent chatmenu evPar
		
		
		#bind on configure for saving the window shape
		
		bind $container <Configure> "::ChatWindow::ContainerConfigured %W"

		set tabbar [CreateTabBar $container] 
		pack $tabbar -side top -fill both -expand false

		return $container

	}


	proc CreateTabBar { w } {
		set bar $w.bar
		set less ${bar}.less
		set more ${bar}.more

		::skin::setPixmap tab tab.gif
		::skin::setPixmap tab_close tab_close.gif

		::skin::setPixmap tab_close_hover tab_close_hover.gif
		::skin::setPixmap tab_hover tab_hover.gif

		::skin::setPixmap tab_current tab_current.gif
		::skin::setPixmap tab_flicker tab_flicker.gif
		::skin::setPixmap moretabs moretabs.gif
		::skin::setPixmap lesstabs lesstabs.gif
		
		set less_w [image width [::skin::loadPixmap moretabs]] 
		set more_w [image width [::skin::loadPixmap lesstabs]]

		frame $bar -class Amsn -relief solid -bg [::skin::getKey tabbarbg] -bd 0

		label $less -image [::skin::loadPixmap lesstabs] \
		    -width $less_w -bg [::skin::getKey tabbarbg] -bd 0 -relief flat \
		    -activebackground [::skin::getKey tabbarbg] -highlightthickness 0 -pady 0 -padx 0
		bind $less <<Button1>> "::ChatWindow::LessTabs $w $less $more"
		label $more -image [::skin::loadPixmap moretabs] \
		    -width $more_w -bg [::skin::getKey tabbarbg] -bd 0 -relief flat \
		    -activebackground [::skin::getKey tabbarbg] -highlightthickness 0 -pady 0 -padx 0
		bind $more <<Button1>> "::ChatWindow::MoreTabs $w $less $more"

		if { $::tcl_version >= 8.4 } {
			$bar configure  -padx [::skin::getKey chat_tabbar_padx] -pady [::skin::getKey chat_tabbar_pady]
			$less configure -compound center
			$more configure -compound center
		}

		return $bar
	}

	###################################################
	# CreateContainerWindow
	# This proc should create the toplevel window for a chat window
	# container and configure it and then return it's pathname
	#
	proc CreateContainerWindow { } {
		set w ".container_$::ChatWindow::containerid"
		incr ::ChatWindow::containerid
			
		chatwindow $w -background [::skin::getKey chatwindowbg]	-borderwidth 0
#		::Event::registerEvent messageReceived all $w
		
		# If there isn't a configured size for Chat Windows, use the default one and store it.
		if {[catch { wm geometry $w [::config::getKey wincontainersize] } res]} {
			wm geometry $w 350x390
			::config::setKey wincontainersize 350x390
			::config::setKey winmaximized 0
			status_log "No config(winchatsize). Setting default size for chat window\n" red
		}

		if { [winfo exists .bossmode] } {
			set ::BossMode($w) "iconic"
			wm state $w withdraw
		} else {
			wm state $w iconic
		}

		wm title $w "[trans chat]"
		wm group $w .

		# If the platform is NOT windows, set the windows' icon to our xbm
		if { ![OnWin] && [version_vcompare [info patchlevel] 8.4.8] >= 0 } {
			catch {wm iconbitmap $w @[::skin::GetSkinFile pixmaps amsn.xbm]}
			catch {wm iconmask $w @[::skin::GetSkinFile pixmaps amsnmask.xbm]}
		}

		# Create the necessary bindings
		bind $w <<Cut>> "status_log cut\n;tk_textCut \[::ChatWindow::GetCurrentWindow $w\]"
		bind $w <<Copy>> "status_log copy\n;tk_textCopy \[::ChatWindow::GetCurrentWindow $w\]"
		bind $w <<Paste>> "status_log paste\n;tk_textPaste \[::ChatWindow::GetCurrentWindow $w\]"

		# Different shortcuts for MacOS
		if { [OnMac] } {
			bind $w <Command-Option-h> "::amsn::ShowChatList \"[trans history]\" \[::ChatWindow::getCurrentTab $w\] ::log::OpenLogWin"

			# Control-w for closing current tab not implemented on Mac (germinator)
			bind $w <Command-Right> "::ChatWindow::GoToNextTab $w"
			bind $w <Command-Left> "::ChatWindow::GoToPrevTab $w"
                        
			bind $w <Control-Tab> "::ChatWindow::GoToNextTab $w"
			bind $w <Control-Shift-Tab> "::ChatWindow::GoToPrevTab $w"
			#Implement bindings for webcam, see below?
		} else {
			bind $w <Control-h> \
				"::amsn::ShowChatList \"[trans history]\" \[::ChatWindow::GetCurrentWindow $w\] ::log::OpenLogWin"
			bind $w <Control-H> \
				"::amsn::ShowChatList \"[trans history]\" \[::ChatWindow::GetCurrentWindow $w\] ::log::OpenLogWin"
			bind $w <Control-w> "::ChatWindow::CloseTab \[set ::ChatWindow::win2tab(\[::ChatWindow::GetCurrentWindow $w\])\]"
			bind $w <Control-W> "::ChatWindow::CloseTab \[set ::ChatWindow::win2tab(\[::ChatWindow::GetCurrentWindow $w\])\]"
			bind $w <Control-Tab> "::ChatWindow::GoToNextTab $w"
			bind $w <Control-Shift-Tab> "::ChatWindow::GoToPrevTab $w"
			bind $w <Control-Next> "::ChatWindow::GoToNextTab $w"
			bind $w <Control-Prior> "::ChatWindow::GoToPrevTab $w"
			bind $w <Control-n> "::AVAssistant::AVAssistant"
			bind $w <Control-N> "::AVAssistant::AVAssistant"
		}

		searchdialog $w.search
		$w.search hide
		$w.search bindwindow $w

		if {[::config::getKey escape_close_cw 1] == 1} {
			bind $w <<Escape>> "::ChatWindow::ContainerClose $w; break"
		}
		bind $w <Destroy> "::ChatWindow::DetachAll %W"

		# These bindings are handlers for closing the window (Leave the SB, store settings...)
		wm protocol $w WM_DELETE_WINDOW "::ChatWindow::ContainerClose $w"


		return $w
	}


	proc CreateTabbedWindow { container } {

		set w "${container}.msg_${::ChatWindow::winid}"
		incr ::ChatWindow::winid

		status_log "tabbed window is : $w\n" red

		frame $w -background [::skin::getKey chatwindowbg] -relief solid -bd 0 -padx 0 -pady 0

		# If the platform is NOT windows, set the windows' icon to our xbm
		if { ![OnWin] && [version_vcompare [info patchlevel] 8.4.8] >= 0 } {
			catch {wm iconbitmap $w @[::skin::GetSkinFile pixmaps amsn.xbm]}
			catch {wm iconmask $w @[::skin::GetSkinFile pixmaps amsnmask.xbm]}
		}


		# Create the necessary bindings
		bind $w <<Cut>> "status_log cut\n;tk_textCut $w"
		bind $w <<Copy>> "status_log copy\n;tk_textCopy $w"
		bind $w <<Paste>> "status_log paste\n;tk_textPaste $w"

		#Change shortcut for history on Mac OS X
		if { [OnMac] } {
			bind $w <Command-Option-h> \
				"::amsn::ShowChatList \"[trans history]\" $w ::log::OpenLogWin"
		} else {
			bind $w <Control-h> \
				"::amsn::ShowChatList \"[trans history]\" $w ::log::OpenLogWin"
		}
		#I think it's not needed because the container already have <<escape>> binding
		#bind $w <<Escape>> "::ChatWindow::Close $w; break"
		bind $w <Destroy> "window_history clear %W; ::ChatWindow::Closed $w %W"


		return $w
	
	}
	###################################################
	# CreateTopLevelWindow
	# This proc should create the toplevel window for a chat window
	# configure it and then return it's pathname
	#
	proc CreateTopLevelWindow { } {
	
		set w ".msg_$::ChatWindow::winid"
		incr ::ChatWindow::winid
			
		toplevel $w -class Amsn -background [::skin::getKey chatwindowbg]	
		
		# If there isn't a configured size for Chat Windows, use the default one and store it.
		if {[catch { wm geometry $w [::config::getKey winchatsize] } res]} {
			wm geometry $w 350x390
			::config::setKey winchatsize 350x390
			::config::setKey winmaximized 0
			status_log "No config(winchatsize). Setting default size for chat window\n" red
		}

		if { [winfo exists .bossmode] } {
			set ::BossMode($w) "iconic"
			wm state $w withdraw
		} else {
			wm state $w iconic
		}

#		wm title $w "[trans chat]"
		wm group $w .

		# If the platform is NOT windows, set the windows' icon to our xbm
		if { ![OnWin] && [version_vcompare [info patchlevel] 8.4.8] >= 0 } {
			catch {wm iconbitmap $w @[::skin::GetSkinFile pixmaps amsn.xbm]}
			catch {wm iconmask $w @[::skin::GetSkinFile pixmaps amsnmask.xbm]}
		}


		# Create the necessary bindings
		bind $w <<Cut>> "status_log cut\n;tk_textCut $w"
		bind $w <<Copy>> "status_log copy\n;tk_textCopy $w"
		bind $w <<Paste>> "status_log paste\n;tk_textPaste $w"

		#Change shortcut for history on Mac OS X
		if { [OnMac] } {
			bind $w <Command-Option-h> \
				"::amsn::ShowChatList \"[trans history]\" $w ::log::OpenLogWin"
		} else {
			bind $w <Control-h> \
				"::amsn::ShowChatList \"[trans history]\" $w ::log::OpenLogWin"
		}

		if {[::config::getKey escape_close_cw 1] == 1} {
			bind $w <<Escape>> "::ChatWindow::Close $w; break"
		}
		bind $w <Destroy> "window_history clear %W; ::ChatWindow::Closed $w %W"

		#Different shortcuts on Mac OS X
		if { [OnMac] } {
			bind $w <Command-,> "Preferences"
		}


		# These bindings are handlers for closing the window (Leave the SB, store settings...)
		wm protocol $w WM_DELETE_WINDOW "::ChatWindow::Close $w"


		return $w

	}

	proc NewChatWindowCreated { window menu }  {
	    variable chatWindowMenus
	    set chatWindowMenus($window) $menu
	}
	proc ChatWindowDestroyed { window }  {
	    variable chatWindowMenus
	    array unset chatWindowMenus $window
	}

	proc ShowHideChatWindowMenus { {window .} {toggle 0} } {
	    variable chatWindowMenus

	    if {$toggle} { 
		if { [::config::getKey showcwmenus -1] == -1 } {
		    if { [ShowFirstTimeMenuHidingFeature $window] == 0 } {
			return
		    }
		}
		::config::setKey showcwmenus [expr ![::config::getKey showcwmenus -1]] 
		
	    } 
	    
	    if { [::config::getKey showcwmenus -1]} {
		foreach win [array names chatWindowMenus] {
		    if { [winfo exists $win] } {
			$win configure -menu [set chatWindowMenus($win)]
		    }
		}
	    } else {
		foreach win [array names chatWindowMenus] {
		    if { [winfo exists $win] } {
			$win configure -menu {}
		    }
		}
	    }

	}

	#############################################
	# CreateMainMenu $w
	# This proc should create the main menu of the chat window
	# it only creates the menu supposed to appear in the menu bar actually
	#
	proc CreateMainMenu { w } {
		set mainmenu $w.menu	

		if {[package provide pixmapmenu] != "" && \
			[info commands pixmapmenu_isEnabled] != "" && [pixmapmenu_isEnabled]} {
			pack [menubar $mainmenu] -fill x -side top
		} else {
			menu $mainmenu -tearoff 0 -type menubar -borderwidth 0 -activeborderwidth -0
		}

		# App menu, only on Mac OS X (see Mac Interface Guidelines)
		if { [OnMac] } { create_apple_menu $mainmenu }

		set chatmenu [CreateChatMenu $w $mainmenu]
		set editmenu [CreateEditMenu $w $mainmenu]
		set viewmenu [CreateViewMenu $w $mainmenu]
		set actionsmenu [CreateActionsMenu $w $mainmenu]
		set contactmenu [CreateContactMenu $w $mainmenu]
		set helpmenu [CreateHelpMenu $w $mainmenu]

		#no need to call it "file"
		# http://developer.apple.com/documentation/UserExperience/Conceptual/OSXHIGuidelines/index.html
		$mainmenu add cascade -label "[trans chat]" -menu $chatmenu
		$mainmenu add cascade -label "[trans edit]" -menu $editmenu
		$mainmenu add cascade -label "[trans view]" -menu $viewmenu
		$mainmenu add cascade -label "[trans actions]" -menu $actionsmenu		
		$mainmenu add cascade -label "[trans contact]" -menu $contactmenu
		if { [OnMac] } {
			# Add a window menu as required by Apple's HIG.
			package require windowlist
			set window [windowlist::windowMenu $mainmenu]
		}
		$mainmenu add cascade -label "[trans help]" -menu $helpmenu

		return $mainmenu
	}

	#############################################
	# CreateChatMenu $menu
	# This proc should create the Chat submenu of the chat window
	#
	proc CreateChatMenu { w menu } {
		set chatmenu $menu.msn
		menu $chatmenu -tearoff 0 -type normal

		#new chat
		$chatmenu add command -label "[trans newchat]..." \
			-command [list ::amsn::ShowUserList [trans sendmsg] ::amsn::chatUser]
			
		if { [OnMac] } {
			#----------------------
			$chatmenu add separator
			
			$chatmenu add command -label "[trans close]" \
				-command "::ChatWindow::Close $w" -accelerator "Command-W"
		} 
		
		#Save
		$chatmenu add command -label "[trans savetofile]..." \
			-command "::ChatWindow::SaveToFile \[::ChatWindow::getCurrentTab $w\]"		

		#----------------------
		$chatmenu add separator
		
		#Invite a user to the chat
		$chatmenu add command -label "[trans invite]..." \
			-command "::amsn::ShowInviteList \"[trans invite]\" \[::ChatWindow::getCurrentTab $w\]"


#TODO:		#powertool should add the "hide window" thing here	
#		if { ![OnMac] } {
#			$chatmenu add command -label "[trans hidewindow]" \
#				-command "wm state \[winfo toplevel \[::ChatWindow::getCurrentTab $w\]\] withdraw"
#		}

		if { ![OnMac] } {
			#----------------------
			$chatmenu add separator

			$chatmenu add command -label "[trans close]" \
				-command "::ChatWindow::Close $w"
		}
		
		return $chatmenu
		
	}

	#############################################
	# CreateEditMenu $menu
	# This proc should create the Edit submenu of the chat window
	#
	proc CreateEditMenu { w menu } {

		set editmenu $menu.edit

		menu $editmenu -tearoff 0 -type normal

		#Change the accelerator on Mac OS X
		if { [OnMac] } {
			$editmenu add command -label "[trans cut]" \
				-command "tk_textCut \[::ChatWindow::getCurrentTab $w\]" -accelerator "Command+X"
			$editmenu add command -label "[trans copy]" \
				-command "tk_textCopy \[::ChatWindow::getCurrentTab $w\]" -accelerator "Command+C"
			$editmenu add command -label "[trans paste]" \
				-command "tk_textPaste \[::ChatWindow::getCurrentTab $w\]" -accelerator "Command+V"
			$editmenu add separator
			$editmenu add command \-label "[trans find]" \
				-command "$w.search show" -accelerator "Command+F"
			$editmenu add command -label "[trans findnext]" -command "$w.search findnext" -accelerator "Command+G"
			$editmenu add command -label "[trans findprev]" -command "$w.search findprev" -accelerator "Command+Shift+G"
			$editmenu add separator
			$editmenu add command -label "[trans editavsettings]" \
				 -command "::AVAssistant::AVAssistant" ;#Accelerator?
		} else {
			$editmenu add command -label "[trans cut]" \
				-command "tk_textCut \[::ChatWindow::getCurrentTab $w\]" -accelerator "Ctrl+X"
			$editmenu add command -label "[trans copy]" \
				-command "tk_textCopy \[::ChatWindow::getCurrentTab $w\]" -accelerator "Ctrl+C"
			$editmenu add command -label "[trans paste]" \
				-command "tk_textPaste \[::ChatWindow::getCurrentTab $w\]" -accelerator "Ctrl+V"
			$editmenu add separator
			$editmenu add command -label "[trans find]" \
				-command "$w.search show" -accelerator "Ctrl+F"
			$editmenu add command -label "[trans findnext]" -command "$w.search findnext" -accelerator "F3"
			$editmenu add command -label "[trans findprev]" -command "$w.search findprev" -accelerator "Shift+F3"
			$editmenu add separator
			$editmenu add command -label "[trans editavsettings]" \
				-command "::AVAssistant::AVAssistant"  -accelerator "Ctrl+N"
		}

		return $editmenu
	}


	#############################################
	# CreateViewMenu $menu
	# This proc should create the View submenu of the chat window
	#
	proc CreateViewMenu { w menu } {

		set viewmenu $menu.view
		menu $viewmenu -tearoff 0 -type normal

		#show emoticons check
		$viewmenu add checkbutton -label "[trans chatsmileys]" \
			-onvalue 1 -offvalue 0 -variable [::config::getVar chatsmileys]

		#show dp check
		$viewmenu add checkbutton -label "[trans showdisplaypic]" \
		    -command "::amsn::ShowOrHidePicture"\
		    -onvalue 1 -offvalue 0 -variable [::config::getVar showdisplaypic]
		# Show the button bar check
		$viewmenu add checkbutton -label "[trans hidebuttonbar]" \
		    -command [list ::ChatWindow::ShowOrHideButtonBar]  \
		    -onvalue 0 -offvalue 1 -variable [::config::getVar ShowButtonBar]
		
		#----------------------
		$viewmenu add separator			
		
		#chatstyle
		$viewmenu add cascade -label "[trans style]" -menu [CreateStyleMenu $viewmenu]

		#textstyle
		$viewmenu add cascade -label "[trans textsize]" -menu [CreateTextSizeMenu $viewmenu]

		#changefont
		$viewmenu add command -label "[trans changefont]" -command "after 1 change_font [string range $w 1 end] mychatfont"


		#----------------------
		$viewmenu add separator

		#Clear
		$viewmenu add command -label "[trans clear]" -command [list ::ChatWindow::Clear $w]


		return $viewmenu
	}

	#############################################
	# CreateTextSizeMenu $menu
	# This proc should create the TextSize submenu of the View menu
	# of the chat window
	#
	proc CreateTextSizeMenu { menu } {
		set textsizemenu $menu.textsize
		menu $textsizemenu -tearoff 0 -type normal

		$textsizemenu add radiobutton -label "[trans smallest]" -value -2 -variable [::config::getVar textsize] -command "change_myfontsize -2"
		$textsizemenu add radiobutton -label "[trans small]" -value -1 -variable [::config::getVar textsize] -command "change_myfontsize -1"
		$textsizemenu add radiobutton -label "[trans medium]" -value 0 -variable [::config::getVar textsize] -command "change_myfontsize 0"
		$textsizemenu add radiobutton -label "[trans large]" -value 2 -variable [::config::getVar textsize] -command "change_myfontsize 2"
		$textsizemenu add radiobutton -label "[trans largest]" -value 4 -variable [::config::getVar textsize] -command "change_myfontsize 4"
	
		return $textsizemenu
	}

	#############################################
	# CreateStyleMenu $menu
	# This proc should create the Style submenu of the View menu
	# of the chat window
	#
	proc CreateStyleMenu { menu } { 

		set stylemenu $menu.style
		menu $stylemenu -tearoff 0 -type normal

		$stylemenu add radiobutton -label "[trans msnstyle]" \
			-value "msn" -variable [::config::getVar chatstyle]
		$stylemenu add radiobutton -label "[trans ircstyle]" \
			-value "irc" -variable [::config::getVar chatstyle]
		$stylemenu add radiobutton -label "[trans compactstyle]" \
			-value "compact" -variable [::config::getVar chatstyle]
		$stylemenu add radiobutton -label "[trans customstyle]..." \
			-value "custom" -variable [::config::getVar chatstyle] \
			-command "::amsn::enterCustomStyle"

		return $stylemenu

	}

	#############################################
	# CreateActionsMenu $w $menu
	# This proc should create the Actions submenu of the chat window
	#
	proc CreateActionsMenu { w menu } {
		set actionsmenu $menu.actions

		menu $actionsmenu -tearoff 0 -type normal

		$actionsmenu add command -label "[trans sendfile]..." \
			-command "::amsn::FileTransferSend \[::ChatWindow::getCurrentTab $w\]"

		$actionsmenu add separator

		$actionsmenu add command -label "[trans askcam]..." \
			-command "::amsn::ShowChatList \"[trans askcam]\" \[::ChatWindow::getCurrentTab $w\] ::MSNCAM::AskWebcamQueue"

		$actionsmenu add command -label "[trans sendcam]..." \
			-command "::amsn::ShowChatList \"[trans sendcam]\" \[::ChatWindow::getCurrentTab $w\] ::MSNCAM::SendInviteQueue"
		
		global enable_sip
		if {$enable_sip} {
			$actionsmenu add command -label "[trans sendsip]..." \
			    -command "::amsn::ShowChatList \"[trans sendsip]\" \[::ChatWindow::getCurrentTab $w\] \"::amsn::SIPCallInviteUser 0\""

			$actionsmenu add command -label "[trans sendvideosip]..." \
			    -command "::amsn::ShowChatList \"[trans sendvideosip]\" \[::ChatWindow::getCurrentTab $w\] \"::amsn::SIPCallInviteUser 1\""
		}

		$actionsmenu add separator

		$actionsmenu add cascade -label "[trans playgame]" -menu [::MSNGamesGUI::buildMenu $actionsmenu $w]
		
		#nudge to add item here
	
		return $actionsmenu
	}


	#############################################
	# Createcontactmenu $menu
	# This proc should create the Contact submenu of the chat window
	#
	proc CreateContactMenu { w menu } {
		set contactmenu $menu.contact

		menu $contactmenu -tearoff 0 -type normal


		#Chat history
		if { [OnMac] } {
			$contactmenu add command -label "[trans history]" \
				-command "::amsn::ShowChatList \"[trans history]\" \[::ChatWindow::getCurrentTab $w\] ::log::OpenLogWin" \
				-accelerator "Command-Option-H"
		} else {
			$contactmenu add command -label "[trans history]" \
				-command "::amsn::ShowChatList \"[trans history]\" \[::ChatWindow::getCurrentTab $w\] ::log::OpenLogWin" \
				-accelerator "Ctrl+H"
		}

		#webcam history
		$contactmenu add command -label "[trans webcamhistory]" \
		    -command "::amsn::ShowChatList \"[trans webcamhistory]\" \[::ChatWindow::getCurrentTab $w\] ::log::OpenCamLogWin" 

		#received files
		$contactmenu add command -label "[trans openreceived]..." \
			-command {launch_filemanager "[::config::getKey receiveddir]"}


		#-------------------------
		$contactmenu add separator
		
		#profile
		$contactmenu add command -label "[trans viewprofile]" \
			-command "::amsn::ShowChatList \"[trans viewprofile]\" \[::ChatWindow::getCurrentTab $w\] ::hotmail::viewProfile"		
		
		#email
		$contactmenu add command -label "[trans sendmail]..." \
			-command "::amsn::ShowChatList \"[trans sendmail]\" \[::ChatWindow::getCurrentTab $w\] launch_mailer"		
		
		#sms
		$contactmenu add command -label "[trans sendmobmsg]..." \
			-command "::amsn::ShowChatList \"[trans sendmobmsg]\" \[::ChatWindow::getCurrentTab $w\] ::MSNMobile::OpenMobileWindow"

		#-------------------------
		$contactmenu add separator
		
		#block/unblock
		$contactmenu add command -label "[trans block]/[trans unblock]" \
			-command "::amsn::ShowChatList \"[trans block]/[trans unblock]\" \[::ChatWindow::getCurrentTab $w\] ::amsn::blockUnblockUser"		
		
		#add to list
		$contactmenu add command -label "[trans addtocontacts]" \
			-command "::amsn::ShowAddList \"[trans addtocontacts]\" \[::ChatWindow::getCurrentTab $w\] ::MSN::addUser"


		#-------------------------
		$contactmenu add separator

		#alarm
		$contactmenu add command -label "[trans cfgalarm]" \
			-command "::amsn::ShowChatList \"[trans cfgalarm]\" \[::ChatWindow::getCurrentTab $w\] ::abookGui::showUserAlarmSettings"


		#-------------------------
		$contactmenu add separator

		#properties							
		$contactmenu add command -label "[trans properties]" \
			-command "::amsn::ShowChatList \"[trans properties]\" \[::ChatWindow::getCurrentTab $w\] ::abookGui::showUserProperties"

		
		return $contactmenu
	}
	
	#############################################
	# CreateHelpMenu $w $menu
	# This proc should create the Actions submenu of the chat window
	#
	proc CreateHelpMenu { w menu } {
		set helpmenu $menu.helpmenu

		menu $helpmenu -tearoff 0 -type normal

		$helpmenu add command -label "[trans helpcontents]" \
			-command "::amsn::showHelpFileWindow HELP [list [trans helpcontents]]"

		$helpmenu add separator

		$helpmenu add command -label "[trans about]" -command ::amsn::aboutWindow

		return $helpmenu
	}	


	################################################
	# CreateCopyPasteMenu
	# This proc creates the menu shown when a user right clicks 
	# on the input of the chat window
	#
	proc CreateCopyPasteMenu { w } {
		set menu $w.copypaste

		menu $menu -tearoff 0 -type normal

		$menu add command -label [trans cut] \
			-command "status_log cut\n;tk_textCut $w"
		$menu add command -label [trans copy] \
			-command "status_log copy\n;tk_textCopy $w"
		$menu add command -label [trans paste] \
			-command "status_log paste\n;tk_textPaste $w"
		$menu add command -label [trans insertsmiley] -command ""

		return $menu
	}
	
	################################################
	# CreateCopyMenu
	# This proc creates the menu shown when a user right clicks 
	# on the output of the chat window
	#
	proc CreateCopyMenu { w } {

		set menu $w.copy

		menu $menu -tearoff 0 -type normal

		$menu add command -label [trans copy] \
			-command "status_log copy\n;copy 0 $w"
			
		return $menu
	}

	###################################################
	# CreateTopFrame
	# This proc creates the top frame of a chatwindow
	#
	proc CreateTopFrame { w } {

		# Create our frame
		set top [GetTopFrame $w]
		
		framec $top -type canvas -relief solid -borderwidth [::skin::getKey chat_top_border] -bordercolor [::skin::getKey topbarborder] -background [::skin::getKey topbarbg] -state disabled
		
		if { [::skin::getKey chat_top_pixmap] } {
			set bg "::$top.bg"
			set topimg [image create photo [TmpImgName]] ;#gets destroyed
			$topimg copy [::skin::loadPixmap cwtopback]
			::picture::Colorize $topimg [::skin::getKey topbarbg]
			scalable-bg $bg -source $topimg \
				-n [::skin::getKey topbarpady] -e [::skin::getKey topbarpadx] \
				-s [::skin::getKey topbarpady] -w [::skin::getKey topbarpadx] \
				-width 0 -height 0 -resizemethod [::skin::getKey chat_top_resize "tile"]
			$top create image 0 0 -image [$bg name] -anchor nw -tag backgnd
			bind [$top getinnerframe] <Configure> "$bg configure -width %w -height %h"
			bind [$top getinnerframe] <Destroy> "$bg destroy; image delete $topimg"
		}
		
		set toX [::skin::getKey topbarpadx]
		set usrsX [expr {$toX + [font measure bplainf -displayof $top "[trans to]:"] + 5}]
		set txtY [::skin::getKey topbarpady]
		
		$top create text $toX $txtY -fill [::skin::getKey topbartext] -state disabled -font bplainf -text "[trans to]:" -anchor nw -tag to

		$top create text $usrsX $txtY -fill [::skin::getKey topbartext] -state disabled -font sboldf -anchor nw -tag text
		
		#As the contact list isn't filled we set the height to fit with the To field
		$top configure -height [expr {[::ChatWindow::MeasureTextCanvas $top "to" "h"] + 2*[::skin::getKey topbarpady]}]

		return $top
	}


	###################################################
	# CreateStatusBar
	# This proc creates the status bar of a chatwindow
	#
	proc CreateStatusBar { w } {
		
		#Create the frame
		set statusbar $w.statusbar
		framec $statusbar -class Amsn -relief solid\
				-borderwidth [::skin::getKey chat_status_border] \
				-bordercolor [::skin::getKey chat_status_border_color] \
				-background [::skin::getKey statusbarbg]

		# set our inner widget's names
		set status [$statusbar getinnerframe].status
		set charstyped [$statusbar getinnerframe].charstyped

		#Create text insert frame
		text $status  -width 5 -height 1 -wrap none \
			-font bplainf -borderwidth 0 -background [::skin::getKey statusbarbg] -foreground [::skin::getKey statusbartext]\
			-highlightthickness 0 -selectbackground [::skin::getKey statusbarbg_sel] -selectborderwidth 0 \
			-selectforeground [::skin::getKey statusbartext_sel] -exportselection 1 -pady 4
		text $charstyped  -width 4 -height 1 -wrap none \
			-font splainf -borderwidth 0 -background [::skin::getKey statusbarbg] -foreground [::skin::getKey statusbartext]\
			-highlightthickness 0 -selectbackground [::skin::getKey statusbarbg_sel] -selectborderwidth 0 \
			-selectforeground [::skin::getKey statusbartext_sel] -exportselection 1 -pady 4


		# Configure them
		$charstyped tag configure center -justify left
		$status configure -state disabled
		$charstyped configure -state disabled

		# Pack them
		pack $status -side left -expand true -fill x -padx 0 -pady 0 -anchor w

		if { [::config::getKey charscounter] } {
			pack $charstyped -side right -expand false -padx 0 -pady 0 -anchor e
		}

		return $statusbar
	}

	proc CreatePanedWindow { w } {
		
		set paned $w.f
		
		panedwindow $paned \
			-background [::skin::getKey chatwindowbg] \
			-borderwidth 0 \
			-relief flat \
			-orient vertical

		set output [GetOutFrame $w]
		set input [GetInFrame $w]

		frame $output -class Amsn -borderwidth 0 -relief solid \
			-background [::skin::getKey chatwindowbg] -height [::config::getKey winchatoutheight]

		frame $input -class Amsn -borderwidth 0 -relief solid \
			-background [::skin::getKey chatwindowbg]

		$paned add $output $input
		$paned paneconfigure $output -minsize 50 -height 200
		$paned paneconfigure $input -minsize 100 -height 120
		$paned configure \
			-showhandle [::skin::getKey chat_sash_showhandle] \
			-sashpad [::skin::getKey chat_sash_pady] \
			-sashwidth [::skin::getKey chat_sash_width] \
			-sashrelief [::skin::getKey chat_sash_relief]

		CreateOutputWindow $w $output
		CreateInputWindow $w $input

		# Bind on focus, so we always put the focus on the input window
		bind $paned <FocusIn> "focus $input"

		bind $input <Configure> "::ChatWindow::InputPaneConfigured $paned $input $output %W %h"
		bind $output <Configure> "::ChatWindow::OutputPaneConfigured $paned $input $output %W %h"
		bind $paned <Configure> "::ChatWindow::PanedWindowConfigured $paned $input $output %W %h"

		return $paned
	}


	proc GetSashHeight { paned } {
		set sashheight [expr { [$paned cget -sashpad ] + [$paned cget -sashwidth]}]
		if { [ $paned cget -showhandle ] } {
			set handleheight [expr { [$paned cget -sashpad ] + (([$paned cget -sashwidth]+1)/2) + ([$paned cget -handlesize]/2) }]
			if { $handleheight > $sashheight } {
				set sashheight $handleheight
			}
		}

		return $sashheight
	}

	proc SetSashPos { paned input output } {
		# We need to get the 'old' bottom size BEFORE doing the [update idletasks]
		# We need to do the [update idletasks] for 'some' reason, probably because placing the sash inside of an event handler 
		# of a sash change will scew up everything... and I think Tk8.5 crashes if we don't...
		set bottomsize [winfo height $input]
		update idletasks

		if { $bottomsize < [$paned panecget $input -minsize] } {
			set bottomsize [$paned panecget $input -minsize]
		}
		set sashheight [::ChatWindow::GetSashHeight $paned]
		$paned sash place 0 0 [expr {[winfo height $paned] - ($bottomsize + $sashheight)}]
	}

	proc InputPaneConfigured { paned input output W newh } {
		#only run this if the window is the outer frame
		if { ![string equal $input $W]} { return }

		set win [string first "msg" $paned]
		set win [string first "." $paned $win]
		incr win -1
		set win [string range $paned 0 $win]

		set scrolling [getScrolling [::ChatWindow::GetOutText $win]]

		#check that the drag adhered to minsize input pane
		#first checking that there is enough room otherwise you get an infinite loop
		if { ( [winfo height $input] < [$paned panecget $input -minsize] ) \
			&& ( [winfo height $output] > [$paned panecget $output -minsize] ) \
			&& ( [winfo height $paned] > [$paned panecget $output -minsize] ) } {
			::ChatWindow::SetSashPos $paned $input $output
		}

		if { $scrolling } { after 100 "catch {::ChatWindow::Scroll [::ChatWindow::GetOutText $win]}" }

		if { [::config::getKey savechatwinsize] } {
			::config::setKey winchatoutheight [winfo height $output]
		}
	}

	# this proc is only needed when the sash is moved manually
	# and the input pane is off the screen so the obove doesnt get called
	proc OutputPaneConfigured { paned input output W newh } {
		#only run this if the window is the outer frame
		if { ![string equal $output $W]} { return }

		#only run if input frame not visible
		if { [winfo height $paned] <= [lindex [$paned sash coord 0] 1] + [::ChatWindow::GetSashHeight $paned] } {
		
			#check that the drag adhered to minsize for the input pane
			if { ( [winfo height $input] < [$paned panecget $input -minsize] ) \
					&& ( [winfo height $output] > [$paned panecget $output -minsize] ) \
					&& ( [winfo height $paned] > [$paned panecget $output -minsize] ) } {

				::ChatWindow::SetSashPos $paned $input $output
			}
		}
	}
	
	proc PanedWindowConfigured { paned input output W newh } {
		#only run this if the window is the outer frame
		if { ![string equal $paned $W]} { return }

		#keep the input pane the same size, only change the output		
		#dont call the first time it is created
		#as the input size hasnt been set yet
		if {([winfo height $input] != 1) || ([winfo height $output] != 1) } {
			::ChatWindow::SetSashPos $paned $input $output
		}
	}

	proc CreateOutputWindow { w paned } {
		set out [CreateOutputFrame $w $paned]
		
		pack $out -side left -expand true -fill both \
		    -padx [::skin::getKey chat_output_padx] \
		    -pady [::skin::getKey chat_output_pady]
		
		set picture [CreateDisplayPicturesFrame $w $paned]
			
		pack $picture -side right -fill y -anchor ne \
		    -padx [::skin::getKey chat_dp_padx] \
		    -pady [::skin::getKey chat_dp_pady]
	}

	proc CreateOutputFrame { w fr } {
		set out $fr.scroll
		set text $out.text

		ScrolledWindow $out -auto vertical -scrollbar vertical -ipad 0
		framec $text -type ::ChatWindow::rotext -relief solid -foreground white \
			-background [::skin::getKey chat_output_back_color] -width 45 -height 3 \
			-setgrid 0 -wrap word -exportselection 1 -highlightthickness 0 -selectborderwidth 1 \
			-borderwidth [::skin::getKey chat_output_border] \
			-bordercolor [::skin::getKey chat_output_border_color]
		set textinner [$text getinnerframe]

		$out setwidget $text

		
		# Configure our widgets
		$text configure -state normal
		$text tag configure green -foreground darkgreen -font sboldf
		$text tag configure red -foreground red -font sboldf
		$text tag configure blue -foreground blue -font sboldf
		$text tag configure gray -foreground #404040 -font splainf
		$text tag configure gray_italic -foreground #000000 -font sbolditalf
		$text tag configure white -foreground white -background black -font sboldf
		$text tag configure url -foreground #000080 -font splainf -underline true

		# Create our bindings
		bind $textinner <<Button3>> "tk_popup $w.copy %X %Y"

		# Do not bind copy command on button 1 on Mac OS X 
		if { ![OnMac] } {
			bind $textinner <<Button1>> "copy 0 $w"
		}

		# When someone type something in out.text, regive the focus to in.input and insert that key,
		bind $textinner <KeyPress> "::ChatWindow::lastKeytyped %A %K $w"
		if {[OnMac]} {
			bind $textinner <Command-KeyPress> ";"
			bind $textinner <Command-KeyPress-v> "::ChatWindow::pasteToInput $w"
		}

		#Added to stop amsn freezing when control-up pressed in the output window
		#If you can find why it is freezing and can stop it remove this line
		bind $textinner <Control-Up> "break"

		return $out
	}
	
	proc CreateDisplayPicturesFrame { w fr } {

		# Pack them
		if { [::config::getKey old_dpframe 0] == 0 } {

			# Create them
			frame $fr.f -class Amsn -borderwidth 0  -padx 0 -pady 0 \
	                    -relief solid -background [::skin::getKey chatwindowbg]
			ScrolledWindow $fr.f.sw -scrollbar vertical -auto vertical -borderwidth 0
			ScrollableFrame $fr.f.sw.sf -width 0 -bg [::skin::getKey chatwindowbg]
			$fr.f.sw setwidget $fr.f.sw.sf
			
			# Name our widgets
			set f [$fr.f.sw.sf getframe]
			set dpsframe $f.dps
			set images $dpsframe.imgs
			set showpic $dpsframe.showpic

			frame $dpsframe -class Amsn -borderwidth 0 -padx 0 -pady 0 \
					-relief solid -background [::skin::getKey chatwindowbg]
			frame $images -class Amsn -borderwidth 0 -padx 0 -pady 0 \
				-relief solid -background [::skin::getKey chatwindowbg]


			label $showpic -bd 0 -padx 0 -pady 0 -image [::skin::loadPixmap imgshow] \
					-bg [::skin::getKey chatwindowbg] -highlightthickness 0 -font splainf \
					-highlightbackground [::skin::getKey chatwindowbg] -activebackground [::skin::getKey chatwindowbg]
			bind $showpic <Enter> "$showpic configure -image [::skin::loadPixmap imgshow_hover]"
			bind $showpic <Leave> "$showpic configure -image [::skin::loadPixmap imgshow]"
			set_balloon $showpic [trans showdisplaypic]

			pack $fr.f.sw -fill y -anchor ne
			pack $dpsframe -side top -padx 0 -pady 0 -anchor ne
			pack $images -side left -anchor ne
			pack $showpic -side right -anchor ne

			bind $showpic <<Button1>> [list ::amsn::ToggleShowTopPicture]
			::amsn::ShowOrHideTopPicture
		} else {
			# Create them
			frame $fr.f -class Amsn -borderwidth 0  -padx 0 -pady 0 \
	                    -relief solid -background [::skin::getKey chatwindowbg]
		}

		return $fr.f

	}

	#pasteToInput -- text pasted in output window goes to input window
	#This is processed before the paste occurs, so this is sufficient.
	proc pasteToInput {w} {
		focus -force [::ChatWindow::GetInputText $w]
	}

	#lastkeytyped
	#Force the focus to the input text box when someone try to write something in the output
	proc lastKeytyped {typed keysym w} {
		if {[regexp {^[ -~]$} $typed]} {
			focus -force [::ChatWindow::GetInputText $w]
			[::ChatWindow::GetInputText $w] insert insert $typed
		} elseif {$keysym == "BackSpace"} {
			focus -force [::ChatWindow::GetInputText $w]
			[::ChatWindow::GetInputText $w] delete "insert - 1 char" insert
		} elseif {$keysym == "Delete"} {
			focus -force [::ChatWindow::GetInputText $w]
			[::ChatWindow::GetInputText $w] delete insert "insert + 1 char"
		}
	}

	proc CreateInputWindow { w paned } {

		status_log "Creating input frame\n"
		# Name our widgets
		set leftframe $paned.left

		# Create The left frame
		frame $leftframe -class Amsn -background [::skin::getKey chatwindowbg] -relief solid -borderwidth 0

		# Create the other widgets for the bottom frame
		set input [CreateInputFrame $w $leftframe]
		set buttons [CreateButtonBar $w $leftframe]
		set picture [CreatePictureFrame $w $paned]

		pack $buttons -side top -expand false -fill x -anchor n \
				-padx [::skin::getKey chat_buttons_padx] \
				-pady [::skin::getKey chat_buttons_pady]
		pack $input -side top -expand true -fill both -anchor n \
				-padx [::skin::getKey chat_input_padx] \
				-pady [::skin::getKey chat_input_pady]
		pack $leftframe -side left -expand true -fill both \
				-padx [::skin::getKey chat_leftframe_padx] \
				-pady [::skin::getKey chat_leftframe_pady]
		pack $picture -side right -fill y -anchor ne \
				-padx [::skin::getKey chat_dp_padx] \
				-pady [::skin::getKey chat_dp_pady]

		if {![::config::getKey ShowButtonBar] == 1 } {
			pack forget $buttons
		}

		# Bind the focus
		bind $paned <FocusIn> "focus $input"

		#send chatwininput postevent
		set evPar(input) $input
		set evPar(buttons) $buttons
		set evPar(picture) $picture
		set evPar(window) "$w"

		::plugins::PostEvent chatwininput evPar
	}

	proc ShowButtonBarRightClick { win x y } {
		catch {menu $win.buttonbarmenu -tearoff 0}
		$win.buttonbarmenu delete 0 end
		# Setup the menu
		if {[::config::getKey ShowButtonBar] == 1 } {
			$win.buttonbarmenu add command -label "[trans hidebuttonbar]" -command [list ::ChatWindow::HideButtonBar]
			# Show the menu
			tk_popup $win.buttonbarmenu $x $y
		}
	}

	proc ShowOrHideButtonBar { } {
		if {[::config::getKey ShowButtonBar 1] == 0 } {
			status_log "Hiding Button Bar"
			::ChatWindow::HideButtonBar
		} else {
			status_log "Showing Button Bar"
			::ChatWindow::ShowButtonBar 
		}
	}

	proc HideButtonBar { } {
		# Hide the button bar
		set chatids [::ChatWindow::getAllChatIds]
		# Loop through all chats
		foreach chat $chatids {
			set win [::ChatWindow::For $chat]
			# Un pack the Bar
			pack forget [::ChatWindow::GetButtonBarForWin $win]
		}
		
		::config::setKey ShowButtonBar 0
		
	}

	proc ShowButtonBar { } {
		# Show the button bar
		set chatids [::ChatWindow::getAllChatIds]
		# Loop through the chats
		foreach chat $chatids {
			set win [::ChatWindow::For $chat]
			set buttons [::ChatWindow::GetButtonBarForWin $win]
			# Repack the bar
			pack [::ChatWindow::GetButtonBarForWin $win] -anchor n \
			    -side top -in [GetLeftFrame $win]  \
			    -anchor n -expand 0 -fill x -ipadx 0 -ipady 0 \
			    -padx 3 -pady 4 -side top
			pack $win.f.bottom.left.in -side top -expand true \
			    -fill both -anchor n -in [GetLeftFrame $win] \
			    -padx [::skin::getKey chat_input_padx] \
			    -pady [::skin::getKey chat_input_pady]
		}

		::config::setKey ShowButtonBar 1
	}

	proc CreateInputFrame { w bottom} { 
		# Create The input frame
		set input $bottom.in
		framec $input -class Amsn -relief solid \
				-background [::skin::getKey sendbuttonbg] \
				-borderwidth [::skin::getKey chat_input_border] \
				-bordercolor [::skin::getKey chat_input_border_color]
		
		# set our inner widget's names
		set sendbuttonframe [$input getinnerframe].sbframe
		set sendbutton $sendbuttonframe.send
		set text [$input getinnerframe].text

		# Create the text widget and the send button widget
		text $text -background [::skin::getKey chat_input_back_color] -width 15 -wrap word -font bboldf \
			-borderwidth 0 -relief solid -highlightthickness 0 -exportselection 1
		
		frame $sendbuttonframe -borderwidth 0 -bg [::skin::getKey sendbuttonbg]
		
		# Send button in conversation window, specifications and command.
		button $sendbutton -image [::skin::loadPixmap nullimage] \
		    -command "::amsn::MessageSend $w $text" \
		    -fg [::skin::getKey sendbuttonfg] -bg [::skin::getKey sendbuttonbg] -bd 0 -relief flat \
		    -activebackground [::skin::getKey sendbuttonbg] -activeforeground [::skin::getKey sendbuttonfghover] \
		    -text [trans send] -font sboldf -highlightthickness 0 -pady 0 -padx 0 \
		    -overrelief flat -compound center

		set send_button_bg [scalable-bg $sendbutton.bg -source [::skin::loadPixmap sendbutton] \
					-n [::skin::getKey sendbuttony 1] -e [::skin::getKey sendbuttonx 1] \
					-s [::skin::getKey sendbuttony 1] -w [::skin::getKey sendbuttonx 1] \
					-resizemethod [::skin::getKey sendbuttonresize "tile"]]
		
		# Configure my widgets
		$sendbutton configure -state normal
		$text configure -state normal

		# Create my bindings
		bind $sendbutton <Return> "::amsn::MessageSend $w $text; break"

		bind $sendbutton <Enter> [list $send_button_bg configure -source [::skin::loadPixmap sendbutton_hover]]
		bind $sendbutton <Leave> [list $send_button_bg configure -source [::skin::loadPixmap sendbutton]]
		bind $sendbutton <Configure> [list ::ChatWindow::SendButtonResized $sendbutton $send_button_bg %w %h]
		bind $sendbutton <Destroy> [list $send_button_bg destroy]

		bind $text <Shift-Return> {%W insert insert "\n"; %W see insert; break}
		bind $text <Control-KP_Enter> {%W insert insert "\n"; %W see insert; break}
		bind $text <Shift-KP_Enter> {%W insert insert "\n"; %W see insert; break}

		# Add a binding for Ctrl-Backspace that seems to be default in Tk to Meta-Backspace (Meta == Alt) but isn't the right thing..
		bind $text <Control-Key-BackSpace> [bind Text <Meta-Key-BackSpace>]

		# Change shortcuts on Mac OS X (TKAqua). ALT=Option Control=Command on Mac
		if { [OnMac] } {
			bind $text <Command-Return> {%W insert insert "\n"; %W see insert; break}
			bind $text <Command-Shift-space> BossMode
			bind $text <Command-a> {%W tag add sel 1.0 {end - 1 chars};break}
			bind $text <Command-A> {%W tag add sel 1.0 {end - 1 chars};break}
			bind $text <Option-Key-BackSpace> [bind Text <Meta-Key-BackSpace>]
		} else {
			bind $text <Control-Return> {%W insert insert "\n"; %W see insert; break}
			bind $text <Control-Alt-space> BossMode
			bind $text <Control-a> {%W tag add sel 1.0 {end - 1 chars};break}
			bind $text <Control-A> {%W tag add sel 1.0 {end - 1 chars};break}
			#bind $text <Tab> "focus $sendbutton; break"
		}

		bind $text <<Button3>> [list ::ChatWindow::OpenPasteMenu $w %X %Y] 
		bind $text <<Button2>> "paste $w 1"

		#Better binding, works for Tk 8.4 only (see proc tification too)
		if { [catch {
			$text edit modified false
			bind $text <<Modified>> "::amsn::TypingNotification $w $text"
		} res]} {
			#If fails, fall back to 8.3
			bind $text <Key> "::amsn::TypingNotification $w $text"
			bind $text <Key-Meta_L> "break;"
			bind $text <Key-Meta_R> "break;"
			bind $text <Key-Alt_L> "break;"
			bind $text <Key-Alt_R> "break;"
			bind $text <Key-Control_L> "break;"
			bind $text <Key-Control_R> "break;"
			bind $text <Key-Return> "break;"
		}

		bind $text <Key-Delete> "::amsn::DeleteKeyPressed $w $text %K"
		bind $text <Key-BackSpace> "::amsn::DeleteKeyPressed $w $text %K"
		bind $text <Key-Up> {my_TextSetCursor %W [::amsn::UpKeyPressed %W]; break}
		bind $text <Key-Down> {my_TextSetCursor %W [::amsn::DownKeyPressed %W]; break}
		bind $text <Shift-Key-Up> {::tk::TextKeySelect %W [::amsn::UpKeyPressed %W]; break}
		bind $text <Shift-Key-Down> {::tk::TextKeySelect %W [::amsn::DownKeyPressed %W]; break}

		global skipthistime
		set skipthistime 0

		bind $text <Control-S> "window_history add %W; ::amsn::MessageSend $w %W; break"
		bind $text <Return> "window_history add %W; ::amsn::MessageSend $w %W; break"
		bind $text <Key-KP_Enter> "window_history add %W; ::amsn::MessageSend $w %W; break"

		#Different shortcuts on Mac OS X / TkAqua
		if { [OnMac] } {
			bind $text <Control-s> "window_history add %W; ::amsn::MessageSend $w %W; break"
			bind $text <Command-Up> "window_history previous %W; break"
			bind $text <Command-Down> "window_history next %W; break"
		} else {
			bind $text <Alt-s> "window_history add %W; ::amsn::MessageSend $w %W; break"
			bind $text <Control-Up> "window_history previous %W; break"
			bind $text <Control-Down> "window_history next %W; break"
		}

		bind $input <FocusIn> "focus $text"


		# Pack My input frame widgets
		pack $text -side left -expand true -fill both -padx 1 -pady 1
		pack $sendbutton -side top
		if {[::skin::getKey chat_show_sendbuttonframe]} {
			pack $sendbuttonframe -side right -padx [::skin::getKey chat_sendbutton_padx]\
				-pady [::skin::getKey chat_sendbutton_pady]
		}

		#send chatsendbutton postevent
		set evPar(window_name) "$w"
		set evPar(bottomleft) [$input getinnerframe]
		::plugins::PostEvent chatsendbutton evPar

		set droptarget [::ChatWindow::GetInputText $w]
		status_log "Going to register DND for $droptarget"
		if {[catch {tkdnd::drop_target register $droptarget *} res]} {
	                status_log "dnd error: $res"
	        } else {
			status_log "DND bind for $droptarget"
			#bind $droptarget <<Drop>> {puts works}
	                bind $droptarget <<Drop:DND_Files>> [list ::fileDropHandler %D sendfile $w]
			bind $droptarget <<Drop:DND_Text>> [list ::fileDropHandler %D pasteText $w]
		}

#		# Drag and Drop file sending
#		if {[catch {::dnd bindtarget [::ChatWindow::GetInputText $w] Files <Drop> "fileDropHandler %D sendfile $w"} res ]} {
#				status_log "dnd error: $res"
#		}
#		#::dnd bindtarget [::ChatWindow::GetInputText $w] UniformResourceLocator <Drop> "%W insert end %D"
#		if {[catch {::dnd bindtarget [::ChatWindow::GetInputText $w] Text <Drop> {%W insert end %D}} res ]} {
##				status_log "dnd error: $res"
#		}

		return $input
	}

	proc SendButtonResized {sendbutton sendbutton_bg width height} {
		#Don't put {} here for expr as we need to substitute in the current context
		$sendbutton_bg configure -width [expr $width+2*[::skin::getKey sendbuttonx 1]] \
		    -height [expr $height+2*[::skin::getKey sendbuttony 1]]
		bind $sendbutton <Configure> ""
		$sendbutton configure -image [$sendbutton_bg name]
	}

	proc OpenPasteMenu { w x y } {
		$w.copypaste entryconfigure [$w.copypaste index [trans insertsmiley]] \
		    -command "::smiley::smileyMenu \[winfo pointerx $w\] \[winfo pointery $w\] [::ChatWindow::GetInputText $w]"
		tk_popup $w.copypaste $x $y
	}

	proc CreateButtonBar { w bottom } {

		status_log "Creating button bar\n"
		# create the frame
		set buttons $bottom.buttons
		framec $buttons -class Amsn -relief solid \
				-borderwidth [::skin::getKey chat_buttons_border] \
				-bordercolor [::skin::getKey chat_buttons_border_color] \
				-background [::skin::getKey buttonbarbg]	

		# Bind to show the buttonbar right click menu to hide it
		set buttonsinner [$buttons getinnerframe]
		bind $buttonsinner <<Button3>> [list ::ChatWindow::ShowButtonBarRightClick $w %X %Y]

		# Name our widgets
		set buttonsinner [$buttons getinnerframe]
		set smileys $buttonsinner.smileys
		set fontsel $buttonsinner.fontsel
		set voice $buttonsinner.voice
		set block $buttonsinner.block
		set sendfile $buttonsinner.sendfile
		set invite $buttonsinner.invite
		set webcam $buttonsinner.webcam
		set call $buttonsinner.call
		set callv $buttonsinner.callv

		# widget name from another proc
		set input [::ChatWindow::GetInputText $w]


		#Smiley button
		button $smileys  -image [::skin::loadPixmap butsmile] -relief flat -padx 0 \
			-background [::skin::getKey buttonbarbg] -highlightthickness 0 -borderwidth 0 \
			-highlightbackground [::skin::getKey buttonbarbg]  -activebackground [::skin::getKey buttonbarbg]\
			-command "::smiley::smileyMenu \[winfo rootx $smileys\] \[winfo rooty $smileys\] $input"
		set_balloon $smileys [trans insertsmiley]

	       	#Font button
		button $fontsel -image [::skin::loadPixmap butfont] -relief flat -padx 0 \
			-background [::skin::getKey buttonbarbg] -highlightthickness 0 -borderwidth 0\
			-highlightbackground [::skin::getKey buttonbarbg] -activebackground [::skin::getKey buttonbarbg]\
			-command "after 1 change_font [string range $w 1 end] mychatfont"
		set_balloon $fontsel [trans changefont]

		#Voice button
		button $voice -image [::skin::loadPixmap butvoice] -relief flat -padx 0 \
			-background [::skin::getKey buttonbarbg] -highlightthickness 0 -borderwidth 0\
			-highlightbackground [::skin::getKey buttonbarbg] -activebackground [::skin::getKey buttonbarbg]
		set_balloon $voice [trans sendvoice]

		#Block button
		button $block -image [::skin::loadPixmap butblock] -relief flat -padx 0 \
			-background [::skin::getKey buttonbarbg] -highlightthickness 0 -borderwidth 0\
			-highlightbackground [::skin::getKey buttonbarbg] -activebackground [::skin::getKey buttonbarbg]\
			-command "::amsn::ShowChatList \"[trans block]/[trans unblock]\" $w ::amsn::blockUnblockUser"
		set_balloon $block "--command--::ChatWindow::SetBlockText $w"
		
		#Send file button
		button $sendfile -image [::skin::loadPixmap butsend] -relief flat -padx 0 \
			-background [::skin::getKey buttonbarbg] -highlightthickness 0 -borderwidth 0\
			-highlightbackground [::skin::getKey buttonbarbg] -activebackground [::skin::getKey buttonbarbg]\
			-command "::amsn::FileTransferSend $w"
		set_balloon $sendfile [trans sendfile]
	
		#Invite another contact button
		button $invite -image [::skin::loadPixmap butinvite] -relief flat -padx 0 \
			-background [::skin::getKey buttonbarbg] -highlightthickness 0 -borderwidth 0\
			-highlightbackground [::skin::getKey buttonbarbg] -activebackground [::skin::getKey buttonbarbg]\
			-command "::amsn::ShowInviteMenu $w \[winfo pointerx $w\] \[winfo pointery $w\]"
		set_balloon $invite [trans invite]

		#Webcam button
		button $webcam -image [::skin::loadPixmap butwebcam] -relief flat -padx 0 \
			-background [::skin::getKey buttonbarbg] -highlightthickness 0 -borderwidth 0\
			-highlightbackground [::skin::getKey buttonbarbg] -activebackground [::skin::getKey buttonbarbg]\
			-command "::ChatWindow::webcambuttonAction $w"
		set_balloon $webcam "--command--::ChatWindow::SetWebcamText"
		
		global enable_sip
		if {$enable_sip} {
			#Call button
			button $call -image [::skin::loadPixmap butcall] -relief flat -padx 0 \
			    -background [::skin::getKey buttonbarbg] -highlightthickness 0 -borderwidth 0\
			    -highlightbackground [::skin::getKey buttonbarbg] -activebackground [::skin::getKey buttonbarbg]\
			    -command "::amsn::InviteCallFromCW $w 0"
			set_balloon $call "[trans sendsip]"

			#Video button
			button $callv -image [::skin::loadPixmap butcallvideo] -relief flat -padx 0 \
			    -background [::skin::getKey buttonbarbg] -highlightthickness 0 -borderwidth 0\
			    -highlightbackground [::skin::getKey buttonbarbg] -activebackground [::skin::getKey buttonbarbg]\
			    -command "::amsn::InviteCallFromCW $w 1"
			set_balloon $callv "[trans sendvideosip]"
		}

		# Pack them
		pack $fontsel $smileys $voice -side left -padx 0 -pady 0
		if {$enable_sip} {
			pack $block $webcam $sendfile $invite $call $callv -side right -padx 0 -pady 0
		} else {
			pack $block $webcam $sendfile $invite -side right -padx 0 -pady 0
		}

		bind $voice    <<Button1-Press>> "::ChatWindow::start_voice_clip $w"
		bind $voice    <<Button1>> "::ChatWindow::stop_and_send_voice_clip $w"

		# Create our bindings
		bind $smileys <Enter> "$smileys configure -image [::skin::loadPixmap butsmile_hover]"
		bind $smileys <Leave> "$smileys configure -image [::skin::loadPixmap butsmile]"
		bind $fontsel <Enter> "$fontsel configure -image [::skin::loadPixmap butfont_hover]"
		bind $fontsel <Leave> "$fontsel configure -image [::skin::loadPixmap butfont]"
		bind $voice <Enter> "$voice configure -image [::skin::loadPixmap butvoice_hover]"
		bind $voice <Leave> "$voice configure -image [::skin::loadPixmap butvoice]"
		bind $block <Enter> "$block configure -image [::skin::loadPixmap butblock_hover]"
		bind $block <Leave> "$block configure -image [::skin::loadPixmap butblock]"
		
		bind $sendfile <Enter> "$sendfile configure -image [::skin::loadPixmap butsend_hover]"
		bind $sendfile <Leave> "$sendfile configure -image [::skin::loadPixmap butsend]"
		bind $invite <Enter> "$invite configure -image [::skin::loadPixmap butinvite_hover]"
		bind $invite <Leave> "$invite configure -image [::skin::loadPixmap butinvite]"
		bind $webcam <Enter> "$webcam configure -image [::skin::loadPixmap butwebcam_hover]"
		bind $webcam <Leave> "$webcam configure -image [::skin::loadPixmap butwebcam]"

		if {$enable_sip} {
			bind $call <Enter> "$call configure -image [::skin::loadPixmap butcall_hover]"
			bind $call <Leave> "$call configure -image [::skin::loadPixmap butcall]"
			bind $callv <Enter> "$callv configure -image [::skin::loadPixmap butcallvideo_hover]"
			bind $callv <Leave> "$callv configure -image [::skin::loadPixmap butcallvideo]"
		}
		
		#send chatwindowbutton postevent
		set evPar(bottom) $buttonsinner
		set evPar(window_name) "$w"
		::plugins::PostEvent chatwindowbutton evPar

		return $buttons
	}


	proc webcambuttonAction { w } {
		if {[::config::getKey webcamDevice] != ""} {
			::amsn::ShowChatList \"[trans sendwebcaminvite]\" $w ::MSNCAM::SendInviteQueue
		} elseif {[OnMac] } {
			# On mac webcamDevice always returns 0. So we need to check manually if the grabber is open. If the grabber isn't open then we create it.
			# The behaviour of the grabber window opening without the user configuring the cam first is default for most OS X applications, and a lot of users have requested this.
			if {[winfo exists .grabber]} {
				::amsn::ShowChatList \"[trans sendwebcaminvite]\" $w ::MSNCAM::SendInviteQueue
			} else {
				::CAMGUI::CreateGrabberWindowMac
				::amsn::ShowChatList \"[trans sendwebcaminvite]\" $w ::MSNCAM::SendInviteQueue
			}
		} else {
			::AVAssistant::AVAssistant
		}
	}

	proc AddVoipControls {chatid video {sip ""} {callid ""}} {
		
		set win [::ChatWindow::For $chatid]

		set frame_in [GetInDisplayPictureFrame $win].voip
		if {[winfo exists $frame_in]} {destroy $frame_in}
		set frame_out [GetOutDisplayPicturesFrame $win].voip
		if {[winfo exists $frame_out]} {destroy $frame_out}


		package require voipcontrols
		status_log "Creating CW Voip controls"

		voipcontrol $frame_in -orient vertical \
			-bg [::skin::getKey chatwindowbg]\
			-endcallimage [::skin::loadPixmap buthangup_mini] \
			-endcallstate disabled \
			-mutedimage [::skin::loadPixmap mic_muted] \
			-unmutedimage [::skin::loadPixmap mic] \
			-mutecommand [list ::ChatWindow::MuteIn $frame_in] \
			-mutevariable ::ChatWindow::voip_mute_in \
			-volumecommand [list ::ChatWindow::VolumeIn $frame_in] \
			-volumevariable [::config::getVar fs_in_volume]
		if { [::config::getKey old_dpframe 0] == 0 } {
			set orient "horizontal"
		} else {
			set orient "vertical"
		}
		voipcontrol $frame_out -orient $orient \
			-bg [::skin::getKey chatwindowbg]\
			-endcallimage [::skin::loadPixmap buthangup_mini] \
			-endcallstate disabled \
			-mutedimage [::skin::loadPixmap speaker_muted] \
			-unmutedimage [::skin::loadPixmap speaker] \
			-mutecommand [list ::ChatWindow::MuteOut $frame_out] \
			-mutevariable ::ChatWindow::voip_mute_out \
			-volumecommand [list ::ChatWindow::VolumeOut $frame_out] \
			-volumevariable [::config::getVar fs_out_volume]
		$frame_in configure -width [$frame_in getSize]
		pack $frame_in -side left -padx 0 -pady 0 -anchor w -fill y
		if { [::config::getKey old_dpframe 0] == 0 } {
			$frame_out configure -height [$frame_out getSize]
			pack $frame_out -side bottom -padx 0 -pady 0 -anchor ne -fill x
		} else {
			$frame_out configure -width [$frame_out getSize]
			$frame_out configure -height 150
			pack $frame_out -side bottom -padx 0 -pady 0 -anchor ne
		}

		set ::ChatWindow::voip_mute_in 0

		set ::ChatWindow::voip_mute_out 0

		UpdateVoipControls $chatid $video $sip $callid


		#Redraw the frames correctly
		::amsn::ShowOrHidePicture
		if { [winfo exists [::ChatWindow::GetOutDisplayPicturesFrame $win].dps] } {
				::amsn::ShowOrHideTopPicture
		}

	}

	proc UpdateVoipControls {chatid video {sip ""} {callid ""}} {
		
		set window [::ChatWindow::For $chatid]

		set frame_in [GetInDisplayPictureFrame $window].voip
		set frame_out [GetOutDisplayPicturesFrame $window].voip
		if {![winfo exists $frame_in] || ![winfo exists $frame_out]} {
			return
		}

		#status_log "Updating CW Voip controls"

		#IN
		if {[catch {set volume [::Farsight::SetVolumeIn [::config::getKey fs_in_volume]]} ] } {
			$frame_in configure -volumestate disabled
		} else {
			$frame_in configure -volumestate normal
		}
		if {[catch {set mute [::Farsight::GetMuteIn]} ] } {
			$frame_in configure -mutestate disabled
		} else {
			set ::ChatWindow::voip_mute_in $mute
			$frame_in configure -mutestate normal
			if {$mute} {
				$frame_in Mute
			} else {
				$frame_in UnMute
			}
		}

		#OUT
		if {[catch {set volume [::Farsight::SetVolumeOut [::config::getKey fs_out_volume]]} ] } {
			$frame_out configure -volumestate disabled
		} else {
			$frame_out configure -volumestate normal
		}
		if {[catch {set mute [::Farsight::GetMuteOut]} ] } {
			$frame_out configure -mutestate disabled
		} else {
			set ::ChatWindow::voip_mute_out $mute
			$frame_out configure -mutestate normal
			if {$mute} {
				$frame_out Mute
			} else {
				$frame_out UnMute
			}
		}

		if {$sip != "" && $callid != ""} {
			$frame_in configure -endcallstate normal\
			    -endcallcommand [list ::amsn::HangupSIPCall $video $chatid $sip $callid]
			$frame_out configure -endcallstate normal\
			    -endcallcommand [list ::amsn::HangupSIPCall $video $chatid $sip $callid]
		} else {
			$frame_in configure -endcallstate disabled
			$frame_out configure -endcallstate disabled
		}
	}

	proc RemoveVoipControls {chatid} {
		
		set win [::ChatWindow::For $chatid]

		set frame_in [GetInDisplayPictureFrame $win].voip
		set frame_out [GetOutDisplayPicturesFrame $win].voip

		status_log "Removing CW Voip controls"
		catch {
			destroy $frame_in
		}
		catch {
			destroy $frame_out
		}
		
		if { [::config::getKey old_dpframe 0] != 0 } {
			#WTF IS THIS NOT WORKING?????
			[GetOutDisplayPicturesFrame $win] configure -width 0
			[winfo parent [GetOutDisplayPicturesFrame $win]] configure -width 0
		}
		catch {
			unset ::ChatWindow::voip_mute_in
		}
		catch {
			unset ::ChatWindow::voip_mute_out
		}

		#Redraw the frames correctly
		::amsn::ShowOrHidePicture
		if { [winfo exists [::ChatWindow::GetOutDisplayPicturesFrame $win].dps] } {
				::amsn::ShowOrHideTopPicture
		}
	}

	proc MuteIn {w } {
		if {[catch {::Farsight::SetMuteIn $::ChatWindow::voip_mute_in}]} {
			$w configure -mutestate disabled
		}
	}

	proc VolumeIn {widget val} {
		if {[catch {::Farsight::SetVolumeIn $val}]} {
			$widget configure -volumestate disabled
		}
	}
	proc MuteOut {w } {
		if {[catch {::Farsight::SetMuteOut $::ChatWindow::voip_mute_out}]} {
			$w configure -mutestate disabled
		}
	}

	proc VolumeOut {widget val} {
		if {[catch {::Farsight::SetVolumeOut $val}]} {
			$widget configure -volumestate disabled
		}
	}
	
	proc setCallButton {chatid type video {sip ""} {callid ""}} {
		set win [For $chatid]
		if { $win == 0 } {
			status_log "Oops, no CW for chatid : $chatid" red
			return
		}
		set buttons [GetButtonBarForWin $win]
		set buttonsinner [$buttons getinnerframe]
		if {$video } {
			set button $buttonsinner.callv
			set otherbutton $buttonsinner.call
			set txt [trans sendvideosip]
		} else {
			set button $buttonsinner.call
			set otherbutton $buttonsinner.callv
			set txt [trans sendsip]
		}
		if {$type == "invite" } {
			set cmd [list ::amsn::InviteCallFromCW [::ChatWindow::For $chatid] $video]
			set disable 0
		} elseif {$type == "hangup" } {
			set cmd [list ::amsn::HangupSIPCall $video $chatid $sip $callid] 
			set disable 1
			set txt [trans hangup]
		} elseif {$type == "cancel" } {
			set cmd [list ::amsn::CancelSIPCall $video $chatid $sip $callid]
			set disable 1
			set txt [trans hangup]
		} elseif {$type == "decline" } {
			set cmd [list ::amsn::DeclineSIPCall $video $chatid $sip $callid]
			set disable 1
			set txt [trans reject]
		} else {
			return
		}

		if {[winfo exists $button]} {
			$button configure -command ${cmd}
			set_balloon $button $txt
		} else {
			return
		}

		if {$disable} {
			if {$video} {
				$button configure -image [::skin::loadPixmap buthangupvideo]
				bind $button <Enter> "$button configure -image [::skin::loadPixmap buthangupvideo_hover]"
				bind $button <Leave> "$button configure -image [::skin::loadPixmap buthangupvideo]"
			} else {
				$button configure -image [::skin::loadPixmap buthangup]
				bind $button <Enter> "$button configure -image [::skin::loadPixmap buthangup_hover]"
				bind $button <Leave> "$button configure -image [::skin::loadPixmap buthangup]"
			}
			$otherbutton configure -state disabled
		} else {
			if {$video} {
				$button configure -image [::skin::loadPixmap butcallvideo]
				bind $button <Enter> "$button configure -image [::skin::loadPixmap butcallvideo_hover]"
				bind $button <Leave> "$button configure -image [::skin::loadPixmap butcallvideo]"
			} else {
				$button configure -image [::skin::loadPixmap butcall]
				bind $button <Enter> "$button configure -image [::skin::loadPixmap butcall_hover]"
				bind $button <Leave> "$button configure -image [::skin::loadPixmap butcall]"
			}
			$otherbutton configure -state normal
		}
	}


	proc start_voice_clip { w } {
		variable voice_sound
		variable voice_text_pack

		set chatid [Name $w]
		if { [llength  [::MSN::usersInChat $chatid]] > 0 } {
			if { [catch {require_snack} ] || [package vcompare [set ::snack::patchLevel] 2.2.9] < 0 || [catch {package require tcl_siren }] } {
				amsn::WinWrite $chatid "\n" red
				amsn::WinWriteIcon $chatid greyline 3
				amsn::WinWrite $chatid "\n" red
				amsn::WinWriteIcon $chatid voice_icon 3 2
				amsn::WinWrite $chatid "[timestamp] [trans snackneeded]\n" red
				amsn::WinWriteIcon $chatid greyline 3
				return
			}

			catch { $voice_sound destroy }

			set voice_sound [::snack::sound]
			if { [catch {$voice_sound record} res]} {
				
				amsn::WinWrite $chatid "\n" red
				amsn::WinWriteIcon $chatid greyline 3
				amsn::WinWrite $chatid "\n" red
				amsn::WinWriteIcon $chatid voice_icon 3 2
				amsn::WinWrite $chatid "[timestamp] [trans recorderror $res]\n" red
				amsn::WinWriteIcon $chatid greyline 3
				$voice_sound destroy
			} else {
				set inputtext [GetInputText $w]
				set inputframe [winfo parent $inputtext]

				# Here, we'll build a list of the packes children of the inputframe, excluding the send button.. this will allow us to remove anything packed inside
				# the inputframe and replace it with the voice clip widget... we'll also save the pack info for each one of them... 
				# This is useful if we want to keep the capability of sending voice clips when the inkdraw plugin is activated and the text widget is unpacked
				# and the drawboard is packed instead... 
				set slaves [pack slaves $inputframe]
				set voice_text_pack [list]
				foreach slave $slaves {
					if {$slave != "$inputframe.sbframe" } {
						lappend voice_text_pack [list $slave [pack info $slave]]
						pack forget $slave
					}
				}
				canvas $inputframe.wave -background [::skin::getKey chat_input_back_color] -borderwidth 0 -relief solid
				eval pack $inputframe.wave -side left -padx 0 -pady 0 -expand true -fill both

				# This update here is necessary because it seems if we don't update, the waveform won't appear...
				# this is because we depend on the [winfo width] and [winfo height] for the waveform size
				update
				
				# If the user clicks/unclicks quickly then the update statement will cause the waveform to be destroyed. So we check for that.
				if {![winfo exists ${inputframe}.wave]} {
					status_log "VoiceClips: Waveform destroyed during start_voice_clip function." red
					return
				}
				
				$inputframe.wave create waveform 0 0 -sound $voice_sound -zerolevel 0 -width [winfo width $inputframe.wave] -height [winfo height $inputframe.wave] -pixelspersecond [expr {[winfo width $inputframe.wave] / 15}]

								
				
				::MSN::SendRecordingUserNotification $chatid
				after 15000 "::ChatWindow::stop_and_send_voice_clip $w"
			}
		}
	}

	# This proc is not needed because I found the undocumented 'datasamples' subcommand...
	proc SoundToWave { sound filename } {
		$sound convert -rate 16000 -channels 2
		
		set input [$sound data]
		
		binary scan $input @0a4ia4 riff size wave
		set offset 12
		#puts "found size $size"
		while { $offset < $size } {
			binary scan $input @${offset}a4i id chunk_size
			incr offset 8
			#puts "found chunk $id $chunk_size"
			if {$id == "data" } {
				set data [string range $input $offset [expr {$offset + $chunk_size - 1}]]
			} 
			incr offset $chunk_size
			
		}
		
		if { [info exists data] } {
			set enc [::Siren::NewEncoder]

			if { [catch {set out [::Siren::Encode $enc $data] } res] } {
				::Siren::Close $enc    		
				status_log "Error Encoding : $res"
				return 0
			}

			::Siren::WriteWav $enc $filename $out 
			::Siren::Close $enc
		}
		return 1
	}
		
	proc DecodeWave { file_in file_out } {
		if { [catch {package require tcl_siren 0.3}] } {
			return -1
		} else {
			set fd [open $file_in r]
			fconfigure $fd -translation binary
			set input [read $fd]
			close $fd
			
			set riff ""
			set wave ""
			binary scan $input @0a4ia4 riff size wave
			set offset 12
			if { $riff == "RIFF" && $wave == "WAVE" } {
				while { $offset < $size } {
					binary scan $input @${offset}a4i id chunk_size
					incr offset 8
					if {$id == "fmt " } {
						binary scan $input @${offset}ssiiss format channels sampleRate byteRate blockAlign bitsPerSample
					}
					if {$id == "data" } {
						set data [string range $input $offset [expr {$offset + $chunk_size - 1}]]
					} 
					incr offset $chunk_size
					
				}
			}
			
			if {![info exists format] } {
				set format 1
			}
			
			if { [info exists data] && [expr {$format == 0x028E}] } {
				set dec [::Siren::NewDecoder]
				if { [catch {set out [::Siren::Decode $dec $data] } res] } {
					::Siren::Close $dec    		
					status_log "Error Decoding : $res"
					return 0
				}
				::Siren::WriteWav $dec $file_out $out 
				::Siren::Close $dec
				return 1
			} else {
				return 0
			}
		}
	}
	

	proc stop_and_send_voice_clip { w } {
		variable voice_sound
		variable voice_text_pack
		global HOME

		after cancel "::ChatWindow::stop_and_send_voice_clip $w"

		set chatid [Name $w]
		if { [info exists voice_text_pack] } {
			set inputtext [GetInputText $w]
			set inputframe [winfo parent $inputtext]
			
			# This update is here to prevent a race condition. if you click very fast ont he voice button the first time
			# the 'pressed' event will get called, and the 'unpressed' event will be called too right after it, but if we do 
			# a 'package require snack', etc.. it might take some time for it to load, etc, so we could get the stop_voice_clip
			# proc being called before the start_voice_clip has finished processing, so we can get here, destroy the wave form before 
			# the start_voice_clip proc finished using it, which would result in a bug.
			# 
			update idletasks
			
			destroy $inputframe.wave
			foreach slave $voice_text_pack {
				eval pack [lindex $slave 0] [lindex $slave 1]
			}
			unset voice_text_pack
		}

		# Should we remove the usersInChat ? I know I added it for some reason.. can't remember what.. 
		# think about you send a voice clip and the user closes your window at the same time? should the message be lost ?
		if { [llength  [::MSN::usersInChat $chatid]] > 0 && [catch {$voice_sound stop}] == 0} {
			
			set timestamp [clock format [clock seconds] -format "%d %b %Y @ %H_%m_%S"]
			set user [lindex [::MSN::usersInChat $chatid] 0]
			
			create_dir [file join $HOME voiceclips]
			set filename [file join $HOME voiceclips ${user}_${timestamp}.wav]
			set filename_siren [file join $HOME voiceclips ${user}_${timestamp}_encoded.wav]

			if { [$voice_sound min] > -1000 && [$voice_sound max] < 1000 } {
				amsn::WinWrite $chatid "\n" red
				amsn::WinWriteIcon $chatid greyline 3
				amsn::WinWrite $chatid "\n" red
				amsn::WinWriteIcon $chatid voice_icon 3 2
				if { [$voice_sound length -unit seconds] < 2 } {
					amsn::WinWrite $chatid "[timestamp] [trans nosound_or_hold]\n" red					
				} else {
					amsn::WinWrite $chatid "[timestamp] [trans nosound]\n" red
				}
			} else {
				set enc [::Siren::NewEncoder]
				# We need to add the -byteorder littleEndian because on Mac, the datasamples are in big endian and tcl_siren expects little endian
				# since WAV file contents are in little endian.
				if { [catch {set out [::Siren::Encode $enc [$voice_sound datasamples -byteorder littleEndian]] } res] } {
					::Siren::Close $enc    		
					status_log "Error Encoding voice clip to Siren codec : $res" red
					return 0
				}
				::Siren::WriteWav $enc $filename_siren $out 
				::Siren::Close $enc
				
				$voice_sound write $filename
				
				
				::MSN::ChatQueue $chatid [list ::MSNP2P::SendVoiceClip $chatid $filename_siren]
				
				set uid [getUniqueValue]
				
				amsn::WinWrite $chatid "\n" red
				amsn::WinWriteIcon $chatid greyline 3
				amsn::WinWrite $chatid "\n" red
				amsn::WinWriteIcon $chatid voice_icon 3 2
				amsn::WinWrite $chatid "[timestamp] [trans sentvoice]\n  " green
				amsn::WinWriteClickable $chatid "[trans play]" [list ::ChatWindow::playVoiceClip $w $filename $uid] play_voice_clip_$uid
				amsn::WinWriteClickable $chatid "[trans stop]" [list ::ChatWindow::stopVoiceClip $w $filename $uid] stop_voice_clip_$uid
				[::ChatWindow::GetOutText $w] tag configure play_voice_clip_$uid -elide false
				[::ChatWindow::GetOutText $w] tag configure stop_voice_clip_$uid -elide true
				amsn::WinWrite $chatid " - " green
				amsn::WinWriteClickable $chatid "[trans saveas]" [list ::ChatWindow::saveVoiceClip $filename] 
				amsn::WinWrite $chatid "\n" red
				amsn::WinWriteIcon $chatid greyline 3
			}
		}
		catch {$voice_sound destroy}
	}

	proc playVoiceClip { w filename uid} {
		variable play_snd_$uid

		if { [file exists $filename] } {
			if { [catch {
				set snd [snack::sound]
				set play_snd_$uid $snd
				$snd read $filename
				$snd play -command [list ::ChatWindow::stopVoiceClipDelayed $w $filename $uid]	
				[::ChatWindow::GetOutText $w] tag configure play_voice_clip_$uid -elide true
				[::ChatWindow::GetOutText $w] tag configure stop_voice_clip_$uid -elide false	} ] } {
				if { [info exists snd] } { 
					catch { $snd destroy } 
					catch { unset play_snd_$uid }
				}
				# Full back to play_sound which.. hopefully does not have a 'usesnack' setting.
				play_sound $filename 1
			}
		}
	}

	proc stopVoiceClipDelayed { w filename uid} {
		# We need this little hack because it looks like snack (at least on my PC) calls our callback 1 second before the audio
		# really finished playing.
		after 1200 [list ::ChatWindow::stopVoiceClip $w $filename $uid]
	}

	proc stopVoiceClip { w filename uid} {
		variable play_snd_$uid

		if { [info exists play_snd_$uid] } {
			set snd [set play_snd_$uid]
			catch { $snd stop }
			catch { $snd destroy }
			unset play_snd_$uid
		}
		set text [::ChatWindow::GetOutText $w]
		if { [winfo exists $text] } {
			$text tag configure play_voice_clip_$uid -elide false
			$text tag configure stop_voice_clip_$uid -elide true	
		}
	}

	proc ReceivedVoiceClip {chatid filename } {

		set filename_decoded "[filenoext $filename]_decoded.wav"
		
		# This proc should be uncommented once tcl_siren implements the decoder
		if { [DecodeWave $filename $filename_decoded] == -1 } {
			amsn::WinWrite $chatid "\n" red
			amsn::WinWriteIcon $chatid greyline 3
			amsn::WinWrite $chatid " \n" red
			amsn::WinWriteIcon $chatid voice_icon 3 2
			amsn::WinWrite $chatid "[timestamp] [trans snackneeded]\n" red
			amsn::WinWriteIcon $chatid greyline 3
			return
		} else {
			set uid [getUniqueValue]
			
			if {![info exists ::ChatWindow::msg_windows($chatid)]} {
				::ChatWindow::MakeFor $chatid
			}
			set w [::ChatWindow::For $chatid]

			amsn::WinWrite $chatid "\n" red
			amsn::WinWriteIcon $chatid greyline 3
			amsn::WinWrite $chatid " \n" red
			amsn::WinWriteIcon $chatid voice_icon 3 2
			amsn::WinWrite $chatid "[timestamp] [trans receivedvoice]\n  " green
			amsn::WinWriteClickable $chatid "[trans play]" [list ::ChatWindow::playVoiceClip $w $filename_decoded $uid] play_voice_clip_$uid
			amsn::WinWriteClickable $chatid "[trans stop]" [list ::ChatWindow::stopVoiceClip $w $filename_decoded $uid] stop_voice_clip_$uid
			[::ChatWindow::GetOutText $w] tag configure play_voice_clip_$uid -elide false
			[::ChatWindow::GetOutText $w] tag configure stop_voice_clip_$uid -elide true
			amsn::WinWrite $chatid " - " green
			amsn::WinWriteClickable $chatid "[trans saveas]" [list ::ChatWindow::saveVoiceClip $filename_decoded] 
			amsn::WinWrite $chatid "\n" red
			amsn::WinWriteIcon $chatid greyline 3
			
			if { [::config::getKey autolisten_voiceclips 1] } {
				playVoiceClip $w $filename_decoded $uid
			}
		}
	}

	proc saveVoiceClip { filename } {
		if {[file exists $filename] } {
			set file [chooseFileDialog "" "Save Voice Clip" "" "" save [list [list [trans soundfiles] [list *.wav]] [list [trans allfiles] *]]]
			
			if { $file != "" } {
				if { ![string equal -nocase [file extension $file] ".wav"] } {
					append file ".wav"
				}
				file copy -force $filename $file
			}
		}
	}

	proc SetWebcamText {} {
	 if {[::config::getKey webcamDevice] != "" || [OnMac]} {
			return "[trans sendwebcaminvite]"

		} else {
			return "[trans webcamconfigure]"
		}
	}


	#Show a different ballon if the user is currently blocked or unblocked
	proc SetBlockText {win_name} {
		set Chatters [::MSN::usersInChat [::ChatWindow::Name $win_name]]
		set NrOfChatters [llength $Chatters]

		if { $NrOfChatters == 0 || $NrOfChatters > 1} {
			return "[trans block]/[trans unblock]"
		} else {
			if {[::MSN::userIsBlocked [lindex $Chatters 0]] == 0} {
				return "[trans block]"
			} else {
				return "[trans unblock]"
			}
		}
	}
	#Show the nickname of someone in the balloon
	#If someone changed nick, the new nick appear in the new balloon
	proc SetNickText {chatid} {
		return [::abook::getDisplayNick $chatid]
	}


	proc CreatePictureFrame { w bottom } {

		status_log "Creating picture frame\n"

		frame $bottom.f -class Amsn -borderwidth 0  -padx 0 -pady 0 \
	                    -relief solid -background [::skin::getKey chatwindowbg]

		set f $bottom.f
		set frame $f.pic
		set picture $frame.image
		set showpic $frame.showpic

		# Create them
		frame $frame -class Amsn -borderwidth 0 -relief solid -background [::skin::getKey chatwindowbg]

		framec $picture -type label -relief solid -image [::skin::getNoDisplayPicture] \
				-borderwidth [::skin::getKey chat_dp_border] \
				-bordercolor [::skin::getKey chat_dp_border_color] \
				-background [::skin::getKey chatwindowbg]
		set pictureinner [$picture getinnerframe]

		set_balloon $pictureinner [trans nopic]
		label $showpic -bd 0 -padx 0 -pady 0 -image [::skin::loadPixmap imgshow] \
			-bg [::skin::getKey chatwindowbg] -highlightthickness 0 -font splainf \
			-highlightbackground [::skin::getKey chatwindowbg] -activebackground [::skin::getKey chatwindowbg]
		bind $showpic <Enter> "$showpic configure -image [::skin::loadPixmap imgshow_hover]"
		bind $showpic <Leave> "$showpic configure -image [::skin::loadPixmap imgshow]"
		set_balloon $showpic [trans showdisplaypic]

		# Pack them
		#pack $picture -side left -padx 0 -pady [::skin::getKey chatpady] -anchor w
		pack $frame -side right -padx 0 -pady 0 -anchor e -fill y
		pack $showpic -side right -padx 0 -pady 0

		# Create our bindings
		bind $showpic <<Button1>> "::amsn::ToggleShowPicture"
		if { [::config::getKey old_dpframe 0] == 0 } {
			bind $pictureinner <<Button1>> "::amsn::ShowPicMenu $w %X %Y\n"
			bind $pictureinner <<Button3>> "::amsn::ShowPicMenu $w %X %Y\n"
			if {[catch {::dnd bindtarget $pictureinner Files <Drop> "fileDropHandler %D setdp self"} res]} {
				status_log "dnd error: $res"
			}
		} else {
			bind $pictureinner <<Button1>> "::amsn::ShowOldPicMenu $w %X %Y\n"
			bind $pictureinner <<Button3>> "::amsn::ShowOldPicMenu $w %X %Y\n"
		}

		#For TkAqua: Disable temporary, crash issue with that line
		if { ![OnMac] } {
			bind $picture <Configure> "::ChatWindow::ImageResized $w %h [::skin::getKey chat_dp_pady]"
		}
		::amsn::ShowOrHidePicture
		return $bottom.f

	}

        #///////////////////////////////////////////////////////////////////////////////
        # ::ChatWindow::GoToPrevTab ( container )
        # Used to switch to the next tab in a container. Called by the binding for the
        # <ctrl>+<PageUp> key combination. The list of windows in the container is used to
        # determine the next tab. ::ChatWindow::SwitchToTab is used for switching.
        # Arguments:
        # - container => The container window in which the current tab is located.
        proc GoToPrevTab { container } {
            set currentWin [::ChatWindow::getCurrentTab $container]
            set windows [set ::ChatWindow::containerwindows($container)]
            set tabPos [lsearch $windows $currentWin]

            # If the current tab is the last go the the first, else go to the next.
            if { $tabPos == 0 } {
                set nextTab [expr {[llength $windows] - 1}]
            } else {
                set nextTab [expr {$tabPos - 1}]
            }

            SwitchToTab $container [lindex $windows $nextTab]
        }
        #///////////////////////////////////////////////////////////////////////////////


        #///////////////////////////////////////////////////////////////////////////////
        # ::ChatWindow::GoToNextTab ( container )
        # Used to switch to the next tab in a container. Called by the binding for the
        # <ctrl>+<pagedown> key combination. The list of windows in the container is used to
        # determine the next tab. ::ChatWindow::SwitchToTab is used for switching.
        # Arguments:
        # - container => The container window in which the current tab is located.
        proc GoToNextTab { container } {
            set currentWin [::ChatWindow::getCurrentTab $container]
            set windows [set ::ChatWindow::containerwindows($container)]
            set tabPos [lsearch $windows $currentWin]

            # If the current tab is the last go the the first, else go to the next.
            if { $tabPos == [expr {[llength $windows] - 1}] } {
                set nextTab 0
            } else {
                set nextTab [expr {$tabPos + 1}]
            }

            SwitchToTab $container [lindex $windows $nextTab]
        }
        #///////////////////////////////////////////////////////////////////////////////


	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::ImageResized (win, height, padding)
	# Resets the minsize for the bottom frame when the image size changes
	# Arguments:
	#  - win => Is the window where the image has been changed
	#  - height => Is the new height of the image
	#  - padding => Is the padding around the image
	proc ImageResized { win height padding} {
		#TODO: need to remove hard coding here
		set picheight [image height [[GetInDisplayPictureFrame $win].pic.image cget -image]]
		if { $height < $picheight } {
			set height $picheight
		}

		set h [expr {$height + ( 2 * $padding ) }]
		if { $h < 100 } {
			set h 100
		}
		
		status_log "setting bottom pane misize for $win to $h\n"
		$win.f paneconfigure [GetInFrame $win] -minsize $h
	}


	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::SetFor (chatid, window)
	# Sets the specified window to be the one which will show messages and information
	# for the chat names 'chatid'
	# Arguments:
	#  - chatid => Is the chat id of the window, the passport account of the buddy
	#  - window => Is the window widget to be assigned (.msg_n - Where n is an integer)
	proc SetFor { chatid window } {
		if {$chatid != ""} {
			set ::ChatWindow::msg_windows($chatid) $window
			set ::ChatWindow::chat_ids($window) $chatid
		}
	}
	#///////////////////////////////////////////////////////////////////////////////


	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::Status (window, msg, [icon ""])
	# Writes the message $msg in the status bar of the window $window. It will add
	# the icon $icon at the beginning of the message, if specified.
	# Arguments:
	#  - window => Is the window widget focused (.msg_n - Where n is an integer)
	#  - msg => The status message that will be showed in the status bar of $window
	#  - [icon ""] => [NOT REQUIRED] The icon that will be at left of the message
	proc Status { win_name msg {icon ""}} {
		set msg [string map {"\n" " "} $msg]

		if { [winfo exists $win_name] } {

			[::ChatWindow::GetStatusText ${win_name}] configure -state normal
			[::ChatWindow::GetStatusText ${win_name}] delete 0.0 end

			if { "$icon"!=""} {
				[::ChatWindow::GetStatusText ${win_name}] image create end -image [::skin::loadPixmap $icon] -pady 0 -padx 1
			}

			[::ChatWindow::GetStatusText ${win_name}] insert end $msg
			[::ChatWindow::GetStatusText ${win_name}] configure -state disabled

		}
	}
	#///////////////////////////////////////////////////////////////////////////////

	
	proc MeasureTextCanvas { widget id dimension } {
		set bbox [$widget bbox $id]
		if {[llength $bbox] < 4} {
			set bbox [list 0 0 0 0]
		}
		if { $dimension == "w" } {
			return [expr {[lindex $bbox 2]-[lindex $bbox 0]}]
		} else {
			return [expr {[lindex $bbox 3]-[lindex $bbox 1]}]
		}
	}

	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::TopUpdate (chatid)
	# Gets the users in 'chatid' from the protocol layer, and updates the top of the
	# window with the user names and states.
	# Arguments:
	#  - chatid => Is the chat id of the window, the passport account of the buddy
	proc TopUpdate { chatid } {
		if { [::ChatWindow::For $chatid] == 0 } {
			return 0
		}

		set title ""
		set user_list [::MSN::usersInChat $chatid]

		if {[llength $user_list] == 0} {
			#return 0
			#We have a chatwindow, but no SB for it.
			#Check if the chatid is a valid user...
			if { [lsearch [::abook::getAllContacts] $chatid] != -1 } {
				set user_list $chatid
			} else {
				return 0
			}
		}

		set win_name [::ChatWindow::For $chatid]
		set top [::ChatWindow::GetTopFrame ${win_name}]
		set scrolling [getScrolling [::ChatWindow::GetOutText ${win_name}]]

		set camicon [::skin::loadPixmap camicon]
		set toX [::skin::getKey topbarpadx]

		set font [$top itemcget text -font]
		if { $font != "" } {
			set incr_y [font metrics $font -displayof $top -linespace]
		} else {
			set f [font create -family helvetica -size 12 -weight normal]
			set incr_y [font metrics $f -displayof $top -linespace]
			font delete $f
		}

		set usrsX [expr {$toX + [font measure bplainf -displayof $top "[trans to]:"] + 5}]
		set Ycoord [lindex [$top coords text] 1]
		set Ycoord [expr {int($Ycoord)}]
		set maxw [expr {[winfo width $top] - [::skin::getKey topbarpadx] - [expr {int([lindex [$top coords text] 0])} ] } ]
		set default_incr_y $incr_y
		set default_maxw $maxw
		set defaultfont sboldf
		
		$top dchars text 0 end
		$top dchars cw_txt 0 end
		$top dchars showhideusers 0 end
		$top delete camicon cw_txt bg ;#remove the camicon(s) and default icons

		#this code is for multichat with more then 3 users
		if {[llength $user_list] > 3} {
			$top dchars showhideusers 0 end
			set txt [list ]
			if {[::config::getKey hide_users_in_cw]} {
				set len [llength $user_list]
				set user_list ""
			
				lappend txt [list font sboldf] [list text "[trans showuserscw $len]"]
			} else {
				lappend txt [list font sboldf] [list text "[trans hideuserscw]"]
			}
			::guiContactList::renderContact $top "showhideusers" $maxw $txt 0
			$top configure -state normal 
			$top move showhideusers $usrsX $Ycoord
			
			$top bind showhideusers <Button-1> "::ChatWindow::ShowHideUsers"
			$top bind showhideusers <Enter> "$top configure -cursor hand2"
			$top bind showhideusers <Leave> "$top configure -cursor left_ptr"
			
			set Ycoord [expr {$Ycoord + $incr_y + 2}]
		}
		
		foreach user_login $user_list {
			set shares_cam [::abook::getContactData $user_login webcam_shared]
			
			if { [::config::getKey emailsincontactlist] == 1 } {
				set user_name [list text ""]
				set user_name_str ""
			} else {
				set user_name [::abook::getDisplayNick $user_login 1]
				set user_name_str [string map {"\n" " "} [::abook::removeStyles $user_name]]
			}

			if { [::config::getKey psmplace] == 0 } {
				set psmmedia [list text ""]
			} else {
				set psmmedia [::abook::getpsmmedia $user_login 1]
			}

			set state_code [::abook::getVolatileData $user_login state]
			if { $state_code == "" } {
				set user_state ""
				set state_code FLN
			} else {
				set user_state [::MSN::stateToDescription $state_code]
			}

			set maxw $default_maxw
			set incr_y $default_incr_y
			
			set user_name_dim $usrsX
			set new_temp_list [list ]
			foreach unit $user_name {
				switch [lindex $unit 0] {
					"text" {
						incr user_name_dim [font measure sboldf -displayof $top [lindex $unit 1]]
						lappend new_temp_list [lindex $unit]
					}
					"smiley" {
						if {[image height [lindex $unit 1]] > $incr_y} {
							set incr_y [image height [lindex $unit 1]]
						}
						incr user_name_dim [image width [lindex $unit 1]]
						lappend new_temp_list [lindex $unit]
					}
					"newline" {}
					default { lappend new_temp_list [lindex $unit] }
				}
			}
			foreach unit $psmmedia {
				switch [lindex $unit 0] {
					"smiley" {
						if {[image height [lindex $unit 1]] > $incr_y} {
							set incr_y [image height [lindex $unit 1]]
						}
					}
				}
			}
			set user_name $new_temp_list
			#to be sure there is a < and a > more
			incr user_name_dim [font measure sboldf -displayof $top " <<${user_login}>> "]


			if { "$user_state" != "" && "$user_state" != "online" } {
				#There is a free space before status name so it doesn't stick next to the psm
				set statetxt " \([trans $user_state]\)"
			} else {
				set statetxt ""
			}
			
			if { $shares_cam == 1} {
				incr maxw [expr { 0 - [image width $camicon] - 10 }]
			}

			set nicktxt [list ]
			set truncatenames [::config::getKey truncatenames]
			lappend nicktxt [list trunc $truncatenames] 
			set nicktxt [concat $nicktxt $user_name]
			
			if {!$truncatenames} {
				set maxw 2000
			}
			
			if {$user_name_dim >= $maxw && $truncatenames} {
				lappend nicktxt [list trunc 0] [list text " <${user_login}> $statetxt"] [list trunc 1]
			} else {
				lappend nicktxt [list text " <${user_login}> "]
				set nicktxt [concat $nicktxt $psmmedia]
				lappend nicktxt [list trunc 0] [list text $statetxt] [list trunc 1]
			}

			#get the default colour for the specific state
			set defaultcolour [::skin::getKey topbartext]
			if { ([llength $user_list] == 1) && ( "$user_state" != "" ) } {
				switch $state_code {
					"IDL" { set defaultcolour [::skin::getKey topbaridletext] }
					"BRB" { set defaultcolour [::skin::getKey topbarbrbtext] }
					"AWY" { set defaultcolour [::skin::getKey topbarawaytext] }
					"LUN" { set defaultcolour [::skin::getKey topbarlunchtext] }
					"PHN" { set defaultcolour [::skin::getKey topbarphonetext] }
					"BSY" { set defaultcolour [::skin::getKey topbarbusytext] }
					"FLN" { set defaultcolour [::skin::getKey topbarofflinetext] }
				}
			}

			set list_1  [list [list default $defaultcolour $defaultfont] [list colour reset] [list font reset] [list font $defaultfont]]
			set nicktxt [concat $list_1 $nicktxt]
			::guiContactList::renderContact $top [list cw_${user_login} cw_txt] $maxw $nicktxt 0
			
			$top move cw_${user_login} $usrsX $Ycoord

			if { $user_name_str != "" } {
				set title "${title}${user_name_str}, "
			} else {
				set title "${title}${user_login}, "
			}
			
			if { $shares_cam == 1 } {
				if {[image height $camicon] > $incr_y} {
					set incr_y [image height $camicon]
				}

				#the image aligned-right to the text
				set Xcoord [expr {[winfo width $top] - [image width $camicon]}]
	
				$top create image $Xcoord $Ycoord -anchor nw -image $camicon -tags [list camicon camicon_$user_login] -state normal

				#If clicked, invite the user to send webcam
				$top bind camicon_$user_login <Button-1> "::MSNCAM::AskWebcamQueue $user_login" 

				#add the balloon-binding
				$top bind camicon <Enter> [list balloon_enter %W %X %Y "[trans askwebcam]"]
				$top bind camicon <Motion> [list balloon_motion %W %X %Y "[trans askwebcam]"]
				$top bind camicon <Leave> "set Bulle(first) 0; kill_balloon"
				#change the cursor
				$top bind camicon <Enter> "+$top configure -cursor hand2"
				$top bind camicon <Leave> "+$top configure -cursor left_ptr"
			}

			set Ycoord [expr {$Ycoord + $incr_y + 2}]
		}

		bind $top <Configure> [list ::ChatWindow::TopUpdate $chatid]

		if {[llength $user_list] > 0 && ![::config::getKey hide_users_in_cw]} {
			#Change color of top background by the status of the contact
			ChangeColorState $user_list $user_state $state_code ${win_name}
		}

		set title [EscapeTitle [string replace $title end-1 end " - [trans chat]"]]
		set ::ChatWindow::titles(${win_name}) ${title}

		set Ycoord [expr {int($Ycoord)}]
		$top configure -height $Ycoord

		if { [GetContainerFromWindow $win_name] == "" } {
			if { [info exists ::ChatWindow::new_message_on(${win_name})] && $::ChatWindow::new_message_on(${win_name}) == "asterisk" } {
				wm title ${win_name} "*${title}"
			} else {
				wm title ${win_name} ${title}
			}
		} else {
			NameTabButton $win_name $chatid
		}

		if { $scrolling } { catch {::ChatWindow::Scroll [::ChatWindow::GetOutText ${win_name}]} }

		#PostEvent 'TopUpdate'
		set evPar(chatid) "chatid"
		set evPar(win_name) "win_name"
		set evPar(user_list) "user_list"
		::plugins::PostEvent TopUpdate evPar
		
		update idletasks

		# If we had a flickering window, bypass windows bug and reflicker it after the title change..
		if { [OnWin] } {
			# Make sure we check the toplevel window, in case we use a container.
			set window $win_name
			set container [GetContainerFromWindow $window]
			if { $container != ""} {
				set window $container
			}

			if {[bind $window <FocusIn>] != "" } {
				catch {winflash $window -count 1}
			}
		}

		after cancel [list ::ChatWindow::TopUpdate $chatid]
	}
	
	proc ShowHideUsers {} {
		if {[::config::getKey hide_users_in_cw]} {
			::config::setKey hide_users_in_cw 0
		} else {
			::config::setKey hide_users_in_cw 1
		}
		
		foreach chat_id [getAllChatIds] {
			TopUpdate $chat_id
		}
	}

	
	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::ChangeColorState {user_list user_state state_code win_name}
	# Change the color of the top window when the other contact is in another status
	proc ChangeColorState {user_list user_state state_code win_name} {
		#get the colour for the state
		set colour [::skin::getKey topbarbg]
		set scolour [::skin::getKey topbarbg_sel]
		set tcolour [::skin::getKey topbartext]
		set bcolour [::skin::getKey topbarborder]
		if { ([llength $user_list] == 1) && ("$user_state" != "" ) } {
			if { $state_code == "IDL" } {
				set colour [::skin::getKey topbaridlebg]
				set tcolour [::skin::getKey topbaridletext]
				set bcolour [::skin::getKey topbaridleborder]
			} elseif { $state_code == "BRB" } {
				set colour [::skin::getKey topbarbrbbg]
				set tcolour [::skin::getKey topbarbrbtext]
				set bcolour [::skin::getKey topbarbrbborder]
			} elseif { $state_code == "AWY" } {
				set colour [::skin::getKey topbarawaybg]
				set tcolour [::skin::getKey topbarawaytext]
				set bcolour [::skin::getKey topbarawayborder]
			} elseif { $state_code == "LUN" } {
				set colour [::skin::getKey topbarlunchbg]
				set tcolour [::skin::getKey topbarlunchtext]
				set bcolour [::skin::getKey topbarlunchborder]
			} elseif { $state_code == "PHN" } {
				set colour [::skin::getKey topbarphonebg]
				set tcolour [::skin::getKey topbarphonetext]
				set bcolour [::skin::getKey topbarphoneborder]
			} elseif { $state_code == "BSY" } {
				set colour [::skin::getKey topbarbusybg]
				set tcolour [::skin::getKey topbarbusytext]
				set bcolour [::skin::getKey topbarbusyborder]
			} elseif { ($state_code == "FLN") } {
				set colour [::skin::getKey topbarofflinebg]
				set tcolour [::skin::getKey topbarofflinetext]
				set bcolour [::skin::getKey topbarofflineborder]
			}
		}
		#set the areas to the colour
		
		set top [GetTopFrame ${win_name}]
		$top configure -bg $colour -bordercolor $bcolour
		$top itemconfigure text -fill $tcolour
		$top itemconfigure to -fill $tcolour
		
		set bg "::$top.bg"

		if { [::skin::getKey chat_top_pixmap] && [info procs $bg] != ""} {
			set topimg [$bg cget -source]
			$topimg copy [::skin::loadPixmap cwtopback]
			::picture::Colorize $topimg $colour
			$bg BuildImage
			bind $top <Configure> "[bind $top <Configure>]; $bg configure -width %w -height %h" 
		}
	}

	#///////////////////////////////////////////////////////////////////////////////
	# ::ChatWindow::UnsetFor (chatid, window)
	# Tells the GUI system that window $window is no longer available for $chatid
	# Arguments:
	#  - chatid => Is the chat id of the window, the passport account of the buddy
	#  - window => Is the window widget assigned (.msg_n - Where n is an integer)
	proc UnsetFor {chatid window} {
		if {[info exists ::ChatWindow::msg_windows($chatid)]} {
			unset ::ChatWindow::msg_windows($chatid)
			unset ::ChatWindow::chat_ids($window)
		}
	}
	#///////////////////////////////////////////////////////////////////////////////

	proc FlickerTab { win {new 1}} {
		variable win2tab
		variable winflicker
		variable visibletabs
		variable containerwindows

		if { $win == 0 || ![info exists win2tab($win)] } { return }
		if {![winfo exists $win]} { return }
		if { $win == [GetCurrentWindow [winfo toplevel $win]] } { return }

		set tab $win2tab($win)
		set container [string range $tab 0 [expr {[string last "." $tab] - 1}] ]
		set container [string range $container 0 [expr {[string last "." $container] -1}] ]

                TrayBlinkStart $win

		#if tab is not visible, then we should change the color of the < or > button
		#to let know there is an invisible tab flickering (an incoming message)
		if { [info exists visibletabs($container)] } {
		
			foreach window [set containerwindows($container)] {
				set visible 0
				foreach winvisible [set visibletabs($container)] {
					if { ![string equal $window $winvisible] } {
						if { !$visible && [string equal $window $win] } {
							set right 0
						} elseif { [string equal $window $win] } {
							set right 1
						}
					} else {
						set visible 1
					}
				}
			}
	
	
			if { [info exists right] } {
				if { $right == 0 } {
					#we change the less color
					catch { ${container}.bar.less configure -bg green }
				} else {
					#we flicker the more button
					catch { ${container}.bar.more configure -bg green }
				}
			}
		}

		if { [::picture::IsAnimated [::skin::GetSkinFile pixmaps tab_flicker.gif]] } {
			ConfigureTab $tab "tab_flicker"
		} else {
			after cancel "::ChatWindow::FlickerTab $win 0"
			if { $new == 1 || ![info exists winflicker($win)]} {
				set winflicker($win) 0
			}

			set count [set winflicker($win)]

			if { [expr {$count % 2}] == 0 } {
				ConfigureTab $tab "tab_flicker"
			} else {
				ConfigureTab $tab "tab"	
			}

			incr winflicker($win)

			#if { $count > 10 } {
			#	$tab configure -image [::skin::loadPixmap tab_flicker]
			#	return
			#}

			#Check if the container window lost focus, then make it flicker:
			set container [GetContainerFromWindow $win]
			if { $container != "" } {
				if { ![info exists ::ChatWindow::new_message_on(${container})] &&
				     [string first $container [focus]] != 0 } {
					Flicker $container
				}	
			}
			
			
			after 300 "::ChatWindow::FlickerTab $win 0"
		}
	}

	proc GetContainerFor { user } {
		variable containers
		 
		if { [::config::getKey tabbedchat] == 1 } {
			if { [info exists containers(global)] && $containers(global) != ""} {
				return $containers(global)
			} else {
	
				set containers(global) [CreateNewContainer]
		
				return $containers(global)
			}

		} elseif { [::config::getKey tabbedchat] == 2 } {
			set gid "group[lindex [::abook::getContactData $user group] 0]"
			if { [info exists containers($gid)] && $containers($gid) != ""} {
				return $containers($gid)
			} else {

				set containers($gid) [CreateNewContainer]
			
				return $containers($gid)
			}
		} else {
			return ""
		}
		

	}

	proc AddWindowToContainer { container win } {
		variable containerwindows

		if { ![info exists containerwindows($container)] } {

			set tab [CreateTabButton $container $win]
			pack $tab -side left -expand false -fill both -anchor e

			set containerwindows($container) $win
			SwitchToTab $container $win
			
			if { [OnMac] } {
				lower $container
			}
			
		} else {
			if { [lsearch [set containerwindows($container)] $win] == -1 } {
				set tab [CreateTabButton $container $win]
				pack $tab -side left -expand false -fill both -anchor e

				lappend containerwindows($container) $win
			} else {
				return
			}
		}
		CheckForTooManyTabs $container
	}


	proc GetContainerFromWindow { win } {
		variable containerwindows

		if { ![info exists containerwindows] } {
			return ""
		} else {
			foreach container [array names containerwindows] {
				if { [lsearch [set containerwindows($container)] $win] != -1 } {
					return $container
				}
			}
		}

		return ""

	}

	proc ConfigureTab {tab img} {
		$tab delete tab_bg
		$tab create image 1 0 -image [::skin::loadPixmap $img] -anchor nw -tags tab_bg
		$tab lower tab_bg tab_text
	}
	

	proc CreateTabButton { container win} {
		variable containerwindows
		variable tab2win
		variable win2tab
		
		set w [string map { "." "_"} $win]
		set tab $container.bar.$w

		set tab_width [image width [::skin::loadPixmap tab]]
		set tab_height [image height [::skin::loadPixmap tab]]

		set nick [string trim $win] ;# to avoid havng a blank tab if the user has  a nick like "\n\n\n my nick"
	#	set idx [string first "\n" $nick]
	#	if { $idx != -1 } {
	#	        set nick [string range $nick 0 [expr {$idx -1}]]
	#	}

		set nick [list [list text $nick]]
		canvas $tab -bg [::skin::getKey tabbarbg] -width $tab_width -height $tab_height
		::guiContactList::renderContact $tab tab_text $tab_width $nick 0
		$tab create image [::skin::getKey tab_close_x] [::skin::getKey tab_close_y] -image [::skin::loadPixmap tab_close] -activeimage [::skin::loadPixmap tab_close_hover] -anchor nw -tags tab_close
		$tab create image 1 0 -image [::skin::loadPixmap tab] -anchor nw -tags [list tab_bg]


		bind $tab <Enter> "::ChatWindow::TabEntered $tab $win"
		bind $tab <Leave> "::ChatWindow::TabLeft $tab $win"
		bind $tab <<Button2>> "::ChatWindow::CloseTab $tab"
		$tab bind tab_close <ButtonRelease-1> [list after 0 "::ChatWindow::CloseTab $tab"]
		$tab bind tab_bg <ButtonRelease-1> "::ChatWindow::SwitchToTab $container $win"
		$tab bind tab_text <ButtonRelease-1> "::ChatWindow::SwitchToTab $container $win"

		set tab2win($tab) $win
		set win2tab($win) $tab

		bind $tab <<Button3>> [list ::ChatWindow::createRightTabMenu $tab %X %Y]

		return $tab
	}

	proc CloseOtherTabs { tokeep } {
		variable containerwindows
		variable win2tab

		set w [winfo toplevel $tokeep]

		if {![info exists containerwindows($w)] || [winfo toplevel $w] != $w} {
			return
		}

		foreach window [set containerwindows($w)] {
			set tab [set win2tab($window)]
			if {$tab != $tokeep} {
				CloseTab $tab
			}
		}
	}
	
	proc CloseTab { tab {detach 0}} {
		variable win_history
		variable containercurrent
		variable containerprevious
		variable containerwindows
		variable tab2win
		variable win2tab
		
		set win [set tab2win($tab)]
		if {[::amsn::SIPchatidExistsInList [Name $win]]} {
			status_log " we can't close, there's a sip call running ..." green
			if {[$::farsight IsVideo] } {
				::amsn::infoMsg [trans closeorcallvideo]
			} else {
				::amsn::infoMsg [trans closeorcall]
			}
			return
		}
		set container [winfo toplevel $win]

		if {!$detach} {
			array unset win_history [GetInputText $win]
		}
		
		destroy $win
		destroy [set win2tab($win)]
		set idx [lsearch [set containerwindows($container)] $win]
		set containerwindows($container) [lreplace [set containerwindows($container)] $idx $idx]
		unset win2tab($win)
		unset tab2win($tab)

		if { [info exists containerprevious($container)] && [set containerprevious($container)] != "" } {
			set newwin [set containerprevious($container)]
			if { [GetContainerFromWindow $newwin] != $container } {
				set newwin [lindex [set containerwindows($container)] 0]
			}
		} else {
			set newwin [lindex [set containerwindows($container)] 0]
		}

		CheckForTooManyTabs $container

		if { $newwin == "" } { 
			set containercurrent($container) ""
			destroy $container
		        ChatWindowDestroyed $container
		} else {
			SwitchToTab $container $newwin
		}
		
	}

	proc TabEntered { tab win } {
		after cancel "::ChatWindow::FlickerTab $win"; 
		ConfigureTab $tab "tab_hover"
		set chatid [::ChatWindow::Name $win]
		NameTabButton $win $chatid 1
	}
	
	proc TabLeft {tab win} {
		if { [info exists ::ChatWindow::oldpixmap($tab)] } { 
			set image [set ::ChatWindow::oldpixmap($tab)]
		} else {
			set image tab
		}

		set win [set ::ChatWindow::tab2win($tab)]
		if { $win == [GetCurrentWindow [winfo toplevel $win]] } { 
			set image tab_current
		}
		
		ConfigureTab $tab $image
		set chatid [::ChatWindow::Name $win]
		NameTabButton $win $chatid 0
	 }

	#///////////////////////////////////////////////////////////////////////////////////
	# NameTabButton $win $chatid
	# This proc changes the name of the tab
	proc NameTabButton { win chatid {hovered 0}} {
		variable win2tab
		

		set tab [set win2tab($win)]
		set users [::MSN::usersInChat $chatid]
		# We have two ways of changing a tab button text
		if { $::tcl_version >= 8.4 } {
			set tabvar $tab
		} else {
			set tabvar ${tab}_lbl
		}
		#status_log "naming tab $win with chatid info $chatid\n" red
		
		$tabvar dchars tab_text 0 end
		$tabvar delete tab_text
		if {$hovered} {
			set tabfg [::skin::getKey tabfg_hover]
		} else {
			set tabfg [::skin::getKey tabfg]
		}

		set style [list [list space 10] [list margin 0 8] \
			       [list default $tabfg splainf] [list colour reset]]
		
		if { $users == "" || [llength $users] == 1} {
			set nick [::abook::getDisplayNick $chatid 1]
			if { $nick == "" || [::config::getKey tabtitlenick] == 0 } {
				set txt [concat $style [list [list text $chatid]]]
			} else {
				set txt [concat $style $nick]
			}
		} elseif { [llength $users] != 1 } {
			set number [llength $users]
			set txt [trans conversationwith $number]
			set txt [concat $style [list [list text $txt]]]
		}
		
		::guiContactList::renderContact $tabvar tab_text [expr {[::skin::getKey tab_close_x] - 5}] $txt 0
		$tabvar create image [::skin::getKey tab_close_x] [::skin::getKey tab_close_y] -image [::skin::loadPixmap tab_close]  -activeimage [::skin::loadPixmap tab_close_hover] -anchor nw -tags tab_close
		
		::ChatWindow::UpdateContainerTitle [winfo toplevel $win]
	}


	proc GetCurrentWindow { container } {
		variable containercurrent

		if { [info exists containercurrent($container)] && [set containercurrent($container)] != "" } {
			return [set containercurrent($container)]
		} else {
			return $container
		}

	}

	proc SwitchToTab { container win } {
		variable containercurrent
		variable win2tab
		variable containerprevious
		variable containerwindows
		
		if { [info exists containerwindows($container)] &&
		     [lsearch [set containerwindows($container)] $win] == -1 } { 
			status_log "can't switch to a window that doesn't belong to the correct container"
			return
		} else {
			::ChatWindow::TrayBlinkStop $win
		}
		
#TODO:		# Don't switch if tab clicked is already current tab. > 2 used because otherwise windows for new mesages dont appear. this means this is only effective with three or more tabs open. hope someone can find how to fix this.
		if { [info exists containercurrent($container)] == 1 && [set containercurrent($container)] == $win && [llength [set containerwindows($container)]] > 2  } { return }

		if { [info exists containercurrent($container)] && [set containercurrent($container)] != "" } {
			set w [set containercurrent($container)]
			pack forget $w
			set containerprevious($container) $w
			if { [info exists win2tab($w)] } {
				set tab $win2tab($w)
				ConfigureTab $tab "tab"
			}
		}
		
		set  containercurrent($container) $win
		pack $win -side bottom -expand true -fill both

		# Tell search dialog we've changed tabs
		if { [winfo exists $container.search] } {
			$container.search configure -searchin [::ChatWindow::GetOutText $win]
		}

		if { ![info exists containerprevious($container)] } {
			set containerprevious($container) $win
		}

		if { [info exists win2tab($win)] } {
			set tab $win2tab($win)
			ConfigureTab $tab "tab_current"
		}

		::ChatWindow::UpdateContainerTitle $container

		# Should fix the issue with tab switching and the input not focusing.
		#update idletasks

#		bind $win <Map> [list focus [::ChatWindow::GetInputText $win] ]

		focus [::ChatWindow::GetInputText $win]
	}

	#updates the title and the icon of the container window
	proc UpdateContainerTitle { container } {
		#get the name of the "window" which is hte name of the tab in fact
		set win [GetCurrentWindow $container]
		#get the ID of the chat (email if only one user)
		set chatid [::ChatWindow::Name $win]
		set usersinchat [::MSN::usersInChat $chatid]
		if {$usersinchat == ""} {
			set usersinchat $chatid
		}

		#we'll set a title for the container-window, beginning from scratch
		set title ""


#TODO: have the titled made up with a template with vars like $nicknames, $groupname and [trans chat] etc
		if { $chatid != 0 } {

			#append all nicknames in the chat first to the title	
			foreach user $usersinchat { 
				#strip out newlines and tabs
				set nick [string map {"\n" " " "\t" " "} [::abook::getDisplayNick $user]]
				set title "${title}${nick}, "
			}

			#replace the last ", " with " : <name of the containerwindow> - chat"
			set title [string replace $title end-1 end " : [GetContainerName $container] - [trans chat]"]
		}

		if { [::OIM_GUI::IsOIM $chatid] == 1 } {
			set title "$chatid - [trans oim]"
		}
		#don't think this proc does much .. anyway ;)
		set title [EscapeTitle $title]
		#store our generated title in the array which is needed to reset the title after out "blink"
		set ::ChatWindow::titles($container) $title

		#put an asterisk for the title if a new message has arrived
		if { [info exists ::ChatWindow::new_message_on($container)] && [set ::ChatWindow::new_message_on($container)] == "asterisk" } {
			wm title $container "*$title"
		} else {
			wm title $container "$title"
		}
		
		#Post event for plugins to know the window title was changed
		set evPar(title) $title
		set evPar(win) $win
		set evPar(chatid) $chatid
		::plugins::PostEvent chatwin_title_changed evPar
	}

	#this proc is to get the name of the containerwindow, like groupname for groupchats
	proc GetContainerName { container } {
		variable containers

		foreach type [array names containers] {
			if { $container == [set containers($type)] } {
				if { $type == "global" } {
					return ""
				} elseif { [string first "group" $type] == 0} {
					set gid [string range $type 5 end]
					set name [::groups::GetName $gid]
					if {$name != "" } {
						return "$name"
					} else {
						return "$type"
					}
				} else {
					return "$type"
				}
			}
		} 

		return ""
	}

	proc UseContainer { } {
		set istabbed [::config::getKey tabbedchat]

		if { $istabbed == 1 || $istabbed == 2 } {
			return 1
		} else {
			return 0
		}

	}

	proc CheckForTooManyTabs { container {dorepack "1"}} {
		variable containerwindows
		variable visibletabs
		variable win2tab
		if { ![info exists containerwindows($container)] } {
			return
		}

		set bar_w [winfo width ${container}.bar]
		set tab_w [image width [::skin::loadPixmap tab]]

		set less_w [image width [::skin::loadPixmap moretabs]] 
		set more_w [image width [::skin::loadPixmap lesstabs]]

		set bar_w [expr {$bar_w - $less_w - $more_w}]

		set max_tabs [expr int(floor($bar_w / $tab_w))]
		set number_tabs [llength [set containerwindows($container)]]
	
		set less ${container}.bar.less
		set more ${container}.bar.more

		pack forget $less
		pack forget $more

#		status_log "Got $number_tabs tabs in $container that has a max of $max_tabs\n" red

		if { $number_tabs < 2 } {
			pack forget ${container}.bar
		} else {
			#Fix  hidden tabs problem, thanks to Le philousophe
			pack ${container}.bar -side top -fill both -expand false
			
			#These lines are absolutely necessary on Mac OS X to fix a crash problem
			if { [OnMac] && [winfo exists [GetCurrentWindow $container]] && $dorepack } {
				pack forget [GetCurrentWindow $container]
				pack [GetCurrentWindow $container] -side bottom -expand true -fill both
			}

		}
		if { $max_tabs > 0 && $number_tabs > $max_tabs } {
			pack $more -side right -expand false -fill both -anchor e
			pack $less -side right -expand false -fill both -anchor e

			UpdateVisibleTabs $container  $max_tabs		
			UpdateLessMoreButtons $container $less $more

		} else {
			set visibletabs($container) [set containerwindows($container)]

		}
		foreach window [set containerwindows($container)] {
			set tab [set win2tab($window)]
			catch {pack forget $tab}
		}
		foreach window [set visibletabs($container)] {
			set tab [set win2tab($window)]
			pack $tab -side left -expand false -fill both -anchor e
		}
	}

	proc LessTabs { container less more} {
		variable visibletabs
		variable containerwindows
		variable win2tab

		set visible [set visibletabs($container)]
		set windows [set containerwindows($container)]

		set first [lindex $visible 0]
		set last [lindex $visible end]

		set idx [lsearch $windows $first]
		incr idx -1

		set new [lindex $windows $idx]
		if {$new != "" } {
			set tab [set win2tab($new)]
			catch {pack forget [set win2tab($last)]}
			if { $first != $last } {
				pack $tab -side left -expand false -fill both -anchor e -before [set win2tab($first)]
			} else {
				pack $tab -side left -expand false -fill both -anchor e
			}
			set visibletabs($container) [lrange $visible 0 end-1] 
			set visibletabs($container) [linsert [set visibletabs($container)] 0 $new]
		} else {
			$less conf -state disabled
		}
		$more conf -state normal	

		UpdateLessMoreButtons $container $less $more
		
	}

	proc MoreTabs { container less more} {
		variable visibletabs
		variable containerwindows
		variable win2tab

		set visible [set visibletabs($container)]
		set windows [set containerwindows($container)]

		set first [lindex $visible 0]
		set last [lindex $visible end]

		set idx [lsearch $windows $last]
		incr idx 

		set new [lindex $windows $idx]
		if {$new != "" } {
			set tab [set win2tab($new)]
			catch {pack forget [set win2tab($first)]}
			pack $tab -side left -expand false -fill both -anchor e
			set visibletabs($container) [lrange $visible 1 end]
			lappend visibletabs($container) $new
			
		} else {
			$more conf -state disabled
		}
		$less conf -state normal

		UpdateLessMoreButtons $container $less $more
	}

	proc UpdateVisibleTabs { container max } {
		variable visibletabs
		variable containerwindows

		set visible [set visibletabs($container)]
		set windows [set containerwindows($container)]

		set first_idx [lsearch $windows [lindex $visible 0]]
		if {$first_idx == -1 } {
			set first_idx [lsearch $windows [lindex $visible 0]]
		}
		
		set visible [lrange $windows $first_idx [expr {$first_idx + $max - 1}]]
		if { [llength $visible] < $max } {
			set visible [lrange $windows end-[expr {$max -1}] end]
		}

		set visibletabs($container) $visible

	}

	proc UpdateLessMoreButtons { container less more } {
		variable visibletabs
		variable containerwindows

		set visible [set visibletabs($container)]
		set windows [set containerwindows($container)]
		
		set first [lindex $visible 0]
		set last [lindex $visible end]
		
		set idx [lsearch $windows $first]
		incr idx -1
		
		set new [lindex $windows $idx]
		if {$new == "" } {
			$less conf -state disabled
		}
		
		set idx [lsearch $windows $last]
		incr idx 
		
		set new [lindex $windows $idx]
		if {$new == "" } {
			$more conf -state disabled
		}
	}

	proc getCurrentTab { win } {
		return [GetCurrentWindow $win]
	}

	proc createRightTabMenu { tab x y} {
		if { [winfo exists .tabmenu] } { destroy .tabmenu }
		menu .tabmenu -tearoff 0 -type normal
		.tabmenu insert end command -command "::ChatWindow::CloseTab $tab; destroy .tabmenu" -label "[trans close]"
		.tabmenu insert end command -command "::ChatWindow::CloseOtherTabs $tab; destroy .tabmenu" -label "[trans closeothers]"
		.tabmenu insert end command -command "::ChatWindow::DetachTab $tab; destroy .tabmenu" -label "[trans detach]"
		tk_popup .tabmenu $x $y
		#return .tabmenu
	}

	proc DetachTab { tab } {
		global win_history
		set win [set ::ChatWindow::tab2win($tab)]
		set out [GetOutText $win]
		set in [GetInputText $win]
		set dump_out [$out dump 0.0 end]
		set dump_in [$in dump 0.0 end]

		foreach tag [$out tag names] {
			foreach option [$out tag configure $tag] {
				if { ([llength $option] == 5) && ([lindex $option 4] != {}) } {
					lappend tags_out($tag) [lindex $option 0]
					lappend tags_out($tag) [lindex $option 4]
				}
			}
		}


		status_log "Got dumps : \n$dump_out\n\n$dump_in\n" red

		set chatid [Name $win]
		
		UnsetFor $chatid $win
		set new [RecreateWindow $chatid]

		set ::ChatWindow::titles(${new}) [set ::ChatWindow::titles(${win})]
		set ::ChatWindow::first_message(${new}) [set ::ChatWindow::first_message(${win})]
		set ::ChatWindow::recent_message(${new}) [set ::ChatWindow::recent_message(${win})]
		set ::ChatWindow::containercurrent(${new}) ${new}

		#We now copy the history of what we said
		set winhisto [GetInputText $win]
		set newhisto [GetInputText $new]
		if { [info exists win_history(${winhisto}_count)] } {
			set win_history(${newhisto}_count) $win_history(${winhisto}_count)
			set win_history(${newhisto}_index) $win_history(${winhisto}_index)
			set win_history(${newhisto}) $win_history(${winhisto})
			if { [info exists win_history(${winhisto}_temp)] } {
				set win_history(${newhisto}_temp) $win_history(${winhisto}_temp)
			}
		}
		
		unset ::ChatWindow::titles(${win})
		unset ::ChatWindow::first_message(${win})
		unset ::ChatWindow::recent_message(${win})

		#Delete images if not in use
		catch {destroy [GetInDisplayPictureFrame $win].pic}

		CloseTab $tab 1

		#We now clean the old history
		if { [info exists win_history(${winhisto}_count)] } {
			unset win_history(${winhisto}_count)
			unset win_history(${winhisto}_index)
			unset win_history(${winhisto})
			if { [info exists win_history(${winhisto}_temp)] } {
				unset win_history(${winhisto}_temp)
			}
		}
		
		set out [GetOutText $new]
		set in [GetInputText $new]

		$out configure -state normal -font bplainf -foreground black

		undump $out $dump_out 1 [array get tags_out]
		#We dumped an invisible new line due to end index so remove it now
		$out delete "end - 1 lines"
		undump $in $dump_in 0
		$in delete "end - 1 lines"
		
	}

	proc undump { w dump rotext {tags_config ""}} {
		status_log "tags : $tags_config\n" red
		if { $rotext } { set insert_cmd roinsert } else { set insert_cmd insert }
		foreach {tag options} $tags_config {
			status_log "tag $tag has options $options" red
			foreach {option value} $options { 
				status_log "option $option of tag $tag is $value\n" red
				if {$value != "" } {
					status_log "setting tag option to $value\n" red
					$w tag configure $tag $option $value
				}
			}
		}

		foreach { key value index } $dump {
			#status_log "Undumping into $w, the key $key with value $value at index $index\n" red
			switch -- $key {
				text { 
					$w $insert_cmd $index $value
				} 
				mark {
					$w mark set $value $index
				} 
				image {
					if { [catch {image width $value} ]} {
						if { [string first "#" $value] != -1 } {
							set value [string range $value 0 [expr {[string last "#" $value] -1}]]
						} else {
							set value ""
						}
						if { [catch {image width $value} ]} {
							set value ""
						}
						
					}
					if { $value != "" } {
						$w image create $index -image $value
					}
				}
				window {
					if {[winfo exists $value] } {
						$w window create $index -window $value
					} else {
						status_log "undumping a window that doesn't exist\n" error
					}
				}
				tagon {
					set tags($value) $index
				}
				tagoff {
					$w tag add $value [set tags($value)] $index
				}
				default {
					status_log "Undumping to window $w an unknown key $key with value $value at index $index\n" red
				}
			}
		}
		
	}

	proc RecreateWindow { chatid } {
	
		set win_name [::ChatWindow::Open]
		::ChatWindow::SetFor $chatid $win_name
	
		set ::ChatWindow::first_message($win_name) 0
		set usr_name [lindex [::MSN::usersInChat $chatid] 0]
	
		# PostEvent 'new_conversation' to notify plugins that the window was created
		set evPar(chatid) chatid
		set evPar(usr_name) usr_name
		::plugins::PostEvent new_conversation evPar
		

		set top_win [winfo toplevel $win_name]

		if { [winfo exists .bossmode] } {
			set ::BossMode(${top_win}) "normal"
			wm state ${top_win} withdraw
		} else {
			if { [::config::getKey winmaximized 0] == 1 } {
				wm state ${top_win} zoomed
			} else {
				wm state ${top_win} normal
			}
		}
		
		wm deiconify ${top_win}
		

		update idletasks

		if { [OnMac] } {
			::ChatWindow::MacPosition ${top_win}
		}
		::ChatWindow::TopUpdate $chatid

		set usr_name [lindex [::MSN::usersInChat $chatid] 0]
		if { [winfo exists [GetOutDisplayPicturesFrame $win_name].dps] } {
			::amsn::ShowOrHidePicture
			::amsn::ShowOrHideTopPicture
			::amsn::UpdatePictures $win_name
		} else {
			if { [::config::getKey showdisplaypic] && $usr_name != ""} {
				::amsn::ChangePicture $win_name [::skin::getDisplayPicture $usr_name] [trans showuserpic $usr_name]
			} else {
				::amsn::ChangePicture $win_name [::skin::getDisplayPicture $usr_name] [trans showuserpic $usr_name] nopack
			}
		}
		
		#We have a window for that chatid, raise it
		raise ${top_win}

		#Causes freeze when detaching the last tab...
		after idle [list after 0 [list focus [::ChatWindow::GetInputText ${win_name}]]]

		return $win_name

	}

	###################################################
	# proc getScrolling : gets the scrolling status of
	# textwidget $tw. Returns 1 to scroll, 0 not to.
	
	proc getScrolling { tw } {
		variable scrolling
		
		#status_log "getScrolling: $tw\n"
		
		if { [info exists scrolling($tw)] } {
		#We are scrolling to the bottom so we are obviously stuck to the end
			return 1
		} elseif { [winfo exists $tw] } {
			if { [lindex [$tw yview] 1] == 1.0 } {
				#We are at the bottom of the tw so we are stuck to the end
				return 1
			} else {
				#The tw doesn't exist
				return 0
			}
		} else {
			return 0
		}
	}
	
	#########################################################
	# proc Scroll : Scrolls down the textwidget $tw

	proc Scroll { tw } {
		variable scrolling

		if { ![winfo exists $tw] } { return }
		
		if { ![info exists scrolling($tw)] } {
			set scrolling($tw) 0
		}
		#status_log "Scroll: $tw "
		incr scrolling($tw)
		$tw yview end

		after 100 "catch {incr ::ChatWindow::scrolling($tw) -1; if {\$::ChatWindow::scrolling($tw) == 0 } {unset ::ChatWindow::scrolling($tw) }}"
		
	}

	proc SaveToFile { w } {
		set chatid [::ChatWindow::Name $w]

		switch -- [::config::getKey dateformat] {
			"MDY" {
				set date [clock format [clock seconds] -format "%m%d%Y"]
			}
			"DMY" {
				set date [clock format [clock seconds] -format "%d%m%Y"]
			}
			"YMD" -
			default {
				set date [clock format [clock seconds] -format "%Y%m%d"]
			}
		}

		if {$chatid == 0 || [llength [::MSN::usersInChat $chatid]] > 1} {
			set filename "[trans chat]_${date}.log"
		} else {
			set filename "${chatid}_${date}.log"
		}
		set txtw [::ChatWindow::GetOutText $w]
		set file [chooseFileDialog $filename [trans save] $w "" save]
		
		if { $file != "" } {
			if { [catch {set fd [open $file w] }] } {
				msg_box "[trans invalidfile2 $file]"
				return
			}
		
			set content ""
			set dump [$txtw  dump  -text 0.0 end]
			foreach { text output index } $dump {
				append content $output
			}
		
			puts $fd $content
			close $fd
		}
	}
}

::snit::widget chatwindow {

	hulltype toplevel
	delegate option * to hull

	constructor {args} {
#		button $win.open -text Open -command [mymethod open]
#		button $win.save -text Save -command [mymethod save]

		# ....

		$self configurelist $args

	}

	method messageReceived { message } {
		status_log "(chatwindow.tcl)[$message getBody]"
	}
}


proc EscapeTitle { title } {
	
        return $title

	# This RE is just a character class for everything "bad"
	set RE {[\u0080-\uffff]}
	
	# We will substitute with a fragment of Tcl script in brackets
	set substitution "?" ;#{[format \\\\u%04x [scan "\\&" %c]]}
	
	# Now we apply the substitution to get a subst-string that
	# will perform the computational parts of the conversion.
	return [regsub -all $RE $title $substitution]

}