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