]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/js/media-views.js
WordPress 4.1
[autoinstalls/wordpress.git] / wp-includes / js / media-views.js
1 /* global _wpMediaViewsL10n, confirm, getUserSetting, setUserSetting */
2 ( function( $, _ ) {
3         var l10n,
4                 media = wp.media,
5                 isTouchDevice = ( 'ontouchend' in document );
6
7         // Link any localized strings.
8         l10n = media.view.l10n = typeof _wpMediaViewsL10n === 'undefined' ? {} : _wpMediaViewsL10n;
9
10         // Link any settings.
11         media.view.settings = l10n.settings || {};
12         delete l10n.settings;
13
14         // Copy the `post` setting over to the model settings.
15         media.model.settings.post = media.view.settings.post;
16
17         // Check if the browser supports CSS 3.0 transitions
18         $.support.transition = (function(){
19                 var style = document.documentElement.style,
20                         transitions = {
21                                 WebkitTransition: 'webkitTransitionEnd',
22                                 MozTransition:    'transitionend',
23                                 OTransition:      'oTransitionEnd otransitionend',
24                                 transition:       'transitionend'
25                         }, transition;
26
27                 transition = _.find( _.keys( transitions ), function( transition ) {
28                         return ! _.isUndefined( style[ transition ] );
29                 });
30
31                 return transition && {
32                         end: transitions[ transition ]
33                 };
34         }());
35
36         /**
37          * A shared event bus used to provide events into
38          * the media workflows that 3rd-party devs can use to hook
39          * in.
40          */
41         media.events = _.extend( {}, Backbone.Events );
42
43         /**
44          * Makes it easier to bind events using transitions.
45          *
46          * @param {string} selector
47          * @param {Number} sensitivity
48          * @returns {Promise}
49          */
50         media.transition = function( selector, sensitivity ) {
51                 var deferred = $.Deferred();
52
53                 sensitivity = sensitivity || 2000;
54
55                 if ( $.support.transition ) {
56                         if ( ! (selector instanceof $) ) {
57                                 selector = $( selector );
58                         }
59
60                         // Resolve the deferred when the first element finishes animating.
61                         selector.first().one( $.support.transition.end, deferred.resolve );
62
63                         // Just in case the event doesn't trigger, fire a callback.
64                         _.delay( deferred.resolve, sensitivity );
65
66                 // Otherwise, execute on the spot.
67                 } else {
68                         deferred.resolve();
69                 }
70
71                 return deferred.promise();
72         };
73
74         /**
75          * wp.media.controller.Region
76          *
77          * A region is a persistent application layout area.
78          *
79          * A region assumes one mode at any time, and can be switched to another.
80          *
81          * When mode changes, events are triggered on the region's parent view.
82          * The parent view will listen to specific events and fill the region with an
83          * appropriate view depending on mode. For example, a frame listens for the
84          * 'browse' mode t be activated on the 'content' view and then fills the region
85          * with an AttachmentsBrowser view.
86          *
87          * @class
88          *
89          * @param {object}        options          Options hash for the region.
90          * @param {string}        options.id       Unique identifier for the region.
91          * @param {Backbone.View} options.view     A parent view the region exists within.
92          * @param {string}        options.selector jQuery selector for the region within the parent view.
93          */
94         media.controller.Region = function( options ) {
95                 _.extend( this, _.pick( options || {}, 'id', 'view', 'selector' ) );
96         };
97
98         // Use Backbone's self-propagating `extend` inheritance method.
99         media.controller.Region.extend = Backbone.Model.extend;
100
101         _.extend( media.controller.Region.prototype, {
102                 /**
103                  * Activate a mode.
104                  *
105                  * @since 3.5.0
106                  *
107                  * @param {string} mode
108                  *
109                  * @fires this.view#{this.id}:activate:{this._mode}
110                  * @fires this.view#{this.id}:activate
111                  * @fires this.view#{this.id}:deactivate:{this._mode}
112                  * @fires this.view#{this.id}:deactivate
113                  *
114                  * @returns {wp.media.controller.Region} Returns itself to allow chaining.
115                  */
116                 mode: function( mode ) {
117                         if ( ! mode ) {
118                                 return this._mode;
119                         }
120                         // Bail if we're trying to change to the current mode.
121                         if ( mode === this._mode ) {
122                                 return this;
123                         }
124
125                         /**
126                          * Region mode deactivation event.
127                          *
128                          * @event this.view#{this.id}:deactivate:{this._mode}
129                          * @event this.view#{this.id}:deactivate
130                          */
131                         this.trigger('deactivate');
132
133                         this._mode = mode;
134                         this.render( mode );
135
136                         /**
137                          * Region mode activation event.
138                          *
139                          * @event this.view#{this.id}:activate:{this._mode}
140                          * @event this.view#{this.id}:activate
141                          */
142                         this.trigger('activate');
143                         return this;
144                 },
145                 /**
146                  * Render a mode.
147                  *
148                  * @since 3.5.0
149                  *
150                  * @param {string} mode
151                  *
152                  * @fires this.view#{this.id}:create:{this._mode}
153                  * @fires this.view#{this.id}:create
154                  * @fires this.view#{this.id}:render:{this._mode}
155                  * @fires this.view#{this.id}:render
156                  *
157                  * @returns {wp.media.controller.Region} Returns itself to allow chaining
158                  */
159                 render: function( mode ) {
160                         // If the mode isn't active, activate it.
161                         if ( mode && mode !== this._mode ) {
162                                 return this.mode( mode );
163                         }
164
165                         var set = { view: null },
166                                 view;
167
168                         /**
169                          * Create region view event.
170                          *
171                          * Region view creation takes place in an event callback on the frame.
172                          *
173                          * @event this.view#{this.id}:create:{this._mode}
174                          * @event this.view#{this.id}:create
175                          */
176                         this.trigger( 'create', set );
177                         view = set.view;
178
179                         /**
180                          * Render region view event.
181                          *
182                          * Region view creation takes place in an event callback on the frame.
183                          *
184                          * @event this.view#{this.id}:create:{this._mode}
185                          * @event this.view#{this.id}:create
186                          */
187                         this.trigger( 'render', view );
188                         if ( view ) {
189                                 this.set( view );
190                         }
191                         return this;
192                 },
193
194                 /**
195                  * Get the region's view.
196                  *
197                  * @since 3.5.0
198                  *
199                  * @returns {wp.media.View}
200                  */
201                 get: function() {
202                         return this.view.views.first( this.selector );
203                 },
204
205                 /**
206                  * Set the region's view as a subview of the frame.
207                  *
208                  * @since 3.5.0
209                  *
210                  * @param {Array|Object} views
211                  * @param {Object} [options={}]
212                  * @returns {wp.Backbone.Subviews} Subviews is returned to allow chaining
213                  */
214                 set: function( views, options ) {
215                         if ( options ) {
216                                 options.add = false;
217                         }
218                         return this.view.views.set( this.selector, views, options );
219                 },
220
221                 /**
222                  * Trigger regional view events on the frame.
223                  *
224                  * @since 3.5.0
225                  *
226                  * @param {string} event
227                  * @returns {undefined|wp.media.controller.Region} Returns itself to allow chaining.
228                  */
229                 trigger: function( event ) {
230                         var base, args;
231
232                         if ( ! this._mode ) {
233                                 return;
234                         }
235
236                         args = _.toArray( arguments );
237                         base = this.id + ':' + event;
238
239                         // Trigger `{this.id}:{event}:{this._mode}` event on the frame.
240                         args[0] = base + ':' + this._mode;
241                         this.view.trigger.apply( this.view, args );
242
243                         // Trigger `{this.id}:{event}` event on the frame.
244                         args[0] = base;
245                         this.view.trigger.apply( this.view, args );
246                         return this;
247                 }
248         });
249
250         /**
251          * wp.media.controller.StateMachine
252          *
253          * A state machine keeps track of state. It is in one state at a time,
254          * and can change from one state to another.
255          *
256          * States are stored as models in a Backbone collection.
257          *
258          * @since 3.5.0
259          *
260          * @class
261          * @augments Backbone.Model
262          * @mixin
263          * @mixes Backbone.Events
264          *
265          * @param {Array} states
266          */
267         media.controller.StateMachine = function( states ) {
268                 // @todo This is dead code. The states collection gets created in media.view.Frame._createStates.
269                 this.states = new Backbone.Collection( states );
270         };
271
272         // Use Backbone's self-propagating `extend` inheritance method.
273         media.controller.StateMachine.extend = Backbone.Model.extend;
274
275         _.extend( media.controller.StateMachine.prototype, Backbone.Events, {
276                 /**
277                  * Fetch a state.
278                  *
279                  * If no `id` is provided, returns the active state.
280                  *
281                  * Implicitly creates states.
282                  *
283                  * Ensure that the `states` collection exists so the `StateMachine`
284                  *   can be used as a mixin.
285                  *
286                  * @since 3.5.0
287                  *
288                  * @param {string} id
289                  * @returns {wp.media.controller.State} Returns a State model
290                  *   from the StateMachine collection
291                  */
292                 state: function( id ) {
293                         this.states = this.states || new Backbone.Collection();
294
295                         // Default to the active state.
296                         id = id || this._state;
297
298                         if ( id && ! this.states.get( id ) ) {
299                                 this.states.add({ id: id });
300                         }
301                         return this.states.get( id );
302                 },
303
304                 /**
305                  * Sets the active state.
306                  *
307                  * Bail if we're trying to select the current state, if we haven't
308                  * created the `states` collection, or are trying to select a state
309                  * that does not exist.
310                  *
311                  * @since 3.5.0
312                  *
313                  * @param {string} id
314                  *
315                  * @fires wp.media.controller.State#deactivate
316                  * @fires wp.media.controller.State#activate
317                  *
318                  * @returns {wp.media.controller.StateMachine} Returns itself to allow chaining
319                  */
320                 setState: function( id ) {
321                         var previous = this.state();
322
323                         if ( ( previous && id === previous.id ) || ! this.states || ! this.states.get( id ) ) {
324                                 return this;
325                         }
326
327                         if ( previous ) {
328                                 previous.trigger('deactivate');
329                                 this._lastState = previous.id;
330                         }
331
332                         this._state = id;
333                         this.state().trigger('activate');
334
335                         return this;
336                 },
337
338                 /**
339                  * Returns the previous active state.
340                  *
341                  * Call the `state()` method with no parameters to retrieve the current
342                  * active state.
343                  *
344                  * @since 3.5.0
345                  *
346                  * @returns {wp.media.controller.State} Returns a State model
347                  *    from the StateMachine collection
348                  */
349                 lastState: function() {
350                         if ( this._lastState ) {
351                                 return this.state( this._lastState );
352                         }
353                 }
354         });
355
356         // Map all event binding and triggering on a StateMachine to its `states` collection.
357         _.each([ 'on', 'off', 'trigger' ], function( method ) {
358                 /**
359                  * @returns {wp.media.controller.StateMachine} Returns itself to allow chaining.
360                  */
361                 media.controller.StateMachine.prototype[ method ] = function() {
362                         // Ensure that the `states` collection exists so the `StateMachine`
363                         // can be used as a mixin.
364                         this.states = this.states || new Backbone.Collection();
365                         // Forward the method to the `states` collection.
366                         this.states[ method ].apply( this.states, arguments );
367                         return this;
368                 };
369         });
370
371         /**
372          * wp.media.controller.State
373          *
374          * A state is a step in a workflow that when set will trigger the controllers
375          * for the regions to be updated as specified in the frame.
376          *
377          * A state has an event-driven lifecycle:
378          *
379          *     'ready'      triggers when a state is added to a state machine's collection.
380          *     'activate'   triggers when a state is activated by a state machine.
381          *     'deactivate' triggers when a state is deactivated by a state machine.
382          *     'reset'      is not triggered automatically. It should be invoked by the
383          *                  proper controller to reset the state to its default.
384          *
385          * @class
386          * @augments Backbone.Model
387          */
388         media.controller.State = Backbone.Model.extend({
389                 /**
390                  * Constructor.
391                  *
392                  * @since 3.5.0
393                  */
394                 constructor: function() {
395                         this.on( 'activate', this._preActivate, this );
396                         this.on( 'activate', this.activate, this );
397                         this.on( 'activate', this._postActivate, this );
398                         this.on( 'deactivate', this._deactivate, this );
399                         this.on( 'deactivate', this.deactivate, this );
400                         this.on( 'reset', this.reset, this );
401                         this.on( 'ready', this._ready, this );
402                         this.on( 'ready', this.ready, this );
403                         /**
404                          * Call parent constructor with passed arguments
405                          */
406                         Backbone.Model.apply( this, arguments );
407                         this.on( 'change:menu', this._updateMenu, this );
408                 },
409                 /**
410                  * Ready event callback.
411                  *
412                  * @abstract
413                  * @since 3.5.0
414                  */
415                 ready: function() {},
416
417                 /**
418                  * Activate event callback.
419                  *
420                  * @abstract
421                  * @since 3.5.0
422                  */
423                 activate: function() {},
424
425                 /**
426                  * Deactivate event callback.
427                  *
428                  * @abstract
429                  * @since 3.5.0
430                  */
431                 deactivate: function() {},
432
433                 /**
434                  * Reset event callback.
435                  *
436                  * @abstract
437                  * @since 3.5.0
438                  */
439                 reset: function() {},
440
441                 /**
442                  * @access private
443                  * @since 3.5.0
444                  */
445                 _ready: function() {
446                         this._updateMenu();
447                 },
448
449                 /**
450                  * @access private
451                  * @since 3.5.0
452                 */
453                 _preActivate: function() {
454                         this.active = true;
455                 },
456
457                 /**
458                  * @access private
459                  * @since 3.5.0
460                  */
461                 _postActivate: function() {
462                         this.on( 'change:menu', this._menu, this );
463                         this.on( 'change:titleMode', this._title, this );
464                         this.on( 'change:content', this._content, this );
465                         this.on( 'change:toolbar', this._toolbar, this );
466
467                         this.frame.on( 'title:render:default', this._renderTitle, this );
468
469                         this._title();
470                         this._menu();
471                         this._toolbar();
472                         this._content();
473                         this._router();
474                 },
475
476                 /**
477                  * @access private
478                  * @since 3.5.0
479                  */
480                 _deactivate: function() {
481                         this.active = false;
482
483                         this.frame.off( 'title:render:default', this._renderTitle, this );
484
485                         this.off( 'change:menu', this._menu, this );
486                         this.off( 'change:titleMode', this._title, this );
487                         this.off( 'change:content', this._content, this );
488                         this.off( 'change:toolbar', this._toolbar, this );
489                 },
490
491                 /**
492                  * @access private
493                  * @since 3.5.0
494                  */
495                 _title: function() {
496                         this.frame.title.render( this.get('titleMode') || 'default' );
497                 },
498
499                 /**
500                  * @access private
501                  * @since 3.5.0
502                  */
503                 _renderTitle: function( view ) {
504                         view.$el.text( this.get('title') || '' );
505                 },
506
507                 /**
508                  * @access private
509                  * @since 3.5.0
510                  */
511                 _router: function() {
512                         var router = this.frame.router,
513                                 mode = this.get('router'),
514                                 view;
515
516                         this.frame.$el.toggleClass( 'hide-router', ! mode );
517                         if ( ! mode ) {
518                                 return;
519                         }
520
521                         this.frame.router.render( mode );
522
523                         view = router.get();
524                         if ( view && view.select ) {
525                                 view.select( this.frame.content.mode() );
526                         }
527                 },
528
529                 /**
530                  * @access private
531                  * @since 3.5.0
532                  */
533                 _menu: function() {
534                         var menu = this.frame.menu,
535                                 mode = this.get('menu'),
536                                 view;
537
538                         this.frame.$el.toggleClass( 'hide-menu', ! mode );
539                         if ( ! mode ) {
540                                 return;
541                         }
542
543                         menu.mode( mode );
544
545                         view = menu.get();
546                         if ( view && view.select ) {
547                                 view.select( this.id );
548                         }
549                 },
550
551                 /**
552                  * @access private
553                  * @since 3.5.0
554                  */
555                 _updateMenu: function() {
556                         var previous = this.previous('menu'),
557                                 menu = this.get('menu');
558
559                         if ( previous ) {
560                                 this.frame.off( 'menu:render:' + previous, this._renderMenu, this );
561                         }
562
563                         if ( menu ) {
564                                 this.frame.on( 'menu:render:' + menu, this._renderMenu, this );
565                         }
566                 },
567
568                 /**
569                  * Create a view in the media menu for the state.
570                  *
571                  * @access private
572                  * @since 3.5.0
573                  *
574                  * @param {media.view.Menu} view The menu view.
575                  */
576                 _renderMenu: function( view ) {
577                         var menuItem = this.get('menuItem'),
578                                 title = this.get('title'),
579                                 priority = this.get('priority');
580
581                         if ( ! menuItem && title ) {
582                                 menuItem = { text: title };
583
584                                 if ( priority ) {
585                                         menuItem.priority = priority;
586                                 }
587                         }
588
589                         if ( ! menuItem ) {
590                                 return;
591                         }
592
593                         view.set( this.id, menuItem );
594                 }
595         });
596
597         _.each(['toolbar','content'], function( region ) {
598                 /**
599                  * @access private
600                  */
601                 media.controller.State.prototype[ '_' + region ] = function() {
602                         var mode = this.get( region );
603                         if ( mode ) {
604                                 this.frame[ region ].render( mode );
605                         }
606                 };
607         });
608
609         /**
610          * wp.media.selectionSync
611          *
612          * Sync an attachments selection in a state with another state.
613          *
614          * Allows for selecting multiple images in the Insert Media workflow, and then
615          * switching to the Insert Gallery workflow while preserving the attachments selection.
616          *
617          * @mixin
618          */
619         media.selectionSync = {
620                 /**
621                  * @since 3.5.0
622                  */
623                 syncSelection: function() {
624                         var selection = this.get('selection'),
625                                 manager = this.frame._selection;
626
627                         if ( ! this.get('syncSelection') || ! manager || ! selection ) {
628                                 return;
629                         }
630
631                         // If the selection supports multiple items, validate the stored
632                         // attachments based on the new selection's conditions. Record
633                         // the attachments that are not included; we'll maintain a
634                         // reference to those. Other attachments are considered in flux.
635                         if ( selection.multiple ) {
636                                 selection.reset( [], { silent: true });
637                                 selection.validateAll( manager.attachments );
638                                 manager.difference = _.difference( manager.attachments.models, selection.models );
639                         }
640
641                         // Sync the selection's single item with the master.
642                         selection.single( manager.single );
643                 },
644
645                 /**
646                  * Record the currently active attachments, which is a combination
647                  * of the selection's attachments and the set of selected
648                  * attachments that this specific selection considered invalid.
649                  * Reset the difference and record the single attachment.
650                  *
651                  * @since 3.5.0
652                  */
653                 recordSelection: function() {
654                         var selection = this.get('selection'),
655                                 manager = this.frame._selection;
656
657                         if ( ! this.get('syncSelection') || ! manager || ! selection ) {
658                                 return;
659                         }
660
661                         if ( selection.multiple ) {
662                                 manager.attachments.reset( selection.toArray().concat( manager.difference ) );
663                                 manager.difference = [];
664                         } else {
665                                 manager.attachments.add( selection.toArray() );
666                         }
667
668                         manager.single = selection._single;
669                 }
670         };
671
672         /**
673          * wp.media.controller.Library
674          *
675          * A state for choosing an attachment or group of attachments from the media library.
676          *
677          * @class
678          * @augments wp.media.controller.State
679          * @augments Backbone.Model
680          * @mixes media.selectionSync
681          *
682          * @param {object}                          [attributes]                         The attributes hash passed to the state.
683          * @param {string}                          [attributes.id=library]              Unique identifier.
684          * @param {string}                          [attributes.title=Media library]     Title for the state. Displays in the media menu and the frame's title region.
685          * @param {wp.media.model.Attachments}      [attributes.library]                 The attachments collection to browse.
686          *                                                                               If one is not supplied, a collection of all attachments will be created.
687          * @param {wp.media.model.Selection|object} [attributes.selection]               A collection to contain attachment selections within the state.
688          *                                                                               If the 'selection' attribute is a plain JS object,
689          *                                                                               a Selection will be created using its values as the selection instance's `props` model.
690          *                                                                               Otherwise, it will copy the library's `props` model.
691          * @param {boolean}                         [attributes.multiple=false]          Whether multi-select is enabled.
692          * @param {string}                          [attributes.content=upload]          Initial mode for the content region.
693          *                                                                               Overridden by persistent user setting if 'contentUserSetting' is true.
694          * @param {string}                          [attributes.menu=default]            Initial mode for the menu region.
695          * @param {string}                          [attributes.router=browse]           Initial mode for the router region.
696          * @param {string}                          [attributes.toolbar=select]          Initial mode for the toolbar region.
697          * @param {boolean}                         [attributes.searchable=true]         Whether the library is searchable.
698          * @param {boolean|string}                  [attributes.filterable=false]        Whether the library is filterable, and if so what filters should be shown.
699          *                                                                               Accepts 'all', 'uploaded', or 'unattached'.
700          * @param {boolean}                         [attributes.sortable=true]           Whether the Attachments should be sortable. Depends on the orderby property being set to menuOrder on the attachments collection.
701          * @param {boolean}                         [attributes.autoSelect=true]         Whether an uploaded attachment should be automatically added to the selection.
702          * @param {boolean}                         [attributes.describe=false]          Whether to offer UI to describe attachments - e.g. captioning images in a gallery.
703          * @param {boolean}                         [attributes.contentUserSetting=true] Whether the content region's mode should be set and persisted per user.
704          * @param {boolean}                         [attributes.syncSelection=true]      Whether the Attachments selection should be persisted from the last state.
705          */
706         media.controller.Library = media.controller.State.extend({
707                 defaults: {
708                         id:                 'library',
709                         title:              l10n.mediaLibraryTitle,
710                         multiple:           false,
711                         content:            'upload',
712                         menu:               'default',
713                         router:             'browse',
714                         toolbar:            'select',
715                         searchable:         true,
716                         filterable:         false,
717                         sortable:           true,
718                         autoSelect:         true,
719                         describe:           false,
720                         contentUserSetting: true,
721                         syncSelection:      true
722                 },
723
724                 /**
725                  * If a library isn't provided, query all media items.
726                  * If a selection instance isn't provided, create one.
727                  *
728                  * @since 3.5.0
729                  */
730                 initialize: function() {
731                         var selection = this.get('selection'),
732                                 props;
733
734                         if ( ! this.get('library') ) {
735                                 this.set( 'library', media.query() );
736                         }
737
738                         if ( ! (selection instanceof media.model.Selection) ) {
739                                 props = selection;
740
741                                 if ( ! props ) {
742                                         props = this.get('library').props.toJSON();
743                                         props = _.omit( props, 'orderby', 'query' );
744                                 }
745
746                                 this.set( 'selection', new media.model.Selection( null, {
747                                         multiple: this.get('multiple'),
748                                         props: props
749                                 }) );
750                         }
751
752                         this.resetDisplays();
753                 },
754
755                 /**
756                  * @since 3.5.0
757                  */
758                 activate: function() {
759                         this.syncSelection();
760
761                         wp.Uploader.queue.on( 'add', this.uploading, this );
762
763                         this.get('selection').on( 'add remove reset', this.refreshContent, this );
764
765                         if ( this.get( 'router' ) && this.get('contentUserSetting') ) {
766                                 this.frame.on( 'content:activate', this.saveContentMode, this );
767                                 this.set( 'content', getUserSetting( 'libraryContent', this.get('content') ) );
768                         }
769                 },
770
771                 /**
772                  * @since 3.5.0
773                  */
774                 deactivate: function() {
775                         this.recordSelection();
776
777                         this.frame.off( 'content:activate', this.saveContentMode, this );
778
779                         // Unbind all event handlers that use this state as the context
780                         // from the selection.
781                         this.get('selection').off( null, null, this );
782
783                         wp.Uploader.queue.off( null, null, this );
784                 },
785
786                 /**
787                  * Reset the library to its initial state.
788                  *
789                  * @since 3.5.0
790                  */
791                 reset: function() {
792                         this.get('selection').reset();
793                         this.resetDisplays();
794                         this.refreshContent();
795                 },
796
797                 /**
798                  * Reset the attachment display settings defaults to the site options.
799                  *
800                  * If site options don't define them, fall back to a persistent user setting.
801                  *
802                  * @since 3.5.0
803                  */
804                 resetDisplays: function() {
805                         var defaultProps = media.view.settings.defaultProps;
806                         this._displays = [];
807                         this._defaultDisplaySettings = {
808                                 align: defaultProps.align || getUserSetting( 'align', 'none' ),
809                                 size:  defaultProps.size  || getUserSetting( 'imgsize', 'medium' ),
810                                 link:  defaultProps.link  || getUserSetting( 'urlbutton', 'file' )
811                         };
812                 },
813
814                 /**
815                  * Create a model to represent display settings (alignment, etc.) for an attachment.
816                  *
817                  * @since 3.5.0
818                  *
819                  * @param {wp.media.model.Attachment} attachment
820                  * @returns {Backbone.Model}
821                  */
822                 display: function( attachment ) {
823                         var displays = this._displays;
824
825                         if ( ! displays[ attachment.cid ] ) {
826                                 displays[ attachment.cid ] = new Backbone.Model( this.defaultDisplaySettings( attachment ) );
827                         }
828                         return displays[ attachment.cid ];
829                 },
830
831                 /**
832                  * Given an attachment, create attachment display settings properties.
833                  *
834                  * @since 3.6.0
835                  *
836                  * @param {wp.media.model.Attachment} attachment
837                  * @returns {Object}
838                  */
839                 defaultDisplaySettings: function( attachment ) {
840                         var settings = this._defaultDisplaySettings;
841                         if ( settings.canEmbed = this.canEmbed( attachment ) ) {
842                                 settings.link = 'embed';
843                         }
844                         return settings;
845                 },
846
847                 /**
848                  * Whether an attachment can be embedded (audio or video).
849                  *
850                  * @since 3.6.0
851                  *
852                  * @param {wp.media.model.Attachment} attachment
853                  * @returns {Boolean}
854                  */
855                 canEmbed: function( attachment ) {
856                         // If uploading, we know the filename but not the mime type.
857                         if ( ! attachment.get('uploading') ) {
858                                 var type = attachment.get('type');
859                                 if ( type !== 'audio' && type !== 'video' ) {
860                                         return false;
861                                 }
862                         }
863
864                         return _.contains( media.view.settings.embedExts, attachment.get('filename').split('.').pop() );
865                 },
866
867
868                 /**
869                  * If the state is active, no items are selected, and the current
870                  * content mode is not an option in the state's router (provided
871                  * the state has a router), reset the content mode to the default.
872                  *
873                  * @since 3.5.0
874                  */
875                 refreshContent: function() {
876                         var selection = this.get('selection'),
877                                 frame = this.frame,
878                                 router = frame.router.get(),
879                                 mode = frame.content.mode();
880
881                         if ( this.active && ! selection.length && router && ! router.get( mode ) ) {
882                                 this.frame.content.render( this.get('content') );
883                         }
884                 },
885
886                 /**
887                  * Callback handler when an attachment is uploaded.
888                  *
889                  * Switch to the Media Library if uploaded from the 'Upload Files' tab.
890                  *
891                  * Adds any uploading attachments to the selection.
892                  *
893                  * If the state only supports one attachment to be selected and multiple
894                  * attachments are uploaded, the last attachment in the upload queue will
895                  * be selected.
896                  *
897                  * @since 3.5.0
898                  *
899                  * @param {wp.media.model.Attachment} attachment
900                  */
901                 uploading: function( attachment ) {
902                         var content = this.frame.content;
903
904                         if ( 'upload' === content.mode() ) {
905                                 this.frame.content.mode('browse');
906                         }
907
908                         if ( this.get( 'autoSelect' ) ) {
909                                 this.get('selection').add( attachment );
910                                 this.frame.trigger( 'library:selection:add' );
911                         }
912                 },
913
914                 /**
915                  * Persist the mode of the content region as a user setting.
916                  *
917                  * @since 3.5.0
918                  */
919                 saveContentMode: function() {
920                         if ( 'browse' !== this.get('router') ) {
921                                 return;
922                         }
923
924                         var mode = this.frame.content.mode(),
925                                 view = this.frame.router.get();
926
927                         if ( view && view.get( mode ) ) {
928                                 setUserSetting( 'libraryContent', mode );
929                         }
930                 }
931         });
932
933         // Make selectionSync available on any Media Library state.
934         _.extend( media.controller.Library.prototype, media.selectionSync );
935
936         /**
937          * wp.media.controller.ImageDetails
938          *
939          * A state for editing the attachment display settings of an image that's been
940          * inserted into the editor.
941          *
942          * @class
943          * @augments wp.media.controller.State
944          * @augments Backbone.Model
945          *
946          * @param {object}                    [attributes]                       The attributes hash passed to the state.
947          * @param {string}                    [attributes.id=image-details]      Unique identifier.
948          * @param {string}                    [attributes.title=Image Details]   Title for the state. Displays in the frame's title region.
949          * @param {wp.media.model.Attachment} attributes.image                   The image's model.
950          * @param {string|false}              [attributes.content=image-details] Initial mode for the content region.
951          * @param {string|false}              [attributes.menu=false]            Initial mode for the menu region.
952          * @param {string|false}              [attributes.router=false]          Initial mode for the router region.
953          * @param {string|false}              [attributes.toolbar=image-details] Initial mode for the toolbar region.
954          * @param {boolean}                   [attributes.editing=false]         Unused.
955          * @param {int}                       [attributes.priority=60]           Unused.
956          *
957          * @todo This state inherits some defaults from media.controller.Library.prototype.defaults,
958          *       however this may not do anything.
959          */
960         media.controller.ImageDetails = media.controller.State.extend({
961                 defaults: _.defaults({
962                         id:       'image-details',
963                         title:    l10n.imageDetailsTitle,
964                         content:  'image-details',
965                         menu:     false,
966                         router:   false,
967                         toolbar:  'image-details',
968                         editing:  false,
969                         priority: 60
970                 }, media.controller.Library.prototype.defaults ),
971
972                 /**
973                  * @since 3.9.0
974                  *
975                  * @param options Attributes
976                  */
977                 initialize: function( options ) {
978                         this.image = options.image;
979                         media.controller.State.prototype.initialize.apply( this, arguments );
980                 },
981
982                 /**
983                  * @since 3.9.0
984                  */
985                 activate: function() {
986                         this.frame.modal.$el.addClass('image-details');
987                 }
988         });
989
990         /**
991          * wp.media.controller.GalleryEdit
992          *
993          * A state for editing a gallery's images and settings.
994          *
995          * @class
996          * @augments wp.media.controller.Library
997          * @augments wp.media.controller.State
998          * @augments Backbone.Model
999          *
1000          * @param {object}                     [attributes]                       The attributes hash passed to the state.
1001          * @param {string}                     [attributes.id=gallery-edit]       Unique identifier.
1002          * @param {string}                     [attributes.title=Edit Gallery]    Title for the state. Displays in the frame's title region.
1003          * @param {wp.media.model.Attachments} [attributes.library]               The collection of attachments in the gallery.
1004          *                                                                        If one is not supplied, an empty media.model.Selection collection is created.
1005          * @param {boolean}                    [attributes.multiple=false]        Whether multi-select is enabled.
1006          * @param {boolean}                    [attributes.searchable=false]      Whether the library is searchable.
1007          * @param {boolean}                    [attributes.sortable=true]         Whether the Attachments should be sortable. Depends on the orderby property being set to menuOrder on the attachments collection.
1008          * @param {string|false}               [attributes.content=browse]        Initial mode for the content region.
1009          * @param {string|false}               [attributes.toolbar=image-details] Initial mode for the toolbar region.
1010          * @param {boolean}                    [attributes.describe=true]         Whether to offer UI to describe attachments - e.g. captioning images in a gallery.
1011          * @param {boolean}                    [attributes.displaySettings=true]  Whether to show the attachment display settings interface.
1012          * @param {boolean}                    [attributes.dragInfo=true]         Whether to show instructional text about the attachments being sortable.
1013          * @param {int}                        [attributes.idealColumnWidth=170]  The ideal column width in pixels for attachments.
1014          * @param {boolean}                    [attributes.editing=false]         Whether the gallery is being created, or editing an existing instance.
1015          * @param {int}                        [attributes.priority=60]           The priority for the state link in the media menu.
1016          * @param {boolean}                    [attributes.syncSelection=false]   Whether the Attachments selection should be persisted from the last state.
1017          *                                                                        Defaults to false for this state, because the library passed in  *is* the selection.
1018          * @param {view}                       [attributes.AttachmentView]        The single `Attachment` view to be used in the `Attachments`.
1019          *                                                                        If none supplied, defaults to wp.media.view.Attachment.EditLibrary.
1020          */
1021         media.controller.GalleryEdit = media.controller.Library.extend({
1022                 defaults: {
1023                         id:               'gallery-edit',
1024                         title:            l10n.editGalleryTitle,
1025                         multiple:         false,
1026                         searchable:       false,
1027                         sortable:         true,
1028                         display:          false,
1029                         content:          'browse',
1030                         toolbar:          'gallery-edit',
1031                         describe:         true,
1032                         displaySettings:  true,
1033                         dragInfo:         true,
1034                         idealColumnWidth: 170,
1035                         editing:          false,
1036                         priority:         60,
1037                         syncSelection:    false
1038                 },
1039
1040                 /**
1041                  * @since 3.5.0
1042                  */
1043                 initialize: function() {
1044                         // If we haven't been provided a `library`, create a `Selection`.
1045                         if ( ! this.get('library') )
1046                                 this.set( 'library', new media.model.Selection() );
1047
1048                         // The single `Attachment` view to be used in the `Attachments` view.
1049                         if ( ! this.get('AttachmentView') )
1050                                 this.set( 'AttachmentView', media.view.Attachment.EditLibrary );
1051                         media.controller.Library.prototype.initialize.apply( this, arguments );
1052                 },
1053
1054                 /**
1055                  * @since 3.5.0
1056                  */
1057                 activate: function() {
1058                         var library = this.get('library');
1059
1060                         // Limit the library to images only.
1061                         library.props.set( 'type', 'image' );
1062
1063                         // Watch for uploaded attachments.
1064                         this.get('library').observe( wp.Uploader.queue );
1065
1066                         this.frame.on( 'content:render:browse', this.gallerySettings, this );
1067
1068                         media.controller.Library.prototype.activate.apply( this, arguments );
1069                 },
1070
1071                 /**
1072                  * @since 3.5.0
1073                  */
1074                 deactivate: function() {
1075                         // Stop watching for uploaded attachments.
1076                         this.get('library').unobserve( wp.Uploader.queue );
1077
1078                         this.frame.off( 'content:render:browse', this.gallerySettings, this );
1079
1080                         media.controller.Library.prototype.deactivate.apply( this, arguments );
1081                 },
1082
1083                 /**
1084                  * @since 3.5.0
1085                  *
1086                  * @param browser
1087                  */
1088                 gallerySettings: function( browser ) {
1089                         if ( ! this.get('displaySettings') ) {
1090                                 return;
1091                         }
1092
1093                         var library = this.get('library');
1094
1095                         if ( ! library || ! browser ) {
1096                                 return;
1097                         }
1098
1099                         library.gallery = library.gallery || new Backbone.Model();
1100
1101                         browser.sidebar.set({
1102                                 gallery: new media.view.Settings.Gallery({
1103                                         controller: this,
1104                                         model:      library.gallery,
1105                                         priority:   40
1106                                 })
1107                         });
1108
1109                         browser.toolbar.set( 'reverse', {
1110                                 text:     l10n.reverseOrder,
1111                                 priority: 80,
1112
1113                                 click: function() {
1114                                         library.reset( library.toArray().reverse() );
1115                                 }
1116                         });
1117                 }
1118         });
1119
1120         /**
1121          * A state for selecting more images to add to a gallery.
1122          *
1123          * @class
1124          * @augments wp.media.controller.Library
1125          * @augments wp.media.controller.State
1126          * @augments Backbone.Model
1127          *
1128          * @param {object}                     [attributes]                         The attributes hash passed to the state.
1129          * @param {string}                     [attributes.id=gallery-library]      Unique identifier.
1130          * @param {string}                     [attributes.title=Add to Gallery]    Title for the state. Displays in the frame's title region.
1131          * @param {boolean}                    [attributes.multiple=add]            Whether multi-select is enabled. @todo 'add' doesn't seem do anything special, and gets used as a boolean.
1132          * @param {wp.media.model.Attachments} [attributes.library]                 The attachments collection to browse.
1133          *                                                                          If one is not supplied, a collection of all images will be created.
1134          * @param {boolean|string}             [attributes.filterable=uploaded]     Whether the library is filterable, and if so what filters should be shown.
1135          *                                                                          Accepts 'all', 'uploaded', or 'unattached'.
1136          * @param {string}                     [attributes.menu=gallery]            Initial mode for the menu region.
1137          * @param {string}                     [attributes.content=upload]          Initial mode for the content region.
1138          *                                                                          Overridden by persistent user setting if 'contentUserSetting' is true.
1139          * @param {string}                     [attributes.router=browse]           Initial mode for the router region.
1140          * @param {string}                     [attributes.toolbar=gallery-add]     Initial mode for the toolbar region.
1141          * @param {boolean}                    [attributes.searchable=true]         Whether the library is searchable.
1142          * @param {boolean}                    [attributes.sortable=true]           Whether the Attachments should be sortable. Depends on the orderby property being set to menuOrder on the attachments collection.
1143          * @param {boolean}                    [attributes.autoSelect=true]         Whether an uploaded attachment should be automatically added to the selection.
1144          * @param {boolean}                    [attributes.contentUserSetting=true] Whether the content region's mode should be set and persisted per user.
1145          * @param {int}                        [attributes.priority=100]            The priority for the state link in the media menu.
1146          * @param {boolean}                    [attributes.syncSelection=false]     Whether the Attachments selection should be persisted from the last state.
1147          *                                                                          Defaults to false because for this state, because the library of the Edit Gallery state is the selection.
1148          */
1149         media.controller.GalleryAdd = media.controller.Library.extend({
1150                 defaults: _.defaults({
1151                         id:            'gallery-library',
1152                         title:         l10n.addToGalleryTitle,
1153                         multiple:      'add',
1154                         filterable:    'uploaded',
1155                         menu:          'gallery',
1156                         toolbar:       'gallery-add',
1157                         priority:      100,
1158                         syncSelection: false
1159                 }, media.controller.Library.prototype.defaults ),
1160
1161                 /**
1162                  * @since 3.5.0
1163                  */
1164                 initialize: function() {
1165                         // If a library wasn't supplied, create a library of images.
1166                         if ( ! this.get('library') )
1167                                 this.set( 'library', media.query({ type: 'image' }) );
1168
1169                         media.controller.Library.prototype.initialize.apply( this, arguments );
1170                 },
1171
1172                 /**
1173                  * @since 3.5.0
1174                  */
1175                 activate: function() {
1176                         var library = this.get('library'),
1177                                 edit    = this.frame.state('gallery-edit').get('library');
1178
1179                         if ( this.editLibrary && this.editLibrary !== edit )
1180                                 library.unobserve( this.editLibrary );
1181
1182                         // Accepts attachments that exist in the original library and
1183                         // that do not exist in gallery's library.
1184                         library.validator = function( attachment ) {
1185                                 return !! this.mirroring.get( attachment.cid ) && ! edit.get( attachment.cid ) && media.model.Selection.prototype.validator.apply( this, arguments );
1186                         };
1187
1188                         // Reset the library to ensure that all attachments are re-added
1189                         // to the collection. Do so silently, as calling `observe` will
1190                         // trigger the `reset` event.
1191                         library.reset( library.mirroring.models, { silent: true });
1192                         library.observe( edit );
1193                         this.editLibrary = edit;
1194
1195                         media.controller.Library.prototype.activate.apply( this, arguments );
1196                 }
1197         });
1198
1199         /**
1200          * wp.media.controller.CollectionEdit
1201          *
1202          * A state for editing a collection, which is used by audio and video playlists,
1203          * and can be used for other collections.
1204          *
1205          * @class
1206          * @augments wp.media.controller.Library
1207          * @augments wp.media.controller.State
1208          * @augments Backbone.Model
1209          *
1210          * @param {object}                     [attributes]                      The attributes hash passed to the state.
1211          * @param {string}                     attributes.title                  Title for the state. Displays in the media menu and the frame's title region.
1212          * @param {wp.media.model.Attachments} [attributes.library]              The attachments collection to edit.
1213          *                                                                       If one is not supplied, an empty media.model.Selection collection is created.
1214          * @param {boolean}                    [attributes.multiple=false]       Whether multi-select is enabled.
1215          * @param {string}                     [attributes.content=browse]       Initial mode for the content region.
1216          * @param {string}                     attributes.menu                   Initial mode for the menu region. @todo this needs a better explanation.
1217          * @param {boolean}                    [attributes.searchable=false]     Whether the library is searchable.
1218          * @param {boolean}                    [attributes.sortable=true]        Whether the Attachments should be sortable. Depends on the orderby property being set to menuOrder on the attachments collection.
1219          * @param {boolean}                    [attributes.describe=true]        Whether to offer UI to describe the attachments - e.g. captioning images in a gallery.
1220          * @param {boolean}                    [attributes.dragInfo=true]        Whether to show instructional text about the attachments being sortable.
1221          * @param {boolean}                    [attributes.dragInfoText]         Instructional text about the attachments being sortable.
1222          * @param {int}                        [attributes.idealColumnWidth=170] The ideal column width in pixels for attachments.
1223          * @param {boolean}                    [attributes.editing=false]        Whether the gallery is being created, or editing an existing instance.
1224          * @param {int}                        [attributes.priority=60]          The priority for the state link in the media menu.
1225          * @param {boolean}                    [attributes.syncSelection=false]  Whether the Attachments selection should be persisted from the last state.
1226          *                                                                       Defaults to false for this state, because the library passed in  *is* the selection.
1227          * @param {view}                       [attributes.SettingsView]         The view to edit the collection instance settings (e.g. Playlist settings with "Show tracklist" checkbox).
1228          * @param {view}                       [attributes.AttachmentView]       The single `Attachment` view to be used in the `Attachments`.
1229          *                                                                       If none supplied, defaults to wp.media.view.Attachment.EditLibrary.
1230          * @param {string}                     attributes.type                   The collection's media type. (e.g. 'video').
1231          * @param {string}                     attributes.collectionType         The collection type. (e.g. 'playlist').
1232          */
1233         media.controller.CollectionEdit = media.controller.Library.extend({
1234                 defaults: {
1235                         multiple:         false,
1236                         sortable:         true,
1237                         searchable:       false,
1238                         content:          'browse',
1239                         describe:         true,
1240                         dragInfo:         true,
1241                         idealColumnWidth: 170,
1242                         editing:          false,
1243                         priority:         60,
1244                         SettingsView:     false,
1245                         syncSelection:    false
1246                 },
1247
1248                 /**
1249                  * @since 3.9.0
1250                  */
1251                 initialize: function() {
1252                         var collectionType = this.get('collectionType');
1253
1254                         if ( 'video' === this.get( 'type' ) ) {
1255                                 collectionType = 'video-' + collectionType;
1256                         }
1257
1258                         this.set( 'id', collectionType + '-edit' );
1259                         this.set( 'toolbar', collectionType + '-edit' );
1260
1261                         // If we haven't been provided a `library`, create a `Selection`.
1262                         if ( ! this.get('library') ) {
1263                                 this.set( 'library', new media.model.Selection() );
1264                         }
1265                         // The single `Attachment` view to be used in the `Attachments` view.
1266                         if ( ! this.get('AttachmentView') ) {
1267                                 this.set( 'AttachmentView', media.view.Attachment.EditLibrary );
1268                         }
1269                         media.controller.Library.prototype.initialize.apply( this, arguments );
1270                 },
1271
1272                 /**
1273                  * @since 3.9.0
1274                  */
1275                 activate: function() {
1276                         var library = this.get('library');
1277
1278                         // Limit the library to images only.
1279                         library.props.set( 'type', this.get( 'type' ) );
1280
1281                         // Watch for uploaded attachments.
1282                         this.get('library').observe( wp.Uploader.queue );
1283
1284                         this.frame.on( 'content:render:browse', this.renderSettings, this );
1285
1286                         media.controller.Library.prototype.activate.apply( this, arguments );
1287                 },
1288
1289                 /**
1290                  * @since 3.9.0
1291                  */
1292                 deactivate: function() {
1293                         // Stop watching for uploaded attachments.
1294                         this.get('library').unobserve( wp.Uploader.queue );
1295
1296                         this.frame.off( 'content:render:browse', this.renderSettings, this );
1297
1298                         media.controller.Library.prototype.deactivate.apply( this, arguments );
1299                 },
1300
1301                 /**
1302                  * Render the collection embed settings view in the browser sidebar.
1303                  *
1304                  * @todo This is against the pattern elsewhere in media. Typically the frame
1305                  *       is responsible for adding region mode callbacks. Explain.
1306                  *
1307                  * @since 3.9.0
1308                  *
1309                  * @param {wp.media.view.attachmentsBrowser} The attachments browser view.
1310                  */
1311                 renderSettings: function( attachmentsBrowserView ) {
1312                         var library = this.get('library'),
1313                                 collectionType = this.get('collectionType'),
1314                                 dragInfoText = this.get('dragInfoText'),
1315                                 SettingsView = this.get('SettingsView'),
1316                                 obj = {};
1317
1318                         if ( ! library || ! attachmentsBrowserView ) {
1319                                 return;
1320                         }
1321
1322                         library[ collectionType ] = library[ collectionType ] || new Backbone.Model();
1323
1324                         obj[ collectionType ] = new SettingsView({
1325                                 controller: this,
1326                                 model:      library[ collectionType ],
1327                                 priority:   40
1328                         });
1329
1330                         attachmentsBrowserView.sidebar.set( obj );
1331
1332                         if ( dragInfoText ) {
1333                                 attachmentsBrowserView.toolbar.set( 'dragInfo', new media.View({
1334                                         el: $( '<div class="instructions">' + dragInfoText + '</div>' )[0],
1335                                         priority: -40
1336                                 }) );
1337                         }
1338
1339                         // Add the 'Reverse order' button to the toolbar.
1340                         attachmentsBrowserView.toolbar.set( 'reverse', {
1341                                 text:     l10n.reverseOrder,
1342                                 priority: 80,
1343
1344                                 click: function() {
1345                                         library.reset( library.toArray().reverse() );
1346                                 }
1347                         });
1348                 }
1349         });
1350
1351         /**
1352          * wp.media.controller.CollectionAdd
1353          *
1354          * A state for adding attachments to a collection (e.g. video playlist).
1355          *
1356          * @class
1357          * @augments wp.media.controller.Library
1358          * @augments wp.media.controller.State
1359          * @augments Backbone.Model
1360          *
1361          * @param {object}                     [attributes]                         The attributes hash passed to the state.
1362          * @param {string}                     [attributes.id=library]      Unique identifier.
1363          * @param {string}                     attributes.title                    Title for the state. Displays in the frame's title region.
1364          * @param {boolean}                    [attributes.multiple=add]            Whether multi-select is enabled. @todo 'add' doesn't seem do anything special, and gets used as a boolean.
1365          * @param {wp.media.model.Attachments} [attributes.library]                 The attachments collection to browse.
1366          *                                                                          If one is not supplied, a collection of attachments of the specified type will be created.
1367          * @param {boolean|string}             [attributes.filterable=uploaded]     Whether the library is filterable, and if so what filters should be shown.
1368          *                                                                          Accepts 'all', 'uploaded', or 'unattached'.
1369          * @param {string}                     [attributes.menu=gallery]            Initial mode for the menu region.
1370          * @param {string}                     [attributes.content=upload]          Initial mode for the content region.
1371          *                                                                          Overridden by persistent user setting if 'contentUserSetting' is true.
1372          * @param {string}                     [attributes.router=browse]           Initial mode for the router region.
1373          * @param {string}                     [attributes.toolbar=gallery-add]     Initial mode for the toolbar region.
1374          * @param {boolean}                    [attributes.searchable=true]         Whether the library is searchable.
1375          * @param {boolean}                    [attributes.sortable=true]           Whether the Attachments should be sortable. Depends on the orderby property being set to menuOrder on the attachments collection.
1376          * @param {boolean}                    [attributes.autoSelect=true]         Whether an uploaded attachment should be automatically added to the selection.
1377          * @param {boolean}                    [attributes.contentUserSetting=true] Whether the content region's mode should be set and persisted per user.
1378          * @param {int}                        [attributes.priority=100]            The priority for the state link in the media menu.
1379          * @param {boolean}                    [attributes.syncSelection=false]     Whether the Attachments selection should be persisted from the last state.
1380          *                                                                          Defaults to false because for this state, because the library of the Edit Gallery state is the selection.
1381          * @param {string}                     attributes.type                   The collection's media type. (e.g. 'video').
1382          * @param {string}                     attributes.collectionType         The collection type. (e.g. 'playlist').
1383          */
1384         media.controller.CollectionAdd = media.controller.Library.extend({
1385                 defaults: _.defaults( {
1386                         // Selection defaults. @see media.model.Selection
1387                         multiple:      'add',
1388                         // Attachments browser defaults. @see media.view.AttachmentsBrowser
1389                         filterable:    'uploaded',
1390
1391                         priority:      100,
1392                         syncSelection: false
1393                 }, media.controller.Library.prototype.defaults ),
1394
1395                 /**
1396                  * @since 3.9.0
1397                  */
1398                 initialize: function() {
1399                         var collectionType = this.get('collectionType');
1400
1401                         if ( 'video' === this.get( 'type' ) ) {
1402                                 collectionType = 'video-' + collectionType;
1403                         }
1404
1405                         this.set( 'id', collectionType + '-library' );
1406                         this.set( 'toolbar', collectionType + '-add' );
1407                         this.set( 'menu', collectionType );
1408
1409                         // If we haven't been provided a `library`, create a `Selection`.
1410                         if ( ! this.get('library') ) {
1411                                 this.set( 'library', media.query({ type: this.get('type') }) );
1412                         }
1413                         media.controller.Library.prototype.initialize.apply( this, arguments );
1414                 },
1415
1416                 /**
1417                  * @since 3.9.0
1418                  */
1419                 activate: function() {
1420                         var library = this.get('library'),
1421                                 editLibrary = this.get('editLibrary'),
1422                                 edit = this.frame.state( this.get('collectionType') + '-edit' ).get('library');
1423
1424                         if ( editLibrary && editLibrary !== edit ) {
1425                                 library.unobserve( editLibrary );
1426                         }
1427
1428                         // Accepts attachments that exist in the original library and
1429                         // that do not exist in gallery's library.
1430                         library.validator = function( attachment ) {
1431                                 return !! this.mirroring.get( attachment.cid ) && ! edit.get( attachment.cid ) && media.model.Selection.prototype.validator.apply( this, arguments );
1432                         };
1433
1434                         // Reset the library to ensure that all attachments are re-added
1435                         // to the collection. Do so silently, as calling `observe` will
1436                         // trigger the `reset` event.
1437                         library.reset( library.mirroring.models, { silent: true });
1438                         library.observe( edit );
1439                         this.set('editLibrary', edit);
1440
1441                         media.controller.Library.prototype.activate.apply( this, arguments );
1442                 }
1443         });
1444
1445         /**
1446          * wp.media.controller.FeaturedImage
1447          *
1448          * A state for selecting a featured image for a post.
1449          *
1450          * @class
1451          * @augments wp.media.controller.Library
1452          * @augments wp.media.controller.State
1453          * @augments Backbone.Model
1454          *
1455          * @param {object}                     [attributes]                          The attributes hash passed to the state.
1456          * @param {string}                     [attributes.id=featured-image]        Unique identifier.
1457          * @param {string}                     [attributes.title=Set Featured Image] Title for the state. Displays in the media menu and the frame's title region.
1458          * @param {wp.media.model.Attachments} [attributes.library]                  The attachments collection to browse.
1459          *                                                                           If one is not supplied, a collection of all images will be created.
1460          * @param {boolean}                    [attributes.multiple=false]           Whether multi-select is enabled.
1461          * @param {string}                     [attributes.content=upload]           Initial mode for the content region.
1462          *                                                                           Overridden by persistent user setting if 'contentUserSetting' is true.
1463          * @param {string}                     [attributes.menu=default]             Initial mode for the menu region.
1464          * @param {string}                     [attributes.router=browse]            Initial mode for the router region.
1465          * @param {string}                     [attributes.toolbar=featured-image]   Initial mode for the toolbar region.
1466          * @param {int}                        [attributes.priority=60]              The priority for the state link in the media menu.
1467          * @param {boolean}                    [attributes.searchable=true]          Whether the library is searchable.
1468          * @param {boolean|string}             [attributes.filterable=false]         Whether the library is filterable, and if so what filters should be shown.
1469          *                                                                           Accepts 'all', 'uploaded', or 'unattached'.
1470          * @param {boolean}                    [attributes.sortable=true]            Whether the Attachments should be sortable. Depends on the orderby property being set to menuOrder on the attachments collection.
1471          * @param {boolean}                    [attributes.autoSelect=true]          Whether an uploaded attachment should be automatically added to the selection.
1472          * @param {boolean}                    [attributes.describe=false]           Whether to offer UI to describe attachments - e.g. captioning images in a gallery.
1473          * @param {boolean}                    [attributes.contentUserSetting=true]  Whether the content region's mode should be set and persisted per user.
1474          * @param {boolean}                    [attributes.syncSelection=true]       Whether the Attachments selection should be persisted from the last state.
1475          */
1476         media.controller.FeaturedImage = media.controller.Library.extend({
1477                 defaults: _.defaults({
1478                         id:            'featured-image',
1479                         title:         l10n.setFeaturedImageTitle,
1480                         multiple:      false,
1481                         filterable:    'uploaded',
1482                         toolbar:       'featured-image',
1483                         priority:      60,
1484                         syncSelection: true
1485                 }, media.controller.Library.prototype.defaults ),
1486
1487                 /**
1488                  * @since 3.5.0
1489                  */
1490                 initialize: function() {
1491                         var library, comparator;
1492
1493                         // If we haven't been provided a `library`, create a `Selection`.
1494                         if ( ! this.get('library') ) {
1495                                 this.set( 'library', media.query({ type: 'image' }) );
1496                         }
1497
1498                         media.controller.Library.prototype.initialize.apply( this, arguments );
1499
1500                         library    = this.get('library');
1501                         comparator = library.comparator;
1502
1503                         // Overload the library's comparator to push items that are not in
1504                         // the mirrored query to the front of the aggregate collection.
1505                         library.comparator = function( a, b ) {
1506                                 var aInQuery = !! this.mirroring.get( a.cid ),
1507                                         bInQuery = !! this.mirroring.get( b.cid );
1508
1509                                 if ( ! aInQuery && bInQuery ) {
1510                                         return -1;
1511                                 } else if ( aInQuery && ! bInQuery ) {
1512                                         return 1;
1513                                 } else {
1514                                         return comparator.apply( this, arguments );
1515                                 }
1516                         };
1517
1518                         // Add all items in the selection to the library, so any featured
1519                         // images that are not initially loaded still appear.
1520                         library.observe( this.get('selection') );
1521                 },
1522
1523                 /**
1524                  * @since 3.5.0
1525                  */
1526                 activate: function() {
1527                         this.updateSelection();
1528                         this.frame.on( 'open', this.updateSelection, this );
1529
1530                         media.controller.Library.prototype.activate.apply( this, arguments );
1531                 },
1532
1533                 /**
1534                  * @since 3.5.0
1535                  */
1536                 deactivate: function() {
1537                         this.frame.off( 'open', this.updateSelection, this );
1538
1539                         media.controller.Library.prototype.deactivate.apply( this, arguments );
1540                 },
1541
1542                 /**
1543                  * @since 3.5.0
1544                  */
1545                 updateSelection: function() {
1546                         var selection = this.get('selection'),
1547                                 id = media.view.settings.post.featuredImageId,
1548                                 attachment;
1549
1550                         if ( '' !== id && -1 !== id ) {
1551                                 attachment = media.model.Attachment.get( id );
1552                                 attachment.fetch();
1553                         }
1554
1555                         selection.reset( attachment ? [ attachment ] : [] );
1556                 }
1557         });
1558
1559         /**
1560          * wp.media.controller.ReplaceImage
1561          *
1562          * A state for replacing an image.
1563          *
1564          * @class
1565          * @augments wp.media.controller.Library
1566          * @augments wp.media.controller.State
1567          * @augments Backbone.Model
1568          *
1569          * @param {object}                     [attributes]                         The attributes hash passed to the state.
1570          * @param {string}                     [attributes.id=replace-image]        Unique identifier.
1571          * @param {string}                     [attributes.title=Replace Image]     Title for the state. Displays in the media menu and the frame's title region.
1572          * @param {wp.media.model.Attachments} [attributes.library]                 The attachments collection to browse.
1573          *                                                                          If one is not supplied, a collection of all images will be created.
1574          * @param {boolean}                    [attributes.multiple=false]          Whether multi-select is enabled.
1575          * @param {string}                     [attributes.content=upload]          Initial mode for the content region.
1576          *                                                                          Overridden by persistent user setting if 'contentUserSetting' is true.
1577          * @param {string}                     [attributes.menu=default]            Initial mode for the menu region.
1578          * @param {string}                     [attributes.router=browse]           Initial mode for the router region.
1579          * @param {string}                     [attributes.toolbar=replace]         Initial mode for the toolbar region.
1580          * @param {int}                        [attributes.priority=60]             The priority for the state link in the media menu.
1581          * @param {boolean}                    [attributes.searchable=true]         Whether the library is searchable.
1582          * @param {boolean|string}             [attributes.filterable=uploaded]     Whether the library is filterable, and if so what filters should be shown.
1583          *                                                                          Accepts 'all', 'uploaded', or 'unattached'.
1584          * @param {boolean}                    [attributes.sortable=true]           Whether the Attachments should be sortable. Depends on the orderby property being set to menuOrder on the attachments collection.
1585          * @param {boolean}                    [attributes.autoSelect=true]         Whether an uploaded attachment should be automatically added to the selection.
1586          * @param {boolean}                    [attributes.describe=false]          Whether to offer UI to describe attachments - e.g. captioning images in a gallery.
1587          * @param {boolean}                    [attributes.contentUserSetting=true] Whether the content region's mode should be set and persisted per user.
1588          * @param {boolean}                    [attributes.syncSelection=true]      Whether the Attachments selection should be persisted from the last state.
1589          */
1590         media.controller.ReplaceImage = media.controller.Library.extend({
1591                 defaults: _.defaults({
1592                         id:            'replace-image',
1593                         title:         l10n.replaceImageTitle,
1594                         multiple:      false,
1595                         filterable:    'uploaded',
1596                         toolbar:       'replace',
1597                         menu:          false,
1598                         priority:      60,
1599                         syncSelection: true
1600                 }, media.controller.Library.prototype.defaults ),
1601
1602                 /**
1603                  * @since 3.9.0
1604                  *
1605                  * @param options
1606                  */
1607                 initialize: function( options ) {
1608                         var library, comparator;
1609
1610                         this.image = options.image;
1611                         // If we haven't been provided a `library`, create a `Selection`.
1612                         if ( ! this.get('library') ) {
1613                                 this.set( 'library', media.query({ type: 'image' }) );
1614                         }
1615
1616                         media.controller.Library.prototype.initialize.apply( this, arguments );
1617
1618                         library    = this.get('library');
1619                         comparator = library.comparator;
1620
1621                         // Overload the library's comparator to push items that are not in
1622                         // the mirrored query to the front of the aggregate collection.
1623                         library.comparator = function( a, b ) {
1624                                 var aInQuery = !! this.mirroring.get( a.cid ),
1625                                         bInQuery = !! this.mirroring.get( b.cid );
1626
1627                                 if ( ! aInQuery && bInQuery ) {
1628                                         return -1;
1629                                 } else if ( aInQuery && ! bInQuery ) {
1630                                         return 1;
1631                                 } else {
1632                                         return comparator.apply( this, arguments );
1633                                 }
1634                         };
1635
1636                         // Add all items in the selection to the library, so any featured
1637                         // images that are not initially loaded still appear.
1638                         library.observe( this.get('selection') );
1639                 },
1640
1641                 /**
1642                  * @since 3.9.0
1643                  */
1644                 activate: function() {
1645                         this.updateSelection();
1646                         media.controller.Library.prototype.activate.apply( this, arguments );
1647                 },
1648
1649                 /**
1650                  * @since 3.9.0
1651                  */
1652                 updateSelection: function() {
1653                         var selection = this.get('selection'),
1654                                 attachment = this.image.attachment;
1655
1656                         selection.reset( attachment ? [ attachment ] : [] );
1657                 }
1658         });
1659
1660         /**
1661          * wp.media.controller.EditImage
1662          *
1663          * A state for editing (cropping, etc.) an image.
1664          *
1665          * @class
1666          * @augments wp.media.controller.State
1667          * @augments Backbone.Model
1668          *
1669          * @param {object}                    attributes                      The attributes hash passed to the state.
1670          * @param {wp.media.model.Attachment} attributes.model                The attachment.
1671          * @param {string}                    [attributes.id=edit-image]      Unique identifier.
1672          * @param {string}                    [attributes.title=Edit Image]   Title for the state. Displays in the media menu and the frame's title region.
1673          * @param {string}                    [attributes.content=edit-image] Initial mode for the content region.
1674          * @param {string}                    [attributes.toolbar=edit-image] Initial mode for the toolbar region.
1675          * @param {string}                    [attributes.menu=false]         Initial mode for the menu region.
1676          * @param {string}                    [attributes.url]                Unused. @todo Consider removal.
1677          */
1678         media.controller.EditImage = media.controller.State.extend({
1679                 defaults: {
1680                         id:      'edit-image',
1681                         title:   l10n.editImage,
1682                         menu:    false,
1683                         toolbar: 'edit-image',
1684                         content: 'edit-image',
1685                         url:     ''
1686                 },
1687
1688                 /**
1689                  * @since 3.9.0
1690                  */
1691                 activate: function() {
1692                         this.listenTo( this.frame, 'toolbar:render:edit-image', this.toolbar );
1693                 },
1694
1695                 /**
1696                  * @since 3.9.0
1697                  */
1698                 deactivate: function() {
1699                         this.stopListening( this.frame );
1700                 },
1701
1702                 /**
1703                  * @since 3.9.0
1704                  */
1705                 toolbar: function() {
1706                         var frame = this.frame,
1707                                 lastState = frame.lastState(),
1708                                 previous = lastState && lastState.id;
1709
1710                         frame.toolbar.set( new media.view.Toolbar({
1711                                 controller: frame,
1712                                 items: {
1713                                         back: {
1714                                                 style: 'primary',
1715                                                 text:     l10n.back,
1716                                                 priority: 20,
1717                                                 click:    function() {
1718                                                         if ( previous ) {
1719                                                                 frame.setState( previous );
1720                                                         } else {
1721                                                                 frame.close();
1722                                                         }
1723                                                 }
1724                                         }
1725                                 }
1726                         }) );
1727                 }
1728         });
1729
1730         /**
1731          * wp.media.controller.MediaLibrary
1732          *
1733          * @class
1734          * @augments wp.media.controller.Library
1735          * @augments wp.media.controller.State
1736          * @augments Backbone.Model
1737          */
1738         media.controller.MediaLibrary = media.controller.Library.extend({
1739                 defaults: _.defaults({
1740                         // Attachments browser defaults. @see media.view.AttachmentsBrowser
1741                         filterable:      'uploaded',
1742
1743                         displaySettings: false,
1744                         priority:        80,
1745                         syncSelection:   false
1746                 }, media.controller.Library.prototype.defaults ),
1747
1748                 /**
1749                  * @since 3.9.0
1750                  *
1751                  * @param options
1752                  */
1753                 initialize: function( options ) {
1754                         this.media = options.media;
1755                         this.type = options.type;
1756                         this.set( 'library', media.query({ type: this.type }) );
1757
1758                         media.controller.Library.prototype.initialize.apply( this, arguments );
1759                 },
1760
1761                 /**
1762                  * @since 3.9.0
1763                  */
1764                 activate: function() {
1765                         // @todo this should use this.frame.
1766                         if ( media.frame.lastMime ) {
1767                                 this.set( 'library', media.query({ type: media.frame.lastMime }) );
1768                                 delete media.frame.lastMime;
1769                         }
1770                         media.controller.Library.prototype.activate.apply( this, arguments );
1771                 }
1772         });
1773
1774         /**
1775          * wp.media.controller.Embed
1776          *
1777          * A state for embedding media from a URL.
1778          *
1779          * @class
1780          * @augments wp.media.controller.State
1781          * @augments Backbone.Model
1782          *
1783          * @param {object} attributes                         The attributes hash passed to the state.
1784          * @param {string} [attributes.id=embed]              Unique identifier.
1785          * @param {string} [attributes.title=Insert From URL] Title for the state. Displays in the media menu and the frame's title region.
1786          * @param {string} [attributes.content=embed]         Initial mode for the content region.
1787          * @param {string} [attributes.menu=default]          Initial mode for the menu region.
1788          * @param {string} [attributes.toolbar=main-embed]    Initial mode for the toolbar region.
1789          * @param {string} [attributes.menu=false]            Initial mode for the menu region.
1790          * @param {int}    [attributes.priority=120]          The priority for the state link in the media menu.
1791          * @param {string} [attributes.type=link]             The type of embed. Currently only link is supported.
1792          * @param {string} [attributes.url]                   The embed URL.
1793          * @param {object} [attributes.metadata={}]           Properties of the embed, which will override attributes.url if set.
1794          */
1795         media.controller.Embed = media.controller.State.extend({
1796                 defaults: {
1797                         id:       'embed',
1798                         title:    l10n.insertFromUrlTitle,
1799                         content:  'embed',
1800                         menu:     'default',
1801                         toolbar:  'main-embed',
1802                         priority: 120,
1803                         type:     'link',
1804                         url:      '',
1805                         metadata: {}
1806                 },
1807
1808                 // The amount of time used when debouncing the scan.
1809                 sensitivity: 200,
1810
1811                 initialize: function(options) {
1812                         this.metadata = options.metadata;
1813                         this.debouncedScan = _.debounce( _.bind( this.scan, this ), this.sensitivity );
1814                         this.props = new Backbone.Model( this.metadata || { url: '' });
1815                         this.props.on( 'change:url', this.debouncedScan, this );
1816                         this.props.on( 'change:url', this.refresh, this );
1817                         this.on( 'scan', this.scanImage, this );
1818                 },
1819
1820                 /**
1821                  * Trigger a scan of the embedded URL's content for metadata required to embed.
1822                  *
1823                  * @fires wp.media.controller.Embed#scan
1824                  */
1825                 scan: function() {
1826                         var scanners,
1827                                 embed = this,
1828                                 attributes = {
1829                                         type: 'link',
1830                                         scanners: []
1831                                 };
1832
1833                         // Scan is triggered with the list of `attributes` to set on the
1834                         // state, useful for the 'type' attribute and 'scanners' attribute,
1835                         // an array of promise objects for asynchronous scan operations.
1836                         if ( this.props.get('url') ) {
1837                                 this.trigger( 'scan', attributes );
1838                         }
1839
1840                         if ( attributes.scanners.length ) {
1841                                 scanners = attributes.scanners = $.when.apply( $, attributes.scanners );
1842                                 scanners.always( function() {
1843                                         if ( embed.get('scanners') === scanners ) {
1844                                                 embed.set( 'loading', false );
1845                                         }
1846                                 });
1847                         } else {
1848                                 attributes.scanners = null;
1849                         }
1850
1851                         attributes.loading = !! attributes.scanners;
1852                         this.set( attributes );
1853                 },
1854                 /**
1855                  * Try scanning the embed as an image to discover its dimensions.
1856                  *
1857                  * @param {Object} attributes
1858                  */
1859                 scanImage: function( attributes ) {
1860                         var frame = this.frame,
1861                                 state = this,
1862                                 url = this.props.get('url'),
1863                                 image = new Image(),
1864                                 deferred = $.Deferred();
1865
1866                         attributes.scanners.push( deferred.promise() );
1867
1868                         // Try to load the image and find its width/height.
1869                         image.onload = function() {
1870                                 deferred.resolve();
1871
1872                                 if ( state !== frame.state() || url !== state.props.get('url') ) {
1873                                         return;
1874                                 }
1875
1876                                 state.set({
1877                                         type: 'image'
1878                                 });
1879
1880                                 state.props.set({
1881                                         width:  image.width,
1882                                         height: image.height
1883                                 });
1884                         };
1885
1886                         image.onerror = deferred.reject;
1887                         image.src = url;
1888                 },
1889
1890                 refresh: function() {
1891                         this.frame.toolbar.get().refresh();
1892                 },
1893
1894                 reset: function() {
1895                         this.props.clear().set({ url: '' });
1896
1897                         if ( this.active ) {
1898                                 this.refresh();
1899                         }
1900                 }
1901         });
1902
1903         /**
1904          * wp.media.controller.Cropper
1905          *
1906          * A state for cropping an image.
1907          *
1908          * @class
1909          * @augments wp.media.controller.State
1910          * @augments Backbone.Model
1911          */
1912         media.controller.Cropper = media.controller.State.extend({
1913                 defaults: {
1914                         id:          'cropper',
1915                         title:       l10n.cropImage,
1916                         // Region mode defaults.
1917                         toolbar:     'crop',
1918                         content:     'crop',
1919                         router:      false,
1920
1921                         canSkipCrop: false
1922                 },
1923
1924                 activate: function() {
1925                         this.frame.on( 'content:create:crop', this.createCropContent, this );
1926                         this.frame.on( 'close', this.removeCropper, this );
1927                         this.set('selection', new Backbone.Collection(this.frame._selection.single));
1928                 },
1929
1930                 deactivate: function() {
1931                         this.frame.toolbar.mode('browse');
1932                 },
1933
1934                 createCropContent: function() {
1935                         this.cropperView = new wp.media.view.Cropper({controller: this,
1936                                         attachment: this.get('selection').first() });
1937                         this.cropperView.on('image-loaded', this.createCropToolbar, this);
1938                         this.frame.content.set(this.cropperView);
1939
1940                 },
1941                 removeCropper: function() {
1942                         this.imgSelect.cancelSelection();
1943                         this.imgSelect.setOptions({remove: true});
1944                         this.imgSelect.update();
1945                         this.cropperView.remove();
1946                 },
1947                 createCropToolbar: function() {
1948                         var canSkipCrop, toolbarOptions;
1949
1950                         canSkipCrop = this.get('canSkipCrop') || false;
1951
1952                         toolbarOptions = {
1953                                 controller: this.frame,
1954                                 items: {
1955                                         insert: {
1956                                                 style:    'primary',
1957                                                 text:     l10n.cropImage,
1958                                                 priority: 80,
1959                                                 requires: { library: false, selection: false },
1960
1961                                                 click: function() {
1962                                                         var self = this,
1963                                                                 selection = this.controller.state().get('selection').first();
1964
1965                                                         selection.set({cropDetails: this.controller.state().imgSelect.getSelection()});
1966
1967                                                         this.$el.text(l10n.cropping);
1968                                                         this.$el.attr('disabled', true);
1969                                                         this.controller.state().doCrop( selection ).done( function( croppedImage ) {
1970                                                                 self.controller.trigger('cropped', croppedImage );
1971                                                                 self.controller.close();
1972                                                         }).fail( function() {
1973                                                                 self.controller.trigger('content:error:crop');
1974                                                         });
1975                                                 }
1976                                         }
1977                                 }
1978                         };
1979
1980                         if ( canSkipCrop ) {
1981                                 _.extend( toolbarOptions.items, {
1982                                         skip: {
1983                                                 style:      'secondary',
1984                                                 text:       l10n.skipCropping,
1985                                                 priority:   70,
1986                                                 requires:   { library: false, selection: false },
1987                                                 click:      function() {
1988                                                         var selection = this.controller.state().get('selection').first();
1989                                                         this.controller.state().cropperView.remove();
1990                                                         this.controller.trigger('skippedcrop', selection);
1991                                                         this.controller.close();
1992                                                 }
1993                                         }
1994                                 });
1995                         }
1996
1997                         this.frame.toolbar.set( new wp.media.view.Toolbar(toolbarOptions) );
1998                 },
1999
2000                 doCrop: function( attachment ) {
2001                         return wp.ajax.post( 'custom-header-crop', {
2002                                 nonce: attachment.get('nonces').edit,
2003                                 id: attachment.get('id'),
2004                                 cropDetails: attachment.get('cropDetails')
2005                         } );
2006                 }
2007         });
2008
2009         /**
2010          * wp.media.View
2011          *
2012          * The base view class for media.
2013          *
2014          * Undelegating events, removing events from the model, and
2015          * removing events from the controller mirror the code for
2016          * `Backbone.View.dispose` in Backbone 0.9.8 development.
2017          *
2018          * This behavior has since been removed, and should not be used
2019          * outside of the media manager.
2020          *
2021          * @class
2022          * @augments wp.Backbone.View
2023          * @augments Backbone.View
2024          */
2025         media.View = wp.Backbone.View.extend({
2026                 constructor: function( options ) {
2027                         if ( options && options.controller ) {
2028                                 this.controller = options.controller;
2029                         }
2030                         wp.Backbone.View.apply( this, arguments );
2031                 },
2032                 /**
2033                  * @todo The internal comment mentions this might have been a stop-gap
2034                  *       before Backbone 0.9.8 came out. Figure out if Backbone core takes
2035                  *       care of this in Backbone.View now.
2036                  *
2037                  * @returns {wp.media.View} Returns itself to allow chaining
2038                  */
2039                 dispose: function() {
2040                         // Undelegating events, removing events from the model, and
2041                         // removing events from the controller mirror the code for
2042                         // `Backbone.View.dispose` in Backbone 0.9.8 development.
2043                         this.undelegateEvents();
2044
2045                         if ( this.model && this.model.off ) {
2046                                 this.model.off( null, null, this );
2047                         }
2048
2049                         if ( this.collection && this.collection.off ) {
2050                                 this.collection.off( null, null, this );
2051                         }
2052
2053                         // Unbind controller events.
2054                         if ( this.controller && this.controller.off ) {
2055                                 this.controller.off( null, null, this );
2056                         }
2057
2058                         return this;
2059                 },
2060                 /**
2061                  * @returns {wp.media.View} Returns itself to allow chaining
2062                  */
2063                 remove: function() {
2064                         this.dispose();
2065                         /**
2066                          * call 'remove' directly on the parent class
2067                          */
2068                         return wp.Backbone.View.prototype.remove.apply( this, arguments );
2069                 }
2070         });
2071
2072         /**
2073          * wp.media.view.Frame
2074          *
2075          * A frame is a composite view consisting of one or more regions and one or more
2076          * states.
2077          *
2078          * @see wp.media.controller.State
2079          * @see wp.media.controller.Region
2080          *
2081          * @class
2082          * @augments wp.media.View
2083          * @augments wp.Backbone.View
2084          * @augments Backbone.View
2085          * @mixes wp.media.controller.StateMachine
2086          */
2087         media.view.Frame = media.View.extend({
2088                 initialize: function() {
2089                         _.defaults( this.options, {
2090                                 mode: [ 'select' ]
2091                         });
2092                         this._createRegions();
2093                         this._createStates();
2094                         this._createModes();
2095                 },
2096
2097                 _createRegions: function() {
2098                         // Clone the regions array.
2099                         this.regions = this.regions ? this.regions.slice() : [];
2100
2101                         // Initialize regions.
2102                         _.each( this.regions, function( region ) {
2103                                 this[ region ] = new media.controller.Region({
2104                                         view:     this,
2105                                         id:       region,
2106                                         selector: '.media-frame-' + region
2107                                 });
2108                         }, this );
2109                 },
2110                 /**
2111                  * Create the frame's states.
2112                  *
2113                  * @see wp.media.controller.State
2114                  * @see wp.media.controller.StateMachine
2115                  *
2116                  * @fires wp.media.controller.State#ready
2117                  */
2118                 _createStates: function() {
2119                         // Create the default `states` collection.
2120                         this.states = new Backbone.Collection( null, {
2121                                 model: media.controller.State
2122                         });
2123
2124                         // Ensure states have a reference to the frame.
2125                         this.states.on( 'add', function( model ) {
2126                                 model.frame = this;
2127                                 model.trigger('ready');
2128                         }, this );
2129
2130                         if ( this.options.states ) {
2131                                 this.states.add( this.options.states );
2132                         }
2133                 },
2134
2135                 /**
2136                  * A frame can be in a mode or multiple modes at one time.
2137                  *
2138                  * For example, the manage media frame can be in the `Bulk Select` or `Edit` mode.
2139                  */
2140                 _createModes: function() {
2141                         // Store active "modes" that the frame is in. Unrelated to region modes.
2142                         this.activeModes = new Backbone.Collection();
2143                         this.activeModes.on( 'add remove reset', _.bind( this.triggerModeEvents, this ) );
2144
2145                         _.each( this.options.mode, function( mode ) {
2146                                 this.activateMode( mode );
2147                         }, this );
2148                 },
2149                 /**
2150                  * Reset all states on the frame to their defaults.
2151                  *
2152                  * @returns {wp.media.view.Frame} Returns itself to allow chaining
2153                  */
2154                 reset: function() {
2155                         this.states.invoke( 'trigger', 'reset' );
2156                         return this;
2157                 },
2158                 /**
2159                  * Map activeMode collection events to the frame.
2160                  */
2161                 triggerModeEvents: function( model, collection, options ) {
2162                         var collectionEvent,
2163                                 modeEventMap = {
2164                                         add: 'activate',
2165                                         remove: 'deactivate'
2166                                 },
2167                                 eventToTrigger;
2168                         // Probably a better way to do this.
2169                         _.each( options, function( value, key ) {
2170                                 if ( value ) {
2171                                         collectionEvent = key;
2172                                 }
2173                         } );
2174
2175                         if ( ! _.has( modeEventMap, collectionEvent ) ) {
2176                                 return;
2177                         }
2178
2179                         eventToTrigger = model.get('id') + ':' + modeEventMap[collectionEvent];
2180                         this.trigger( eventToTrigger );
2181                 },
2182                 /**
2183                  * Activate a mode on the frame.
2184                  *
2185                  * @param string mode Mode ID.
2186                  * @returns {this} Returns itself to allow chaining.
2187                  */
2188                 activateMode: function( mode ) {
2189                         // Bail if the mode is already active.
2190                         if ( this.isModeActive( mode ) ) {
2191                                 return;
2192                         }
2193                         this.activeModes.add( [ { id: mode } ] );
2194                         // Add a CSS class to the frame so elements can be styled for the mode.
2195                         this.$el.addClass( 'mode-' + mode );
2196
2197                         return this;
2198                 },
2199                 /**
2200                  * Deactivate a mode on the frame.
2201                  *
2202                  * @param string mode Mode ID.
2203                  * @returns {this} Returns itself to allow chaining.
2204                  */
2205                 deactivateMode: function( mode ) {
2206                         // Bail if the mode isn't active.
2207                         if ( ! this.isModeActive( mode ) ) {
2208                                 return this;
2209                         }
2210                         this.activeModes.remove( this.activeModes.where( { id: mode } ) );
2211                         this.$el.removeClass( 'mode-' + mode );
2212                         /**
2213                          * Frame mode deactivation event.
2214                          *
2215                          * @event this#{mode}:deactivate
2216                          */
2217                         this.trigger( mode + ':deactivate' );
2218
2219                         return this;
2220                 },
2221                 /**
2222                  * Check if a mode is enabled on the frame.
2223                  *
2224                  * @param  string mode Mode ID.
2225                  * @return bool
2226                  */
2227                 isModeActive: function( mode ) {
2228                         return Boolean( this.activeModes.where( { id: mode } ).length );
2229                 }
2230         });
2231
2232         // Make the `Frame` a `StateMachine`.
2233         _.extend( media.view.Frame.prototype, media.controller.StateMachine.prototype );
2234
2235         /**
2236          * wp.media.view.MediaFrame
2237          *
2238          * The frame used to create the media modal.
2239          *
2240          * @class
2241          * @augments wp.media.view.Frame
2242          * @augments wp.media.View
2243          * @augments wp.Backbone.View
2244          * @augments Backbone.View
2245          * @mixes wp.media.controller.StateMachine
2246          */
2247         media.view.MediaFrame = media.view.Frame.extend({
2248                 className: 'media-frame',
2249                 template:  media.template('media-frame'),
2250                 regions:   ['menu','title','content','toolbar','router'],
2251
2252                 events: {
2253                         'click div.media-frame-title h1': 'toggleMenu'
2254                 },
2255
2256                 /**
2257                  * @global wp.Uploader
2258                  */
2259                 initialize: function() {
2260                         media.view.Frame.prototype.initialize.apply( this, arguments );
2261
2262                         _.defaults( this.options, {
2263                                 title:    '',
2264                                 modal:    true,
2265                                 uploader: true
2266                         });
2267
2268                         // Ensure core UI is enabled.
2269                         this.$el.addClass('wp-core-ui');
2270
2271                         // Initialize modal container view.
2272                         if ( this.options.modal ) {
2273                                 this.modal = new media.view.Modal({
2274                                         controller: this,
2275                                         title:      this.options.title
2276                                 });
2277
2278                                 this.modal.content( this );
2279                         }
2280
2281                         // Force the uploader off if the upload limit has been exceeded or
2282                         // if the browser isn't supported.
2283                         if ( wp.Uploader.limitExceeded || ! wp.Uploader.browser.supported ) {
2284                                 this.options.uploader = false;
2285                         }
2286
2287                         // Initialize window-wide uploader.
2288                         if ( this.options.uploader ) {
2289                                 this.uploader = new media.view.UploaderWindow({
2290                                         controller: this,
2291                                         uploader: {
2292                                                 dropzone:  this.modal ? this.modal.$el : this.$el,
2293                                                 container: this.$el
2294                                         }
2295                                 });
2296                                 this.views.set( '.media-frame-uploader', this.uploader );
2297                         }
2298
2299                         this.on( 'attach', _.bind( this.views.ready, this.views ), this );
2300
2301                         // Bind default title creation.
2302                         this.on( 'title:create:default', this.createTitle, this );
2303                         this.title.mode('default');
2304
2305                         this.on( 'title:render', function( view ) {
2306                                 view.$el.append( '<span class="dashicons dashicons-arrow-down"></span>' );
2307                         });
2308
2309                         // Bind default menu.
2310                         this.on( 'menu:create:default', this.createMenu, this );
2311                 },
2312                 /**
2313                  * @returns {wp.media.view.MediaFrame} Returns itself to allow chaining
2314                  */
2315                 render: function() {
2316                         // Activate the default state if no active state exists.
2317                         if ( ! this.state() && this.options.state ) {
2318                                 this.setState( this.options.state );
2319                         }
2320                         /**
2321                          * call 'render' directly on the parent class
2322                          */
2323                         return media.view.Frame.prototype.render.apply( this, arguments );
2324                 },
2325                 /**
2326                  * @param {Object} title
2327                  * @this wp.media.controller.Region
2328                  */
2329                 createTitle: function( title ) {
2330                         title.view = new media.View({
2331                                 controller: this,
2332                                 tagName: 'h1'
2333                         });
2334                 },
2335                 /**
2336                  * @param {Object} menu
2337                  * @this wp.media.controller.Region
2338                  */
2339                 createMenu: function( menu ) {
2340                         menu.view = new media.view.Menu({
2341                                 controller: this
2342                         });
2343                 },
2344
2345                 toggleMenu: function() {
2346                         this.$el.find( '.media-menu' ).toggleClass( 'visible' );
2347                 },
2348
2349                 /**
2350                  * @param {Object} toolbar
2351                  * @this wp.media.controller.Region
2352                  */
2353                 createToolbar: function( toolbar ) {
2354                         toolbar.view = new media.view.Toolbar({
2355                                 controller: this
2356                         });
2357                 },
2358                 /**
2359                  * @param {Object} router
2360                  * @this wp.media.controller.Region
2361                  */
2362                 createRouter: function( router ) {
2363                         router.view = new media.view.Router({
2364                                 controller: this
2365                         });
2366                 },
2367                 /**
2368                  * @param {Object} options
2369                  */
2370                 createIframeStates: function( options ) {
2371                         var settings = media.view.settings,
2372                                 tabs = settings.tabs,
2373                                 tabUrl = settings.tabUrl,
2374                                 $postId;
2375
2376                         if ( ! tabs || ! tabUrl ) {
2377                                 return;
2378                         }
2379
2380                         // Add the post ID to the tab URL if it exists.
2381                         $postId = $('#post_ID');
2382                         if ( $postId.length ) {
2383                                 tabUrl += '&post_id=' + $postId.val();
2384                         }
2385
2386                         // Generate the tab states.
2387                         _.each( tabs, function( title, id ) {
2388                                 this.state( 'iframe:' + id ).set( _.defaults({
2389                                         tab:     id,
2390                                         src:     tabUrl + '&tab=' + id,
2391                                         title:   title,
2392                                         content: 'iframe',
2393                                         menu:    'default'
2394                                 }, options ) );
2395                         }, this );
2396
2397                         this.on( 'content:create:iframe', this.iframeContent, this );
2398                         this.on( 'content:deactivate:iframe', this.iframeContentCleanup, this );
2399                         this.on( 'menu:render:default', this.iframeMenu, this );
2400                         this.on( 'open', this.hijackThickbox, this );
2401                         this.on( 'close', this.restoreThickbox, this );
2402                 },
2403
2404                 /**
2405                  * @param {Object} content
2406                  * @this wp.media.controller.Region
2407                  */
2408                 iframeContent: function( content ) {
2409                         this.$el.addClass('hide-toolbar');
2410                         content.view = new media.view.Iframe({
2411                                 controller: this
2412                         });
2413                 },
2414
2415                 iframeContentCleanup: function() {
2416                         this.$el.removeClass('hide-toolbar');
2417                 },
2418
2419                 iframeMenu: function( view ) {
2420                         var views = {};
2421
2422                         if ( ! view ) {
2423                                 return;
2424                         }
2425
2426                         _.each( media.view.settings.tabs, function( title, id ) {
2427                                 views[ 'iframe:' + id ] = {
2428                                         text: this.state( 'iframe:' + id ).get('title'),
2429                                         priority: 200
2430                                 };
2431                         }, this );
2432
2433                         view.set( views );
2434                 },
2435
2436                 hijackThickbox: function() {
2437                         var frame = this;
2438
2439                         if ( ! window.tb_remove || this._tb_remove ) {
2440                                 return;
2441                         }
2442
2443                         this._tb_remove = window.tb_remove;
2444                         window.tb_remove = function() {
2445                                 frame.close();
2446                                 frame.reset();
2447                                 frame.setState( frame.options.state );
2448                                 frame._tb_remove.call( window );
2449                         };
2450                 },
2451
2452                 restoreThickbox: function() {
2453                         if ( ! this._tb_remove ) {
2454                                 return;
2455                         }
2456
2457                         window.tb_remove = this._tb_remove;
2458                         delete this._tb_remove;
2459                 }
2460         });
2461
2462         // Map some of the modal's methods to the frame.
2463         _.each(['open','close','attach','detach','escape'], function( method ) {
2464                 /**
2465                  * @returns {wp.media.view.MediaFrame} Returns itself to allow chaining
2466                  */
2467                 media.view.MediaFrame.prototype[ method ] = function() {
2468                         if ( this.modal ) {
2469                                 this.modal[ method ].apply( this.modal, arguments );
2470                         }
2471                         return this;
2472                 };
2473         });
2474
2475         /**
2476          * wp.media.view.MediaFrame.Select
2477          *
2478          * A frame for selecting an item or items from the media library.
2479          *
2480          * @class
2481          * @augments wp.media.view.MediaFrame
2482          * @augments wp.media.view.Frame
2483          * @augments wp.media.View
2484          * @augments wp.Backbone.View
2485          * @augments Backbone.View
2486          * @mixes wp.media.controller.StateMachine
2487          */
2488         media.view.MediaFrame.Select = media.view.MediaFrame.extend({
2489                 initialize: function() {
2490                         // Call 'initialize' directly on the parent class.
2491                         media.view.MediaFrame.prototype.initialize.apply( this, arguments );
2492
2493                         _.defaults( this.options, {
2494                                 selection: [],
2495                                 library:   {},
2496                                 multiple:  false,
2497                                 state:    'library'
2498                         });
2499
2500                         this.createSelection();
2501                         this.createStates();
2502                         this.bindHandlers();
2503                 },
2504
2505                 /**
2506                  * Attach a selection collection to the frame.
2507                  *
2508                  * A selection is a collection of attachments used for a specific purpose
2509                  * by a media frame. e.g. Selecting an attachment (or many) to insert into
2510                  * post content.
2511                  *
2512                  * @see media.model.Selection
2513                  */
2514                 createSelection: function() {
2515                         var selection = this.options.selection;
2516
2517                         if ( ! (selection instanceof media.model.Selection) ) {
2518                                 this.options.selection = new media.model.Selection( selection, {
2519                                         multiple: this.options.multiple
2520                                 });
2521                         }
2522
2523                         this._selection = {
2524                                 attachments: new media.model.Attachments(),
2525                                 difference: []
2526                         };
2527                 },
2528
2529                 /**
2530                  * Create the default states on the frame.
2531                  */
2532                 createStates: function() {
2533                         var options = this.options;
2534
2535                         if ( this.options.states ) {
2536                                 return;
2537                         }
2538
2539                         // Add the default states.
2540                         this.states.add([
2541                                 // Main states.
2542                                 new media.controller.Library({
2543                                         library:   media.query( options.library ),
2544                                         multiple:  options.multiple,
2545                                         title:     options.title,
2546                                         priority:  20
2547                                 })
2548                         ]);
2549                 },
2550
2551                 /**
2552                  * Bind region mode event callbacks.
2553                  *
2554                  * @see media.controller.Region.render
2555                  */
2556                 bindHandlers: function() {
2557                         this.on( 'router:create:browse', this.createRouter, this );
2558                         this.on( 'router:render:browse', this.browseRouter, this );
2559                         this.on( 'content:create:browse', this.browseContent, this );
2560                         this.on( 'content:render:upload', this.uploadContent, this );
2561                         this.on( 'toolbar:create:select', this.createSelectToolbar, this );
2562                 },
2563
2564                 /**
2565                  * Render callback for the router region in the `browse` mode.
2566                  *
2567                  * @param {wp.media.view.Router} routerView
2568                  */
2569                 browseRouter: function( routerView ) {
2570                         routerView.set({
2571                                 upload: {
2572                                         text:     l10n.uploadFilesTitle,
2573                                         priority: 20
2574                                 },
2575                                 browse: {
2576                                         text:     l10n.mediaLibraryTitle,
2577                                         priority: 40
2578                                 }
2579                         });
2580                 },
2581
2582                 /**
2583                  * Render callback for the content region in the `browse` mode.
2584                  *
2585                  * @param {wp.media.controller.Region} contentRegion
2586                  */
2587                 browseContent: function( contentRegion ) {
2588                         var state = this.state();
2589
2590                         this.$el.removeClass('hide-toolbar');
2591
2592                         // Browse our library of attachments.
2593                         contentRegion.view = new media.view.AttachmentsBrowser({
2594                                 controller: this,
2595                                 collection: state.get('library'),
2596                                 selection:  state.get('selection'),
2597                                 model:      state,
2598                                 sortable:   state.get('sortable'),
2599                                 search:     state.get('searchable'),
2600                                 filters:    state.get('filterable'),
2601                                 date:       state.get('date'),
2602                                 display:    state.has('display') ? state.get('display') : state.get('displaySettings'),
2603                                 dragInfo:   state.get('dragInfo'),
2604
2605                                 idealColumnWidth: state.get('idealColumnWidth'),
2606                                 suggestedWidth:   state.get('suggestedWidth'),
2607                                 suggestedHeight:  state.get('suggestedHeight'),
2608
2609                                 AttachmentView: state.get('AttachmentView')
2610                         });
2611                 },
2612
2613                 /**
2614                  * Render callback for the content region in the `upload` mode.
2615                  */
2616                 uploadContent: function() {
2617                         this.$el.removeClass( 'hide-toolbar' );
2618                         this.content.set( new media.view.UploaderInline({
2619                                 controller: this
2620                         }) );
2621                 },
2622
2623                 /**
2624                  * Toolbars
2625                  *
2626                  * @param {Object} toolbar
2627                  * @param {Object} [options={}]
2628                  * @this wp.media.controller.Region
2629                  */
2630                 createSelectToolbar: function( toolbar, options ) {
2631                         options = options || this.options.button || {};
2632                         options.controller = this;
2633
2634                         toolbar.view = new media.view.Toolbar.Select( options );
2635                 }
2636         });
2637
2638         /**
2639          * wp.media.view.MediaFrame.Post
2640          *
2641          * The frame for manipulating media on the Edit Post page.
2642          *
2643          * @class
2644          * @augments wp.media.view.MediaFrame.Select
2645          * @augments wp.media.view.MediaFrame
2646          * @augments wp.media.view.Frame
2647          * @augments wp.media.View
2648          * @augments wp.Backbone.View
2649          * @augments Backbone.View
2650          * @mixes wp.media.controller.StateMachine
2651          */
2652         media.view.MediaFrame.Post = media.view.MediaFrame.Select.extend({
2653                 initialize: function() {
2654                         this.counts = {
2655                                 audio: {
2656                                         count: media.view.settings.attachmentCounts.audio,
2657                                         state: 'playlist'
2658                                 },
2659                                 video: {
2660                                         count: media.view.settings.attachmentCounts.video,
2661                                         state: 'video-playlist'
2662                                 }
2663                         };
2664
2665                         _.defaults( this.options, {
2666                                 multiple:  true,
2667                                 editing:   false,
2668                                 state:    'insert',
2669                                 metadata:  {}
2670                         });
2671
2672                         // Call 'initialize' directly on the parent class.
2673                         media.view.MediaFrame.Select.prototype.initialize.apply( this, arguments );
2674                         this.createIframeStates();
2675
2676                 },
2677
2678                 /**
2679                  * Create the default states.
2680                  */
2681                 createStates: function() {
2682                         var options = this.options;
2683
2684                         this.states.add([
2685                                 // Main states.
2686                                 new media.controller.Library({
2687                                         id:         'insert',
2688                                         title:      l10n.insertMediaTitle,
2689                                         priority:   20,
2690                                         toolbar:    'main-insert',
2691                                         filterable: 'all',
2692                                         library:    media.query( options.library ),
2693                                         multiple:   options.multiple ? 'reset' : false,
2694                                         editable:   true,
2695
2696                                         // If the user isn't allowed to edit fields,
2697                                         // can they still edit it locally?
2698                                         allowLocalEdits: true,
2699
2700                                         // Show the attachment display settings.
2701                                         displaySettings: true,
2702                                         // Update user settings when users adjust the
2703                                         // attachment display settings.
2704                                         displayUserSettings: true
2705                                 }),
2706
2707                                 new media.controller.Library({
2708                                         id:         'gallery',
2709                                         title:      l10n.createGalleryTitle,
2710                                         priority:   40,
2711                                         toolbar:    'main-gallery',
2712                                         filterable: 'uploaded',
2713                                         multiple:   'add',
2714                                         editable:   false,
2715
2716                                         library:  media.query( _.defaults({
2717                                                 type: 'image'
2718                                         }, options.library ) )
2719                                 }),
2720
2721                                 // Embed states.
2722                                 new media.controller.Embed( { metadata: options.metadata } ),
2723
2724                                 new media.controller.EditImage( { model: options.editImage } ),
2725
2726                                 // Gallery states.
2727                                 new media.controller.GalleryEdit({
2728                                         library: options.selection,
2729                                         editing: options.editing,
2730                                         menu:    'gallery'
2731                                 }),
2732
2733                                 new media.controller.GalleryAdd(),
2734
2735                                 new media.controller.Library({
2736                                         id:         'playlist',
2737                                         title:      l10n.createPlaylistTitle,
2738                                         priority:   60,
2739                                         toolbar:    'main-playlist',
2740                                         filterable: 'uploaded',
2741                                         multiple:   'add',
2742                                         editable:   false,
2743
2744                                         library:  media.query( _.defaults({
2745                                                 type: 'audio'
2746                                         }, options.library ) )
2747                                 }),
2748
2749                                 // Playlist states.
2750                                 new media.controller.CollectionEdit({
2751                                         type: 'audio',
2752                                         collectionType: 'playlist',
2753                                         title:          l10n.editPlaylistTitle,
2754                                         SettingsView:   media.view.Settings.Playlist,
2755                                         library:        options.selection,
2756                                         editing:        options.editing,
2757                                         menu:           'playlist',
2758                                         dragInfoText:   l10n.playlistDragInfo,
2759                                         dragInfo:       false
2760                                 }),
2761
2762                                 new media.controller.CollectionAdd({
2763                                         type: 'audio',
2764                                         collectionType: 'playlist',
2765                                         title: l10n.addToPlaylistTitle
2766                                 }),
2767
2768                                 new media.controller.Library({
2769                                         id:         'video-playlist',
2770                                         title:      l10n.createVideoPlaylistTitle,
2771                                         priority:   60,
2772                                         toolbar:    'main-video-playlist',
2773                                         filterable: 'uploaded',
2774                                         multiple:   'add',
2775                                         editable:   false,
2776
2777                                         library:  media.query( _.defaults({
2778                                                 type: 'video'
2779                                         }, options.library ) )
2780                                 }),
2781
2782                                 new media.controller.CollectionEdit({
2783                                         type: 'video',
2784                                         collectionType: 'playlist',
2785                                         title:          l10n.editVideoPlaylistTitle,
2786                                         SettingsView:   media.view.Settings.Playlist,
2787                                         library:        options.selection,
2788                                         editing:        options.editing,
2789                                         menu:           'video-playlist',
2790                                         dragInfoText:   l10n.videoPlaylistDragInfo,
2791                                         dragInfo:       false
2792                                 }),
2793
2794                                 new media.controller.CollectionAdd({
2795                                         type: 'video',
2796                                         collectionType: 'playlist',
2797                                         title: l10n.addToVideoPlaylistTitle
2798                                 })
2799                         ]);
2800
2801                         if ( media.view.settings.post.featuredImageId ) {
2802                                 this.states.add( new media.controller.FeaturedImage() );
2803                         }
2804                 },
2805
2806                 bindHandlers: function() {
2807                         var handlers, checkCounts;
2808
2809                         media.view.MediaFrame.Select.prototype.bindHandlers.apply( this, arguments );
2810
2811                         this.on( 'activate', this.activate, this );
2812
2813                         // Only bother checking media type counts if one of the counts is zero
2814                         checkCounts = _.find( this.counts, function( type ) {
2815                                 return type.count === 0;
2816                         } );
2817
2818                         if ( typeof checkCounts !== 'undefined' ) {
2819                                 this.listenTo( media.model.Attachments.all, 'change:type', this.mediaTypeCounts );
2820                         }
2821
2822                         this.on( 'menu:create:gallery', this.createMenu, this );
2823                         this.on( 'menu:create:playlist', this.createMenu, this );
2824                         this.on( 'menu:create:video-playlist', this.createMenu, this );
2825                         this.on( 'toolbar:create:main-insert', this.createToolbar, this );
2826                         this.on( 'toolbar:create:main-gallery', this.createToolbar, this );
2827                         this.on( 'toolbar:create:main-playlist', this.createToolbar, this );
2828                         this.on( 'toolbar:create:main-video-playlist', this.createToolbar, this );
2829                         this.on( 'toolbar:create:featured-image', this.featuredImageToolbar, this );
2830                         this.on( 'toolbar:create:main-embed', this.mainEmbedToolbar, this );
2831
2832                         handlers = {
2833                                 menu: {
2834                                         'default': 'mainMenu',
2835                                         'gallery': 'galleryMenu',
2836                                         'playlist': 'playlistMenu',
2837                                         'video-playlist': 'videoPlaylistMenu'
2838                                 },
2839
2840                                 content: {
2841                                         'embed':          'embedContent',
2842                                         'edit-image':     'editImageContent',
2843                                         'edit-selection': 'editSelectionContent'
2844                                 },
2845
2846                                 toolbar: {
2847                                         'main-insert':      'mainInsertToolbar',
2848                                         'main-gallery':     'mainGalleryToolbar',
2849                                         'gallery-edit':     'galleryEditToolbar',
2850                                         'gallery-add':      'galleryAddToolbar',
2851                                         'main-playlist':        'mainPlaylistToolbar',
2852                                         'playlist-edit':        'playlistEditToolbar',
2853                                         'playlist-add':         'playlistAddToolbar',
2854                                         'main-video-playlist': 'mainVideoPlaylistToolbar',
2855                                         'video-playlist-edit': 'videoPlaylistEditToolbar',
2856                                         'video-playlist-add': 'videoPlaylistAddToolbar'
2857                                 }
2858                         };
2859
2860                         _.each( handlers, function( regionHandlers, region ) {
2861                                 _.each( regionHandlers, function( callback, handler ) {
2862                                         this.on( region + ':render:' + handler, this[ callback ], this );
2863                                 }, this );
2864                         }, this );
2865                 },
2866
2867                 activate: function() {
2868                         // Hide menu items for states tied to particular media types if there are no items
2869                         _.each( this.counts, function( type ) {
2870                                 if ( type.count < 1 ) {
2871                                         this.menuItemVisibility( type.state, 'hide' );
2872                                 }
2873                         }, this );
2874                 },
2875
2876                 mediaTypeCounts: function( model, attr ) {
2877                         if ( typeof this.counts[ attr ] !== 'undefined' && this.counts[ attr ].count < 1 ) {
2878                                 this.counts[ attr ].count++;
2879                                 this.menuItemVisibility( this.counts[ attr ].state, 'show' );
2880                         }
2881                 },
2882
2883                 // Menus
2884                 /**
2885                  * @param {wp.Backbone.View} view
2886                  */
2887                 mainMenu: function( view ) {
2888                         view.set({
2889                                 'library-separator': new media.View({
2890                                         className: 'separator',
2891                                         priority: 100
2892                                 })
2893                         });
2894                 },
2895
2896                 menuItemVisibility: function( state, visibility ) {
2897                         var menu = this.menu.get();
2898                         if ( visibility === 'hide' ) {
2899                                 menu.hide( state );
2900                         } else if ( visibility === 'show' ) {
2901                                 menu.show( state );
2902                         }
2903                 },
2904                 /**
2905                  * @param {wp.Backbone.View} view
2906                  */
2907                 galleryMenu: function( view ) {
2908                         var lastState = this.lastState(),
2909                                 previous = lastState && lastState.id,
2910                                 frame = this;
2911
2912                         view.set({
2913                                 cancel: {
2914                                         text:     l10n.cancelGalleryTitle,
2915                                         priority: 20,
2916                                         click:    function() {
2917                                                 if ( previous ) {
2918                                                         frame.setState( previous );
2919                                                 } else {
2920                                                         frame.close();
2921                                                 }
2922
2923                                                 // Keep focus inside media modal
2924                                                 // after canceling a gallery
2925                                                 this.controller.modal.focusManager.focus();
2926                                         }
2927                                 },
2928                                 separateCancel: new media.View({
2929                                         className: 'separator',
2930                                         priority: 40
2931                                 })
2932                         });
2933                 },
2934
2935                 playlistMenu: function( view ) {
2936                         var lastState = this.lastState(),
2937                                 previous = lastState && lastState.id,
2938                                 frame = this;
2939
2940                         view.set({
2941                                 cancel: {
2942                                         text:     l10n.cancelPlaylistTitle,
2943                                         priority: 20,
2944                                         click:    function() {
2945                                                 if ( previous ) {
2946                                                         frame.setState( previous );
2947                                                 } else {
2948                                                         frame.close();
2949                                                 }
2950                                         }
2951                                 },
2952                                 separateCancel: new media.View({
2953                                         className: 'separator',
2954                                         priority: 40
2955                                 })
2956                         });
2957                 },
2958
2959                 videoPlaylistMenu: function( view ) {
2960                         var lastState = this.lastState(),
2961                                 previous = lastState && lastState.id,
2962                                 frame = this;
2963
2964                         view.set({
2965                                 cancel: {
2966                                         text:     l10n.cancelVideoPlaylistTitle,
2967                                         priority: 20,
2968                                         click:    function() {
2969                                                 if ( previous ) {
2970                                                         frame.setState( previous );
2971                                                 } else {
2972                                                         frame.close();
2973                                                 }
2974                                         }
2975                                 },
2976                                 separateCancel: new media.View({
2977                                         className: 'separator',
2978                                         priority: 40
2979                                 })
2980                         });
2981                 },
2982
2983                 // Content
2984                 embedContent: function() {
2985                         var view = new media.view.Embed({
2986                                 controller: this,
2987                                 model:      this.state()
2988                         }).render();
2989
2990                         this.content.set( view );
2991
2992                         if ( ! isTouchDevice ) {
2993                                 view.url.focus();
2994                         }
2995                 },
2996
2997                 editSelectionContent: function() {
2998                         var state = this.state(),
2999                                 selection = state.get('selection'),
3000                                 view;
3001
3002                         view = new media.view.AttachmentsBrowser({
3003                                 controller: this,
3004                                 collection: selection,
3005                                 selection:  selection,
3006                                 model:      state,
3007                                 sortable:   true,
3008                                 search:     false,
3009                                 dragInfo:   true,
3010
3011                                 AttachmentView: media.view.Attachment.EditSelection
3012                         }).render();
3013
3014                         view.toolbar.set( 'backToLibrary', {
3015                                 text:     l10n.returnToLibrary,
3016                                 priority: -100,
3017
3018                                 click: function() {
3019                                         this.controller.content.mode('browse');
3020                                 }
3021                         });
3022
3023                         // Browse our library of attachments.
3024                         this.content.set( view );
3025
3026                         // Trigger the controller to set focus
3027                         this.trigger( 'edit:selection', this );
3028                 },
3029
3030                 editImageContent: function() {
3031                         var image = this.state().get('image'),
3032                                 view = new media.view.EditImage( { model: image, controller: this } ).render();
3033
3034                         this.content.set( view );
3035
3036                         // after creating the wrapper view, load the actual editor via an ajax call
3037                         view.loadEditor();
3038
3039                 },
3040
3041                 // Toolbars
3042
3043                 /**
3044                  * @param {wp.Backbone.View} view
3045                  */
3046                 selectionStatusToolbar: function( view ) {
3047                         var editable = this.state().get('editable');
3048
3049                         view.set( 'selection', new media.view.Selection({
3050                                 controller: this,
3051                                 collection: this.state().get('selection'),
3052                                 priority:   -40,
3053
3054                                 // If the selection is editable, pass the callback to
3055                                 // switch the content mode.
3056                                 editable: editable && function() {
3057                                         this.controller.content.mode('edit-selection');
3058                                 }
3059                         }).render() );
3060                 },
3061
3062                 /**
3063                  * @param {wp.Backbone.View} view
3064                  */
3065                 mainInsertToolbar: function( view ) {
3066                         var controller = this;
3067
3068                         this.selectionStatusToolbar( view );
3069
3070                         view.set( 'insert', {
3071                                 style:    'primary',
3072                                 priority: 80,
3073                                 text:     l10n.insertIntoPost,
3074                                 requires: { selection: true },
3075
3076                                 /**
3077                                  * @fires wp.media.controller.State#insert
3078                                  */
3079                                 click: function() {
3080                                         var state = controller.state(),
3081                                                 selection = state.get('selection');
3082
3083                                         controller.close();
3084                                         state.trigger( 'insert', selection ).reset();
3085                                 }
3086                         });
3087                 },
3088
3089                 /**
3090                  * @param {wp.Backbone.View} view
3091                  */
3092                 mainGalleryToolbar: function( view ) {
3093                         var controller = this;
3094
3095                         this.selectionStatusToolbar( view );
3096
3097                         view.set( 'gallery', {
3098                                 style:    'primary',
3099                                 text:     l10n.createNewGallery,
3100                                 priority: 60,
3101                                 requires: { selection: true },
3102
3103                                 click: function() {
3104                                         var selection = controller.state().get('selection'),
3105                                                 edit = controller.state('gallery-edit'),
3106                                                 models = selection.where({ type: 'image' });
3107
3108                                         edit.set( 'library', new media.model.Selection( models, {
3109                                                 props:    selection.props.toJSON(),
3110                                                 multiple: true
3111                                         }) );
3112
3113                                         this.controller.setState('gallery-edit');
3114
3115                                         // Keep focus inside media modal
3116                                         // after jumping to gallery view
3117                                         this.controller.modal.focusManager.focus();
3118                                 }
3119                         });
3120                 },
3121
3122                 mainPlaylistToolbar: function( view ) {
3123                         var controller = this;
3124
3125                         this.selectionStatusToolbar( view );
3126
3127                         view.set( 'playlist', {
3128                                 style:    'primary',
3129                                 text:     l10n.createNewPlaylist,
3130                                 priority: 100,
3131                                 requires: { selection: true },
3132
3133                                 click: function() {
3134                                         var selection = controller.state().get('selection'),
3135                                                 edit = controller.state('playlist-edit'),
3136                                                 models = selection.where({ type: 'audio' });
3137
3138                                         edit.set( 'library', new media.model.Selection( models, {
3139                                                 props:    selection.props.toJSON(),
3140                                                 multiple: true
3141                                         }) );
3142
3143                                         this.controller.setState('playlist-edit');
3144
3145                                         // Keep focus inside media modal
3146                                         // after jumping to playlist view
3147                                         this.controller.modal.focusManager.focus();
3148                                 }
3149                         });
3150                 },
3151
3152                 mainVideoPlaylistToolbar: function( view ) {
3153                         var controller = this;
3154
3155                         this.selectionStatusToolbar( view );
3156
3157                         view.set( 'video-playlist', {
3158                                 style:    'primary',
3159                                 text:     l10n.createNewVideoPlaylist,
3160                                 priority: 100,
3161                                 requires: { selection: true },
3162
3163                                 click: function() {
3164                                         var selection = controller.state().get('selection'),
3165                                                 edit = controller.state('video-playlist-edit'),
3166                                                 models = selection.where({ type: 'video' });
3167
3168                                         edit.set( 'library', new media.model.Selection( models, {
3169                                                 props:    selection.props.toJSON(),
3170                                                 multiple: true
3171                                         }) );
3172
3173                                         this.controller.setState('video-playlist-edit');
3174
3175                                         // Keep focus inside media modal
3176                                         // after jumping to video playlist view
3177                                         this.controller.modal.focusManager.focus();
3178                                 }
3179                         });
3180                 },
3181
3182                 featuredImageToolbar: function( toolbar ) {
3183                         this.createSelectToolbar( toolbar, {
3184                                 text:  l10n.setFeaturedImage,
3185                                 state: this.options.state
3186                         });
3187                 },
3188
3189                 mainEmbedToolbar: function( toolbar ) {
3190                         toolbar.view = new media.view.Toolbar.Embed({
3191                                 controller: this
3192                         });
3193                 },
3194
3195                 galleryEditToolbar: function() {
3196                         var editing = this.state().get('editing');
3197                         this.toolbar.set( new media.view.Toolbar({
3198                                 controller: this,
3199                                 items: {
3200                                         insert: {
3201                                                 style:    'primary',
3202                                                 text:     editing ? l10n.updateGallery : l10n.insertGallery,
3203                                                 priority: 80,
3204                                                 requires: { library: true },
3205
3206                                                 /**
3207                                                  * @fires wp.media.controller.State#update
3208                                                  */
3209                                                 click: function() {
3210                                                         var controller = this.controller,
3211                                                                 state = controller.state();
3212
3213                                                         controller.close();
3214                                                         state.trigger( 'update', state.get('library') );
3215
3216                                                         // Restore and reset the default state.
3217                                                         controller.setState( controller.options.state );
3218                                                         controller.reset();
3219                                                 }
3220                                         }
3221                                 }
3222                         }) );
3223                 },
3224
3225                 galleryAddToolbar: function() {
3226                         this.toolbar.set( new media.view.Toolbar({
3227                                 controller: this,
3228                                 items: {
3229                                         insert: {
3230                                                 style:    'primary',
3231                                                 text:     l10n.addToGallery,
3232                                                 priority: 80,
3233                                                 requires: { selection: true },
3234
3235                                                 /**
3236                                                  * @fires wp.media.controller.State#reset
3237                                                  */
3238                                                 click: function() {
3239                                                         var controller = this.controller,
3240                                                                 state = controller.state(),
3241                                                                 edit = controller.state('gallery-edit');
3242
3243                                                         edit.get('library').add( state.get('selection').models );
3244                                                         state.trigger('reset');
3245                                                         controller.setState('gallery-edit');
3246                                                 }
3247                                         }
3248                                 }
3249                         }) );
3250                 },
3251
3252                 playlistEditToolbar: function() {
3253                         var editing = this.state().get('editing');
3254                         this.toolbar.set( new media.view.Toolbar({
3255                                 controller: this,
3256                                 items: {
3257                                         insert: {
3258                                                 style:    'primary',
3259                                                 text:     editing ? l10n.updatePlaylist : l10n.insertPlaylist,
3260                                                 priority: 80,
3261                                                 requires: { library: true },
3262
3263                                                 /**
3264                                                  * @fires wp.media.controller.State#update
3265                                                  */
3266                                                 click: function() {
3267                                                         var controller = this.controller,
3268                                                                 state = controller.state();
3269
3270                                                         controller.close();
3271                                                         state.trigger( 'update', state.get('library') );
3272
3273                                                         // Restore and reset the default state.
3274                                                         controller.setState( controller.options.state );
3275                                                         controller.reset();
3276                                                 }
3277                                         }
3278                                 }
3279                         }) );
3280                 },
3281
3282                 playlistAddToolbar: function() {
3283                         this.toolbar.set( new media.view.Toolbar({
3284                                 controller: this,
3285                                 items: {
3286                                         insert: {
3287                                                 style:    'primary',
3288                                                 text:     l10n.addToPlaylist,
3289                                                 priority: 80,
3290                                                 requires: { selection: true },
3291
3292                                                 /**
3293                                                  * @fires wp.media.controller.State#reset
3294                                                  */
3295                                                 click: function() {
3296                                                         var controller = this.controller,
3297                                                                 state = controller.state(),
3298                                                                 edit = controller.state('playlist-edit');
3299
3300                                                         edit.get('library').add( state.get('selection').models );
3301                                                         state.trigger('reset');
3302                                                         controller.setState('playlist-edit');
3303                                                 }
3304                                         }
3305                                 }
3306                         }) );
3307                 },
3308
3309                 videoPlaylistEditToolbar: function() {
3310                         var editing = this.state().get('editing');
3311                         this.toolbar.set( new media.view.Toolbar({
3312                                 controller: this,
3313                                 items: {
3314                                         insert: {
3315                                                 style:    'primary',
3316                                                 text:     editing ? l10n.updateVideoPlaylist : l10n.insertVideoPlaylist,
3317                                                 priority: 140,
3318                                                 requires: { library: true },
3319
3320                                                 click: function() {
3321                                                         var controller = this.controller,
3322                                                                 state = controller.state(),
3323                                                                 library = state.get('library');
3324
3325                                                         library.type = 'video';
3326
3327                                                         controller.close();
3328                                                         state.trigger( 'update', library );
3329
3330                                                         // Restore and reset the default state.
3331                                                         controller.setState( controller.options.state );
3332                                                         controller.reset();
3333                                                 }
3334                                         }
3335                                 }
3336                         }) );
3337                 },
3338
3339                 videoPlaylistAddToolbar: function() {
3340                         this.toolbar.set( new media.view.Toolbar({
3341                                 controller: this,
3342                                 items: {
3343                                         insert: {
3344                                                 style:    'primary',
3345                                                 text:     l10n.addToVideoPlaylist,
3346                                                 priority: 140,
3347                                                 requires: { selection: true },
3348
3349                                                 click: function() {
3350                                                         var controller = this.controller,
3351                                                                 state = controller.state(),
3352                                                                 edit = controller.state('video-playlist-edit');
3353
3354                                                         edit.get('library').add( state.get('selection').models );
3355                                                         state.trigger('reset');
3356                                                         controller.setState('video-playlist-edit');
3357                                                 }
3358                                         }
3359                                 }
3360                         }) );
3361                 }
3362         });
3363
3364         /**
3365          * wp.media.view.MediaFrame.ImageDetails
3366          *
3367          * A media frame for manipulating an image that's already been inserted
3368          * into a post.
3369          *
3370          * @class
3371          * @augments wp.media.view.MediaFrame.Select
3372          * @augments wp.media.view.MediaFrame
3373          * @augments wp.media.view.Frame
3374          * @augments wp.media.View
3375          * @augments wp.Backbone.View
3376          * @augments Backbone.View
3377          * @mixes wp.media.controller.StateMachine
3378          */
3379         media.view.MediaFrame.ImageDetails = media.view.MediaFrame.Select.extend({
3380                 defaults: {
3381                         id:      'image',
3382                         url:     '',
3383                         menu:    'image-details',
3384                         content: 'image-details',
3385                         toolbar: 'image-details',
3386                         type:    'link',
3387                         title:    l10n.imageDetailsTitle,
3388                         priority: 120
3389                 },
3390
3391                 initialize: function( options ) {
3392                         this.image = new media.model.PostImage( options.metadata );
3393                         this.options.selection = new media.model.Selection( this.image.attachment, { multiple: false } );
3394                         media.view.MediaFrame.Select.prototype.initialize.apply( this, arguments );
3395                 },
3396
3397                 bindHandlers: function() {
3398                         media.view.MediaFrame.Select.prototype.bindHandlers.apply( this, arguments );
3399                         this.on( 'menu:create:image-details', this.createMenu, this );
3400                         this.on( 'content:create:image-details', this.imageDetailsContent, this );
3401                         this.on( 'content:render:edit-image', this.editImageContent, this );
3402                         this.on( 'toolbar:render:image-details', this.renderImageDetailsToolbar, this );
3403                         // override the select toolbar
3404                         this.on( 'toolbar:render:replace', this.renderReplaceImageToolbar, this );
3405                 },
3406
3407                 createStates: function() {
3408                         this.states.add([
3409                                 new media.controller.ImageDetails({
3410                                         image: this.image,
3411                                         editable: false
3412                                 }),
3413                                 new media.controller.ReplaceImage({
3414                                         id: 'replace-image',
3415                                         library:   media.query( { type: 'image' } ),
3416                                         image: this.image,
3417                                         multiple:  false,
3418                                         title:     l10n.imageReplaceTitle,
3419                                         toolbar: 'replace',
3420                                         priority:  80,
3421                                         displaySettings: true
3422                                 }),
3423                                 new media.controller.EditImage( {
3424                                         image: this.image,
3425                                         selection: this.options.selection
3426                                 } )
3427                         ]);
3428                 },
3429
3430                 imageDetailsContent: function( options ) {
3431                         options.view = new media.view.ImageDetails({
3432                                 controller: this,
3433                                 model: this.state().image,
3434                                 attachment: this.state().image.attachment
3435                         });
3436                 },
3437
3438                 editImageContent: function() {
3439                         var state = this.state(),
3440                                 model = state.get('image'),
3441                                 view;
3442
3443                         if ( ! model ) {
3444                                 return;
3445                         }
3446
3447                         view = new media.view.EditImage( { model: model, controller: this } ).render();
3448
3449                         this.content.set( view );
3450
3451                         // after bringing in the frame, load the actual editor via an ajax call
3452                         view.loadEditor();
3453
3454                 },
3455
3456                 renderImageDetailsToolbar: function() {
3457                         this.toolbar.set( new media.view.Toolbar({
3458                                 controller: this,
3459                                 items: {
3460                                         select: {
3461                                                 style:    'primary',
3462                                                 text:     l10n.update,
3463                                                 priority: 80,
3464
3465                                                 click: function() {
3466                                                         var controller = this.controller,
3467                                                                 state = controller.state();
3468
3469                                                         controller.close();
3470
3471                                                         // not sure if we want to use wp.media.string.image which will create a shortcode or
3472                                                         // perhaps wp.html.string to at least to build the <img />
3473                                                         state.trigger( 'update', controller.image.toJSON() );
3474
3475                                                         // Restore and reset the default state.
3476                                                         controller.setState( controller.options.state );
3477                                                         controller.reset();
3478                                                 }
3479                                         }
3480                                 }
3481                         }) );
3482                 },
3483
3484                 renderReplaceImageToolbar: function() {
3485                         var frame = this,
3486                                 lastState = frame.lastState(),
3487                                 previous = lastState && lastState.id;
3488
3489                         this.toolbar.set( new media.view.Toolbar({
3490                                 controller: this,
3491                                 items: {
3492                                         back: {
3493                                                 text:     l10n.back,
3494                                                 priority: 20,
3495                                                 click:    function() {
3496                                                         if ( previous ) {
3497                                                                 frame.setState( previous );
3498                                                         } else {
3499                                                                 frame.close();
3500                                                         }
3501                                                 }
3502                                         },
3503
3504                                         replace: {
3505                                                 style:    'primary',
3506                                                 text:     l10n.replace,
3507                                                 priority: 80,
3508
3509                                                 click: function() {
3510                                                         var controller = this.controller,
3511                                                                 state = controller.state(),
3512                                                                 selection = state.get( 'selection' ),
3513                                                                 attachment = selection.single();
3514
3515                                                         controller.close();
3516
3517                                                         controller.image.changeAttachment( attachment, state.display( attachment ) );
3518
3519                                                         // not sure if we want to use wp.media.string.image which will create a shortcode or
3520                                                         // perhaps wp.html.string to at least to build the <img />
3521                                                         state.trigger( 'replace', controller.image.toJSON() );
3522
3523                                                         // Restore and reset the default state.
3524                                                         controller.setState( controller.options.state );
3525                                                         controller.reset();
3526                                                 }
3527                                         }
3528                                 }
3529                         }) );
3530                 }
3531
3532         });
3533
3534         /**
3535          * wp.media.view.Modal
3536          *
3537          * A modal view, which the media modal uses as its default container.
3538          *
3539          * @class
3540          * @augments wp.media.View
3541          * @augments wp.Backbone.View
3542          * @augments Backbone.View
3543          */
3544         media.view.Modal = media.View.extend({
3545                 tagName:  'div',
3546                 template: media.template('media-modal'),
3547
3548                 attributes: {
3549                         tabindex: 0
3550                 },
3551
3552                 events: {
3553                         'click .media-modal-backdrop, .media-modal-close': 'escapeHandler',
3554                         'keydown': 'keydown'
3555                 },
3556
3557                 initialize: function() {
3558                         _.defaults( this.options, {
3559                                 container: document.body,
3560                                 title:     '',
3561                                 propagate: true,
3562                                 freeze:    true
3563                         });
3564
3565                         this.focusManager = new media.view.FocusManager({
3566                                 el: this.el
3567                         });
3568                 },
3569                 /**
3570                  * @returns {Object}
3571                  */
3572                 prepare: function() {
3573                         return {
3574                                 title: this.options.title
3575                         };
3576                 },
3577
3578                 /**
3579                  * @returns {wp.media.view.Modal} Returns itself to allow chaining
3580                  */
3581                 attach: function() {
3582                         if ( this.views.attached ) {
3583                                 return this;
3584                         }
3585
3586                         if ( ! this.views.rendered ) {
3587                                 this.render();
3588                         }
3589
3590                         this.$el.appendTo( this.options.container );
3591
3592                         // Manually mark the view as attached and trigger ready.
3593                         this.views.attached = true;
3594                         this.views.ready();
3595
3596                         return this.propagate('attach');
3597                 },
3598
3599                 /**
3600                  * @returns {wp.media.view.Modal} Returns itself to allow chaining
3601                  */
3602                 detach: function() {
3603                         if ( this.$el.is(':visible') ) {
3604                                 this.close();
3605                         }
3606
3607                         this.$el.detach();
3608                         this.views.attached = false;
3609                         return this.propagate('detach');
3610                 },
3611
3612                 /**
3613                  * @returns {wp.media.view.Modal} Returns itself to allow chaining
3614                  */
3615                 open: function() {
3616                         var $el = this.$el,
3617                                 options = this.options,
3618                                 mceEditor;
3619
3620                         if ( $el.is(':visible') ) {
3621                                 return this;
3622                         }
3623
3624                         if ( ! this.views.attached ) {
3625                                 this.attach();
3626                         }
3627
3628                         // If the `freeze` option is set, record the window's scroll position.
3629                         if ( options.freeze ) {
3630                                 this._freeze = {
3631                                         scrollTop: $( window ).scrollTop()
3632                                 };
3633                         }
3634
3635                         // Disable page scrolling.
3636                         $( 'body' ).addClass( 'modal-open' );
3637
3638                         $el.show();
3639
3640                         // Try to close the onscreen keyboard
3641                         if ( 'ontouchend' in document ) {
3642                                 if ( ( mceEditor = window.tinymce && window.tinymce.activeEditor )  && ! mceEditor.isHidden() && mceEditor.iframeElement ) {
3643                                         mceEditor.iframeElement.focus();
3644                                         mceEditor.iframeElement.blur();
3645
3646                                         setTimeout( function() {
3647                                                 mceEditor.iframeElement.blur();
3648                                         }, 100 );
3649                                 }
3650                         }
3651
3652                         this.$el.focus();
3653
3654                         return this.propagate('open');
3655                 },
3656
3657                 /**
3658                  * @param {Object} options
3659                  * @returns {wp.media.view.Modal} Returns itself to allow chaining
3660                  */
3661                 close: function( options ) {
3662                         var freeze = this._freeze;
3663
3664                         if ( ! this.views.attached || ! this.$el.is(':visible') ) {
3665                                 return this;
3666                         }
3667
3668                         // Enable page scrolling.
3669                         $( 'body' ).removeClass( 'modal-open' );
3670
3671                         // Hide modal and remove restricted media modal tab focus once it's closed
3672                         this.$el.hide().undelegate( 'keydown' );
3673
3674                         // Put focus back in useful location once modal is closed
3675                         $('#wpbody-content').focus();
3676
3677                         this.propagate('close');
3678
3679                         // If the `freeze` option is set, restore the container's scroll position.
3680                         if ( freeze ) {
3681                                 $( window ).scrollTop( freeze.scrollTop );
3682                         }
3683
3684                         if ( options && options.escape ) {
3685                                 this.propagate('escape');
3686                         }
3687
3688                         return this;
3689                 },
3690                 /**
3691                  * @returns {wp.media.view.Modal} Returns itself to allow chaining
3692                  */
3693                 escape: function() {
3694                         return this.close({ escape: true });
3695                 },
3696                 /**
3697                  * @param {Object} event
3698                  */
3699                 escapeHandler: function( event ) {
3700                         event.preventDefault();
3701                         this.escape();
3702                 },
3703
3704                 /**
3705                  * @param {Array|Object} content Views to register to '.media-modal-content'
3706                  * @returns {wp.media.view.Modal} Returns itself to allow chaining
3707                  */
3708                 content: function( content ) {
3709                         this.views.set( '.media-modal-content', content );
3710                         return this;
3711                 },
3712
3713                 /**
3714                  * Triggers a modal event and if the `propagate` option is set,
3715                  * forwards events to the modal's controller.
3716                  *
3717                  * @param {string} id
3718                  * @returns {wp.media.view.Modal} Returns itself to allow chaining
3719                  */
3720                 propagate: function( id ) {
3721                         this.trigger( id );
3722
3723                         if ( this.options.propagate ) {
3724                                 this.controller.trigger( id );
3725                         }
3726
3727                         return this;
3728                 },
3729                 /**
3730                  * @param {Object} event
3731                  */
3732                 keydown: function( event ) {
3733                         // Close the modal when escape is pressed.
3734                         if ( 27 === event.which && this.$el.is(':visible') ) {
3735                                 this.escape();
3736                                 event.stopImmediatePropagation();
3737                         }
3738                 }
3739         });
3740
3741         /**
3742          * wp.media.view.FocusManager
3743          *
3744          * @class
3745          * @augments wp.media.View
3746          * @augments wp.Backbone.View
3747          * @augments Backbone.View
3748          */
3749         media.view.FocusManager = media.View.extend({
3750
3751                 events: {
3752                         'keydown': 'constrainTabbing'
3753                 },
3754
3755                 focus: function() { // Reset focus on first left menu item
3756                         this.$('.media-menu-item').first().focus();
3757                 },
3758                 /**
3759                  * @param {Object} event
3760                  */
3761                 constrainTabbing: function( event ) {
3762                         var tabbables;
3763
3764                         // Look for the tab key.
3765                         if ( 9 !== event.keyCode ) {
3766                                 return;
3767                         }
3768
3769                         tabbables = this.$( ':tabbable' );
3770
3771                         // Keep tab focus within media modal while it's open
3772                         if ( tabbables.last()[0] === event.target && ! event.shiftKey ) {
3773                                 tabbables.first().focus();
3774                                 return false;
3775                         } else if ( tabbables.first()[0] === event.target && event.shiftKey ) {
3776                                 tabbables.last().focus();
3777                                 return false;
3778                         }
3779                 }
3780
3781         });
3782
3783         /**
3784          * wp.media.view.UploaderWindow
3785          *
3786          * An uploader window that allows for dragging and dropping media.
3787          *
3788          * @class
3789          * @augments wp.media.View
3790          * @augments wp.Backbone.View
3791          * @augments Backbone.View
3792          *
3793          * @param {object} [options]                   Options hash passed to the view.
3794          * @param {object} [options.uploader]          Uploader properties.
3795          * @param {jQuery} [options.uploader.browser]
3796          * @param {jQuery} [options.uploader.dropzone] jQuery collection of the dropzone.
3797          * @param {object} [options.uploader.params]
3798          */
3799         media.view.UploaderWindow = media.View.extend({
3800                 tagName:   'div',
3801                 className: 'uploader-window',
3802                 template:  media.template('uploader-window'),
3803
3804                 initialize: function() {
3805                         var uploader;
3806
3807                         this.$browser = $('<a href="#" class="browser" />').hide().appendTo('body');
3808
3809                         uploader = this.options.uploader = _.defaults( this.options.uploader || {}, {
3810                                 dropzone:  this.$el,
3811                                 browser:   this.$browser,
3812                                 params:    {}
3813                         });
3814
3815                         // Ensure the dropzone is a jQuery collection.
3816                         if ( uploader.dropzone && ! (uploader.dropzone instanceof $) ) {
3817                                 uploader.dropzone = $( uploader.dropzone );
3818                         }
3819
3820                         this.controller.on( 'activate', this.refresh, this );
3821
3822                         this.controller.on( 'detach', function() {
3823                                 this.$browser.remove();
3824                         }, this );
3825                 },
3826
3827                 refresh: function() {
3828                         if ( this.uploader ) {
3829                                 this.uploader.refresh();
3830                         }
3831                 },
3832
3833                 ready: function() {
3834                         var postId = media.view.settings.post.id,
3835                                 dropzone;
3836
3837                         // If the uploader already exists, bail.
3838                         if ( this.uploader ) {
3839                                 return;
3840                         }
3841
3842                         if ( postId ) {
3843                                 this.options.uploader.params.post_id = postId;
3844                         }
3845                         this.uploader = new wp.Uploader( this.options.uploader );
3846
3847                         dropzone = this.uploader.dropzone;
3848                         dropzone.on( 'dropzone:enter', _.bind( this.show, this ) );
3849                         dropzone.on( 'dropzone:leave', _.bind( this.hide, this ) );
3850
3851                         $( this.uploader ).on( 'uploader:ready', _.bind( this._ready, this ) );
3852                 },
3853
3854                 _ready: function() {
3855                         this.controller.trigger( 'uploader:ready' );
3856                 },
3857
3858                 show: function() {
3859                         var $el = this.$el.show();
3860
3861                         // Ensure that the animation is triggered by waiting until
3862                         // the transparent element is painted into the DOM.
3863                         _.defer( function() {
3864                                 $el.css({ opacity: 1 });
3865                         });
3866                 },
3867
3868                 hide: function() {
3869                         var $el = this.$el.css({ opacity: 0 });
3870
3871                         media.transition( $el ).done( function() {
3872                                 // Transition end events are subject to race conditions.
3873                                 // Make sure that the value is set as intended.
3874                                 if ( '0' === $el.css('opacity') ) {
3875                                         $el.hide();
3876                                 }
3877                         });
3878
3879                         // https://core.trac.wordpress.org/ticket/27341
3880                         _.delay( function() {
3881                                 if ( '0' === $el.css('opacity') && $el.is(':visible') ) {
3882                                         $el.hide();
3883                                 }
3884                         }, 500 );
3885                 }
3886         });
3887
3888         /**
3889          * Creates a dropzone on WP editor instances (elements with .wp-editor-wrap
3890          * or #wp-fullscreen-body) and relays drag'n'dropped files to a media workflow.
3891          *
3892          * wp.media.view.EditorUploader
3893          *
3894          * @class
3895          * @augments wp.media.View
3896          * @augments wp.Backbone.View
3897          * @augments Backbone.View
3898          */
3899         media.view.EditorUploader = media.View.extend({
3900                 tagName:   'div',
3901                 className: 'uploader-editor',
3902                 template:  media.template( 'uploader-editor' ),
3903
3904                 localDrag: false,
3905                 overContainer: false,
3906                 overDropzone: false,
3907                 draggingFile: null,
3908
3909                 /**
3910                  * Bind drag'n'drop events to callbacks.
3911                  */
3912                 initialize: function() {
3913                         var self = this;
3914
3915                         this.initialized = false;
3916
3917                         // Bail if not enabled or UA does not support drag'n'drop or File API.
3918                         if ( ! window.tinyMCEPreInit || ! window.tinyMCEPreInit.dragDropUpload || ! this.browserSupport() ) {
3919                                 return this;
3920                         }
3921
3922                         this.$document = $(document);
3923                         this.dropzones = [];
3924                         this.files = [];
3925
3926                         this.$document.on( 'drop', '.uploader-editor', _.bind( this.drop, this ) );
3927                         this.$document.on( 'dragover', '.uploader-editor', _.bind( this.dropzoneDragover, this ) );
3928                         this.$document.on( 'dragleave', '.uploader-editor', _.bind( this.dropzoneDragleave, this ) );
3929                         this.$document.on( 'click', '.uploader-editor', _.bind( this.click, this ) );
3930
3931                         this.$document.on( 'dragover', _.bind( this.containerDragover, this ) );
3932                         this.$document.on( 'dragleave', _.bind( this.containerDragleave, this ) );
3933
3934                         this.$document.on( 'dragstart dragend drop', function( event ) {
3935                                 self.localDrag = event.type === 'dragstart';
3936                         });
3937
3938                         this.initialized = true;
3939                         return this;
3940                 },
3941
3942                 /**
3943                  * Check browser support for drag'n'drop.
3944                  *
3945                  * @return Boolean
3946                  */
3947                 browserSupport: function() {
3948                         var supports = false, div = document.createElement('div');
3949
3950                         supports = ( 'draggable' in div ) || ( 'ondragstart' in div && 'ondrop' in div );
3951                         supports = supports && !! ( window.File && window.FileList && window.FileReader );
3952                         return supports;
3953                 },
3954
3955                 isDraggingFile: function( event ) {
3956                         if ( this.draggingFile !== null ) {
3957                                 return this.draggingFile;
3958                         }
3959
3960                         if ( _.isUndefined( event.originalEvent ) || _.isUndefined( event.originalEvent.dataTransfer ) ) {
3961                                 return false;
3962                         }
3963
3964                         this.draggingFile = _.indexOf( event.originalEvent.dataTransfer.types, 'Files' ) > -1 &&
3965                                 _.indexOf( event.originalEvent.dataTransfer.types, 'text/plain' ) === -1;
3966
3967                         return this.draggingFile;
3968                 },
3969
3970                 refresh: function( e ) {
3971                         var dropzone_id;
3972                         for ( dropzone_id in this.dropzones ) {
3973                                 // Hide the dropzones only if dragging has left the screen.
3974                                 this.dropzones[ dropzone_id ].toggle( this.overContainer || this.overDropzone );
3975                         }
3976
3977                         if ( ! _.isUndefined( e ) ) {
3978                                 $( e.target ).closest( '.uploader-editor' ).toggleClass( 'droppable', this.overDropzone );
3979                         }
3980
3981                         if ( ! this.overContainer && ! this.overDropzone ) {
3982                                 this.draggingFile = null;
3983                         }
3984
3985                         return this;
3986                 },
3987
3988                 render: function() {
3989                         if ( ! this.initialized ) {
3990                                 return this;
3991                         }
3992
3993                         media.View.prototype.render.apply( this, arguments );
3994                         $( '.wp-editor-wrap, #wp-fullscreen-body' ).each( _.bind( this.attach, this ) );
3995                         return this;
3996                 },
3997
3998                 attach: function( index, editor ) {
3999                         // Attach a dropzone to an editor.
4000                         var dropzone = this.$el.clone();
4001                         this.dropzones.push( dropzone );
4002                         $( editor ).append( dropzone );
4003                         return this;
4004                 },
4005
4006                 /**
4007                  * When a file is dropped on the editor uploader, open up an editor media workflow
4008                  * and upload the file immediately.
4009                  *
4010                  * @param  {jQuery.Event} event The 'drop' event.
4011                  */
4012                 drop: function( event ) {
4013                         var $wrap = null, uploadView;
4014
4015                         this.containerDragleave( event );
4016                         this.dropzoneDragleave( event );
4017
4018                         this.files = event.originalEvent.dataTransfer.files;
4019                         if ( this.files.length < 1 ) {
4020                                 return;
4021                         }
4022
4023                         // Set the active editor to the drop target.
4024                         $wrap = $( event.target ).parents( '.wp-editor-wrap' );
4025                         if ( $wrap.length > 0 && $wrap[0].id ) {
4026                                 window.wpActiveEditor = $wrap[0].id.slice( 3, -5 );
4027                         }
4028
4029                         if ( ! this.workflow ) {
4030                                 this.workflow = wp.media.editor.open( 'content', {
4031                                         frame:    'post',
4032                                         state:    'insert',
4033                                         title:    wp.media.view.l10n.addMedia,
4034                                         multiple: true
4035                                 });
4036                                 uploadView = this.workflow.uploader;
4037                                 if ( uploadView.uploader && uploadView.uploader.ready ) {
4038                                         this.addFiles.apply( this );
4039                                 } else {
4040                                         this.workflow.on( 'uploader:ready', this.addFiles, this );
4041                                 }
4042                         } else {
4043                                 this.workflow.state().reset();
4044                                 this.addFiles.apply( this );
4045                                 this.workflow.open();
4046                         }
4047
4048                         return false;
4049                 },
4050
4051                 /**
4052                  * Add the files to the uploader.
4053                  */
4054                 addFiles: function() {
4055                         if ( this.files.length ) {
4056                                 this.workflow.uploader.uploader.uploader.addFile( _.toArray( this.files ) );
4057                                 this.files = [];
4058                         }
4059                         return this;
4060                 },
4061
4062                 containerDragover: function( event ) {
4063                         if ( this.localDrag || ! this.isDraggingFile( event ) ) {
4064                                 return;
4065                         }
4066
4067                         this.overContainer = true;
4068                         this.refresh();
4069                 },
4070
4071                 containerDragleave: function() {
4072                         this.overContainer = false;
4073
4074                         // Throttle dragleave because it's called when bouncing from some elements to others.
4075                         _.delay( _.bind( this.refresh, this ), 50 );
4076                 },
4077
4078                 dropzoneDragover: function( event ) {
4079                         if ( this.localDrag || ! this.isDraggingFile( event ) ) {
4080                                 return;
4081                         }
4082
4083                         this.overDropzone = true;
4084                         this.refresh( event );
4085                         return false;
4086                 },
4087
4088                 dropzoneDragleave: function( e ) {
4089                         this.overDropzone = false;
4090                         _.delay( _.bind( this.refresh, this, e ), 50 );
4091                 },
4092
4093                 click: function( e ) {
4094                         // In the rare case where the dropzone gets stuck, hide it on click.
4095                         this.containerDragleave( e );
4096                         this.dropzoneDragleave( e );
4097                         this.localDrag = false;
4098                 }
4099         });
4100
4101         /**
4102          * wp.media.view.UploaderInline
4103          *
4104          * The inline uploader that shows up in the 'Upload Files' tab.
4105          *
4106          * @class
4107          * @augments wp.media.View
4108          * @augments wp.Backbone.View
4109          * @augments Backbone.View
4110          */
4111         media.view.UploaderInline = media.View.extend({
4112                 tagName:   'div',
4113                 className: 'uploader-inline',
4114                 template:  media.template('uploader-inline'),
4115
4116                 events: {
4117                         'click .close': 'hide'
4118                 },
4119
4120                 initialize: function() {
4121                         _.defaults( this.options, {
4122                                 message: '',
4123                                 status:  true,
4124                                 canClose: false
4125                         });
4126
4127                         if ( ! this.options.$browser && this.controller.uploader ) {
4128                                 this.options.$browser = this.controller.uploader.$browser;
4129                         }
4130
4131                         if ( _.isUndefined( this.options.postId ) ) {
4132                                 this.options.postId = media.view.settings.post.id;
4133                         }
4134
4135                         if ( this.options.status ) {
4136                                 this.views.set( '.upload-inline-status', new media.view.UploaderStatus({
4137                                         controller: this.controller
4138                                 }) );
4139                         }
4140                 },
4141
4142                 prepare: function() {
4143                         var suggestedWidth = this.controller.state().get('suggestedWidth'),
4144                                 suggestedHeight = this.controller.state().get('suggestedHeight'),
4145                                 data = {};
4146
4147                         data.message = this.options.message;
4148                         data.canClose = this.options.canClose;
4149
4150                         if ( suggestedWidth && suggestedHeight ) {
4151                                 data.suggestedWidth = suggestedWidth;
4152                                 data.suggestedHeight = suggestedHeight;
4153                         }
4154
4155                         return data;
4156                 },
4157                 /**
4158                  * @returns {wp.media.view.UploaderInline} Returns itself to allow chaining
4159                  */
4160                 dispose: function() {
4161                         if ( this.disposing ) {
4162                                 /**
4163                                  * call 'dispose' directly on the parent class
4164                                  */
4165                                 return media.View.prototype.dispose.apply( this, arguments );
4166                         }
4167
4168                         // Run remove on `dispose`, so we can be sure to refresh the
4169                         // uploader with a view-less DOM. Track whether we're disposing
4170                         // so we don't trigger an infinite loop.
4171                         this.disposing = true;
4172                         return this.remove();
4173                 },
4174                 /**
4175                  * @returns {wp.media.view.UploaderInline} Returns itself to allow chaining
4176                  */
4177                 remove: function() {
4178                         /**
4179                          * call 'remove' directly on the parent class
4180                          */
4181                         var result = media.View.prototype.remove.apply( this, arguments );
4182
4183                         _.defer( _.bind( this.refresh, this ) );
4184                         return result;
4185                 },
4186
4187                 refresh: function() {
4188                         var uploader = this.controller.uploader;
4189
4190                         if ( uploader ) {
4191                                 uploader.refresh();
4192                         }
4193                 },
4194                 /**
4195                  * @returns {wp.media.view.UploaderInline}
4196                  */
4197                 ready: function() {
4198                         var $browser = this.options.$browser,
4199                                 $placeholder;
4200
4201                         if ( this.controller.uploader ) {
4202                                 $placeholder = this.$('.browser');
4203
4204                                 // Check if we've already replaced the placeholder.
4205                                 if ( $placeholder[0] === $browser[0] ) {
4206                                         return;
4207                                 }
4208
4209                                 $browser.detach().text( $placeholder.text() );
4210                                 $browser[0].className = $placeholder[0].className;
4211                                 $placeholder.replaceWith( $browser.show() );
4212                         }
4213
4214                         this.refresh();
4215                         return this;
4216                 },
4217                 show: function() {
4218                         this.$el.removeClass( 'hidden' );
4219                 },
4220                 hide: function() {
4221                         this.$el.addClass( 'hidden' );
4222                 }
4223
4224         });
4225
4226         /**
4227          * wp.media.view.UploaderStatus
4228          *
4229          * An uploader status for on-going uploads.
4230          *
4231          * @class
4232          * @augments wp.media.View
4233          * @augments wp.Backbone.View
4234          * @augments Backbone.View
4235          */
4236         media.view.UploaderStatus = media.View.extend({
4237                 className: 'media-uploader-status',
4238                 template:  media.template('uploader-status'),
4239
4240                 events: {
4241                         'click .upload-dismiss-errors': 'dismiss'
4242                 },
4243
4244                 initialize: function() {
4245                         this.queue = wp.Uploader.queue;
4246                         this.queue.on( 'add remove reset', this.visibility, this );
4247                         this.queue.on( 'add remove reset change:percent', this.progress, this );
4248                         this.queue.on( 'add remove reset change:uploading', this.info, this );
4249
4250                         this.errors = wp.Uploader.errors;
4251                         this.errors.reset();
4252                         this.errors.on( 'add remove reset', this.visibility, this );
4253                         this.errors.on( 'add', this.error, this );
4254                 },
4255                 /**
4256                  * @global wp.Uploader
4257                  * @returns {wp.media.view.UploaderStatus}
4258                  */
4259                 dispose: function() {
4260                         wp.Uploader.queue.off( null, null, this );
4261                         /**
4262                          * call 'dispose' directly on the parent class
4263                          */
4264                         media.View.prototype.dispose.apply( this, arguments );
4265                         return this;
4266                 },
4267
4268                 visibility: function() {
4269                         this.$el.toggleClass( 'uploading', !! this.queue.length );
4270                         this.$el.toggleClass( 'errors', !! this.errors.length );
4271                         this.$el.toggle( !! this.queue.length || !! this.errors.length );
4272                 },
4273
4274                 ready: function() {
4275                         _.each({
4276                                 '$bar':      '.media-progress-bar div',
4277                                 '$index':    '.upload-index',
4278                                 '$total':    '.upload-total',
4279                                 '$filename': '.upload-filename'
4280                         }, function( selector, key ) {
4281                                 this[ key ] = this.$( selector );
4282                         }, this );
4283
4284                         this.visibility();
4285                         this.progress();
4286                         this.info();
4287                 },
4288
4289                 progress: function() {
4290                         var queue = this.queue,
4291                                 $bar = this.$bar;
4292
4293                         if ( ! $bar || ! queue.length ) {
4294                                 return;
4295                         }
4296
4297                         $bar.width( ( queue.reduce( function( memo, attachment ) {
4298                                 if ( ! attachment.get('uploading') ) {
4299                                         return memo + 100;
4300                                 }
4301
4302                                 var percent = attachment.get('percent');
4303                                 return memo + ( _.isNumber( percent ) ? percent : 100 );
4304                         }, 0 ) / queue.length ) + '%' );
4305                 },
4306
4307                 info: function() {
4308                         var queue = this.queue,
4309                                 index = 0, active;
4310
4311                         if ( ! queue.length ) {
4312                                 return;
4313                         }
4314
4315                         active = this.queue.find( function( attachment, i ) {
4316                                 index = i;
4317                                 return attachment.get('uploading');
4318                         });
4319
4320                         this.$index.text( index + 1 );
4321                         this.$total.text( queue.length );
4322                         this.$filename.html( active ? this.filename( active.get('filename') ) : '' );
4323                 },
4324                 /**
4325                  * @param {string} filename
4326                  * @returns {string}
4327                  */
4328                 filename: function( filename ) {
4329                         return media.truncate( _.escape( filename ), 24 );
4330                 },
4331                 /**
4332                  * @param {Backbone.Model} error
4333                  */
4334                 error: function( error ) {
4335                         this.views.add( '.upload-errors', new media.view.UploaderStatusError({
4336                                 filename: this.filename( error.get('file').name ),
4337                                 message:  error.get('message')
4338                         }), { at: 0 });
4339                 },
4340
4341                 /**
4342                  * @global wp.Uploader
4343                  *
4344                  * @param {Object} event
4345                  */
4346                 dismiss: function( event ) {
4347                         var errors = this.views.get('.upload-errors');
4348
4349                         event.preventDefault();
4350
4351                         if ( errors ) {
4352                                 _.invoke( errors, 'remove' );
4353                         }
4354                         wp.Uploader.errors.reset();
4355                 }
4356         });
4357
4358         /**
4359          * wp.media.view.UploaderStatusError
4360          *
4361          * @class
4362          * @augments wp.media.View
4363          * @augments wp.Backbone.View
4364          * @augments Backbone.View
4365          */
4366         media.view.UploaderStatusError = media.View.extend({
4367                 className: 'upload-error',
4368                 template:  media.template('uploader-status-error')
4369         });
4370
4371         /**
4372          * wp.media.view.Toolbar
4373          *
4374          * A toolbar which consists of a primary and a secondary section. Each sections
4375          * can be filled with views.
4376          *
4377          * @class
4378          * @augments wp.media.View
4379          * @augments wp.Backbone.View
4380          * @augments Backbone.View
4381          */
4382         media.view.Toolbar = media.View.extend({
4383                 tagName:   'div',
4384                 className: 'media-toolbar',
4385
4386                 initialize: function() {
4387                         var state = this.controller.state(),
4388                                 selection = this.selection = state.get('selection'),
4389                                 library = this.library = state.get('library');
4390
4391                         this._views = {};
4392
4393                         // The toolbar is composed of two `PriorityList` views.
4394                         this.primary   = new media.view.PriorityList();
4395                         this.secondary = new media.view.PriorityList();
4396                         this.primary.$el.addClass('media-toolbar-primary search-form');
4397                         this.secondary.$el.addClass('media-toolbar-secondary');
4398
4399                         this.views.set([ this.secondary, this.primary ]);
4400
4401                         if ( this.options.items ) {
4402                                 this.set( this.options.items, { silent: true });
4403                         }
4404
4405                         if ( ! this.options.silent ) {
4406                                 this.render();
4407                         }
4408
4409                         if ( selection ) {
4410                                 selection.on( 'add remove reset', this.refresh, this );
4411                         }
4412
4413                         if ( library ) {
4414                                 library.on( 'add remove reset', this.refresh, this );
4415                         }
4416                 },
4417                 /**
4418                  * @returns {wp.media.view.Toolbar} Returns itsef to allow chaining
4419                  */
4420                 dispose: function() {
4421                         if ( this.selection ) {
4422                                 this.selection.off( null, null, this );
4423                         }
4424
4425                         if ( this.library ) {
4426                                 this.library.off( null, null, this );
4427                         }
4428                         /**
4429                          * call 'dispose' directly on the parent class
4430                          */
4431                         return media.View.prototype.dispose.apply( this, arguments );
4432                 },
4433
4434                 ready: function() {
4435                         this.refresh();
4436                 },
4437
4438                 /**
4439                  * @param {string} id
4440                  * @param {Backbone.View|Object} view
4441                  * @param {Object} [options={}]
4442                  * @returns {wp.media.view.Toolbar} Returns itself to allow chaining
4443                  */
4444                 set: function( id, view, options ) {
4445                         var list;
4446                         options = options || {};
4447
4448                         // Accept an object with an `id` : `view` mapping.
4449                         if ( _.isObject( id ) ) {
4450                                 _.each( id, function( view, id ) {
4451                                         this.set( id, view, { silent: true });
4452                                 }, this );
4453
4454                         } else {
4455                                 if ( ! ( view instanceof Backbone.View ) ) {
4456                                         view.classes = [ 'media-button-' + id ].concat( view.classes || [] );
4457                                         view = new media.view.Button( view ).render();
4458                                 }
4459
4460                                 view.controller = view.controller || this.controller;
4461
4462                                 this._views[ id ] = view;
4463
4464                                 list = view.options.priority < 0 ? 'secondary' : 'primary';
4465                                 this[ list ].set( id, view, options );
4466                         }
4467
4468                         if ( ! options.silent ) {
4469                                 this.refresh();
4470                         }
4471
4472                         return this;
4473                 },
4474                 /**
4475                  * @param {string} id
4476                  * @returns {wp.media.view.Button}
4477                  */
4478                 get: function( id ) {
4479                         return this._views[ id ];
4480                 },
4481                 /**
4482                  * @param {string} id
4483                  * @param {Object} options
4484                  * @returns {wp.media.view.Toolbar} Returns itself to allow chaining
4485                  */
4486                 unset: function( id, options ) {
4487                         delete this._views[ id ];
4488                         this.primary.unset( id, options );
4489                         this.secondary.unset( id, options );
4490
4491                         if ( ! options || ! options.silent ) {
4492                                 this.refresh();
4493                         }
4494                         return this;
4495                 },
4496
4497                 refresh: function() {
4498                         var state = this.controller.state(),
4499                                 library = state.get('library'),
4500                                 selection = state.get('selection');
4501
4502                         _.each( this._views, function( button ) {
4503                                 if ( ! button.model || ! button.options || ! button.options.requires ) {
4504                                         return;
4505                                 }
4506
4507                                 var requires = button.options.requires,
4508                                         disabled = false;
4509
4510                                 // Prevent insertion of attachments if any of them are still uploading
4511                                 disabled = _.some( selection.models, function( attachment ) {
4512                                         return attachment.get('uploading') === true;
4513                                 });
4514
4515                                 if ( requires.selection && selection && ! selection.length ) {
4516                                         disabled = true;
4517                                 } else if ( requires.library && library && ! library.length ) {
4518                                         disabled = true;
4519                                 }
4520                                 button.model.set( 'disabled', disabled );
4521                         });
4522                 }
4523         });
4524
4525         /**
4526          * wp.media.view.Toolbar.Select
4527          *
4528          * @class
4529          * @augments wp.media.view.Toolbar
4530          * @augments wp.media.View
4531          * @augments wp.Backbone.View
4532          * @augments Backbone.View
4533          */
4534         media.view.Toolbar.Select = media.view.Toolbar.extend({
4535                 initialize: function() {
4536                         var options = this.options;
4537
4538                         _.bindAll( this, 'clickSelect' );
4539
4540                         _.defaults( options, {
4541                                 event: 'select',
4542                                 state: false,
4543                                 reset: true,
4544                                 close: true,
4545                                 text:  l10n.select,
4546
4547                                 // Does the button rely on the selection?
4548                                 requires: {
4549                                         selection: true
4550                                 }
4551                         });
4552
4553                         options.items = _.defaults( options.items || {}, {
4554                                 select: {
4555                                         style:    'primary',
4556                                         text:     options.text,
4557                                         priority: 80,
4558                                         click:    this.clickSelect,
4559                                         requires: options.requires
4560                                 }
4561                         });
4562                         // Call 'initialize' directly on the parent class.
4563                         media.view.Toolbar.prototype.initialize.apply( this, arguments );
4564                 },
4565
4566                 clickSelect: function() {
4567                         var options = this.options,
4568                                 controller = this.controller;
4569
4570                         if ( options.close ) {
4571                                 controller.close();
4572                         }
4573
4574                         if ( options.event ) {
4575                                 controller.state().trigger( options.event );
4576                         }
4577
4578                         if ( options.state ) {
4579                                 controller.setState( options.state );
4580                         }
4581
4582                         if ( options.reset ) {
4583                                 controller.reset();
4584                         }
4585                 }
4586         });
4587
4588         /**
4589          * wp.media.view.Toolbar.Embed
4590          *
4591          * @class
4592          * @augments wp.media.view.Toolbar.Select
4593          * @augments wp.media.view.Toolbar
4594          * @augments wp.media.View
4595          * @augments wp.Backbone.View
4596          * @augments Backbone.View
4597          */
4598         media.view.Toolbar.Embed = media.view.Toolbar.Select.extend({
4599                 initialize: function() {
4600                         _.defaults( this.options, {
4601                                 text: l10n.insertIntoPost,
4602                                 requires: false
4603                         });
4604                         // Call 'initialize' directly on the parent class.
4605                         media.view.Toolbar.Select.prototype.initialize.apply( this, arguments );
4606                 },
4607
4608                 refresh: function() {
4609                         var url = this.controller.state().props.get('url');
4610                         this.get('select').model.set( 'disabled', ! url || url === 'http://' );
4611                         /**
4612                          * call 'refresh' directly on the parent class
4613                          */
4614                         media.view.Toolbar.Select.prototype.refresh.apply( this, arguments );
4615                 }
4616         });
4617
4618         /**
4619          * wp.media.view.Button
4620          *
4621          * @class
4622          * @augments wp.media.View
4623          * @augments wp.Backbone.View
4624          * @augments Backbone.View
4625          */
4626         media.view.Button = media.View.extend({
4627                 tagName:    'a',
4628                 className:  'media-button',
4629                 attributes: { href: '#' },
4630
4631                 events: {
4632                         'click': 'click'
4633                 },
4634
4635                 defaults: {
4636                         text:     '',
4637                         style:    '',
4638                         size:     'large',
4639                         disabled: false
4640                 },
4641
4642                 initialize: function() {
4643                         /**
4644                          * Create a model with the provided `defaults`.
4645                          *
4646                          * @member {Backbone.Model}
4647                          */
4648                         this.model = new Backbone.Model( this.defaults );
4649
4650                         // If any of the `options` have a key from `defaults`, apply its
4651                         // value to the `model` and remove it from the `options object.
4652                         _.each( this.defaults, function( def, key ) {
4653                                 var value = this.options[ key ];
4654                                 if ( _.isUndefined( value ) ) {
4655                                         return;
4656                                 }
4657
4658                                 this.model.set( key, value );
4659                                 delete this.options[ key ];
4660                         }, this );
4661
4662                         this.model.on( 'change', this.render, this );
4663                 },
4664                 /**
4665                  * @returns {wp.media.view.Button} Returns itself to allow chaining
4666                  */
4667                 render: function() {
4668                         var classes = [ 'button', this.className ],
4669                                 model = this.model.toJSON();
4670
4671                         if ( model.style ) {
4672                                 classes.push( 'button-' + model.style );
4673                         }
4674
4675                         if ( model.size ) {
4676                                 classes.push( 'button-' + model.size );
4677                         }
4678
4679                         classes = _.uniq( classes.concat( this.options.classes ) );
4680                         this.el.className = classes.join(' ');
4681
4682                         this.$el.attr( 'disabled', model.disabled );
4683                         this.$el.text( this.model.get('text') );
4684
4685                         return this;
4686                 },
4687                 /**
4688                  * @param {Object} event
4689                  */
4690                 click: function( event ) {
4691                         if ( '#' === this.attributes.href ) {
4692                                 event.preventDefault();
4693                         }
4694
4695                         if ( this.options.click && ! this.model.get('disabled') ) {
4696                                 this.options.click.apply( this, arguments );
4697                         }
4698                 }
4699         });
4700
4701         /**
4702          * wp.media.view.ButtonGroup
4703          *
4704          * @class
4705          * @augments wp.media.View
4706          * @augments wp.Backbone.View
4707          * @augments Backbone.View
4708          */
4709         media.view.ButtonGroup = media.View.extend({
4710                 tagName:   'div',
4711                 className: 'button-group button-large media-button-group',
4712
4713                 initialize: function() {
4714                         /**
4715                          * @member {wp.media.view.Button[]}
4716                          */
4717                         this.buttons = _.map( this.options.buttons || [], function( button ) {
4718                                 if ( button instanceof Backbone.View ) {
4719                                         return button;
4720                                 } else {
4721                                         return new media.view.Button( button ).render();
4722                                 }
4723                         });
4724
4725                         delete this.options.buttons;
4726
4727                         if ( this.options.classes ) {
4728                                 this.$el.addClass( this.options.classes );
4729                         }
4730                 },
4731
4732                 /**
4733                  * @returns {wp.media.view.ButtonGroup}
4734                  */
4735                 render: function() {
4736                         this.$el.html( $( _.pluck( this.buttons, 'el' ) ).detach() );
4737                         return this;
4738                 }
4739         });
4740
4741         /**
4742          * wp.media.view.PriorityList
4743          *
4744          * @class
4745          * @augments wp.media.View
4746          * @augments wp.Backbone.View
4747          * @augments Backbone.View
4748          */
4749         media.view.PriorityList = media.View.extend({
4750                 tagName:   'div',
4751
4752                 initialize: function() {
4753                         this._views = {};
4754
4755                         this.set( _.extend( {}, this._views, this.options.views ), { silent: true });
4756                         delete this.options.views;
4757
4758                         if ( ! this.options.silent ) {
4759                                 this.render();
4760                         }
4761                 },
4762                 /**
4763                  * @param {string} id
4764                  * @param {wp.media.View|Object} view
4765                  * @param {Object} options
4766                  * @returns {wp.media.view.PriorityList} Returns itself to allow chaining
4767                  */
4768                 set: function( id, view, options ) {
4769                         var priority, views, index;
4770
4771                         options = options || {};
4772
4773                         // Accept an object with an `id` : `view` mapping.
4774                         if ( _.isObject( id ) ) {
4775                                 _.each( id, function( view, id ) {
4776                                         this.set( id, view );
4777                                 }, this );
4778                                 return this;
4779                         }
4780
4781                         if ( ! (view instanceof Backbone.View) ) {
4782                                 view = this.toView( view, id, options );
4783                         }
4784                         view.controller = view.controller || this.controller;
4785
4786                         this.unset( id );
4787
4788                         priority = view.options.priority || 10;
4789                         views = this.views.get() || [];
4790
4791                         _.find( views, function( existing, i ) {
4792                                 if ( existing.options.priority > priority ) {
4793                                         index = i;
4794                                         return true;
4795                                 }
4796                         });
4797
4798                         this._views[ id ] = view;
4799                         this.views.add( view, {
4800                                 at: _.isNumber( index ) ? index : views.length || 0
4801                         });
4802
4803                         return this;
4804                 },
4805                 /**
4806                  * @param {string} id
4807                  * @returns {wp.media.View}
4808                  */
4809                 get: function( id ) {
4810                         return this._views[ id ];
4811                 },
4812                 /**
4813                  * @param {string} id
4814                  * @returns {wp.media.view.PriorityList}
4815                  */
4816                 unset: function( id ) {
4817                         var view = this.get( id );
4818
4819                         if ( view ) {
4820                                 view.remove();
4821                         }
4822
4823                         delete this._views[ id ];
4824                         return this;
4825                 },
4826                 /**
4827                  * @param {Object} options
4828                  * @returns {wp.media.View}
4829                  */
4830                 toView: function( options ) {
4831                         return new media.View( options );
4832                 }
4833         });
4834
4835         /**
4836          * wp.media.view.MenuItem
4837          *
4838          * @class
4839          * @augments wp.media.View
4840          * @augments wp.Backbone.View
4841          * @augments Backbone.View
4842          */
4843         media.view.MenuItem = media.View.extend({
4844                 tagName:   'a',
4845                 className: 'media-menu-item',
4846
4847                 attributes: {
4848                         href: '#'
4849                 },
4850
4851                 events: {
4852                         'click': '_click'
4853                 },
4854                 /**
4855                  * @param {Object} event
4856                  */
4857                 _click: function( event ) {
4858                         var clickOverride = this.options.click;
4859
4860                         if ( event ) {
4861                                 event.preventDefault();
4862                         }
4863
4864                         if ( clickOverride ) {
4865                                 clickOverride.call( this );
4866                         } else {
4867                                 this.click();
4868                         }
4869
4870                         // When selecting a tab along the left side,
4871                         // focus should be transferred into the main panel
4872                         if ( ! isTouchDevice ) {
4873                                 $('.media-frame-content input').first().focus();
4874                         }
4875                 },
4876
4877                 click: function() {
4878                         var state = this.options.state;
4879
4880                         if ( state ) {
4881                                 this.controller.setState( state );
4882                                 this.views.parent.$el.removeClass( 'visible' ); // TODO: or hide on any click, see below
4883                         }
4884                 },
4885                 /**
4886                  * @returns {wp.media.view.MenuItem} returns itself to allow chaining
4887                  */
4888                 render: function() {
4889                         var options = this.options;
4890
4891                         if ( options.text ) {
4892                                 this.$el.text( options.text );
4893                         } else if ( options.html ) {
4894                                 this.$el.html( options.html );
4895                         }
4896
4897                         return this;
4898                 }
4899         });
4900
4901         /**
4902          * wp.media.view.Menu
4903          *
4904          * @class
4905          * @augments wp.media.view.PriorityList
4906          * @augments wp.media.View
4907          * @augments wp.Backbone.View
4908          * @augments Backbone.View
4909          */
4910         media.view.Menu = media.view.PriorityList.extend({
4911                 tagName:   'div',
4912                 className: 'media-menu',
4913                 property:  'state',
4914                 ItemView:  media.view.MenuItem,
4915                 region:    'menu',
4916
4917                 /* TODO: alternatively hide on any click anywhere
4918                 events: {
4919                         'click': 'click'
4920                 },
4921
4922                 click: function() {
4923                         this.$el.removeClass( 'visible' );
4924                 },
4925                 */
4926
4927                 /**
4928                  * @param {Object} options
4929                  * @param {string} id
4930                  * @returns {wp.media.View}
4931                  */
4932                 toView: function( options, id ) {
4933                         options = options || {};
4934                         options[ this.property ] = options[ this.property ] || id;
4935                         return new this.ItemView( options ).render();
4936                 },
4937
4938                 ready: function() {
4939                         /**
4940                          * call 'ready' directly on the parent class
4941                          */
4942                         media.view.PriorityList.prototype.ready.apply( this, arguments );
4943                         this.visibility();
4944                 },
4945
4946                 set: function() {
4947                         /**
4948                          * call 'set' directly on the parent class
4949                          */
4950                         media.view.PriorityList.prototype.set.apply( this, arguments );
4951                         this.visibility();
4952                 },
4953
4954                 unset: function() {
4955                         /**
4956                          * call 'unset' directly on the parent class
4957                          */
4958                         media.view.PriorityList.prototype.unset.apply( this, arguments );
4959                         this.visibility();
4960                 },
4961
4962                 visibility: function() {
4963                         var region = this.region,
4964                                 view = this.controller[ region ].get(),
4965                                 views = this.views.get(),
4966                                 hide = ! views || views.length < 2;
4967
4968                         if ( this === view ) {
4969                                 this.controller.$el.toggleClass( 'hide-' + region, hide );
4970                         }
4971                 },
4972                 /**
4973                  * @param {string} id
4974                  */
4975                 select: function( id ) {
4976                         var view = this.get( id );
4977
4978                         if ( ! view ) {
4979                                 return;
4980                         }
4981
4982                         this.deselect();
4983                         view.$el.addClass('active');
4984                 },
4985
4986                 deselect: function() {
4987                         this.$el.children().removeClass('active');
4988                 },
4989
4990                 hide: function( id ) {
4991                         var view = this.get( id );
4992
4993                         if ( ! view ) {
4994                                 return;
4995                         }
4996
4997                         view.$el.addClass('hidden');
4998                 },
4999
5000                 show: function( id ) {
5001                         var view = this.get( id );
5002
5003                         if ( ! view ) {
5004                                 return;
5005                         }
5006
5007                         view.$el.removeClass('hidden');
5008                 }
5009         });
5010
5011         /**
5012          * wp.media.view.RouterItem
5013          *
5014          * @class
5015          * @augments wp.media.view.MenuItem
5016          * @augments wp.media.View
5017          * @augments wp.Backbone.View
5018          * @augments Backbone.View
5019          */
5020         media.view.RouterItem = media.view.MenuItem.extend({
5021                 /**
5022                  * On click handler to activate the content region's corresponding mode.
5023                  */
5024                 click: function() {
5025                         var contentMode = this.options.contentMode;
5026                         if ( contentMode ) {
5027                                 this.controller.content.mode( contentMode );
5028                         }
5029                 }
5030         });
5031
5032         /**
5033          * wp.media.view.Router
5034          *
5035          * @class
5036          * @augments wp.media.view.Menu
5037          * @augments wp.media.view.PriorityList
5038          * @augments wp.media.View
5039          * @augments wp.Backbone.View
5040          * @augments Backbone.View
5041          */
5042         media.view.Router = media.view.Menu.extend({
5043                 tagName:   'div',
5044                 className: 'media-router',
5045                 property:  'contentMode',
5046                 ItemView:  media.view.RouterItem,
5047                 region:    'router',
5048
5049                 initialize: function() {
5050                         this.controller.on( 'content:render', this.update, this );
5051                         // Call 'initialize' directly on the parent class.
5052                         media.view.Menu.prototype.initialize.apply( this, arguments );
5053                 },
5054
5055                 update: function() {
5056                         var mode = this.controller.content.mode();
5057                         if ( mode ) {
5058                                 this.select( mode );
5059                         }
5060                 }
5061         });
5062
5063         /**
5064          * wp.media.view.Sidebar
5065          *
5066          * @class
5067          * @augments wp.media.view.PriorityList
5068          * @augments wp.media.View
5069          * @augments wp.Backbone.View
5070          * @augments Backbone.View
5071          */
5072         media.view.Sidebar = media.view.PriorityList.extend({
5073                 className: 'media-sidebar'
5074         });
5075
5076         /**
5077          * wp.media.view.Attachment
5078          *
5079          * @class
5080          * @augments wp.media.View
5081          * @augments wp.Backbone.View
5082          * @augments Backbone.View
5083          */
5084         media.view.Attachment = media.View.extend({
5085                 tagName:   'li',
5086                 className: 'attachment',
5087                 template:  media.template('attachment'),
5088
5089                 attributes: function() {
5090                         return {
5091                                 'tabIndex':     0,
5092                                 'role':         'checkbox',
5093                                 'aria-label':   this.model.get( 'title' ),
5094                                 'aria-checked': false,
5095                                 'data-id':      this.model.get( 'id' )
5096                         };
5097                 },
5098
5099                 events: {
5100                         'click .js--select-attachment':   'toggleSelectionHandler',
5101                         'change [data-setting]':          'updateSetting',
5102                         'change [data-setting] input':    'updateSetting',
5103                         'change [data-setting] select':   'updateSetting',
5104                         'change [data-setting] textarea': 'updateSetting',
5105                         'click .close':                   'removeFromLibrary',
5106                         'click .check':                   'checkClickHandler',
5107                         'click a':                        'preventDefault',
5108                         'keydown .close':                 'removeFromLibrary',
5109                         'keydown':                        'toggleSelectionHandler'
5110                 },
5111
5112                 buttons: {},
5113
5114                 initialize: function() {
5115                         var selection = this.options.selection,
5116                                 options = _.defaults( this.options, {
5117                                         rerenderOnModelChange: true
5118                                 } );
5119
5120                         if ( options.rerenderOnModelChange ) {
5121                                 this.model.on( 'change', this.render, this );
5122                         } else {
5123                                 this.model.on( 'change:percent', this.progress, this );
5124                         }
5125                         this.model.on( 'change:title', this._syncTitle, this );
5126                         this.model.on( 'change:caption', this._syncCaption, this );
5127                         this.model.on( 'change:artist', this._syncArtist, this );
5128                         this.model.on( 'change:album', this._syncAlbum, this );
5129
5130                         // Update the selection.
5131                         this.model.on( 'add', this.select, this );
5132                         this.model.on( 'remove', this.deselect, this );
5133                         if ( selection ) {
5134                                 selection.on( 'reset', this.updateSelect, this );
5135                                 // Update the model's details view.
5136                                 this.model.on( 'selection:single selection:unsingle', this.details, this );
5137                                 this.details( this.model, this.controller.state().get('selection') );
5138                         }
5139
5140                         this.listenTo( this.controller, 'attachment:compat:waiting attachment:compat:ready', this.updateSave );
5141                 },
5142                 /**
5143                  * @returns {wp.media.view.Attachment} Returns itself to allow chaining
5144                  */
5145                 dispose: function() {
5146                         var selection = this.options.selection;
5147
5148                         // Make sure all settings are saved before removing the view.
5149                         this.updateAll();
5150
5151                         if ( selection ) {
5152                                 selection.off( null, null, this );
5153                         }
5154                         /**
5155                          * call 'dispose' directly on the parent class
5156                          */
5157                         media.View.prototype.dispose.apply( this, arguments );
5158                         return this;
5159                 },
5160                 /**
5161                  * @returns {wp.media.view.Attachment} Returns itself to allow chaining
5162                  */
5163                 render: function() {
5164                         var options = _.defaults( this.model.toJSON(), {
5165                                         orientation:   'landscape',
5166                                         uploading:     false,
5167                                         type:          '',
5168                                         subtype:       '',
5169                                         icon:          '',
5170                                         filename:      '',
5171                                         caption:       '',
5172                                         title:         '',
5173                                         dateFormatted: '',
5174                                         width:         '',
5175                                         height:        '',
5176                                         compat:        false,
5177                                         alt:           '',
5178                                         description:   ''
5179                                 }, this.options );
5180
5181                         options.buttons  = this.buttons;
5182                         options.describe = this.controller.state().get('describe');
5183
5184                         if ( 'image' === options.type ) {
5185                                 options.size = this.imageSize();
5186                         }
5187
5188                         options.can = {};
5189                         if ( options.nonces ) {
5190                                 options.can.remove = !! options.nonces['delete'];
5191                                 options.can.save = !! options.nonces.update;
5192                         }
5193
5194                         if ( this.controller.state().get('allowLocalEdits') ) {
5195                                 options.allowLocalEdits = true;
5196                         }
5197
5198                         if ( options.uploading && ! options.percent ) {
5199                                 options.percent = 0;
5200                         }
5201
5202                         this.views.detach();
5203                         this.$el.html( this.template( options ) );
5204
5205                         this.$el.toggleClass( 'uploading', options.uploading );
5206
5207                         if ( options.uploading ) {
5208                                 this.$bar = this.$('.media-progress-bar div');
5209                         } else {
5210                                 delete this.$bar;
5211                         }
5212
5213                         // Check if the model is selected.
5214                         this.updateSelect();
5215
5216                         // Update the save status.
5217                         this.updateSave();
5218
5219                         this.views.render();
5220
5221                         return this;
5222                 },
5223
5224                 progress: function() {
5225                         if ( this.$bar && this.$bar.length ) {
5226                                 this.$bar.width( this.model.get('percent') + '%' );
5227                         }
5228                 },
5229
5230                 /**
5231                  * @param {Object} event
5232                  */
5233                 toggleSelectionHandler: function( event ) {
5234                         var method;
5235
5236                         // Don't do anything inside inputs.
5237                         if ( 'INPUT' === event.target.nodeName ) {
5238                                 return;
5239                         }
5240
5241                         // Catch arrow events
5242                         if ( 37 === event.keyCode || 38 === event.keyCode || 39 === event.keyCode || 40 === event.keyCode ) {
5243                                 this.controller.trigger( 'attachment:keydown:arrow', event );
5244                                 return;
5245                         }
5246
5247                         // Catch enter and space events
5248                         if ( 'keydown' === event.type && 13 !== event.keyCode && 32 !== event.keyCode ) {
5249                                 return;
5250                         }
5251
5252                         event.preventDefault();
5253
5254                         // In the grid view, bubble up an edit:attachment event to the controller.
5255                         if ( this.controller.isModeActive( 'grid' ) ) {
5256                                 if ( this.controller.isModeActive( 'edit' ) ) {
5257                                         // Pass the current target to restore focus when closing
5258                                         this.controller.trigger( 'edit:attachment', this.model, event.currentTarget );
5259                                         return;
5260                                 }
5261
5262                                 if ( this.controller.isModeActive( 'select' ) ) {
5263                                         method = 'toggle';
5264                                 }
5265                         }
5266
5267                         if ( event.shiftKey ) {
5268                                 method = 'between';
5269                         } else if ( event.ctrlKey || event.metaKey ) {
5270                                 method = 'toggle';
5271                         }
5272
5273                         this.toggleSelection({
5274                                 method: method
5275                         });
5276
5277                         this.controller.trigger( 'selection:toggle' );
5278                 },
5279                 /**
5280                  * @param {Object} options
5281                  */
5282                 toggleSelection: function( options ) {
5283                         var collection = this.collection,
5284                                 selection = this.options.selection,
5285                                 model = this.model,
5286                                 method = options && options.method,
5287                                 single, models, singleIndex, modelIndex;
5288
5289                         if ( ! selection ) {
5290                                 return;
5291                         }
5292
5293                         single = selection.single();
5294                         method = _.isUndefined( method ) ? selection.multiple : method;
5295
5296                         // If the `method` is set to `between`, select all models that
5297                         // exist between the current and the selected model.
5298                         if ( 'between' === method && single && selection.multiple ) {
5299                                 // If the models are the same, short-circuit.
5300                                 if ( single === model ) {
5301                                         return;
5302                                 }
5303
5304                                 singleIndex = collection.indexOf( single );
5305                                 modelIndex  = collection.indexOf( this.model );
5306
5307                                 if ( singleIndex < modelIndex ) {
5308                                         models = collection.models.slice( singleIndex, modelIndex + 1 );
5309                                 } else {
5310                                         models = collection.models.slice( modelIndex, singleIndex + 1 );
5311                                 }
5312
5313                                 selection.add( models );
5314                                 selection.single( model );
5315                                 return;
5316
5317                         // If the `method` is set to `toggle`, just flip the selection
5318                         // status, regardless of whether the model is the single model.
5319                         } else if ( 'toggle' === method ) {
5320                                 selection[ this.selected() ? 'remove' : 'add' ]( model );
5321                                 selection.single( model );
5322                                 return;
5323                         } else if ( 'add' === method ) {
5324                                 selection.add( model );
5325                                 selection.single( model );
5326                                 return;
5327                         }
5328
5329                         // Fixes bug that loses focus when selecting a featured image
5330                         if ( ! method ) {
5331                                 method = 'add';
5332                         }
5333
5334                         if ( method !== 'add' ) {
5335                                 method = 'reset';
5336                         }
5337
5338                         if ( this.selected() ) {
5339                                 // If the model is the single model, remove it.
5340                                 // If it is not the same as the single model,
5341                                 // it now becomes the single model.
5342                                 selection[ single === model ? 'remove' : 'single' ]( model );
5343                         } else {
5344                                 // If the model is not selected, run the `method` on the
5345                                 // selection. By default, we `reset` the selection, but the
5346                                 // `method` can be set to `add` the model to the selection.
5347                                 selection[ method ]( model );
5348                                 selection.single( model );
5349                         }
5350                 },
5351
5352                 updateSelect: function() {
5353                         this[ this.selected() ? 'select' : 'deselect' ]();
5354                 },
5355                 /**
5356                  * @returns {unresolved|Boolean}
5357                  */
5358                 selected: function() {
5359                         var selection = this.options.selection;
5360                         if ( selection ) {
5361                                 return !! selection.get( this.model.cid );
5362                         }
5363                 },
5364                 /**
5365                  * @param {Backbone.Model} model
5366                  * @param {Backbone.Collection} collection
5367                  */
5368                 select: function( model, collection ) {
5369                         var selection = this.options.selection,
5370                                 controller = this.controller;
5371
5372                         // Check if a selection exists and if it's the collection provided.
5373                         // If they're not the same collection, bail; we're in another
5374                         // selection's event loop.
5375                         if ( ! selection || ( collection && collection !== selection ) ) {
5376                                 return;
5377                         }
5378
5379                         // Bail if the model is already selected.
5380                         if ( this.$el.hasClass( 'selected' ) ) {
5381                                 return;
5382                         }
5383
5384                         // Add 'selected' class to model, set aria-checked to true.
5385                         this.$el.addClass( 'selected' ).attr( 'aria-checked', true );
5386                         //  Make the checkbox tabable, except in media grid (bulk select mode).
5387                         if ( ! ( controller.isModeActive( 'grid' ) && controller.isModeActive( 'select' ) ) ) {
5388                                 this.$( '.check' ).attr( 'tabindex', '0' );
5389                         }
5390                 },
5391                 /**
5392                  * @param {Backbone.Model} model
5393                  * @param {Backbone.Collection} collection
5394                  */
5395                 deselect: function( model, collection ) {
5396                         var selection = this.options.selection;
5397
5398                         // Check if a selection exists and if it's the collection provided.
5399                         // If they're not the same collection, bail; we're in another
5400                         // selection's event loop.
5401                         if ( ! selection || ( collection && collection !== selection ) ) {
5402                                 return;
5403                         }
5404                         this.$el.removeClass( 'selected' ).attr( 'aria-checked', false )
5405                                 .find( '.check' ).attr( 'tabindex', '-1' );
5406                 },
5407                 /**
5408                  * @param {Backbone.Model} model
5409                  * @param {Backbone.Collection} collection
5410                  */
5411                 details: function( model, collection ) {
5412                         var selection = this.options.selection,
5413                                 details;
5414
5415                         if ( selection !== collection ) {
5416                                 return;
5417                         }
5418
5419                         details = selection.single();
5420                         this.$el.toggleClass( 'details', details === this.model );
5421                 },
5422                 /**
5423                  * @param {Object} event
5424                  */
5425                 preventDefault: function( event ) {
5426                         event.preventDefault();
5427                 },
5428                 /**
5429                  * @param {string} size
5430                  * @returns {Object}
5431                  */
5432                 imageSize: function( size ) {
5433                         var sizes = this.model.get('sizes');
5434
5435                         size = size || 'medium';
5436
5437                         // Use the provided image size if possible.
5438                         if ( sizes && sizes[ size ] ) {
5439                                 return _.clone( sizes[ size ] );
5440                         } else {
5441                                 return {
5442                                         url:         this.model.get('url'),
5443                                         width:       this.model.get('width'),
5444                                         height:      this.model.get('height'),
5445                                         orientation: this.model.get('orientation')
5446                                 };
5447                         }
5448                 },
5449                 /**
5450                  * @param {Object} event
5451                  */
5452                 updateSetting: function( event ) {
5453                         var $setting = $( event.target ).closest('[data-setting]'),
5454                                 setting, value;
5455
5456                         if ( ! $setting.length ) {
5457                                 return;
5458                         }
5459
5460                         setting = $setting.data('setting');
5461                         value   = event.target.value;
5462
5463                         if ( this.model.get( setting ) !== value ) {
5464                                 this.save( setting, value );
5465                         }
5466                 },
5467
5468                 /**
5469                  * Pass all the arguments to the model's save method.
5470                  *
5471                  * Records the aggregate status of all save requests and updates the
5472                  * view's classes accordingly.
5473                  */
5474                 save: function() {
5475                         var view = this,
5476                                 save = this._save = this._save || { status: 'ready' },
5477                                 request = this.model.save.apply( this.model, arguments ),
5478                                 requests = save.requests ? $.when( request, save.requests ) : request;
5479
5480                         // If we're waiting to remove 'Saved.', stop.
5481                         if ( save.savedTimer ) {
5482                                 clearTimeout( save.savedTimer );
5483                         }
5484
5485                         this.updateSave('waiting');
5486                         save.requests = requests;
5487                         requests.always( function() {
5488                                 // If we've performed another request since this one, bail.
5489                                 if ( save.requests !== requests ) {
5490                                         return;
5491                                 }
5492
5493                                 view.updateSave( requests.state() === 'resolved' ? 'complete' : 'error' );
5494                                 save.savedTimer = setTimeout( function() {
5495                                         view.updateSave('ready');
5496                                         delete save.savedTimer;
5497                                 }, 2000 );
5498                         });
5499                 },
5500                 /**
5501                  * @param {string} status
5502                  * @returns {wp.media.view.Attachment} Returns itself to allow chaining
5503                  */
5504                 updateSave: function( status ) {
5505                         var save = this._save = this._save || { status: 'ready' };
5506
5507                         if ( status && status !== save.status ) {
5508                                 this.$el.removeClass( 'save-' + save.status );
5509                                 save.status = status;
5510                         }
5511
5512                         this.$el.addClass( 'save-' + save.status );
5513                         return this;
5514                 },
5515
5516                 updateAll: function() {
5517                         var $settings = this.$('[data-setting]'),
5518                                 model = this.model,
5519                                 changed;
5520
5521                         changed = _.chain( $settings ).map( function( el ) {
5522                                 var $input = $('input, textarea, select, [value]', el ),
5523                                         setting, value;
5524
5525                                 if ( ! $input.length ) {
5526                                         return;
5527                                 }
5528
5529                                 setting = $(el).data('setting');
5530                                 value = $input.val();
5531
5532                                 // Record the value if it changed.
5533                                 if ( model.get( setting ) !== value ) {
5534                                         return [ setting, value ];
5535                                 }
5536                         }).compact().object().value();
5537
5538                         if ( ! _.isEmpty( changed ) ) {
5539                                 model.save( changed );
5540                         }
5541                 },
5542                 /**
5543                  * @param {Object} event
5544                  */
5545                 removeFromLibrary: function( event ) {
5546                         // Catch enter and space events
5547                         if ( 'keydown' === event.type && 13 !== event.keyCode && 32 !== event.keyCode ) {
5548                                 return;
5549                         }
5550
5551                         // Stop propagation so the model isn't selected.
5552                         event.stopPropagation();
5553
5554                         this.collection.remove( this.model );
5555                 },
5556
5557                 /**
5558                  * Add the model if it isn't in the selection, if it is in the selection,
5559                  * remove it.
5560                  *
5561                  * @param  {[type]} event [description]
5562                  * @return {[type]}       [description]
5563                  */
5564                 checkClickHandler: function ( event ) {
5565                         var selection = this.options.selection;
5566                         if ( ! selection ) {
5567                                 return;
5568                         }
5569                         event.stopPropagation();
5570                         if ( selection.where( { id: this.model.get( 'id' ) } ).length ) {
5571                                 selection.remove( this.model );
5572                                 // Move focus back to the attachment tile (from the check).
5573                                 this.$el.focus();
5574                         } else {
5575                                 selection.add( this.model );
5576                         }
5577                 }
5578         });
5579
5580         // Ensure settings remain in sync between attachment views.
5581         _.each({
5582                 caption: '_syncCaption',
5583                 title:   '_syncTitle',
5584                 artist:  '_syncArtist',
5585                 album:   '_syncAlbum'
5586         }, function( method, setting ) {
5587                 /**
5588                  * @param {Backbone.Model} model
5589                  * @param {string} value
5590                  * @returns {wp.media.view.Attachment} Returns itself to allow chaining
5591                  */
5592                 media.view.Attachment.prototype[ method ] = function( model, value ) {
5593                         var $setting = this.$('[data-setting="' + setting + '"]');
5594
5595                         if ( ! $setting.length ) {
5596                                 return this;
5597                         }
5598
5599                         // If the updated value is in sync with the value in the DOM, there
5600                         // is no need to re-render. If we're currently editing the value,
5601                         // it will automatically be in sync, suppressing the re-render for
5602                         // the view we're editing, while updating any others.
5603                         if ( value === $setting.find('input, textarea, select, [value]').val() ) {
5604                                 return this;
5605                         }
5606
5607                         return this.render();
5608                 };
5609         });
5610
5611         /**
5612          * wp.media.view.Attachment.Library
5613          *
5614          * @class
5615          * @augments wp.media.view.Attachment
5616          * @augments wp.media.View
5617          * @augments wp.Backbone.View
5618          * @augments Backbone.View
5619          */
5620         media.view.Attachment.Library = media.view.Attachment.extend({
5621                 buttons: {
5622                         check: true
5623                 }
5624         });
5625
5626         /**
5627          * wp.media.view.Attachment.EditLibrary
5628          *
5629          * @class
5630          * @augments wp.media.view.Attachment
5631          * @augments wp.media.View
5632          * @augments wp.Backbone.View
5633          * @augments Backbone.View
5634          */
5635         media.view.Attachment.EditLibrary = media.view.Attachment.extend({
5636                 buttons: {
5637                         close: true
5638                 }
5639         });
5640
5641         /**
5642          * wp.media.view.Attachments
5643          *
5644          * @class
5645          * @augments wp.media.View
5646          * @augments wp.Backbone.View
5647          * @augments Backbone.View
5648          */
5649         media.view.Attachments = media.View.extend({
5650                 tagName:   'ul',
5651                 className: 'attachments',
5652
5653                 attributes: {
5654                         tabIndex: -1
5655                 },
5656
5657                 initialize: function() {
5658                         this.el.id = _.uniqueId('__attachments-view-');
5659
5660                         _.defaults( this.options, {
5661                                 refreshSensitivity: isTouchDevice ? 300 : 200,
5662                                 refreshThreshold:   3,
5663                                 AttachmentView:     media.view.Attachment,
5664                                 sortable:           false,
5665                                 resize:             true,
5666                                 idealColumnWidth:   $( window ).width() < 640 ? 135 : 150
5667                         });
5668
5669                         this._viewsByCid = {};
5670                         this.$window = $( window );
5671                         this.resizeEvent = 'resize.media-modal-columns';
5672
5673                         this.collection.on( 'add', function( attachment ) {
5674                                 this.views.add( this.createAttachmentView( attachment ), {
5675                                         at: this.collection.indexOf( attachment )
5676                                 });
5677                         }, this );
5678
5679                         this.collection.on( 'remove', function( attachment ) {
5680                                 var view = this._viewsByCid[ attachment.cid ];
5681                                 delete this._viewsByCid[ attachment.cid ];
5682
5683                                 if ( view ) {
5684                                         view.remove();
5685                                 }
5686                         }, this );
5687
5688                         this.collection.on( 'reset', this.render, this );
5689
5690                         this.listenTo( this.controller, 'library:selection:add',    this.attachmentFocus );
5691
5692                         // Throttle the scroll handler and bind this.
5693                         this.scroll = _.chain( this.scroll ).bind( this ).throttle( this.options.refreshSensitivity ).value();
5694
5695                         this.options.scrollElement = this.options.scrollElement || this.el;
5696                         $( this.options.scrollElement ).on( 'scroll', this.scroll );
5697
5698                         this.initSortable();
5699
5700                         _.bindAll( this, 'setColumns' );
5701
5702                         if ( this.options.resize ) {
5703                                 this.on( 'ready', this.bindEvents );
5704                                 this.controller.on( 'open', this.setColumns );
5705
5706                                 // Call this.setColumns() after this view has been rendered in the DOM so
5707                                 // attachments get proper width applied.
5708                                 _.defer( this.setColumns, this );
5709                         }
5710                 },
5711
5712                 bindEvents: function() {
5713                         this.$window.off( this.resizeEvent ).on( this.resizeEvent, _.debounce( this.setColumns, 50 ) );
5714                 },
5715
5716                 attachmentFocus: function() {
5717                         this.$( 'li:first' ).focus();
5718                 },
5719
5720                 restoreFocus: function() {
5721                         this.$( 'li.selected:first' ).focus();
5722                 },
5723
5724                 arrowEvent: function( event ) {
5725                         var attachments = this.$el.children( 'li' ),
5726                                 perRow = this.columns,
5727                                 index = attachments.filter( ':focus' ).index(),
5728                                 row = ( index + 1 ) <= perRow ? 1 : Math.ceil( ( index + 1 ) / perRow );
5729
5730                         if ( index === -1 ) {
5731                                 return;
5732                         }
5733
5734                         // Left arrow
5735                         if ( 37 === event.keyCode ) {
5736                                 if ( 0 === index ) {
5737                                         return;
5738                                 }
5739                                 attachments.eq( index - 1 ).focus();
5740                         }
5741
5742                         // Up arrow
5743                         if ( 38 === event.keyCode ) {
5744                                 if ( 1 === row ) {
5745                                         return;
5746                                 }
5747                                 attachments.eq( index - perRow ).focus();
5748                         }
5749
5750                         // Right arrow
5751                         if ( 39 === event.keyCode ) {
5752                                 if ( attachments.length === index ) {
5753                                         return;
5754                                 }
5755                                 attachments.eq( index + 1 ).focus();
5756                         }
5757
5758                         // Down arrow
5759                         if ( 40 === event.keyCode ) {
5760                                 if ( Math.ceil( attachments.length / perRow ) === row ) {
5761                                         return;
5762                                 }
5763                                 attachments.eq( index + perRow ).focus();
5764                         }
5765                 },
5766
5767                 dispose: function() {
5768                         this.collection.props.off( null, null, this );
5769                         if ( this.options.resize ) {
5770                                 this.$window.off( this.resizeEvent );
5771                         }
5772
5773                         /**
5774                          * call 'dispose' directly on the parent class
5775                          */
5776                         media.View.prototype.dispose.apply( this, arguments );
5777                 },
5778
5779                 setColumns: function() {
5780                         var prev = this.columns,
5781                                 width = this.$el.width();
5782
5783                         if ( width ) {
5784                                 this.columns = Math.min( Math.round( width / this.options.idealColumnWidth ), 12 ) || 1;
5785
5786                                 if ( ! prev || prev !== this.columns ) {
5787                                         this.$el.closest( '.media-frame-content' ).attr( 'data-columns', this.columns );
5788                                 }
5789                         }
5790                 },
5791
5792                 initSortable: function() {
5793                         var collection = this.collection;
5794
5795                         if ( isTouchDevice || ! this.options.sortable || ! $.fn.sortable ) {
5796                                 return;
5797                         }
5798
5799                         this.$el.sortable( _.extend({
5800                                 // If the `collection` has a `comparator`, disable sorting.
5801                                 disabled: !! collection.comparator,
5802
5803                                 // Change the position of the attachment as soon as the
5804                                 // mouse pointer overlaps a thumbnail.
5805                                 tolerance: 'pointer',
5806
5807                                 // Record the initial `index` of the dragged model.
5808                                 start: function( event, ui ) {
5809                                         ui.item.data('sortableIndexStart', ui.item.index());
5810                                 },
5811
5812                                 // Update the model's index in the collection.
5813                                 // Do so silently, as the view is already accurate.
5814                                 update: function( event, ui ) {
5815                                         var model = collection.at( ui.item.data('sortableIndexStart') ),
5816                                                 comparator = collection.comparator;
5817
5818                                         // Temporarily disable the comparator to prevent `add`
5819                                         // from re-sorting.
5820                                         delete collection.comparator;
5821
5822                                         // Silently shift the model to its new index.
5823                                         collection.remove( model, {
5824                                                 silent: true
5825                                         });
5826                                         collection.add( model, {
5827                                                 silent: true,
5828                                                 at:     ui.item.index()
5829                                         });
5830
5831                                         // Restore the comparator.
5832                                         collection.comparator = comparator;
5833
5834                                         // Fire the `reset` event to ensure other collections sync.
5835                                         collection.trigger( 'reset', collection );
5836
5837                                         // If the collection is sorted by menu order,
5838                                         // update the menu order.
5839                                         collection.saveMenuOrder();
5840                                 }
5841                         }, this.options.sortable ) );
5842
5843                         // If the `orderby` property is changed on the `collection`,
5844                         // check to see if we have a `comparator`. If so, disable sorting.
5845                         collection.props.on( 'change:orderby', function() {
5846                                 this.$el.sortable( 'option', 'disabled', !! collection.comparator );
5847                         }, this );
5848
5849                         this.collection.props.on( 'change:orderby', this.refreshSortable, this );
5850                         this.refreshSortable();
5851                 },
5852
5853                 refreshSortable: function() {
5854                         if ( isTouchDevice || ! this.options.sortable || ! $.fn.sortable ) {
5855                                 return;
5856                         }
5857
5858                         // If the `collection` has a `comparator`, disable sorting.
5859                         var collection = this.collection,
5860                                 orderby = collection.props.get('orderby'),
5861                                 enabled = 'menuOrder' === orderby || ! collection.comparator;
5862
5863                         this.$el.sortable( 'option', 'disabled', ! enabled );
5864                 },
5865
5866                 /**
5867                  * @param {wp.media.model.Attachment} attachment
5868                  * @returns {wp.media.View}
5869                  */
5870                 createAttachmentView: function( attachment ) {
5871                         var view = new this.options.AttachmentView({
5872                                 controller:           this.controller,
5873                                 model:                attachment,
5874                                 collection:           this.collection,
5875                                 selection:            this.options.selection
5876                         });
5877
5878                         return this._viewsByCid[ attachment.cid ] = view;
5879                 },
5880
5881                 prepare: function() {
5882                         // Create all of the Attachment views, and replace
5883                         // the list in a single DOM operation.
5884                         if ( this.collection.length ) {
5885                                 this.views.set( this.collection.map( this.createAttachmentView, this ) );
5886
5887                         // If there are no elements, clear the views and load some.
5888                         } else {
5889                                 this.views.unset();
5890                                 this.collection.more().done( this.scroll );
5891                         }
5892                 },
5893
5894                 ready: function() {
5895                         // Trigger the scroll event to check if we're within the
5896                         // threshold to query for additional attachments.
5897                         this.scroll();
5898                 },
5899
5900                 scroll: function() {
5901                         var view = this,
5902                                 el = this.options.scrollElement,
5903                                 scrollTop = el.scrollTop,
5904                                 toolbar;
5905
5906                         // The scroll event occurs on the document, but the element
5907                         // that should be checked is the document body.
5908                         if ( el == document ) {
5909                                 el = document.body;
5910                                 scrollTop = $(document).scrollTop();
5911                         }
5912
5913                         if ( ! $(el).is(':visible') || ! this.collection.hasMore() ) {
5914                                 return;
5915                         }
5916
5917                         toolbar = this.views.parent.toolbar;
5918
5919                         // Show the spinner only if we are close to the bottom.
5920                         if ( el.scrollHeight - ( scrollTop + el.clientHeight ) < el.clientHeight / 3 ) {
5921                                 toolbar.get('spinner').show();
5922                         }
5923
5924                         if ( el.scrollHeight < scrollTop + ( el.clientHeight * this.options.refreshThreshold ) ) {
5925                                 this.collection.more().done(function() {
5926                                         view.scroll();
5927                                         toolbar.get('spinner').hide();
5928                                 });
5929                         }
5930                 }
5931         });
5932
5933         /**
5934          * wp.media.view.Search
5935          *
5936          * @class
5937          * @augments wp.media.View
5938          * @augments wp.Backbone.View
5939          * @augments Backbone.View
5940          */
5941         media.view.Search = media.View.extend({
5942                 tagName:   'input',
5943                 className: 'search',
5944                 id:        'media-search-input',
5945
5946                 attributes: {
5947                         type:        'search',
5948                         placeholder: l10n.search
5949                 },
5950
5951                 events: {
5952                         'input':  'search',
5953                         'keyup':  'search',
5954                         'change': 'search',
5955                         'search': 'search'
5956                 },
5957
5958                 /**
5959                  * @returns {wp.media.view.Search} Returns itself to allow chaining
5960                  */
5961                 render: function() {
5962                         this.el.value = this.model.escape('search');
5963                         return this;
5964                 },
5965
5966                 search: function( event ) {
5967                         if ( event.target.value ) {
5968                                 this.model.set( 'search', event.target.value );
5969                         } else {
5970                                 this.model.unset('search');
5971                         }
5972                 }
5973         });
5974
5975         /**
5976          * wp.media.view.AttachmentFilters
5977          *
5978          * @class
5979          * @augments wp.media.View
5980          * @augments wp.Backbone.View
5981          * @augments Backbone.View
5982          */
5983         media.view.AttachmentFilters = media.View.extend({
5984                 tagName:   'select',
5985                 className: 'attachment-filters',
5986                 id:        'media-attachment-filters',
5987
5988                 events: {
5989                         change: 'change'
5990                 },
5991
5992                 keys: [],
5993
5994                 initialize: function() {
5995                         this.createFilters();
5996                         _.extend( this.filters, this.options.filters );
5997
5998                         // Build `<option>` elements.
5999                         this.$el.html( _.chain( this.filters ).map( function( filter, value ) {
6000                                 return {
6001                                         el: $( '<option></option>' ).val( value ).html( filter.text )[0],
6002                                         priority: filter.priority || 50
6003                                 };
6004                         }, this ).sortBy('priority').pluck('el').value() );
6005
6006                         this.model.on( 'change', this.select, this );
6007                         this.select();
6008                 },
6009
6010                 /**
6011                  * @abstract
6012                  */
6013                 createFilters: function() {
6014                         this.filters = {};
6015                 },
6016
6017                 /**
6018                  * When the selected filter changes, update the Attachment Query properties to match.
6019                  */
6020                 change: function() {
6021                         var filter = this.filters[ this.el.value ];
6022                         if ( filter ) {
6023                                 this.model.set( filter.props );
6024                         }
6025                 },
6026
6027                 select: function() {
6028                         var model = this.model,
6029                                 value = 'all',
6030                                 props = model.toJSON();
6031
6032                         _.find( this.filters, function( filter, id ) {
6033                                 var equal = _.all( filter.props, function( prop, key ) {
6034                                         return prop === ( _.isUndefined( props[ key ] ) ? null : props[ key ] );
6035                                 });
6036
6037                                 if ( equal ) {
6038                                         return value = id;
6039                                 }
6040                         });
6041
6042                         this.$el.val( value );
6043                 }
6044         });
6045
6046         /**
6047          * A filter dropdown for month/dates.
6048          *
6049          * @class
6050          * @augments wp.media.view.AttachmentFilters
6051          * @augments wp.media.View
6052          * @augments wp.Backbone.View
6053          * @augments Backbone.View
6054          */
6055         media.view.DateFilter = media.view.AttachmentFilters.extend({
6056                 id: 'media-attachment-date-filters',
6057
6058                 createFilters: function() {
6059                         var filters = {};
6060                         _.each( media.view.settings.months || {}, function( value, index ) {
6061                                 filters[ index ] = {
6062                                         text: value.text,
6063                                         props: {
6064                                                 year: value.year,
6065                                                 monthnum: value.month
6066                                         }
6067                                 };
6068                         });
6069                         filters.all = {
6070                                 text:  l10n.allDates,
6071                                 props: {
6072                                         monthnum: false,
6073                                         year:  false
6074                                 },
6075                                 priority: 10
6076                         };
6077                         this.filters = filters;
6078                 }
6079         });
6080
6081         /**
6082          * wp.media.view.AttachmentFilters.Uploaded
6083          *
6084          * @class
6085          * @augments wp.media.view.AttachmentFilters
6086          * @augments wp.media.View
6087          * @augments wp.Backbone.View
6088          * @augments Backbone.View
6089          */
6090         media.view.AttachmentFilters.Uploaded = media.view.AttachmentFilters.extend({
6091                 createFilters: function() {
6092                         var type = this.model.get('type'),
6093                                 types = media.view.settings.mimeTypes,
6094                                 text;
6095
6096                         if ( types && type ) {
6097                                 text = types[ type ];
6098                         }
6099
6100                         this.filters = {
6101                                 all: {
6102                                         text:  text || l10n.allMediaItems,
6103                                         props: {
6104                                                 uploadedTo: null,
6105                                                 orderby: 'date',
6106                                                 order:   'DESC'
6107                                         },
6108                                         priority: 10
6109                                 },
6110
6111                                 uploaded: {
6112                                         text:  l10n.uploadedToThisPost,
6113                                         props: {
6114                                                 uploadedTo: media.view.settings.post.id,
6115                                                 orderby: 'menuOrder',
6116                                                 order:   'ASC'
6117                                         },
6118                                         priority: 20
6119                                 },
6120
6121                                 unattached: {
6122                                         text:  l10n.unattached,
6123                                         props: {
6124                                                 uploadedTo: 0,
6125                                                 orderby: 'menuOrder',
6126                                                 order:   'ASC'
6127                                         },
6128                                         priority: 50
6129                                 }
6130                         };
6131                 }
6132         });
6133
6134         /**
6135          * wp.media.view.AttachmentFilters.All
6136          *
6137          * @class
6138          * @augments wp.media.view.AttachmentFilters
6139          * @augments wp.media.View
6140          * @augments wp.Backbone.View
6141          * @augments Backbone.View
6142          */
6143         media.view.AttachmentFilters.All = media.view.AttachmentFilters.extend({
6144                 createFilters: function() {
6145                         var filters = {};
6146
6147                         _.each( media.view.settings.mimeTypes || {}, function( text, key ) {
6148                                 filters[ key ] = {
6149                                         text: text,
6150                                         props: {
6151                                                 status:  null,
6152                                                 type:    key,
6153                                                 uploadedTo: null,
6154                                                 orderby: 'date',
6155                                                 order:   'DESC'
6156                                         }
6157                                 };
6158                         });
6159
6160                         filters.all = {
6161                                 text:  l10n.allMediaItems,
6162                                 props: {
6163                                         status:  null,
6164                                         type:    null,
6165                                         uploadedTo: null,
6166                                         orderby: 'date',
6167                                         order:   'DESC'
6168                                 },
6169                                 priority: 10
6170                         };
6171
6172                         if ( media.view.settings.post.id ) {
6173                                 filters.uploaded = {
6174                                         text:  l10n.uploadedToThisPost,
6175                                         props: {
6176                                                 status:  null,
6177                                                 type:    null,
6178                                                 uploadedTo: media.view.settings.post.id,
6179                                                 orderby: 'menuOrder',
6180                                                 order:   'ASC'
6181                                         },
6182                                         priority: 20
6183                                 };
6184                         }
6185
6186                         filters.unattached = {
6187                                 text:  l10n.unattached,
6188                                 props: {
6189                                         status:     null,
6190                                         uploadedTo: 0,
6191                                         type:       null,
6192                                         orderby:    'menuOrder',
6193                                         order:      'ASC'
6194                                 },
6195                                 priority: 50
6196                         };
6197
6198                         if ( media.view.settings.mediaTrash &&
6199                                 this.controller.isModeActive( 'grid' ) ) {
6200
6201                                 filters.trash = {
6202                                         text:  l10n.trash,
6203                                         props: {
6204                                                 uploadedTo: null,
6205                                                 status:     'trash',
6206                                                 type:       null,
6207                                                 orderby:    'date',
6208                                                 order:      'DESC'
6209                                         },
6210                                         priority: 50
6211                                 };
6212                         }
6213
6214                         this.filters = filters;
6215                 }
6216         });
6217
6218         /**
6219          * wp.media.view.AttachmentsBrowser
6220          *
6221          * @class
6222          * @augments wp.media.View
6223          * @augments wp.Backbone.View
6224          * @augments Backbone.View
6225          *
6226          * @param {object}      options
6227          * @param {object}      [options.filters=false] Which filters to show in the browser's toolbar.
6228          *                                              Accepts 'uploaded' and 'all'.
6229          * @param {object}      [options.search=true]   Whether to show the search interface in the
6230          *                                              browser's toolbar.
6231          * @param {object}      [options.date=true]     Whether to show the date filter in the
6232          *                                              browser's toolbar.
6233          * @param {object}      [options.display=false] Whether to show the attachments display settings
6234          *                                              view in the sidebar.
6235          * @param {bool|string} [options.sidebar=true]  Whether to create a sidebar for the browser.
6236          *                                              Accepts true, false, and 'errors'.
6237          */
6238         media.view.AttachmentsBrowser = media.View.extend({
6239                 tagName:   'div',
6240                 className: 'attachments-browser',
6241
6242                 initialize: function() {
6243                         _.defaults( this.options, {
6244                                 filters: false,
6245                                 search:  true,
6246                                 date:    true,
6247                                 display: false,
6248                                 sidebar: true,
6249                                 AttachmentView: media.view.Attachment.Library
6250                         });
6251
6252                         this.listenTo( this.controller, 'toggle:upload:attachment', _.bind( this.toggleUploader, this ) );
6253                         this.controller.on( 'edit:selection', this.editSelection );
6254                         this.createToolbar();
6255                         if ( this.options.sidebar ) {
6256                                 this.createSidebar();
6257                         }
6258                         this.createUploader();
6259                         this.createAttachments();
6260                         this.updateContent();
6261
6262                         if ( ! this.options.sidebar || 'errors' === this.options.sidebar ) {
6263                                 this.$el.addClass( 'hide-sidebar' );
6264
6265                                 if ( 'errors' === this.options.sidebar ) {
6266                                         this.$el.addClass( 'sidebar-for-errors' );
6267                                 }
6268                         }
6269
6270                         this.collection.on( 'add remove reset', this.updateContent, this );
6271                 },
6272
6273                 editSelection: function( modal ) {
6274                         modal.$( '.media-button-backToLibrary' ).focus();
6275                 },
6276
6277                 /**
6278                  * @returns {wp.media.view.AttachmentsBrowser} Returns itself to allow chaining
6279                  */
6280                 dispose: function() {
6281                         this.options.selection.off( null, null, this );
6282                         media.View.prototype.dispose.apply( this, arguments );
6283                         return this;
6284                 },
6285
6286                 createToolbar: function() {
6287                         var LibraryViewSwitcher, Filters, toolbarOptions;
6288
6289                         toolbarOptions = {
6290                                 controller: this.controller
6291                         };
6292
6293                         if ( this.controller.isModeActive( 'grid' ) ) {
6294                                 toolbarOptions.className = 'media-toolbar wp-filter';
6295                         }
6296
6297                         /**
6298                         * @member {wp.media.view.Toolbar}
6299                         */
6300                         this.toolbar = new media.view.Toolbar( toolbarOptions );
6301
6302                         this.views.add( this.toolbar );
6303
6304                         this.toolbar.set( 'spinner', new media.view.Spinner({
6305                                 priority: -60
6306                         }) );
6307
6308                         if ( -1 !== $.inArray( this.options.filters, [ 'uploaded', 'all' ] ) ) {
6309                                 // "Filters" will return a <select>, need to render
6310                                 // screen reader text before
6311                                 this.toolbar.set( 'filtersLabel', new media.view.Label({
6312                                         value: l10n.filterByType,
6313                                         attributes: {
6314                                                 'for':  'media-attachment-filters'
6315                                         },
6316                                         priority:   -80
6317                                 }).render() );
6318
6319                                 if ( 'uploaded' === this.options.filters ) {
6320                                         this.toolbar.set( 'filters', new media.view.AttachmentFilters.Uploaded({
6321                                                 controller: this.controller,
6322                                                 model:      this.collection.props,
6323                                                 priority:   -80
6324                                         }).render() );
6325                                 } else {
6326                                         Filters = new media.view.AttachmentFilters.All({
6327                                                 controller: this.controller,
6328                                                 model:      this.collection.props,
6329                                                 priority:   -80
6330                                         });
6331
6332                                         this.toolbar.set( 'filters', Filters.render() );
6333                                 }
6334                         }
6335
6336                         // Feels odd to bring the global media library switcher into the Attachment
6337                         // browser view. Is this a use case for doAction( 'add:toolbar-items:attachments-browser', this.toolbar );
6338                         // which the controller can tap into and add this view?
6339                         if ( this.controller.isModeActive( 'grid' ) ) {
6340                                 LibraryViewSwitcher = media.View.extend({
6341                                         className: 'view-switch media-grid-view-switch',
6342                                         template: media.template( 'media-library-view-switcher')
6343                                 });
6344
6345                                 this.toolbar.set( 'libraryViewSwitcher', new LibraryViewSwitcher({
6346                                         controller: this.controller,
6347                                         priority: -90
6348                                 }).render() );
6349
6350                                 // DateFilter is a <select>, screen reader text needs to be rendered before
6351                                 this.toolbar.set( 'dateFilterLabel', new media.view.Label({
6352                                         value: l10n.filterByDate,
6353                                         attributes: {
6354                                                 'for': 'media-attachment-date-filters'
6355                                         },
6356                                         priority: -75
6357                                 }).render() );
6358                                 this.toolbar.set( 'dateFilter', new media.view.DateFilter({
6359                                         controller: this.controller,
6360                                         model:      this.collection.props,
6361                                         priority: -75
6362                                 }).render() );
6363
6364                                 // BulkSelection is a <div> with subviews, including screen reader text
6365                                 this.toolbar.set( 'selectModeToggleButton', new media.view.SelectModeToggleButton({
6366                                         text: l10n.bulkSelect,
6367                                         controller: this.controller,
6368                                         priority: -70
6369                                 }).render() );
6370
6371                                 this.toolbar.set( 'deleteSelectedButton', new media.view.DeleteSelectedButton({
6372                                         filters: Filters,
6373                                         style: 'primary',
6374                                         disabled: true,
6375                                         text: media.view.settings.mediaTrash ? l10n.trashSelected : l10n.deleteSelected,
6376                                         controller: this.controller,
6377                                         priority: -60,
6378                                         click: function() {
6379                                                 var changed = [], removed = [], self = this,
6380                                                         selection = this.controller.state().get( 'selection' ),
6381                                                         library = this.controller.state().get( 'library' );
6382
6383                                                 if ( ! selection.length ) {
6384                                                         return;
6385                                                 }
6386
6387                                                 if ( ! media.view.settings.mediaTrash && ! confirm( l10n.warnBulkDelete ) ) {
6388                                                         return;
6389                                                 }
6390
6391                                                 if ( media.view.settings.mediaTrash &&
6392                                                         'trash' !== selection.at( 0 ).get( 'status' ) &&
6393                                                         ! confirm( l10n.warnBulkTrash ) ) {
6394
6395                                                         return;
6396                                                 }
6397
6398                                                 selection.each( function( model ) {
6399                                                         if ( ! model.get( 'nonces' )['delete'] ) {
6400                                                                 removed.push( model );
6401                                                                 return;
6402                                                         }
6403
6404                                                         if ( media.view.settings.mediaTrash && 'trash' === model.get( 'status' ) ) {
6405                                                                 model.set( 'status', 'inherit' );
6406                                                                 changed.push( model.save() );
6407                                                                 removed.push( model );
6408                                                         } else if ( media.view.settings.mediaTrash ) {
6409                                                                 model.set( 'status', 'trash' );
6410                                                                 changed.push( model.save() );
6411                                                                 removed.push( model );
6412                                                         } else {
6413                                                                 model.destroy({wait: true});
6414                                                         }
6415                                                 } );
6416
6417                                                 if ( changed.length ) {
6418                                                         selection.remove( removed );
6419
6420                                                         $.when.apply( null, changed ).then( function() {
6421                                                                 library._requery( true );
6422                                                                 self.controller.trigger( 'selection:action:done' );
6423                                                         } );
6424                                                 } else {
6425                                                         this.controller.trigger( 'selection:action:done' );
6426                                                 }
6427                                         }
6428                                 }).render() );
6429
6430                                 if ( media.view.settings.mediaTrash ) {
6431                                         this.toolbar.set( 'deleteSelectedPermanentlyButton', new media.view.DeleteSelectedPermanentlyButton({
6432                                                 filters: Filters,
6433                                                 style: 'primary',
6434                                                 disabled: true,
6435                                                 text: l10n.deleteSelected,
6436                                                 controller: this.controller,
6437                                                 priority: -55,
6438                                                 click: function() {
6439                                                         var removed = [], selection = this.controller.state().get( 'selection' );
6440
6441                                                         if ( ! selection.length || ! confirm( l10n.warnBulkDelete ) ) {
6442                                                                 return;
6443                                                         }
6444
6445                                                         selection.each( function( model ) {
6446                                                                 if ( ! model.get( 'nonces' )['delete'] ) {
6447                                                                         removed.push( model );
6448                                                                         return;
6449                                                                 }
6450
6451                                                                 model.destroy();
6452                                                         } );
6453
6454                                                         selection.remove( removed );
6455                                                         this.controller.trigger( 'selection:action:done' );
6456                                                 }
6457                                         }).render() );
6458                                 }
6459
6460                         } else if ( this.options.date ) {
6461                                 // DateFilter is a <select>, screen reader text needs to be rendered before
6462                                 this.toolbar.set( 'dateFilterLabel', new media.view.Label({
6463                                         value: l10n.filterByDate,
6464                                         attributes: {
6465                                                 'for': 'media-attachment-date-filters'
6466                                         },
6467                                         priority: -75
6468                                 }).render() );
6469                                 this.toolbar.set( 'dateFilter', new media.view.DateFilter({
6470                                         controller: this.controller,
6471                                         model:      this.collection.props,
6472                                         priority: -75
6473                                 }).render() );
6474                         }
6475
6476                         if ( this.options.search ) {
6477                                 // Search is an input, screen reader text needs to be rendered before
6478                                 this.toolbar.set( 'searchLabel', new media.view.Label({
6479                                         value: l10n.searchMediaLabel,
6480                                         attributes: {
6481                                                 'for': 'media-search-input'
6482                                         },
6483                                         priority:   60
6484                                 }).render() );
6485                                 this.toolbar.set( 'search', new media.view.Search({
6486                                         controller: this.controller,
6487                                         model:      this.collection.props,
6488                                         priority:   60
6489                                 }).render() );
6490                         }
6491
6492                         if ( this.options.dragInfo ) {
6493                                 this.toolbar.set( 'dragInfo', new media.View({
6494                                         el: $( '<div class="instructions">' + l10n.dragInfo + '</div>' )[0],
6495                                         priority: -40
6496                                 }) );
6497                         }
6498
6499                         if ( this.options.suggestedWidth && this.options.suggestedHeight ) {
6500                                 this.toolbar.set( 'suggestedDimensions', new media.View({
6501                                         el: $( '<div class="instructions">' + l10n.suggestedDimensions + ' ' + this.options.suggestedWidth + ' &times; ' + this.options.suggestedHeight + '</div>' )[0],
6502                                         priority: -40
6503                                 }) );
6504                         }
6505                 },
6506
6507                 updateContent: function() {
6508                         var view = this,
6509                                 noItemsView;
6510
6511                         if ( this.controller.isModeActive( 'grid' ) ) {
6512                                 noItemsView = view.attachmentsNoResults;
6513                         } else {
6514                                 noItemsView = view.uploader;
6515                         }
6516
6517                         if ( ! this.collection.length ) {
6518                                 this.toolbar.get( 'spinner' ).show();
6519                                 this.dfd = this.collection.more().done( function() {
6520                                         if ( ! view.collection.length ) {
6521                                                 noItemsView.$el.removeClass( 'hidden' );
6522                                         } else {
6523                                                 noItemsView.$el.addClass( 'hidden' );
6524                                         }
6525                                         view.toolbar.get( 'spinner' ).hide();
6526                                 } );
6527                         } else {
6528                                 noItemsView.$el.addClass( 'hidden' );
6529                                 view.toolbar.get( 'spinner' ).hide();
6530                         }
6531                 },
6532
6533                 createUploader: function() {
6534                         this.uploader = new media.view.UploaderInline({
6535                                 controller: this.controller,
6536                                 status:     false,
6537                                 message:    this.controller.isModeActive( 'grid' ) ? '' : l10n.noItemsFound,
6538                                 canClose:   this.controller.isModeActive( 'grid' )
6539                         });
6540
6541                         this.uploader.hide();
6542                         this.views.add( this.uploader );
6543                 },
6544
6545                 toggleUploader: function() {
6546                         if ( this.uploader.$el.hasClass( 'hidden' ) ) {
6547                                 this.uploader.show();
6548                         } else {
6549                                 this.uploader.hide();
6550                         }
6551                 },
6552
6553                 createAttachments: function() {
6554                         this.attachments = new media.view.Attachments({
6555                                 controller:           this.controller,
6556                                 collection:           this.collection,
6557                                 selection:            this.options.selection,
6558                                 model:                this.model,
6559                                 sortable:             this.options.sortable,
6560                                 scrollElement:        this.options.scrollElement,
6561                                 idealColumnWidth:     this.options.idealColumnWidth,
6562
6563                                 // The single `Attachment` view to be used in the `Attachments` view.
6564                                 AttachmentView: this.options.AttachmentView
6565                         });
6566
6567                         // Add keydown listener to the instance of the Attachments view
6568                         this.attachments.listenTo( this.controller, 'attachment:keydown:arrow',     this.attachments.arrowEvent );
6569                         this.attachments.listenTo( this.controller, 'attachment:details:shift-tab', this.attachments.restoreFocus );
6570
6571                         this.views.add( this.attachments );
6572
6573
6574                         if ( this.controller.isModeActive( 'grid' ) ) {
6575                                 this.attachmentsNoResults = new media.View({
6576                                         controller: this.controller,
6577                                         tagName: 'p'
6578                                 });
6579
6580                                 this.attachmentsNoResults.$el.addClass( 'hidden no-media' );
6581                                 this.attachmentsNoResults.$el.html( l10n.noMedia );
6582
6583                                 this.views.add( this.attachmentsNoResults );
6584                         }
6585                 },
6586
6587                 createSidebar: function() {
6588                         var options = this.options,
6589                                 selection = options.selection,
6590                                 sidebar = this.sidebar = new media.view.Sidebar({
6591                                         controller: this.controller
6592                                 });
6593
6594                         this.views.add( sidebar );
6595
6596                         if ( this.controller.uploader ) {
6597                                 sidebar.set( 'uploads', new media.view.UploaderStatus({
6598                                         controller: this.controller,
6599                                         priority:   40
6600                                 }) );
6601                         }
6602
6603                         selection.on( 'selection:single', this.createSingle, this );
6604                         selection.on( 'selection:unsingle', this.disposeSingle, this );
6605
6606                         if ( selection.single() ) {
6607                                 this.createSingle();
6608                         }
6609                 },
6610
6611                 createSingle: function() {
6612                         var sidebar = this.sidebar,
6613                                 single = this.options.selection.single();
6614
6615                         sidebar.set( 'details', new media.view.Attachment.Details({
6616                                 controller: this.controller,
6617                                 model:      single,
6618                                 priority:   80
6619                         }) );
6620
6621                         sidebar.set( 'compat', new media.view.AttachmentCompat({
6622                                 controller: this.controller,
6623                                 model:      single,
6624                                 priority:   120
6625                         }) );
6626
6627                         if ( this.options.display ) {
6628                                 sidebar.set( 'display', new media.view.Settings.AttachmentDisplay({
6629                                         controller:   this.controller,
6630                                         model:        this.model.display( single ),
6631                                         attachment:   single,
6632                                         priority:     160,
6633                                         userSettings: this.model.get('displayUserSettings')
6634                                 }) );
6635                         }
6636
6637                         // Show the sidebar on mobile
6638                         if ( this.model.id === 'insert' ) {
6639                                 sidebar.$el.addClass( 'visible' );
6640                         }
6641                 },
6642
6643                 disposeSingle: function() {
6644                         var sidebar = this.sidebar;
6645                         sidebar.unset('details');
6646                         sidebar.unset('compat');
6647                         sidebar.unset('display');
6648                         // Hide the sidebar on mobile
6649                         sidebar.$el.removeClass( 'visible' );
6650                 }
6651         });
6652
6653         /**
6654          * wp.media.view.Selection
6655          *
6656          * @class
6657          * @augments wp.media.View
6658          * @augments wp.Backbone.View
6659          * @augments Backbone.View
6660          */
6661         media.view.Selection = media.View.extend({
6662                 tagName:   'div',
6663                 className: 'media-selection',
6664                 template:  media.template('media-selection'),
6665
6666                 events: {
6667                         'click .edit-selection':  'edit',
6668                         'click .clear-selection': 'clear'
6669                 },
6670
6671                 initialize: function() {
6672                         _.defaults( this.options, {
6673                                 editable:  false,
6674                                 clearable: true
6675                         });
6676
6677                         /**
6678                          * @member {wp.media.view.Attachments.Selection}
6679                          */
6680                         this.attachments = new media.view.Attachments.Selection({
6681                                 controller: this.controller,
6682                                 collection: this.collection,
6683                                 selection:  this.collection,
6684                                 model:      new Backbone.Model()
6685                         });
6686
6687                         this.views.set( '.selection-view', this.attachments );
6688                         this.collection.on( 'add remove reset', this.refresh, this );
6689                         this.controller.on( 'content:activate', this.refresh, this );
6690                 },
6691
6692                 ready: function() {
6693                         this.refresh();
6694                 },
6695
6696                 refresh: function() {
6697                         // If the selection hasn't been rendered, bail.
6698                         if ( ! this.$el.children().length ) {
6699                                 return;
6700                         }
6701
6702                         var collection = this.collection,
6703                                 editing = 'edit-selection' === this.controller.content.mode();
6704
6705                         // If nothing is selected, display nothing.
6706                         this.$el.toggleClass( 'empty', ! collection.length );
6707                         this.$el.toggleClass( 'one', 1 === collection.length );
6708                         this.$el.toggleClass( 'editing', editing );
6709
6710                         this.$('.count').text( l10n.selected.replace('%d', collection.length) );
6711                 },
6712
6713                 edit: function( event ) {
6714                         event.preventDefault();
6715                         if ( this.options.editable ) {
6716                                 this.options.editable.call( this, this.collection );
6717                         }
6718                 },
6719
6720                 clear: function( event ) {
6721                         event.preventDefault();
6722                         this.collection.reset();
6723
6724                         // Keep focus inside media modal
6725                         // after clear link is selected
6726                         this.controller.modal.focusManager.focus();
6727                 }
6728         });
6729
6730
6731         /**
6732          * wp.media.view.Attachment.Selection
6733          *
6734          * @class
6735          * @augments wp.media.view.Attachment
6736          * @augments wp.media.View
6737          * @augments wp.Backbone.View
6738          * @augments Backbone.View
6739          */
6740         media.view.Attachment.Selection = media.view.Attachment.extend({
6741                 className: 'attachment selection',
6742
6743                 // On click, just select the model, instead of removing the model from
6744                 // the selection.
6745                 toggleSelection: function() {
6746                         this.options.selection.single( this.model );
6747                 }
6748         });
6749
6750         /**
6751          * wp.media.view.Attachments.Selection
6752          *
6753          * @class
6754          * @augments wp.media.view.Attachments
6755          * @augments wp.media.View
6756          * @augments wp.Backbone.View
6757          * @augments Backbone.View
6758          */
6759         media.view.Attachments.Selection = media.view.Attachments.extend({
6760                 events: {},
6761                 initialize: function() {
6762                         _.defaults( this.options, {
6763                                 sortable:   false,
6764                                 resize:     false,
6765
6766                                 // The single `Attachment` view to be used in the `Attachments` view.
6767                                 AttachmentView: media.view.Attachment.Selection
6768                         });
6769                         // Call 'initialize' directly on the parent class.
6770                         return media.view.Attachments.prototype.initialize.apply( this, arguments );
6771                 }
6772         });
6773
6774         /**
6775          * wp.media.view.Attachments.EditSelection
6776          *
6777          * @class
6778          * @augments wp.media.view.Attachment.Selection
6779          * @augments wp.media.view.Attachment
6780          * @augments wp.media.View
6781          * @augments wp.Backbone.View
6782          * @augments Backbone.View
6783          */
6784         media.view.Attachment.EditSelection = media.view.Attachment.Selection.extend({
6785                 buttons: {
6786                         close: true
6787                 }
6788         });
6789
6790
6791         /**
6792          * wp.media.view.Settings
6793          *
6794          * @class
6795          * @augments wp.media.View
6796          * @augments wp.Backbone.View
6797          * @augments Backbone.View
6798          */
6799         media.view.Settings = media.View.extend({
6800                 events: {
6801                         'click button':    'updateHandler',
6802                         'change input':    'updateHandler',
6803                         'change select':   'updateHandler',
6804                         'change textarea': 'updateHandler'
6805                 },
6806
6807                 initialize: function() {
6808                         this.model = this.model || new Backbone.Model();
6809                         this.model.on( 'change', this.updateChanges, this );
6810                 },
6811
6812                 prepare: function() {
6813                         return _.defaults({
6814                                 model: this.model.toJSON()
6815                         }, this.options );
6816                 },
6817                 /**
6818                  * @returns {wp.media.view.Settings} Returns itself to allow chaining
6819                  */
6820                 render: function() {
6821                         media.View.prototype.render.apply( this, arguments );
6822                         // Select the correct values.
6823                         _( this.model.attributes ).chain().keys().each( this.update, this );
6824                         return this;
6825                 },
6826                 /**
6827                  * @param {string} key
6828                  */
6829                 update: function( key ) {
6830                         var value = this.model.get( key ),
6831                                 $setting = this.$('[data-setting="' + key + '"]'),
6832                                 $buttons, $value;
6833
6834                         // Bail if we didn't find a matching setting.
6835                         if ( ! $setting.length ) {
6836                                 return;
6837                         }
6838
6839                         // Attempt to determine how the setting is rendered and update
6840                         // the selected value.
6841
6842                         // Handle dropdowns.
6843                         if ( $setting.is('select') ) {
6844                                 $value = $setting.find('[value="' + value + '"]');
6845
6846                                 if ( $value.length ) {
6847                                         $setting.find('option').prop( 'selected', false );
6848                                         $value.prop( 'selected', true );
6849                                 } else {
6850                                         // If we can't find the desired value, record what *is* selected.
6851                                         this.model.set( key, $setting.find(':selected').val() );
6852                                 }
6853
6854                         // Handle button groups.
6855                         } else if ( $setting.hasClass('button-group') ) {
6856                                 $buttons = $setting.find('button').removeClass('active');
6857                                 $buttons.filter( '[value="' + value + '"]' ).addClass('active');
6858
6859                         // Handle text inputs and textareas.
6860                         } else if ( $setting.is('input[type="text"], textarea') ) {
6861                                 if ( ! $setting.is(':focus') ) {
6862                                         $setting.val( value );
6863                                 }
6864                         // Handle checkboxes.
6865                         } else if ( $setting.is('input[type="checkbox"]') ) {
6866                                 $setting.prop( 'checked', !! value && 'false' !== value );
6867                         }
6868                 },
6869                 /**
6870                  * @param {Object} event
6871                  */
6872                 updateHandler: function( event ) {
6873                         var $setting = $( event.target ).closest('[data-setting]'),
6874                                 value = event.target.value,
6875                                 userSetting;
6876
6877                         event.preventDefault();
6878
6879                         if ( ! $setting.length ) {
6880                                 return;
6881                         }
6882
6883                         // Use the correct value for checkboxes.
6884                         if ( $setting.is('input[type="checkbox"]') ) {
6885                                 value = $setting[0].checked;
6886                         }
6887
6888                         // Update the corresponding setting.
6889                         this.model.set( $setting.data('setting'), value );
6890
6891                         // If the setting has a corresponding user setting,
6892                         // update that as well.
6893                         if ( userSetting = $setting.data('userSetting') ) {
6894                                 setUserSetting( userSetting, value );
6895                         }
6896                 },
6897
6898                 updateChanges: function( model ) {
6899                         if ( model.hasChanged() ) {
6900                                 _( model.changed ).chain().keys().each( this.update, this );
6901                         }
6902                 }
6903         });
6904
6905         /**
6906          * wp.media.view.Settings.AttachmentDisplay
6907          *
6908          * @class
6909          * @augments wp.media.view.Settings
6910          * @augments wp.media.View
6911          * @augments wp.Backbone.View
6912          * @augments Backbone.View
6913          */
6914         media.view.Settings.AttachmentDisplay = media.view.Settings.extend({
6915                 className: 'attachment-display-settings',
6916                 template:  media.template('attachment-display-settings'),
6917
6918                 initialize: function() {
6919                         var attachment = this.options.attachment;
6920
6921                         _.defaults( this.options, {
6922                                 userSettings: false
6923                         });
6924                         // Call 'initialize' directly on the parent class.
6925                         media.view.Settings.prototype.initialize.apply( this, arguments );
6926                         this.model.on( 'change:link', this.updateLinkTo, this );
6927
6928                         if ( attachment ) {
6929                                 attachment.on( 'change:uploading', this.render, this );
6930                         }
6931                 },
6932
6933                 dispose: function() {
6934                         var attachment = this.options.attachment;
6935                         if ( attachment ) {
6936                                 attachment.off( null, null, this );
6937                         }
6938                         /**
6939                          * call 'dispose' directly on the parent class
6940                          */
6941                         media.view.Settings.prototype.dispose.apply( this, arguments );
6942                 },
6943                 /**
6944                  * @returns {wp.media.view.AttachmentDisplay} Returns itself to allow chaining
6945                  */
6946                 render: function() {
6947                         var attachment = this.options.attachment;
6948                         if ( attachment ) {
6949                                 _.extend( this.options, {
6950                                         sizes: attachment.get('sizes'),
6951                                         type:  attachment.get('type')
6952                                 });
6953                         }
6954                         /**
6955                          * call 'render' directly on the parent class
6956                          */
6957                         media.view.Settings.prototype.render.call( this );
6958                         this.updateLinkTo();
6959                         return this;
6960                 },
6961
6962                 updateLinkTo: function() {
6963                         var linkTo = this.model.get('link'),
6964                                 $input = this.$('.link-to-custom'),
6965                                 attachment = this.options.attachment;
6966
6967                         if ( 'none' === linkTo || 'embed' === linkTo || ( ! attachment && 'custom' !== linkTo ) ) {
6968                                 $input.addClass( 'hidden' );
6969                                 return;
6970                         }
6971
6972                         if ( attachment ) {
6973                                 if ( 'post' === linkTo ) {
6974                                         $input.val( attachment.get('link') );
6975                                 } else if ( 'file' === linkTo ) {
6976                                         $input.val( attachment.get('url') );
6977                                 } else if ( ! this.model.get('linkUrl') ) {
6978                                         $input.val('http://');
6979                                 }
6980
6981                                 $input.prop( 'readonly', 'custom' !== linkTo );
6982                         }
6983
6984                         $input.removeClass( 'hidden' );
6985
6986                         // If the input is visible, focus and select its contents.
6987                         if ( ! isTouchDevice && $input.is(':visible') ) {
6988                                 $input.focus()[0].select();
6989                         }
6990                 }
6991         });
6992
6993         /**
6994          * wp.media.view.Settings.Gallery
6995          *
6996          * @class
6997          * @augments wp.media.view.Settings
6998          * @augments wp.media.View
6999          * @augments wp.Backbone.View
7000          * @augments Backbone.View
7001          */
7002         media.view.Settings.Gallery = media.view.Settings.extend({
7003                 className: 'collection-settings gallery-settings',
7004                 template:  media.template('gallery-settings')
7005         });
7006
7007         /**
7008          * wp.media.view.Settings.Playlist
7009          *
7010          * @class
7011          * @augments wp.media.view.Settings
7012          * @augments wp.media.View
7013          * @augments wp.Backbone.View
7014          * @augments Backbone.View
7015          */
7016         media.view.Settings.Playlist = media.view.Settings.extend({
7017                 className: 'collection-settings playlist-settings',
7018                 template:  media.template('playlist-settings')
7019         });
7020
7021         /**
7022          * wp.media.view.Attachment.Details
7023          *
7024          * @class
7025          * @augments wp.media.view.Attachment
7026          * @augments wp.media.View
7027          * @augments wp.Backbone.View
7028          * @augments Backbone.View
7029          */
7030         media.view.Attachment.Details = media.view.Attachment.extend({
7031                 tagName:   'div',
7032                 className: 'attachment-details',
7033                 template:  media.template('attachment-details'),
7034
7035                 attributes: function() {
7036                         return {
7037                                 'tabIndex':     0,
7038                                 'data-id':      this.model.get( 'id' )
7039                         };
7040                 },
7041
7042                 events: {
7043                         'change [data-setting]':          'updateSetting',
7044                         'change [data-setting] input':    'updateSetting',
7045                         'change [data-setting] select':   'updateSetting',
7046                         'change [data-setting] textarea': 'updateSetting',
7047                         'click .delete-attachment':       'deleteAttachment',
7048                         'click .trash-attachment':        'trashAttachment',
7049                         'click .untrash-attachment':      'untrashAttachment',
7050                         'click .edit-attachment':         'editAttachment',
7051                         'click .refresh-attachment':      'refreshAttachment',
7052                         'keydown':                        'toggleSelectionHandler'
7053                 },
7054
7055                 initialize: function() {
7056                         this.options = _.defaults( this.options, {
7057                                 rerenderOnModelChange: false
7058                         });
7059
7060                         this.on( 'ready', this.initialFocus );
7061                         // Call 'initialize' directly on the parent class.
7062                         media.view.Attachment.prototype.initialize.apply( this, arguments );
7063                 },
7064
7065                 initialFocus: function() {
7066                         if ( ! isTouchDevice ) {
7067                                 this.$( ':input' ).eq( 0 ).focus();
7068                         }
7069                 },
7070                 /**
7071                  * @param {Object} event
7072                  */
7073                 deleteAttachment: function( event ) {
7074                         event.preventDefault();
7075
7076                         if ( confirm( l10n.warnDelete ) ) {
7077                                 this.model.destroy();
7078                                 // Keep focus inside media modal
7079                                 // after image is deleted
7080                                 this.controller.modal.focusManager.focus();
7081                         }
7082                 },
7083                 /**
7084                  * @param {Object} event
7085                  */
7086                 trashAttachment: function( event ) {
7087                         var library = this.controller.library;
7088                         event.preventDefault();
7089
7090                         if ( media.view.settings.mediaTrash &&
7091                                 'edit-metadata' === this.controller.content.mode() ) {
7092
7093                                 this.model.set( 'status', 'trash' );
7094                                 this.model.save().done( function() {
7095                                         library._requery( true );
7096                                 } );
7097                         }  else {
7098                                 this.model.destroy();
7099                         }
7100                 },
7101                 /**
7102                  * @param {Object} event
7103                  */
7104                 untrashAttachment: function( event ) {
7105                         var library = this.controller.library;
7106                         event.preventDefault();
7107
7108                         this.model.set( 'status', 'inherit' );
7109                         this.model.save().done( function() {
7110                                 library._requery( true );
7111                         } );
7112                 },
7113                 /**
7114                  * @param {Object} event
7115                  */
7116                 editAttachment: function( event ) {
7117                         var editState = this.controller.states.get( 'edit-image' );
7118                         if ( window.imageEdit && editState ) {
7119                                 event.preventDefault();
7120
7121                                 editState.set( 'image', this.model );
7122                                 this.controller.setState( 'edit-image' );
7123                         } else {
7124                                 this.$el.addClass('needs-refresh');
7125                         }
7126                 },
7127                 /**
7128                  * @param {Object} event
7129                  */
7130                 refreshAttachment: function( event ) {
7131                         this.$el.removeClass('needs-refresh');
7132                         event.preventDefault();
7133                         this.model.fetch();
7134                 },
7135                 /**
7136                  * When reverse tabbing(shift+tab) out of the right details panel, deliver
7137                  * the focus to the item in the list that was being edited.
7138                  *
7139                  * @param {Object} event
7140                  */
7141                 toggleSelectionHandler: function( event ) {
7142                         if ( 'keydown' === event.type && 9 === event.keyCode && event.shiftKey && event.target === this.$( ':tabbable' ).get( 0 ) ) {
7143                                 this.controller.trigger( 'attachment:details:shift-tab', event );
7144                                 return false;
7145                         }
7146
7147                         if ( 37 === event.keyCode || 38 === event.keyCode || 39 === event.keyCode || 40 === event.keyCode ) {
7148                                 this.controller.trigger( 'attachment:keydown:arrow', event );
7149                                 return;
7150                         }
7151                 }
7152         });
7153
7154         /**
7155          * wp.media.view.AttachmentCompat
7156          *
7157          * A view to display fields added via the `attachment_fields_to_edit` filter.
7158          *
7159          * @class
7160          * @augments wp.media.View
7161          * @augments wp.Backbone.View
7162          * @augments Backbone.View
7163          */
7164         media.view.AttachmentCompat = media.View.extend({
7165                 tagName:   'form',
7166                 className: 'compat-item',
7167
7168                 events: {
7169                         'submit':          'preventDefault',
7170                         'change input':    'save',
7171                         'change select':   'save',
7172                         'change textarea': 'save'
7173                 },
7174
7175                 initialize: function() {
7176                         this.model.on( 'change:compat', this.render, this );
7177                 },
7178                 /**
7179                  * @returns {wp.media.view.AttachmentCompat} Returns itself to allow chaining
7180                  */
7181                 dispose: function() {
7182                         if ( this.$(':focus').length ) {
7183                                 this.save();
7184                         }
7185                         /**
7186                          * call 'dispose' directly on the parent class
7187                          */
7188                         return media.View.prototype.dispose.apply( this, arguments );
7189                 },
7190                 /**
7191                  * @returns {wp.media.view.AttachmentCompat} Returns itself to allow chaining
7192                  */
7193                 render: function() {
7194                         var compat = this.model.get('compat');
7195                         if ( ! compat || ! compat.item ) {
7196                                 return;
7197                         }
7198
7199                         this.views.detach();
7200                         this.$el.html( compat.item );
7201                         this.views.render();
7202                         return this;
7203                 },
7204                 /**
7205                  * @param {Object} event
7206                  */
7207                 preventDefault: function( event ) {
7208                         event.preventDefault();
7209                 },
7210                 /**
7211                  * @param {Object} event
7212                  */
7213                 save: function( event ) {
7214                         var data = {};
7215
7216                         if ( event ) {
7217                                 event.preventDefault();
7218                         }
7219
7220                         _.each( this.$el.serializeArray(), function( pair ) {
7221                                 data[ pair.name ] = pair.value;
7222                         });
7223
7224                         this.controller.trigger( 'attachment:compat:waiting', ['waiting'] );
7225                         this.model.saveCompat( data ).always( _.bind( this.postSave, this ) );
7226                 },
7227
7228                 postSave: function() {
7229                         this.controller.trigger( 'attachment:compat:ready', ['ready'] );
7230                 }
7231         });
7232
7233         /**
7234          * wp.media.view.Iframe
7235          *
7236          * @class
7237          * @augments wp.media.View
7238          * @augments wp.Backbone.View
7239          * @augments Backbone.View
7240          */
7241         media.view.Iframe = media.View.extend({
7242                 className: 'media-iframe',
7243                 /**
7244                  * @returns {wp.media.view.Iframe} Returns itself to allow chaining
7245                  */
7246                 render: function() {
7247                         this.views.detach();
7248                         this.$el.html( '<iframe src="' + this.controller.state().get('src') + '" />' );
7249                         this.views.render();
7250                         return this;
7251                 }
7252         });
7253
7254         /**
7255          * wp.media.view.Embed
7256          *
7257          * @class
7258          * @augments wp.media.View
7259          * @augments wp.Backbone.View
7260          * @augments Backbone.View
7261          */
7262         media.view.Embed = media.View.extend({
7263                 className: 'media-embed',
7264
7265                 initialize: function() {
7266                         /**
7267                          * @member {wp.media.view.EmbedUrl}
7268                          */
7269                         this.url = new media.view.EmbedUrl({
7270                                 controller: this.controller,
7271                                 model:      this.model.props
7272                         }).render();
7273
7274                         this.views.set([ this.url ]);
7275                         this.refresh();
7276                         this.model.on( 'change:type', this.refresh, this );
7277                         this.model.on( 'change:loading', this.loading, this );
7278                 },
7279
7280                 /**
7281                  * @param {Object} view
7282                  */
7283                 settings: function( view ) {
7284                         if ( this._settings ) {
7285                                 this._settings.remove();
7286                         }
7287                         this._settings = view;
7288                         this.views.add( view );
7289                 },
7290
7291                 refresh: function() {
7292                         var type = this.model.get('type'),
7293                                 constructor;
7294
7295                         if ( 'image' === type ) {
7296                                 constructor = media.view.EmbedImage;
7297                         } else if ( 'link' === type ) {
7298                                 constructor = media.view.EmbedLink;
7299                         } else {
7300                                 return;
7301                         }
7302
7303                         this.settings( new constructor({
7304                                 controller: this.controller,
7305                                 model:      this.model.props,
7306                                 priority:   40
7307                         }) );
7308                 },
7309
7310                 loading: function() {
7311                         this.$el.toggleClass( 'embed-loading', this.model.get('loading') );
7312                 }
7313         });
7314
7315         /**
7316          * @class
7317          * @augments wp.media.View
7318          * @augments wp.Backbone.View
7319          * @augments Backbone.View
7320          */
7321         media.view.Label = media.View.extend({
7322                 tagName: 'label',
7323                 className: 'screen-reader-text',
7324
7325                 initialize: function() {
7326                         this.value = this.options.value;
7327                 },
7328
7329                 render: function() {
7330                         this.$el.html( this.value );
7331
7332                         return this;
7333                 }
7334         });
7335
7336         /**
7337          * wp.media.view.EmbedUrl
7338          *
7339          * @class
7340          * @augments wp.media.View
7341          * @augments wp.Backbone.View
7342          * @augments Backbone.View
7343          */
7344         media.view.EmbedUrl = media.View.extend({
7345                 tagName:   'label',
7346                 className: 'embed-url',
7347
7348                 events: {
7349                         'input':  'url',
7350                         'keyup':  'url',
7351                         'change': 'url'
7352                 },
7353
7354                 initialize: function() {
7355                         var self = this;
7356
7357                         this.$input = $('<input id="embed-url-field" type="url" />').val( this.model.get('url') );
7358                         this.input = this.$input[0];
7359
7360                         this.spinner = $('<span class="spinner" />')[0];
7361                         this.$el.append([ this.input, this.spinner ]);
7362
7363                         this.model.on( 'change:url', this.render, this );
7364
7365                         if ( this.model.get( 'url' ) ) {
7366                                 _.delay( function () {
7367                                         self.model.trigger( 'change:url' );
7368                                 }, 500 );
7369                         }
7370                 },
7371                 /**
7372                  * @returns {wp.media.view.EmbedUrl} Returns itself to allow chaining
7373                  */
7374                 render: function() {
7375                         var $input = this.$input;
7376
7377                         if ( $input.is(':focus') ) {
7378                                 return;
7379                         }
7380
7381                         this.input.value = this.model.get('url') || 'http://';
7382                         /**
7383                          * Call `render` directly on parent class with passed arguments
7384                          */
7385                         media.View.prototype.render.apply( this, arguments );
7386                         return this;
7387                 },
7388
7389                 ready: function() {
7390                         if ( ! isTouchDevice ) {
7391                                 this.focus();
7392                         }
7393                 },
7394
7395                 url: function( event ) {
7396                         this.model.set( 'url', event.target.value );
7397                 },
7398
7399                 /**
7400                  * If the input is visible, focus and select its contents.
7401                  */
7402                 focus: function() {
7403                         var $input = this.$input;
7404                         if ( $input.is(':visible') ) {
7405                                 $input.focus()[0].select();
7406                         }
7407                 }
7408         });
7409
7410         /**
7411          * wp.media.view.EmbedLink
7412          *
7413          * @class
7414          * @augments wp.media.view.Settings
7415          * @augments wp.media.View
7416          * @augments wp.Backbone.View
7417          * @augments Backbone.View
7418          */
7419         media.view.EmbedLink = media.view.Settings.extend({
7420                 className: 'embed-link-settings',
7421                 template:  media.template('embed-link-settings'),
7422
7423                 initialize: function() {
7424                         this.spinner = $('<span class="spinner" />');
7425                         this.$el.append( this.spinner[0] );
7426                         this.listenTo( this.model, 'change:url', this.updateoEmbed );
7427                 },
7428
7429                 updateoEmbed: function() {
7430                         var url = this.model.get( 'url' );
7431
7432                         this.$('.setting.title').show();
7433                         // clear out previous results
7434                         this.$('.embed-container').hide().find('.embed-preview').html('');
7435
7436                         // only proceed with embed if the field contains more than 6 characters
7437                         if ( url && url.length < 6 ) {
7438                                 return;
7439                         }
7440
7441                         this.spinner.show();
7442
7443                         setTimeout( _.bind( this.fetch, this ), 500 );
7444                 },
7445
7446                 fetch: function() {
7447                         // check if they haven't typed in 500 ms
7448                         if ( $('#embed-url-field').val() !== this.model.get('url') ) {
7449                                 return;
7450                         }
7451
7452                         wp.ajax.send( 'parse-embed', {
7453                                 data : {
7454                                         post_ID: media.view.settings.post.id,
7455                                         shortcode: '[embed]' + this.model.get('url') + '[/embed]'
7456                                 }
7457                         } ).done( _.bind( this.renderoEmbed, this ) );
7458                 },
7459
7460                 renderoEmbed: function( response ) {
7461                         var html = ( response && response.body ) || '';
7462
7463                         this.spinner.hide();
7464
7465                         this.$('.setting.title').hide();
7466                         this.$('.embed-container').show().find('.embed-preview').html( html );
7467                 }
7468         });
7469
7470         /**
7471          * wp.media.view.EmbedImage
7472          *
7473          * @class
7474          * @augments wp.media.view.Settings.AttachmentDisplay
7475          * @augments wp.media.view.Settings
7476          * @augments wp.media.View
7477          * @augments wp.Backbone.View
7478          * @augments Backbone.View
7479          */
7480         media.view.EmbedImage =  media.view.Settings.AttachmentDisplay.extend({
7481                 className: 'embed-media-settings',
7482                 template:  media.template('embed-image-settings'),
7483
7484                 initialize: function() {
7485                         /**
7486                          * Call `initialize` directly on parent class with passed arguments
7487                          */
7488                         media.view.Settings.AttachmentDisplay.prototype.initialize.apply( this, arguments );
7489                         this.model.on( 'change:url', this.updateImage, this );
7490                 },
7491
7492                 updateImage: function() {
7493                         this.$('img').attr( 'src', this.model.get('url') );
7494                 }
7495         });
7496
7497         /**
7498          * wp.media.view.ImageDetails
7499          *
7500          * @class
7501          * @augments wp.media.view.Settings.AttachmentDisplay
7502          * @augments wp.media.view.Settings
7503          * @augments wp.media.View
7504          * @augments wp.Backbone.View
7505          * @augments Backbone.View
7506          */
7507         media.view.ImageDetails = media.view.Settings.AttachmentDisplay.extend({
7508                 className: 'image-details',
7509                 template:  media.template('image-details'),
7510                 events: _.defaults( media.view.Settings.AttachmentDisplay.prototype.events, {
7511                         'click .edit-attachment': 'editAttachment',
7512                         'click .replace-attachment': 'replaceAttachment',
7513                         'click .advanced-toggle': 'onToggleAdvanced',
7514                         'change [data-setting="customWidth"]': 'onCustomSize',
7515                         'change [data-setting="customHeight"]': 'onCustomSize',
7516                         'keyup [data-setting="customWidth"]': 'onCustomSize',
7517                         'keyup [data-setting="customHeight"]': 'onCustomSize'
7518                 } ),
7519                 initialize: function() {
7520                         // used in AttachmentDisplay.prototype.updateLinkTo
7521                         this.options.attachment = this.model.attachment;
7522                         this.listenTo( this.model, 'change:url', this.updateUrl );
7523                         this.listenTo( this.model, 'change:link', this.toggleLinkSettings );
7524                         this.listenTo( this.model, 'change:size', this.toggleCustomSize );
7525
7526                         media.view.Settings.AttachmentDisplay.prototype.initialize.apply( this, arguments );
7527                 },
7528
7529                 prepare: function() {
7530                         var attachment = false;
7531
7532                         if ( this.model.attachment ) {
7533                                 attachment = this.model.attachment.toJSON();
7534                         }
7535                         return _.defaults({
7536                                 model: this.model.toJSON(),
7537                                 attachment: attachment
7538                         }, this.options );
7539                 },
7540
7541                 render: function() {
7542                         var self = this,
7543                                 args = arguments;
7544
7545                         if ( this.model.attachment && 'pending' === this.model.dfd.state() ) {
7546                                 this.model.dfd.done( function() {
7547                                         media.view.Settings.AttachmentDisplay.prototype.render.apply( self, args );
7548                                         self.postRender();
7549                                 } ).fail( function() {
7550                                         self.model.attachment = false;
7551                                         media.view.Settings.AttachmentDisplay.prototype.render.apply( self, args );
7552                                         self.postRender();
7553                                 } );
7554                         } else {
7555                                 media.view.Settings.AttachmentDisplay.prototype.render.apply( this, arguments );
7556                                 this.postRender();
7557                         }
7558
7559                         return this;
7560                 },
7561
7562                 postRender: function() {
7563                         setTimeout( _.bind( this.resetFocus, this ), 10 );
7564                         this.toggleLinkSettings();
7565                         if ( getUserSetting( 'advImgDetails' ) === 'show' ) {
7566                                 this.toggleAdvanced( true );
7567                         }
7568                         this.trigger( 'post-render' );
7569                 },
7570
7571                 resetFocus: function() {
7572                         this.$( '.link-to-custom' ).blur();
7573                         this.$( '.embed-media-settings' ).scrollTop( 0 );
7574                 },
7575
7576                 updateUrl: function() {
7577                         this.$( '.image img' ).attr( 'src', this.model.get( 'url' ) );
7578                         this.$( '.url' ).val( this.model.get( 'url' ) );
7579                 },
7580
7581                 toggleLinkSettings: function() {
7582                         if ( this.model.get( 'link' ) === 'none' ) {
7583                                 this.$( '.link-settings' ).addClass('hidden');
7584                         } else {
7585                                 this.$( '.link-settings' ).removeClass('hidden');
7586                         }
7587                 },
7588
7589                 toggleCustomSize: function() {
7590                         if ( this.model.get( 'size' ) !== 'custom' ) {
7591                                 this.$( '.custom-size' ).addClass('hidden');
7592                         } else {
7593                                 this.$( '.custom-size' ).removeClass('hidden');
7594                         }
7595                 },
7596
7597                 onCustomSize: function( event ) {
7598                         var dimension = $( event.target ).data('setting'),
7599                                 num = $( event.target ).val(),
7600                                 value;
7601
7602                         // Ignore bogus input
7603                         if ( ! /^\d+/.test( num ) || parseInt( num, 10 ) < 1 ) {
7604                                 event.preventDefault();
7605                                 return;
7606                         }
7607
7608                         if ( dimension === 'customWidth' ) {
7609                                 value = Math.round( 1 / this.model.get( 'aspectRatio' ) * num );
7610                                 this.model.set( 'customHeight', value, { silent: true } );
7611                                 this.$( '[data-setting="customHeight"]' ).val( value );
7612                         } else {
7613                                 value = Math.round( this.model.get( 'aspectRatio' ) * num );
7614                                 this.model.set( 'customWidth', value, { silent: true  } );
7615                                 this.$( '[data-setting="customWidth"]' ).val( value );
7616                         }
7617                 },
7618
7619                 onToggleAdvanced: function( event ) {
7620                         event.preventDefault();
7621                         this.toggleAdvanced();
7622                 },
7623
7624                 toggleAdvanced: function( show ) {
7625                         var $advanced = this.$el.find( '.advanced-section' ),
7626                                 mode;
7627
7628                         if ( $advanced.hasClass('advanced-visible') || show === false ) {
7629                                 $advanced.removeClass('advanced-visible');
7630                                 $advanced.find('.advanced-settings').addClass('hidden');
7631                                 mode = 'hide';
7632                         } else {
7633                                 $advanced.addClass('advanced-visible');
7634                                 $advanced.find('.advanced-settings').removeClass('hidden');
7635                                 mode = 'show';
7636                         }
7637
7638                         setUserSetting( 'advImgDetails', mode );
7639                 },
7640
7641                 editAttachment: function( event ) {
7642                         var editState = this.controller.states.get( 'edit-image' );
7643
7644                         if ( window.imageEdit && editState ) {
7645                                 event.preventDefault();
7646                                 editState.set( 'image', this.model.attachment );
7647                                 this.controller.setState( 'edit-image' );
7648                         }
7649                 },
7650
7651                 replaceAttachment: function( event ) {
7652                         event.preventDefault();
7653                         this.controller.setState( 'replace-image' );
7654                 }
7655         });
7656
7657         /**
7658          * wp.media.view.Cropper
7659          *
7660          * Uses the imgAreaSelect plugin to allow a user to crop an image.
7661          *
7662          * Takes imgAreaSelect options from
7663          * wp.customize.HeaderControl.calculateImageSelectOptions via
7664          * wp.customize.HeaderControl.openMM.
7665          *
7666          * @class
7667          * @augments wp.media.View
7668          * @augments wp.Backbone.View
7669          * @augments Backbone.View
7670          */
7671         media.view.Cropper = media.View.extend({
7672                 className: 'crop-content',
7673                 template: media.template('crop-content'),
7674                 initialize: function() {
7675                         _.bindAll(this, 'onImageLoad');
7676                 },
7677                 ready: function() {
7678                         this.controller.frame.on('content:error:crop', this.onError, this);
7679                         this.$image = this.$el.find('.crop-image');
7680                         this.$image.on('load', this.onImageLoad);
7681                         $(window).on('resize.cropper', _.debounce(this.onImageLoad, 250));
7682                 },
7683                 remove: function() {
7684                         $(window).off('resize.cropper');
7685                         this.$el.remove();
7686                         this.$el.off();
7687                         wp.media.View.prototype.remove.apply(this, arguments);
7688                 },
7689                 prepare: function() {
7690                         return {
7691                                 title: l10n.cropYourImage,
7692                                 url: this.options.attachment.get('url')
7693                         };
7694                 },
7695                 onImageLoad: function() {
7696                         var imgOptions = this.controller.get('imgSelectOptions');
7697                         if (typeof imgOptions === 'function') {
7698                                 imgOptions = imgOptions(this.options.attachment, this.controller);
7699                         }
7700
7701                         imgOptions = _.extend(imgOptions, {parent: this.$el});
7702                         this.trigger('image-loaded');
7703                         this.controller.imgSelect = this.$image.imgAreaSelect(imgOptions);
7704                 },
7705                 onError: function() {
7706                         var filename = this.options.attachment.get('filename');
7707
7708                         this.views.add( '.upload-errors', new media.view.UploaderStatusError({
7709                                 filename: media.view.UploaderStatus.prototype.filename(filename),
7710                                 message: _wpMediaViewsL10n.cropError
7711                         }), { at: 0 });
7712                 }
7713         });
7714
7715         media.view.EditImage = media.View.extend({
7716
7717                 className: 'image-editor',
7718                 template: media.template('image-editor'),
7719
7720                 initialize: function( options ) {
7721                         this.editor = window.imageEdit;
7722                         this.controller = options.controller;
7723                         media.View.prototype.initialize.apply( this, arguments );
7724                 },
7725
7726                 prepare: function() {
7727                         return this.model.toJSON();
7728                 },
7729
7730                 render: function() {
7731                         media.View.prototype.render.apply( this, arguments );
7732                         return this;
7733                 },
7734
7735                 loadEditor: function() {
7736                         var dfd = this.editor.open( this.model.get('id'), this.model.get('nonces').edit, this );
7737                         dfd.done( _.bind( this.focus, this ) );
7738                 },
7739
7740                 focus: function() {
7741                         this.$( '.imgedit-submit .button' ).eq( 0 ).focus();
7742                 },
7743
7744                 back: function() {
7745                         var lastState = this.controller.lastState();
7746                         this.controller.setState( lastState );
7747                 },
7748
7749                 refresh: function() {
7750                         this.model.fetch();
7751                 },
7752
7753                 save: function() {
7754                         var self = this,
7755                                 lastState = this.controller.lastState();
7756
7757                         this.model.fetch().done( function() {
7758                                 self.controller.setState( lastState );
7759                         });
7760                 }
7761
7762         });
7763
7764         /**
7765          * wp.media.view.Spinner
7766          *
7767          * @class
7768          * @augments wp.media.View
7769          * @augments wp.Backbone.View
7770          * @augments Backbone.View
7771          */
7772         media.view.Spinner = media.View.extend({
7773                 tagName:   'span',
7774                 className: 'spinner',
7775                 spinnerTimeout: false,
7776                 delay: 400,
7777
7778                 show: function() {
7779                         if ( ! this.spinnerTimeout ) {
7780                                 this.spinnerTimeout = _.delay(function( $el ) {
7781                                         $el.show();
7782                                 }, this.delay, this.$el );
7783                         }
7784
7785                         return this;
7786                 },
7787
7788                 hide: function() {
7789                         this.$el.hide();
7790                         this.spinnerTimeout = clearTimeout( this.spinnerTimeout );
7791
7792                         return this;
7793                 }
7794         });
7795 }(jQuery, _));