]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-admin/js/theme.js
WordPress 4.7.2-scripts
[autoinstalls/wordpress.git] / wp-admin / js / theme.js
1 /* global _wpThemeSettings, confirm */
2 window.wp = window.wp || {};
3
4 ( function($) {
5
6 // Set up our namespace...
7 var themes, l10n;
8 themes = wp.themes = wp.themes || {};
9
10 // Store the theme data and settings for organized and quick access
11 // themes.data.settings, themes.data.themes, themes.data.l10n
12 themes.data = _wpThemeSettings;
13 l10n = themes.data.l10n;
14
15 // Shortcut for isInstall check
16 themes.isInstall = !! themes.data.settings.isInstall;
17
18 // Setup app structure
19 _.extend( themes, { model: {}, view: {}, routes: {}, router: {}, template: wp.template });
20
21 themes.Model = Backbone.Model.extend({
22         // Adds attributes to the default data coming through the .org themes api
23         // Map `id` to `slug` for shared code
24         initialize: function() {
25                 var description;
26
27                 // If theme is already installed, set an attribute.
28                 if ( _.indexOf( themes.data.installedThemes, this.get( 'slug' ) ) !== -1 ) {
29                         this.set({ installed: true });
30                 }
31
32                 // Set the attributes
33                 this.set({
34                         // slug is for installation, id is for existing.
35                         id: this.get( 'slug' ) || this.get( 'id' )
36                 });
37
38                 // Map `section.description` to `description`
39                 // as the API sometimes returns it differently
40                 if ( this.has( 'sections' ) ) {
41                         description = this.get( 'sections' ).description;
42                         this.set({ description: description });
43                 }
44         }
45 });
46
47 // Main view controller for themes.php
48 // Unifies and renders all available views
49 themes.view.Appearance = wp.Backbone.View.extend({
50
51         el: '#wpbody-content .wrap .theme-browser',
52
53         window: $( window ),
54         // Pagination instance
55         page: 0,
56
57         // Sets up a throttler for binding to 'scroll'
58         initialize: function( options ) {
59                 // Scroller checks how far the scroll position is
60                 _.bindAll( this, 'scroller' );
61
62                 this.SearchView = options.SearchView ? options.SearchView : themes.view.Search;
63                 // Bind to the scroll event and throttle
64                 // the results from this.scroller
65                 this.window.bind( 'scroll', _.throttle( this.scroller, 300 ) );
66         },
67
68         // Main render control
69         render: function() {
70                 // Setup the main theme view
71                 // with the current theme collection
72                 this.view = new themes.view.Themes({
73                         collection: this.collection,
74                         parent: this
75                 });
76
77                 // Render search form.
78                 this.search();
79
80                 // Render and append
81                 this.view.render();
82                 this.$el.empty().append( this.view.el ).addClass( 'rendered' );
83         },
84
85         // Defines search element container
86         searchContainer: $( '#wpbody h1:first' ),
87
88         // Search input and view
89         // for current theme collection
90         search: function() {
91                 var view,
92                         self = this;
93
94                 // Don't render the search if there is only one theme
95                 if ( themes.data.themes.length === 1 ) {
96                         return;
97                 }
98
99                 view = new this.SearchView({
100                         collection: self.collection,
101                         parent: this
102                 });
103
104                 // Render and append after screen title
105                 view.render();
106                 this.searchContainer
107                         .append( $.parseHTML( '<label class="screen-reader-text" for="wp-filter-search-input">' + l10n.search + '</label>' ) )
108                         .append( view.el );
109         },
110
111         // Checks when the user gets close to the bottom
112         // of the mage and triggers a theme:scroll event
113         scroller: function() {
114                 var self = this,
115                         bottom, threshold;
116
117                 bottom = this.window.scrollTop() + self.window.height();
118                 threshold = self.$el.offset().top + self.$el.outerHeight( false ) - self.window.height();
119                 threshold = Math.round( threshold * 0.9 );
120
121                 if ( bottom > threshold ) {
122                         this.trigger( 'theme:scroll' );
123                 }
124         }
125 });
126
127 // Set up the Collection for our theme data
128 // @has 'id' 'name' 'screenshot' 'author' 'authorURI' 'version' 'active' ...
129 themes.Collection = Backbone.Collection.extend({
130
131         model: themes.Model,
132
133         // Search terms
134         terms: '',
135
136         // Controls searching on the current theme collection
137         // and triggers an update event
138         doSearch: function( value ) {
139
140                 // Don't do anything if we've already done this search
141                 // Useful because the Search handler fires multiple times per keystroke
142                 if ( this.terms === value ) {
143                         return;
144                 }
145
146                 // Updates terms with the value passed
147                 this.terms = value;
148
149                 // If we have terms, run a search...
150                 if ( this.terms.length > 0 ) {
151                         this.search( this.terms );
152                 }
153
154                 // If search is blank, show all themes
155                 // Useful for resetting the views when you clean the input
156                 if ( this.terms === '' ) {
157                         this.reset( themes.data.themes );
158                         $( 'body' ).removeClass( 'no-results' );
159                 }
160
161                 // Trigger a 'themes:update' event
162                 this.trigger( 'themes:update' );
163         },
164
165         // Performs a search within the collection
166         // @uses RegExp
167         search: function( term ) {
168                 var match, results, haystack, name, description, author;
169
170                 // Start with a full collection
171                 this.reset( themes.data.themes, { silent: true } );
172
173                 // Escape the term string for RegExp meta characters
174                 term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' );
175
176                 // Consider spaces as word delimiters and match the whole string
177                 // so matching terms can be combined
178                 term = term.replace( / /g, ')(?=.*' );
179                 match = new RegExp( '^(?=.*' + term + ').+', 'i' );
180
181                 // Find results
182                 // _.filter and .test
183                 results = this.filter( function( data ) {
184                         name        = data.get( 'name' ).replace( /(<([^>]+)>)/ig, '' );
185                         description = data.get( 'description' ).replace( /(<([^>]+)>)/ig, '' );
186                         author      = data.get( 'author' ).replace( /(<([^>]+)>)/ig, '' );
187
188                         haystack = _.union( [ name, data.get( 'id' ), description, author, data.get( 'tags' ) ] );
189
190                         if ( match.test( data.get( 'author' ) ) && term.length > 2 ) {
191                                 data.set( 'displayAuthor', true );
192                         }
193
194                         return match.test( haystack );
195                 });
196
197                 if ( results.length === 0 ) {
198                         this.trigger( 'query:empty' );
199                 } else {
200                         $( 'body' ).removeClass( 'no-results' );
201                 }
202
203                 this.reset( results );
204         },
205
206         // Paginates the collection with a helper method
207         // that slices the collection
208         paginate: function( instance ) {
209                 var collection = this;
210                 instance = instance || 0;
211
212                 // Themes per instance are set at 20
213                 collection = _( collection.rest( 20 * instance ) );
214                 collection = _( collection.first( 20 ) );
215
216                 return collection;
217         },
218
219         count: false,
220
221         // Handles requests for more themes
222         // and caches results
223         //
224         // When we are missing a cache object we fire an apiCall()
225         // which triggers events of `query:success` or `query:fail`
226         query: function( request ) {
227                 /**
228                  * @static
229                  * @type Array
230                  */
231                 var queries = this.queries,
232                         self = this,
233                         query, isPaginated, count;
234
235                 // Store current query request args
236                 // for later use with the event `theme:end`
237                 this.currentQuery.request = request;
238
239                 // Search the query cache for matches.
240                 query = _.find( queries, function( query ) {
241                         return _.isEqual( query.request, request );
242                 });
243
244                 // If the request matches the stored currentQuery.request
245                 // it means we have a paginated request.
246                 isPaginated = _.has( request, 'page' );
247
248                 // Reset the internal api page counter for non paginated queries.
249                 if ( ! isPaginated ) {
250                         this.currentQuery.page = 1;
251                 }
252
253                 // Otherwise, send a new API call and add it to the cache.
254                 if ( ! query && ! isPaginated ) {
255                         query = this.apiCall( request ).done( function( data ) {
256
257                                 // Update the collection with the queried data.
258                                 if ( data.themes ) {
259                                         self.reset( data.themes );
260                                         count = data.info.results;
261                                         // Store the results and the query request
262                                         queries.push( { themes: data.themes, request: request, total: count } );
263                                 }
264
265                                 // Trigger a collection refresh event
266                                 // and a `query:success` event with a `count` argument.
267                                 self.trigger( 'themes:update' );
268                                 self.trigger( 'query:success', count );
269
270                                 if ( data.themes && data.themes.length === 0 ) {
271                                         self.trigger( 'query:empty' );
272                                 }
273
274                         }).fail( function() {
275                                 self.trigger( 'query:fail' );
276                         });
277                 } else {
278                         // If it's a paginated request we need to fetch more themes...
279                         if ( isPaginated ) {
280                                 return this.apiCall( request, isPaginated ).done( function( data ) {
281                                         // Add the new themes to the current collection
282                                         // @todo update counter
283                                         self.add( data.themes );
284                                         self.trigger( 'query:success' );
285
286                                         // We are done loading themes for now.
287                                         self.loadingThemes = false;
288
289                                 }).fail( function() {
290                                         self.trigger( 'query:fail' );
291                                 });
292                         }
293
294                         if ( query.themes.length === 0 ) {
295                                 self.trigger( 'query:empty' );
296                         } else {
297                                 $( 'body' ).removeClass( 'no-results' );
298                         }
299
300                         // Only trigger an update event since we already have the themes
301                         // on our cached object
302                         if ( _.isNumber( query.total ) ) {
303                                 this.count = query.total;
304                         }
305
306                         this.reset( query.themes );
307                         if ( ! query.total ) {
308                                 this.count = this.length;
309                         }
310
311                         this.trigger( 'themes:update' );
312                         this.trigger( 'query:success', this.count );
313                 }
314         },
315
316         // Local cache array for API queries
317         queries: [],
318
319         // Keep track of current query so we can handle pagination
320         currentQuery: {
321                 page: 1,
322                 request: {}
323         },
324
325         // Send request to api.wordpress.org/themes
326         apiCall: function( request, paginated ) {
327                 return wp.ajax.send( 'query-themes', {
328                         data: {
329                         // Request data
330                                 request: _.extend({
331                                         per_page: 100,
332                                         fields: {
333                                                 description: true,
334                                                 tested: true,
335                                                 requires: true,
336                                                 rating: true,
337                                                 downloaded: true,
338                                                 downloadLink: true,
339                                                 last_updated: true,
340                                                 homepage: true,
341                                                 num_ratings: true
342                                         }
343                                 }, request)
344                         },
345
346                         beforeSend: function() {
347                                 if ( ! paginated ) {
348                                         // Spin it
349                                         $( 'body' ).addClass( 'loading-content' ).removeClass( 'no-results' );
350                                 }
351                         }
352                 });
353         },
354
355         // Static status controller for when we are loading themes.
356         loadingThemes: false
357 });
358
359 // This is the view that controls each theme item
360 // that will be displayed on the screen
361 themes.view.Theme = wp.Backbone.View.extend({
362
363         // Wrap theme data on a div.theme element
364         className: 'theme',
365
366         // Reflects which theme view we have
367         // 'grid' (default) or 'detail'
368         state: 'grid',
369
370         // The HTML template for each element to be rendered
371         html: themes.template( 'theme' ),
372
373         events: {
374                 'click': themes.isInstall ? 'preview': 'expand',
375                 'keydown': themes.isInstall ? 'preview': 'expand',
376                 'touchend': themes.isInstall ? 'preview': 'expand',
377                 'keyup': 'addFocus',
378                 'touchmove': 'preventExpand',
379                 'click .theme-install': 'installTheme',
380                 'click .update-message': 'updateTheme'
381         },
382
383         touchDrag: false,
384
385         initialize: function() {
386                 this.model.on( 'change', this.render, this );
387         },
388
389         render: function() {
390                 var data = this.model.toJSON();
391
392                 // Render themes using the html template
393                 this.$el.html( this.html( data ) ).attr({
394                         tabindex: 0,
395                         'aria-describedby' : data.id + '-action ' + data.id + '-name',
396                         'data-slug': data.id
397                 });
398
399                 // Renders active theme styles
400                 this.activeTheme();
401
402                 if ( this.model.get( 'displayAuthor' ) ) {
403                         this.$el.addClass( 'display-author' );
404                 }
405         },
406
407         // Adds a class to the currently active theme
408         // and to the overlay in detailed view mode
409         activeTheme: function() {
410                 if ( this.model.get( 'active' ) ) {
411                         this.$el.addClass( 'active' );
412                 }
413         },
414
415         // Add class of focus to the theme we are focused on.
416         addFocus: function() {
417                 var $themeToFocus = ( $( ':focus' ).hasClass( 'theme' ) ) ? $( ':focus' ) : $(':focus').parents('.theme');
418
419                 $('.theme.focus').removeClass('focus');
420                 $themeToFocus.addClass('focus');
421         },
422
423         // Single theme overlay screen
424         // It's shown when clicking a theme
425         expand: function( event ) {
426                 var self = this;
427
428                 event = event || window.event;
429
430                 // 'enter' and 'space' keys expand the details view when a theme is :focused
431                 if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
432                         return;
433                 }
434
435                 // Bail if the user scrolled on a touch device
436                 if ( this.touchDrag === true ) {
437                         return this.touchDrag = false;
438                 }
439
440                 // Prevent the modal from showing when the user clicks
441                 // one of the direct action buttons
442                 if ( $( event.target ).is( '.theme-actions a' ) ) {
443                         return;
444                 }
445
446                 // Prevent the modal from showing when the user clicks one of the direct action buttons.
447                 if ( $( event.target ).is( '.theme-actions a, .update-message, .button-link, .notice-dismiss' ) ) {
448                         return;
449                 }
450
451                 // Set focused theme to current element
452                 themes.focusedTheme = this.$el;
453
454                 this.trigger( 'theme:expand', self.model.cid );
455         },
456
457         preventExpand: function() {
458                 this.touchDrag = true;
459         },
460
461         preview: function( event ) {
462                 var self = this,
463                         current, preview;
464
465                 event = event || window.event;
466
467                 // Bail if the user scrolled on a touch device
468                 if ( this.touchDrag === true ) {
469                         return this.touchDrag = false;
470                 }
471
472                 // Allow direct link path to installing a theme.
473                 if ( $( event.target ).not( '.install-theme-preview' ).parents( '.theme-actions' ).length ) {
474                         return;
475                 }
476
477                 // 'enter' and 'space' keys expand the details view when a theme is :focused
478                 if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
479                         return;
480                 }
481
482                 // pressing enter while focused on the buttons shouldn't open the preview
483                 if ( event.type === 'keydown' && event.which !== 13 && $( ':focus' ).hasClass( 'button' ) ) {
484                         return;
485                 }
486
487                 event.preventDefault();
488
489                 event = event || window.event;
490
491                 // Set focus to current theme.
492                 themes.focusedTheme = this.$el;
493
494                 // Construct a new Preview view.
495                 preview = new themes.view.Preview({
496                         model: this.model
497                 });
498
499                 // Render the view and append it.
500                 preview.render();
501                 this.setNavButtonsState();
502
503                 // Hide previous/next navigation if there is only one theme
504                 if ( this.model.collection.length === 1 ) {
505                         preview.$el.addClass( 'no-navigation' );
506                 } else {
507                         preview.$el.removeClass( 'no-navigation' );
508                 }
509
510                 // Append preview
511                 $( 'div.wrap' ).append( preview.el );
512
513                 // Listen to our preview object
514                 // for `theme:next` and `theme:previous` events.
515                 this.listenTo( preview, 'theme:next', function() {
516
517                         // Keep local track of current theme model.
518                         current = self.model;
519
520                         // If we have ventured away from current model update the current model position.
521                         if ( ! _.isUndefined( self.current ) ) {
522                                 current = self.current;
523                         }
524
525                         // Get next theme model.
526                         self.current = self.model.collection.at( self.model.collection.indexOf( current ) + 1 );
527
528                         // If we have no more themes, bail.
529                         if ( _.isUndefined( self.current ) ) {
530                                 self.options.parent.parent.trigger( 'theme:end' );
531                                 return self.current = current;
532                         }
533
534                         preview.model = self.current;
535
536                         // Render and append.
537                         preview.render();
538                         this.setNavButtonsState();
539                         $( '.next-theme' ).focus();
540                 })
541                 .listenTo( preview, 'theme:previous', function() {
542
543                         // Keep track of current theme model.
544                         current = self.model;
545
546                         // Bail early if we are at the beginning of the collection
547                         if ( self.model.collection.indexOf( self.current ) === 0 ) {
548                                 return;
549                         }
550
551                         // If we have ventured away from current model update the current model position.
552                         if ( ! _.isUndefined( self.current ) ) {
553                                 current = self.current;
554                         }
555
556                         // Get previous theme model.
557                         self.current = self.model.collection.at( self.model.collection.indexOf( current ) - 1 );
558
559                         // If we have no more themes, bail.
560                         if ( _.isUndefined( self.current ) ) {
561                                 return;
562                         }
563
564                         preview.model = self.current;
565
566                         // Render and append.
567                         preview.render();
568                         this.setNavButtonsState();
569                         $( '.previous-theme' ).focus();
570                 });
571
572                 this.listenTo( preview, 'preview:close', function() {
573                         self.current = self.model;
574                 });
575         },
576
577         // Handles .disabled classes for previous/next buttons in theme installer preview
578         setNavButtonsState: function() {
579                 var $themeInstaller = $( '.theme-install-overlay' ),
580                         current = _.isUndefined( this.current ) ? this.model : this.current;
581
582                 // Disable previous at the zero position
583                 if ( 0 === this.model.collection.indexOf( current ) ) {
584                         $themeInstaller.find( '.previous-theme' ).addClass( 'disabled' );
585                 }
586
587                 // Disable next if the next model is undefined
588                 if ( _.isUndefined( this.model.collection.at( this.model.collection.indexOf( current ) + 1 ) ) ) {
589                         $themeInstaller.find( '.next-theme' ).addClass( 'disabled' );
590                 }
591         },
592
593         installTheme: function( event ) {
594                 var _this = this;
595
596                 event.preventDefault();
597
598                 wp.updates.maybeRequestFilesystemCredentials( event );
599
600                 $( document ).on( 'wp-theme-install-success', function( event, response ) {
601                         if ( _this.model.get( 'id' ) === response.slug ) {
602                                 _this.model.set( { 'installed': true } );
603                         }
604                 } );
605
606                 wp.updates.installTheme( {
607                         slug: $( event.target ).data( 'slug' )
608                 } );
609         },
610
611         updateTheme: function( event ) {
612                 var _this = this;
613
614                 if ( ! this.model.get( 'hasPackage' ) ) {
615                         return;
616                 }
617
618                 event.preventDefault();
619
620                 wp.updates.maybeRequestFilesystemCredentials( event );
621
622                 $( document ).on( 'wp-theme-update-success', function( event, response ) {
623                         _this.model.off( 'change', _this.render, _this );
624                         if ( _this.model.get( 'id' ) === response.slug ) {
625                                 _this.model.set( {
626                                         hasUpdate: false,
627                                         version: response.newVersion
628                                 } );
629                         }
630                         _this.model.on( 'change', _this.render, _this );
631                 } );
632
633                 wp.updates.updateTheme( {
634                         slug: $( event.target ).parents( 'div.theme' ).first().data( 'slug' )
635                 } );
636         }
637 });
638
639 // Theme Details view
640 // Set ups a modal overlay with the expanded theme data
641 themes.view.Details = wp.Backbone.View.extend({
642
643         // Wrap theme data on a div.theme element
644         className: 'theme-overlay',
645
646         events: {
647                 'click': 'collapse',
648                 'click .delete-theme': 'deleteTheme',
649                 'click .left': 'previousTheme',
650                 'click .right': 'nextTheme',
651                 'click #update-theme': 'updateTheme'
652         },
653
654         // The HTML template for the theme overlay
655         html: themes.template( 'theme-single' ),
656
657         render: function() {
658                 var data = this.model.toJSON();
659                 this.$el.html( this.html( data ) );
660                 // Renders active theme styles
661                 this.activeTheme();
662                 // Set up navigation events
663                 this.navigation();
664                 // Checks screenshot size
665                 this.screenshotCheck( this.$el );
666                 // Contain "tabbing" inside the overlay
667                 this.containFocus( this.$el );
668         },
669
670         // Adds a class to the currently active theme
671         // and to the overlay in detailed view mode
672         activeTheme: function() {
673                 // Check the model has the active property
674                 this.$el.toggleClass( 'active', this.model.get( 'active' ) );
675         },
676
677         // Set initial focus and constrain tabbing within the theme browser modal.
678         containFocus: function( $el ) {
679
680                 // Set initial focus on the primary action control.
681                 _.delay( function() {
682                         $( '.theme-wrap a.button-primary:visible' ).focus();
683                 }, 100 );
684
685                 // Constrain tabbing within the modal.
686                 $el.on( 'keydown.wp-themes', function( event ) {
687                         var $firstFocusable = $el.find( '.theme-header button:not(.disabled)' ).first(),
688                                 $lastFocusable = $el.find( '.theme-actions a:visible' ).last();
689
690                         // Check for the Tab key.
691                         if ( 9 === event.which ) {
692                                 if ( $firstFocusable[0] === event.target && event.shiftKey ) {
693                                         $lastFocusable.focus();
694                                         event.preventDefault();
695                                 } else if ( $lastFocusable[0] === event.target && ! event.shiftKey ) {
696                                         $firstFocusable.focus();
697                                         event.preventDefault();
698                                 }
699                         }
700                 });
701         },
702
703         // Single theme overlay screen
704         // It's shown when clicking a theme
705         collapse: function( event ) {
706                 var self = this,
707                         scroll;
708
709                 event = event || window.event;
710
711                 // Prevent collapsing detailed view when there is only one theme available
712                 if ( themes.data.themes.length === 1 ) {
713                         return;
714                 }
715
716                 // Detect if the click is inside the overlay
717                 // and don't close it unless the target was
718                 // the div.back button
719                 if ( $( event.target ).is( '.theme-backdrop' ) || $( event.target ).is( '.close' ) || event.keyCode === 27 ) {
720
721                         // Add a temporary closing class while overlay fades out
722                         $( 'body' ).addClass( 'closing-overlay' );
723
724                         // With a quick fade out animation
725                         this.$el.fadeOut( 130, function() {
726                                 // Clicking outside the modal box closes the overlay
727                                 $( 'body' ).removeClass( 'closing-overlay' );
728                                 // Handle event cleanup
729                                 self.closeOverlay();
730
731                                 // Get scroll position to avoid jumping to the top
732                                 scroll = document.body.scrollTop;
733
734                                 // Clean the url structure
735                                 themes.router.navigate( themes.router.baseUrl( '' ) );
736
737                                 // Restore scroll position
738                                 document.body.scrollTop = scroll;
739
740                                 // Return focus to the theme div
741                                 if ( themes.focusedTheme ) {
742                                         themes.focusedTheme.focus();
743                                 }
744                         });
745                 }
746         },
747
748         // Handles .disabled classes for next/previous buttons
749         navigation: function() {
750
751                 // Disable Left/Right when at the start or end of the collection
752                 if ( this.model.cid === this.model.collection.at(0).cid ) {
753                         this.$el.find( '.left' )
754                                 .addClass( 'disabled' )
755                                 .prop( 'disabled', true );
756                 }
757                 if ( this.model.cid === this.model.collection.at( this.model.collection.length - 1 ).cid ) {
758                         this.$el.find( '.right' )
759                                 .addClass( 'disabled' )
760                                 .prop( 'disabled', true );
761                 }
762         },
763
764         // Performs the actions to effectively close
765         // the theme details overlay
766         closeOverlay: function() {
767                 $( 'body' ).removeClass( 'modal-open' );
768                 this.remove();
769                 this.unbind();
770                 this.trigger( 'theme:collapse' );
771         },
772
773         updateTheme: function( event ) {
774                 var _this = this;
775                 event.preventDefault();
776
777                 wp.updates.maybeRequestFilesystemCredentials( event );
778
779                 $( document ).on( 'wp-theme-update-success', function( event, response ) {
780                         if ( _this.model.get( 'id' ) === response.slug ) {
781                                 _this.model.set( {
782                                         hasUpdate: false,
783                                         version: response.newVersion
784                                 } );
785                         }
786                         _this.render();
787                 } );
788
789                 wp.updates.updateTheme( {
790                         slug: $( event.target ).data( 'slug' )
791                 } );
792         },
793
794         deleteTheme: function( event ) {
795                 var _this = this,
796                     _collection = _this.model.collection,
797                     _themes = themes;
798                 event.preventDefault();
799
800                 // Confirmation dialog for deleting a theme.
801                 if ( ! window.confirm( wp.themes.data.settings.confirmDelete ) ) {
802                         return;
803                 }
804
805                 wp.updates.maybeRequestFilesystemCredentials( event );
806
807                 $( document ).one( 'wp-theme-delete-success', function( event, response ) {
808                         _this.$el.find( '.close' ).trigger( 'click' );
809                         $( '[data-slug="' + response.slug + '"]' ).css( { backgroundColor:'#faafaa' } ).fadeOut( 350, function() {
810                                 $( this ).remove();
811                                 _themes.data.themes = _.without( _themes.data.themes, _.findWhere( _themes.data.themes, { id: response.slug } ) );
812
813                                 $( '.wp-filter-search' ).val( '' );
814                                 _collection.doSearch( '' );
815                                 _collection.remove( _this.model );
816                                 _collection.trigger( 'themes:update' );
817                         } );
818                 } );
819
820                 wp.updates.deleteTheme( {
821                         slug: this.model.get( 'id' )
822                 } );
823         },
824
825         nextTheme: function() {
826                 var self = this;
827                 self.trigger( 'theme:next', self.model.cid );
828                 return false;
829         },
830
831         previousTheme: function() {
832                 var self = this;
833                 self.trigger( 'theme:previous', self.model.cid );
834                 return false;
835         },
836
837         // Checks if the theme screenshot is the old 300px width version
838         // and adds a corresponding class if it's true
839         screenshotCheck: function( el ) {
840                 var screenshot, image;
841
842                 screenshot = el.find( '.screenshot img' );
843                 image = new Image();
844                 image.src = screenshot.attr( 'src' );
845
846                 // Width check
847                 if ( image.width && image.width <= 300 ) {
848                         el.addClass( 'small-screenshot' );
849                 }
850         }
851 });
852
853 // Theme Preview view
854 // Set ups a modal overlay with the expanded theme data
855 themes.view.Preview = themes.view.Details.extend({
856
857         className: 'wp-full-overlay expanded',
858         el: '.theme-install-overlay',
859
860         events: {
861                 'click .close-full-overlay': 'close',
862                 'click .collapse-sidebar': 'collapse',
863                 'click .devices button': 'previewDevice',
864                 'click .previous-theme': 'previousTheme',
865                 'click .next-theme': 'nextTheme',
866                 'keyup': 'keyEvent',
867                 'click .theme-install': 'installTheme'
868         },
869
870         // The HTML template for the theme preview
871         html: themes.template( 'theme-preview' ),
872
873         render: function() {
874                 var self = this,
875                         currentPreviewDevice,
876                         data = this.model.toJSON(),
877                         $body = $( document.body );
878
879                 $body.attr( 'aria-busy', 'true' );
880
881                 this.$el.removeClass( 'iframe-ready' ).html( this.html( data ) );
882
883                 currentPreviewDevice = this.$el.data( 'current-preview-device' );
884                 if ( currentPreviewDevice ) {
885                         self.tooglePreviewDeviceButtons( currentPreviewDevice );
886                 }
887
888                 themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.get( 'id' ) ), { replace: true } );
889
890                 this.$el.fadeIn( 200, function() {
891                         $body.addClass( 'theme-installer-active full-overlay-active' );
892                 });
893
894                 this.$el.find( 'iframe' ).one( 'load', function() {
895                         self.iframeLoaded();
896                 });
897         },
898
899         iframeLoaded: function() {
900                 this.$el.addClass( 'iframe-ready' );
901                 $( document.body ).attr( 'aria-busy', 'false' );
902         },
903
904         close: function() {
905                 this.$el.fadeOut( 200, function() {
906                         $( 'body' ).removeClass( 'theme-installer-active full-overlay-active' );
907
908                         // Return focus to the theme div
909                         if ( themes.focusedTheme ) {
910                                 themes.focusedTheme.focus();
911                         }
912                 }).removeClass( 'iframe-ready' );
913
914                 themes.router.navigate( themes.router.baseUrl( '' ) );
915                 this.trigger( 'preview:close' );
916                 this.undelegateEvents();
917                 this.unbind();
918                 return false;
919         },
920
921         collapse: function( event ) {
922                 var $button = $( event.currentTarget );
923                 if ( 'true' === $button.attr( 'aria-expanded' ) ) {
924                         $button.attr({ 'aria-expanded': 'false', 'aria-label': l10n.expandSidebar });
925                 } else {
926                         $button.attr({ 'aria-expanded': 'true', 'aria-label': l10n.collapseSidebar });
927                 }
928
929                 this.$el.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
930                 return false;
931         },
932
933         previewDevice: function( event ) {
934                 var device = $( event.currentTarget ).data( 'device' );
935
936                 this.$el
937                         .removeClass( 'preview-desktop preview-tablet preview-mobile' )
938                         .addClass( 'preview-' + device )
939                         .data( 'current-preview-device', device );
940
941                 this.tooglePreviewDeviceButtons( device );
942         },
943
944         tooglePreviewDeviceButtons: function( newDevice ) {
945                 var $devices = $( '.wp-full-overlay-footer .devices' );
946
947                 $devices.find( 'button' )
948                         .removeClass( 'active' )
949                         .attr( 'aria-pressed', false );
950
951                 $devices.find( 'button.preview-' + newDevice )
952                         .addClass( 'active' )
953                         .attr( 'aria-pressed', true );
954         },
955
956         keyEvent: function( event ) {
957                 // The escape key closes the preview
958                 if ( event.keyCode === 27 ) {
959                         this.undelegateEvents();
960                         this.close();
961                 }
962                 // The right arrow key, next theme
963                 if ( event.keyCode === 39 ) {
964                         _.once( this.nextTheme() );
965                 }
966
967                 // The left arrow key, previous theme
968                 if ( event.keyCode === 37 ) {
969                         this.previousTheme();
970                 }
971         },
972
973         installTheme: function( event ) {
974                 var _this   = this,
975                     $target = $( event.target );
976                 event.preventDefault();
977
978                 if ( $target.hasClass( 'disabled' ) ) {
979                         return;
980                 }
981
982                 wp.updates.maybeRequestFilesystemCredentials( event );
983
984                 $( document ).on( 'wp-theme-install-success', function() {
985                         _this.model.set( { 'installed': true } );
986                 } );
987
988                 wp.updates.installTheme( {
989                         slug: $target.data( 'slug' )
990                 } );
991         }
992 });
993
994 // Controls the rendering of div.themes,
995 // a wrapper that will hold all the theme elements
996 themes.view.Themes = wp.Backbone.View.extend({
997
998         className: 'themes wp-clearfix',
999         $overlay: $( 'div.theme-overlay' ),
1000
1001         // Number to keep track of scroll position
1002         // while in theme-overlay mode
1003         index: 0,
1004
1005         // The theme count element
1006         count: $( '.wrap .theme-count' ),
1007
1008         // The live themes count
1009         liveThemeCount: 0,
1010
1011         initialize: function( options ) {
1012                 var self = this;
1013
1014                 // Set up parent
1015                 this.parent = options.parent;
1016
1017                 // Set current view to [grid]
1018                 this.setView( 'grid' );
1019
1020                 // Move the active theme to the beginning of the collection
1021                 self.currentTheme();
1022
1023                 // When the collection is updated by user input...
1024                 this.listenTo( self.collection, 'themes:update', function() {
1025                         self.parent.page = 0;
1026                         self.currentTheme();
1027                         self.render( this );
1028                 } );
1029
1030                 // Update theme count to full result set when available.
1031                 this.listenTo( self.collection, 'query:success', function( count ) {
1032                         if ( _.isNumber( count ) ) {
1033                                 self.count.text( count );
1034                                 self.announceSearchResults( count );
1035                         } else {
1036                                 self.count.text( self.collection.length );
1037                                 self.announceSearchResults( self.collection.length );
1038                         }
1039                 });
1040
1041                 this.listenTo( self.collection, 'query:empty', function() {
1042                         $( 'body' ).addClass( 'no-results' );
1043                 });
1044
1045                 this.listenTo( this.parent, 'theme:scroll', function() {
1046                         self.renderThemes( self.parent.page );
1047                 });
1048
1049                 this.listenTo( this.parent, 'theme:close', function() {
1050                         if ( self.overlay ) {
1051                                 self.overlay.closeOverlay();
1052                         }
1053                 } );
1054
1055                 // Bind keyboard events.
1056                 $( 'body' ).on( 'keyup', function( event ) {
1057                         if ( ! self.overlay ) {
1058                                 return;
1059                         }
1060
1061                         // Bail if the filesystem credentials dialog is shown.
1062                         if ( $( '#request-filesystem-credentials-dialog' ).is( ':visible' ) ) {
1063                                 return;
1064                         }
1065
1066                         // Pressing the right arrow key fires a theme:next event
1067                         if ( event.keyCode === 39 ) {
1068                                 self.overlay.nextTheme();
1069                         }
1070
1071                         // Pressing the left arrow key fires a theme:previous event
1072                         if ( event.keyCode === 37 ) {
1073                                 self.overlay.previousTheme();
1074                         }
1075
1076                         // Pressing the escape key fires a theme:collapse event
1077                         if ( event.keyCode === 27 ) {
1078                                 self.overlay.collapse( event );
1079                         }
1080                 });
1081         },
1082
1083         // Manages rendering of theme pages
1084         // and keeping theme count in sync
1085         render: function() {
1086                 // Clear the DOM, please
1087                 this.$el.empty();
1088
1089                 // If the user doesn't have switch capabilities
1090                 // or there is only one theme in the collection
1091                 // render the detailed view of the active theme
1092                 if ( themes.data.themes.length === 1 ) {
1093
1094                         // Constructs the view
1095                         this.singleTheme = new themes.view.Details({
1096                                 model: this.collection.models[0]
1097                         });
1098
1099                         // Render and apply a 'single-theme' class to our container
1100                         this.singleTheme.render();
1101                         this.$el.addClass( 'single-theme' );
1102                         this.$el.append( this.singleTheme.el );
1103                 }
1104
1105                 // Generate the themes
1106                 // Using page instance
1107                 // While checking the collection has items
1108                 if ( this.options.collection.size() > 0 ) {
1109                         this.renderThemes( this.parent.page );
1110                 }
1111
1112                 // Display a live theme count for the collection
1113                 this.liveThemeCount = this.collection.count ? this.collection.count : this.collection.length;
1114                 this.count.text( this.liveThemeCount );
1115
1116                 /*
1117                  * In the theme installer the themes count is already announced
1118                  * because `announceSearchResults` is called on `query:success`.
1119                  */
1120                 if ( ! themes.isInstall ) {
1121                         this.announceSearchResults( this.liveThemeCount );
1122                 }
1123         },
1124
1125         // Iterates through each instance of the collection
1126         // and renders each theme module
1127         renderThemes: function( page ) {
1128                 var self = this;
1129
1130                 self.instance = self.collection.paginate( page );
1131
1132                 // If we have no more themes bail
1133                 if ( self.instance.size() === 0 ) {
1134                         // Fire a no-more-themes event.
1135                         this.parent.trigger( 'theme:end' );
1136                         return;
1137                 }
1138
1139                 // Make sure the add-new stays at the end
1140                 if ( ! themes.isInstall && page >= 1 ) {
1141                         $( '.add-new-theme' ).remove();
1142                 }
1143
1144                 // Loop through the themes and setup each theme view
1145                 self.instance.each( function( theme ) {
1146                         self.theme = new themes.view.Theme({
1147                                 model: theme,
1148                                 parent: self
1149                         });
1150
1151                         // Render the views...
1152                         self.theme.render();
1153                         // and append them to div.themes
1154                         self.$el.append( self.theme.el );
1155
1156                         // Binds to theme:expand to show the modal box
1157                         // with the theme details
1158                         self.listenTo( self.theme, 'theme:expand', self.expand, self );
1159                 });
1160
1161                 // 'Add new theme' element shown at the end of the grid
1162                 if ( ! themes.isInstall && themes.data.settings.canInstall ) {
1163                         this.$el.append( '<div class="theme add-new-theme"><a href="' + themes.data.settings.installURI + '"><div class="theme-screenshot"><span></span></div><h2 class="theme-name">' + l10n.addNew + '</h2></a></div>' );
1164                 }
1165
1166                 this.parent.page++;
1167         },
1168
1169         // Grabs current theme and puts it at the beginning of the collection
1170         currentTheme: function() {
1171                 var self = this,
1172                         current;
1173
1174                 current = self.collection.findWhere({ active: true });
1175
1176                 // Move the active theme to the beginning of the collection
1177                 if ( current ) {
1178                         self.collection.remove( current );
1179                         self.collection.add( current, { at:0 } );
1180                 }
1181         },
1182
1183         // Sets current view
1184         setView: function( view ) {
1185                 return view;
1186         },
1187
1188         // Renders the overlay with the ThemeDetails view
1189         // Uses the current model data
1190         expand: function( id ) {
1191                 var self = this, $card, $modal;
1192
1193                 // Set the current theme model
1194                 this.model = self.collection.get( id );
1195
1196                 // Trigger a route update for the current model
1197                 themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.id ) );
1198
1199                 // Sets this.view to 'detail'
1200                 this.setView( 'detail' );
1201                 $( 'body' ).addClass( 'modal-open' );
1202
1203                 // Set up the theme details view
1204                 this.overlay = new themes.view.Details({
1205                         model: self.model
1206                 });
1207
1208                 this.overlay.render();
1209
1210                 if ( this.model.get( 'hasUpdate' ) ) {
1211                         $card  = $( '[data-slug="' + this.model.id + '"]' );
1212                         $modal = $( this.overlay.el );
1213
1214                         if ( $card.find( '.updating-message' ).length ) {
1215                                 $modal.find( '.notice-warning h3' ).remove();
1216                                 $modal.find( '.notice-warning' )
1217                                         .removeClass( 'notice-large' )
1218                                         .addClass( 'updating-message' )
1219                                         .find( 'p' ).text( wp.updates.l10n.updating );
1220                         } else if ( $card.find( '.notice-error' ).length ) {
1221                                 $modal.find( '.notice-warning' ).remove();
1222                         }
1223                 }
1224
1225                 this.$overlay.html( this.overlay.el );
1226
1227                 // Bind to theme:next and theme:previous
1228                 // triggered by the arrow keys
1229                 //
1230                 // Keep track of the current model so we
1231                 // can infer an index position
1232                 this.listenTo( this.overlay, 'theme:next', function() {
1233                         // Renders the next theme on the overlay
1234                         self.next( [ self.model.cid ] );
1235
1236                 })
1237                 .listenTo( this.overlay, 'theme:previous', function() {
1238                         // Renders the previous theme on the overlay
1239                         self.previous( [ self.model.cid ] );
1240                 });
1241         },
1242
1243         // This method renders the next theme on the overlay modal
1244         // based on the current position in the collection
1245         // @params [model cid]
1246         next: function( args ) {
1247                 var self = this,
1248                         model, nextModel;
1249
1250                 // Get the current theme
1251                 model = self.collection.get( args[0] );
1252                 // Find the next model within the collection
1253                 nextModel = self.collection.at( self.collection.indexOf( model ) + 1 );
1254
1255                 // Sanity check which also serves as a boundary test
1256                 if ( nextModel !== undefined ) {
1257
1258                         // We have a new theme...
1259                         // Close the overlay
1260                         this.overlay.closeOverlay();
1261
1262                         // Trigger a route update for the current model
1263                         self.theme.trigger( 'theme:expand', nextModel.cid );
1264
1265                 }
1266         },
1267
1268         // This method renders the previous theme on the overlay modal
1269         // based on the current position in the collection
1270         // @params [model cid]
1271         previous: function( args ) {
1272                 var self = this,
1273                         model, previousModel;
1274
1275                 // Get the current theme
1276                 model = self.collection.get( args[0] );
1277                 // Find the previous model within the collection
1278                 previousModel = self.collection.at( self.collection.indexOf( model ) - 1 );
1279
1280                 if ( previousModel !== undefined ) {
1281
1282                         // We have a new theme...
1283                         // Close the overlay
1284                         this.overlay.closeOverlay();
1285
1286                         // Trigger a route update for the current model
1287                         self.theme.trigger( 'theme:expand', previousModel.cid );
1288
1289                 }
1290         },
1291
1292         // Dispatch audible search results feedback message
1293         announceSearchResults: function( count ) {
1294                 if ( 0 === count ) {
1295                         wp.a11y.speak( l10n.noThemesFound );
1296                 } else {
1297                         wp.a11y.speak( l10n.themesFound.replace( '%d', count ) );
1298                 }
1299         }
1300 });
1301
1302 // Search input view controller.
1303 themes.view.Search = wp.Backbone.View.extend({
1304
1305         tagName: 'input',
1306         className: 'wp-filter-search',
1307         id: 'wp-filter-search-input',
1308         searching: false,
1309
1310         attributes: {
1311                 placeholder: l10n.searchPlaceholder,
1312                 type: 'search',
1313                 'aria-describedby': 'live-search-desc'
1314         },
1315
1316         events: {
1317                 'input': 'search',
1318                 'keyup': 'search',
1319                 'blur': 'pushState'
1320         },
1321
1322         initialize: function( options ) {
1323
1324                 this.parent = options.parent;
1325
1326                 this.listenTo( this.parent, 'theme:close', function() {
1327                         this.searching = false;
1328                 } );
1329
1330         },
1331
1332         search: function( event ) {
1333                 // Clear on escape.
1334                 if ( event.type === 'keyup' && event.which === 27 ) {
1335                         event.target.value = '';
1336                 }
1337
1338                 /**
1339                  * Since doSearch is debounced, it will only run when user input comes to a rest
1340                  */
1341                 this.doSearch( event );
1342         },
1343
1344         // Runs a search on the theme collection.
1345         doSearch: _.debounce( function( event ) {
1346                 var options = {};
1347
1348                 this.collection.doSearch( event.target.value );
1349
1350                 // if search is initiated and key is not return
1351                 if ( this.searching && event.which !== 13 ) {
1352                         options.replace = true;
1353                 } else {
1354                         this.searching = true;
1355                 }
1356
1357                 // Update the URL hash
1358                 if ( event.target.value ) {
1359                         themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + event.target.value ), options );
1360                 } else {
1361                         themes.router.navigate( themes.router.baseUrl( '' ) );
1362                 }
1363         }, 500 ),
1364
1365         pushState: function( event ) {
1366                 var url = themes.router.baseUrl( '' );
1367
1368                 if ( event.target.value ) {
1369                         url = themes.router.baseUrl( themes.router.searchPath + event.target.value );
1370                 }
1371
1372                 this.searching = false;
1373                 themes.router.navigate( url );
1374
1375         }
1376 });
1377
1378 // Sets up the routes events for relevant url queries
1379 // Listens to [theme] and [search] params
1380 themes.Router = Backbone.Router.extend({
1381
1382         routes: {
1383                 'themes.php?theme=:slug': 'theme',
1384                 'themes.php?search=:query': 'search',
1385                 'themes.php?s=:query': 'search',
1386                 'themes.php': 'themes',
1387                 '': 'themes'
1388         },
1389
1390         baseUrl: function( url ) {
1391                 return 'themes.php' + url;
1392         },
1393
1394         themePath: '?theme=',
1395         searchPath: '?search=',
1396
1397         search: function( query ) {
1398                 $( '.wp-filter-search' ).val( query );
1399         },
1400
1401         themes: function() {
1402                 $( '.wp-filter-search' ).val( '' );
1403         },
1404
1405         navigate: function() {
1406                 if ( Backbone.history._hasPushState ) {
1407                         Backbone.Router.prototype.navigate.apply( this, arguments );
1408                 }
1409         }
1410
1411 });
1412
1413 // Execute and setup the application
1414 themes.Run = {
1415         init: function() {
1416                 // Initializes the blog's theme library view
1417                 // Create a new collection with data
1418                 this.themes = new themes.Collection( themes.data.themes );
1419
1420                 // Set up the view
1421                 this.view = new themes.view.Appearance({
1422                         collection: this.themes
1423                 });
1424
1425                 this.render();
1426         },
1427
1428         render: function() {
1429
1430                 // Render results
1431                 this.view.render();
1432                 this.routes();
1433
1434                 Backbone.history.start({
1435                         root: themes.data.settings.adminUrl,
1436                         pushState: true,
1437                         hashChange: false
1438                 });
1439         },
1440
1441         routes: function() {
1442                 var self = this;
1443                 // Bind to our global thx object
1444                 // so that the object is available to sub-views
1445                 themes.router = new themes.Router();
1446
1447                 // Handles theme details route event
1448                 themes.router.on( 'route:theme', function( slug ) {
1449                         self.view.view.expand( slug );
1450                 });
1451
1452                 themes.router.on( 'route:themes', function() {
1453                         self.themes.doSearch( '' );
1454                         self.view.trigger( 'theme:close' );
1455                 });
1456
1457                 // Handles search route event
1458                 themes.router.on( 'route:search', function() {
1459                         $( '.wp-filter-search' ).trigger( 'keyup' );
1460                 });
1461
1462                 this.extraRoutes();
1463         },
1464
1465         extraRoutes: function() {
1466                 return false;
1467         }
1468 };
1469
1470 // Extend the main Search view
1471 themes.view.InstallerSearch =  themes.view.Search.extend({
1472
1473         events: {
1474                 'input': 'search',
1475                 'keyup': 'search'
1476         },
1477
1478         terms: '',
1479
1480         // Handles Ajax request for searching through themes in public repo
1481         search: function( event ) {
1482
1483                 // Tabbing or reverse tabbing into the search input shouldn't trigger a search
1484                 if ( event.type === 'keyup' && ( event.which === 9 || event.which === 16 ) ) {
1485                         return;
1486                 }
1487
1488                 this.collection = this.options.parent.view.collection;
1489
1490                 // Clear on escape.
1491                 if ( event.type === 'keyup' && event.which === 27 ) {
1492                         event.target.value = '';
1493                 }
1494
1495                 this.doSearch( event.target.value );
1496         },
1497
1498         doSearch: _.debounce( function( value ) {
1499                 var request = {};
1500
1501                 // Don't do anything if the search terms haven't changed.
1502                 if ( this.terms === value ) {
1503                         return;
1504                 }
1505
1506                 // Updates terms with the value passed.
1507                 this.terms = value;
1508
1509                 request.search = value;
1510
1511                 // Intercept an [author] search.
1512                 //
1513                 // If input value starts with `author:` send a request
1514                 // for `author` instead of a regular `search`
1515                 if ( value.substring( 0, 7 ) === 'author:' ) {
1516                         request.search = '';
1517                         request.author = value.slice( 7 );
1518                 }
1519
1520                 // Intercept a [tag] search.
1521                 //
1522                 // If input value starts with `tag:` send a request
1523                 // for `tag` instead of a regular `search`
1524                 if ( value.substring( 0, 4 ) === 'tag:' ) {
1525                         request.search = '';
1526                         request.tag = [ value.slice( 4 ) ];
1527                 }
1528
1529                 $( '.filter-links li > a.current' ).removeClass( 'current' );
1530                 $( 'body' ).removeClass( 'show-filters filters-applied show-favorites-form' );
1531                 $( '.drawer-toggle' ).attr( 'aria-expanded', 'false' );
1532
1533                 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1534                 // or searching the local cache
1535                 this.collection.query( request );
1536
1537                 // Set route
1538                 themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + value ), { replace: true } );
1539         }, 500 )
1540 });
1541
1542 themes.view.Installer = themes.view.Appearance.extend({
1543
1544         el: '#wpbody-content .wrap',
1545
1546         // Register events for sorting and filters in theme-navigation
1547         events: {
1548                 'click .filter-links li > a': 'onSort',
1549                 'click .theme-filter': 'onFilter',
1550                 'click .drawer-toggle': 'moreFilters',
1551                 'click .filter-drawer .apply-filters': 'applyFilters',
1552                 'click .filter-group [type="checkbox"]': 'addFilter',
1553                 'click .filter-drawer .clear-filters': 'clearFilters',
1554                 'click .edit-filters': 'backToFilters',
1555                 'click .favorites-form-submit' : 'saveUsername',
1556                 'keyup #wporg-username-input': 'saveUsername'
1557         },
1558
1559         // Initial render method
1560         render: function() {
1561                 var self = this;
1562
1563                 this.search();
1564                 this.uploader();
1565
1566                 this.collection = new themes.Collection();
1567
1568                 // Bump `collection.currentQuery.page` and request more themes if we hit the end of the page.
1569                 this.listenTo( this, 'theme:end', function() {
1570
1571                         // Make sure we are not already loading
1572                         if ( self.collection.loadingThemes ) {
1573                                 return;
1574                         }
1575
1576                         // Set loadingThemes to true and bump page instance of currentQuery.
1577                         self.collection.loadingThemes = true;
1578                         self.collection.currentQuery.page++;
1579
1580                         // Use currentQuery.page to build the themes request.
1581                         _.extend( self.collection.currentQuery.request, { page: self.collection.currentQuery.page } );
1582                         self.collection.query( self.collection.currentQuery.request );
1583                 });
1584
1585                 this.listenTo( this.collection, 'query:success', function() {
1586                         $( 'body' ).removeClass( 'loading-content' );
1587                         $( '.theme-browser' ).find( 'div.error' ).remove();
1588                 });
1589
1590                 this.listenTo( this.collection, 'query:fail', function() {
1591                         $( 'body' ).removeClass( 'loading-content' );
1592                         $( '.theme-browser' ).find( 'div.error' ).remove();
1593                         $( '.theme-browser' ).find( 'div.themes' ).before( '<div class="error"><p>' + l10n.error + '</p></div>' );
1594                 });
1595
1596                 if ( this.view ) {
1597                         this.view.remove();
1598                 }
1599
1600                 // Set ups the view and passes the section argument
1601                 this.view = new themes.view.Themes({
1602                         collection: this.collection,
1603                         parent: this
1604                 });
1605
1606                 // Reset pagination every time the install view handler is run
1607                 this.page = 0;
1608
1609                 // Render and append
1610                 this.$el.find( '.themes' ).remove();
1611                 this.view.render();
1612                 this.$el.find( '.theme-browser' ).append( this.view.el ).addClass( 'rendered' );
1613         },
1614
1615         // Handles all the rendering of the public theme directory
1616         browse: function( section ) {
1617                 // Create a new collection with the proper theme data
1618                 // for each section
1619                 this.collection.query( { browse: section } );
1620         },
1621
1622         // Sorting navigation
1623         onSort: function( event ) {
1624                 var $el = $( event.target ),
1625                         sort = $el.data( 'sort' );
1626
1627                 event.preventDefault();
1628
1629                 $( 'body' ).removeClass( 'filters-applied show-filters' );
1630                 $( '.drawer-toggle' ).attr( 'aria-expanded', 'false' );
1631
1632                 // Bail if this is already active
1633                 if ( $el.hasClass( this.activeClass ) ) {
1634                         return;
1635                 }
1636
1637                 this.sort( sort );
1638
1639                 // Trigger a router.naviagte update
1640                 themes.router.navigate( themes.router.baseUrl( themes.router.browsePath + sort ) );
1641         },
1642
1643         sort: function( sort ) {
1644                 this.clearSearch();
1645
1646                 $( '.filter-links li > a, .theme-filter' ).removeClass( this.activeClass );
1647                 $( '[data-sort="' + sort + '"]' ).addClass( this.activeClass );
1648
1649                 if ( 'favorites' === sort ) {
1650                         $( 'body' ).addClass( 'show-favorites-form' );
1651                 } else {
1652                         $( 'body' ).removeClass( 'show-favorites-form' );
1653                 }
1654
1655                 this.browse( sort );
1656         },
1657
1658         // Filters and Tags
1659         onFilter: function( event ) {
1660                 var request,
1661                         $el = $( event.target ),
1662                         filter = $el.data( 'filter' );
1663
1664                 // Bail if this is already active
1665                 if ( $el.hasClass( this.activeClass ) ) {
1666                         return;
1667                 }
1668
1669                 $( '.filter-links li > a, .theme-section' ).removeClass( this.activeClass );
1670                 $el.addClass( this.activeClass );
1671
1672                 if ( ! filter ) {
1673                         return;
1674                 }
1675
1676                 // Construct the filter request
1677                 // using the default values
1678                 filter = _.union( [ filter, this.filtersChecked() ] );
1679                 request = { tag: [ filter ] };
1680
1681                 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1682                 // or searching the local cache
1683                 this.collection.query( request );
1684         },
1685
1686         // Clicking on a checkbox to add another filter to the request
1687         addFilter: function() {
1688                 this.filtersChecked();
1689         },
1690
1691         // Applying filters triggers a tag request
1692         applyFilters: function( event ) {
1693                 var name,
1694                         tags = this.filtersChecked(),
1695                         request = { tag: tags },
1696                         filteringBy = $( '.filtered-by .tags' );
1697
1698                 if ( event ) {
1699                         event.preventDefault();
1700                 }
1701
1702                 if ( ! tags ) {
1703                         wp.a11y.speak( l10n.selectFeatureFilter );
1704                         return;
1705                 }
1706
1707                 $( 'body' ).addClass( 'filters-applied' );
1708                 $( '.filter-links li > a.current' ).removeClass( 'current' );
1709                 filteringBy.empty();
1710
1711                 _.each( tags, function( tag ) {
1712                         name = $( 'label[for="filter-id-' + tag + '"]' ).text();
1713                         filteringBy.append( '<span class="tag">' + name + '</span>' );
1714                 });
1715
1716                 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1717                 // or searching the local cache
1718                 this.collection.query( request );
1719         },
1720
1721         // Save the user's WordPress.org username and get his favorite themes.
1722         saveUsername: function ( event ) {
1723                 var username = $( '#wporg-username-input' ).val(),
1724                         nonce = $( '#wporg-username-nonce' ).val(),
1725                         request = { browse: 'favorites', user: username },
1726                         that = this;
1727
1728                 if ( event ) {
1729                         event.preventDefault();
1730                 }
1731
1732                 // save username on enter
1733                 if ( event.type === 'keyup' && event.which !== 13 ) {
1734                         return;
1735                 }
1736
1737                 return wp.ajax.send( 'save-wporg-username', {
1738                         data: {
1739                                 _wpnonce: nonce,
1740                                 username: username
1741                         },
1742                         success: function () {
1743                                 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1744                                 // or searching the local cache
1745                                 that.collection.query( request );
1746                         }
1747                 } );
1748         },
1749
1750         // Get the checked filters
1751         // @return {array} of tags or false
1752         filtersChecked: function() {
1753                 var items = $( '.filter-group' ).find( ':checkbox' ),
1754                         tags = [];
1755
1756                 _.each( items.filter( ':checked' ), function( item ) {
1757                         tags.push( $( item ).prop( 'value' ) );
1758                 });
1759
1760                 // When no filters are checked, restore initial state and return
1761                 if ( tags.length === 0 ) {
1762                         $( '.filter-drawer .apply-filters' ).find( 'span' ).text( '' );
1763                         $( '.filter-drawer .clear-filters' ).hide();
1764                         $( 'body' ).removeClass( 'filters-applied' );
1765                         return false;
1766                 }
1767
1768                 $( '.filter-drawer .apply-filters' ).find( 'span' ).text( tags.length );
1769                 $( '.filter-drawer .clear-filters' ).css( 'display', 'inline-block' );
1770
1771                 return tags;
1772         },
1773
1774         activeClass: 'current',
1775
1776         // Overwrite search container class to append search
1777         // in new location
1778         searchContainer: $( '.wp-filter .search-form' ),
1779
1780         /*
1781          * When users press the "Upload Theme" button, show the upload form in place.
1782          */
1783         uploader: function() {
1784                 var uploadViewToggle = $( '.upload-view-toggle' ),
1785                         $body = $( document.body );
1786
1787                 uploadViewToggle.on( 'click', function() {
1788                         // Toggle the upload view.
1789                         $body.toggleClass( 'show-upload-view' );
1790                         // Toggle the `aria-expanded` button attribute.
1791                         uploadViewToggle.attr( 'aria-expanded', $body.hasClass( 'show-upload-view' ) );
1792                 });
1793         },
1794
1795         // Toggle the full filters navigation
1796         moreFilters: function( event ) {
1797                 var $body = $( 'body' ),
1798                         $toggleButton = $( '.drawer-toggle' );
1799
1800                 event.preventDefault();
1801
1802                 if ( $body.hasClass( 'filters-applied' ) ) {
1803                         return this.backToFilters();
1804                 }
1805
1806                 this.clearSearch();
1807
1808                 themes.router.navigate( themes.router.baseUrl( '' ) );
1809                 // Toggle the feature filters view.
1810                 $body.toggleClass( 'show-filters' );
1811                 // Toggle the `aria-expanded` button attribute.
1812                 $toggleButton.attr( 'aria-expanded', $body.hasClass( 'show-filters' ) );
1813         },
1814
1815         // Clears all the checked filters
1816         // @uses filtersChecked()
1817         clearFilters: function( event ) {
1818                 var items = $( '.filter-group' ).find( ':checkbox' ),
1819                         self = this;
1820
1821                 event.preventDefault();
1822
1823                 _.each( items.filter( ':checked' ), function( item ) {
1824                         $( item ).prop( 'checked', false );
1825                         return self.filtersChecked();
1826                 });
1827         },
1828
1829         backToFilters: function( event ) {
1830                 if ( event ) {
1831                         event.preventDefault();
1832                 }
1833
1834                 $( 'body' ).removeClass( 'filters-applied' );
1835         },
1836
1837         clearSearch: function() {
1838                 $( '#wp-filter-search-input').val( '' );
1839         }
1840 });
1841
1842 themes.InstallerRouter = Backbone.Router.extend({
1843         routes: {
1844                 'theme-install.php?theme=:slug': 'preview',
1845                 'theme-install.php?browse=:sort': 'sort',
1846                 'theme-install.php?search=:query': 'search',
1847                 'theme-install.php': 'sort'
1848         },
1849
1850         baseUrl: function( url ) {
1851                 return 'theme-install.php' + url;
1852         },
1853
1854         themePath: '?theme=',
1855         browsePath: '?browse=',
1856         searchPath: '?search=',
1857
1858         search: function( query ) {
1859                 $( '.wp-filter-search' ).val( query );
1860         },
1861
1862         navigate: function() {
1863                 if ( Backbone.history._hasPushState ) {
1864                         Backbone.Router.prototype.navigate.apply( this, arguments );
1865                 }
1866         }
1867 });
1868
1869
1870 themes.RunInstaller = {
1871
1872         init: function() {
1873                 // Set up the view
1874                 // Passes the default 'section' as an option
1875                 this.view = new themes.view.Installer({
1876                         section: 'featured',
1877                         SearchView: themes.view.InstallerSearch
1878                 });
1879
1880                 // Render results
1881                 this.render();
1882
1883         },
1884
1885         render: function() {
1886
1887                 // Render results
1888                 this.view.render();
1889                 this.routes();
1890
1891                 Backbone.history.start({
1892                         root: themes.data.settings.adminUrl,
1893                         pushState: true,
1894                         hashChange: false
1895                 });
1896         },
1897
1898         routes: function() {
1899                 var self = this,
1900                         request = {};
1901
1902                 // Bind to our global `wp.themes` object
1903                 // so that the router is available to sub-views
1904                 themes.router = new themes.InstallerRouter();
1905
1906                 // Handles `theme` route event
1907                 // Queries the API for the passed theme slug
1908                 themes.router.on( 'route:preview', function( slug ) {
1909                         request.theme = slug;
1910                         self.view.collection.query( request );
1911                         self.view.collection.once( 'update', function() {
1912                                 self.view.view.theme.preview();
1913                         });
1914                 });
1915
1916                 // Handles sorting / browsing routes
1917                 // Also handles the root URL triggering a sort request
1918                 // for `featured`, the default view
1919                 themes.router.on( 'route:sort', function( sort ) {
1920                         if ( ! sort ) {
1921                                 sort = 'featured';
1922                         }
1923                         self.view.sort( sort );
1924                         self.view.trigger( 'theme:close' );
1925                 });
1926
1927                 // The `search` route event. The router populates the input field.
1928                 themes.router.on( 'route:search', function() {
1929                         $( '.wp-filter-search' ).focus().trigger( 'keyup' );
1930                 });
1931
1932                 this.extraRoutes();
1933         },
1934
1935         extraRoutes: function() {
1936                 return false;
1937         }
1938 };
1939
1940 // Ready...
1941 $( document ).ready(function() {
1942         if ( themes.isInstall ) {
1943                 themes.RunInstaller.init();
1944         } else {
1945                 themes.Run.init();
1946         }
1947
1948         $( '.broken-themes .delete-theme' ).on( 'click', function() {
1949                 return confirm( _wpThemeSettings.settings.confirmDelete );
1950         });
1951 });
1952
1953 })( jQuery );
1954
1955 // Align theme browser thickbox
1956 var tb_position;
1957 jQuery(document).ready( function($) {
1958         tb_position = function() {
1959                 var tbWindow = $('#TB_window'),
1960                         width = $(window).width(),
1961                         H = $(window).height(),
1962                         W = ( 1040 < width ) ? 1040 : width,
1963                         adminbar_height = 0;
1964
1965                 if ( $('#wpadminbar').length ) {
1966                         adminbar_height = parseInt( $('#wpadminbar').css('height'), 10 );
1967                 }
1968
1969                 if ( tbWindow.size() ) {
1970                         tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
1971                         $('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
1972                         tbWindow.css({'margin-left': '-' + parseInt( ( ( W - 50 ) / 2 ), 10 ) + 'px'});
1973                         if ( typeof document.body.style.maxWidth !== 'undefined' ) {
1974                                 tbWindow.css({'top': 20 + adminbar_height + 'px', 'margin-top': '0'});
1975                         }
1976                 }
1977         };
1978
1979         $(window).resize(function(){ tb_position(); });
1980 });