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