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