2 * StatusNet - a distributed open-source microblogging tool
3 * Copyright (C) 2008, StatusNet, Inc.
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.
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.
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/>.
18 * @category UI interaction
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/
28 var SN = { // StatusNet
31 CounterBlackout: false,
33 PatternUsername: /^[0-9a-zA-Z\-_.]*$/,
34 HTTP20x30x: [200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307]
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.
42 * In theory, minification could reduce them to shorter variable names,
43 * but at present that doesn't happen with yui-compressor.
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'
67 * Map of localized message strings exported to script from the PHP
68 * side via Action::getScriptMessages().
70 * Retrieve them via SN.msg(); this array is an implementation detail.
77 * Grabs a localized string that's been previously exported to us
78 * from server-side code via Action::getScriptMessages().
80 * @example alert(SN.msg('coolplugin-failed'));
82 * @param {String} key: string key name to pull from message index
83 * @return matching localized message string
86 if (typeof SN.messages[key] == "undefined") {
87 return '[' + key + ']';
89 return SN.messages[key];
95 * Setup function -- DOES NOT trigger actions immediately.
97 * Sets up event handlers on the new notice form.
99 * @param {jQuery} form: jQuery object whose first matching element is the form
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;
108 jQuery.data(form[0], 'ElementData', {MaxLength:MaxLength});
112 NDT = form.find('[name=status_textarea]');
114 NDT.bind('keyup', function(e) {
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() {
127 // Note there's still no event for mouse-triggered 'delete'.
128 NDT.bind('cut', delayedUpdate)
129 .bind('paste', delayedUpdate);
132 form.find('.count').text(jQuery.data(form[0], 'ElementData').MaxLength);
137 * To be called from event handlers on the notice import form.
138 * Triggers an update of the remaining-characters counter.
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.
144 * The maximum length is pulled from data established by
145 * FormNoticeEnhancements.
147 * @param {jQuery} form: jQuery object whose first element is the notice posting form
150 Counter: function(form) {
151 SN.C.I.FormNoticeCurrent = form;
153 var MaxLength = jQuery.data(form[0], 'ElementData').MaxLength;
155 if (MaxLength <= 0) {
159 var remaining = MaxLength - SN.U.CharacterCount(form);
160 var counter = form.find('.count');
162 if (remaining.toString() != counter.text()) {
163 if (!SN.C.I.CounterBlackout || remaining === 0) {
164 if (counter.text() != String(remaining)) {
165 counter.text(remaining);
168 form.addClass(SN.C.S.Warning);
170 form.removeClass(SN.C.S.Warning);
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);
184 * Pull the count of characters in the current edit field.
185 * Plugins replacing the edit control may need to override this.
187 * @param {jQuery} form: jQuery object whose first element is the notice posting form
188 * @return number of chars
190 CharacterCount: function(form) {
191 return form.find('[name=status_textarea]').val().length;
195 * Called internally after the counter update blackout period expires;
196 * runs another update to make sure we didn't miss anything.
198 * @param {jQuery} form: jQuery object whose first element is the notice posting form
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
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
213 * It would be better to output URLs that didn't hardcode protocol
214 * and hostname in the first place...
216 * @param {String} url
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);
229 * Grabs form data and submits it asynchronously, with 'ajax=1'
230 * parameter added to the rest.
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.
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
240 * @param {jQuery} form: jQuery object whose first element is a form
244 FormXHR: function(form) {
248 url: SN.U.RewriteAjaxAction(form.attr('action')),
249 data: form.serialize() + '&ajax=1',
250 beforeSend: function(xhr) {
252 .addClass(SN.C.S.Processing)
254 .addClass(SN.C.S.Disabled)
255 .attr(SN.C.S.Disabled, SN.C.S.Disabled);
257 error: function (xhr, textStatus, errorThrown) {
258 alert(errorThrown || textStatus);
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);
266 form.replaceWith(document._importNode($('p', data)[0], true));
273 * Setup function -- DOES NOT trigger actions immediately.
275 * Sets up event handlers for special-cased async submission of the
276 * notice-posting form, including some pre-post validation.
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
283 * Also unlike FormXHR(), this system will use a hidden iframe
284 * automatically to handle file uploads via <input type="file">
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?
295 * @param {jQuery} form: jQuery object whose first element is a form
299 FormNoticeXHR: function(form) {
300 SN.C.I.NoticeDataGeo = {};
301 form.append('<input type="hidden" name="ajax" value="1"/>');
303 // Make sure we don't have a mixed HTTP/HTTPS submission...
304 form.attr('action', SN.U.RewriteAjaxAction(form.attr('action')));
307 * Show a response feedback bit under the new-notice dialog.
309 * @param {String} cls: CSS class name to use ('error' or 'success')
310 * @param {String} text
313 var showFeedback = function(cls, text) {
315 $('<p class="form_response"></p>')
322 * Hide the previous response feedback, if any.
324 var removeFeedback = function() {
325 form.find('.form_response').remove();
331 beforeSend: function(formData) {
332 if (form.find('[name=status_textarea]').val() == '') {
333 form.addClass(SN.C.S.Warning);
337 .addClass(SN.C.S.Processing)
339 .addClass(SN.C.S.Disabled)
340 .attr(SN.C.S.Disabled, SN.C.S.Disabled);
342 SN.U.normalizeGeoData(form);
346 error: function (xhr, textStatus, errorThrown) {
348 .removeClass(SN.C.S.Processing)
350 .removeClass(SN.C.S.Disabled)
351 .removeAttr(SN.C.S.Disabled, SN.C.S.Disabled);
353 if (textStatus == 'timeout') {
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.');
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));
363 if (parseInt(xhr.status) === 0 || jQuery.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) >= 0) {
366 .find('.attach-status').remove();
367 SN.U.FormNoticeEnhancements(form);
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.');
376 success: function(data, textStatus) {
378 var errorResult = $('#'+SN.C.S.Error, data);
379 if (errorResult.length > 0) {
380 showFeedback('error', errorResult.text());
383 if($('body')[0].id == 'bookmarklet') {
384 // @fixme self is not referenced anywhere?
388 var commandResult = $('#'+SN.C.S.CommandResult, data);
389 if (commandResult.length > 0) {
390 showFeedback('success', commandResult.text());
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>');
404 $($(notice_irt+' .notices')[0]).append(notice);
407 notices.prepend(notice);
410 .css({display:'none'})
412 SN.U.NoticeWithAttachment($('#'+notice.id));
413 SN.U.NoticeReplyTo($('#'+notice.id));
417 // Not on a timeline that this belongs on?
418 // Just show a success message.
419 showFeedback('success', $('title', data).text());
423 form.find('[name=inreplyto]').val('');
424 form.find('.attach-status').remove();
425 SN.U.FormNoticeEnhancements(form);
428 complete: function(xhr, textStatus) {
430 .removeClass(SN.C.S.Processing)
432 .removeAttr(SN.C.S.Disabled)
433 .removeClass(SN.C.S.Disabled);
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);
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
451 var cookieValue = $.cookie(SN.C.S.NoticeDataGeoCookie);
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();
461 form.find('[name=location_ns]').val('');
462 form.find('[name=location_id]').val('');
465 if (cookieValue == 'disabled') {
466 SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).attr('checked', false).attr('checked');
469 SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).attr('checked', true).attr('checked');
474 * Fetch an XML DOM from an XHR's response data.
476 * Works around unavailable responseXML when document.domain
477 * has been modified by Meteor or other tools, in some but not
480 * @param {XMLHTTPRequest} xhr
481 * @return DOMDocument
483 GetResponseXML: function(xhr) {
485 return xhr.responseXML;
487 return (new DOMParser()).parseFromString(xhr.responseText, "text/xml");
492 * Setup function -- DOES NOT trigger actions immediately.
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
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.)
504 NoticeReply: function() {
505 if ($('#content .notice_reply').length > 0) {
506 $('#content .notice').each(function() { SN.U.NoticeReplyTo($(this)); });
511 * Setup function -- DOES NOT trigger actions immediately.
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
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.)
521 * @param {jQuery} notice: jQuery object containing one or more notices
524 NoticeReplyTo: function(notice) {
525 notice.find('.notice_reply').live('click', function(e) {
527 var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname.uid');
528 SN.U.NoticeInlineReplyTrigger(notice, '@' + nickname.text());
534 * Open up a notice's inline reply box.
536 * @param {jQuery} notice: jQuery object containing one notice
537 * @param {String} initialText
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;
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');
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>');
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();
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">' +
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);
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!
593 if (list.find('li').length > 0) {
594 SN.U.NoticeInlineReplyPlaceholder(parentNotice);
600 replyForm.submit(function(event) {
601 var form = replyForm;
605 url: SN.U.RewriteAjaxAction(form.attr('action')),
606 data: form.serialize() + '&ajax=1',
607 beforeSend: function(xhr) {
609 .addClass(SN.C.S.Processing)
611 .addClass(SN.C.S.Disabled)
612 .attr(SN.C.S.Disabled, SN.C.S.Disabled)
615 .addClass(SN.C.S.Disabled)
616 .attr(SN.C.S.Disabled, SN.C.S.Disabled);
618 error: function (xhr, textStatus, errorThrown) {
619 alert(errorThrown || textStatus);
621 success: function(data, textStatus) {
622 var orig_li = $('li', data)[0];
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);
630 // Realtime came through before us...
636 event.preventDefault();
643 replyForm.find('input[name=inreplyto]').val(id);
646 var text = replyForm.find('textarea');
647 if (text.length == 0) {
652 replyto = initialText + ' ';
654 text.val(replyto + text.val().replace(RegExp(replyto, 'i'), ''));
655 text.data('initialText', $.trim(initialText + ''));
657 if (text[0].setSelectionRange) {
658 var len = text.val().length;
659 text[0].setSelectionRange(len,len);
664 * Setup function -- DOES NOT apply immediately.
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.
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; });
674 NoticeInlineReplyPlaceholder: function(notice) {
675 var list = notice.find('ul.threaded-replies');
676 var placeholder = $('<li class="notice-reply-placeholder">' +
677 '<input class="placeholder">' +
679 placeholder.click(function() {
680 SN.U.NoticeInlineReplyTrigger(notice);
682 placeholder.find('input').val(SN.msg('reply_placeholder'));
683 list.append(placeholder);
687 * Setup function -- DOES NOT apply immediately.
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.
692 NoticeInlineReplySetup: function() {
693 $('.threaded-replies').each(function() {
695 var notice = list.closest('.notice');
696 SN.U.NoticeInlineReplyPlaceholder(notice);
701 * Setup function -- DOES NOT trigger actions immediately.
703 * Sets up event handlers for repeat forms to toss up a confirmation
704 * popout before submitting.
706 * Uses 'live' rather than 'bind', so applies to future as well as present items.
708 NoticeRepeat: function() {
709 $('.form_repeat').live('click', function(e) {
712 SN.U.NoticeRepeatConfirmation($(this));
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.
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.
728 * @fixme create confirmation dialogs through a generalized interface
729 * that can be reused instead of hardcoded text and styles.
731 * @param {jQuery} form
733 NoticeRepeatConfirmation: function(form) {
734 var submit_i = form.find('.submit');
736 var submit = submit_i.clone();
738 .addClass('submit_dialogbox')
739 .removeClass('submit');
741 submit.bind('click', function() { SN.U.FormXHR(form); return false; });
746 .addClass('dialogbox')
747 .append('<button class="close">×</button>')
748 .closest('.notice-options')
751 form.find('button.close').click(function(){
755 .removeClass('dialogbox')
756 .closest('.notice-options')
757 .removeClass('opaque');
759 form.find('.submit_dialogbox').remove();
760 form.find('.submit').show();
767 * Setup function -- DOES NOT trigger actions immediately.
769 * Goes through all notices currently displayed and sets up attachment
770 * handling if needed.
772 NoticeAttachments: function() {
773 $('.notice a.attachment').each(function() {
774 SN.U.NoticeWithAttachment($(this).closest('.notice'));
779 * Setup function -- DOES NOT trigger actions immediately.
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.
786 * @param {jQuery} notice
788 NoticeWithAttachment: function(notice) {
789 if (notice.find('.attachment').length === 0) {
793 var attachment_more = notice.find('.attachment.more');
794 if (attachment_more.length > 0) {
795 $(attachment_more[0]).click(function() {
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());
803 }).attr('title', SN.msg('showmore_tooltip'));
808 * Setup function -- DOES NOT trigger actions immediately.
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.
815 * This preview box will also allow removing the attachment
818 * @param {jQuery} form
820 NoticeDataAttach: function(form) {
821 var NDA = form.find('input[type=file]');
822 NDA.change(function(event) {
823 form.find('.attach-status').remove();
825 var filename = $(this).val();
827 // No file -- we've been tricked!
831 var attachStatus = $('<div class="attach-status '+SN.C.S.Success+'"><code></code> <button class="close">×</button></div>');
832 attachStatus.find('code').text(filename);
833 attachStatus.find('button').click(function(){
834 attachStatus.remove();
839 form.append(attachStatus);
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]);
851 * Get PHP's MAX_FILE_SIZE setting for this form;
852 * used to apply client-side file size limit checks.
854 * @param {jQuery} form
855 * @return int max size in bytes; 0 or negative means no limit
857 maxFileSize: function(form) {
858 var max = $(form).find('input[name=MAX_FILE_SIZE]').attr('value');
860 return parseInt(max);
867 * For browsers with FileAPI support: make a thumbnail if possible,
868 * and append it into the attachment display widget.
871 * - Firefox 3.6.6, 4.0b7
872 * - Chrome 8.0.552.210
874 * Known ok metadata, can't get contents:
878 * - Opera 10.63, 11 beta (no input.files interface)
880 * @param {jQuery} form
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?
887 PreviewAttach: function(form, file) {
888 var tooltip = file.type + ' ' + Math.round(file.size / 1024) + 'KB';
892 if (typeof window.createObjectURL != "undefined") {
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.
898 * - Firefox 3.6.6: no
899 * - Firefox 4.0b7: no
901 * - Chrome 8.0.552.210: works!
903 blobAsDataURL = function(blob, callback) {
904 callback(window.createObjectURL(blob));
906 } else if (typeof window.FileReader != "undefined") {
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.
912 * - Firefox 3.6.6: works!
913 * - Firefox 4.0b7: works!
915 * - Chrome 8.0.552.210: works!
917 blobAsDataURL = function(blob, callback) {
918 var reader = new FileReader();
919 reader.onload = function(event) {
920 callback(reader.result);
922 reader.readAsDataURL(blob);
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.
934 var maxSize = 8 * 1024 * 1024;
935 if (file.size > maxSize) {
936 // Don't kill the browser trying to load some giant image.
941 blobAsDataURL(file, function(url) {
943 .attr('title', tooltip)
944 .attr('alt', tooltip)
946 .attr('style', 'height: 120px');
947 form.find('.attach-status').append(img);
950 var img = $('<div></div>').text(tooltip);
951 form.find('.attach-status').append(img);
956 * Setup function -- DOES NOT trigger actions immediately.
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.
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.
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);
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');
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);
987 $.cookie(SN.C.S.NoticeDataGeoCookie, 'disabled', { path: '/' });
990 $('.geo_status_wrapper').removeClass('success').addClass('error');
991 $('.geo_status_wrapper .geo_status').text(error);
993 $('.geo_status_wrapper').remove();
997 function getJSONgeocodeURL(geocodeURL, data) {
998 SN.U.NoticeGeoStatus('Looking up place name...');
999 $.getJSON(geocodeURL, data, function(location) {
1002 if (typeof(location.location_ns) != 'undefined') {
1003 $('#'+SN.C.S.NoticeLocationNs).val(location.location_ns);
1004 lns = location.location_ns;
1007 if (typeof(location.location_id) != 'undefined') {
1008 $('#'+SN.C.S.NoticeLocationId).val(location.location_id);
1009 lid = location.location_id;
1012 if (typeof(location.name) == 'undefined') {
1013 NLN_text = data.lat + ';' + data.lon;
1016 NLN_text = location.name;
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 + ')');
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);
1039 $.cookie(SN.C.S.NoticeDataGeoCookie, JSON.stringify(cookieValue), { path: '/' });
1043 if (NDGe.length > 0) {
1044 if ($.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
1045 NDGe.attr('checked', false);
1048 NDGe.attr('checked', true);
1051 var NGW = $('#notice_data-geo_wrap');
1052 var geocodeURL = NGW.attr('title');
1053 NGW.removeAttr('title');
1055 $('label[for='+SN.C.S.NoticeDataGeo+']')
1056 .attr('title', jQuery.trim($('label[for='+SN.C.S.NoticeDataGeo+']').text()));
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');
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);
1073 lat: position.coords.latitude,
1074 lon: position.coords.longitude,
1075 token: $('#token').val()
1078 getJSONgeocodeURL(geocodeURL, data);
1082 switch(error.code) {
1083 case error.PERMISSION_DENIED:
1084 removeNoticeDataGeo('Location permission denied.');
1087 //$('#'+SN.C.S.NoticeDataGeo).attr('checked', false);
1088 removeNoticeDataGeo('Location lookup timeout.');
1099 if (NLat.length > 0 && NLon.length > 0) {
1103 token: $('#token').val()
1106 getJSONgeocodeURL(geocodeURL, data);
1109 removeNoticeDataGeo();
1110 $('#'+SN.C.S.NoticeDataGeo).remove();
1111 $('label[for='+SN.C.S.NoticeDataGeo+']').remove();
1116 var cookieValue = JSON.parse($.cookie(SN.C.S.NoticeDataGeoCookie));
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);
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');
1131 removeNoticeDataGeo();
1138 * Create or update a geolocation status widget in this notice posting form.
1140 * @param {String} status
1141 * @param {String} lat (optional)
1142 * @param {String} lon (optional)
1143 * @param {String} url (optional)
1145 NoticeGeoStatus: function(status, lat, lon, url)
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">×</button><div class="geo_status"></div></div>');
1151 wrapper.find('button.close').click(function() {
1152 $('#'+SN.C.S.NoticeDataGeo).removeAttr('checked').change();
1154 form.append(wrapper);
1158 label = $('<a></a>').attr('href', url);
1160 label = $('<span></span>');
1164 var latlon = lat + ';' + lon;
1165 label.attr('title', latlon);
1170 wrapper.find('.geo_status').empty().append(label);
1174 * Setup function -- DOES NOT trigger actions immediately.
1176 * Initializes event handlers for the "Send direct message" link on
1177 * profile pages, setting it up to display a dialog box when clicked.
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.
1183 * @fixme breaks ability to open link in new window?
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">×</button>');
1198 $('.entity_send-a-message button').click(function(){
1202 NDM.removeClass(SN.C.S.Processing);
1207 $('.entity_send-a-message textarea').focus();
1214 * Return a date object with the current local time on the
1215 * given year, month, and day.
1217 * @param {number} year: 4-digit year
1218 * @param {number} month: 0 == January
1219 * @param {number} day: 1 == 1
1222 GetFullYear: function(year, month, day) {
1223 var date = new Date();
1224 date.setFullYear(year, month, day);
1230 * Some sort of object interface for storing some structured
1231 * information in a cookie.
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?
1238 * @fixme what is this?
1239 * @fixme should this use non-cookie local storage when available?
1241 StatusNetInstance: {
1243 * @fixme what is this?
1245 Set: function(value) {
1246 var SNI = SN.U.StatusNetInstance.Get();
1248 value = $.extend(SNI, value);
1252 SN.C.S.StatusNetInstance,
1253 JSON.stringify(value),
1256 expires: SN.U.GetFullYear(2029, 0, 1)
1261 * @fixme what is this?
1264 var cookieValue = $.cookie(SN.C.S.StatusNetInstance);
1265 if (cookieValue !== null) {
1266 return JSON.parse(cookieValue);
1272 * @fixme what is this?
1274 Delete: function() {
1275 $.cookie(SN.C.S.StatusNetInstance, null);
1280 * Check if the current page is a timeline where the current user's
1281 * posts should be displayed immediately on success.
1283 * @fixme this should be done in a saner way, with machine-readable
1284 * info about what page we're looking at.
1286 * @param {DOMElement} notice: HTML chunk with formatted notice
1289 belongsOnTimeline: function(notice) {
1290 var action = $("body").attr('id');
1291 if (action == 'public') {
1295 var profileLink = $('#nav_profile a').attr('href');
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.
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.
1317 * If user is logged in, run setup code for the new notice form:
1322 * - file upload events
1324 NoticeForm: function() {
1325 if ($('body.user_in').length > 0) {
1326 SN.U.NoticeLocationAttach();
1328 $('.'+SN.C.S.FormNotice).each(function() {
1329 SN.U.FormNoticeXHR($(this));
1330 SN.U.FormNoticeEnhancements($(this));
1331 SN.U.NoticeDataAttach($(this));
1337 * Run setup code for notice timeline views items:
1339 * - AJAX submission for fave/repeat/reply (if logged in)
1340 * - Attachment link extras ('more' links)
1342 Notices: function() {
1343 if ($('body.user_in').length > 0) {
1345 SN.U.NoticeRepeat();
1347 SN.U.NoticeInlineReplySetup();
1350 SN.U.NoticeAttachments();
1354 * Run setup code for user & group profile page header area if logged in:
1356 * - AJAX submission for sub/unsub/join/leave/nudge
1357 * - AJAX form popup for direct-message
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; });
1367 SN.U.NewDirectMessage();
1372 * Run setup code for login form:
1374 * - loads saved last-used-nickname from cookie
1375 * - sets event handler to save nickname to cookie on submit
1377 * @fixme is this necessary? Browsers do their own form saving these days.
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);
1387 $('#form_login').bind('submit', function() {
1388 SN.U.StatusNetInstance.Set({Nickname: $('#form_login #nickname').val()});
1394 * Add logic to any file upload forms to handle file size limits,
1395 * on browsers that support basic FileAPI.
1397 UploadForms: function () {
1398 $('input[type=file]').change(function(event) {
1399 if (typeof this.files == "object" && this.files.length > 0) {
1401 for (var i = 0; i < this.files.length; i++) {
1402 size += this.files[i].size;
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));
1412 event.preventDefault();
1422 * Run initialization functions on DOM-ready.
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!
1428 $(document).ready(function(){
1429 SN.Init.UploadForms();
1430 if ($('.'+SN.C.S.FormNotice).length > 0) {
1431 SN.Init.NoticeForm();
1433 if ($('#content .notices').length > 0) {
1436 if ($('#content .entity_actions').length > 0) {
1437 SN.Init.EntityActions();
1439 if ($('#form_login').length > 0) {