]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - js/util.js
47b8bbe6caaef32bbdc2ab4dc297224a05defcd8
[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                     $('#'+SN.C.S.NoticeDataGeo).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 = $('#'+SN.C.S.NoticeDataGeo).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 = $('#'+SN.C.S.NoticeDataGeo).attr('checked', false).attr('checked');
467             }
468             else {
469                 SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).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          * @fixme tl;dr
963          * @fixme there's not good visual state update here, so users have a
964          *        hard time figuring out if it's working or fixing if it's wrong.
965          *
966          */
967         NoticeLocationAttach: function() {
968             // @fixme this should not be tied to the main notice form, as there may be multiple notice forms...
969             var NLat = $('#'+SN.C.S.NoticeLat).val();
970             var NLon = $('#'+SN.C.S.NoticeLon).val();
971             var NLNS = $('#'+SN.C.S.NoticeLocationNs).val();
972             var NLID = $('#'+SN.C.S.NoticeLocationId).val();
973             var NLN = $('#'+SN.C.S.NoticeGeoName).text();
974             var NDGe = $('#'+SN.C.S.NoticeDataGeo);
975
976             function removeNoticeDataGeo(error) {
977                 $('label[for='+SN.C.S.NoticeDataGeo+']')
978                     .attr('title', jQuery.trim($('label[for='+SN.C.S.NoticeDataGeo+']').text()))
979                     .removeClass('checked');
980
981                 $('.form_notice [name=lat]').val('');
982                 $('.form_notice [name=lon]').val('');
983                 $('.form_notice [name=location_ns]').val('');
984                 $('.form_notice [name=location_id]').val('');
985                 $('#'+SN.C.S.NoticeDataGeo).attr('checked', false);
986
987                 $.cookie(SN.C.S.NoticeDataGeoCookie, 'disabled', { path: '/' });
988
989                 if (error) {
990                     $('.geo_status_wrapper').removeClass('success').addClass('error');
991                     $('.geo_status_wrapper .geo_status').text(error);
992                 } else {
993                     $('.geo_status_wrapper').remove();
994                 }
995             }
996
997             function getJSONgeocodeURL(geocodeURL, data) {
998                 SN.U.NoticeGeoStatus('Looking up place name...');
999                 $.getJSON(geocodeURL, data, function(location) {
1000                     var lns, lid;
1001
1002                     if (typeof(location.location_ns) != 'undefined') {
1003                         $('#'+SN.C.S.NoticeLocationNs).val(location.location_ns);
1004                         lns = location.location_ns;
1005                     }
1006
1007                     if (typeof(location.location_id) != 'undefined') {
1008                         $('#'+SN.C.S.NoticeLocationId).val(location.location_id);
1009                         lid = location.location_id;
1010                     }
1011
1012                     if (typeof(location.name) == 'undefined') {
1013                         NLN_text = data.lat + ';' + data.lon;
1014                     }
1015                     else {
1016                         NLN_text = location.name;
1017                     }
1018
1019                     SN.U.NoticeGeoStatus(NLN_text, data.lat, data.lon, location.url);
1020                     $('label[for='+SN.C.S.NoticeDataGeo+']')
1021                         .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + NLN_text + ')');
1022
1023                     $('.form_notice [name=lat]').val(data.lat);
1024                     $('.form_notice [name=lon]').val(data.lon);
1025                     $('.form_notice [name=location_ns]').val(lns);
1026                     $('.form_notice [name=location_id]').val(lid);
1027                     $('#'+SN.C.S.NoticeDataGeo).attr('checked', true);
1028
1029                     var cookieValue = {
1030                         NLat: data.lat,
1031                         NLon: data.lon,
1032                         NLNS: lns,
1033                         NLID: lid,
1034                         NLN: NLN_text,
1035                         NLNU: location.url,
1036                         NDG: true
1037                     };
1038
1039                     $.cookie(SN.C.S.NoticeDataGeoCookie, JSON.stringify(cookieValue), { path: '/' });
1040                 });
1041             }
1042
1043             if (NDGe.length > 0) {
1044                 if ($.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
1045                     NDGe.attr('checked', false);
1046                 }
1047                 else {
1048                     NDGe.attr('checked', true);
1049                 }
1050
1051                 var NGW = $('#notice_data-geo_wrap');
1052                 var geocodeURL = NGW.attr('title');
1053                 NGW.removeAttr('title');
1054
1055                 $('label[for='+SN.C.S.NoticeDataGeo+']')
1056                     .attr('title', jQuery.trim($('label[for='+SN.C.S.NoticeDataGeo+']').text()));
1057
1058                 NDGe.change(function() {
1059                     if ($('#'+SN.C.S.NoticeDataGeo).attr('checked') === true || $.cookie(SN.C.S.NoticeDataGeoCookie) === null) {
1060                         $('label[for='+SN.C.S.NoticeDataGeo+']')
1061                             .attr('title', NoticeDataGeo_text.ShareDisable)
1062                             .addClass('checked');
1063
1064                         if ($.cookie(SN.C.S.NoticeDataGeoCookie) === null || $.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
1065                             if (navigator.geolocation) {
1066                                 SN.U.NoticeGeoStatus('Requesting location from browser...');
1067                                 navigator.geolocation.getCurrentPosition(
1068                                     function(position) {
1069                                         $('.form_notice [name=lat]').val(position.coords.latitude);
1070                                         $('.form_notice [name=lon]').val(position.coords.longitude);
1071
1072                                         var data = {
1073                                             lat: position.coords.latitude,
1074                                             lon: position.coords.longitude,
1075                                             token: $('#token').val()
1076                                         };
1077
1078                                         getJSONgeocodeURL(geocodeURL, data);
1079                                     },
1080
1081                                     function(error) {
1082                                         switch(error.code) {
1083                                             case error.PERMISSION_DENIED:
1084                                                 removeNoticeDataGeo('Location permission denied.');
1085                                                 break;
1086                                             case error.TIMEOUT:
1087                                                 //$('#'+SN.C.S.NoticeDataGeo).attr('checked', false);
1088                                                 removeNoticeDataGeo('Location lookup timeout.');
1089                                                 break;
1090                                         }
1091                                     },
1092
1093                                     {
1094                                         timeout: 10000
1095                                     }
1096                                 );
1097                             }
1098                             else {
1099                                 if (NLat.length > 0 && NLon.length > 0) {
1100                                     var data = {
1101                                         lat: NLat,
1102                                         lon: NLon,
1103                                         token: $('#token').val()
1104                                     };
1105
1106                                     getJSONgeocodeURL(geocodeURL, data);
1107                                 }
1108                                 else {
1109                                     removeNoticeDataGeo();
1110                                     $('#'+SN.C.S.NoticeDataGeo).remove();
1111                                     $('label[for='+SN.C.S.NoticeDataGeo+']').remove();
1112                                 }
1113                             }
1114                         }
1115                         else {
1116                             var cookieValue = JSON.parse($.cookie(SN.C.S.NoticeDataGeoCookie));
1117
1118                             $('.form_notice [name=lat]').val(cookieValue.NLat);
1119                             $('.form_notice [name=lon]').val(cookieValue.NLon);
1120                             $('.form_notice [name=location_ns]').val(cookieValue.NLNS);
1121                             $('.form_notice [name=location_id]').val(cookieValue.NLID);
1122                             $('#'+SN.C.S.NoticeDataGeo).attr('checked', cookieValue.NDG);
1123
1124                             SN.U.NoticeGeoStatus(cookieValue.NLN, cookieValue.NLat, cookieValue.NLon, cookieValue.NLNU);
1125                             $('label[for='+SN.C.S.NoticeDataGeo+']')
1126                                 .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + cookieValue.NLN + ')')
1127                                 .addClass('checked');
1128                         }
1129                     }
1130                     else {
1131                         removeNoticeDataGeo();
1132                     }
1133                 }).change();
1134             }
1135         },
1136
1137         /**
1138          * Create or update a geolocation status widget in this notice posting form.
1139          *
1140          * @param {String} status
1141          * @param {String} lat (optional)
1142          * @param {String} lon (optional)
1143          * @param {String} url (optional)
1144          */
1145         NoticeGeoStatus: function(status, lat, lon, url)
1146         {
1147             var form = $('#form_notice');
1148             var wrapper = form.find('.geo_status_wrapper');
1149             if (wrapper.length == 0) {
1150                 wrapper = $('<div class="'+SN.C.S.Success+' geo_status_wrapper"><button class="close" style="float:right">&#215;</button><div class="geo_status"></div></div>');
1151                 wrapper.find('button.close').click(function() {
1152                     $('#'+SN.C.S.NoticeDataGeo).removeAttr('checked').change();
1153                 });
1154                 form.append(wrapper);
1155             }
1156             var label;
1157             if (url) {
1158                 label = $('<a></a>').attr('href', url);
1159             } else {
1160                 label = $('<span></span>');
1161             }
1162             label.text(status);
1163             if (lat || lon) {
1164                 var latlon = lat + ';' + lon;
1165                 label.attr('title', latlon);
1166                 if (!status) {
1167                     label.text(latlon)
1168                 }
1169             }
1170             wrapper.find('.geo_status').empty().append(label);
1171         },
1172
1173         /**
1174          * Setup function -- DOES NOT trigger actions immediately.
1175          *
1176          * Initializes event handlers for the "Send direct message" link on
1177          * profile pages, setting it up to display a dialog box when clicked.
1178          *
1179          * Unlike the repeat confirmation form, this appears to fetch
1180          * the form _from the original link target_, so the form itself
1181          * doesn't need to be in the current document.
1182          *
1183          * @fixme breaks ability to open link in new window?
1184          */
1185         NewDirectMessage: function() {
1186             NDM = $('.entity_send-a-message a');
1187             NDM.attr({'href':NDM.attr('href')+'&ajax=1'});
1188             NDM.bind('click', function() {
1189                 var NDMF = $('.entity_send-a-message form');
1190                 if (NDMF.length === 0) {
1191                     $(this).addClass(SN.C.S.Processing);
1192                     $.get(NDM.attr('href'), null, function(data) {
1193                         $('.entity_send-a-message').append(document._importNode($('form', data)[0], true));
1194                         NDMF = $('.entity_send-a-message .form_notice');
1195                         SN.U.FormNoticeXHR(NDMF);
1196                         SN.U.FormNoticeEnhancements(NDMF);
1197                         NDMF.append('<button class="close">&#215;</button>');
1198                         $('.entity_send-a-message button').click(function(){
1199                             NDMF.hide();
1200                             return false;
1201                         });
1202                         NDM.removeClass(SN.C.S.Processing);
1203                     });
1204                 }
1205                 else {
1206                     NDMF.show();
1207                     $('.entity_send-a-message textarea').focus();
1208                 }
1209                 return false;
1210             });
1211         },
1212
1213         /**
1214          * Return a date object with the current local time on the
1215          * given year, month, and day.
1216          *
1217          * @param {number} year: 4-digit year
1218          * @param {number} month: 0 == January
1219          * @param {number} day: 1 == 1
1220          * @return {Date}
1221          */
1222         GetFullYear: function(year, month, day) {
1223             var date = new Date();
1224             date.setFullYear(year, month, day);
1225
1226             return date;
1227         },
1228
1229         /**
1230          * Some sort of object interface for storing some structured
1231          * information in a cookie.
1232          *
1233          * Appears to be used to save the last-used login nickname?
1234          * That's something that browsers usually take care of for us
1235          * these days, do we really need to do it? Does anything else
1236          * use this interface?
1237          *
1238          * @fixme what is this?
1239          * @fixme should this use non-cookie local storage when available?
1240          */
1241         StatusNetInstance: {
1242             /**
1243              * @fixme what is this?
1244              */
1245             Set: function(value) {
1246                 var SNI = SN.U.StatusNetInstance.Get();
1247                 if (SNI !== null) {
1248                     value = $.extend(SNI, value);
1249                 }
1250
1251                 $.cookie(
1252                     SN.C.S.StatusNetInstance,
1253                     JSON.stringify(value),
1254                     {
1255                         path: '/',
1256                         expires: SN.U.GetFullYear(2029, 0, 1)
1257                     });
1258             },
1259
1260             /**
1261              * @fixme what is this?
1262              */
1263             Get: function() {
1264                 var cookieValue = $.cookie(SN.C.S.StatusNetInstance);
1265                 if (cookieValue !== null) {
1266                     return JSON.parse(cookieValue);
1267                 }
1268                 return null;
1269             },
1270
1271             /**
1272              * @fixme what is this?
1273              */
1274             Delete: function() {
1275                 $.cookie(SN.C.S.StatusNetInstance, null);
1276             }
1277         },
1278
1279         /**
1280          * Check if the current page is a timeline where the current user's
1281          * posts should be displayed immediately on success.
1282          *
1283          * @fixme this should be done in a saner way, with machine-readable
1284          * info about what page we're looking at.
1285          *
1286          * @param {DOMElement} notice: HTML chunk with formatted notice
1287          * @return boolean
1288          */
1289         belongsOnTimeline: function(notice) {
1290             var action = $("body").attr('id');
1291             if (action == 'public') {
1292                 return true;
1293             }
1294
1295             var profileLink = $('#nav_profile a').attr('href');
1296             if (profileLink) {
1297                 var authorUrl = $(notice).find('.entry-title .author a.url').attr('href');
1298                 if (authorUrl == profileLink) {
1299                     if (action == 'all' || action == 'showstream') {
1300                         // Posts always show on your own friends and profile streams.
1301                         return true;
1302                     }
1303                 }
1304             }
1305
1306             // @fixme tag, group, reply timelines should be feasible as well.
1307             // Mismatch between id-based and name-based user/group links currently complicates
1308             // the lookup, since all our inline mentions contain the absolute links but the
1309             // UI links currently on the page use malleable names.
1310
1311             return false;
1312         }
1313     },
1314
1315     Init: {
1316         /**
1317          * If user is logged in, run setup code for the new notice form:
1318          *
1319          *  - char counter
1320          *  - AJAX submission
1321          *  - location events
1322          *  - file upload events
1323          */
1324         NoticeForm: function() {
1325             if ($('body.user_in').length > 0) {
1326                 SN.U.NoticeLocationAttach();
1327
1328                 $('.'+SN.C.S.FormNotice).each(function() {
1329                     SN.U.FormNoticeXHR($(this));
1330                     SN.U.FormNoticeEnhancements($(this));
1331                     SN.U.NoticeDataAttach($(this));
1332                 });
1333             }
1334         },
1335
1336         /**
1337          * Run setup code for notice timeline views items:
1338          *
1339          * - AJAX submission for fave/repeat/reply (if logged in)
1340          * - Attachment link extras ('more' links)
1341          */
1342         Notices: function() {
1343             if ($('body.user_in').length > 0) {
1344                 SN.U.NoticeFavor();
1345                 SN.U.NoticeRepeat();
1346                 SN.U.NoticeReply();
1347                 SN.U.NoticeInlineReplySetup();
1348             }
1349
1350             SN.U.NoticeAttachments();
1351         },
1352
1353         /**
1354          * Run setup code for user & group profile page header area if logged in:
1355          *
1356          * - AJAX submission for sub/unsub/join/leave/nudge
1357          * - AJAX form popup for direct-message
1358          */
1359         EntityActions: function() {
1360             if ($('body.user_in').length > 0) {
1361                 $('.form_user_subscribe').live('click', function() { SN.U.FormXHR($(this)); return false; });
1362                 $('.form_user_unsubscribe').live('click', function() { SN.U.FormXHR($(this)); return false; });
1363                 $('.form_group_join').live('click', function() { SN.U.FormXHR($(this)); return false; });
1364                 $('.form_group_leave').live('click', function() { SN.U.FormXHR($(this)); return false; });
1365                 $('.form_user_nudge').live('click', function() { SN.U.FormXHR($(this)); return false; });
1366
1367                 SN.U.NewDirectMessage();
1368             }
1369         },
1370
1371         /**
1372          * Run setup code for login form:
1373          *
1374          * - loads saved last-used-nickname from cookie
1375          * - sets event handler to save nickname to cookie on submit
1376          *
1377          * @fixme is this necessary? Browsers do their own form saving these days.
1378          */
1379         Login: function() {
1380             if (SN.U.StatusNetInstance.Get() !== null) {
1381                 var nickname = SN.U.StatusNetInstance.Get().Nickname;
1382                 if (nickname !== null) {
1383                     $('#form_login #nickname').val(nickname);
1384                 }
1385             }
1386
1387             $('#form_login').bind('submit', function() {
1388                 SN.U.StatusNetInstance.Set({Nickname: $('#form_login #nickname').val()});
1389                 return true;
1390             });
1391         },
1392
1393         /**
1394          * Add logic to any file upload forms to handle file size limits,
1395          * on browsers that support basic FileAPI.
1396          */
1397         UploadForms: function () {
1398             $('input[type=file]').change(function(event) {
1399                 if (typeof this.files == "object" && this.files.length > 0) {
1400                     var size = 0;
1401                     for (var i = 0; i < this.files.length; i++) {
1402                         size += this.files[i].size;
1403                     }
1404
1405                     var max = SN.U.maxFileSize($(this.form));
1406                     if (max > 0 && size > max) {
1407                         var msg = 'File too large: maximum upload size is %d bytes.';
1408                         alert(msg.replace('%d', max));
1409
1410                         // Clear the files.
1411                         $(this).val('');
1412                         event.preventDefault();
1413                         return false;
1414                     }
1415                 }
1416             });
1417         }
1418     }
1419 };
1420
1421 /**
1422  * Run initialization functions on DOM-ready.
1423  *
1424  * Note that if we're waiting on other scripts to load, this won't happen
1425  * until that's done. To load scripts asynchronously without delaying setup,
1426  * don't start them loading until after DOM-ready time!
1427  */
1428 $(document).ready(function(){
1429     SN.Init.UploadForms();
1430     if ($('.'+SN.C.S.FormNotice).length > 0) {
1431         SN.Init.NoticeForm();
1432     }
1433     if ($('#content .notices').length > 0) {
1434         SN.Init.Notices();
1435     }
1436     if ($('#content .entity_actions').length > 0) {
1437         SN.Init.EntityActions();
1438     }
1439     if ($('#form_login').length > 0) {
1440         SN.Init.Login();
1441     }
1442 });