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 NoticeActionSubmit: 'notice_action-submit',
55 NoticeLat: 'notice_data-lat',
56 NoticeLon: 'notice_data-lon',
57 NoticeLocationId: 'notice_data-location_id',
58 NoticeLocationNs: 'notice_data-location_ns',
59 NoticeGeoName: 'notice_data-geo_name',
60 NoticeDataGeo: 'notice_data-geo',
61 NoticeDataGeoCookie: 'NoticeDataGeo',
62 NoticeDataGeoSelected: 'notice_data-geo_selected',
63 StatusNetInstance:'StatusNetInstance'
68 * Map of localized message strings exported to script from the PHP
69 * side via Action::getScriptMessages().
71 * Retrieve them via SN.msg(); this array is an implementation detail.
78 * Grabs a localized string that's been previously exported to us
79 * from server-side code via Action::getScriptMessages().
81 * @example alert(SN.msg('coolplugin-failed'));
83 * @param {String} key: string key name to pull from message index
84 * @return matching localized message string
87 if (typeof SN.messages[key] == "undefined") {
88 return '[' + key + ']';
90 return SN.messages[key];
96 * Setup function -- DOES NOT trigger actions immediately.
98 * Sets up event handlers on the new notice form.
100 * @param {jQuery} form: jQuery object whose first matching element is the form
103 FormNoticeEnhancements: function(form) {
104 if (jQuery.data(form[0], 'ElementData') === undefined) {
105 MaxLength = form.find('.count').text();
106 if (typeof(MaxLength) == 'undefined') {
107 MaxLength = SN.C.I.MaxLength;
109 jQuery.data(form[0], 'ElementData', {MaxLength:MaxLength});
113 NDT = form.find('[name=status_textarea]');
115 NDT.bind('keyup', function(e) {
119 var delayedUpdate= function(e) {
120 // Cut and paste events fire *before* the operation,
121 // so we need to trigger an update in a little bit.
122 // This would be so much easier if the 'change' event
123 // actually fired every time the value changed. :P
124 window.setTimeout(function() {
128 // Note there's still no event for mouse-triggered 'delete'.
129 NDT.bind('cut', delayedUpdate)
130 .bind('paste', delayedUpdate);
133 form.find('.count').text(jQuery.data(form[0], 'ElementData').MaxLength);
138 * To be called from event handlers on the notice import form.
139 * Triggers an update of the remaining-characters counter.
141 * Additional counter updates will be suppressed during the
142 * next half-second to avoid flooding the layout engine with
143 * updates, followed by another automatic check.
145 * The maximum length is pulled from data established by
146 * FormNoticeEnhancements.
148 * @param {jQuery} form: jQuery object whose first element is the notice posting form
151 Counter: function(form) {
152 SN.C.I.FormNoticeCurrent = form;
154 var MaxLength = jQuery.data(form[0], 'ElementData').MaxLength;
156 if (MaxLength <= 0) {
160 var remaining = MaxLength - SN.U.CharacterCount(form);
161 var counter = form.find('.count');
163 if (remaining.toString() != counter.text()) {
164 if (!SN.C.I.CounterBlackout || remaining === 0) {
165 if (counter.text() != String(remaining)) {
166 counter.text(remaining);
169 form.addClass(SN.C.S.Warning);
171 form.removeClass(SN.C.S.Warning);
173 // Skip updates for the next 500ms.
174 // On slower hardware, updating on every keypress is unpleasant.
175 if (!SN.C.I.CounterBlackout) {
176 SN.C.I.CounterBlackout = true;
177 SN.C.I.FormNoticeCurrent = form;
178 window.setTimeout("SN.U.ClearCounterBlackout(SN.C.I.FormNoticeCurrent);", 500);
185 * Pull the count of characters in the current edit field.
186 * Plugins replacing the edit control may need to override this.
188 * @param {jQuery} form: jQuery object whose first element is the notice posting form
189 * @return number of chars
191 CharacterCount: function(form) {
192 return form.find('[name=status_textarea]').val().length;
196 * Called internally after the counter update blackout period expires;
197 * runs another update to make sure we didn't miss anything.
199 * @param {jQuery} form: jQuery object whose first element is the notice posting form
202 ClearCounterBlackout: function(form) {
203 // Allow keyup events to poke the counter again
204 SN.C.I.CounterBlackout = false;
205 // Check if the string changed since we last looked
210 * Helper function to rewrite default HTTP form action URLs to HTTPS
211 * so we can actually fetch them when on an SSL page in ssl=sometimes
214 * It would be better to output URLs that didn't hardcode protocol
215 * and hostname in the first place...
217 * @param {String} url
220 RewriteAjaxAction: function(url) {
221 // Quick hack: rewrite AJAX submits to HTTPS if they'd fail otherwise.
222 if (document.location.protocol == 'https:' && url.substr(0, 5) == 'http:') {
223 return url.replace(/^http:\/\/[^:\/]+/, 'https://' + document.location.host);
230 * Grabs form data and submits it asynchronously, with 'ajax=1'
231 * parameter added to the rest.
233 * If a successful response includes another form, that form
234 * will be extracted and copied in, replacing the original form.
235 * If there's no form, the first paragraph will be used.
237 * @fixme can sometimes explode confusingly if returnd data is bogus
238 * @fixme error handling is pretty vague
239 * @fixme can't submit file uploads
241 * @param {jQuery} form: jQuery object whose first element is a form
245 FormXHR: function(form) {
249 url: SN.U.RewriteAjaxAction(form.attr('action')),
250 data: form.serialize() + '&ajax=1',
251 beforeSend: function(xhr) {
253 .addClass(SN.C.S.Processing)
255 .addClass(SN.C.S.Disabled)
256 .attr(SN.C.S.Disabled, SN.C.S.Disabled);
258 error: function (xhr, textStatus, errorThrown) {
259 alert(errorThrown || textStatus);
261 success: function(data, textStatus) {
262 if (typeof($('form', data)[0]) != 'undefined') {
263 form_new = document._importNode($('form', data)[0], true);
264 form.replaceWith(form_new);
267 form.replaceWith(document._importNode($('p', data)[0], true));
274 * Setup function -- DOES NOT trigger actions immediately.
276 * Sets up event handlers for special-cased async submission of the
277 * notice-posting form, including some pre-post validation.
279 * Unlike FormXHR() this does NOT submit the form immediately!
280 * It sets up event handlers so that any method of submitting the
281 * form (click on submit button, enter, submit() etc) will trigger
284 * Also unlike FormXHR(), this system will use a hidden iframe
285 * automatically to handle file uploads via <input type="file">
289 * @fixme vast swaths of duplicate code and really long variable names clutter this function up real bad
290 * @fixme error handling is unreliable
291 * @fixme cookieValue is a global variable, but probably shouldn't be
292 * @fixme saving the location cache cookies should be split out
293 * @fixme some error messages are hardcoded english: needs i18n
294 * @fixme special-case for bookmarklet is confusing and uses a global var "self". Is this ok?
296 * @param {jQuery} form: jQuery object whose first element is a form
300 FormNoticeXHR: function(form) {
301 SN.C.I.NoticeDataGeo = {};
302 form.append('<input type="hidden" name="ajax" value="1"/>');
304 // Make sure we don't have a mixed HTTP/HTTPS submission...
305 form.attr('action', SN.U.RewriteAjaxAction(form.attr('action')));
308 * Show a response feedback bit under the new-notice dialog.
310 * @param {String} cls: CSS class name to use ('error' or 'success')
311 * @param {String} text
314 var showFeedback = function(cls, text) {
316 $('<p class="form_response"></p>')
323 * Hide the previous response feedback, if any.
325 var removeFeedback = function() {
326 form.find('.form_response').remove();
332 beforeSend: function(formData) {
333 if (form.find('[name=status_textarea]').val() == '') {
334 form.addClass(SN.C.S.Warning);
338 .addClass(SN.C.S.Processing)
339 .find('#'+SN.C.S.NoticeActionSubmit)
340 .addClass(SN.C.S.Disabled)
341 .attr(SN.C.S.Disabled, SN.C.S.Disabled);
343 SN.U.normalizeGeoData(form);
347 error: function (xhr, textStatus, errorThrown) {
349 .removeClass(SN.C.S.Processing)
350 .find('#'+SN.C.S.NoticeActionSubmit)
351 .removeClass(SN.C.S.Disabled)
352 .removeAttr(SN.C.S.Disabled, SN.C.S.Disabled);
354 if (textStatus == 'timeout') {
356 showFeedback('error', 'Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists.');
359 var response = SN.U.GetResponseXML(xhr);
360 if ($('.'+SN.C.S.Error, response).length > 0) {
361 form.append(document._importNode($('.'+SN.C.S.Error, response)[0], true));
364 if (parseInt(xhr.status) === 0 || jQuery.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) >= 0) {
367 .find('.attach-status').remove();
368 SN.U.FormNoticeEnhancements(form);
372 showFeedback('error', '(Sorry! We had trouble sending your notice ('+xhr.status+' '+xhr.statusText+'). Please report the problem to the site administrator if this happens again.');
377 success: function(data, textStatus) {
379 var errorResult = $('#'+SN.C.S.Error, data);
380 if (errorResult.length > 0) {
381 showFeedback('error', errorResult.text());
384 if($('body')[0].id == 'bookmarklet') {
385 // @fixme self is not referenced anywhere?
389 var commandResult = $('#'+SN.C.S.CommandResult, data);
390 if (commandResult.length > 0) {
391 showFeedback('success', commandResult.text());
394 // New notice post was successful. If on our timeline, show it!
395 var notice = document._importNode($('li', data)[0], true);
396 var notices = $('#notices_primary .notices:first');
397 if (notices.length > 0 && SN.U.belongsOnTimeline(notice)) {
398 if ($('#'+notice.id).length === 0) {
399 var notice_irt_value = $('#'+SN.C.S.NoticeInReplyTo).val();
400 var notice_irt = '#notices_primary #notice-'+notice_irt_value;
401 if($('body')[0].id == 'conversation') {
402 if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
403 $(notice_irt).append('<ul class="notices"></ul>');
405 $($(notice_irt+' .notices')[0]).append(notice);
408 notices.prepend(notice);
411 .css({display:'none'})
413 SN.U.NoticeWithAttachment($('#'+notice.id));
414 SN.U.NoticeReplyTo($('#'+notice.id));
418 // Not on a timeline that this belongs on?
419 // Just show a success message.
420 showFeedback('success', $('title', data).text());
424 form.find('[name=inreplyto]').val('');
425 form.find('.attach-status').remove();
426 SN.U.FormNoticeEnhancements(form);
429 complete: function(xhr, textStatus) {
431 .removeClass(SN.C.S.Processing)
432 .find('#'+SN.C.S.NoticeActionSubmit)
433 .removeAttr(SN.C.S.Disabled)
434 .removeClass(SN.C.S.Disabled);
436 form.find('[name=lat]').val(SN.C.I.NoticeDataGeo.NLat);
437 form.find('[name=lon]').val(SN.C.I.NoticeDataGeo.NLon);
438 form.find('[name=location_ns]').val(SN.C.I.NoticeDataGeo.NLNS);
439 form.find('[name=location_id]').val(SN.C.I.NoticeDataGeo.NLID);
440 $('#'+SN.C.S.NoticeDataGeo).attr('checked', SN.C.I.NoticeDataGeo.NDG);
445 normalizeGeoData: function(form) {
446 SN.C.I.NoticeDataGeo.NLat = form.find('[name=lat]').val();
447 SN.C.I.NoticeDataGeo.NLon = form.find('[name=lon]').val();
448 SN.C.I.NoticeDataGeo.NLNS = form.find('[name=location_ns]').val();
449 SN.C.I.NoticeDataGeo.NLID = form.find('[name=location_id]').val();
450 SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).attr('checked'); // @fixme
452 var cookieValue = $.cookie(SN.C.S.NoticeDataGeoCookie);
454 if (cookieValue !== null && cookieValue != 'disabled') {
455 cookieValue = JSON.parse(cookieValue);
456 SN.C.I.NoticeDataGeo.NLat = form.find('[name=lat]').val(cookieValue.NLat).val();
457 SN.C.I.NoticeDataGeo.NLon = form.find('[name=lon]').val(cookieValue.NLon).val();
458 if (cookieValue.NLNS) {
459 SN.C.I.NoticeDataGeo.NLNS = form.find('[name=location_ns]').val(cookieValue.NLNS).val();
460 SN.C.I.NoticeDataGeo.NLID = form.find('[name=location_id]').val(cookieValue.NLID).val();
462 form.find('[name=location_ns]').val('');
463 form.find('[name=location_id]').val('');
466 if (cookieValue == 'disabled') {
467 SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).attr('checked', false).attr('checked');
470 SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).attr('checked', true).attr('checked');
475 * Fetch an XML DOM from an XHR's response data.
477 * Works around unavailable responseXML when document.domain
478 * has been modified by Meteor or other tools, in some but not
481 * @param {XMLHTTPRequest} xhr
482 * @return DOMDocument
484 GetResponseXML: function(xhr) {
486 return xhr.responseXML;
488 return (new DOMParser()).parseFromString(xhr.responseText, "text/xml");
493 * Setup function -- DOES NOT trigger actions immediately.
495 * Sets up event handlers on all visible notice's reply buttons to
496 * tweak the new-notice form with needed variables and focus it
499 * (This replaces the default reply button behavior to submit
500 * directly to a form which comes back with a specialized page
501 * with the form data prefilled.)
505 NoticeReply: function() {
506 if ($('#content .notice_reply').length > 0) {
507 $('#content .notice').each(function() { SN.U.NoticeReplyTo($(this)); });
512 * Setup function -- DOES NOT trigger actions immediately.
514 * Sets up event handlers on the given notice's reply button to
515 * tweak the new-notice form with needed variables and focus it
518 * (This replaces the default reply button behavior to submit
519 * directly to a form which comes back with a specialized page
520 * with the form data prefilled.)
522 * @param {jQuery} notice: jQuery object containing one or more notices
525 NoticeReplyTo: function(notice) {
526 notice.find('.notice_reply').live('click', function(e) {
528 var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname.uid');
529 SN.U.NoticeInlineReplyTrigger(notice, '@' + nickname.text());
535 * Open up a notice's inline reply box.
537 * @param {jQuery} notice: jQuery object containing one notice
538 * @param {String} initialText
540 NoticeInlineReplyTrigger: function(notice, initialText) {
541 // Find the notice we're replying to...
542 var id = $($('.notice_id', notice)[0]).text();
543 var parentNotice = notice;
545 // Find the threaded replies view we'll be adding to...
546 var list = notice.closest('.notices');
547 if (list.hasClass('threaded-replies')) {
548 // We're replying to a reply; use reply form on the end of this list.
549 // We'll add our form at the end of this; grab the root notice.
550 parentNotice = list.closest('.notice');
552 // We're replying to a parent notice; pull its threaded list
553 // and we'll add on the end of it. Will add if needed.
554 list = $('ul.threaded-replies', notice);
555 if (list.length == 0) {
556 list = $('<ul class="notices threaded-replies xoxo"></ul>');
561 // See if the form's already open...
562 var replyForm = $('.notice-reply-form', list);
563 if (replyForm.length == 0) {
564 // Remove placeholder if any
565 $('li.notice-reply-placeholder').remove();
567 // Create the reply form entry at the end
568 var replyItem = $('li.notice-reply', list);
569 if (replyItem.length == 0) {
570 replyItem = $('<li class="notice-reply">' +
571 '<form class="notice-reply-form" method="post">' +
572 '<textarea name="status_textarea"></textarea>' +
573 '<div class="controls">' +
574 '<input type="hidden" name="token">' +
575 '<input type="hidden" name="inreplyto">' +
576 '<input type="submit" class="submit">' +
581 var baseForm = $('#form_notice');
582 replyForm = replyItem.find('form');
583 replyForm.attr('action', baseForm.attr('action'));
584 replyForm.find('input[name="token"]').val(baseForm.find('input[name=token]').val());
585 replyForm.find('input[type="submit"]').val(SN.msg('reply_submit'));
586 list.append(replyItem);
588 replyForm.find('textarea').blur(function() {
589 var textarea = $(this);
590 var txt = $.trim(textarea.val());
591 if (txt == '' || txt == textarea.data('initialText')) {
592 // Nothing to say? Begone!
594 if (list.find('li').length > 0) {
595 SN.U.NoticeInlineReplyPlaceholder(parentNotice);
601 replyForm.submit(function(event) {
602 var form = replyForm;
606 url: SN.U.RewriteAjaxAction(form.attr('action')),
607 data: form.serialize() + '&ajax=1',
608 beforeSend: function(xhr) {
610 .addClass(SN.C.S.Processing)
612 .addClass(SN.C.S.Disabled)
613 .attr(SN.C.S.Disabled, SN.C.S.Disabled)
616 .addClass(SN.C.S.Disabled)
617 .attr(SN.C.S.Disabled, SN.C.S.Disabled);
619 error: function (xhr, textStatus, errorThrown) {
620 alert(errorThrown || textStatus);
622 success: function(data, textStatus) {
623 var orig_li = $('li', data)[0];
625 var li = document._importNode(orig_li, true);
626 var id = $(li).attr('id');
627 if ($("#"+id).length == 0) {
628 replyItem.replaceWith(li);
629 SN.U.NoticeInlineReplyPlaceholder(parentNotice);
631 // Realtime came through before us...
637 event.preventDefault();
644 replyForm.find('input[name=inreplyto]').val(id);
647 var text = replyForm.find('textarea');
648 if (text.length == 0) {
653 replyto = initialText + ' ';
655 text.val(replyto + text.val().replace(RegExp(replyto, 'i'), ''));
656 text.data('initialText', $.trim(initialText + ''));
658 if (text[0].setSelectionRange) {
659 var len = text.val().length;
660 text[0].setSelectionRange(len,len);
665 * Setup function -- DOES NOT apply immediately.
667 * Sets up event handlers for favor/disfavor forms to submit via XHR.
668 * Uses 'live' rather than 'bind', so applies to future as well as present items.
670 NoticeFavor: function() {
671 $('.form_favor').live('click', function() { SN.U.FormXHR($(this)); return false; });
672 $('.form_disfavor').live('click', function() { SN.U.FormXHR($(this)); return false; });
675 NoticeInlineReplyPlaceholder: function(notice) {
676 var list = notice.find('ul.threaded-replies');
677 var placeholder = $('<li class="notice-reply-placeholder">' +
678 '<input class="placeholder">' +
680 placeholder.click(function() {
681 SN.U.NoticeInlineReplyTrigger(notice);
683 placeholder.find('input').val(SN.msg('reply_placeholder'));
684 list.append(placeholder);
688 * Setup function -- DOES NOT apply immediately.
690 * Sets up event handlers for favor/disfavor forms to submit via XHR.
691 * Uses 'live' rather than 'bind', so applies to future as well as present items.
693 NoticeInlineReplySetup: function() {
694 $('.threaded-replies').each(function() {
696 var notice = list.closest('.notice');
697 SN.U.NoticeInlineReplyPlaceholder(notice);
702 * Setup function -- DOES NOT trigger actions immediately.
704 * Sets up event handlers for repeat forms to toss up a confirmation
705 * popout before submitting.
707 * Uses 'live' rather than 'bind', so applies to future as well as present items.
709 NoticeRepeat: function() {
710 $('.form_repeat').live('click', function(e) {
713 SN.U.NoticeRepeatConfirmation($(this));
719 * Shows a confirmation dialog box variant of the repeat button form.
720 * This seems to use a technique where the repeat form contains
721 * _both_ a standalone button _and_ text and buttons for a dialog.
722 * The dialog will close after its copy of the form is submitted,
723 * or if you click its 'close' button.
725 * The dialog is created by duplicating the original form and changing
726 * its style; while clever, this is hard to generalize and probably
727 * duplicates a lot of unnecessary HTML output.
729 * @fixme create confirmation dialogs through a generalized interface
730 * that can be reused instead of hardcoded text and styles.
732 * @param {jQuery} form
734 NoticeRepeatConfirmation: function(form) {
735 var submit_i = form.find('.submit');
737 var submit = submit_i.clone();
739 .addClass('submit_dialogbox')
740 .removeClass('submit');
742 submit.bind('click', function() { SN.U.FormXHR(form); return false; });
747 .addClass('dialogbox')
748 .append('<button class="close">×</button>')
749 .closest('.notice-options')
752 form.find('button.close').click(function(){
756 .removeClass('dialogbox')
757 .closest('.notice-options')
758 .removeClass('opaque');
760 form.find('.submit_dialogbox').remove();
761 form.find('.submit').show();
768 * Setup function -- DOES NOT trigger actions immediately.
770 * Goes through all notices currently displayed and sets up attachment
771 * handling if needed.
773 NoticeAttachments: function() {
774 $('.notice a.attachment').each(function() {
775 SN.U.NoticeWithAttachment($(this).closest('.notice'));
780 * Setup function -- DOES NOT trigger actions immediately.
782 * Sets up special attachment link handling if needed. Currently this
783 * consists only of making the "more" button used for OStatus message
784 * cropping turn into an auto-expansion button that loads the full
785 * text from an attachment file.
787 * @param {jQuery} notice
789 NoticeWithAttachment: function(notice) {
790 if (notice.find('.attachment').length === 0) {
794 var attachment_more = notice.find('.attachment.more');
795 if (attachment_more.length > 0) {
796 $(attachment_more[0]).click(function() {
798 m.addClass(SN.C.S.Processing);
799 $.get(m.attr('href')+'/ajax', null, function(data) {
800 m.parent('.entry-content').html($(data).find('#attachment_view .entry-content').html());
804 }).attr('title', SN.msg('showmore_tooltip'));
809 * Setup function -- DOES NOT trigger actions immediately.
811 * Sets up event handlers for the file-attachment widget in the
812 * new notice form. When a file is selected, a box will be added
813 * below the text input showing the filename and, if supported
814 * by the browser, a thumbnail preview.
816 * This preview box will also allow removing the attachment
819 * @param {jQuery} form
821 NoticeDataAttach: function(form) {
822 var NDA = form.find('input[type=file]');
823 NDA.change(function(event) {
824 form.find('.attach-status').remove();
826 var filename = $(this).val();
828 // No file -- we've been tricked!
832 var attachStatus = $('<div class="attach-status '+SN.C.S.Success+'"><code></code> <button class="close">×</button></div>');
833 attachStatus.find('code').text(filename);
834 attachStatus.find('button').click(function(){
835 attachStatus.remove();
840 form.append(attachStatus);
842 if (typeof this.files == "object") {
843 // Some newer browsers will let us fetch the files for preview.
844 for (var i = 0; i < this.files.length; i++) {
845 SN.U.PreviewAttach(form, this.files[i]);
852 * Get PHP's MAX_FILE_SIZE setting for this form;
853 * used to apply client-side file size limit checks.
855 * @param {jQuery} form
856 * @return int max size in bytes; 0 or negative means no limit
858 maxFileSize: function(form) {
859 var max = $(form).find('input[name=MAX_FILE_SIZE]').attr('value');
861 return parseInt(max);
868 * For browsers with FileAPI support: make a thumbnail if possible,
869 * and append it into the attachment display widget.
872 * - Firefox 3.6.6, 4.0b7
873 * - Chrome 8.0.552.210
875 * Known ok metadata, can't get contents:
879 * - Opera 10.63, 11 beta (no input.files interface)
881 * @param {jQuery} form
884 * @todo use configured thumbnail size
885 * @todo detect pixel size?
886 * @todo should we render a thumbnail to a canvas and then use the smaller image?
888 PreviewAttach: function(form, file) {
889 var tooltip = file.type + ' ' + Math.round(file.size / 1024) + 'KB';
893 if (typeof window.createObjectURL != "undefined") {
895 * createObjectURL lets us reference the file directly from an <img>
896 * This produces a compact URL with an opaque reference to the file,
897 * which we can reference immediately.
899 * - Firefox 3.6.6: no
900 * - Firefox 4.0b7: no
902 * - Chrome 8.0.552.210: works!
904 blobAsDataURL = function(blob, callback) {
905 callback(window.createObjectURL(blob));
907 } else if (typeof window.FileReader != "undefined") {
909 * FileAPI's FileReader can build a data URL from a blob's contents,
910 * but it must read the file and build it asynchronously. This means
911 * we'll be passing a giant data URL around, which may be inefficient.
913 * - Firefox 3.6.6: works!
914 * - Firefox 4.0b7: works!
916 * - Chrome 8.0.552.210: works!
918 blobAsDataURL = function(blob, callback) {
919 var reader = new FileReader();
920 reader.onload = function(event) {
921 callback(reader.result);
923 reader.readAsDataURL(blob);
929 var imageTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/svg+xml'];
930 if ($.inArray(file.type, imageTypes) == -1) {
931 // We probably don't know how to show the file.
935 var maxSize = 8 * 1024 * 1024;
936 if (file.size > maxSize) {
937 // Don't kill the browser trying to load some giant image.
942 blobAsDataURL(file, function(url) {
944 .attr('title', tooltip)
945 .attr('alt', tooltip)
947 .attr('style', 'height: 120px');
948 form.find('.attach-status').append(img);
951 var img = $('<div></div>').text(tooltip);
952 form.find('.attach-status').append(img);
957 * Setup function -- DOES NOT trigger actions immediately.
959 * Initializes state for the location-lookup features in the
960 * new-notice form. Seems to set up some event handlers for
961 * triggering lookups and using the new values.
964 * @fixme there's not good visual state update here, so users have a
965 * hard time figuring out if it's working or fixing if it's wrong.
968 NoticeLocationAttach: function() {
969 // @fixme this should not be tied to the main notice form, as there may be multiple notice forms...
970 var NLat = $('#'+SN.C.S.NoticeLat).val();
971 var NLon = $('#'+SN.C.S.NoticeLon).val();
972 var NLNS = $('#'+SN.C.S.NoticeLocationNs).val();
973 var NLID = $('#'+SN.C.S.NoticeLocationId).val();
974 var NLN = $('#'+SN.C.S.NoticeGeoName).text();
975 var NDGe = $('#'+SN.C.S.NoticeDataGeo);
977 function removeNoticeDataGeo(error) {
978 $('label[for='+SN.C.S.NoticeDataGeo+']')
979 .attr('title', jQuery.trim($('label[for='+SN.C.S.NoticeDataGeo+']').text()))
980 .removeClass('checked');
982 $('.form_notice [name=lat]').val('');
983 $('.form_notice [name=lon]').val('');
984 $('.form_notice [name=location_ns]').val('');
985 $('.form_notice [name=location_id]').val('');
986 $('#'+SN.C.S.NoticeDataGeo).attr('checked', false);
988 $.cookie(SN.C.S.NoticeDataGeoCookie, 'disabled', { path: '/' });
991 $('.geo_status_wrapper').removeClass('success').addClass('error');
992 $('.geo_status_wrapper .geo_status').text(error);
994 $('.geo_status_wrapper').remove();
998 function getJSONgeocodeURL(geocodeURL, data) {
999 SN.U.NoticeGeoStatus('Looking up place name...');
1000 $.getJSON(geocodeURL, data, function(location) {
1003 if (typeof(location.location_ns) != 'undefined') {
1004 $('#'+SN.C.S.NoticeLocationNs).val(location.location_ns);
1005 lns = location.location_ns;
1008 if (typeof(location.location_id) != 'undefined') {
1009 $('#'+SN.C.S.NoticeLocationId).val(location.location_id);
1010 lid = location.location_id;
1013 if (typeof(location.name) == 'undefined') {
1014 NLN_text = data.lat + ';' + data.lon;
1017 NLN_text = location.name;
1020 SN.U.NoticeGeoStatus(NLN_text, data.lat, data.lon, location.url);
1021 $('label[for='+SN.C.S.NoticeDataGeo+']')
1022 .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + NLN_text + ')');
1024 $('.form_notice [name=lat]').val(data.lat);
1025 $('.form_notice [name=lon]').val(data.lon);
1026 $('.form_notice [name=location_ns]').val(lns);
1027 $('.form_notice [name=location_id]').val(lid);
1028 $('#'+SN.C.S.NoticeDataGeo).attr('checked', true);
1040 $.cookie(SN.C.S.NoticeDataGeoCookie, JSON.stringify(cookieValue), { path: '/' });
1044 if (NDGe.length > 0) {
1045 if ($.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
1046 NDGe.attr('checked', false);
1049 NDGe.attr('checked', true);
1052 var NGW = $('#notice_data-geo_wrap');
1053 var geocodeURL = NGW.attr('title');
1054 NGW.removeAttr('title');
1056 $('label[for='+SN.C.S.NoticeDataGeo+']')
1057 .attr('title', jQuery.trim($('label[for='+SN.C.S.NoticeDataGeo+']').text()));
1059 NDGe.change(function() {
1060 if ($('#'+SN.C.S.NoticeDataGeo).attr('checked') === true || $.cookie(SN.C.S.NoticeDataGeoCookie) === null) {
1061 $('label[for='+SN.C.S.NoticeDataGeo+']')
1062 .attr('title', NoticeDataGeo_text.ShareDisable)
1063 .addClass('checked');
1065 if ($.cookie(SN.C.S.NoticeDataGeoCookie) === null || $.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
1066 if (navigator.geolocation) {
1067 SN.U.NoticeGeoStatus('Requesting location from browser...');
1068 navigator.geolocation.getCurrentPosition(
1069 function(position) {
1070 $('.form_notice [name=lat]').val(position.coords.latitude);
1071 $('.form_notice [name=lon]').val(position.coords.longitude);
1074 lat: position.coords.latitude,
1075 lon: position.coords.longitude,
1076 token: $('#token').val()
1079 getJSONgeocodeURL(geocodeURL, data);
1083 switch(error.code) {
1084 case error.PERMISSION_DENIED:
1085 removeNoticeDataGeo('Location permission denied.');
1088 //$('#'+SN.C.S.NoticeDataGeo).attr('checked', false);
1089 removeNoticeDataGeo('Location lookup timeout.');
1100 if (NLat.length > 0 && NLon.length > 0) {
1104 token: $('#token').val()
1107 getJSONgeocodeURL(geocodeURL, data);
1110 removeNoticeDataGeo();
1111 $('#'+SN.C.S.NoticeDataGeo).remove();
1112 $('label[for='+SN.C.S.NoticeDataGeo+']').remove();
1117 var cookieValue = JSON.parse($.cookie(SN.C.S.NoticeDataGeoCookie));
1119 $('.form_notice [name=lat]').val(cookieValue.NLat);
1120 $('.form_notice [name=lon]').val(cookieValue.NLon);
1121 $('.form_notice [name=location_ns]').val(cookieValue.NLNS);
1122 $('.form_notice [name=location_id]').val(cookieValue.NLID);
1123 $('#'+SN.C.S.NoticeDataGeo).attr('checked', cookieValue.NDG);
1125 SN.U.NoticeGeoStatus(cookieValue.NLN, cookieValue.NLat, cookieValue.NLon, cookieValue.NLNU);
1126 $('label[for='+SN.C.S.NoticeDataGeo+']')
1127 .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + cookieValue.NLN + ')')
1128 .addClass('checked');
1132 removeNoticeDataGeo();
1139 * Create or update a geolocation status widget in this notice posting form.
1141 * @param {String} status
1142 * @param {String} lat (optional)
1143 * @param {String} lon (optional)
1144 * @param {String} url (optional)
1146 NoticeGeoStatus: function(status, lat, lon, url)
1148 var form = $('#form_notice');
1149 var wrapper = form.find('.geo_status_wrapper');
1150 if (wrapper.length == 0) {
1151 wrapper = $('<div class="'+SN.C.S.Success+' geo_status_wrapper"><button class="close" style="float:right">×</button><div class="geo_status"></div></div>');
1152 wrapper.find('button.close').click(function() {
1153 $('#'+SN.C.S.NoticeDataGeo).removeAttr('checked').change();
1155 form.append(wrapper);
1159 label = $('<a></a>').attr('href', url);
1161 label = $('<span></span>');
1165 var latlon = lat + ';' + lon;
1166 label.attr('title', latlon);
1171 wrapper.find('.geo_status').empty().append(label);
1175 * Setup function -- DOES NOT trigger actions immediately.
1177 * Initializes event handlers for the "Send direct message" link on
1178 * profile pages, setting it up to display a dialog box when clicked.
1180 * Unlike the repeat confirmation form, this appears to fetch
1181 * the form _from the original link target_, so the form itself
1182 * doesn't need to be in the current document.
1184 * @fixme breaks ability to open link in new window?
1186 NewDirectMessage: function() {
1187 NDM = $('.entity_send-a-message a');
1188 NDM.attr({'href':NDM.attr('href')+'&ajax=1'});
1189 NDM.bind('click', function() {
1190 var NDMF = $('.entity_send-a-message form');
1191 if (NDMF.length === 0) {
1192 $(this).addClass(SN.C.S.Processing);
1193 $.get(NDM.attr('href'), null, function(data) {
1194 $('.entity_send-a-message').append(document._importNode($('form', data)[0], true));
1195 NDMF = $('.entity_send-a-message .form_notice');
1196 SN.U.FormNoticeXHR(NDMF);
1197 SN.U.FormNoticeEnhancements(NDMF);
1198 NDMF.append('<button class="close">×</button>');
1199 $('.entity_send-a-message button').click(function(){
1203 NDM.removeClass(SN.C.S.Processing);
1208 $('.entity_send-a-message textarea').focus();
1215 * Return a date object with the current local time on the
1216 * given year, month, and day.
1218 * @param {number} year: 4-digit year
1219 * @param {number} month: 0 == January
1220 * @param {number} day: 1 == 1
1223 GetFullYear: function(year, month, day) {
1224 var date = new Date();
1225 date.setFullYear(year, month, day);
1231 * Some sort of object interface for storing some structured
1232 * information in a cookie.
1234 * Appears to be used to save the last-used login nickname?
1235 * That's something that browsers usually take care of for us
1236 * these days, do we really need to do it? Does anything else
1237 * use this interface?
1239 * @fixme what is this?
1240 * @fixme should this use non-cookie local storage when available?
1242 StatusNetInstance: {
1244 * @fixme what is this?
1246 Set: function(value) {
1247 var SNI = SN.U.StatusNetInstance.Get();
1249 value = $.extend(SNI, value);
1253 SN.C.S.StatusNetInstance,
1254 JSON.stringify(value),
1257 expires: SN.U.GetFullYear(2029, 0, 1)
1262 * @fixme what is this?
1265 var cookieValue = $.cookie(SN.C.S.StatusNetInstance);
1266 if (cookieValue !== null) {
1267 return JSON.parse(cookieValue);
1273 * @fixme what is this?
1275 Delete: function() {
1276 $.cookie(SN.C.S.StatusNetInstance, null);
1281 * Check if the current page is a timeline where the current user's
1282 * posts should be displayed immediately on success.
1284 * @fixme this should be done in a saner way, with machine-readable
1285 * info about what page we're looking at.
1287 * @param {DOMElement} notice: HTML chunk with formatted notice
1290 belongsOnTimeline: function(notice) {
1291 var action = $("body").attr('id');
1292 if (action == 'public') {
1296 var profileLink = $('#nav_profile a').attr('href');
1298 var authorUrl = $(notice).find('.entry-title .author a.url').attr('href');
1299 if (authorUrl == profileLink) {
1300 if (action == 'all' || action == 'showstream') {
1301 // Posts always show on your own friends and profile streams.
1307 // @fixme tag, group, reply timelines should be feasible as well.
1308 // Mismatch between id-based and name-based user/group links currently complicates
1309 // the lookup, since all our inline mentions contain the absolute links but the
1310 // UI links currently on the page use malleable names.
1318 * If user is logged in, run setup code for the new notice form:
1323 * - file upload events
1325 NoticeForm: function() {
1326 if ($('body.user_in').length > 0) {
1327 SN.U.NoticeLocationAttach();
1329 $('.'+SN.C.S.FormNotice).each(function() {
1330 SN.U.FormNoticeXHR($(this));
1331 SN.U.FormNoticeEnhancements($(this));
1332 SN.U.NoticeDataAttach($(this));
1338 * Run setup code for notice timeline views items:
1340 * - AJAX submission for fave/repeat/reply (if logged in)
1341 * - Attachment link extras ('more' links)
1343 Notices: function() {
1344 if ($('body.user_in').length > 0) {
1346 SN.U.NoticeRepeat();
1348 SN.U.NoticeInlineReplySetup();
1351 SN.U.NoticeAttachments();
1355 * Run setup code for user & group profile page header area if logged in:
1357 * - AJAX submission for sub/unsub/join/leave/nudge
1358 * - AJAX form popup for direct-message
1360 EntityActions: function() {
1361 if ($('body.user_in').length > 0) {
1362 $('.form_user_subscribe').live('click', function() { SN.U.FormXHR($(this)); return false; });
1363 $('.form_user_unsubscribe').live('click', function() { SN.U.FormXHR($(this)); return false; });
1364 $('.form_group_join').live('click', function() { SN.U.FormXHR($(this)); return false; });
1365 $('.form_group_leave').live('click', function() { SN.U.FormXHR($(this)); return false; });
1366 $('.form_user_nudge').live('click', function() { SN.U.FormXHR($(this)); return false; });
1368 SN.U.NewDirectMessage();
1373 * Run setup code for login form:
1375 * - loads saved last-used-nickname from cookie
1376 * - sets event handler to save nickname to cookie on submit
1378 * @fixme is this necessary? Browsers do their own form saving these days.
1381 if (SN.U.StatusNetInstance.Get() !== null) {
1382 var nickname = SN.U.StatusNetInstance.Get().Nickname;
1383 if (nickname !== null) {
1384 $('#form_login #nickname').val(nickname);
1388 $('#form_login').bind('submit', function() {
1389 SN.U.StatusNetInstance.Set({Nickname: $('#form_login #nickname').val()});
1395 * Add logic to any file upload forms to handle file size limits,
1396 * on browsers that support basic FileAPI.
1398 UploadForms: function () {
1399 $('input[type=file]').change(function(event) {
1400 if (typeof this.files == "object" && this.files.length > 0) {
1402 for (var i = 0; i < this.files.length; i++) {
1403 size += this.files[i].size;
1406 var max = SN.U.maxFileSize($(this.form));
1407 if (max > 0 && size > max) {
1408 var msg = 'File too large: maximum upload size is %d bytes.';
1409 alert(msg.replace('%d', max));
1413 event.preventDefault();
1423 * Run initialization functions on DOM-ready.
1425 * Note that if we're waiting on other scripts to load, this won't happen
1426 * until that's done. To load scripts asynchronously without delaying setup,
1427 * don't start them loading until after DOM-ready time!
1429 $(document).ready(function(){
1430 SN.Init.UploadForms();
1431 if ($('.'+SN.C.S.FormNotice).length > 0) {
1432 SN.Init.NoticeForm();
1434 if ($('#content .notices').length > 0) {
1437 if ($('#content .entity_actions').length > 0) {
1438 SN.Init.EntityActions();
1440 if ($('#form_login').length > 0) {