1 /* global plupload, pluploadL10n, ajaxurl, post_id, wpUploaderInit, deleteUserSetting, setUserSetting, getUserSetting, shortform */
2 var topWin = window.dialogArguments || opener || parent || top, uploader, uploader_init;
4 // progress and success handlers for media multi uploads
5 function fileQueued(fileObj) {
6 // Get rid of unused form
7 jQuery('.media-blank').remove();
9 var items = jQuery('#media-items').children(), postid = post_id || 0;
11 // Collapse a single item
12 if ( items.length == 1 ) {
13 items.removeClass('open').find('.slidetoggle').slideUp(200);
15 // Create a progress bar containing the filename
16 jQuery('<div class="media-item">')
17 .attr( 'id', 'media-item-' + fileObj.id )
18 .addClass('child-of-' + postid)
19 .append('<div class="progress"><div class="percent">0%</div><div class="bar"></div></div>',
20 jQuery('<div class="filename original">').text( ' ' + fileObj.name ))
21 .appendTo( jQuery('#media-items' ) );
24 jQuery('#insert-gallery').prop('disabled', true);
27 function uploadStart() {
29 if ( typeof topWin.tb_remove != 'undefined' )
30 topWin.jQuery('#TB_overlay').unbind('click', topWin.tb_remove);
36 function uploadProgress(up, file) {
37 var item = jQuery('#media-item-' + file.id);
39 jQuery('.bar', item).width( (200 * file.loaded) / file.size );
40 jQuery('.percent', item).html( file.percent + '%' );
43 // check to see if a large file failed to upload
44 function fileUploading( up, file ) {
45 var hundredmb = 100 * 1024 * 1024,
46 max = parseInt( up.settings.max_file_size, 10 );
48 if ( max > hundredmb && file.size > hundredmb ) {
49 setTimeout( function() {
50 if ( file.status < 3 && file.loaded === 0 ) { // not uploading
51 wpFileError( file, pluploadL10n.big_upload_failed.replace( '%1$s', '<a class="uploader-html" href="#">' ).replace( '%2$s', '</a>' ) );
52 up.stop(); // stops the whole queue
53 up.removeFile( file );
54 up.start(); // restart the queue
56 }, 10000 ); // wait for 10 sec. for the file to start uploading
60 function updateMediaForm() {
61 var items = jQuery('#media-items').children();
63 // Just one file, no need for collapsible part
64 if ( items.length == 1 ) {
65 items.addClass('open').find('.slidetoggle').show();
66 jQuery('.insert-gallery').hide();
67 } else if ( items.length > 1 ) {
68 items.removeClass('open');
69 // Only show Gallery/Playlist buttons when there are at least two files.
70 jQuery('.insert-gallery').show();
73 // Only show Save buttons when there is at least one file.
74 if ( items.not('.media-blank').length > 0 )
75 jQuery('.savebutton').show();
77 jQuery('.savebutton').hide();
80 function uploadSuccess(fileObj, serverData) {
81 var item = jQuery('#media-item-' + fileObj.id);
83 // on success serverData should be numeric, fix bug in html4 runtime returning the serverData wrapped in a <pre> tag
84 serverData = serverData.replace(/^<pre>(\d+)<\/pre>$/, '$1');
86 // if async-upload returned an error message, place it in the media item div and return
87 if ( serverData.match(/media-upload-error|error-div/) ) {
88 item.html(serverData);
91 jQuery('.percent', item).html( pluploadL10n.crunching );
94 prepareMediaItem(fileObj, serverData);
97 // Increment the counter.
98 if ( post_id && item.hasClass('child-of-' + post_id) )
99 jQuery('#attachments-count').text(1 * jQuery('#attachments-count').text() + 1);
102 function setResize( arg ) {
104 if ( window.resize_width && window.resize_height ) {
105 uploader.settings.resize = {
107 width: window.resize_width,
108 height: window.resize_height,
112 uploader.settings.multipart_params.image_resize = true;
115 delete( uploader.settings.multipart_params.image_resize );
119 function prepareMediaItem(fileObj, serverData) {
120 var f = ( typeof shortform == 'undefined' ) ? 1 : 2, item = jQuery('#media-item-' + fileObj.id);
121 if ( f == 2 && shortform > 2 )
125 if ( typeof topWin.tb_remove != 'undefined' )
126 topWin.jQuery('#TB_overlay').click(topWin.tb_remove);
129 if ( isNaN(serverData) || !serverData ) { // Old style: Append the HTML returned by the server -- thumbnail and form inputs
130 item.append(serverData);
131 prepareMediaItemInit(fileObj);
132 } else { // New style: server data is just the attachment ID, fetch the thumbnail and form html from the server
133 item.load('async-upload.php', {attachment_id:serverData, fetch:f}, function(){prepareMediaItemInit(fileObj);updateMediaForm();});
137 function prepareMediaItemInit(fileObj) {
138 var item = jQuery('#media-item-' + fileObj.id);
139 // Clone the thumbnail as a "pinkynail" -- a tiny image to the left of the filename
140 jQuery('.thumbnail', item).clone().attr('class', 'pinkynail toggle').prependTo(item);
142 // Replace the original filename with the new (unique) one assigned during upload
143 jQuery('.filename.original', item).replaceWith( jQuery('.filename.new', item) );
145 // Bind AJAX to the new Delete button
146 jQuery('a.delete', item).click(function(){
147 // Tell the server to delete it. TODO: handle exceptions
151 success: deleteSuccess,
155 id : this.id.replace(/[^0-9]/g, ''),
156 action : 'trash-post',
157 _ajax_nonce : this.href.replace(/^.*wpnonce=/,'')
163 // Bind AJAX to the new Undo button
164 jQuery('a.undo', item).click(function(){
165 // Tell the server to untrash it. TODO: handle exceptions
171 id : this.id.replace(/[^0-9]/g,''),
172 action: 'untrash-post',
173 _ajax_nonce: this.href.replace(/^.*wpnonce=/,'')
175 success: function( ){
177 item = jQuery('#media-item-' + fileObj.id);
179 if ( type = jQuery('#type-of-' + fileObj.id).val() )
180 jQuery('#' + type + '-counter').text(jQuery('#' + type + '-counter').text()-0+1);
182 if ( post_id && item.hasClass('child-of-'+post_id) )
183 jQuery('#attachments-count').text(jQuery('#attachments-count').text()-0+1);
185 jQuery('.filename .trashnotice', item).remove();
186 jQuery('.filename .title', item).css('font-weight','normal');
187 jQuery('a.undo', item).addClass('hidden');
188 jQuery('.menu_order_input', item).show();
189 item.css( {backgroundColor:'#ceb'} ).animate( {backgroundColor: '#fff'}, { queue: false, duration: 500, complete: function(){ jQuery(this).css({backgroundColor:''}); } }).removeClass('undo');
195 // Open this item if it says to start open (e.g. to display an error)
196 jQuery('#media-item-' + fileObj.id + '.startopen').removeClass('startopen').addClass('open').find('slidetoggle').fadeIn();
199 // generic error message
200 function wpQueueError(message) {
201 jQuery('#media-upload-error').show().html( '<div class="error"><p>' + message + '</p></div>' );
204 // file-specific error messages
205 function wpFileError(fileObj, message) {
206 itemAjaxError(fileObj.id, message);
209 function itemAjaxError(id, message) {
210 var item = jQuery('#media-item-' + id), filename = item.find('.filename').text(), last_err = item.data('last-err');
212 if ( last_err == id ) // prevent firing an error for the same file twice
215 item.html('<div class="error-div">' +
216 '<a class="dismiss" href="#">' + pluploadL10n.dismiss + '</a>' +
217 '<strong>' + pluploadL10n.error_uploading.replace('%s', jQuery.trim(filename)) + '</strong> ' +
219 '</div>').data('last-err', id);
222 function deleteSuccess(data) {
225 return itemAjaxError(this.id, 'You do not have permission. Has your session expired?');
228 return itemAjaxError(this.id, 'Could not be deleted. Has it been deleted already?');
231 item = jQuery('#media-item-' + id);
233 // Decrement the counters.
234 if ( type = jQuery('#type-of-' + id).val() )
235 jQuery('#' + type + '-counter').text( jQuery('#' + type + '-counter').text() - 1 );
237 if ( post_id && item.hasClass('child-of-'+post_id) )
238 jQuery('#attachments-count').text( jQuery('#attachments-count').text() - 1 );
240 if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) {
241 jQuery('.toggle').toggle();
242 jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden');
246 jQuery('.toggle', item).toggle();
247 jQuery('.slidetoggle', item).slideUp(200).siblings().removeClass('hidden');
248 item.css( {backgroundColor:'#faa'} ).animate( {backgroundColor:'#f4f4f4'}, {queue:false, duration:500} ).addClass('undo');
250 jQuery('.filename:empty', item).remove();
251 jQuery('.filename .title', item).css('font-weight','bold');
252 jQuery('.filename', item).append('<span class="trashnotice"> ' + pluploadL10n.deleted + ' </span>').siblings('a.toggle').hide();
253 jQuery('.filename', item).append( jQuery('a.undo', item).removeClass('hidden') );
254 jQuery('.menu_order_input', item).hide();
259 function deleteError() {
263 function uploadComplete() {
264 jQuery('#insert-gallery').prop('disabled', false);
267 function switchUploader(s) {
269 deleteUserSetting('uploader');
270 jQuery('.media-upload-form').removeClass('html-uploader');
272 if ( typeof(uploader) == 'object' )
275 setUserSetting('uploader', '1'); // 1 == html uploader
276 jQuery('.media-upload-form').addClass('html-uploader');
280 function uploadError(fileObj, errorCode, message, uploader) {
281 var hundredmb = 100 * 1024 * 1024, max;
284 case plupload.FAILED:
285 wpFileError(fileObj, pluploadL10n.upload_failed);
287 case plupload.FILE_EXTENSION_ERROR:
288 wpFileError(fileObj, pluploadL10n.invalid_filetype);
290 case plupload.FILE_SIZE_ERROR:
291 uploadSizeError(uploader, fileObj);
293 case plupload.IMAGE_FORMAT_ERROR:
294 wpFileError(fileObj, pluploadL10n.not_an_image);
296 case plupload.IMAGE_MEMORY_ERROR:
297 wpFileError(fileObj, pluploadL10n.image_memory_exceeded);
299 case plupload.IMAGE_DIMENSIONS_ERROR:
300 wpFileError(fileObj, pluploadL10n.image_dimensions_exceeded);
302 case plupload.GENERIC_ERROR:
303 wpQueueError(pluploadL10n.upload_failed);
305 case plupload.IO_ERROR:
306 max = parseInt( uploader.settings.filters.max_file_size, 10 );
308 if ( max > hundredmb && fileObj.size > hundredmb )
309 wpFileError( fileObj, pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>') );
311 wpQueueError(pluploadL10n.io_error);
313 case plupload.HTTP_ERROR:
314 wpQueueError(pluploadL10n.http_error);
316 case plupload.INIT_ERROR:
317 jQuery('.media-upload-form').addClass('html-uploader');
319 case plupload.SECURITY_ERROR:
320 wpQueueError(pluploadL10n.security_error);
322 /* case plupload.UPLOAD_ERROR.UPLOAD_STOPPED:
323 case plupload.UPLOAD_ERROR.FILE_CANCELLED:
324 jQuery('#media-item-' + fileObj.id).remove();
327 wpFileError(fileObj, pluploadL10n.default_error);
331 function uploadSizeError( up, file, over100mb ) {
335 message = pluploadL10n.big_upload_queued.replace('%s', file.name) + ' ' + pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>');
337 message = pluploadL10n.file_exceeds_size_limit.replace('%s', file.name);
339 jQuery('#media-items').append('<div id="media-item-' + file.id + '" class="media-item error"><p>' + message + '</p></div>');
343 jQuery(document).ready(function($){
344 $('.media-upload-form').bind('click.uploader', function(e) {
345 var target = $(e.target), tr, c;
347 if ( target.is('input[type="radio"]') ) { // remember the last used image size and alignment
348 tr = target.closest('tr');
350 if ( tr.hasClass('align') )
351 setUserSetting('align', target.val());
352 else if ( tr.hasClass('image-size') )
353 setUserSetting('imgsize', target.val());
355 } else if ( target.is('button.button') ) { // remember the last used image link url
356 c = e.target.className || '';
357 c = c.match(/url([^ '"]+)/);
360 setUserSetting('urlbutton', c[1]);
361 target.siblings('.urlfield').val( target.data('link-url') );
363 } else if ( target.is('a.dismiss') ) {
364 target.parents('.media-item').fadeOut(200, function(){
367 } else if ( target.is('.upload-flash-bypass a') || target.is('a.uploader-html') ) { // switch uploader to html4
368 $('#media-items, p.submit, span.big-file-warning').css('display', 'none');
371 } else if ( target.is('.upload-html-bypass a') ) { // switch uploader to multi-file
372 $('#media-items, p.submit, span.big-file-warning').css('display', '');
375 } else if ( target.is('a.describe-toggle-on') ) { // Show
376 target.parent().addClass('open');
377 target.siblings('.slidetoggle').fadeIn(250, function(){
378 var S = $(window).scrollTop(), H = $(window).height(), top = $(this).offset().top, h = $(this).height(), b, B;
380 if ( H && top && h ) {
385 if ( b - B < top - S )
386 window.scrollBy(0, (b - B) + 10);
388 window.scrollBy(0, top - S - 40);
393 } else if ( target.is('a.describe-toggle-off') ) { // Hide
394 target.siblings('.slidetoggle').fadeOut(250, function(){
395 target.parent().removeClass('open');
401 // init and set the uploader
402 uploader_init = function() {
403 var isIE = navigator.userAgent.indexOf('Trident/') != -1 || navigator.userAgent.indexOf('MSIE ') != -1;
405 // Make sure flash sends cookies (seems in IE it does whitout switching to urlstream mode)
406 if ( ! isIE && 'flash' === plupload.predictRuntime( wpUploaderInit ) &&
407 ( ! wpUploaderInit.required_features || ! wpUploaderInit.required_features.hasOwnProperty( 'send_binary_string' ) ) ) {
409 wpUploaderInit.required_features = wpUploaderInit.required_features || {};
410 wpUploaderInit.required_features.send_binary_string = true;
413 uploader = new plupload.Uploader(wpUploaderInit);
415 $('#image_resize').bind('change', function() {
416 var arg = $(this).prop('checked');
421 setUserSetting('upload_resize', '1');
423 deleteUserSetting('upload_resize');
426 uploader.bind('Init', function(up) {
427 var uploaddiv = $('#plupload-upload-ui');
429 setResize( getUserSetting('upload_resize', false) );
431 if ( up.features.dragdrop && ! $(document.body).hasClass('mobile') ) {
432 uploaddiv.addClass('drag-drop');
433 $('#drag-drop-area').bind('dragover.wp-uploader', function(){ // dragenter doesn't fire right :(
434 uploaddiv.addClass('drag-over');
435 }).bind('dragleave.wp-uploader, drop.wp-uploader', function(){
436 uploaddiv.removeClass('drag-over');
439 uploaddiv.removeClass('drag-drop');
440 $('#drag-drop-area').unbind('.wp-uploader');
443 if ( up.runtime === 'html4' ) {
444 $('.upload-flash-bypass').hide();
450 uploader.bind('FilesAdded', function( up, files ) {
451 $('#media-upload-error').html('');
454 plupload.each( files, function( file ) {
462 uploader.bind('UploadFile', function(up, file) {
463 fileUploading(up, file);
466 uploader.bind('UploadProgress', function(up, file) {
467 uploadProgress(up, file);
470 uploader.bind('Error', function(up, err) {
471 uploadError(err.file, err.code, err.message, up);
475 uploader.bind('FileUploaded', function(up, file, response) {
476 uploadSuccess(file, response.response);
479 uploader.bind('UploadComplete', function() {
484 if ( typeof(wpUploaderInit) == 'object' ) {