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