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