]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-admin/js/post.js
WordPress 4.6.1
[autoinstalls/wordpress.git] / wp-admin / js / post.js
1 /* global postL10n, ajaxurl, wpAjax, setPostThumbnailL10n, postboxes, pagenow, tinymce, alert, deleteUserSetting */
2 /* global theList:true, theExtraList:true, getUserSetting, setUserSetting, commentReply */
3
4 var commentsBox, WPSetThumbnailHTML, WPSetThumbnailID, WPRemoveThumbnail, wptitlehint, makeSlugeditClickable, editPermalink;
5 // Back-compat: prevent fatal errors
6 makeSlugeditClickable = editPermalink = function(){};
7
8 window.wp = window.wp || {};
9
10 ( function( $ ) {
11         var titleHasFocus = false;
12
13 commentsBox = {
14         st : 0,
15
16         get : function(total, num) {
17                 var st = this.st, data;
18                 if ( ! num )
19                         num = 20;
20
21                 this.st += num;
22                 this.total = total;
23                 $( '#commentsdiv .spinner' ).addClass( 'is-active' );
24
25                 data = {
26                         'action' : 'get-comments',
27                         'mode' : 'single',
28                         '_ajax_nonce' : $('#add_comment_nonce').val(),
29                         'p' : $('#post_ID').val(),
30                         'start' : st,
31                         'number' : num
32                 };
33
34                 $.post(ajaxurl, data,
35                         function(r) {
36                                 r = wpAjax.parseAjaxResponse(r);
37                                 $('#commentsdiv .widefat').show();
38                                 $( '#commentsdiv .spinner' ).removeClass( 'is-active' );
39
40                                 if ( 'object' == typeof r && r.responses[0] ) {
41                                         $('#the-comment-list').append( r.responses[0].data );
42
43                                         theList = theExtraList = null;
44                                         $( 'a[className*=\':\']' ).unbind();
45
46                                         if ( commentsBox.st > commentsBox.total )
47                                                 $('#show-comments').hide();
48                                         else
49                                                 $('#show-comments').show().children('a').html(postL10n.showcomm);
50
51                                         return;
52                                 } else if ( 1 == r ) {
53                                         $('#show-comments').html(postL10n.endcomm);
54                                         return;
55                                 }
56
57                                 $('#the-comment-list').append('<tr><td colspan="2">'+wpAjax.broken+'</td></tr>');
58                         }
59                 );
60
61                 return false;
62         },
63
64         load: function(total){
65                 this.st = jQuery('#the-comment-list tr.comment:visible').length;
66                 this.get(total);
67         }
68 };
69
70 WPSetThumbnailHTML = function(html){
71         $('.inside', '#postimagediv').html(html);
72 };
73
74 WPSetThumbnailID = function(id){
75         var field = $('input[value="_thumbnail_id"]', '#list-table');
76         if ( field.length > 0 ) {
77                 $('#meta\\[' + field.attr('id').match(/[0-9]+/) + '\\]\\[value\\]').text(id);
78         }
79 };
80
81 WPRemoveThumbnail = function(nonce){
82         $.post(ajaxurl, {
83                 action: 'set-post-thumbnail', post_id: $( '#post_ID' ).val(), thumbnail_id: -1, _ajax_nonce: nonce, cookie: encodeURIComponent( document.cookie )
84         }, function(str){
85                 if ( str == '0' ) {
86                         alert( setPostThumbnailL10n.error );
87                 } else {
88                         WPSetThumbnailHTML(str);
89                 }
90         }
91         );
92 };
93
94 $(document).on( 'heartbeat-send.refresh-lock', function( e, data ) {
95         var lock = $('#active_post_lock').val(),
96                 post_id = $('#post_ID').val(),
97                 send = {};
98
99         if ( ! post_id || ! $('#post-lock-dialog').length )
100                 return;
101
102         send.post_id = post_id;
103
104         if ( lock )
105                 send.lock = lock;
106
107         data['wp-refresh-post-lock'] = send;
108
109 }).on( 'heartbeat-tick.refresh-lock', function( e, data ) {
110         // Post locks: update the lock string or show the dialog if somebody has taken over editing
111         var received, wrap, avatar;
112
113         if ( data['wp-refresh-post-lock'] ) {
114                 received = data['wp-refresh-post-lock'];
115
116                 if ( received.lock_error ) {
117                         // show "editing taken over" message
118                         wrap = $('#post-lock-dialog');
119
120                         if ( wrap.length && ! wrap.is(':visible') ) {
121                                 if ( wp.autosave ) {
122                                         // Save the latest changes and disable
123                                         $(document).one( 'heartbeat-tick', function() {
124                                                 wp.autosave.server.suspend();
125                                                 wrap.removeClass('saving').addClass('saved');
126                                                 $(window).off( 'beforeunload.edit-post' );
127                                         });
128
129                                         wrap.addClass('saving');
130                                         wp.autosave.server.triggerSave();
131                                 }
132
133                                 if ( received.lock_error.avatar_src ) {
134                                         avatar = $( '<img class="avatar avatar-64 photo" width="64" height="64" alt="" />' ).attr( 'src', received.lock_error.avatar_src.replace( /&amp;/g, '&' ) );
135                                         wrap.find('div.post-locked-avatar').empty().append( avatar );
136                                 }
137
138                                 wrap.show().find('.currently-editing').text( received.lock_error.text );
139                                 wrap.find('.wp-tab-first').focus();
140                         }
141                 } else if ( received.new_lock ) {
142                         $('#active_post_lock').val( received.new_lock );
143                 }
144         }
145 }).on( 'before-autosave.update-post-slug', function() {
146         titleHasFocus = document.activeElement && document.activeElement.id === 'title';
147 }).on( 'after-autosave.update-post-slug', function() {
148         // Create slug area only if not already there
149         // and the title field was not focused (user was not typing a title) when autosave ran
150         if ( ! $('#edit-slug-box > *').length && ! titleHasFocus ) {
151                 $.post( ajaxurl, {
152                                 action: 'sample-permalink',
153                                 post_id: $('#post_ID').val(),
154                                 new_title: $('#title').val(),
155                                 samplepermalinknonce: $('#samplepermalinknonce').val()
156                         },
157                         function( data ) {
158                                 if ( data != '-1' ) {
159                                         $('#edit-slug-box').html(data);
160                                 }
161                         }
162                 );
163         }
164 });
165
166 }(jQuery));
167
168 (function($) {
169         var check, timeout;
170
171         function schedule() {
172                 check = false;
173                 window.clearTimeout( timeout );
174                 timeout = window.setTimeout( function(){ check = true; }, 300000 );
175         }
176
177         $(document).on( 'heartbeat-send.wp-refresh-nonces', function( e, data ) {
178                 var post_id,
179                         $authCheck = $('#wp-auth-check-wrap');
180
181                 if ( check || ( $authCheck.length && ! $authCheck.hasClass( 'hidden' ) ) ) {
182                         if ( ( post_id = $('#post_ID').val() ) && $('#_wpnonce').val() ) {
183                                 data['wp-refresh-post-nonces'] = {
184                                         post_id: post_id
185                                 };
186                         }
187                 }
188         }).on( 'heartbeat-tick.wp-refresh-nonces', function( e, data ) {
189                 var nonces = data['wp-refresh-post-nonces'];
190
191                 if ( nonces ) {
192                         schedule();
193
194                         if ( nonces.replace ) {
195                                 $.each( nonces.replace, function( selector, value ) {
196                                         $( '#' + selector ).val( value );
197                                 });
198                         }
199
200                         if ( nonces.heartbeatNonce )
201                                 window.heartbeatSettings.nonce = nonces.heartbeatNonce;
202                 }
203         }).ready( function() {
204                 schedule();
205         });
206 }(jQuery));
207
208 jQuery(document).ready( function($) {
209         var stamp, visibility, $submitButtons, updateVisibility, updateText,
210                 sticky = '',
211                 $textarea = $('#content'),
212                 $document = $(document),
213                 postId = $('#post_ID').val() || 0,
214                 $submitpost = $('#submitpost'),
215                 releaseLock = true,
216                 $postVisibilitySelect = $('#post-visibility-select'),
217                 $timestampdiv = $('#timestampdiv'),
218                 $postStatusSelect = $('#post-status-select'),
219                 isMac = window.navigator.platform ? window.navigator.platform.indexOf( 'Mac' ) !== -1 : false;
220
221         postboxes.add_postbox_toggles(pagenow);
222
223         // Clear the window name. Otherwise if this is a former preview window where the user navigated to edit another post,
224         // and the first post is still being edited, clicking Preview there will use this window to show the preview.
225         window.name = '';
226
227         // Post locks: contain focus inside the dialog. If the dialog is shown, focus the first item.
228         $('#post-lock-dialog .notification-dialog').on( 'keydown', function(e) {
229                 if ( e.which != 9 )
230                         return;
231
232                 var target = $(e.target);
233
234                 if ( target.hasClass('wp-tab-first') && e.shiftKey ) {
235                         $(this).find('.wp-tab-last').focus();
236                         e.preventDefault();
237                 } else if ( target.hasClass('wp-tab-last') && ! e.shiftKey ) {
238                         $(this).find('.wp-tab-first').focus();
239                         e.preventDefault();
240                 }
241         }).filter(':visible').find('.wp-tab-first').focus();
242
243         // Set the heartbeat interval to 15 sec. if post lock dialogs are enabled
244         if ( wp.heartbeat && $('#post-lock-dialog').length ) {
245                 wp.heartbeat.interval( 15 );
246         }
247
248         // The form is being submitted by the user
249         $submitButtons = $submitpost.find( ':submit, a.submitdelete, #post-preview' ).on( 'click.edit-post', function( event ) {
250                 var $button = $(this);
251
252                 if ( $button.hasClass('disabled') ) {
253                         event.preventDefault();
254                         return;
255                 }
256
257                 if ( $button.hasClass('submitdelete') || $button.is( '#post-preview' ) ) {
258                         return;
259                 }
260
261                 // The form submission can be blocked from JS or by using HTML 5.0 validation on some fields.
262                 // Run this only on an actual 'submit'.
263                 $('form#post').off( 'submit.edit-post' ).on( 'submit.edit-post', function( event ) {
264                         if ( event.isDefaultPrevented() ) {
265                                 return;
266                         }
267
268                         // Stop autosave
269                         if ( wp.autosave ) {
270                                 wp.autosave.server.suspend();
271                         }
272
273                         if ( typeof commentReply !== 'undefined' ) {
274                                 /*
275                                  * Warn the user they have an unsaved comment before submitting
276                                  * the post data for update.
277                                  */
278                                 if ( ! commentReply.discardCommentChanges() ) {
279                                         return false;
280                                 }
281
282                                 /*
283                                  * Close the comment edit/reply form if open to stop the form
284                                  * action from interfering with the post's form action.
285                                  */
286                                 commentReply.close();
287                         }
288
289                         releaseLock = false;
290                         $(window).off( 'beforeunload.edit-post' );
291
292                         $submitButtons.addClass( 'disabled' );
293
294                         if ( $button.attr('id') === 'publish' ) {
295                                 $submitpost.find( '#major-publishing-actions .spinner' ).addClass( 'is-active' );
296                         } else {
297                                 $submitpost.find( '#minor-publishing .spinner' ).addClass( 'is-active' );
298                         }
299                 });
300         });
301
302         // Submit the form saving a draft or an autosave, and show a preview in a new tab
303         $('#post-preview').on( 'click.post-preview', function( event ) {
304                 var $this = $(this),
305                         $form = $('form#post'),
306                         $previewField = $('input#wp-preview'),
307                         target = $this.attr('target') || 'wp-preview',
308                         ua = navigator.userAgent.toLowerCase();
309
310                 event.preventDefault();
311
312                 if ( $this.hasClass('disabled') ) {
313                         return;
314                 }
315
316                 if ( wp.autosave ) {
317                         wp.autosave.server.tempBlockSave();
318                 }
319
320                 $previewField.val('dopreview');
321                 $form.attr( 'target', target ).submit().attr( 'target', '' );
322
323                 // Workaround for WebKit bug preventing a form submitting twice to the same action.
324                 // https://bugs.webkit.org/show_bug.cgi?id=28633
325                 if ( ua.indexOf('safari') !== -1 && ua.indexOf('chrome') === -1 ) {
326                         $form.attr( 'action', function( index, value ) {
327                                 return value + '?t=' + ( new Date() ).getTime();
328                         });
329                 }
330
331                 $previewField.val('');
332         });
333
334         // This code is meant to allow tabbing from Title to Post content.
335         $('#title').on( 'keydown.editor-focus', function( event ) {
336                 var editor;
337
338                 if ( event.keyCode === 9 && ! event.ctrlKey && ! event.altKey && ! event.shiftKey ) {
339                         editor = typeof tinymce != 'undefined' && tinymce.get('content');
340
341                         if ( editor && ! editor.isHidden() ) {
342                                 editor.focus();
343                         } else if ( $textarea.length ) {
344                                 $textarea.focus();
345                         } else {
346                                 return;
347                         }
348
349                         event.preventDefault();
350                 }
351         });
352
353         // Autosave new posts after a title is typed
354         if ( $( '#auto_draft' ).val() ) {
355                 $( '#title' ).blur( function() {
356                         var cancel;
357
358                         if ( ! this.value || $('#edit-slug-box > *').length ) {
359                                 return;
360                         }
361
362                         // Cancel the autosave when the blur was triggered by the user submitting the form
363                         $('form#post').one( 'submit', function() {
364                                 cancel = true;
365                         });
366
367                         window.setTimeout( function() {
368                                 if ( ! cancel && wp.autosave ) {
369                                         wp.autosave.server.triggerSave();
370                                 }
371                         }, 200 );
372                 });
373         }
374
375         $document.on( 'autosave-disable-buttons.edit-post', function() {
376                 $submitButtons.addClass( 'disabled' );
377         }).on( 'autosave-enable-buttons.edit-post', function() {
378                 if ( ! wp.heartbeat || ! wp.heartbeat.hasConnectionError() ) {
379                         $submitButtons.removeClass( 'disabled' );
380                 }
381         }).on( 'before-autosave.edit-post', function() {
382                 $( '.autosave-message' ).text( postL10n.savingText );
383         }).on( 'after-autosave.edit-post', function( event, data ) {
384                 $( '.autosave-message' ).text( data.message );
385
386                 if ( $( document.body ).hasClass( 'post-new-php' ) ) {
387                         $( '.submitbox .submitdelete' ).show();
388                 }
389         });
390
391         $(window).on( 'beforeunload.edit-post', function() {
392                 var editor = typeof tinymce !== 'undefined' && tinymce.get('content');
393
394                 if ( ( editor && ! editor.isHidden() && editor.isDirty() ) ||
395                         ( wp.autosave && wp.autosave.server.postChanged() ) ) {
396
397                         return postL10n.saveAlert;
398                 }
399         }).on( 'unload.edit-post', function( event ) {
400                 if ( ! releaseLock ) {
401                         return;
402                 }
403
404                 // Unload is triggered (by hand) on removing the Thickbox iframe.
405                 // Make sure we process only the main document unload.
406                 if ( event.target && event.target.nodeName != '#document' ) {
407                         return;
408                 }
409
410                 $.ajax({
411                         type: 'POST',
412                         url: ajaxurl,
413                         async: false,
414                         data: {
415                                 action: 'wp-remove-post-lock',
416                                 _wpnonce: $('#_wpnonce').val(),
417                                 post_ID: $('#post_ID').val(),
418                                 active_post_lock: $('#active_post_lock').val()
419                         }
420                 });
421         });
422
423         // multi-taxonomies
424         if ( $('#tagsdiv-post_tag').length ) {
425                 window.tagBox && window.tagBox.init();
426         } else {
427                 $('.meta-box-sortables').children('div.postbox').each(function(){
428                         if ( this.id.indexOf('tagsdiv-') === 0 ) {
429                                 window.tagBox && window.tagBox.init();
430                                 return false;
431                         }
432                 });
433         }
434
435         // categories
436         $('.categorydiv').each( function(){
437                 var this_id = $(this).attr('id'), catAddBefore, catAddAfter, taxonomyParts, taxonomy, settingName;
438
439                 taxonomyParts = this_id.split('-');
440                 taxonomyParts.shift();
441                 taxonomy = taxonomyParts.join('-');
442                 settingName = taxonomy + '_tab';
443                 if ( taxonomy == 'category' )
444                         settingName = 'cats';
445
446                 // TODO: move to jQuery 1.3+, support for multiple hierarchical taxonomies, see wp-lists.js
447                 $('a', '#' + taxonomy + '-tabs').click( function( e ) {
448                         e.preventDefault();
449                         var t = $(this).attr('href');
450                         $(this).parent().addClass('tabs').siblings('li').removeClass('tabs');
451                         $('#' + taxonomy + '-tabs').siblings('.tabs-panel').hide();
452                         $(t).show();
453                         if ( '#' + taxonomy + '-all' == t )
454                                 deleteUserSetting( settingName );
455                         else
456                                 setUserSetting( settingName, 'pop' );
457                 });
458
459                 if ( getUserSetting( settingName ) )
460                         $('a[href="#' + taxonomy + '-pop"]', '#' + taxonomy + '-tabs').click();
461
462                 // Ajax Cat
463                 $( '#new' + taxonomy ).one( 'focus', function() { $( this ).val( '' ).removeClass( 'form-input-tip' ); } );
464
465                 $('#new' + taxonomy).keypress( function(event){
466                         if( 13 === event.keyCode ) {
467                                 event.preventDefault();
468                                 $('#' + taxonomy + '-add-submit').click();
469                         }
470                 });
471                 $('#' + taxonomy + '-add-submit').click( function(){ $('#new' + taxonomy).focus(); });
472
473                 catAddBefore = function( s ) {
474                         if ( !$('#new'+taxonomy).val() )
475                                 return false;
476                         s.data += '&' + $( ':checked', '#'+taxonomy+'checklist' ).serialize();
477                         $( '#' + taxonomy + '-add-submit' ).prop( 'disabled', true );
478                         return s;
479                 };
480
481                 catAddAfter = function( r, s ) {
482                         var sup, drop = $('#new'+taxonomy+'_parent');
483
484                         $( '#' + taxonomy + '-add-submit' ).prop( 'disabled', false );
485                         if ( 'undefined' != s.parsed.responses[0] && (sup = s.parsed.responses[0].supplemental.newcat_parent) ) {
486                                 drop.before(sup);
487                                 drop.remove();
488                         }
489                 };
490
491                 $('#' + taxonomy + 'checklist').wpList({
492                         alt: '',
493                         response: taxonomy + '-ajax-response',
494                         addBefore: catAddBefore,
495                         addAfter: catAddAfter
496                 });
497
498                 $('#' + taxonomy + '-add-toggle').click( function( e ) {
499                         e.preventDefault();
500                         $('#' + taxonomy + '-adder').toggleClass( 'wp-hidden-children' );
501                         $('a[href="#' + taxonomy + '-all"]', '#' + taxonomy + '-tabs').click();
502                         $('#new'+taxonomy).focus();
503                 });
504
505                 $('#' + taxonomy + 'checklist, #' + taxonomy + 'checklist-pop').on( 'click', 'li.popular-category > label input[type="checkbox"]', function() {
506                         var t = $(this), c = t.is(':checked'), id = t.val();
507                         if ( id && t.parents('#taxonomy-'+taxonomy).length )
508                                 $('#in-' + taxonomy + '-' + id + ', #in-popular-' + taxonomy + '-' + id).prop( 'checked', c );
509                 });
510
511         }); // end cats
512
513         // Custom Fields
514         if ( $('#postcustom').length ) {
515                 $( '#the-list' ).wpList( { addAfter: function() {
516                         $('table#list-table').show();
517                 }, addBefore: function( s ) {
518                         s.data += '&post_id=' + $('#post_ID').val();
519                         return s;
520                 }
521                 });
522         }
523
524         // submitdiv
525         if ( $('#submitdiv').length ) {
526                 stamp = $('#timestamp').html();
527                 visibility = $('#post-visibility-display').html();
528
529                 updateVisibility = function() {
530                         if ( $postVisibilitySelect.find('input:radio:checked').val() != 'public' ) {
531                                 $('#sticky').prop('checked', false);
532                                 $('#sticky-span').hide();
533                         } else {
534                                 $('#sticky-span').show();
535                         }
536                         if ( $postVisibilitySelect.find('input:radio:checked').val() != 'password' ) {
537                                 $('#password-span').hide();
538                         } else {
539                                 $('#password-span').show();
540                         }
541                 };
542
543                 updateText = function() {
544
545                         if ( ! $timestampdiv.length )
546                                 return true;
547
548                         var attemptedDate, originalDate, currentDate, publishOn, postStatus = $('#post_status'),
549                                 optPublish = $('option[value="publish"]', postStatus), aa = $('#aa').val(),
550                                 mm = $('#mm').val(), jj = $('#jj').val(), hh = $('#hh').val(), mn = $('#mn').val();
551
552                         attemptedDate = new Date( aa, mm - 1, jj, hh, mn );
553                         originalDate = new Date( $('#hidden_aa').val(), $('#hidden_mm').val() -1, $('#hidden_jj').val(), $('#hidden_hh').val(), $('#hidden_mn').val() );
554                         currentDate = new Date( $('#cur_aa').val(), $('#cur_mm').val() -1, $('#cur_jj').val(), $('#cur_hh').val(), $('#cur_mn').val() );
555
556                         if ( attemptedDate.getFullYear() != aa || (1 + attemptedDate.getMonth()) != mm || attemptedDate.getDate() != jj || attemptedDate.getMinutes() != mn ) {
557                                 $timestampdiv.find('.timestamp-wrap').addClass('form-invalid');
558                                 return false;
559                         } else {
560                                 $timestampdiv.find('.timestamp-wrap').removeClass('form-invalid');
561                         }
562
563                         if ( attemptedDate > currentDate && $('#original_post_status').val() != 'future' ) {
564                                 publishOn = postL10n.publishOnFuture;
565                                 $('#publish').val( postL10n.schedule );
566                         } else if ( attemptedDate <= currentDate && $('#original_post_status').val() != 'publish' ) {
567                                 publishOn = postL10n.publishOn;
568                                 $('#publish').val( postL10n.publish );
569                         } else {
570                                 publishOn = postL10n.publishOnPast;
571                                 $('#publish').val( postL10n.update );
572                         }
573                         if ( originalDate.toUTCString() == attemptedDate.toUTCString() ) { //hack
574                                 $('#timestamp').html(stamp);
575                         } else {
576                                 $('#timestamp').html(
577                                         '\n' + publishOn + ' <b>' +
578                                         postL10n.dateFormat
579                                                 .replace( '%1$s', $( 'option[value="' + mm + '"]', '#mm' ).attr( 'data-text' ) )
580                                                 .replace( '%2$s', parseInt( jj, 10 ) )
581                                                 .replace( '%3$s', aa )
582                                                 .replace( '%4$s', ( '00' + hh ).slice( -2 ) )
583                                                 .replace( '%5$s', ( '00' + mn ).slice( -2 ) ) +
584                                                 '</b> '
585                                 );
586                         }
587
588                         if ( $postVisibilitySelect.find('input:radio:checked').val() == 'private' ) {
589                                 $('#publish').val( postL10n.update );
590                                 if ( 0 === optPublish.length ) {
591                                         postStatus.append('<option value="publish">' + postL10n.privatelyPublished + '</option>');
592                                 } else {
593                                         optPublish.html( postL10n.privatelyPublished );
594                                 }
595                                 $('option[value="publish"]', postStatus).prop('selected', true);
596                                 $('#misc-publishing-actions .edit-post-status').hide();
597                         } else {
598                                 if ( $('#original_post_status').val() == 'future' || $('#original_post_status').val() == 'draft' ) {
599                                         if ( optPublish.length ) {
600                                                 optPublish.remove();
601                                                 postStatus.val($('#hidden_post_status').val());
602                                         }
603                                 } else {
604                                         optPublish.html( postL10n.published );
605                                 }
606                                 if ( postStatus.is(':hidden') )
607                                         $('#misc-publishing-actions .edit-post-status').show();
608                         }
609                         $('#post-status-display').html($('option:selected', postStatus).text());
610                         if ( $('option:selected', postStatus).val() == 'private' || $('option:selected', postStatus).val() == 'publish' ) {
611                                 $('#save-post').hide();
612                         } else {
613                                 $('#save-post').show();
614                                 if ( $('option:selected', postStatus).val() == 'pending' ) {
615                                         $('#save-post').show().val( postL10n.savePending );
616                                 } else {
617                                         $('#save-post').show().val( postL10n.saveDraft );
618                                 }
619                         }
620                         return true;
621                 };
622
623                 $( '#visibility .edit-visibility').click( function( e ) {
624                         e.preventDefault();
625                         if ( $postVisibilitySelect.is(':hidden') ) {
626                                 updateVisibility();
627                                 $postVisibilitySelect.slideDown( 'fast', function() {
628                                         $postVisibilitySelect.find( 'input[type="radio"]' ).first().focus();
629                                 } );
630                                 $(this).hide();
631                         }
632                 });
633
634                 $postVisibilitySelect.find('.cancel-post-visibility').click( function( event ) {
635                         $postVisibilitySelect.slideUp('fast');
636                         $('#visibility-radio-' + $('#hidden-post-visibility').val()).prop('checked', true);
637                         $('#post_password').val($('#hidden-post-password').val());
638                         $('#sticky').prop('checked', $('#hidden-post-sticky').prop('checked'));
639                         $('#post-visibility-display').html(visibility);
640                         $('#visibility .edit-visibility').show().focus();
641                         updateText();
642                         event.preventDefault();
643                 });
644
645                 $postVisibilitySelect.find('.save-post-visibility').click( function( event ) { // crazyhorse - multiple ok cancels
646                         $postVisibilitySelect.slideUp('fast');
647                         $('#visibility .edit-visibility').show().focus();
648                         updateText();
649
650                         if ( $postVisibilitySelect.find('input:radio:checked').val() != 'public' ) {
651                                 $('#sticky').prop('checked', false);
652                         } // WEAPON LOCKED
653
654                         if ( $('#sticky').prop('checked') ) {
655                                 sticky = 'Sticky';
656                         } else {
657                                 sticky = '';
658                         }
659
660                         $('#post-visibility-display').html(     postL10n[ $postVisibilitySelect.find('input:radio:checked').val() + sticky ]    );
661                         event.preventDefault();
662                 });
663
664                 $postVisibilitySelect.find('input:radio').change( function() {
665                         updateVisibility();
666                 });
667
668                 $timestampdiv.siblings('a.edit-timestamp').click( function( event ) {
669                         if ( $timestampdiv.is( ':hidden' ) ) {
670                                 $timestampdiv.slideDown( 'fast', function() {
671                                         $( 'input, select', $timestampdiv.find( '.timestamp-wrap' ) ).first().focus();
672                                 } );
673                                 $(this).hide();
674                         }
675                         event.preventDefault();
676                 });
677
678                 $timestampdiv.find('.cancel-timestamp').click( function( event ) {
679                         $timestampdiv.slideUp('fast').siblings('a.edit-timestamp').show().focus();
680                         $('#mm').val($('#hidden_mm').val());
681                         $('#jj').val($('#hidden_jj').val());
682                         $('#aa').val($('#hidden_aa').val());
683                         $('#hh').val($('#hidden_hh').val());
684                         $('#mn').val($('#hidden_mn').val());
685                         updateText();
686                         event.preventDefault();
687                 });
688
689                 $timestampdiv.find('.save-timestamp').click( function( event ) { // crazyhorse - multiple ok cancels
690                         if ( updateText() ) {
691                                 $timestampdiv.slideUp('fast');
692                                 $timestampdiv.siblings('a.edit-timestamp').show().focus();
693                         }
694                         event.preventDefault();
695                 });
696
697                 $('#post').on( 'submit', function( event ) {
698                         if ( ! updateText() ) {
699                                 event.preventDefault();
700                                 $timestampdiv.show();
701
702                                 if ( wp.autosave ) {
703                                         wp.autosave.enableButtons();
704                                 }
705
706                                 $( '#publishing-action .spinner' ).removeClass( 'is-active' );
707                         }
708                 });
709
710                 $postStatusSelect.siblings('a.edit-post-status').click( function( event ) {
711                         if ( $postStatusSelect.is( ':hidden' ) ) {
712                                 $postStatusSelect.slideDown( 'fast', function() {
713                                         $postStatusSelect.find('select').focus();
714                                 } );
715                                 $(this).hide();
716                         }
717                         event.preventDefault();
718                 });
719
720                 $postStatusSelect.find('.save-post-status').click( function( event ) {
721                         $postStatusSelect.slideUp( 'fast' ).siblings( 'a.edit-post-status' ).show().focus();
722                         updateText();
723                         event.preventDefault();
724                 });
725
726                 $postStatusSelect.find('.cancel-post-status').click( function( event ) {
727                         $postStatusSelect.slideUp( 'fast' ).siblings( 'a.edit-post-status' ).show().focus();
728                         $('#post_status').val( $('#hidden_post_status').val() );
729                         updateText();
730                         event.preventDefault();
731                 });
732         } // end submitdiv
733
734         // permalink
735         function editPermalink() {
736                 var i, slug_value,
737                         $el, revert_e,
738                         c = 0,
739                         real_slug = $('#post_name'),
740                         revert_slug = real_slug.val(),
741                         permalink = $( '#sample-permalink' ),
742                         permalinkOrig = permalink.html(),
743                         permalinkInner = $( '#sample-permalink a' ).html(),
744                         buttons = $('#edit-slug-buttons'),
745                         buttonsOrig = buttons.html(),
746                         full = $('#editable-post-name-full');
747
748                 // Deal with Twemoji in the post-name
749                 full.find( 'img' ).replaceWith( function() { return this.alt; } );
750                 full = full.html();
751
752                 permalink.html( permalinkInner );
753                 $el = $( '#editable-post-name' );
754                 revert_e = $el.html();
755
756                 buttons.html( '<button type="button" class="save button button-small">' + postL10n.ok + '</button> <button type="button" class="cancel button-link">' + postL10n.cancel + '</button>' );
757                 buttons.children( '.save' ).click( function() {
758                         var new_slug = $el.children( 'input' ).val();
759
760                         if ( new_slug == $('#editable-post-name-full').text() ) {
761                                 buttons.children('.cancel').click();
762                                 return;
763                         }
764                         $.post(ajaxurl, {
765                                 action: 'sample-permalink',
766                                 post_id: postId,
767                                 new_slug: new_slug,
768                                 new_title: $('#title').val(),
769                                 samplepermalinknonce: $('#samplepermalinknonce').val()
770                         }, function(data) {
771                                 var box = $('#edit-slug-box');
772                                 box.html(data);
773                                 if (box.hasClass('hidden')) {
774                                         box.fadeIn('fast', function () {
775                                                 box.removeClass('hidden');
776                                         });
777                                 }
778
779                                 buttons.html(buttonsOrig);
780                                 permalink.html(permalinkOrig);
781                                 real_slug.val(new_slug);
782                                 $( '.edit-slug' ).focus();
783                                 wp.a11y.speak( postL10n.permalinkSaved );
784                         });
785                 });
786
787                 buttons.children( '.cancel' ).click( function() {
788                         $('#view-post-btn').show();
789                         $el.html(revert_e);
790                         buttons.html(buttonsOrig);
791                         permalink.html(permalinkOrig);
792                         real_slug.val(revert_slug);
793                         $( '.edit-slug' ).focus();
794                 });
795
796                 for ( i = 0; i < full.length; ++i ) {
797                         if ( '%' == full.charAt(i) )
798                                 c++;
799                 }
800
801                 slug_value = ( c > full.length / 4 ) ? '' : full;
802                 $el.html( '<input type="text" id="new-post-slug" value="' + slug_value + '" autocomplete="off" />' ).children( 'input' ).keydown( function( e ) {
803                         var key = e.which;
804                         // On enter, just save the new slug, don't save the post.
805                         if ( 13 === key ) {
806                                 e.preventDefault();
807                                 buttons.children( '.save' ).click();
808                         }
809                         if ( 27 === key ) {
810                                 buttons.children( '.cancel' ).click();
811                         }
812                 } ).keyup( function() {
813                         real_slug.val( this.value );
814                 }).focus();
815         }
816
817         $( '#titlediv' ).on( 'click', '.edit-slug', function() {
818                 editPermalink();
819         });
820
821         wptitlehint = function(id) {
822                 id = id || 'title';
823
824                 var title = $('#' + id), titleprompt = $('#' + id + '-prompt-text');
825
826                 if ( '' === title.val() )
827                         titleprompt.removeClass('screen-reader-text');
828
829                 titleprompt.click(function(){
830                         $(this).addClass('screen-reader-text');
831                         title.focus();
832                 });
833
834                 title.blur(function(){
835                         if ( '' === this.value )
836                                 titleprompt.removeClass('screen-reader-text');
837                 }).focus(function(){
838                         titleprompt.addClass('screen-reader-text');
839                 }).keydown(function(e){
840                         titleprompt.addClass('screen-reader-text');
841                         $(this).unbind(e);
842                 });
843         };
844
845         wptitlehint();
846
847         // Resize the visual and text editors
848         ( function() {
849                 var editor, offset, mce,
850                         $handle = $('#post-status-info'),
851                         $postdivrich = $('#postdivrich');
852
853                 // No point for touch devices
854                 if ( ! $textarea.length || 'ontouchstart' in window ) {
855                         // Hide the resize handle
856                         $('#content-resize-handle').hide();
857                         return;
858                 }
859
860                 function dragging( event ) {
861                         if ( $postdivrich.hasClass( 'wp-editor-expand' ) ) {
862                                 return;
863                         }
864
865                         if ( mce ) {
866                                 editor.theme.resizeTo( null, offset + event.pageY );
867                         } else {
868                                 $textarea.height( Math.max( 50, offset + event.pageY ) );
869                         }
870
871                         event.preventDefault();
872                 }
873
874                 function endDrag() {
875                         var height, toolbarHeight;
876
877                         if ( $postdivrich.hasClass( 'wp-editor-expand' ) ) {
878                                 return;
879                         }
880
881                         if ( mce ) {
882                                 editor.focus();
883                                 toolbarHeight = parseInt( $( '#wp-content-editor-container .mce-toolbar-grp' ).height(), 10 );
884
885                                 if ( toolbarHeight < 10 || toolbarHeight > 200 ) {
886                                         toolbarHeight = 30;
887                                 }
888
889                                 height = parseInt( $('#content_ifr').css('height'), 10 ) + toolbarHeight - 28;
890                         } else {
891                                 $textarea.focus();
892                                 height = parseInt( $textarea.css('height'), 10 );
893                         }
894
895                         $document.off( '.wp-editor-resize' );
896
897                         // sanity check
898                         if ( height && height > 50 && height < 5000 ) {
899                                 setUserSetting( 'ed_size', height );
900                         }
901                 }
902
903                 $handle.on( 'mousedown.wp-editor-resize', function( event ) {
904                         if ( typeof tinymce !== 'undefined' ) {
905                                 editor = tinymce.get('content');
906                         }
907
908                         if ( editor && ! editor.isHidden() ) {
909                                 mce = true;
910                                 offset = $('#content_ifr').height() - event.pageY;
911                         } else {
912                                 mce = false;
913                                 offset = $textarea.height() - event.pageY;
914                                 $textarea.blur();
915                         }
916
917                         $document.on( 'mousemove.wp-editor-resize', dragging )
918                                 .on( 'mouseup.wp-editor-resize mouseleave.wp-editor-resize', endDrag );
919
920                         event.preventDefault();
921                 }).on( 'mouseup.wp-editor-resize', endDrag );
922         })();
923
924         if ( typeof tinymce !== 'undefined' ) {
925                 // When changing post formats, change the editor body class
926                 $( '#post-formats-select input.post-format' ).on( 'change.set-editor-class', function() {
927                         var editor, body, format = this.id;
928
929                         if ( format && $( this ).prop( 'checked' ) && ( editor = tinymce.get( 'content' ) ) ) {
930                                 body = editor.getBody();
931                                 body.className = body.className.replace( /\bpost-format-[^ ]+/, '' );
932                                 editor.dom.addClass( body, format == 'post-format-0' ? 'post-format-standard' : format );
933                                 $( document ).trigger( 'editor-classchange' );
934                         }
935                 });
936         }
937
938         // Save on pressing Ctrl/Command + S in the Text editor
939         $textarea.on( 'keydown.wp-autosave', function( event ) {
940                 if ( event.which === 83 ) {
941                         if ( event.shiftKey || event.altKey || ( isMac && ( ! event.metaKey || event.ctrlKey ) ) || ( ! isMac && ! event.ctrlKey ) ) {
942                                 return;
943                         }
944
945                         wp.autosave && wp.autosave.server.triggerSave();
946                         event.preventDefault();
947                 }
948         });
949
950         if ( $( '#original_post_status' ).val() === 'auto-draft' && window.history.replaceState ) {
951                 var location;
952
953                 $( '#publish' ).on( 'click', function() {
954                         location = window.location.href;
955                         location += ( location.indexOf( '?' ) !== -1 ) ? '&' : '?';
956                         location += 'wp-post-new-reload=true';
957
958                         window.history.replaceState( null, null, location );
959                 });
960         }
961 });
962
963 ( function( $, counter ) {
964         $( function() {
965                 var $content = $( '#content' ),
966                         $count = $( '#wp-word-count' ).find( '.word-count' ),
967                         prevCount = 0,
968                         contentEditor;
969
970                 function update() {
971                         var text, count;
972
973                         if ( ! contentEditor || contentEditor.isHidden() ) {
974                                 text = $content.val();
975                         } else {
976                                 text = contentEditor.getContent( { format: 'raw' } );
977                         }
978
979                         count = counter.count( text );
980
981                         if ( count !== prevCount ) {
982                                 $count.text( count );
983                         }
984
985                         prevCount = count;
986                 }
987
988                 $( document ).on( 'tinymce-editor-init', function( event, editor ) {
989                         if ( editor.id !== 'content' ) {
990                                 return;
991                         }
992
993                         contentEditor = editor;
994
995                         editor.on( 'nodechange keyup', _.debounce( update, 1000 ) );
996                 } );
997
998                 $content.on( 'input keyup', _.debounce( update, 1000 ) );
999
1000                 update();
1001         } );
1002 } )( jQuery, new wp.utils.WordCounter() );