This file is indexed.

/usr/share/xul-ext/automatic-save-folder/content/asf_download.js is in xul-ext-automatic-save-folder 1.0.4-3.

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
/* ***** BEGIN LICENSE BLOCK *****
Automatic Save Folder
Copyright (C) 2007-2011 Éric Cassar (Cyan).
			  2009 Ted Gifford - Dynamic variable capturing

    "Automatic Save Folder" is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 2 of the License, or
    (at your option) any later version.

    "Automatic Save Folder" is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with "Automatic Save Folder".  If not, see <http://www.gnu.org/licenses/>.

 * ***** END LICENSE BLOCK ***** */
 var automatic_save_folder = {
		prefManager: Components.classes["@mozilla.org/preferences-service;1"]
                        .getService(Components.interfaces.nsIPrefBranch),
						
		appInfo: Components.classes["@mozilla.org/xre/app-info;1"]
                        .getService(Components.interfaces.nsIXULAppInfo),
						
		versionChecker: Components.classes["@mozilla.org/xpcom/version-comparator;1"]
                               .getService(Components.interfaces.nsIVersionComparator),
				
		firefoxversion : "",
		systemslash: "",
		logtoconsole: true,
		inPrivateBrowsing: false,
		matching_filters: new Array(),
		matching_folders: new Array(),
		current_uri: "", // FF7.0.1 use a new per uri saved folder.
		current_uri_lastpath: "", // last stored path for that uri
		
	main: function () {


		// Setting private variables usable in this function
		var prefManager = automatic_save_folder.prefManager;
		var versionChecker = automatic_save_folder.versionChecker;
		var appInfo = automatic_save_folder.appInfo;
		this.checkFirefoxVersion();
		
		// Check if the user is in PrivateBrowsing mode.
		if (this.firefoxversion >= 3)
		{
			try
			{
				var pbs = Components.classes["@mozilla.org/privatebrowsing;1"]
									.getService(Components.interfaces.nsIPrivateBrowsingService);
				this.inPrivateBrowsing = pbs.privateBrowsingEnabled;
			}
			catch (e) { // nsIPrivateBrowsingService not working on FF2 and 3.0
			}
		}
		
		// Enable Private Browsing support with filepicker - Thanks to Ehsan Akhgari at http://ehsanakhgari.org/
		if (this.versionChecker.compare(this.appInfo.version, "3.5") >= 0)
		{
			Components.utils.import("resource://gre/modules/DownloadLastDir.jsm");
		}
		
		// Check if there is any filter in list
		var nbrfilters = 	prefManager.getIntPref("extensions.asf.filtersNumber");
		
		
		// load the domain and the filename of the saved file (copy the data from the firefox saving window)
		var tBrowser = Components.classes["@mozilla.org/appshell/window-mediator;1"]
				 .getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser").getBrowser();
		var tabLocation = tBrowser.mCurrentTab.linkedBrowser.contentDocument.location;
		var filename = 			document.getElementById("location").value ;
		var domain = 			document.getElementById("source").value ;
		var	domainWithoutProtocol = domain.replace(/^.*:\/\//g,'');  // remove the protocol name from the domain
		var fileURL = 			document.getElementById("source").getAttribute("tooltiptext");
		var fileURLAndFilename= document.getElementById("source").getAttribute("tooltiptext") + filename;
		var currentDomain, currentURL = "";
		try
		{
			currentDomain = 	tabLocation.protocol + "//" + tabLocation.host; // look for the current website URL in the DOM.
			currentURL = 		tabLocation.href; // look for the current website URL in the DOM.
		}
		catch (e) // if there is no data (The tab is closed or it's a script redirection), use the file's data.
		{
			currentDomain = domain;
			currentURL = fileURL;
		}
		if (this.firefoxversion >= 7.01) 
		{
			this.current_uri = currentDomain.replace(/^.*:\/\//g,'');
			if (this.current_uri == "") this.current_uri = tabLocation.href; // fix website opening a new about:blank page when clicking on a download link, and that tab is not auto-closing.
			
			// read lastpath for that uri
			var uri = this.current_uri;
			var file = gDownloadLastDir.getFile(uri);
			if (file != null) this.current_uri_lastpath = file.path;
		}
		
		var domain_testOrder = prefManager.getCharPref("extensions.asf.domainTestOrder");
		if (this.trim(domain_testOrder) == "") domain_testOrder = "1,5";
		var message = "These data will be used to verify the filters :\nFilename:\t\t"+filename+"\nDomain test order:\t"+domain_testOrder+"\n1 - File's domain:\t"+domain+"\n2 - File's URL:\t\t"+fileURL+"\n3 - Full file's URL:\t"+fileURLAndFilename+"\n4 - Tab's domain:\t"+currentDomain+"\n5 - Tab's URL:\t\t"+currentURL;
		if (!this.inPrivateBrowsing) this.console_print(message);
		// debug : show the full downloaded link  http://abc.xyz/def/file.ext
		// Can use this new function to get free from the need of the download window.
		//var url = dialog.mLauncher.source.spec;
		//alert(url);
		
		
		
		
		// load prefmanager data
		var savetype = 				prefManager.getIntPref("extensions.asf.savetype");
		var lastdir = 				prefManager.getBoolPref("extensions.asf.lastdir");	     // for Firefox2 : set save as Ctrl+S too
		var defaultfolder = 		this.loadUnicodeString("extensions.asf.defaultfolder");
		var keeptemp = 				prefManager.getBoolPref("extensions.asf.keeptemp");
		var tempdomain = 			this.loadUnicodeString("extensions.asf.tempdomain");      // hosted domain from last saved file
		var variable_mode = 		prefManager.getBoolPref("extensions.asf.variablemode");  // enable Variables in folder creation (dynamic Folders)
		var dialogaccept = 			prefManager.getBoolPref("extensions.asf.dialogaccept");
		var dialogacceptFiltered = 	prefManager.getBoolPref("extensions.asf.dialogacceptFiltered");
		var suggestAllPossibleFolders = prefManager.getBoolPref("extensions.asf.suggestAllPossibleFolders");
		
		// If variable/Dynamic folders mode is ON, let's replace the variables to create the new defaultfolder
		if (variable_mode == true)
		{
			defaultfolder = this.createfolder(defaultfolder);
		}
		
		// set the last saved path into asf.lastpath
		if (this.firefoxversion >= "3")   // take the download.lastDir if it's FF3
		{
			var folder = this.loadUnicodeString("browser.download.lastDir");
		}
		else // else if it's not FF3 (it's 1.5 or 2), read Download.dir
		{
			var folder = this.loadUnicodeString("browser.download.dir");
		}
		this.saveUnicodeString("extensions.asf.lastpath", folder); // And set it to asf.lastpath to be compared later with the new path the filters will set to lastDir (or dir)
		
		
		// load filters data from prefmanager into filters[]
		// filters[filternumber][label]
		var filters = new Array();
		for ( var i = 0 ; i < nbrfilters ; i++)
		{
			var dom = this.loadUnicodeString("extensions.asf.filters"+ i +".domain");
			var fil = this.loadUnicodeString("extensions.asf.filters"+ i +".filename");
			var fol = this.loadUnicodeString("extensions.asf.filters"+ i +".folder");
			var act = prefManager.getBoolPref("extensions.asf.filters"+ i +".active");
			var dom_reg = prefManager.getBoolPref("extensions.asf.filters"+ i +".domain_regexp");
			var fil_reg = prefManager.getBoolPref("extensions.asf.filters"+ i +".filename_regexp");
			filters[i] = [dom, fil, fol, act, dom_reg, fil_reg];
		}
		
		
		//
		// Start checking the filters with the downloaded file
		//
		var idx = -1 ;
		var dom_regexp = false;
		var file_regexp = false;
		while(this.matching_filters.length) this.matching_filters.pop(); // reset the matching filters array
		for ( var i = 0 ; i < filters.length ; i++)
		{
			if (filters[i][3] == true)  // if not temporary deactivated
			{
				dom_regexp = false ; // reset the matching string for the "for" loop
				file_regexp = false ; // same as above
			// Check the domain
				var domain_testOrder = prefManager.getCharPref("extensions.asf.domainTestOrder");
				if (this.trim(domain_testOrder) == "") domain_testOrder = "1,5";
				domain_testOrder = domain_testOrder.split(/,/);
				
				for ( var j = 0 ; j < domain_testOrder.length ; j++)
				{
					switch (this.trim(domain_testOrder[j])) 
					{
						case "1":
							dom_regexp = this.test_regexp(filters[i][0], domain, i, "domain");
							if (dom_regexp && this.logtoconsole && !this.inPrivateBrowsing) this.console_print("Filter "+i+" matched domain type : 1");
							break;
						case "2":
							dom_regexp = this.test_regexp(filters[i][0], fileURL, i, "domain");
							if (dom_regexp && this.logtoconsole && !this.inPrivateBrowsing) this.console_print("Filter "+i+" matched domain type : 2");
							break;
						case "3":
							dom_regexp = this.test_regexp(filters[i][0], fileURLAndFilename, i, "domain");
							if (dom_regexp && this.logtoconsole && !this.inPrivateBrowsing) this.console_print("Filter "+i+" matched domain type : 3");
							break;
						case "4":
							dom_regexp = this.test_regexp(filters[i][0], currentDomain, i, "domain");
							if (dom_regexp && this.logtoconsole && !this.inPrivateBrowsing) this.console_print("Filter "+i+" matched domain type : 4");
							break;
						case "5":
							dom_regexp = this.test_regexp(filters[i][0], currentURL, i, "domain");
							if (dom_regexp && this.logtoconsole && !this.inPrivateBrowsing) this.console_print("Filter "+i+" matched domain type : 5");
						default:
					}
					
					if (dom_regexp) break;
				}
				
			// Check the filename
				file_regexp = this.test_regexp(filters[i][1], filename, i, "filename"); // Filename
				
				// debug
				// alert ("i = "+i+"\n domain match = "+dom_regexp+"\n file match = "+file_regexp);
				if (dom_regexp && file_regexp)
				{
					idx = i;
					this.matching_filters.push(idx); // add the matching filter to the array
					if (this.logtoconsole && !this.inPrivateBrowsing)  this.console_print("Filter "+idx+" is matching both domain and filename.\nDomain:\t\t"+filters[i][0]+"\nFilename:\t"+filters[i][1]+"\nFolder:\t\t"+filters[i][2]);
					if (suggestAllPossibleFolders == false) break;
				}
			}
		} // end filters loop
		
		if (idx < 0) // if no filters matched
		{
			if (this.logtoconsole && !this.inPrivateBrowsing)  this.console_print("No filter matched both domain and filename. These data will be used instead :\nFolder:\t\t"+this.loadUnicodeString("extensions.asf.defaultfolder")+"\n%asf_d%:\t"+domainWithoutProtocol+"\n%asf_f%:\t"+filename);
			
			if(savetype == 1)  // and folder is set to user choice
			{
				if ( (keeptemp == false) || ((keeptemp == true) && ( tempdomain != domain )) ) // and, if [same domain not checked] OR [ if same domain (keeptemp) is checked and domain not same as previous one]
				{	// then change the destination folder to user choice
					this.set_savepath(defaultfolder);
				}
				else  // else, if domain is the same as the last, and the user checked "use the same folder if same domain"
				{
					if (this.firefoxversion >= "3")
					{
						var lastpath = this.loadUnicodeString("browser.download.lastDir");
					}
					if (this.firefoxversion == "2")
					{
						var lastpath = this.loadUnicodeString("browser.download.dir");
					}
					
					if (lastpath == "") // if no path is returned (first time using lastDir, or the user reseted the content manually in about:config)
					{
						lastpath = defaultfolder;
					}
					this.set_savepath(lastpath);
				}
			}
			else // else, if savetype == 0  (folder is set to last folder)
			{
				if (this.firefoxversion >= "3")
				{
					var lastpath = this.loadUnicodeString("browser.download.lastDir");
				}
				if (this.firefoxversion == "2")
				{
					var lastpath = this.loadUnicodeString("browser.download.dir");
				}
				
				if (lastpath == "") // if no path is returned (first time using lastDir, or the user reseted the content manually in about:config)
				{
					lastpath = defaultfolder;
				}
				if (this.firefoxversion >= 7.01 && this.prefManager.getBoolPref("extensions.asf.useSiteBySiteSavePath") == true)
				{
					lastpath = gDownloadLastDir.getFile(this.current_uri).path;
				}
				this.set_savepath(lastpath);
			}
		}
		else // if a filter is found
		{
			for (var i = 0; i < this.matching_filters.length ; i++)
			{
				var idx = this.matching_filters[i];
				var folder = filters[idx][2];
				
				// If Advanced mode is ON, let's check the variables and create the folder
				if (variable_mode == true)
				{
					folder = this.createfolder(folder, idx);
				}
				
				this.matching_folders[i] = folder;
			}
			
			this.set_savepath(this.matching_folders[0]); // set the default folder to the first matching filter
		}
		
		// in every case, set the new file hosted domain to tempdomain if not in private browsing
		if (!this.inPrivateBrowsing)
		{
			this.saveUnicodeString("extensions.asf.tempdomain", domain);
		}
		
		
		// Automatic saving when clicking on a link. The save dialog still flash onscreen very quickly.
		if (dialogacceptFiltered && idx < 0) dialogaccept = false; // no filter matched, do not autoaccept the dialog
		if (dialogaccept)
		{
			// select "Save file" automatically
			if (this.prefManager.getBoolPref("extensions.asf.dialogForceRadio"))
			{
				var radioSavemode = document.getElementById("mode");
				var forceRadioTo = this.prefManager.getCharPref("extensions.asf.dialogForceRadioTo");
				var dta_ASFtoDTA_isActive = this.prefManager.getBoolPref("extensions.asf.dta_ASFtoDTA_isActive");
				if (!this.DownThemAll_isEnabled() && (forceRadioTo == "downthemall" || forceRadioTo == "turbodta")) forceRadioTo = "save"; // default to "Save File" if DTA is uninstalled.
				if (this.DownThemAll_isEnabled() && (!dta_ASFtoDTA_isActive) && (document.getElementById("tdta").hidden == true) && (forceRadioTo == "turbodta")) forceRadioTo = "downthemall"; // default to "DownThemAll" if DTA is installed but extension.dta.directory is empty.
				radioSavemode.selectedItem = document.getElementById(forceRadioTo);
				//alert(document.getElementById("turbodta").selected);
			}
			
			if (this.DownThemAll_isEnabled() && (document.getElementById("downthemall").selected || document.getElementById("turbodta").selected))
			{
				if (typeof (DTA_SaveAs) != "undefined") // dTa 1.x
				{
					DTA_SaveAs.dialogAccepted();
				}
				else // dTa 2.x
				{
					window.close();
					this.DTA_acceptDownload(document.getElementById("turbodta").selected);
				}
			}
			else
			{
				window.close();
				return dialog.onOK();
			}
		}
		else
		{
			// show or hide the asf option on saving window
			this.show_dloptions();
			this.check_uCTOption(true);
			
			var radioSavemode = document.getElementById("mode");
			radioSavemode.addEventListener(
			"command",		// After a save mode change (save, open, etc.)
			function(){ automatic_save_folder.check_uCTOption(); },  // show/hide and enable/disable ASF.
			false
			);
		}
		
	return false;
	},
	
	
	set_savepath: function(path) {
		var folderList = this.prefManager.getIntPref("browser.download.folderList");
		var lastdir = this.prefManager.getBoolPref("extensions.asf.lastdir");	     // for Firefox2 : set save as Ctrl+S too		
		var directory = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);		
		
		// Check if the user use the "do not show file explorer" to automatically save to "desktop" or "downloads" and force the suggested path to those folders instead of filtered path
		if ( (folderList == 0) || (folderList == 1) )
		{
			var desk = Components.classes["@mozilla.org/file/directory_service;1"]
								.getService(Components.interfaces.nsIProperties)
								.get("Desk", Components.interfaces.nsILocalFile);
			directory = desk;
			if (this.firefoxversion >= 3)
			{
				var dnldMgr = Components.classes["@mozilla.org/download-manager;1"]
									.getService(Components.interfaces.nsIDownloadManager);
				var supportDownloadLabel = !dnldMgr.defaultDownloadsDirectory.equals(desk);
				
				if ( (folderList == 0) || (folderList == 1 && !supportDownloadLabel) ) // if desktop or if OS doesn't support default Download dir
				{
					directory = desk;
				}
				if (folderList == 1 && supportDownloadLabel) // default Downloads folder
				{
					directory.initWithPath(dnldMgr.defaultDownloadsDirectory.path);
				}
			}
		}
		else if ( (folderList == 2) && (!path) )   // set to filters but no path is define (either no default folder is set, or first time using 'folderList=2' )
		{
			directory = Components.classes["@mozilla.org/file/directory_service;1"]
								.getService(Components.interfaces.nsIProperties)
								.get("Desk", Components.interfaces.nsILocalFile);
		}
		else
		{
			directory.initWithPath(path);
		}
		
		if (this.firefoxversion == 2)
		{
		
			this.saveUnicodeString("browser.download.dir", directory.path);
			if (lastdir)
			this.saveUnicodeString("browser.download.lastDir", directory.path);
		}
		
		if (this.firefoxversion >= 3)
		{
			if (this.inPrivateBrowsing && directory)
			{
				gDownloadLastDir.file = directory;
			}
			else
			{
				this.saveUnicodeString("browser.download.lastDir", directory.path);
				if (folderList == 2)
					this.saveUnicodeString("browser.download.dir", directory.path);
				
				
				// and process DTA if enabled
				if (this.DownThemAll_isEnabled() && this.prefManager.getBoolPref("extensions.asf.dta_ASFtoDTA_isActive"))
				{
					this.DTA_replaceDirectory(directory.path);
					// If process turbo dta too
					this.DTA_setTurboDtaList();
				}
			}
			
		}
		
		if (this.firefoxversion >= 7.01)
		{
			// Firefox 7.0.1 use a new feature to memorize last used folder on a site-by-site basis.
			// Replace the memorized folder for the current website's URI.
			var uri = this.current_uri;
			// var file = gDownloadLastDir.getFile(uri);
			// alert("uri="+uri+"\noldpath ="+file.path+"\nnewpath ="+directory.path);
			gDownloadLastDir.setFile(uri, directory);
		}
	},
	
	
	loadUnicodeString: function (pref_place) {
		try
		{
			return this.prefManager.getComplexValue(pref_place, Components.interfaces.nsISupportsString).data;
		}
		catch (e)
		{ }
		return "";
	},
	
	
	saveUnicodeString: function (pref_place,pref_data) {
		var str = Components.classes["@mozilla.org/supports-string;1"]
					.createInstance(Components.interfaces.nsISupportsString);
		str.data = pref_data;
		this.prefManager.setComplexValue(pref_place, Components.interfaces.nsISupportsString, str);
	},
	
	
	createfolder: function (path, idx) {
		
		if (!path) return false;
		if (this.trim(path).length==0) return false;
		
		var Date_asf = Date;
		Date_asf.prototype.getWeek = function() // Add the getWeek() function do date()
		{
			var onejan = new Date(this.getFullYear(),0,1);
			var week = Math.ceil((((this - onejan) / 86400000) + onejan.getDay()-1)/7);
			if (onejan.getDay() > 4) week--;  // if the first week does not contain a thrusday, it's not the first week (and return as week 0)
			return week;
		}
		var objdate = new Date_asf();
		
		// make the array with the month's name in the stringbundle of the locale language path.
		
		var stringbundle = Components.classes['@mozilla.org/intl/stringbundle;1'].
											getService(Components.interfaces.nsIStringBundleService).
                           createBundle('chrome://asf/locale/asf.properties');
		
		var fullmonthname = new Array();
		var abbrmonthname = new Array();
		var fulldayname = new Array();
		var abbrdayname = new Array();
		for (var i = 1 ; i<= 12 ; i++)
		{
			fullmonthname[i-1] = stringbundle.GetStringFromName("month"+i+"_full");
			abbrmonthname[i-1] = stringbundle.GetStringFromName("month"+i+"_abbr");
		}
		for (var i = 0 ; i<= 6 ; i++)
		{
			fulldayname[i] = stringbundle.GetStringFromName("day"+i+"_full");
			abbrdayname[i] = stringbundle.GetStringFromName("day"+i+"_abbr");
		}
		
		
		const ZERO = "0";  // leading zero
		
		// load the domain and the filename of the saved file
		var tBrowser = Components.classes["@mozilla.org/appshell/window-mediator;1"]
				 .getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser").getBrowser();
		var tabLocation = tBrowser.mCurrentTab.linkedBrowser.contentDocument.location;
		var filename =			document.getElementById("location").value ;
		var file_name =			filename.replace (/\.(?!.*\.).*$/i, "");  // Trim from the last dot to the end of the file = remove extension
		var extension =			filename.match(/([^\.]*)$/i);  // take out the extension (anything not containing a dot, with an ending line)
		var domain =			document.getElementById("source").value ;
		var	domainWithoutProtocol = domain.replace(/^.*:\/\//g,'');  // remove the protocol name from the domain
		var fileURL =			document.getElementById("source").getAttribute("tooltiptext");
		var fileURLAndFilename= document.getElementById("source").getAttribute("tooltiptext") + filename;
		var currentDomain, currentURL = "";
		try 
		{
			currentDomain = 	tabLocation.protocol + "//" + tabLocation.host; // look for the current website URL in the DOM.
			currentURL = 		tabLocation.href; // look for the current website URL in the DOM.
		}
		catch (e) // if there is no data (The tab is closed or it's a script redirection), use the file's data.
		{
			currentDomain = domain;
			currentURL = fileURL;
		}
		
		// check the filter's data
		var asf_domain = "";
		var asf_filename = "";
		if (idx >= 0)  // If a filter match
		{
			asf_domain = this.loadUnicodeString("extensions.asf.filters"+ idx +".domain");
			asf_filename = this.loadUnicodeString("extensions.asf.filters"+ idx +".filename");
		}
		else // no filter is found, use actual Domain and filename without extension
		{
			asf_domain = domainWithoutProtocol;
			asf_filename = filename;
		}
		
		
		// Check the domain
		var used_domain_string = "";
		var dom_regexp = false;
		var domain_testOrder = this.prefManager.getCharPref("extensions.asf.domainTestOrder");
		if (this.trim(domain_testOrder) == "") domain_testOrder = "1,5";
		domain_testOrder = domain_testOrder.split(/,/);
		
		for ( var j = 0 ; j < domain_testOrder.length ; j++)
		{
			switch (this.trim(domain_testOrder[j])) 
			{
				case "1":
					dom_regexp = this.test_regexp(asf_domain, domain, idx, "domain");
					used_domain_string = domain;
					break;
				case "2":
					dom_regexp = this.test_regexp(asf_domain, fileURL, idx, "domain");
					used_domain_string = fileURL;
					break;
				case "3":
					dom_regexp = this.test_regexp(asf_domain, fileURLAndFilename, idx, "domain");
					used_domain_string = fileURLAndFilename;
					break;
				case "4":
					dom_regexp = this.test_regexp(asf_domain, currentDomain, idx, "domain");
					used_domain_string = currentDomain;
					break;
				case "5":
					dom_regexp = this.test_regexp(asf_domain, currentURL, idx, "domain");
					used_domain_string = currentURL;
				default:
			}
			
			if (dom_regexp) break;
		}
		
		// check the filename
		var file_regexp = this.test_regexp(asf_filename, filename, idx, "filename");
		
// Ted Gifford, start block
		// String capture in filename with $<1-9>f
		try {
		//alert(file_regexp.length);
			if (file_regexp.length > 1)
			{
				//alert('munging path: ' + path);
				for (var replace_index = 1; replace_index < file_regexp.length; ++replace_index)
						path = path.replace("$"+replace_index+"f", file_regexp[replace_index]);
				//alert('munged path: ' + path);
			}
		} catch (e) {alert(e);}
		// String capture in domain with $<1-9>d
		try {
		//alert(dom_regexp.length);
			if (dom_regexp.length > 1)
			{
				//alert('munging path: ' + path);
				for (var replace_index = 1; replace_index < dom_regexp.length; ++replace_index)
						path = path.replace("$"+replace_index+"d", dom_regexp[replace_index]);
				//alert('munged path: ' + path);
			}
		} catch (e) {alert(e);}
// Ted Gifford, end block
		
		
		// read the userpref to define if regexp is case insensitive (default true)
		var param = "";
		var regexp_caseinsensitive = this.prefManager.getBoolPref("extensions.asf.regexp_caseinsensitive");
		if (regexp_caseinsensitive) param = "i";
		
		// Check if asf_rd is present and process     asf_rd = Regexp the domain
		if (path.search("%asf_rd%") != -1)
		{
			// extract the filter part
			var matches = path.match(/%asf_rd%.*?%asf_rd%/g);        // matches is an array
			if (matches != null)
			{
				var datareg = "";
				var result = new Array();
				var matchreplace = new Array();
				for (var i = 0, len = matches.length; i < len; i++)
				{
					datareg = matches[i].replace(/%asf_rd%/g, '');  // remove the %asf_rf% to keep only the regexp
					datareg = new RegExp(datareg, param);			//  create the regexp
					//alert("reg="+datareg);
					result = used_domain_string.match(datareg);    // Check it on the domain type set by the user
					
					if (result == null)
					{
						matchreplace[i] = ""; // if no result, replace with nothing instead of null
					}
					else
					{
						matchreplace[i] = result[0];
					}
					//alert("matchreplace["+i+"]="+matchreplace[i]);
				}
				for (var i = 0, len = matches.length; i < len; i++)
				{
					path = path.replace(matches[i], matchreplace[i]);  // replace each variable in the path
				}
			}
		}
		
		
		// Check if asf_rf is present and process     asf_rf = Regexp the filename
		if (path.search("%asf_rf%") != -1 )
		{
			// extract the filter part
			var matches = path.match(/%asf_rf%.*?%asf_rf%/g);        // matches is an array
			if (matches != null)
			{
				var datareg = "";
				var result = new Array();
				var matchreplace = new Array();
				for (var i = 0, len = matches.length; i < len; i++)
				{
					datareg = matches[i].replace(/%asf_rf%/g, '');  // remove the %asf_rf% to keep only the regexp
					datareg = new RegExp(datareg, param);			//  create the regexp
					//alert("reg="+datareg);
					result = filename.match(datareg);    // Check it
					
					if (result == null)
					{
						matchreplace[i] = ""; // if no result, replace with nothing instead of null
					}
					else
					{
						matchreplace[i] = result[0];
					}
					//alert("matchreplace["+i+"]="+matchreplace[i]);
				}
				for (var i = 0, len = matches.length; i < len; i++)
				{
					path = path.replace(matches[i], matchreplace[i]);  // replace each variable in the path
				}
			}
		}
		
		
		
		// remove special characters from filters :
		// forbidden on windows  \ / : * ? " < > |
		if (navigator.appVersion.indexOf("Win")!=-1) // = Windows
		{
			asf_domain = asf_domain.replace(/[\/\:\*\?\"\<\>\|]/g,'');
			asf_filename = asf_filename.replace(/[\/\:\*\?\"\<\>\|]/g,'');
			file_name = file_name.replace(/[\/\:\*\?\"\<\>\|]/g,'');
			path = path.replace(/[\/\*\?\"\<\>\|]/g,'');
		}
		else  // MacOS and linux, replace only  / :
		{
			asf_domain = asf_domain.replace(/[\/\:]/g,'');
			asf_filename = asf_filename.replace(/[\/\:]/g,'');
			file_name = file_name.replace(/[\/\:]/g,'');
		}
		
		// replace the string here		// Year
			path = path					.replace(/%Y%/g, objdate.getFullYear())  // full year format = 2009
										.replace(/%y%/g, ((objdate.getYear()-100) <10) ? (ZERO + (objdate.getYear()-100)) : objdate.getYear()-100)  // year in YY format : 08, 09, 10
									//	.replace(/%<to define>/g, objdate.getYear()-100)  // 8, 9, 10, (no leading 0)
										// Month
										.replace(/%m%/g, ((objdate.getMonth()+1) <10) ? (ZERO + (objdate.getMonth()+1)) : objdate.getMonth()+1)  // = number of the month : 01 to 12
										.replace(/%n%/g, objdate.getMonth()+1)  // 8, 9, 10, (no leading 0)
										.replace(/%F%/g, fullmonthname[objdate.getMonth()])  // full month name
										.replace(/%M%/g, abbrmonthname[objdate.getMonth()])  // abbreviated month name
										// Week
										.replace(/%W%/g, ((objdate.getWeek()) <10) ? (ZERO + (objdate.getWeek())) : objdate.getWeek())  // = number of the week : 01 to 54
										.replace(/%w%/g, objdate.getDay())  // = Day of the week, from 0 (sunday) to 6 (saturday)
										.replace(/%l%/g, fulldayname[objdate.getDay()])  // = Full day name
										.replace(/%D%/g, abbrdayname[objdate.getDay()])  // = Abbreviated day name
										// Day
										.replace(/%d%/g, ((objdate.getDate()) <10) ? (ZERO + (objdate.getDate())) : objdate.getDate())  // = number of the day : 01 to 31
										.replace(/%j%/g, objdate.getDate())  // = number of the day  1 to 31 (no leading 0)
										// ASF
										.replace(/%asf_D%/g, domainWithoutProtocol)       // downloaded File's domain
										.replace(/%asf_F%/g, filename)     // downloaded File's filename with extension
										.replace(/%asf_Fx%/g, file_name)   // downloaded File's filename without extension
										.replace(/%asf_d%/g, asf_domain)   // matching filter's Domain (without special chars used by regexp)
										.replace(/%asf_f%/g, asf_filename) // mathching filter's filename (without special chars used by regexp)
										.replace(/%asf_x%/g, extension[0]);    // match the filename extension (without the dot)
		// debug
		// alert (path);
		return path;
		
// Canceled the folder creation script, so the folder will not be created if the user cancel the download
// Firefox will create it automatically when accepting the download... under windows XP and Linux Ubuntu at least (not tested under Vista, MacOS, or any other operating system)
/*
		var directory = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
		
		directory.initWithPath(path);
		if (directory.exists())
		{
			return path;
		}
		else  // if it doesn't exist, create it
		{
			if( !directory.exists() || !directory.isDirectory() )
			{
				directory.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0777);
			}
			return path;
		}
*/
	},
	
	
	trim: function (string) {
		return string.replace(/(^\s*)|(\s*$)/g,'');
	},
	
	
	show_dloptions: function () {
		// read asf/content/info_save_ff2-3.txt for differences between Firefox 2 and Firefox 3 saving preferences.
		var asf_dloptions = document.getElementById('asf_dloptions');
		var asf_radiogroup_pathselect = document.getElementById('asf_radiogroup_pathselect');
		var asf_savefolder = document.getElementById('asf_savefolder');
		var asf_folder_list = document.getElementById('asf_folder_list');
		var asf_viewdloption = this.prefManager.getBoolPref("extensions.asf.viewdloption");
		var asf_viewdloptionType = this.prefManager.getIntPref("extensions.asf.viewdloptionType");
		var asf_viewpathselect = this.prefManager.getBoolPref("extensions.asf.viewpathselect");
		var useDownloadDir = this.prefManager.getBoolPref("browser.download.useDownloadDir");
		var folderList = this.prefManager.getIntPref("browser.download.folderList");
		
		var folder = "";
		if (this.firefoxversion == 2) folder = this.loadUnicodeString("browser.download.dir");
		if (this.firefoxversion == 2) // set the show suggested path to "..." because I didn't find how to read the default donloads folder path. (See function Set_savepath(); )
		{
			if (useDownloadDir && folderList == 0)  // desktop
			{
				folder = "...";
			}
			if (useDownloadDir && folderList == 1) // default Downloads folder
			{
				folder = "...";
			}
		}
		if (this.firefoxversion >= 3)
		{
			if (this.inPrivateBrowsing && gDownloadLastDir.file)
			{
				folder = gDownloadLastDir.file.path;
			}
			else
			{
				folder = this.loadUnicodeString("browser.download.lastDir");
			}
			
		}
		
		
		
		// check the lastpath, if different than current folder, then print radio choice to user
		// so he can choose from found filters, or last used path.
		var lastpath = this.loadUnicodeString("extensions.asf.lastpath");
		var asf_lastpath = document.getElementById('asf_lastpath');
		asf_lastpath.label = lastpath;
		
		if ( (lastpath == folder) || (lastpath == "") || (this.indexInArray(this.matching_folders, lastpath) > -1))  // if same or empty (first time using ASF), or already present from a filter's path, do not show radio for lastpath choice
		{
			asf_lastpath.hidden = true;
		}
		else  // else, if last path is different than folder found in filter, show a choice
		{
			asf_lastpath.hidden = false;
		}
		
		// Firefox 7.0.1+ : Check the current uri lastpath, if not in the available paths then print another radio choice to the user
		var asf_currentURI_lastpath = document.getElementById('asf_currentURI_lastpath');
		asf_currentURI_lastpath.hidden = true;
		if ((this.firefoxversion >= 7.01) && (this.current_uri_lastpath != ""))
		{
			asf_currentURI_lastpath.label = this.current_uri_lastpath;
			if ( (this.indexInArray(this.matching_folders, this.current_uri_lastpath) == -1) && (lastpath != this.current_uri_lastpath) ) // check if it's already listed 
			{
				asf_currentURI_lastpath.hidden = false;
			}
		}
		
		//set the text to be written on the Radio comment
		if (this.matching_filters.length >= 1)
		{
			for (var i=asf_savefolder.childNodes.length-1 ; i>=0 ; i--)
			{
				asf_savefolder.removeChild(asf_savefolder.childNodes[i]);
			}
			for (var i = 0; i < this.matching_filters.length; i++)
			{
				var new_radio = document.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'radio');
				new_radio.setAttribute("id", "asf_savefolder_"+i);
				new_radio.setAttribute("value", i);
				new_radio.setAttribute("width", "280");
				new_radio.setAttribute("crop", "center");
				new_radio.setAttribute("label", this.matching_folders[i]);
				new_radio.setAttribute("class", "small-indent");
				new_radio.setAttribute("oncommand", "automatic_save_folder.asf_toggle_savepath(this);");
				asf_savefolder.appendChild(new_radio);
			}
		}
		else
		{
			if (asf_savefolder.childNodes.length == 0)
			{
				var new_radio = document.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'radio');
				new_radio.setAttribute("id", "asf_savefolder_0");
				new_radio.setAttribute("value", 0);
				new_radio.setAttribute("width", "280");
				new_radio.setAttribute("crop", "center");
				new_radio.setAttribute("label", this.matching_folders[0]);
				new_radio.setAttribute("class", "small-indent");
				new_radio.setAttribute("oncommand", "automatic_save_folder.asf_toggle_savepath(this);");
				asf_savefolder.appendChild(new_radio);
			}
			
			document.getElementById('asf_savefolder_0').label = folder;
		}
		
		// Force check the first radio choice (needed on linux + ff2.x) (linux has blank radio choices on loading, this is only visual, it doesn't affect anything here, the value are set to the new path by default until the user change the radio choice)
		var asf_radio_savepath = document.getElementById('asf_radio_savepath');
		asf_radio_savepath.value = 0;
		
		
		//now, if the user checked the option to view asf on saving window, set it to visible
		if(asf_viewdloption == true)
		{
			if(asf_viewdloptionType == 0) asf_dloptions.style.visibility = "visible";
			
			if(asf_viewdloptionType == 1)
			{
				asf_dloptions.style.visibility = "visible";
				document.getElementById('asf_dloptions_content').style.visibility = "collapse";
			}
			
			
			
			//and last, if the user checked the option to view the path list on saving window, set it to visible
			if(asf_viewpathselect == true)
			{
				this.read_all_filterpath();
				asf_radiogroup_pathselect.style.visibility = "visible";
			}
			else
			{
				asf_radiogroup_pathselect.style.visibility = "collapse";
			}
			
			// Check if the user use the "do not show file explorer" to automatically save to "desktop" or "downloads" and force the suggested path to those folders instead of found filters
			if((useDownloadDir == true) && (folderList != 2)) // if set to desktop or Download
			{
				asf_radio_savepath.disabled = true;
				asf_radiogroup_pathselect.disabled = true;
				asf_folder_list.disabled = true;
			}
			else
			{
				asf_radio_savepath.disabled = false;
				asf_radiogroup_pathselect.disabled = false;
				asf_folder_list.disabled = false;
			}
			
			
			// Set the max width to the size of the screen minus 200px. Added for Mac OSX users with long path choice.
			// alert("first screen : " + screen.width + "x" + screen.height);
			asf_dloptions.style.maxWidth = screen.width -200 +"px";
		}
	},
	
	
	toggle_dloptionsContent: function(){
		var asf_dloptions_content = document.getElementById('asf_dloptions_content').style.visibility;
		var asf_viewpathselect = this.prefManager.getBoolPref("extensions.asf.viewpathselect");
		
		document.getElementById('asf_dloptions_content').style.visibility = (asf_dloptions_content == "visible" ? "collapse" : "visible");
		if (asf_viewpathselect) // fix for linux (nested box visibility doesn't work)
		{
			document.getElementById('asf_radiogroup_pathselect').style.visibility = (asf_dloptions_content == "visible" ? "collapse" : "visible");
		}
		window.sizeToContent();
	},
	
	
	check_uCTOption: function (FirstTime) {
		// Check if the user change the unkownContentType option (open with, save as, save with a download manager, etc.)
		var save = document.getElementById("save").selected;
		var asf_radio_savepath = document.getElementById('asf_radio_savepath');
		var asf_radiogroup_pathselect = document.getElementById('asf_radiogroup_pathselect');
		var asf_folder_list = document.getElementById('asf_folder_list');
		var asf_viewdloption = this.prefManager.getBoolPref("extensions.asf.viewdloption");
		var asf_viewdloptionType = this.prefManager.getIntPref("extensions.asf.viewdloptionType");
		var asf_viewpathselect = this.prefManager.getBoolPref("extensions.asf.viewpathselect");
		var dTa = false;
		if (this.DownThemAll_isEnabled) // enable ASF box if dTa is selected and sending folder to dTa is enabled.
		{
			dTa = this.prefManager.getBoolPref("extensions.asf.dta_ASFtoDTA_isActive") && (document.getElementById("downthemall").selected || document.getElementById("turbodta").selected);
		}
		
		// Workaround for bug 439323 (if call when not needed, dosen't work anymore)
		// https://bugzilla.mozilla.org/show_bug.cgi?id=439323
		var initialState = document.getElementById('asf_dloptions_content').style.visibility ;
		
		if (asf_viewdloption)
		{
			if(save || dTa) // if set to "save the file"
			{
				asf_radio_savepath.disabled = false;
				asf_radiogroup_pathselect.disabled = false;
				asf_folder_list.disabled = false;
				if ((asf_viewdloptionType == 2) || (asf_viewdloptionType == 3))
				{
					document.getElementById('asf_dloptions').style.visibility = "visible";
					document.getElementById('asf_dloptions_content').style.visibility = "visible";
					if (asf_viewpathselect) // fix for linux (nested box visibility doesn't work)
					{
						document.getElementById('asf_radiogroup_pathselect').style.visibility = "visible";
					}
				}
			}
			else
			{
				asf_radio_savepath.disabled = true;
				asf_radiogroup_pathselect.disabled = true;
				asf_folder_list.disabled = true;
				if (asf_viewdloptionType == 2) // minimize only
				{
					document.getElementById('asf_dloptions').style.visibility = "visible";
					document.getElementById('asf_dloptions_content').style.visibility = "collapse";
					document.getElementById('asf_radiogroup_pathselect').style.visibility = "collapse"; // fix for linux (nested box visibility doesn't work)
				}
				if (asf_viewdloptionType == 3)
				{
					document.getElementById('asf_dloptions').style.visibility = "collapse";
					document.getElementById('asf_dloptions_content').style.visibility = "collapse";
					document.getElementById('asf_radiogroup_pathselect').style.visibility = "collapse"; // fix for linux (nested box visibility doesn't work)
				}
			}
			
			if ( (initialState != document.getElementById('asf_dloptions_content').style.visibility) && (FirstTime != true) ) // FirstTime is also a workaround of sizeToContent bug (which is called onLoad uCT)
			{
				window.sizeToContent();
			}
		}
	},
	
	
	indexInArray: function (arr,val){
		val = val.replace(/\\/g,'\\\\');
		var test_regexp = new RegExp("^"+val+"$");
		var data = "";
		for(var i=0;i<arr.length;i++)
		{
			if(test_regexp.test(arr[i])) return i;
		}
		return -1;
	} ,
	
	
	read_all_filterpath: function() {
		var variable_mode = this.prefManager.getBoolPref("extensions.asf.variablemode");
		var list = document.getElementById('asf_folder_list');
		var menupopup = document.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menupopup');
		
		// Check if there is any filter in list
		var nbrfilters = 	this.prefManager.getIntPref("extensions.asf.filtersNumber");
		var path = "";
		
		// Delete active list before repopulating (if editing filter and coming back to saving window)
		for (var i=list.childNodes.length-1 ; i>=0 ; i--)
		{
			list.removeChild(list.childNodes[i]);
		}
		
		// Write each path to the menupopup
		var pathlist = new Array();
		var pathlist_defaultforceontop = this.prefManager.getBoolPref("extensions.asf.pathlist_defaultforceontop");
		var defaultfolder = this.loadUnicodeString("extensions.asf.defaultfolder");
		var j = 0;
		if (pathlist_defaultforceontop)
		{
			if (variable_mode == true) defaultfolder = this.createfolder(defaultfolder);
			var menuitem = document.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menuitem');
			menuitem.setAttribute('label', defaultfolder);
			menuitem.setAttribute('crop', 'center');
			menuitem.setAttribute('value', defaultfolder);
			menupopup.appendChild(menuitem);
		}
		else
		{
			pathlist[0] =  variable_mode == true? this.createfolder(defaultfolder) : defaultfolder;
			j++;
		}
		
		for (var i = 0; i < nbrfilters; i++)
		{
			// read the filter number x
			path = this.loadUnicodeString("extensions.asf.filters"+ i +".folder");
			path = variable_mode == true? this.createfolder(path, i) : path;
			
			if (this.indexInArray(pathlist, path) < 0)
			{ 
				pathlist[j++]= path;
			}
		}
		
		var pathlist_sort_alpha = this.prefManager.getBoolPref("extensions.asf.pathlist_alphasort");
		if (pathlist_sort_alpha) pathlist.sort();
		
		for (var i = 0; i < pathlist.length; i++)
		{
			path = pathlist[i];
			
			var menuitem = document.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menuitem');
			menuitem.setAttribute('label', path);
			menuitem.setAttribute('crop', 'center');
			menuitem.setAttribute('value', path);
			menuitem.setAttribute('oncommand', "automatic_save_folder.asf_select_savepath(this)");
			menupopup.appendChild(menuitem);
		}
		
		// Populate the path list into the menu
		list.appendChild(menupopup);
		list.selectedIndex = 0;
	},
	
	
	asf_toggle_savepath: function (elem) {
		
		var asf_pathselect = document.getElementById('asf_pathselect');
		var userchoice = "";
		if(asf_pathselect.selected == true)
		{
			userchoice = document.getElementById('asf_folder_list').value ;
		}
		else
		{
			userchoice = elem.label;
		}
		
		this.set_savepath(userchoice);
		
	},
	
	
	asf_select_savepath: function () {
	
		// check the third radio choice
		var asf_radio_savepath = document.getElementById('asf_radio_savepath');
		var asf_pathselect = document.getElementById('asf_pathselect');
		asf_radio_savepath.value = 99;
		asf_pathselect.checked;
		
		this.asf_toggle_savepath();
	},
	
	
	test_regexp: function (filter_data, downloaded_data, idx, filter_type) {
	/**
	// filter_data (String) : The filter's content
	// downloaded_data (String) : The downloaded filename or domain informations
	// idx (Int) : Current filter number
	// filter_type (String) : Current filter type, can be "domain" of "filename".
	// Return (Array) : return the result as an Array [downloaded_data [, captured group1 [, ... [, captured group9]]]]
	*/
		// Convert normal filter to regular expression filter.
		var isregexp = false;
		if(idx >= 0)
		{
			if (filter_type == "domain") isregexp = this.prefManager.getBoolPref("extensions.asf.filters"+ idx +".domain_regexp");
			if (filter_type == "filename") isregexp = this.prefManager.getBoolPref("extensions.asf.filters"+ idx +".filename_regexp");
		}
		if (isregexp == false) // replace simple wildcard and special characters with corresponding regexp
		{
			filter_data = filter_data.replace(/\./gi, "\\.")
													.replace(/\*/gi, ".*")
													.replace(/\$/gi, "\\$")
													.replace(/\^/gi, "\\^")
													.replace(/\+/gi, "\\+")
													.replace(/\?/gi, ".")
													.replace(/\|/gi, "\\|")
													.replace(/\[/gi, "\\[")
													.replace(/\//gi, "\\/");
			filter_data = ".*"+filter_data+".*";
		}
		
		// initialize the regular expression search
		var param = (this.prefManager.getBoolPref("extensions.asf.regexp_caseinsensitive") == true ? "i" : "");
		var test = new RegExp(filter_data, param);
		
		// Thanks to Ted Gifford for the regular expression capture.
		var res = downloaded_data.match(test);
		if (res) return res;
		return false;
	},
	
	
	readHiddenPref: function(pref_place, type, ret) {
		if(this.prefManager.getPrefType(pref_place))
		{
			switch (type)
			{
				case "bool": return this.prefManager.getBoolPref(pref_place);
				case "int" : return this.prefManager.getIntPref(pref_place);
				case "char": return this.prefManager.getCharPref(pref_place);
				case "complex": return this.prefManager.getComplexValue(pref_place, Components.interfaces.nsISupportsString).data;
			}
		}
		else
		{
			return ret; // return default value if pref doesn't exist
		}
	},


	checkFirefoxVersion: function() {
		
		if (this.versionChecker.compare(this.appInfo.version, "7.0.1") >= 0)
		{
			this.firefoxversion = "7.01";
		}
		else if (this.versionChecker.compare(this.appInfo.version, "4.0b1") >= 0)
		{
			this.firefoxversion = "4";
		}
		else if(this.versionChecker.compare(this.appInfo.version, "3.0") >= 0) 
		{
			this.firefoxversion = "3";
		}
		else 
		{
			this.firefoxversion = "2";
		}
	},


	DownThemAll_isEnabled: function() {
		// Check for DTA add-on, if enabled return true. 
		
		if (this.firefoxversion >= 4)
		{
			var enabledItems = this.prefManager.getCharPref("extensions.enabledAddons");
		}
		if (this.firefoxversion == 3)
		{
			var enabledItems = this.prefManager.getCharPref("extensions.enabledItems");
		}
		
		var addon_GUUID = "{DDC359D1-844A-42a7-9AA1-88A850A938A8}";
		var DTA = enabledItems.indexOf(addon_GUUID,0);
		if (DTA >= 0) return true;
		
		//Same but for beta, nighly release of dTa
		var addon_GUUID = "dta@downthemall.net";
		var DTA = enabledItems.indexOf(addon_GUUID,0);
		if (DTA >= 0) return true;
		
		return false;
	},


	DTA_replaceDirectory: function(folder) {
		var dta_pathArray = this.DTA_readDirectory();
		var asf_saveFolder = this.DTA_preparePath(folder); // filtered ASF folder
		var dta_sendMethod = this.prefManager.getCharPref("extensions.asf.dta_sendMethod");
		
		if (dta_sendMethod == "replace")
		{
			dta_pathArray.splice(0, 1, asf_saveFolder );
		}
		if (dta_sendMethod == "add")
		{
			if (dta_pathArray[0] == "")
			{
				dta_pathArray.splice(0, 1, asf_saveFolder);
			}
			else
			{
				dta_pathArray.unshift(asf_saveFolder);
			}
		}
		this.DTA_saveDirectory(dta_pathArray);
	},


	DTA_readDirectory: function() {
		var string = this.loadUnicodeString("extensions.dta.directory");
		// readHiddenPref("extensions.dta.directory", "complex", "[]");
		
		string = string.substring(1, string.length);
		string = string.substring(0, string.length -1);
		var directories = string.split(", ");
		for (var i=0; i < directories.length; i++)
		{
			directories[i] = directories[i].substring(1, directories[i].length);
			directories[i] = directories[i].substring(0, directories[i].length -1);
		}
		return directories;
	},


	DTA_saveDirectory: function(data) {
		var history = this.prefManager.getIntPref("extensions.dta.history");
		var dta_directory = data.slice(0,history)
		
		dta_directory = dta_directory.join("\", \"");
		dta_directory = "[\"" + dta_directory + "\"]";
		
		return this.saveUnicodeString("extensions.dta.directory", dta_directory);
	},


	DTA_setTurboDtaList: function () {
		var dta_pathArray = this.DTA_readDirectory();
		var history = this.prefManager.getIntPref("extensions.dta.history");
		var tdtalist = document.getElementById("tdtalist");
		var dta_sendMethod = this.prefManager.getCharPref("extensions.asf.dta_sendMethod");
		//alert(tdtalist._list.menupopup.children[0].boxObject.element.attributes[0].value);
		
		// rename menuitems labels if there is any
		if (typeof (tdtalist._list.menupopup.children[0]) == "object")
		{
			if (dta_sendMethod == "replace")
			{
				if (this.systemslash == "\\") dta_pathArray[0] = dta_pathArray[0].replace(/\\\\/g, "\\");
				tdtalist._list.menupopup.children[0].boxObject.element.attributes[0].value =  dta_pathArray[0];
			}
			
			if (dta_sendMethod == "add")
			{
			
				// If menulist < history size, add a new menuitem
				if (tdtalist._list.menupopup.children.length < history)
				{ 
					var menuitem = document.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menuitem');
					menuitem.setAttribute('label', dta_pathArray[tdtalist._list.menupopup.children.length]);
					menuitem.setAttribute('crop', 'center');
					menuitem.setAttribute('value', dta_pathArray[tdtalist._list.menupopup.children.length]);
					tdtalist._list.menupopup.appendChild(menuitem);
				}
				
				for (var i = 0 ; i < tdtalist._list.menupopup.children.length ; i++)
				{
					if (this.systemslash == "\\") dta_pathArray[i] = dta_pathArray[i].replace(/\\\\/g, "\\");
					tdtalist._list.menupopup.children[i].boxObject.element.attributes[0].value =  dta_pathArray[i];
				}
			}
		}
		else // or create a new menuitem
		{
			var menuitem = document.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menuitem');
			menuitem.setAttribute('label', dta_pathArray[0]);
			menuitem.setAttribute('crop', 'center');
			menuitem.setAttribute('value', dta_pathArray[0]);
			tdtalist._list.menupopup.appendChild(menuitem);
			tdtalist._list.selectedIndex = 0;
			document.getElementById("tdta").hidden = false;
			document.getElementById("turbodta").disabled = false;
		}
	},


	DTA_preparePath: function(path) {
		var _profile = Components.classes["@mozilla.org/file/directory_service;1"]
						.getService(Components.interfaces.nsIProperties)
						.get("ProfD", Components.interfaces.nsIFile);
		this.systemslash = (_profile.path.indexOf('/') != -1) ? '/' : '\\';
		
		var formated_path = this.addFinalSlash(path);
		if (this.systemslash == "\\") formated_path = formated_path.replace(/\\/g, "\\\\");
		return formated_path;
	},


	// from dTa 2.x
	DTA_acceptDownload: function(turbo) {
	// New function used by dTa to save files.
	// Accepting the save dialog auomatically doesn't work when dTa is selected.
	// dTa2.x use an eventListener to detect dialogaccept and send data to dTa.
	// this function is a copy from dTa source
	
		let url = dialog.mLauncher.source;
		let referrer;
		try 
		{
			referrer = dialog.mContext.QueryInterface(Components.interfaces.nsIWebNavigation).currentURI.spec;
		}
		catch(ex)
		{
			referrer = url.spec;
		}
		let ml = DTA.getLinkPrintMetalink(url);
		url = new DTA.URL(ml ? ml : url);
	
		DTA.saveSingleLink(window, turbo, url, referrer, "");
	},


	// Inspired from DTA
	addFinalSlash: function(string) {
		if (string.length == 0)
		{
			return this.systemslash;
		}
		
		if (string[string.length - 1] != this.systemslash)
		{
			return string + this.systemslash;
		}
		return string;
	},


	console_print : function (aMessage) {
		var consoleService = Components.classes["@mozilla.org/consoleservice;1"]
                                 .getService(Components.interfaces.nsIConsoleService);
		consoleService.logStringMessage("Automatic Save Folder : \n" + aMessage);
	},
};

	addEventListener( // Autoload
	"load",			// After OnLoad from overlay_unknownContentType.xul file
	function(){ automatic_save_folder.main(); },  // Run main from automatic_save_folder to check the filters
	false
	);