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