jquery.uploadify.js 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  1. /*
  2. SWFObject v2.2 <http://code.google.com/p/swfobject/>
  3. is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
  4. */
  5. ;var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;
  6. if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;
  7. X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);
  8. ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0;}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");
  9. if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)];}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac};
  10. }(),k=function(){if(!M.w3){return;}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f();
  11. }if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false);}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);
  12. f();}});if(O==top){(function(){if(J){return;}try{j.documentElement.doScroll("left");}catch(X){setTimeout(arguments.callee,0);return;}f();})();}}if(M.wk){(function(){if(J){return;
  13. }if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return;}f();})();}s(f);}}();function f(){if(J){return;}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));
  14. Z.parentNode.removeChild(Z);}catch(aa){return;}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]();}}function K(X){if(J){X();}else{U[U.length]=X;}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false);
  15. }else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false);}else{if(typeof O.attachEvent!=D){i(O,"onload",Y);}else{if(typeof O.onload=="function"){var X=O.onload;
  16. O.onload=function(){X();Y();};}else{O.onload=Y;}}}}}function h(){if(T){V();}else{H();}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);
  17. aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");
  18. M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)];}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return;}}X.removeChild(aa);Z=null;H();
  19. })();}else{H();}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);
  20. if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa);}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;
  21. ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class");}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align");
  22. }var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value");
  23. }}P(ai,ah,Y,ab);}else{p(ae);if(ab){ab(aa);}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z;}ab(aa);}}}}}function z(aa){var X=null;
  24. var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y;}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z;}}}return X;}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312);
  25. }function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null;}else{l=ae;Q=X;}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310";
  26. }if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137";}j.title=j.title.slice(0,47)+" - Flash Player Installation";
  27. var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac;
  28. }else{ab.flashvars=ac;}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";
  29. (function(){if(ae.readyState==4){ae.parentNode.removeChild(ae);}else{setTimeout(arguments.callee,10);}})();}u(aa,ab,X);}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");
  30. Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y);}else{setTimeout(arguments.callee,10);
  31. }})();}else{Y.parentNode.replaceChild(g(Y),Y);}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML;}else{var Y=ab.getElementsByTagName(r)[0];
  32. if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true));
  33. }}}}}return aa;}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X;}if(aa){if(typeof ai.id==D){ai.id=Y;}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae];
  34. }else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"';}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"';}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />';
  35. }}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id);}else{var Z=C(r);Z.setAttribute("type",q);
  36. for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac]);}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac]);
  37. }}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab]);}}aa.parentNode.replaceChild(Z,aa);X=Z;}}return X;}function e(Z,X,Y){var aa=C("param");
  38. aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa);}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";
  39. (function(){if(X.readyState==4){b(Y);}else{setTimeout(arguments.callee,10);}})();}else{X.parentNode.removeChild(X);}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null;
  40. }}Y.parentNode.removeChild(Y);}}function c(Z){var X=null;try{X=j.getElementById(Z);}catch(Y){}return X;}function C(X){return j.createElement(X);}function i(Z,X,Y){Z.attachEvent(X,Y);
  41. I[I.length]=[Z,X,Y];}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false;
  42. }function v(ac,Y,ad,ab){if(M.ie&&M.mac){return;}var aa=j.getElementsByTagName("head")[0];if(!aa){return;}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;
  43. G=null;}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1];
  44. }G=X;}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y);}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"));
  45. }}}function w(Z,X){if(!m){return;}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y;}else{v("#"+Z,"visibility:"+Y);}}function L(Y){var Z=/[\\\"<>\.;]/;
  46. var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y;}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;
  47. for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2]);}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa]);}for(var Y in M){M[Y]=null;}M=null;for(var X in swfobject){swfobject[X]=null;
  48. }swfobject=null;});}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;
  49. w(ab,false);}else{if(Z){Z({success:false,id:ab});}}},getObjectById:function(X){if(M.w3){return z(X);}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};
  50. if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al];}}aj.data=ab;
  51. aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak];}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai];
  52. }else{am.flashvars=ai+"="+Z[ai];}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true);}X.success=true;X.ref=an;}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);
  53. return;}else{w(ah,true);}}if(ac){ac(X);}});}else{if(ac){ac(X);}}},switchOffAutoHideShow:function(){m=false;},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]};
  54. },hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X);}else{return undefined;}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y);
  55. }},removeSWF:function(X){if(M.w3){y(X);}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X);}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;
  56. if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1];}if(aa==null){return L(Z);}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)));
  57. }}}return"";},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block";
  58. }}if(E){E(B);}}a=false;}}};}();
  59. /*
  60. Uploadify v3.2.1
  61. Copyright (c) 2012 Reactive Apps, Ronnie Garcia
  62. Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
  63. */
  64. (function($) {
  65. // These methods can be called by adding them as the first argument in the uploadify plugin call
  66. var methods = {
  67. init : function(options, swfUploadOptions) {
  68. return this.each(function() {
  69. // Create a reference to the jQuery DOM object
  70. var $this = $(this);
  71. // Clone the original DOM object
  72. var $clone = $this.clone();
  73. // Setup the default options
  74. var settings = $.extend({
  75. // Required Settings
  76. $upload : $this, // The ID of the DOM object
  77. swf : 'uploadify.swf', // The path to the uploadify SWF file
  78. uploader : 'uploadify.php', // The path to the server-side upload script
  79. // Options
  80. auto : true, // Automatically upload files when added to the queue
  81. buttonClass : '', // A class name to add to the browse button DOM object
  82. buttonCursor : 'hand', // The cursor to use with the browse button
  83. buttonImage : null, // (String or null) The path to an image to use for the Flash browse button if not using CSS to style the button
  84. buttonText : 'SELECT FILES', // The text to use for the browse button
  85. checkExisting : false, // The path to a server-side script that checks for existing files on the server
  86. debug : false, // Turn on swfUpload debugging mode
  87. fileObjName : 'Filedata', // The name of the file object to use in your server-side script
  88. fileSizeLimit : 0, // The maximum size of an uploadable file in KB (Accepts units B KB MB GB if string, 0 for no limit)
  89. fileTypeDesc : 'All Files', // The description for file types in the browse dialog
  90. fileTypeExts : '*.*', // Allowed extensions in the browse dialog (server-side validation should also be used)
  91. height : 30, // The height of the browse button
  92. itemTemplate : false, // The template for the file item in the queue
  93. method : 'post', // The method to use when sending files to the server-side upload script
  94. multi : true, // Allow multiple file selection in the browse dialog
  95. formData : {}, // An object with additional data to send to the server-side upload script with every file upload
  96. preventCaching : true, // Adds a random value to the Flash URL to prevent caching of it (conflicts with existing parameters)
  97. progressData : 'percentage', // ('percentage' or 'speed') Data to show in the queue item during a file upload
  98. queueID : false, // The ID of the DOM object to use as a file queue (without the #)
  99. queueSizeLimit : 999, // The maximum number of files that can be in the queue at one time
  100. removeCompleted : true, // Remove queue items from the queue when they are done uploading
  101. removeTimeout : 3, // The delay in seconds before removing a queue item if removeCompleted is set to true
  102. requeueErrors : false, // Keep errored files in the queue and keep trying to upload them
  103. successTimeout : 30, // The number of seconds to wait for Flash to detect the server's response after the file has finished uploading
  104. uploadLimit : 0, // The maximum number of files you can upload
  105. width : 120, // The width of the browse button
  106. // Events
  107. overrideEvents : [] // (Array) A list of default event handlers to skip
  108. /*
  109. onCancel // Triggered when a file is cancelled from the queue
  110. onClearQueue // Triggered during the 'clear queue' method
  111. onDestroy // Triggered when the uploadify object is destroyed
  112. onDialogClose // Triggered when the browse dialog is closed
  113. onDialogOpen // Triggered when the browse dialog is opened
  114. onDisable // Triggered when the browse button gets disabled
  115. onEnable // Triggered when the browse button gets enabled
  116. onFallback // Triggered is Flash is not detected
  117. onInit // Triggered when Uploadify is initialized
  118. onQueueComplete // Triggered when all files in the queue have been uploaded
  119. onSelectError // Triggered when an error occurs while selecting a file (file size, queue size limit, etc.)
  120. onSelect // Triggered for each file that is selected
  121. onSWFReady // Triggered when the SWF button is loaded
  122. onUploadComplete // Triggered when a file upload completes (success or error)
  123. onUploadError // Triggered when a file upload returns an error
  124. onUploadSuccess // Triggered when a file is uploaded successfully
  125. onUploadProgress // Triggered every time a file progress is updated
  126. onUploadStart // Triggered immediately before a file upload starts
  127. */
  128. }, options);
  129. // Prepare settings for SWFUpload
  130. var swfUploadSettings = {
  131. assume_success_timeout : settings.successTimeout,
  132. button_placeholder_id : settings.id,
  133. button_width : settings.width,
  134. button_height : settings.height,
  135. button_text : null,
  136. button_text_style : null,
  137. button_text_top_padding : 0,
  138. button_text_left_padding : 0,
  139. button_action : (settings.multi ? SWFUpload.BUTTON_ACTION.SELECT_FILES : SWFUpload.BUTTON_ACTION.SELECT_FILE),
  140. button_disabled : false,
  141. button_cursor : (settings.buttonCursor == 'arrow' ? SWFUpload.CURSOR.ARROW : SWFUpload.CURSOR.HAND),
  142. button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT,
  143. debug : settings.debug,
  144. requeue_on_error : settings.requeueErrors,
  145. file_post_name : settings.fileObjName,
  146. file_size_limit : settings.fileSizeLimit,
  147. file_types : settings.fileTypeExts,
  148. file_types_description : settings.fileTypeDesc,
  149. file_queue_limit : settings.queueSizeLimit,
  150. file_upload_limit : settings.uploadLimit,
  151. flash_url : settings.swf,
  152. prevent_swf_caching : settings.preventCaching,
  153. post_params : settings.formData,
  154. upload_url : settings.uploader,
  155. use_query_string : (settings.method == 'get'),
  156. // Event Handlers
  157. file_dialog_complete_handler : handlers.onDialogClose,
  158. file_dialog_start_handler : handlers.onDialogOpen,
  159. file_queued_handler : handlers.onSelect,
  160. file_queue_error_handler : handlers.onSelectError,
  161. swfupload_loaded_handler : settings.onSWFReady,
  162. upload_complete_handler : handlers.onUploadComplete,
  163. upload_error_handler : handlers.onUploadError,
  164. upload_progress_handler : handlers.onUploadProgress,
  165. upload_start_handler : handlers.onUploadStart,
  166. upload_success_handler : handlers.onUploadSuccess
  167. }
  168. // Merge the user-defined options with the defaults
  169. if (swfUploadOptions) {
  170. swfUploadSettings = $.extend(swfUploadSettings, swfUploadOptions);
  171. }
  172. // Add the user-defined settings to the swfupload object
  173. swfUploadSettings = $.extend(swfUploadSettings, settings);
  174. // Detect if Flash is available
  175. var playerVersion = swfobject.getFlashPlayerVersion();
  176. var flashInstalled = (playerVersion.major >= 9);
  177. if (flashInstalled) {
  178. // Create the swfUpload instance
  179. window['uploadify_' + settings.id] = new SWFUpload(swfUploadSettings);
  180. var swfuploadify = window['uploadify_' + settings.id];
  181. // Add the SWFUpload object to the elements data object
  182. $this.data('uploadify', swfuploadify);
  183. // Wrap the instance
  184. var $wrapper = $('<div />', {
  185. 'id' : settings.id,
  186. 'class' : 'uploadify',
  187. 'css' : {
  188. 'height' : settings.height + 'px',
  189. 'width' : settings.width + 'px'
  190. }
  191. });
  192. $('#' + swfuploadify.movieName).wrap($wrapper);
  193. // Recreate the reference to wrapper
  194. $wrapper = $('#' + settings.id);
  195. // Add the data object to the wrapper
  196. $wrapper.data('uploadify', swfuploadify);
  197. // Create the button
  198. var $button = $('<div />', {
  199. 'id' : settings.id + '-button',
  200. 'class' : 'uploadify-button ' + settings.buttonClass
  201. });
  202. if (settings.buttonImage) {
  203. $button.css({
  204. 'background-image' : "url('" + settings.buttonImage + "')",
  205. 'text-indent' : '-9999px'
  206. });
  207. }
  208. $button.html('<span class="uploadify-button-text">' + settings.buttonText + '</span>')
  209. .css({
  210. 'height' : settings.height + 'px',
  211. 'line-height' : settings.height + 'px',
  212. 'width' : settings.width + 'px'
  213. });
  214. // Append the button to the wrapper
  215. $wrapper.append($button);
  216. // Adjust the styles of the movie
  217. $('#' + swfuploadify.movieName).css({
  218. 'position' : 'absolute',
  219. 'z-index' : 1
  220. });
  221. // Create the file queue
  222. if (!settings.queueID) {
  223. var $queue = $('<div />', {
  224. 'id' : settings.id + '-queue',
  225. 'class' : 'uploadify-queue'
  226. });
  227. $wrapper.after($queue);
  228. swfuploadify.settings.queueID = settings.id + '-queue';
  229. swfuploadify.settings.defaultQueue = true;
  230. }
  231. // Create some queue related objects and variables
  232. swfuploadify.queueData = {
  233. files : {}, // The files in the queue
  234. filesSelected : 0, // The number of files selected in the last select operation
  235. filesQueued : 0, // The number of files added to the queue in the last select operation
  236. filesReplaced : 0, // The number of files replaced in the last select operation
  237. filesCancelled : 0, // The number of files that were cancelled instead of replaced
  238. filesErrored : 0, // The number of files that caused error in the last select operation
  239. uploadsSuccessful : 0, // The number of files that were successfully uploaded
  240. uploadsErrored : 0, // The number of files that returned errors during upload
  241. averageSpeed : 0, // The average speed of the uploads in KB
  242. queueLength : 0, // The number of files in the queue
  243. queueSize : 0, // The size in bytes of the entire queue
  244. uploadSize : 0, // The size in bytes of the upload queue
  245. queueBytesUploaded : 0, // The size in bytes that have been uploaded for the current upload queue
  246. uploadQueue : [], // The files currently to be uploaded
  247. errorMsg : 'Some files were not added to the queue:'
  248. };
  249. // Save references to all the objects
  250. swfuploadify.original = $clone;
  251. swfuploadify.wrapper = $wrapper;
  252. swfuploadify.button = $button;
  253. swfuploadify.queue = $queue;
  254. // Call the user-defined init event handler
  255. if (settings.onInit) settings.onInit.call($this, swfuploadify);
  256. } else {
  257. // Call the fallback function
  258. if (settings.onFallback) settings.onFallback.call($this);
  259. }
  260. });
  261. },
  262. // Stop a file upload and remove it from the queue
  263. cancel : function(fileID, supressEvent) {
  264. var args = arguments;
  265. this.each(function() {
  266. // Create a reference to the jQuery DOM object
  267. var $this = $(this),
  268. swfuploadify = $this.data('uploadify'),
  269. settings = swfuploadify.settings,
  270. delay = -1;
  271. if (args[0]) {
  272. // Clear the queue
  273. if (args[0] == '*') {
  274. var queueItemCount = swfuploadify.queueData.queueLength;
  275. $('#' + settings.queueID).find('.uploadify-queue-item').each(function() {
  276. delay++;
  277. if (args[1] === true) {
  278. swfuploadify.cancelUpload($(this).attr('id'), false);
  279. } else {
  280. swfuploadify.cancelUpload($(this).attr('id'));
  281. }
  282. $(this).find('.data').removeClass('data').html(' - Cancelled');
  283. $(this).find('.uploadify-progress-bar').remove();
  284. $(this).delay(1000 + 100 * delay).fadeOut(500, function() {
  285. $(this).remove();
  286. });
  287. });
  288. swfuploadify.queueData.queueSize = 0;
  289. swfuploadify.queueData.queueLength = 0;
  290. // Trigger the onClearQueue event
  291. if (settings.onClearQueue) settings.onClearQueue.call($this, queueItemCount);
  292. } else {
  293. for (var n = 0; n < args.length; n++) {
  294. swfuploadify.cancelUpload(args[n]);
  295. $('#' + args[n]).find('.data').removeClass('data').html(' - Cancelled');
  296. $('#' + args[n]).find('.uploadify-progress-bar').remove();
  297. $('#' + args[n]).delay(1000 + 100 * n).fadeOut(500, function() {
  298. $(this).remove();
  299. });
  300. }
  301. }
  302. } else {
  303. var item = $('#' + settings.queueID).find('.uploadify-queue-item').get(0);
  304. $item = $(item);
  305. swfuploadify.cancelUpload($item.attr('id'));
  306. $item.find('.data').removeClass('data').html(' - Cancelled');
  307. $item.find('.uploadify-progress-bar').remove();
  308. $item.delay(1000).fadeOut(500, function() {
  309. $(this).remove();
  310. });
  311. }
  312. });
  313. },
  314. // Revert the DOM object back to its original state
  315. destroy : function() {
  316. this.each(function() {
  317. // Create a reference to the jQuery DOM object
  318. var $this = $(this),
  319. swfuploadify = $this.data('uploadify'),
  320. settings = swfuploadify.settings;
  321. // Destroy the SWF object and
  322. swfuploadify.destroy();
  323. // Destroy the queue
  324. if (settings.defaultQueue) {
  325. $('#' + settings.queueID).remove();
  326. }
  327. // Reload the original DOM element
  328. $('#' + settings.id).replaceWith(swfuploadify.original);
  329. // Call the user-defined event handler
  330. if (settings.onDestroy) settings.onDestroy.call(this);
  331. delete swfuploadify;
  332. });
  333. },
  334. // Disable the select button
  335. disable : function(isDisabled) {
  336. this.each(function() {
  337. // Create a reference to the jQuery DOM object
  338. var $this = $(this),
  339. swfuploadify = $this.data('uploadify'),
  340. settings = swfuploadify.settings;
  341. // Call the user-defined event handlers
  342. if (isDisabled) {
  343. swfuploadify.button.addClass('disabled');
  344. if (settings.onDisable) settings.onDisable.call(this);
  345. } else {
  346. swfuploadify.button.removeClass('disabled');
  347. if (settings.onEnable) settings.onEnable.call(this);
  348. }
  349. // Enable/disable the browse button
  350. swfuploadify.setButtonDisabled(isDisabled);
  351. });
  352. },
  353. // Get or set the settings data
  354. settings : function(name, value, resetObjects) {
  355. var args = arguments;
  356. var returnValue = value;
  357. this.each(function() {
  358. // Create a reference to the jQuery DOM object
  359. var $this = $(this),
  360. swfuploadify = $this.data('uploadify'),
  361. settings = swfuploadify.settings;
  362. if (typeof(args[0]) == 'object') {
  363. for (var n in value) {
  364. setData(n,value[n]);
  365. }
  366. }
  367. if (args.length === 1) {
  368. returnValue = settings[name];
  369. } else {
  370. switch (name) {
  371. case 'uploader':
  372. swfuploadify.setUploadURL(value);
  373. break;
  374. case 'formData':
  375. if (!resetObjects) {
  376. value = $.extend(settings.formData, value);
  377. }
  378. swfuploadify.setPostParams(settings.formData);
  379. break;
  380. case 'method':
  381. if (value == 'get') {
  382. swfuploadify.setUseQueryString(true);
  383. } else {
  384. swfuploadify.setUseQueryString(false);
  385. }
  386. break;
  387. case 'fileObjName':
  388. swfuploadify.setFilePostName(value);
  389. break;
  390. case 'fileTypeExts':
  391. swfuploadify.setFileTypes(value, settings.fileTypeDesc);
  392. break;
  393. case 'fileTypeDesc':
  394. swfuploadify.setFileTypes(settings.fileTypeExts, value);
  395. break;
  396. case 'fileSizeLimit':
  397. swfuploadify.setFileSizeLimit(value);
  398. break;
  399. case 'uploadLimit':
  400. swfuploadify.setFileUploadLimit(value);
  401. break;
  402. case 'queueSizeLimit':
  403. swfuploadify.setFileQueueLimit(value);
  404. break;
  405. case 'buttonImage':
  406. swfuploadify.button.css('background-image', settingValue);
  407. break;
  408. case 'buttonCursor':
  409. if (value == 'arrow') {
  410. swfuploadify.setButtonCursor(SWFUpload.CURSOR.ARROW);
  411. } else {
  412. swfuploadify.setButtonCursor(SWFUpload.CURSOR.HAND);
  413. }
  414. break;
  415. case 'buttonText':
  416. $('#' + settings.id + '-button').find('.uploadify-button-text').html(value);
  417. break;
  418. case 'width':
  419. swfuploadify.setButtonDimensions(value, settings.height);
  420. break;
  421. case 'height':
  422. swfuploadify.setButtonDimensions(settings.width, value);
  423. break;
  424. case 'multi':
  425. if (value) {
  426. swfuploadify.setButtonAction(SWFUpload.BUTTON_ACTION.SELECT_FILES);
  427. } else {
  428. swfuploadify.setButtonAction(SWFUpload.BUTTON_ACTION.SELECT_FILE);
  429. }
  430. break;
  431. }
  432. settings[name] = value;
  433. }
  434. });
  435. if (args.length === 1) {
  436. return returnValue;
  437. }
  438. },
  439. // Stop the current uploads and requeue what is in progress
  440. stop : function() {
  441. this.each(function() {
  442. // Create a reference to the jQuery DOM object
  443. var $this = $(this),
  444. swfuploadify = $this.data('uploadify');
  445. // Reset the queue information
  446. swfuploadify.queueData.averageSpeed = 0;
  447. swfuploadify.queueData.uploadSize = 0;
  448. swfuploadify.queueData.bytesUploaded = 0;
  449. swfuploadify.queueData.uploadQueue = [];
  450. swfuploadify.stopUpload();
  451. });
  452. },
  453. // Start uploading files in the queue
  454. upload : function() {
  455. var args = arguments;
  456. this.each(function() {
  457. // Create a reference to the jQuery DOM object
  458. var $this = $(this),
  459. swfuploadify = $this.data('uploadify');
  460. // Reset the queue information
  461. swfuploadify.queueData.averageSpeed = 0;
  462. swfuploadify.queueData.uploadSize = 0;
  463. swfuploadify.queueData.bytesUploaded = 0;
  464. swfuploadify.queueData.uploadQueue = [];
  465. // Upload the files
  466. if (args[0]) {
  467. if (args[0] == '*') {
  468. swfuploadify.queueData.uploadSize = swfuploadify.queueData.queueSize;
  469. swfuploadify.queueData.uploadQueue.push('*');
  470. swfuploadify.startUpload();
  471. } else {
  472. for (var n = 0; n < args.length; n++) {
  473. swfuploadify.queueData.uploadSize += swfuploadify.queueData.files[args[n]].size;
  474. swfuploadify.queueData.uploadQueue.push(args[n]);
  475. }
  476. swfuploadify.startUpload(swfuploadify.queueData.uploadQueue.shift());
  477. }
  478. } else {
  479. swfuploadify.startUpload();
  480. }
  481. });
  482. }
  483. }
  484. // These functions handle all the events that occur with the file uploader
  485. var handlers = {
  486. // Triggered when the file dialog is opened
  487. onDialogOpen : function() {
  488. // Load the swfupload settings
  489. var settings = this.settings;
  490. // Reset some queue info
  491. this.queueData.errorMsg = 'Some files were not added to the queue:';
  492. this.queueData.filesReplaced = 0;
  493. this.queueData.filesCancelled = 0;
  494. // Call the user-defined event handler
  495. if (settings.onDialogOpen) settings.onDialogOpen.call(this);
  496. },
  497. // Triggered when the browse dialog is closed
  498. onDialogClose : function(filesSelected, filesQueued, queueLength) {
  499. // Load the swfupload settings
  500. var settings = this.settings;
  501. // Update the queue information
  502. this.queueData.filesErrored = filesSelected - filesQueued;
  503. this.queueData.filesSelected = filesSelected;
  504. this.queueData.filesQueued = filesQueued - this.queueData.filesCancelled;
  505. this.queueData.queueLength = queueLength;
  506. // Run the default event handler
  507. if ($.inArray('onDialogClose', settings.overrideEvents) < 0) {
  508. if (this.queueData.filesErrored > 0) {
  509. alert(this.queueData.errorMsg);
  510. }
  511. }
  512. // Call the user-defined event handler
  513. if (settings.onDialogClose) settings.onDialogClose.call(this, this.queueData);
  514. // Upload the files if auto is true
  515. if (settings.auto) $('#' + settings.id).uploadify('upload', '*');
  516. },
  517. // Triggered once for each file added to the queue
  518. onSelect : function(file) {
  519. // Load the swfupload settings
  520. var settings = this.settings;
  521. // Check if a file with the same name exists in the queue
  522. var queuedFile = {};
  523. for (var n in this.queueData.files) {
  524. queuedFile = this.queueData.files[n];
  525. if (queuedFile.uploaded != true && queuedFile.name == file.name) {
  526. var replaceQueueItem = confirm('The file named "' + file.name + '" is already in the queue.\nDo you want to replace the existing item in the queue?');
  527. if (!replaceQueueItem) {
  528. this.cancelUpload(file.id);
  529. this.queueData.filesCancelled++;
  530. return false;
  531. } else {
  532. $('#' + queuedFile.id).remove();
  533. this.cancelUpload(queuedFile.id);
  534. this.queueData.filesReplaced++;
  535. }
  536. }
  537. }
  538. // Get the size of the file
  539. var fileSize = Math.round(file.size / 1024);
  540. var suffix = 'KB';
  541. if (fileSize > 1000) {
  542. fileSize = Math.round(fileSize / 1000);
  543. suffix = 'MB';
  544. }
  545. var fileSizeParts = fileSize.toString().split('.');
  546. fileSize = fileSizeParts[0];
  547. if (fileSizeParts.length > 1) {
  548. fileSize += '.' + fileSizeParts[1].substr(0,2);
  549. }
  550. fileSize += suffix;
  551. // Truncate the filename if it's too long
  552. var fileName = file.name;
  553. if (fileName.length > 25) {
  554. fileName = fileName.substr(0,25) + '...';
  555. }
  556. // Create the file data object
  557. itemData = {
  558. 'fileID' : file.id,
  559. 'instanceID' : settings.id,
  560. 'fileName' : fileName,
  561. 'fileSize' : fileSize
  562. }
  563. // Create the file item template
  564. if (settings.itemTemplate == false) {
  565. settings.itemTemplate = '<div id="${fileID}" class="uploadify-queue-item">\
  566. <div class="cancel">\
  567. <a href="javascript:$(\'#${instanceID}\').uploadify(\'cancel\', \'${fileID}\')">X</a>\
  568. </div>\
  569. <span class="fileName">${fileName} (${fileSize})</span><span class="data"></span>\
  570. <div class="uploadify-progress">\
  571. <div class="uploadify-progress-bar"><!--Progress Bar--></div>\
  572. </div>\
  573. </div>';
  574. }
  575. // Run the default event handler
  576. if ($.inArray('onSelect', settings.overrideEvents) < 0) {
  577. // Replace the item data in the template
  578. itemHTML = settings.itemTemplate;
  579. for (var d in itemData) {
  580. itemHTML = itemHTML.replace(new RegExp('\\$\\{' + d + '\\}', 'g'), itemData[d]);
  581. }
  582. // Add the file item to the queue
  583. $('#' + settings.queueID).append(itemHTML);
  584. }
  585. this.queueData.queueSize += file.size;
  586. this.queueData.files[file.id] = file;
  587. // Call the user-defined event handler
  588. if (settings.onSelect) settings.onSelect.apply(this, arguments);
  589. },
  590. // Triggered when a file is not added to the queue
  591. onSelectError : function(file, errorCode, errorMsg) {
  592. // Load the swfupload settings
  593. var settings = this.settings;
  594. // Run the default event handler
  595. if ($.inArray('onSelectError', settings.overrideEvents) < 0) {
  596. switch(errorCode) {
  597. case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
  598. if (settings.queueSizeLimit > errorMsg) {
  599. this.queueData.errorMsg += '\nThe number of files selected exceeds the remaining upload limit (' + errorMsg + ').';
  600. } else {
  601. this.queueData.errorMsg += '\nThe number of files selected exceeds the queue size limit (' + settings.queueSizeLimit + ').';
  602. }
  603. break;
  604. case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
  605. this.queueData.errorMsg += '\nThe file "' + file.name + '" exceeds the size limit (' + settings.fileSizeLimit + ').';
  606. break;
  607. case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
  608. this.queueData.errorMsg += '\nThe file "' + file.name + '" is empty.';
  609. break;
  610. case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
  611. this.queueData.errorMsg += '\nThe file "' + file.name + '" is not an accepted file type (' + settings.fileTypeDesc + ').';
  612. break;
  613. }
  614. }
  615. if (errorCode != SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
  616. delete this.queueData.files[file.id];
  617. }
  618. // Call the user-defined event handler
  619. if (settings.onSelectError) settings.onSelectError.apply(this, arguments);
  620. },
  621. // Triggered when all the files in the queue have been processed
  622. onQueueComplete : function() {
  623. if (this.settings.onQueueComplete) this.settings.onQueueComplete.call(this, this.settings.queueData);
  624. },
  625. // Triggered when a file upload successfully completes
  626. onUploadComplete : function(file) {
  627. // Load the swfupload settings
  628. var settings = this.settings,
  629. swfuploadify = this;
  630. // Check if all the files have completed uploading
  631. var stats = this.getStats();
  632. this.queueData.queueLength = stats.files_queued;
  633. if (this.queueData.uploadQueue[0] == '*') {
  634. if (this.queueData.queueLength > 0) {
  635. this.startUpload();
  636. } else {
  637. this.queueData.uploadQueue = [];
  638. // Call the user-defined event handler for queue complete
  639. if (settings.onQueueComplete) settings.onQueueComplete.call(this, this.queueData);
  640. }
  641. } else {
  642. if (this.queueData.uploadQueue.length > 0) {
  643. this.startUpload(this.queueData.uploadQueue.shift());
  644. } else {
  645. this.queueData.uploadQueue = [];
  646. // Call the user-defined event handler for queue complete
  647. if (settings.onQueueComplete) settings.onQueueComplete.call(this, this.queueData);
  648. }
  649. }
  650. // Call the default event handler
  651. if ($.inArray('onUploadComplete', settings.overrideEvents) < 0) {
  652. if (settings.removeCompleted) {
  653. switch (file.filestatus) {
  654. case SWFUpload.FILE_STATUS.COMPLETE:
  655. setTimeout(function() {
  656. if ($('#' + file.id)) {
  657. swfuploadify.queueData.queueSize -= file.size;
  658. swfuploadify.queueData.queueLength -= 1;
  659. delete swfuploadify.queueData.files[file.id]
  660. $('#' + file.id).fadeOut(500, function() {
  661. $(this).remove();
  662. });
  663. }
  664. }, settings.removeTimeout * 1000);
  665. break;
  666. case SWFUpload.FILE_STATUS.ERROR:
  667. if (!settings.requeueErrors) {
  668. setTimeout(function() {
  669. if ($('#' + file.id)) {
  670. swfuploadify.queueData.queueSize -= file.size;
  671. swfuploadify.queueData.queueLength -= 1;
  672. delete swfuploadify.queueData.files[file.id];
  673. $('#' + file.id).fadeOut(500, function() {
  674. $(this).remove();
  675. });
  676. }
  677. }, settings.removeTimeout * 1000);
  678. }
  679. break;
  680. }
  681. } else {
  682. file.uploaded = true;
  683. }
  684. }
  685. // Call the user-defined event handler
  686. if (settings.onUploadComplete) settings.onUploadComplete.call(this, file);
  687. },
  688. // Triggered when a file upload returns an error
  689. onUploadError : function(file, errorCode, errorMsg) {
  690. // Load the swfupload settings
  691. var settings = this.settings;
  692. // Set the error string
  693. var errorString = 'Error';
  694. switch(errorCode) {
  695. case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
  696. errorString = 'HTTP Error (' + errorMsg + ')';
  697. break;
  698. case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
  699. errorString = 'Missing Upload URL';
  700. break;
  701. case SWFUpload.UPLOAD_ERROR.IO_ERROR:
  702. errorString = 'IO Error';
  703. break;
  704. case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
  705. errorString = 'Security Error';
  706. break;
  707. case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
  708. alert('The upload limit has been reached (' + errorMsg + ').');
  709. errorString = 'Exceeds Upload Limit';
  710. break;
  711. case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
  712. errorString = 'Failed';
  713. break;
  714. case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
  715. break;
  716. case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
  717. errorString = 'Validation Error';
  718. break;
  719. case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
  720. errorString = 'Cancelled';
  721. this.queueData.queueSize -= file.size;
  722. this.queueData.queueLength -= 1;
  723. if (file.status == SWFUpload.FILE_STATUS.IN_PROGRESS || $.inArray(file.id, this.queueData.uploadQueue) >= 0) {
  724. this.queueData.uploadSize -= file.size;
  725. }
  726. // Trigger the onCancel event
  727. if (settings.onCancel) settings.onCancel.call(this, file);
  728. delete this.queueData.files[file.id];
  729. break;
  730. case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
  731. errorString = 'Stopped';
  732. break;
  733. }
  734. // Call the default event handler
  735. if ($.inArray('onUploadError', settings.overrideEvents) < 0) {
  736. if (errorCode != SWFUpload.UPLOAD_ERROR.FILE_CANCELLED && errorCode != SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED) {
  737. $('#' + file.id).addClass('uploadify-error');
  738. }
  739. // Reset the progress bar
  740. $('#' + file.id).find('.uploadify-progress-bar').css('width','1px');
  741. // Add the error message to the queue item
  742. if (errorCode != SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND && file.status != SWFUpload.FILE_STATUS.COMPLETE) {
  743. $('#' + file.id).find('.data').html(' - ' + errorString);
  744. }
  745. }
  746. var stats = this.getStats();
  747. this.queueData.uploadsErrored = stats.upload_errors;
  748. // Call the user-defined event handler
  749. if (settings.onUploadError) settings.onUploadError.call(this, file, errorCode, errorMsg, errorString);
  750. },
  751. // Triggered periodically during a file upload
  752. onUploadProgress : function(file, fileBytesLoaded, fileTotalBytes) {
  753. // Load the swfupload settings
  754. var settings = this.settings;
  755. // Setup all the variables
  756. var timer = new Date();
  757. var newTime = timer.getTime();
  758. var lapsedTime = newTime - this.timer;
  759. if (lapsedTime > 500) {
  760. this.timer = newTime;
  761. }
  762. var lapsedBytes = fileBytesLoaded - this.bytesLoaded;
  763. this.bytesLoaded = fileBytesLoaded;
  764. var queueBytesLoaded = this.queueData.queueBytesUploaded + fileBytesLoaded;
  765. var percentage = Math.round(fileBytesLoaded / fileTotalBytes * 100);
  766. // Calculate the average speed
  767. var suffix = 'KB/s';
  768. var mbs = 0;
  769. var kbs = (lapsedBytes / 1024) / (lapsedTime / 1000);
  770. kbs = Math.floor(kbs * 10) / 10;
  771. if (this.queueData.averageSpeed > 0) {
  772. this.queueData.averageSpeed = Math.floor((this.queueData.averageSpeed + kbs) / 2);
  773. } else {
  774. this.queueData.averageSpeed = Math.floor(kbs);
  775. }
  776. if (kbs > 1000) {
  777. mbs = (kbs * .001);
  778. this.queueData.averageSpeed = Math.floor(mbs);
  779. suffix = 'MB/s';
  780. }
  781. // Call the default event handler
  782. if ($.inArray('onUploadProgress', settings.overrideEvents) < 0) {
  783. if (settings.progressData == 'percentage') {
  784. $('#' + file.id).find('.data').html(' - ' + percentage + '%');
  785. } else if (settings.progressData == 'speed' && lapsedTime > 500) {
  786. $('#' + file.id).find('.data').html(' - ' + this.queueData.averageSpeed + suffix);
  787. }
  788. $('#' + file.id).find('.uploadify-progress-bar').css('width', percentage + '%');
  789. }
  790. // Call the user-defined event handler
  791. if (settings.onUploadProgress) settings.onUploadProgress.call(this, file, fileBytesLoaded, fileTotalBytes, queueBytesLoaded, this.queueData.uploadSize);
  792. },
  793. // Triggered right before a file is uploaded
  794. onUploadStart : function(file) {
  795. // Load the swfupload settings
  796. var settings = this.settings;
  797. var timer = new Date();
  798. this.timer = timer.getTime();
  799. this.bytesLoaded = 0;
  800. if (this.queueData.uploadQueue.length == 0) {
  801. this.queueData.uploadSize = file.size;
  802. }
  803. if (settings.checkExisting) {
  804. $.ajax({
  805. type : 'POST',
  806. async : false,
  807. url : settings.checkExisting,
  808. data : {filename: file.name},
  809. success : function(data) {
  810. if (data == 1) {
  811. var overwrite = confirm('A file with the name "' + file.name + '" already exists on the server.\nWould you like to replace the existing file?');
  812. if (!overwrite) {
  813. this.cancelUpload(file.id);
  814. $('#' + file.id).remove();
  815. if (this.queueData.uploadQueue.length > 0 && this.queueData.queueLength > 0) {
  816. if (this.queueData.uploadQueue[0] == '*') {
  817. this.startUpload();
  818. } else {
  819. this.startUpload(this.queueData.uploadQueue.shift());
  820. }
  821. }
  822. }
  823. }
  824. }
  825. });
  826. }
  827. // Call the user-defined event handler
  828. if (settings.onUploadStart) settings.onUploadStart.call(this, file);
  829. },
  830. // Triggered when a file upload returns a successful code
  831. onUploadSuccess : function(file, data, response) {
  832. // Load the swfupload settings
  833. var settings = this.settings;
  834. var stats = this.getStats();
  835. this.queueData.uploadsSuccessful = stats.successful_uploads;
  836. this.queueData.queueBytesUploaded += file.size;
  837. // Call the default event handler
  838. if ($.inArray('onUploadSuccess', settings.overrideEvents) < 0) {
  839. $('#' + file.id).find('.data').html(' - Complete');
  840. }
  841. // Call the user-defined event handler
  842. if (settings.onUploadSuccess) settings.onUploadSuccess.call(this, file, data, settings.$upload);
  843. }
  844. }
  845. $.fn.uploadify = function(method) {
  846. if (methods[method]) {
  847. return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
  848. } else if (typeof method === 'object' || !method) {
  849. return methods.init.apply(this, arguments);
  850. } else {
  851. $.error('The method ' + method + ' does not exist in $.uploadify');
  852. }
  853. }
  854. })($);