]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - js/util.js
a90c3bea63476af3be5c729710fc50bc3f70db4f
[quix0rs-gnu-social.git] / js / util.js
1 /*
2  * StatusNet - a distributed open-source microblogging tool
3  * Copyright (C) 2008, StatusNet, Inc.
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Affero General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  *
18  * @category  UI interaction
19  * @package   StatusNet
20  * @author    Sarven Capadisli <csarven@status.net>
21  * @author    Evan Prodromou <evan@status.net>
22  * @author    Brion Vibber <brion@status.net>
23  * @copyright 2009,2010 StatusNet, Inc.
24  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
25  * @link      http://status.net/
26  */
27
28 var SN = { // StatusNet
29     C: { // Config
30         I: { // Init
31             CounterBlackout: false,
32             MaxLength: 140,
33             PatternUsername: /^[0-9a-zA-Z\-_.]*$/,
34             HTTP20x30x: [200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307],
35             NoticeFormMaster: null // to be cloned from the one at top
36         },
37
38         /**
39          * @fixme are these worth the trouble? They seem to mostly just duplicate
40          * themselves while slightly obscuring the actual selector, so it's hard
41          * to pop over to the HTML and find something.
42          *
43          * In theory, minification could reduce them to shorter variable names,
44          * but at present that doesn't happen with yui-compressor.
45          */
46         S: { // Selector
47             Disabled: 'disabled',
48             Warning: 'warning',
49             Error: 'error',
50             Success: 'success',
51             Processing: 'processing',
52             CommandResult: 'command_result',
53             FormNotice: 'form_notice',
54             NoticeDataGeo: 'notice_data-geo',
55             NoticeDataGeoCookie: 'NoticeDataGeo',
56             NoticeDataGeoSelected: 'notice_data-geo_selected',
57             StatusNetInstance: 'StatusNetInstance'
58         }
59     },
60
61     /**
62      * Map of localized message strings exported to script from the PHP
63      * side via Action::getScriptMessages().
64      *
65      * Retrieve them via SN.msg(); this array is an implementation detail.
66      *
67      * @access private
68      */
69     messages: {},
70
71     /**
72      * Grabs a localized string that's been previously exported to us
73      * from server-side code via Action::getScriptMessages().
74      *
75      * @example alert(SN.msg('coolplugin-failed'));
76      *
77      * @param {String} key: string key name to pull from message index
78      * @return matching localized message string
79      */
80     msg: function (key) {
81         if (SN.messages[key] === undefined) {
82             return '[' + key + ']';
83         }
84         return SN.messages[key];
85     },
86
87     U: { // Utils
88         /**
89          * Setup function -- DOES NOT trigger actions immediately.
90          *
91          * Sets up event handlers on the new notice form.
92          *
93          * @param {jQuery} form: jQuery object whose first matching element is the form
94          * @access private
95          */
96         FormNoticeEnhancements: function (form) {
97             if (jQuery.data(form[0], 'ElementData') === undefined) {
98                 var MaxLength = form.find('.count').text();
99                 if (MaxLength === undefined) {
100                     MaxLength = SN.C.I.MaxLength;
101                 }
102                 jQuery.data(form[0], 'ElementData', {MaxLength: MaxLength});
103
104                 SN.U.Counter(form);
105
106                 var NDT = form.find('.notice_data-text:first');
107
108                 NDT.on('keyup', function (e) {
109                     SN.U.Counter(form);
110                 });
111
112                 var delayedUpdate = function (e) {
113                     // Cut and paste events fire *before* the operation,
114                     // so we need to trigger an update in a little bit.
115                     // This would be so much easier if the 'change' event
116                     // actually fired every time the value changed. :P
117                     window.setTimeout(function () {
118                         SN.U.Counter(form);
119                     }, 50);
120                 };
121                 // Note there's still no event for mouse-triggered 'delete'.
122                 NDT.on('cut', delayedUpdate)
123                     .on('paste', delayedUpdate);
124             } else {
125                 form.find('.count').text(jQuery.data(form[0], 'ElementData').MaxLength);
126             }
127         },
128
129         /**
130          * To be called from event handlers on the notice import form.
131          * Triggers an update of the remaining-characters counter.
132          *
133          * Additional counter updates will be suppressed during the
134          * next half-second to avoid flooding the layout engine with
135          * updates, followed by another automatic check.
136          *
137          * The maximum length is pulled from data established by
138          * FormNoticeEnhancements.
139          *
140          * @param {jQuery} form: jQuery object whose first element is the notice posting form
141          * @access private
142          */
143         Counter: function (form) {
144             SN.C.I.FormNoticeCurrent = form;
145
146             var MaxLength = jQuery.data(form[0], 'ElementData').MaxLength;
147
148             if (MaxLength <= 0) {
149                 return;
150             }
151
152             var remaining = MaxLength - SN.U.CharacterCount(form);
153             var counter = form.find('.count');
154
155             if (remaining.toString() != counter.text()) {
156                 if (!SN.C.I.CounterBlackout || remaining === 0) {
157                     if (counter.text() != String(remaining)) {
158                         counter.text(remaining);
159                     }
160                     if (remaining < 0) {
161                         form.addClass(SN.C.S.Warning);
162                     } else {
163                         form.removeClass(SN.C.S.Warning);
164                     }
165                     // Skip updates for the next 500ms.
166                     // On slower hardware, updating on every keypress is unpleasant.
167                     if (!SN.C.I.CounterBlackout) {
168                         SN.C.I.CounterBlackout = true;
169                         SN.C.I.FormNoticeCurrent = form;
170                         window.setTimeout("SN.U.ClearCounterBlackout(SN.C.I.FormNoticeCurrent);", 500);
171                     }
172                 }
173             }
174         },
175
176         /**
177          * Pull the count of characters in the current edit field.
178          * Plugins replacing the edit control may need to override this.
179          *
180          * @param {jQuery} form: jQuery object whose first element is the notice posting form
181          * @return number of chars
182          */
183         CharacterCount: function (form) {
184             return form.find('.notice_data-text:first').val().length;
185         },
186
187         /**
188          * Called internally after the counter update blackout period expires;
189          * runs another update to make sure we didn't miss anything.
190          *
191          * @param {jQuery} form: jQuery object whose first element is the notice posting form
192          * @access private
193          */
194         ClearCounterBlackout: function (form) {
195             // Allow keyup events to poke the counter again
196             SN.C.I.CounterBlackout = false;
197             // Check if the string changed since we last looked
198             SN.U.Counter(form);
199         },
200
201         /**
202          * Helper function to rewrite default HTTP form action URLs to HTTPS
203          * so we can actually fetch them when on an SSL page in ssl=sometimes
204          * mode.
205          *
206          * It would be better to output URLs that didn't hardcode protocol
207          * and hostname in the first place...
208          *
209          * @param {String} url
210          * @return string
211          */
212         RewriteAjaxAction: function (url) {
213             // Quick hack: rewrite AJAX submits to HTTPS if they'd fail otherwise.
214             if (document.location.protocol === 'https:' && url.substr(0, 5) === 'http:') {
215                 return url.replace(/^http:\/\/[^:\/]+/, 'https://' + document.location.host);
216             }
217             return url;
218         },
219
220         /**
221          * Grabs form data and submits it asynchronously, with 'ajax=1'
222          * parameter added to the rest.
223          *
224          * If a successful response includes another form, that form
225          * will be extracted and copied in, replacing the original form.
226          * If there's no form, the first paragraph will be used.
227          *
228          * This will automatically be applied on the 'submit' event for
229          * any form with the 'ajax' class.
230          *
231          * @fixme can sometimes explode confusingly if returnd data is bogus
232          * @fixme error handling is pretty vague
233          * @fixme can't submit file uploads
234          *
235          * @param {jQuery} form: jQuery object whose first element is a form
236          * @param function onSuccess: something extra to do on success
237          *
238          * @access public
239          */
240         FormXHR: function (form, onSuccess) {
241             $.ajax({
242                 type: 'POST',
243                 dataType: 'xml',
244                 url: SN.U.RewriteAjaxAction(form.attr('action')),
245                 data: form.serialize() + '&ajax=1',
246                 beforeSend: function (xhr) {
247                     form
248                         .addClass(SN.C.S.Processing)
249                         .find('.submit')
250                             .addClass(SN.C.S.Disabled)
251                             .prop(SN.C.S.Disabled, true);
252                 },
253                 error: function (xhr, textStatus, errorThrown) {
254                     // If the server end reported an error from StatusNet,
255                     // find it -- otherwise we'll see what was reported
256                     // from the browser.
257                     var errorReported = null;
258                     if (xhr.responseXML) {
259                         errorReported = $('#error', xhr.responseXML).text();
260                     }
261                     window.alert(errorReported || errorThrown || textStatus);
262
263                     // Restore the form to original state.
264                     // Hopefully. :D
265                     form
266                         .removeClass(SN.C.S.Processing)
267                         .find('.submit')
268                             .removeClass(SN.C.S.Disabled)
269                             .prop(SN.C.S.Disabled, false);
270                 },
271                 success: function (data, textStatus) {
272                     if ($('form', data)[0] !== undefined) {
273                         var form_new = document._importNode($('form', data)[0], true);
274                         form.replaceWith(form_new);
275                         if (onSuccess) {
276                             onSuccess();
277                         }
278                     } else if ($('p', data)[0] !== undefined) {
279                         form.replaceWith(document._importNode($('p', data)[0], true));
280                         if (onSuccess) {
281                             onSuccess();
282                         }
283                     } else {
284                         window.alert('Unknown error.');
285                     }
286                 }
287             });
288         },
289
290         /**
291          * Setup function -- DOES NOT trigger actions immediately.
292          *
293          * Sets up event handlers for special-cased async submission of the
294          * notice-posting form, including some pre-post validation.
295          *
296          * Unlike FormXHR() this does NOT submit the form immediately!
297          * It sets up event handlers so that any method of submitting the
298          * form (click on submit button, enter, submit() etc) will trigger
299          * it properly.
300          *
301          * Also unlike FormXHR(), this system will use a hidden iframe
302          * automatically to handle file uploads via <input type="file">
303          * controls.
304          *
305          * @fixme tl;dr
306          * @fixme vast swaths of duplicate code and really long variable names clutter this function up real bad
307          * @fixme error handling is unreliable
308          * @fixme cookieValue is a global variable, but probably shouldn't be
309          * @fixme saving the location cache cookies should be split out
310          * @fixme some error messages are hardcoded english: needs i18n
311          *
312          * @param {jQuery} form: jQuery object whose first element is a form
313          *
314          * @access public
315          */
316         FormNoticeXHR: function (form) {
317             SN.C.I.NoticeDataGeo = {};
318             form.append('<input type="hidden" name="ajax" value="1"/>');
319
320             // Make sure we don't have a mixed HTTP/HTTPS submission...
321             form.attr('action', SN.U.RewriteAjaxAction(form.attr('action')));
322
323             /**
324              * Show a response feedback bit under the new-notice dialog.
325              *
326              * @param {String} cls: CSS class name to use ('error' or 'success')
327              * @param {String} text
328              * @access private
329              */
330             var showFeedback = function (cls, text) {
331                 form.append(
332                     $('<p class="form_response"></p>')
333                         .addClass(cls)
334                         .text(text)
335                 );
336             };
337
338             /**
339              * Hide the previous response feedback, if any.
340              */
341             var removeFeedback = function () {
342                 form.find('.form_response').remove();
343             };
344
345             form.ajaxForm({
346                 dataType: 'xml',
347                 timeout: '60000',
348                 beforeSend: function (formData) {
349                     if (form.find('.notice_data-text:first').val() == '') {
350                         form.addClass(SN.C.S.Warning);
351                         return false;
352                     }
353                     form
354                         .addClass(SN.C.S.Processing)
355                         .find('.submit')
356                             .addClass(SN.C.S.Disabled)
357                             .prop(SN.C.S.Disabled, true);
358
359                     SN.U.normalizeGeoData(form);
360
361                     return true;
362                 },
363                 error: function (xhr, textStatus, errorThrown) {
364                     form
365                         .removeClass(SN.C.S.Processing)
366                         .find('.submit')
367                             .removeClass(SN.C.S.Disabled)
368                             .prop(SN.C.S.Disabled, false);
369                     removeFeedback();
370                     if (textStatus == 'timeout') {
371                         // @fixme i18n
372                         showFeedback('error', 'Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists.');
373                     } else {
374                         var response = SN.U.GetResponseXML(xhr);
375                         if ($('.' + SN.C.S.Error, response).length > 0) {
376                             form.append(document._importNode($('.' + SN.C.S.Error, response)[0], true));
377                         } else {
378                             if (parseInt(xhr.status) === 0 || jQuery.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) >= 0) {
379                                 form
380                                     .resetForm()
381                                     .find('.attach-status').remove();
382                                 SN.U.FormNoticeEnhancements(form);
383                             } else {
384                                 // @fixme i18n
385                                 showFeedback('error', '(Sorry! We had trouble sending your notice (' + xhr.status + ' ' + xhr.statusText + '). Please report the problem to the site administrator if this happens again.');
386                             }
387                         }
388                     }
389                 },
390                 success: function (data, textStatus) {
391                     removeFeedback();
392                     var errorResult = $('#' + SN.C.S.Error, data);
393                     if (errorResult.length > 0) {
394                         showFeedback('error', errorResult.text());
395                     } else {
396                         var commandResult = $('#' + SN.C.S.CommandResult, data);
397                         if (commandResult.length > 0) {
398                             showFeedback('success', commandResult.text());
399                         } else {
400                             // New notice post was successful. If on our timeline, show it!
401                             var notice = document._importNode($('li', data)[0], true);
402                             var notices = $('#notices_primary .notices:first');
403                             var replyItem = form.closest('li.notice-reply');
404
405                             if (replyItem.length > 0) {
406                                 // If this is an inline reply, remove the form...
407                                 var list = form.closest('.threaded-replies');
408
409                                 var id = $(notice).attr('id');
410                                 if ($('#' + id).length == 0) {
411                                     $(notice).insertBefore(replyItem);
412                                 } // else Realtime came through before us...
413
414                                 alert('reset form now');
415
416                             } else if (notices.length > 0 && SN.U.belongsOnTimeline(notice)) {
417                                 // Not a reply. If on our timeline, show it at the top!
418
419                                 if ($('#' + notice.id).length === 0) {
420                                     var notice_irt_value = form.find('[name=inreplyto]').val();
421                                     var notice_irt = '#notices_primary #notice-' + notice_irt_value;
422                                     if ($('body')[0].id == 'conversation') {
423                                         if (notice_irt_value.length > 0 && $(notice_irt + ' .notices').length < 1) {
424                                             $(notice_irt).append('<ul class="notices"></ul>');
425                                         }
426                                         $($(notice_irt + ' .notices')[0]).append(notice);
427                                     } else {
428                                         notices.prepend(notice);
429                                     }
430                                     $('#' + notice.id)
431                                         .css({display: 'none'})
432                                         .fadeIn(2500);
433                                     SN.U.NoticeWithAttachment($('#' + notice.id));
434                                     SN.U.switchInputFormTab(null);
435                                 }
436                             } else {
437                                 // Not on a timeline that this belongs on?
438                                 // Just show a success message.
439                                 // @fixme inline
440                                 showFeedback('success', $('title', data).text());
441                             }
442                         }
443                         form.resetForm();
444                         form.find('[name=inreplyto]').val('');
445                         form.find('.attach-status').remove();
446                         SN.U.FormNoticeEnhancements(form);
447                     }
448                 },
449                 complete: function (xhr, textStatus) {
450                     form
451                         .removeClass(SN.C.S.Processing)
452                         .find('.submit')
453                             .prop(SN.C.S.Disabled, false)
454                             .removeClass(SN.C.S.Disabled);
455
456                     form.find('[name=lat]').val(SN.C.I.NoticeDataGeo.NLat);
457                     form.find('[name=lon]').val(SN.C.I.NoticeDataGeo.NLon);
458                     form.find('[name=location_ns]').val(SN.C.I.NoticeDataGeo.NLNS);
459                     form.find('[name=location_id]').val(SN.C.I.NoticeDataGeo.NLID);
460                     form.find('[name=notice_data-geo]').prop('checked', SN.C.I.NoticeDataGeo.NDG);
461                 }
462             });
463         },
464
465         FormProfileSearchXHR: function (form) {
466             $.ajax({
467                 type: 'POST',
468                 dataType: 'xml',
469                 url: form.attr('action'),
470                 data: form.serialize() + '&ajax=1',
471                 beforeSend: function (xhr) {
472                     form
473                         .addClass(SN.C.S.Processing)
474                         .find('.submit')
475                             .addClass(SN.C.S.Disabled)
476                             .prop(SN.C.S.Disabled, true);
477                 },
478                 error: function (xhr, textStatus, errorThrown) {
479                     window.alert(errorThrown || textStatus);
480                 },
481                 success: function (data, textStatus) {
482                     var results_placeholder = $('#profile_search_results');
483                     if ($('ul', data)[0] !== undefined) {
484                         var list = document._importNode($('ul', data)[0], true);
485                         results_placeholder.replaceWith(list);
486                     } else {
487                         var _error = $('<li/>').append(document._importNode($('p', data)[0], true));
488                         results_placeholder.html(_error);
489                     }
490                     form
491                         .removeClass(SN.C.S.Processing)
492                         .find('.submit')
493                             .removeClass(SN.C.S.Disabled)
494                             .prop(SN.C.S.Disabled, false);
495                 }
496             });
497         },
498
499         FormPeopletagsXHR: function (form) {
500             $.ajax({
501                 type: 'POST',
502                 dataType: 'xml',
503                 url: form.attr('action'),
504                 data: form.serialize() + '&ajax=1',
505                 beforeSend: function (xhr) {
506                     form.find('.submit')
507                             .addClass(SN.C.S.Processing)
508                             .addClass(SN.C.S.Disabled)
509                             .prop(SN.C.S.Disabled, true);
510                 },
511                 error: function (xhr, textStatus, errorThrown) {
512                     window.alert(errorThrown || textStatus);
513                 },
514                 success: function (data, textStatus) {
515                     var results_placeholder = form.parents('.entity_tags');
516                     if ($('.entity_tags', data)[0] !== undefined) {
517                         var tags = document._importNode($('.entity_tags', data)[0], true);
518                         $(tags).find('.editable').append($('<button class="peopletags_edit_button"/>'));
519                         results_placeholder.replaceWith(tags);
520                     } else {
521                         results_placeholder.find('p').remove();
522                         results_placeholder.append(document._importNode($('p', data)[0], true));
523                         form.removeClass(SN.C.S.Processing)
524                             .find('.submit')
525                                 .removeClass(SN.C.S.Disabled)
526                                 .prop(SN.C.S.Disabled, false);
527                     }
528                 }
529             });
530         },
531
532         normalizeGeoData: function (form) {
533             SN.C.I.NoticeDataGeo.NLat = form.find('[name=lat]').val();
534             SN.C.I.NoticeDataGeo.NLon = form.find('[name=lon]').val();
535             SN.C.I.NoticeDataGeo.NLNS = form.find('[name=location_ns]').val();
536             SN.C.I.NoticeDataGeo.NLID = form.find('[name=location_id]').val();
537             SN.C.I.NoticeDataGeo.NDG = form.find('[name=notice_data-geo]').prop('checked'); // @fixme (does this still need to be fixed somehow?)
538
539             var cookieValue = $.cookie(SN.C.S.NoticeDataGeoCookie);
540
541             if (cookieValue !== undefined && cookieValue != 'disabled') {
542                 cookieValue = JSON.parse(cookieValue);
543                 SN.C.I.NoticeDataGeo.NLat = form.find('[name=lat]').val(cookieValue.NLat).val();
544                 SN.C.I.NoticeDataGeo.NLon = form.find('[name=lon]').val(cookieValue.NLon).val();
545                 if (cookieValue.NLNS) {
546                     SN.C.I.NoticeDataGeo.NLNS = form.find('[name=location_ns]').val(cookieValue.NLNS).val();
547                     SN.C.I.NoticeDataGeo.NLID = form.find('[name=location_id]').val(cookieValue.NLID).val();
548                 } else {
549                     form.find('[name=location_ns]').val('');
550                     form.find('[name=location_id]').val('');
551                 }
552             }
553             if (cookieValue == 'disabled') {
554                 SN.C.I.NoticeDataGeo.NDG = form.find('[name=notice_data-geo]').prop('checked', false).prop('checked');
555             } else {
556                 SN.C.I.NoticeDataGeo.NDG = form.find('[name=notice_data-geo]').prop('checked', true).prop('checked');
557             }
558
559         },
560
561         /**
562          * Fetch an XML DOM from an XHR's response data.
563          *
564          * Works around unavailable responseXML when document.domain
565          * has been modified by Meteor or other tools, in some but not
566          * all browsers.
567          *
568          * @param {XMLHTTPRequest} xhr
569          * @return DOMDocument
570          */
571         GetResponseXML: function (xhr) {
572             try {
573                 return xhr.responseXML;
574             } catch (e) {
575                 return (new DOMParser()).parseFromString(xhr.responseText, "text/xml");
576             }
577         },
578
579         /**
580          * Setup function -- DOES NOT trigger actions immediately.
581          *
582          * Sets up event handlers on all visible notice's reply buttons to
583          * tweak the new-notice form with needed variables and focus it
584          * when pushed.
585          *
586          * (This replaces the default reply button behavior to submit
587          * directly to a form which comes back with a specialized page
588          * with the form data prefilled.)
589          *
590          * @access private
591          */
592         NoticeReply: function () {
593             $(document).on('click', '#content .notice_reply', function (e) {
594                 e.preventDefault();
595                 var notice = $(this).closest('li.notice');
596                 SN.U.NoticeInlineReplyTrigger(notice);
597                 return false;
598             });
599         },
600
601         /**
602          * Stub -- kept for compat with plugins for now.
603          * @access private
604          */
605         NoticeReplyTo: function (notice) {
606         },
607
608         /**
609          * Open up a notice's inline reply box.
610          *
611          * @param {jQuery} notice: jQuery object containing one notice
612          * @param {String} initialText
613          */
614         NoticeInlineReplyTrigger: function (notice, initialText) {
615             // Find the notice we're replying to...
616             var id = $($('.notice_id', notice)[0]).text();
617             var replyForm;
618             var parentNotice = notice;
619             var stripForm = true; // strip a couple things out of reply forms that are inline
620
621             var list = notice.closest('.notices');
622             if (list.hasClass('threaded-replies')) {
623                 // We're replying to a reply; use reply form on the end of this list.
624             } else {
625                 // We're replying to a parent notice; pull its threaded list
626                 // and we'll add on the end of it. Will add the threaded list if needed.
627                 var list = $('ul.threaded-replies', notice);
628                 if (list.length == 0) {
629                     list = $('<ul class="notices threaded-replies xoxo"></ul>');
630                     notice.append(list);
631                     list = notice.find('ul.threaded-replies');
632                 }
633             }
634
635             var nextStep = function () {
636                 // Override...?
637                 replyForm.find('input[name=inreplyto]').val(id);
638                 if (stripForm) {
639                     // Don't do this for old-school reply form, as they don't come back!
640                     replyForm.find('#notice_to').prop('disabled', true).hide();
641                     replyForm.find('#notice_private').prop('disabled', true).hide();
642                     replyForm.find('label[for=notice_to]').hide();
643                     replyForm.find('label[for=notice_private]').hide();
644                 }
645
646                 // Set focus...
647                 var text = replyForm.find('textarea');
648                 if (text.length == 0) {
649                     throw "No textarea";
650                 }
651                 var replyto = '';
652                 if (initialText) {
653                     replyto = initialText + ' ';
654                 }
655                 text.val(replyto + text.val().replace(new RegExp(replyto, 'i'), ''));
656                 text.data('initialText', $.trim(initialText));
657                 text.focus();
658                 if (text[0].setSelectionRange) {
659                     var len = text.val().length;
660                     text[0].setSelectionRange(len, len);
661                 }
662             };
663
664             // Create the reply form entry at the end
665             var replyItem = $('li.notice-reply', list);
666             if (replyItem.length == 0) {
667                 replyItem = $('<li class="notice-reply"></li>');
668
669                 var intermediateStep = function (formMaster) {
670                     var formEl = document._importNode(formMaster, true);
671                     replyItem.append(formEl);
672                     list.append(replyItem); // *after* the placeholder
673
674                     var form = $(formEl);
675                     replyForm = form;
676                     SN.Init.NoticeFormSetup(form);
677
678                     nextStep();
679                 };
680                 if (SN.C.I.NoticeFormMaster) {
681                     // We've already saved a master copy of the form.
682                     // Clone it in!
683                     intermediateStep(SN.C.I.NoticeFormMaster);
684                 }
685             } else {
686                 replyItem.show();
687                 replyTextarea = replyItem.find('textarea');
688                 if (replyTextarea) {
689                     replyTextarea.focus();
690                 }
691             }
692         },
693
694         /**
695          * Setup function -- DOES NOT apply immediately.
696          *
697          * Uses 'on' rather than 'live' or 'bind', so applies to future as well as present items.
698          */
699         NoticeInlineReplySetup: function () {
700             $('#content .notice-reply').hide();
701             // Expand conversation links
702             $(document).on('click', 'li.notice-reply-comments a', function () {
703                     var url = $(this).attr('href');
704                     var area = $(this).closest('.threaded-replies');
705                     $.get(url, {ajax: 1}, function (data, textStatus, xhr) {
706                         var replies = $('.threaded-replies', data);
707                         if (replies.length) {
708                             area.replaceWith(document._importNode(replies[0], true));
709                         }
710                     });
711                     return false;
712                 });
713         },
714
715         /**
716          * Setup function -- DOES NOT trigger actions immediately.
717          *
718          * Sets up event handlers for repeat forms to toss up a confirmation
719          * popout before submitting.
720          *
721          * Uses 'on' rather than 'live' or 'bind', so applies to future as well as present items.
722          *
723          */
724         NoticeRepeat: function () {
725             $('body').on('click', '.form_repeat', function (e) {
726                 e.preventDefault();
727
728                 SN.U.NoticeRepeatConfirmation($(this));
729                 return false;
730             });
731         },
732
733         /**
734          * Shows a confirmation dialog box variant of the repeat button form.
735          * This seems to use a technique where the repeat form contains
736          * _both_ a standalone button _and_ text and buttons for a dialog.
737          * The dialog will close after its copy of the form is submitted,
738          * or if you click its 'close' button.
739          *
740          * The dialog is created by duplicating the original form and changing
741          * its style; while clever, this is hard to generalize and probably
742          * duplicates a lot of unnecessary HTML output.
743          *
744          * @fixme create confirmation dialogs through a generalized interface
745          * that can be reused instead of hardcoded text and styles.
746          *
747          * @param {jQuery} form
748          */
749         NoticeRepeatConfirmation: function (form) {
750             var submit_i = form.find('.submit');
751
752             var submit = submit_i.clone();
753             submit
754                 .addClass('submit_dialogbox')
755                 .removeClass('submit');
756             form.append(submit);
757             submit.on('click', function () { SN.U.FormXHR(form); return false; });
758
759             submit_i.hide();
760
761             form
762                 .addClass('dialogbox')
763                 .append('<button class="close">&#215;</button>')
764                 .closest('.notice-options')
765                     .addClass('opaque');
766
767             form.find('button.close').click(function () {
768                 $(this).remove();
769
770                 form
771                     .removeClass('dialogbox')
772                     .closest('.notice-options')
773                         .removeClass('opaque');
774
775                 form.find('.submit_dialogbox').remove();
776                 form.find('.submit').show();
777
778                 return false;
779             });
780         },
781
782         /**
783          * Setup function -- DOES NOT trigger actions immediately.
784          *
785          * Goes through all notices currently displayed and sets up attachment
786          * handling if needed.
787          */
788         NoticeAttachments: function () {
789             $('.notice a.attachment').each(function () {
790                 SN.U.NoticeWithAttachment($(this).closest('.notice'));
791             });
792         },
793
794         /**
795          * Setup function -- DOES NOT trigger actions immediately.
796          *
797          * Sets up special attachment link handling if needed. Currently this
798          * consists only of making the "more" button used for OStatus message
799          * cropping turn into an auto-expansion button that loads the full
800          * text from an attachment file.
801          *
802          * @param {jQuery} notice
803          */
804         NoticeWithAttachment: function (notice) {
805             if (notice.find('.attachment').length === 0) {
806                 return;
807             }
808
809                         $(document).on('click','.attachment.more',function () {
810                                 var m = $(this);
811                                 m.addClass(SN.C.S.Processing);
812                                 $.get(m.attr('href'), {ajax: 1}, function (data) {
813                                         m.parent('.e-content').html($(data).find('#attachment_view .e-content').html());
814                                 });
815
816                                 return false;
817                         });
818
819         },
820
821         /**
822          * Setup function -- DOES NOT trigger actions immediately.
823          *
824          * Sets up event handlers for the file-attachment widget in the
825          * new notice form. When a file is selected, a box will be added
826          * below the text input showing the filename and, if supported
827          * by the browser, a thumbnail preview.
828          *
829          * This preview box will also allow removing the attachment
830          * prior to posting.
831          *
832          * @param {jQuery} form
833          */
834         NoticeDataAttach: function (form) {
835             var i;
836             var NDA = form.find('input[type=file]');
837             NDA.change(function (event) {
838                 form.find('.attach-status').remove();
839
840                 var filename = $(this).val();
841                 if (!filename) {
842                     // No file -- we've been tricked!
843                     return false;
844                 }
845
846                 var attachStatus = $('<div class="attach-status ' + SN.C.S.Success + '"><code></code> <button class="close">&#215;</button></div>');
847                 attachStatus.find('code').text(filename);
848                 attachStatus.find('button').click(function () {
849                     attachStatus.remove();
850                     NDA.val('');
851
852                     return false;
853                 });
854                 form.append(attachStatus);
855
856                 if (typeof this.files === "object") {
857                     // Some newer browsers will let us fetch the files for preview.
858                     for (i = 0; i < this.files.length; i++) {
859                         SN.U.PreviewAttach(form, this.files[i]);
860                     }
861                 }
862             });
863         },
864
865         /**
866          * Get PHP's MAX_FILE_SIZE setting for this form;
867          * used to apply client-side file size limit checks.
868          *
869          * @param {jQuery} form
870          * @return int max size in bytes; 0 or negative means no limit
871          */
872         maxFileSize: function (form) {
873             var max = $(form).find('input[name=MAX_FILE_SIZE]').attr('value');
874             if (max) {
875                 return parseInt(max);
876             }
877             return 0;
878         },
879
880         /**
881          * For browsers with FileAPI support: make a thumbnail if possible,
882          * and append it into the attachment display widget.
883          *
884          * Known good:
885          * - Firefox 3.6.6, 4.0b7
886          * - Chrome 8.0.552.210
887          *
888          * Known ok metadata, can't get contents:
889          * - Safari 5.0.2
890          *
891          * Known fail:
892          * - Opera 10.63, 11 beta (no input.files interface)
893          *
894          * @param {jQuery} form
895          * @param {File} file
896          *
897          * @todo use configured thumbnail size
898          * @todo detect pixel size?
899          * @todo should we render a thumbnail to a canvas and then use the smaller image?
900          */
901         PreviewAttach: function (form, file) {
902             var tooltip = file.type + ' ' + Math.round(file.size / 1024) + 'KB';
903             var preview = true;
904
905             var blobAsDataURL;
906             if (window.createObjectURL !== undefined) {
907                 /**
908                  * createObjectURL lets us reference the file directly from an <img>
909                  * This produces a compact URL with an opaque reference to the file,
910                  * which we can reference immediately.
911                  *
912                  * - Firefox 3.6.6: no
913                  * - Firefox 4.0b7: no
914                  * - Safari 5.0.2: no
915                  * - Chrome 8.0.552.210: works!
916                  */
917                 blobAsDataURL = function (blob, callback) {
918                     callback(window.createObjectURL(blob));
919                 };
920             } else if (window.FileReader !== undefined) {
921                 /**
922                  * FileAPI's FileReader can build a data URL from a blob's contents,
923                  * but it must read the file and build it asynchronously. This means
924                  * we'll be passing a giant data URL around, which may be inefficient.
925                  *
926                  * - Firefox 3.6.6: works!
927                  * - Firefox 4.0b7: works!
928                  * - Safari 5.0.2: no
929                  * - Chrome 8.0.552.210: works!
930                  */
931                 blobAsDataURL = function (blob, callback) {
932                     var reader = new FileReader();
933                     reader.onload = function (event) {
934                         callback(reader.result);
935                     };
936                     reader.readAsDataURL(blob);
937                 };
938             } else {
939                 preview = false;
940             }
941
942             var imageTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/svg+xml'];
943             if ($.inArray(file.type, imageTypes) == -1) {
944                 // We probably don't know how to show the file.
945                 preview = false;
946             }
947
948             var maxSize = 8 * 1024 * 1024;
949             if (file.size > maxSize) {
950                 // Don't kill the browser trying to load some giant image.
951                 preview = false;
952             }
953
954             if (preview) {
955                 blobAsDataURL(file, function (url) {
956                     var img = $('<img>')
957                         .attr('title', tooltip)
958                         .attr('alt', tooltip)
959                         .attr('src', url)
960                         .attr('style', 'height: 120px');
961                     form.find('.attach-status').append(img);
962                 });
963             } else {
964                 var img = $('<div></div>').text(tooltip);
965                 form.find('.attach-status').append(img);
966             }
967         },
968
969         /**
970          * Setup function -- DOES NOT trigger actions immediately.
971          *
972          * Initializes state for the location-lookup features in the
973          * new-notice form. Seems to set up some event handlers for
974          * triggering lookups and using the new values.
975          *
976          * @param {jQuery} form
977          *
978          * @fixme tl;dr
979          * @fixme there's not good visual state update here, so users have a
980          *        hard time figuring out if it's working or fixing if it's wrong.
981          *
982          */
983         NoticeLocationAttach: function (form) {
984             // @fixme this should not be tied to the main notice form, as there may be multiple notice forms...
985             var NLat = form.find('[name=lat]');
986             var NLon = form.find('[name=lon]');
987             var NLNS = form.find('[name=location_ns]').val();
988             var NLID = form.find('[name=location_id]').val();
989             var NLN = ''; // @fixme
990             var NDGe = form.find('[name=notice_data-geo]');
991             var check = form.find('[name=notice_data-geo]');
992             var label = form.find('label.notice_data-geo');
993
994             function removeNoticeDataGeo(error) {
995                 label
996                     .attr('title', jQuery.trim(label.text()))
997                     .removeClass('checked');
998
999                 form.find('[name=lat]').val('');
1000                 form.find('[name=lon]').val('');
1001                 form.find('[name=location_ns]').val('');
1002                 form.find('[name=location_id]').val('');
1003                 form.find('[name=notice_data-geo]').prop('checked', false);
1004
1005                 $.cookie(SN.C.S.NoticeDataGeoCookie, 'disabled', { path: '/' });
1006
1007                 if (error) {
1008                     form.find('.geo_status_wrapper').removeClass('success').addClass('error');
1009                     form.find('.geo_status_wrapper .geo_status').text(error);
1010                 } else {
1011                     form.find('.geo_status_wrapper').remove();
1012                 }
1013             }
1014
1015             function getJSONgeocodeURL(geocodeURL, data) {
1016                 SN.U.NoticeGeoStatus(form, 'Looking up place name...');
1017                 $.getJSON(geocodeURL, data, function (location) {
1018                     var lns, lid, NLN_text;
1019
1020                     if (location.location_ns !== undefined) {
1021                         form.find('[name=location_ns]').val(location.location_ns);
1022                         lns = location.location_ns;
1023                     }
1024
1025                     if (location.location_id !== undefined) {
1026                         form.find('[name=location_id]').val(location.location_id);
1027                         lid = location.location_id;
1028                     }
1029
1030                     if (location.name === undefined) {
1031                         NLN_text = data.lat + ';' + data.lon;
1032                     } else {
1033                         NLN_text = location.name;
1034                     }
1035
1036                     SN.U.NoticeGeoStatus(form, NLN_text, data.lat, data.lon, location.url);
1037                     label
1038                         .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + NLN_text + ')');
1039
1040                     form.find('[name=lat]').val(data.lat);
1041                     form.find('[name=lon]').val(data.lon);
1042                     form.find('[name=location_ns]').val(lns);
1043                     form.find('[name=location_id]').val(lid);
1044                     form.find('[name=notice_data-geo]').prop('checked', true);
1045
1046                     var cookieValue = {
1047                         NLat: data.lat,
1048                         NLon: data.lon,
1049                         NLNS: lns,
1050                         NLID: lid,
1051                         NLN: NLN_text,
1052                         NLNU: location.url,
1053                         NDG: true
1054                     };
1055
1056                     $.cookie(SN.C.S.NoticeDataGeoCookie, JSON.stringify(cookieValue), { path: '/' });
1057                 });
1058             }
1059
1060             if (check.length > 0) {
1061                 if ($.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
1062                     check.prop('checked', false);
1063                 } else {
1064                     check.prop('checked', true);
1065                 }
1066
1067                 var NGW = form.find('.notice_data-geo_wrap');
1068                 var geocodeURL = NGW.attr('data-api');
1069
1070                 label.attr('title', label.text());
1071
1072                 check.change(function () {
1073                     if (check.prop('checked') === true || $.cookie(SN.C.S.NoticeDataGeoCookie) === null) {
1074                         label
1075                             .attr('title', NoticeDataGeo_text.ShareDisable)
1076                             .addClass('checked');
1077
1078                         if ($.cookie(SN.C.S.NoticeDataGeoCookie) === null || $.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
1079                             if (navigator.geolocation) {
1080                                 SN.U.NoticeGeoStatus(form, 'Requesting location from browser...');
1081                                 navigator.geolocation.getCurrentPosition(
1082                                     function (position) {
1083                                         form.find('[name=lat]').val(position.coords.latitude);
1084                                         form.find('[name=lon]').val(position.coords.longitude);
1085
1086                                         var data = {
1087                                             lat: position.coords.latitude,
1088                                             lon: position.coords.longitude,
1089                                             token: $('#token').val()
1090                                         };
1091
1092                                         getJSONgeocodeURL(geocodeURL, data);
1093                                     },
1094
1095                                     function (error) {
1096                                         switch(error.code) {
1097                                             case error.PERMISSION_DENIED:
1098                                                 removeNoticeDataGeo('Location permission denied.');
1099                                                 break;
1100                                             case error.TIMEOUT:
1101                                                 //$('#' + SN.C.S.NoticeDataGeo).prop('checked', false);
1102                                                 removeNoticeDataGeo('Location lookup timeout.');
1103                                                 break;
1104                                         }
1105                                     },
1106
1107                                     {
1108                                         timeout: 10000
1109                                     }
1110                                 );
1111                             } else {
1112                                 if (NLat.length > 0 && NLon.length > 0) {
1113                                     var data = {
1114                                         lat: NLat,
1115                                         lon: NLon,
1116                                         token: $('#token').val()
1117                                     };
1118
1119                                     getJSONgeocodeURL(geocodeURL, data);
1120                                 } else {
1121                                     removeNoticeDataGeo();
1122                                     check.remove();
1123                                     label.remove();
1124                                 }
1125                             }
1126                         } else {
1127                             try {
1128                                 var cookieValue = JSON.parse($.cookie(SN.C.S.NoticeDataGeoCookie));
1129
1130                                 form.find('[name=lat]').val(cookieValue.NLat);
1131                                 form.find('[name=lon]').val(cookieValue.NLon);
1132                                 form.find('[name=location_ns]').val(cookieValue.NLNS);
1133                                 form.find('[name=location_id]').val(cookieValue.NLID);
1134                                 form.find('[name=notice_data-geo]').prop('checked', cookieValue.NDG);
1135
1136                                SN.U.NoticeGeoStatus(form, cookieValue.NLN, cookieValue.NLat, cookieValue.NLon, cookieValue.NLNU);
1137                                 label
1138                                     .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + cookieValue.NLN + ')')
1139                                     .addClass('checked');
1140                             } catch (e) {
1141                                 console.log('Parsing error:', e);
1142                             }
1143                         }
1144                     } else {
1145                         removeNoticeDataGeo();
1146                     }
1147                 }).change();
1148             }
1149         },
1150
1151         /**
1152          * Create or update a geolocation status widget in this notice posting form.
1153          *
1154          * @param {jQuery} form
1155          * @param {String} status
1156          * @param {String} lat (optional)
1157          * @param {String} lon (optional)
1158          * @param {String} url (optional)
1159          */
1160         NoticeGeoStatus: function (form, status, lat, lon, url)
1161         {
1162             var wrapper = form.find('.geo_status_wrapper');
1163             if (wrapper.length == 0) {
1164                 wrapper = $('<div class="' + SN.C.S.Success + ' geo_status_wrapper"><button class="close" style="float:right">&#215;</button><div class="geo_status"></div></div>');
1165                 wrapper.find('button.close').click(function () {
1166                     form.find('[name=notice_data-geo]').prop('checked', false).change();
1167                     return false;
1168                 });
1169                 form.append(wrapper);
1170             }
1171             var label;
1172             if (url) {
1173                 label = $('<a></a>').attr('href', url);
1174             } else {
1175                 label = $('<span></span>');
1176             }
1177             label.text(status);
1178             if (lat || lon) {
1179                 var latlon = lat + ';' + lon;
1180                 label.attr('title', latlon);
1181                 if (!status) {
1182                     label.text(latlon)
1183                 }
1184             }
1185             wrapper.find('.geo_status').empty().append(label);
1186         },
1187
1188         /**
1189          * Setup function -- DOES NOT trigger actions immediately.
1190          *
1191          * Initializes event handlers for the "Send direct message" link on
1192          * profile pages, setting it up to display a dialog box when clicked.
1193          *
1194          * Unlike the repeat confirmation form, this appears to fetch
1195          * the form _from the original link target_, so the form itself
1196          * doesn't need to be in the current document.
1197          *
1198          * @fixme breaks ability to open link in new window?
1199          */
1200         NewDirectMessage: function () {
1201             NDM = $('.entity_send-a-message a');
1202             NDM.attr({'href': NDM.attr('href') + '&ajax=1'});
1203             NDM.on('click', function () {
1204                 var NDMF = $('.entity_send-a-message form');
1205                 if (NDMF.length === 0) {
1206                     $(this).addClass(SN.C.S.Processing);
1207                     $.get(NDM.attr('href'), null, function (data) {
1208                         $('.entity_send-a-message').append(document._importNode($('form', data)[0], true));
1209                         NDMF = $('.entity_send-a-message .form_notice');
1210                         SN.U.FormNoticeXHR(NDMF);
1211                         SN.U.FormNoticeEnhancements(NDMF);
1212                         NDMF.append('<button class="close">&#215;</button>');
1213                         $('.entity_send-a-message button').click(function () {
1214                             NDMF.hide();
1215                             return false;
1216                         });
1217                         NDM.removeClass(SN.C.S.Processing);
1218                     });
1219                 } else {
1220                     NDMF.show();
1221                     $('.entity_send-a-message textarea').focus();
1222                 }
1223                 return false;
1224             });
1225         },
1226
1227         /**
1228          * Return a date object with the current local time on the
1229          * given year, month, and day.
1230          *
1231          * @param {number} year: 4-digit year
1232          * @param {number} month: 0 == January
1233          * @param {number} day: 1 == 1
1234          * @return {Date}
1235          */
1236         GetFullYear: function (year, month, day) {
1237             var date = new Date();
1238             date.setFullYear(year, month, day);
1239
1240             return date;
1241         },
1242
1243         /**
1244          * Some sort of object interface for storing some structured
1245          * information in a cookie.
1246          *
1247          * Appears to be used to save the last-used login nickname?
1248          * That's something that browsers usually take care of for us
1249          * these days, do we really need to do it? Does anything else
1250          * use this interface?
1251          *
1252          * @fixme what is this?
1253          * @fixme should this use non-cookie local storage when available?
1254          */
1255         StatusNetInstance: {
1256             /**
1257              * @fixme what is this?
1258              */
1259             Set: function (value) {
1260                 var SNI = SN.U.StatusNetInstance.Get();
1261                 if (SNI !== null) {
1262                     value = $.extend(SNI, value);
1263                 }
1264
1265                 $.cookie(
1266                     SN.C.S.StatusNetInstance,
1267                     JSON.stringify(value),
1268                     {
1269                         path: '/',
1270                         expires: SN.U.GetFullYear(2029, 0, 1)
1271                     });
1272             },
1273
1274             /**
1275              * @fixme what is this?
1276              */
1277             Get: function () {
1278                 var cookieValue = $.cookie(SN.C.S.StatusNetInstance);
1279                 if (cookieValue !== undefined) {
1280                     return JSON.parse(cookieValue);
1281                 }
1282                 return null;
1283             },
1284
1285             /**
1286              * @fixme what is this?
1287              */
1288             Delete: function () {
1289                 $.cookie(SN.C.S.StatusNetInstance, null);
1290             }
1291         },
1292
1293         /**
1294          * Check if the current page is a timeline where the current user's
1295          * posts should be displayed immediately on success.
1296          *
1297          * @fixme this should be done in a saner way, with machine-readable
1298          * info about what page we're looking at.
1299          *
1300          * @param {DOMElement} notice: HTML chunk with formatted notice
1301          * @return boolean
1302          */
1303         belongsOnTimeline: function (notice) {
1304             var action = $("body").attr('id');
1305             if (action == 'public') {
1306                 return true;
1307             }
1308
1309             var profileLink = $('#nav_profile a').attr('href');
1310             if (profileLink) {
1311                 var authorUrl = $(notice).find('.h-card.p-author').attr('href');
1312                 if (authorUrl == profileLink) {
1313                     if (action == 'all' || action == 'showstream') {
1314                         // Posts always show on your own friends and profile streams.
1315                         return true;
1316                     }
1317                 }
1318             }
1319
1320             // @fixme tag, group, reply timelines should be feasible as well.
1321             // Mismatch between id-based and name-based user/group links currently complicates
1322             // the lookup, since all our inline mentions contain the absolute links but the
1323             // UI links currently on the page use malleable names.
1324             
1325             return false;
1326         },
1327
1328         /**
1329          * Switch to another active input sub-form.
1330          * This will hide the current form (if any), show the new one, and
1331          * update the input type tab selection state.
1332          *
1333          * @param {String} tag
1334          */
1335         switchInputFormTab: function (tag, setFocus) {
1336             if (typeof setFocus === 'undefined') { setFocus = true; }
1337             // The one that's current isn't current anymore
1338             $('.input_form_nav_tab.current').removeClass('current');
1339             if (tag != null) {
1340                 $('#input_form_nav_' + tag).addClass('current');
1341             }
1342
1343             // Don't remove 'current' if we also have the "nonav" class.
1344             // An example would be the message input form. removing
1345             // 'current' will cause the form to vanish from the page.
1346             var nonav = $('.input_form.current.nonav');
1347             if (nonav.length > 0) {
1348                 return;
1349             }
1350
1351             $('.input_form.current').removeClass('current');
1352             if (tag == null) {
1353                 // we're done here, no new inputform to focus on
1354                 return false;
1355             }
1356
1357             var noticeForm = $('#input_form_' + tag)
1358                     .addClass('current')
1359                     .find('.ajax-notice').each(function () {
1360                         var form = $(this);
1361                         SN.Init.NoticeFormSetup(form);
1362                     });
1363             if (setFocus) {
1364                 noticeForm.find('.notice_data-text').focus();
1365             }
1366
1367             return false;
1368         },
1369
1370         showMoreMenuItems: function (menuid) {
1371             $('#' + menuid + ' .more_link').remove();
1372             var selector = '#' + menuid + ' .extended_menu';
1373             var extended = $(selector);
1374             extended.removeClass('extended_menu');
1375             return void(0);
1376         }
1377     },
1378
1379     Init: {
1380         /**
1381          * If user is logged in, run setup code for the new notice form:
1382          *
1383          *  - char counter
1384          *  - AJAX submission
1385          *  - location events
1386          *  - file upload events
1387          */
1388         NoticeForm: function () {
1389             if ($('body.user_in').length > 0) {
1390                 // SN.Init.NoticeFormSetup() will get run
1391                 // when forms get displayed for the first time...
1392
1393                 // Initialize the input form field
1394                 $('#input_form_nav .input_form_nav_tab.current').each(function () {
1395                     current_tab_id = $(this).attr('id').substring('input_form_nav_'.length);
1396                     SN.U.switchInputFormTab(current_tab_id, false);
1397                 });
1398
1399                 // Make inline reply forms self-close when clicking out.
1400                 $('body').on('click', function (e) {
1401                     var openReplies = $('li.notice-reply');
1402                     if (openReplies.length > 0) {
1403                         var target = $(e.target);
1404                         openReplies.each(function () {
1405                             // Did we click outside this one?
1406                             var replyItem = $(this);
1407                             if (replyItem.has(e.target).length == 0) {
1408                                 var textarea = replyItem.find('.notice_data-text:first');
1409                                 var cur = $.trim(textarea.val());
1410                                 // Only close if there's been no edit.
1411                                 if (cur == '' || cur == textarea.data('initialText')) {
1412                                     var parentNotice = replyItem.closest('li.notice');
1413                                     replyItem.hide();
1414                                     parentNotice.find('li.notice-reply-placeholder').show();
1415                                 }
1416                             }
1417                         });
1418                     }
1419                 });
1420
1421                 // Infield labels for notice form inputs.
1422                 $('.input_forms fieldset fieldset label').inFieldLabels({ fadeOpacity:0 });
1423             }
1424         },
1425
1426         /**
1427          * Encapsulate notice form setup for a single form.
1428          * Plugins can add extra setup by monkeypatching this
1429          * function.
1430          *
1431          * @param {jQuery} form
1432          */
1433         NoticeFormSetup: function (form) {
1434             if (!form.data('NoticeFormSetup')) {
1435                 SN.U.NoticeLocationAttach(form);
1436                 SN.U.FormNoticeXHR(form);
1437                 SN.U.FormNoticeEnhancements(form);
1438                 SN.U.NoticeDataAttach(form);
1439                 form.data('NoticeFormSetup', true);
1440             }
1441         },
1442
1443         /**
1444          * Run setup code for notice timeline views items:
1445          *
1446          * - AJAX submission for fave/repeat/reply (if logged in)
1447          * - Attachment link extras ('more' links)
1448          */
1449         Notices: function () {
1450             if ($('body.user_in').length > 0) {
1451                 var masterForm = $('.form_notice:first');
1452                 if (masterForm.length > 0) {
1453                     SN.C.I.NoticeFormMaster = document._importNode(masterForm[0], true);
1454                 }
1455                 SN.U.NoticeRepeat();
1456                 SN.U.NoticeReply();
1457                 SN.U.NoticeInlineReplySetup();
1458             }
1459
1460             SN.U.NoticeAttachments();
1461         },
1462
1463         /**
1464          * Run setup code for user & group profile page header area if logged in:
1465          *
1466          * - AJAX submission for sub/unsub/join/leave/nudge
1467          * - AJAX form popup for direct-message
1468          */
1469         EntityActions: function () {
1470             if ($('body.user_in').length > 0) {
1471                 $(document).on('click', '.form_user_subscribe', function () { SN.U.FormXHR($(this)); return false; });
1472                 $(document).on('click', '.form_user_unsubscribe', function () { SN.U.FormXHR($(this)); return false; });
1473                 $(document).on('click', '.form_group_join', function () { SN.U.FormXHR($(this)); return false; });
1474                 $(document).on('click', '.form_group_leave', function () { SN.U.FormXHR($(this)); return false; });
1475                 $(document).on('click', '.form_user_nudge', function () { SN.U.FormXHR($(this)); return false; });
1476                 $(document).on('click', '.form_peopletag_subscribe', function () { SN.U.FormXHR($(this)); return false; });
1477                 $(document).on('click', '.form_peopletag_unsubscribe', function () { SN.U.FormXHR($(this)); return false; });
1478                 $(document).on('click', '.form_user_add_peopletag', function () { SN.U.FormXHR($(this)); return false; });
1479                 $(document).on('click', '.form_user_remove_peopletag', function () { SN.U.FormXHR($(this)); return false; });
1480
1481                 SN.U.NewDirectMessage();
1482             }
1483         },
1484
1485         ProfileSearch: function () {
1486             if ($('body.user_in').length > 0) {
1487                 $(document).on('click', '.form_peopletag_edit_user_search input.submit', function () {
1488                     SN.U.FormProfileSearchXHR($(this).parents('form')); return false;
1489                 });
1490             }
1491         },
1492
1493         /**
1494          * Run setup code for login form:
1495          *
1496          * - loads saved last-used-nickname from cookie
1497          * - sets event handler to save nickname to cookie on submit
1498          *
1499          * @fixme is this necessary? Browsers do their own form saving these days.
1500          */
1501         Login: function () {
1502             if (SN.U.StatusNetInstance.Get() !== null) {
1503                 var nickname = SN.U.StatusNetInstance.Get().Nickname;
1504                 if (nickname !== null) {
1505                     $('#form_login #nickname').val(nickname);
1506                 }
1507             }
1508
1509             $('#form_login').on('submit', function () {
1510                 SN.U.StatusNetInstance.Set({Nickname: $('#form_login #nickname').val()});
1511                 return true;
1512             });
1513         },
1514
1515         /**
1516          * Run setup for the ajax people tags editor
1517          *
1518          * - show edit button
1519          * - set event handle for click on edit button
1520          *   - loads people tag autocompletion data if not already present
1521          *     or if it is stale.
1522          *
1523          */
1524         PeopleTags: function () {
1525             $('.user_profile_tags .editable').append($('<button class="peopletags_edit_button"/>'));
1526
1527             $(document).on('click', '.peopletags_edit_button', function () {
1528                 var form = $(this).parents('dd').eq(0).find('form');
1529                 // We can buy time from the above animation
1530
1531                 $.ajax({
1532                     url: _peopletagAC,
1533                     dataType: 'json',
1534                     data: {token: $('#token').val()},
1535                     ifModified: true,
1536                     success: function (data) {
1537                         // item.label is used to match
1538                         for (i=0; i < data.length; i++) {
1539                             data[i].label = data[i].tag;
1540                         }
1541
1542                         SN.C.PtagACData = data;
1543                     }
1544                 });
1545
1546                 $(this).parents('ul').eq(0).fadeOut(200, function () {form.fadeIn(200).find('input#tags')});
1547             });
1548
1549             $(document).on('click', '.user_profile_tags form .submit', function () {
1550                 SN.U.FormPeopletagsXHR($(this).parents('form')); return false;
1551             });
1552         },
1553
1554         /**
1555          * Set up any generic 'ajax' form so it submits via AJAX with auto-replacement.
1556          */
1557         AjaxForms: function () {
1558             $(document).on('submit', 'form.ajax', function () {
1559                 SN.U.FormXHR($(this));
1560                 return false;
1561             });
1562             $(document).on('click', 'form.ajax input[type=submit]', function () {
1563                 // Some forms rely on knowing which submit button was clicked.
1564                 // Save a hidden input field which'll be picked up during AJAX
1565                 // submit...
1566                 var button = $(this);
1567                 var form = button.closest('form');
1568                 form.find('.hidden-submit-button').remove();
1569                 $('<input class="hidden-submit-button" type="hidden" />')
1570                     .attr('name', button.attr('name'))
1571                     .val(button.val())
1572                     .appendTo(form);
1573             });
1574         },
1575
1576         /**
1577          * Add logic to any file upload forms to handle file size limits,
1578          * on browsers that support basic FileAPI.
1579          */
1580         UploadForms: function () {
1581             $('input[type=file]').change(function (event) {
1582                 if (typeof this.files === "object" && this.files.length > 0) {
1583                     var size = 0;
1584                     for (var i = 0; i < this.files.length; i++) {
1585                         size += this.files[i].size;
1586                     }
1587
1588                     var max = SN.U.maxFileSize($(this.form));
1589                     if (max > 0 && size > max) {
1590                         var msg = 'File too large: maximum upload size is %d bytes.';
1591                         alert(msg.replace('%d', max));
1592
1593                         // Clear the files.
1594                         $(this).val('');
1595                         event.preventDefault();
1596                         return false;
1597                     }
1598                 }
1599             });
1600         },
1601
1602         CheckBoxes: function () {
1603             $("span[class='checkbox-wrapper']").addClass("unchecked");
1604             $(".checkbox-wrapper").click(function () {
1605                 if ($(this).children("input").prop("checked")) {
1606                     // uncheck
1607                     $(this).children("input").prop("checked", false);
1608                     $(this).removeClass("checked");
1609                     $(this).addClass("unchecked");
1610                     $(this).children("label").text("Private?");
1611                 } else {
1612                     // check
1613                     $(this).children("input").prop("checked", true);
1614                     $(this).removeClass("unchecked");
1615                     $(this).addClass("checked");
1616                     $(this).children("label").text("Private");
1617                 }
1618             });
1619         }
1620     }
1621 };
1622
1623 /**
1624  * Run initialization functions on DOM-ready.
1625  *
1626  * Note that if we're waiting on other scripts to load, this won't happen
1627  * until that's done. To load scripts asynchronously without delaying setup,
1628  * don't start them loading until after DOM-ready time!
1629  */
1630 $(function () {
1631     SN.Init.AjaxForms();
1632     SN.Init.UploadForms();
1633     SN.Init.CheckBoxes();
1634     if ($('.' + SN.C.S.FormNotice).length > 0) {
1635         SN.Init.NoticeForm();
1636     }
1637     if ($('#content .notices').length > 0) {
1638         SN.Init.Notices();
1639     }
1640     if ($('#content .entity_actions').length > 0) {
1641         SN.Init.EntityActions();
1642     }
1643     if ($('#form_login').length > 0) {
1644         SN.Init.Login();
1645     }
1646     if ($('#profile_search_results').length > 0) {
1647         SN.Init.ProfileSearch();
1648     }
1649     if ($('.user_profile_tags .editable').length > 0) {
1650         SN.Init.PeopleTags();
1651     }
1652 });
1653