Upgrade to ExtJS 3.2.2 - Released 06/02/2010
[extjs.git] / examples / image-organizer / SWFUpload / swfupload.js
1 /*!
2  * Ext JS Library 3.2.2
3  * Copyright(c) 2006-2010 Ext JS, Inc.
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com
9  *
10  * mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/,  http://www.vinterwebb.se/
11  *
12  * SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilzén and Mammon Media and is released under the MIT License:
13  * http://www.opensource.org/licenses/mit-license.php
14  *
15  * SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License:
16  * http://www.opensource.org/licenses/mit-license.php
17  *
18  */
19
20
21 /* ******************* */
22 /* Constructor & Init  */
23 /* ******************* */
24 var SWFUpload;
25
26 if (SWFUpload == undefined) {
27         SWFUpload = function (settings) {
28                 this.initSWFUpload(settings);
29         };
30 }
31
32 SWFUpload.prototype.initSWFUpload = function (settings) {
33         try {
34                 this.customSettings = {};       // A container where developers can place their own settings associated with this instance.
35                 this.settings = settings;
36                 this.eventQueue = [];
37                 this.movieName = "SWFUpload_" + SWFUpload.movieCount++;
38                 this.movieElement = null;
39
40
41                 // Setup global control tracking
42                 SWFUpload.instances[this.movieName] = this;
43
44                 // Load the settings.  Load the Flash movie.
45                 this.initSettings();
46                 this.loadFlash();
47                 this.displayDebugInfo();
48         } catch (ex) {
49                 delete SWFUpload.instances[this.movieName];
50                 throw ex;
51         }
52 };
53
54 /* *************** */
55 /* Static Members  */
56 /* *************** */
57 SWFUpload.instances = {};
58 SWFUpload.movieCount = 0;
59 SWFUpload.version = "2.2.0 2009-03-25";
60 SWFUpload.QUEUE_ERROR = {
61         QUEUE_LIMIT_EXCEEDED                    : -100,
62         FILE_EXCEEDS_SIZE_LIMIT                 : -110,
63         ZERO_BYTE_FILE                                  : -120,
64         INVALID_FILETYPE                                : -130
65 };
66 SWFUpload.UPLOAD_ERROR = {
67         HTTP_ERROR                                              : -200,
68         MISSING_UPLOAD_URL                      : -210,
69         IO_ERROR                                                : -220,
70         SECURITY_ERROR                                  : -230,
71         UPLOAD_LIMIT_EXCEEDED                   : -240,
72         UPLOAD_FAILED                                   : -250,
73         SPECIFIED_FILE_ID_NOT_FOUND             : -260,
74         FILE_VALIDATION_FAILED                  : -270,
75         FILE_CANCELLED                                  : -280,
76         UPLOAD_STOPPED                                  : -290
77 };
78 SWFUpload.FILE_STATUS = {
79         QUEUED           : -1,
80         IN_PROGRESS      : -2,
81         ERROR            : -3,
82         COMPLETE         : -4,
83         CANCELLED        : -5
84 };
85 SWFUpload.BUTTON_ACTION = {
86         SELECT_FILE  : -100,
87         SELECT_FILES : -110,
88         START_UPLOAD : -120
89 };
90 SWFUpload.CURSOR = {
91         ARROW : -1,
92         HAND : -2
93 };
94 SWFUpload.WINDOW_MODE = {
95         WINDOW : "window",
96         TRANSPARENT : "transparent",
97         OPAQUE : "opaque"
98 };
99
100 // Private: takes a URL, determines if it is relative and converts to an absolute URL
101 // using the current site. Only processes the URL if it can, otherwise returns the URL untouched
102 SWFUpload.completeURL = function(url) {
103         if (typeof(url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//)) {
104                 return url;
105         }
106         
107         var currentURL = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "");
108         
109         var indexSlash = window.location.pathname.lastIndexOf("/");
110         if (indexSlash <= 0) {
111                 path = "/";
112         } else {
113                 path = window.location.pathname.substr(0, indexSlash) + "/";
114         }
115         
116         return /*currentURL +*/ path + url;
117         
118 };
119
120
121 /* ******************** */
122 /* Instance Members  */
123 /* ******************** */
124
125 // Private: initSettings ensures that all the
126 // settings are set, getting a default value if one was not assigned.
127 SWFUpload.prototype.initSettings = function () {
128         this.ensureDefault = function (settingName, defaultValue) {
129                 this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
130         };
131         
132         // Upload backend settings
133         this.ensureDefault("upload_url", "");
134         this.ensureDefault("preserve_relative_urls", false);
135         this.ensureDefault("file_post_name", "Filedata");
136         this.ensureDefault("post_params", {});
137         this.ensureDefault("use_query_string", false);
138         this.ensureDefault("requeue_on_error", false);
139         this.ensureDefault("http_success", []);
140         this.ensureDefault("assume_success_timeout", 0);
141         
142         // File Settings
143         this.ensureDefault("file_types", "*.*");
144         this.ensureDefault("file_types_description", "All Files");
145         this.ensureDefault("file_size_limit", 0);       // Default zero means "unlimited"
146         this.ensureDefault("file_upload_limit", 0);
147         this.ensureDefault("file_queue_limit", 0);
148
149         // Flash Settings
150         this.ensureDefault("flash_url", "swfupload.swf");
151         this.ensureDefault("prevent_swf_caching", true);
152         
153         // Button Settings
154         this.ensureDefault("button_image_url", "");
155         this.ensureDefault("button_width", 1);
156         this.ensureDefault("button_height", 1);
157         this.ensureDefault("button_text", "");
158         this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;");
159         this.ensureDefault("button_text_top_padding", 0);
160         this.ensureDefault("button_text_left_padding", 0);
161         this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES);
162         this.ensureDefault("button_disabled", false);
163         this.ensureDefault("button_placeholder_id", "");
164         this.ensureDefault("button_placeholder", null);
165         this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW);
166         this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW);
167         
168         // Debug Settings
169         this.ensureDefault("debug", false);
170         this.settings.debug_enabled = this.settings.debug;      // Here to maintain v2 API
171         
172         // Event Handlers
173         this.settings.return_upload_start_handler = this.returnUploadStart;
174         this.ensureDefault("swfupload_loaded_handler", null);
175         this.ensureDefault("file_dialog_start_handler", null);
176         this.ensureDefault("file_queued_handler", null);
177         this.ensureDefault("file_queue_error_handler", null);
178         this.ensureDefault("file_dialog_complete_handler", null);
179         
180         this.ensureDefault("upload_start_handler", null);
181         this.ensureDefault("upload_progress_handler", null);
182         this.ensureDefault("upload_error_handler", null);
183         this.ensureDefault("upload_success_handler", null);
184         this.ensureDefault("upload_complete_handler", null);
185         
186         this.ensureDefault("debug_handler", this.debugMessage);
187
188         this.ensureDefault("custom_settings", {});
189
190         // Other settings
191         this.customSettings = this.settings.custom_settings;
192         
193         // Update the flash url if needed
194         if (!!this.settings.prevent_swf_caching) {
195                 this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime();
196         }
197         
198         if (!this.settings.preserve_relative_urls) {
199                 //this.settings.flash_url = SWFUpload.completeURL(this.settings.flash_url);     // Don't need to do this one since flash doesn't look at it
200                 this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url);
201                 this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url);
202         }
203         
204         delete this.ensureDefault;
205 };
206
207 // Private: loadFlash replaces the button_placeholder element with the flash movie.
208 SWFUpload.prototype.loadFlash = function () {
209         var targetElement, tempParent;
210
211         // Make sure an element with the ID we are going to use doesn't already exist
212         if (document.getElementById(this.movieName) !== null) {
213                 throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
214         }
215
216         // Get the element where we will be placing the flash movie
217         targetElement = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder;
218
219         if (targetElement == undefined) {
220                 throw "Could not find the placeholder element: " + this.settings.button_placeholder_id;
221         }
222
223         // Append the container and load the flash
224         tempParent = document.createElement("div");
225         tempParent.innerHTML = this.getFlashHTML();     // Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)
226         targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement);
227
228         // Fix IE Flash/Form bug
229         if (window[this.movieName] == undefined) {
230                 window[this.movieName] = this.getMovieElement();
231         }
232         
233 };
234
235 // Private: getFlashHTML generates the object tag needed to embed the flash in to the document
236 SWFUpload.prototype.getFlashHTML = function () {
237         // Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay
238         return ['<object id="', this.movieName, '" type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">',
239                                 '<param name="wmode" value="', this.settings.button_window_mode, '" />',
240                                 '<param name="movie" value="', this.settings.flash_url, '" />',
241                                 '<param name="quality" value="high" />',
242                                 '<param name="menu" value="false" />',
243                                 '<param name="allowScriptAccess" value="always" />',
244                                 '<param name="flashvars" value="' + this.getFlashVars() + '" />',
245                                 '</object>'].join("");
246 };
247
248 // Private: getFlashVars builds the parameter string that will be passed
249 // to flash in the flashvars param.
250 SWFUpload.prototype.getFlashVars = function () {
251         // Build a string from the post param object
252         var paramString = this.buildParamString();
253         var httpSuccessString = this.settings.http_success.join(",");
254         
255         // Build the parameter string
256         return ["movieName=", encodeURIComponent(this.movieName),
257                         "&amp;uploadURL=", encodeURIComponent(this.settings.upload_url),
258                         "&amp;useQueryString=", encodeURIComponent(this.settings.use_query_string),
259                         "&amp;requeueOnError=", encodeURIComponent(this.settings.requeue_on_error),
260                         "&amp;httpSuccess=", encodeURIComponent(httpSuccessString),
261                         "&amp;assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout),
262                         "&amp;params=", encodeURIComponent(paramString),
263                         "&amp;filePostName=", encodeURIComponent(this.settings.file_post_name),
264                         "&amp;fileTypes=", encodeURIComponent(this.settings.file_types),
265                         "&amp;fileTypesDescription=", encodeURIComponent(this.settings.file_types_description),
266                         "&amp;fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit),
267                         "&amp;fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit),
268                         "&amp;fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit),
269                         "&amp;debugEnabled=", encodeURIComponent(this.settings.debug_enabled),
270                         "&amp;buttonImageURL=", encodeURIComponent(this.settings.button_image_url),
271                         "&amp;buttonWidth=", encodeURIComponent(this.settings.button_width),
272                         "&amp;buttonHeight=", encodeURIComponent(this.settings.button_height),
273                         "&amp;buttonText=", encodeURIComponent(this.settings.button_text),
274                         "&amp;buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding),
275                         "&amp;buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding),
276                         "&amp;buttonTextStyle=", encodeURIComponent(this.settings.button_text_style),
277                         "&amp;buttonAction=", encodeURIComponent(this.settings.button_action),
278                         "&amp;buttonDisabled=", encodeURIComponent(this.settings.button_disabled),
279                         "&amp;buttonCursor=", encodeURIComponent(this.settings.button_cursor)
280                 ].join("");
281 };
282
283 // Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload
284 // The element is cached after the first lookup
285 SWFUpload.prototype.getMovieElement = function () {
286         if (this.movieElement == undefined) {
287                 this.movieElement = document.getElementById(this.movieName);
288         }
289
290         if (this.movieElement === null) {
291                 throw "Could not find Flash element";
292         }
293         
294         return this.movieElement;
295 };
296
297 // Private: buildParamString takes the name/value pairs in the post_params setting object
298 // and joins them up in to a string formatted "name=value&amp;name=value"
299 SWFUpload.prototype.buildParamString = function () {
300         var postParams = this.settings.post_params; 
301         var paramStringPairs = [];
302
303         if (typeof(postParams) === "object") {
304                 for (var name in postParams) {
305                         if (postParams.hasOwnProperty(name)) {
306                                 paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString()));
307                         }
308                 }
309         }
310
311         return paramStringPairs.join("&amp;");
312 };
313
314 // Public: Used to remove a SWFUpload instance from the page. This method strives to remove
315 // all references to the SWF, and other objects so memory is properly freed.
316 // Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state.
317 // Credits: Major improvements provided by steffen
318 SWFUpload.prototype.destroy = function () {
319         try {
320                 // Make sure Flash is done before we try to remove it
321                 this.cancelUpload(null, false);
322                 
323
324                 // Remove the SWFUpload DOM nodes
325                 var movieElement = null;
326                 movieElement = this.getMovieElement();
327                 
328                 if (movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
329                         // Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround)
330                         for (var i in movieElement) {
331                                 try {
332                                         if (typeof(movieElement[i]) === "function") {
333                                                 movieElement[i] = null;
334                                         }
335                                 } catch (ex1) {}
336                         }
337
338                         // Remove the Movie Element from the page
339                         try {
340                                 movieElement.parentNode.removeChild(movieElement);
341                         } catch (ex) {}
342                 }
343                 
344                 // Remove IE form fix reference
345                 window[this.movieName] = null;
346
347                 // Destroy other references
348                 SWFUpload.instances[this.movieName] = null;
349                 delete SWFUpload.instances[this.movieName];
350
351                 this.movieElement = null;
352                 this.settings = null;
353                 this.customSettings = null;
354                 this.eventQueue = null;
355                 this.movieName = null;
356                 
357                 
358                 return true;
359         } catch (ex2) {
360                 return false;
361         }
362 };
363
364
365 // Public: displayDebugInfo prints out settings and configuration
366 // information about this SWFUpload instance.
367 // This function (and any references to it) can be deleted when placing
368 // SWFUpload in production.
369 SWFUpload.prototype.displayDebugInfo = function () {
370         this.debug(
371                 [
372                         "---SWFUpload Instance Info---\n",
373                         "Version: ", SWFUpload.version, "\n",
374                         "Movie Name: ", this.movieName, "\n",
375                         "Settings:\n",
376                         "\t", "upload_url:               ", this.settings.upload_url, "\n",
377                         "\t", "flash_url:                ", this.settings.flash_url, "\n",
378                         "\t", "use_query_string:         ", this.settings.use_query_string.toString(), "\n",
379                         "\t", "requeue_on_error:         ", this.settings.requeue_on_error.toString(), "\n",
380                         "\t", "http_success:             ", this.settings.http_success.join(", "), "\n",
381                         "\t", "assume_success_timeout:   ", this.settings.assume_success_timeout, "\n",
382                         "\t", "file_post_name:           ", this.settings.file_post_name, "\n",
383                         "\t", "post_params:              ", this.settings.post_params.toString(), "\n",
384                         "\t", "file_types:               ", this.settings.file_types, "\n",
385                         "\t", "file_types_description:   ", this.settings.file_types_description, "\n",
386                         "\t", "file_size_limit:          ", this.settings.file_size_limit, "\n",
387                         "\t", "file_upload_limit:        ", this.settings.file_upload_limit, "\n",
388                         "\t", "file_queue_limit:         ", this.settings.file_queue_limit, "\n",
389                         "\t", "debug:                    ", this.settings.debug.toString(), "\n",
390
391                         "\t", "prevent_swf_caching:      ", this.settings.prevent_swf_caching.toString(), "\n",
392
393                         "\t", "button_placeholder_id:    ", this.settings.button_placeholder_id.toString(), "\n",
394                         "\t", "button_placeholder:       ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n",
395                         "\t", "button_image_url:         ", this.settings.button_image_url.toString(), "\n",
396                         "\t", "button_width:             ", this.settings.button_width.toString(), "\n",
397                         "\t", "button_height:            ", this.settings.button_height.toString(), "\n",
398                         "\t", "button_text:              ", this.settings.button_text.toString(), "\n",
399                         "\t", "button_text_style:        ", this.settings.button_text_style.toString(), "\n",
400                         "\t", "button_text_top_padding:  ", this.settings.button_text_top_padding.toString(), "\n",
401                         "\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n",
402                         "\t", "button_action:            ", this.settings.button_action.toString(), "\n",
403                         "\t", "button_disabled:          ", this.settings.button_disabled.toString(), "\n",
404
405                         "\t", "custom_settings:          ", this.settings.custom_settings.toString(), "\n",
406                         "Event Handlers:\n",
407                         "\t", "swfupload_loaded_handler assigned:  ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n",
408                         "\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n",
409                         "\t", "file_queued_handler assigned:       ", (typeof this.settings.file_queued_handler === "function").toString(), "\n",
410                         "\t", "file_queue_error_handler assigned:  ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n",
411                         "\t", "upload_start_handler assigned:      ", (typeof this.settings.upload_start_handler === "function").toString(), "\n",
412                         "\t", "upload_progress_handler assigned:   ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n",
413                         "\t", "upload_error_handler assigned:      ", (typeof this.settings.upload_error_handler === "function").toString(), "\n",
414                         "\t", "upload_success_handler assigned:    ", (typeof this.settings.upload_success_handler === "function").toString(), "\n",
415                         "\t", "upload_complete_handler assigned:   ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n",
416                         "\t", "debug_handler assigned:             ", (typeof this.settings.debug_handler === "function").toString(), "\n"
417                 ].join("")
418         );
419 };
420
421 /* Note: addSetting and getSetting are no longer used by SWFUpload but are included
422         the maintain v2 API compatibility
423 */
424 // Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used.
425 SWFUpload.prototype.addSetting = function (name, value, default_value) {
426     if (value == undefined) {
427         return (this.settings[name] = default_value);
428     } else {
429         return (this.settings[name] = value);
430         }
431 };
432
433 // Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found.
434 SWFUpload.prototype.getSetting = function (name) {
435     if (this.settings[name] != undefined) {
436         return this.settings[name];
437         }
438
439     return "";
440 };
441
442
443
444 // Private: callFlash handles function calls made to the Flash element.
445 // Calls are made with a setTimeout for some functions to work around
446 // bugs in the ExternalInterface library.
447 SWFUpload.prototype.callFlash = function (functionName, argumentArray) {
448         argumentArray = argumentArray || [];
449         
450         var movieElement = this.getMovieElement();
451         var returnValue, returnString;
452
453         // Flash's method if calling ExternalInterface methods (code adapted from MooTools).
454         try {
455                 returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');
456                 returnValue = eval(returnString);
457         } catch (ex) {
458                 throw "Call to " + functionName + " failed";
459         }
460         
461         // Unescape file post param values
462         if (returnValue != undefined && typeof returnValue.post === "object") {
463                 returnValue = this.unescapeFilePostParams(returnValue);
464         }
465
466         return returnValue;
467 };
468
469 /* *****************************
470         -- Flash control methods --
471         Your UI should use these
472         to operate SWFUpload
473    ***************************** */
474
475 // WARNING: this function does not work in Flash Player 10
476 // Public: selectFile causes a File Selection Dialog window to appear.  This
477 // dialog only allows 1 file to be selected.
478 SWFUpload.prototype.selectFile = function () {
479         this.callFlash("SelectFile");
480 };
481
482 // WARNING: this function does not work in Flash Player 10
483 // Public: selectFiles causes a File Selection Dialog window to appear/ This
484 // dialog allows the user to select any number of files
485 // Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names.
486 // If the selection name length is too long the dialog will fail in an unpredictable manner.  There is no work-around
487 // for this bug.
488 SWFUpload.prototype.selectFiles = function () {
489         this.callFlash("SelectFiles");
490 };
491
492
493 // Public: startUpload starts uploading the first file in the queue unless
494 // the optional parameter 'fileID' specifies the ID 
495 SWFUpload.prototype.startUpload = function (fileID) {
496         this.callFlash("StartUpload", [fileID]);
497 };
498
499 // Public: cancelUpload cancels any queued file.  The fileID parameter may be the file ID or index.
500 // If you do not specify a fileID the current uploading file or first file in the queue is cancelled.
501 // If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter.
502 SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) {
503         if (triggerErrorEvent !== false) {
504                 triggerErrorEvent = true;
505         }
506         this.callFlash("CancelUpload", [fileID, triggerErrorEvent]);
507 };
508
509 // Public: stopUpload stops the current upload and requeues the file at the beginning of the queue.
510 // If nothing is currently uploading then nothing happens.
511 SWFUpload.prototype.stopUpload = function () {
512         this.callFlash("StopUpload");
513 };
514
515 /* ************************
516  * Settings methods
517  *   These methods change the SWFUpload settings.
518  *   SWFUpload settings should not be changed directly on the settings object
519  *   since many of the settings need to be passed to Flash in order to take
520  *   effect.
521  * *********************** */
522
523 // Public: getStats gets the file statistics object.
524 SWFUpload.prototype.getStats = function () {
525         return this.callFlash("GetStats");
526 };
527
528 // Public: setStats changes the SWFUpload statistics.  You shouldn't need to 
529 // change the statistics but you can.  Changing the statistics does not
530 // affect SWFUpload accept for the successful_uploads count which is used
531 // by the upload_limit setting to determine how many files the user may upload.
532 SWFUpload.prototype.setStats = function (statsObject) {
533         this.callFlash("SetStats", [statsObject]);
534 };
535
536 // Public: getFile retrieves a File object by ID or Index.  If the file is
537 // not found then 'null' is returned.
538 SWFUpload.prototype.getFile = function (fileID) {
539         if (typeof(fileID) === "number") {
540                 return this.callFlash("GetFileByIndex", [fileID]);
541         } else {
542                 return this.callFlash("GetFile", [fileID]);
543         }
544 };
545
546 // Public: addFileParam sets a name/value pair that will be posted with the
547 // file specified by the Files ID.  If the name already exists then the
548 // exiting value will be overwritten.
549 SWFUpload.prototype.addFileParam = function (fileID, name, value) {
550         return this.callFlash("AddFileParam", [fileID, name, value]);
551 };
552
553 // Public: removeFileParam removes a previously set (by addFileParam) name/value
554 // pair from the specified file.
555 SWFUpload.prototype.removeFileParam = function (fileID, name) {
556         this.callFlash("RemoveFileParam", [fileID, name]);
557 };
558
559 // Public: setUploadUrl changes the upload_url setting.
560 SWFUpload.prototype.setUploadURL = function (url) {
561         this.settings.upload_url = url.toString();
562         this.callFlash("SetUploadURL", [url]);
563 };
564
565 // Public: setPostParams changes the post_params setting
566 SWFUpload.prototype.setPostParams = function (paramsObject) {
567         this.settings.post_params = paramsObject;
568         this.callFlash("SetPostParams", [paramsObject]);
569 };
570
571 // Public: addPostParam adds post name/value pair.  Each name can have only one value.
572 SWFUpload.prototype.addPostParam = function (name, value) {
573         this.settings.post_params[name] = value;
574         this.callFlash("SetPostParams", [this.settings.post_params]);
575 };
576
577 // Public: removePostParam deletes post name/value pair.
578 SWFUpload.prototype.removePostParam = function (name) {
579         delete this.settings.post_params[name];
580         this.callFlash("SetPostParams", [this.settings.post_params]);
581 };
582
583 // Public: setFileTypes changes the file_types setting and the file_types_description setting
584 SWFUpload.prototype.setFileTypes = function (types, description) {
585         this.settings.file_types = types;
586         this.settings.file_types_description = description;
587         this.callFlash("SetFileTypes", [types, description]);
588 };
589
590 // Public: setFileSizeLimit changes the file_size_limit setting
591 SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) {
592         this.settings.file_size_limit = fileSizeLimit;
593         this.callFlash("SetFileSizeLimit", [fileSizeLimit]);
594 };
595
596 // Public: setFileUploadLimit changes the file_upload_limit setting
597 SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) {
598         this.settings.file_upload_limit = fileUploadLimit;
599         this.callFlash("SetFileUploadLimit", [fileUploadLimit]);
600 };
601
602 // Public: setFileQueueLimit changes the file_queue_limit setting
603 SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) {
604         this.settings.file_queue_limit = fileQueueLimit;
605         this.callFlash("SetFileQueueLimit", [fileQueueLimit]);
606 };
607
608 // Public: setFilePostName changes the file_post_name setting
609 SWFUpload.prototype.setFilePostName = function (filePostName) {
610         this.settings.file_post_name = filePostName;
611         this.callFlash("SetFilePostName", [filePostName]);
612 };
613
614 // Public: setUseQueryString changes the use_query_string setting
615 SWFUpload.prototype.setUseQueryString = function (useQueryString) {
616         this.settings.use_query_string = useQueryString;
617         this.callFlash("SetUseQueryString", [useQueryString]);
618 };
619
620 // Public: setRequeueOnError changes the requeue_on_error setting
621 SWFUpload.prototype.setRequeueOnError = function (requeueOnError) {
622         this.settings.requeue_on_error = requeueOnError;
623         this.callFlash("SetRequeueOnError", [requeueOnError]);
624 };
625
626 // Public: setHTTPSuccess changes the http_success setting
627 SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) {
628         if (typeof http_status_codes === "string") {
629                 http_status_codes = http_status_codes.replace(" ", "").split(",");
630         }
631         
632         this.settings.http_success = http_status_codes;
633         this.callFlash("SetHTTPSuccess", [http_status_codes]);
634 };
635
636 // Public: setHTTPSuccess changes the http_success setting
637 SWFUpload.prototype.setAssumeSuccessTimeout = function (timeout_seconds) {
638         this.settings.assume_success_timeout = timeout_seconds;
639         this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]);
640 };
641
642 // Public: setDebugEnabled changes the debug_enabled setting
643 SWFUpload.prototype.setDebugEnabled = function (debugEnabled) {
644         this.settings.debug_enabled = debugEnabled;
645         this.callFlash("SetDebugEnabled", [debugEnabled]);
646 };
647
648 // Public: setButtonImageURL loads a button image sprite
649 SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) {
650         if (buttonImageURL == undefined) {
651                 buttonImageURL = "";
652         }
653         
654         this.settings.button_image_url = buttonImageURL;
655         this.callFlash("SetButtonImageURL", [buttonImageURL]);
656 };
657
658 // Public: setButtonDimensions resizes the Flash Movie and button
659 SWFUpload.prototype.setButtonDimensions = function (width, height) {
660         this.settings.button_width = width;
661         this.settings.button_height = height;
662         
663         var movie = this.getMovieElement();
664         if (movie != undefined) {
665                 movie.style.width = width + "px";
666                 movie.style.height = height + "px";
667         }
668         
669         this.callFlash("SetButtonDimensions", [width, height]);
670 };
671 // Public: setButtonText Changes the text overlaid on the button
672 SWFUpload.prototype.setButtonText = function (html) {
673         this.settings.button_text = html;
674         this.callFlash("SetButtonText", [html]);
675 };
676 // Public: setButtonTextPadding changes the top and left padding of the text overlay
677 SWFUpload.prototype.setButtonTextPadding = function (left, top) {
678         this.settings.button_text_top_padding = top;
679         this.settings.button_text_left_padding = left;
680         this.callFlash("SetButtonTextPadding", [left, top]);
681 };
682
683 // Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button
684 SWFUpload.prototype.setButtonTextStyle = function (css) {
685         this.settings.button_text_style = css;
686         this.callFlash("SetButtonTextStyle", [css]);
687 };
688 // Public: setButtonDisabled disables/enables the button
689 SWFUpload.prototype.setButtonDisabled = function (isDisabled) {
690         this.settings.button_disabled = isDisabled;
691         this.callFlash("SetButtonDisabled", [isDisabled]);
692 };
693 // Public: setButtonAction sets the action that occurs when the button is clicked
694 SWFUpload.prototype.setButtonAction = function (buttonAction) {
695         this.settings.button_action = buttonAction;
696         this.callFlash("SetButtonAction", [buttonAction]);
697 };
698
699 // Public: setButtonCursor changes the mouse cursor displayed when hovering over the button
700 SWFUpload.prototype.setButtonCursor = function (cursor) {
701         this.settings.button_cursor = cursor;
702         this.callFlash("SetButtonCursor", [cursor]);
703 };
704
705 /* *******************************
706         Flash Event Interfaces
707         These functions are used by Flash to trigger the various
708         events.
709         
710         All these functions a Private.
711         
712         Because the ExternalInterface library is buggy the event calls
713         are added to a queue and the queue then executed by a setTimeout.
714         This ensures that events are executed in a determinate order and that
715         the ExternalInterface bugs are avoided.
716 ******************************* */
717
718 SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) {
719         // Warning: Don't call this.debug inside here or you'll create an infinite loop
720         
721         if (argumentArray == undefined) {
722                 argumentArray = [];
723         } else if (!(argumentArray instanceof Array)) {
724                 argumentArray = [argumentArray];
725         }
726         
727         var self = this;
728         if (typeof this.settings[handlerName] === "function") {
729                 // Queue the event
730                 this.eventQueue.push(function () {
731                         this.settings[handlerName].apply(this, argumentArray);
732                 });
733                 
734                 // Execute the next queued event
735                 setTimeout(function () {
736                         self.executeNextEvent();
737                 }, 0);
738                 
739         } else if (this.settings[handlerName] !== null) {
740                 throw "Event handler " + handlerName + " is unknown or is not a function";
741         }
742 };
743
744 // Private: Causes the next event in the queue to be executed.  Since events are queued using a setTimeout
745 // we must queue them in order to garentee that they are executed in order.
746 SWFUpload.prototype.executeNextEvent = function () {
747         // Warning: Don't call this.debug inside here or you'll create an infinite loop
748
749         var  f = this.eventQueue ? this.eventQueue.shift() : null;
750         if (typeof(f) === "function") {
751                 f.apply(this);
752         }
753 };
754
755 // Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have
756 // properties that contain characters that are not valid for JavaScript identifiers. To work around this
757 // the Flash Component escapes the parameter names and we must unescape again before passing them along.
758 SWFUpload.prototype.unescapeFilePostParams = function (file) {
759         var reg = /[$]([0-9a-f]{4})/i;
760         var unescapedPost = {};
761         var uk;
762
763         if (file != undefined) {
764                 for (var k in file.post) {
765                         if (file.post.hasOwnProperty(k)) {
766                                 uk = k;
767                                 var match;
768                                 while ((match = reg.exec(uk)) !== null) {
769                                         uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16)));
770                                 }
771                                 unescapedPost[uk] = file.post[k];
772                         }
773                 }
774
775                 file.post = unescapedPost;
776         }
777
778         return file;
779 };
780
781 // Private: Called by Flash to see if JS can call in to Flash (test if External Interface is working)
782 SWFUpload.prototype.testExternalInterface = function () {
783         try {
784                 return this.callFlash("TestExternalInterface");
785         } catch (ex) {
786                 return false;
787         }
788 };
789
790 // Private: This event is called by Flash when it has finished loading. Don't modify this.
791 // Use the swfupload_loaded_handler event setting to execute custom code when SWFUpload has loaded.
792 SWFUpload.prototype.flashReady = function () {
793         // Check that the movie element is loaded correctly with its ExternalInterface methods defined
794         var movieElement = this.getMovieElement();
795
796         if (!movieElement) {
797                 this.debug("Flash called back ready but the flash movie can't be found.");
798                 return;
799         }
800
801         this.cleanUp(movieElement);
802         
803         this.queueEvent("swfupload_loaded_handler");
804 };
805
806 // Private: removes Flash added fuctions to the DOM node to prevent memory leaks in IE.
807 // This function is called by Flash each time the ExternalInterface functions are created.
808 SWFUpload.prototype.cleanUp = function (movieElement) {
809         // Pro-actively unhook all the Flash functions
810         try {
811                 if (this.movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
812                         this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");
813                         for (var key in movieElement) {
814                                 try {
815                                         if (typeof(movieElement[key]) === "function") {
816                                                 movieElement[key] = null;
817                                         }
818                                 } catch (ex) {
819                                 }
820                         }
821                 }
822         } catch (ex1) {
823         
824         }
825
826         // Fix Flashes own cleanup code so if the SWFMovie was removed from the page
827         // it doesn't display errors.
828         window["__flash__removeCallback"] = function (instance, name) {
829                 try {
830                         if (instance) {
831                                 instance[name] = null;
832                         }
833                 } catch (flashEx) {
834                 
835                 }
836         };
837
838 };
839
840
841 /* This is a chance to do something before the browse window opens */
842 SWFUpload.prototype.fileDialogStart = function () {
843         this.queueEvent("file_dialog_start_handler");
844 };
845
846
847 /* Called when a file is successfully added to the queue. */
848 SWFUpload.prototype.fileQueued = function (file) {
849         file = this.unescapeFilePostParams(file);
850         this.queueEvent("file_queued_handler", file);
851 };
852
853
854 /* Handle errors that occur when an attempt to queue a file fails. */
855 SWFUpload.prototype.fileQueueError = function (file, errorCode, message) {
856         file = this.unescapeFilePostParams(file);
857         this.queueEvent("file_queue_error_handler", [file, errorCode, message]);
858 };
859
860 /* Called after the file dialog has closed and the selected files have been queued.
861         You could call startUpload here if you want the queued files to begin uploading immediately. */
862 SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued, numFilesInQueue) {
863         this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued, numFilesInQueue]);
864 };
865
866 SWFUpload.prototype.uploadStart = function (file) {
867         file = this.unescapeFilePostParams(file);
868         this.queueEvent("return_upload_start_handler", file);
869 };
870
871 SWFUpload.prototype.returnUploadStart = function (file) {
872         var returnValue;
873         if (typeof this.settings.upload_start_handler === "function") {
874                 file = this.unescapeFilePostParams(file);
875                 returnValue = this.settings.upload_start_handler.call(this, file);
876         } else if (this.settings.upload_start_handler != undefined) {
877                 throw "upload_start_handler must be a function";
878         }
879
880         // Convert undefined to true so if nothing is returned from the upload_start_handler it is
881         // interpretted as 'true'.
882         if (returnValue === undefined) {
883                 returnValue = true;
884         }
885         
886         returnValue = !!returnValue;
887         
888         this.callFlash("ReturnUploadStart", [returnValue]);
889 };
890
891
892
893 SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) {
894         file = this.unescapeFilePostParams(file);
895         this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);
896 };
897
898 SWFUpload.prototype.uploadError = function (file, errorCode, message) {
899         file = this.unescapeFilePostParams(file);
900         this.queueEvent("upload_error_handler", [file, errorCode, message]);
901 };
902
903 SWFUpload.prototype.uploadSuccess = function (file, serverData, responseReceived) {
904         file = this.unescapeFilePostParams(file);
905         this.queueEvent("upload_success_handler", [file, serverData, responseReceived]);
906 };
907
908 SWFUpload.prototype.uploadComplete = function (file) {
909         file = this.unescapeFilePostParams(file);
910         this.queueEvent("upload_complete_handler", file);
911 };
912
913 /* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the
914    internal debug console.  You can override this event and have messages written where you want. */
915 SWFUpload.prototype.debug = function (message) {
916         this.queueEvent("debug_handler", message);
917 };
918
919
920 /* **********************************
921         Debug Console
922         The debug console is a self contained, in page location
923         for debug message to be sent.  The Debug Console adds
924         itself to the body if necessary.
925
926         The console is automatically scrolled as messages appear.
927         
928         If you are using your own debug handler or when you deploy to production and
929         have debug disabled you can remove these functions to reduce the file size
930         and complexity.
931 ********************************** */
932    
933 // Private: debugMessage is the default debug_handler.  If you want to print debug messages
934 // call the debug() function.  When overriding the function your own function should
935 // check to see if the debug setting is true before outputting debug information.
936 SWFUpload.prototype.debugMessage = function (message) {
937         if (this.settings.debug) {
938                 var exceptionMessage, exceptionValues = [];
939
940                 // Check for an exception object and print it nicely
941                 if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") {
942                         for (var key in message) {
943                                 if (message.hasOwnProperty(key)) {
944                                         exceptionValues.push(key + ": " + message[key]);
945                                 }
946                         }
947                         exceptionMessage = exceptionValues.join("\n") || "";
948                         exceptionValues = exceptionMessage.split("\n");
949                         exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");
950                         SWFUpload.Console.writeLine(exceptionMessage);
951                 } else {
952                         SWFUpload.Console.writeLine(message);
953                 }
954         }
955 };
956
957 SWFUpload.Console = {};
958 SWFUpload.Console.writeLine = function (message) {
959         var console, documentForm;
960
961         try {
962                 console = document.getElementById("SWFUpload_Console");
963
964                 if (!console) {
965                         documentForm = document.createElement("form");
966                         document.getElementsByTagName("body")[0].appendChild(documentForm);
967
968                         console = document.createElement("textarea");
969                         console.id = "SWFUpload_Console";
970                         console.style.fontFamily = "monospace";
971                         console.setAttribute("wrap", "off");
972                         console.wrap = "off";
973                         console.style.overflow = "auto";
974                         console.style.width = "700px";
975                         console.style.height = "350px";
976                         console.style.margin = "5px";
977                         documentForm.appendChild(console);
978                 }
979
980                 console.value += message + "\n";
981
982                 console.scrollTop = console.scrollHeight - console.clientHeight;
983         } catch (ex) {
984                 alert("Exception: " + ex.name + " Message: " + ex.message);
985         }
986 };