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