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 NoticeDataText: 'notice_data-text',
54 NoticeTextCount: 'notice_text-count',
55 NoticeInReplyTo: 'notice_in-reply-to',
56 NoticeDataAttach: 'notice_data-attach',
57 NoticeDataAttachSelected: 'notice_data-attach_selected',
58 NoticeActionSubmit: 'notice_action-submit',
59 NoticeLat: 'notice_data-lat',
60 NoticeLon: 'notice_data-lon',
61 NoticeLocationId: 'notice_data-location_id',
62 NoticeLocationNs: 'notice_data-location_ns',
63 NoticeGeoName: 'notice_data-geo_name',
64 NoticeDataGeo: 'notice_data-geo',
65 NoticeDataGeoCookie: 'NoticeDataGeo',
66 NoticeDataGeoSelected: 'notice_data-geo_selected',
67 StatusNetInstance:'StatusNetInstance'
72 * Map of localized message strings exported to script from the PHP
73 * side via Action::getScriptMessages().
75 * Retrieve them via SN.msg(); this array is an implementation detail.
82 * Grabs a localized string that's been previously exported to us
83 * from server-side code via Action::getScriptMessages().
85 * @example alert(SN.msg('coolplugin-failed'));
87 * @param {String} key: string key name to pull from message index
88 * @return matching localized message string
91 if (typeof SN.messages[key] == "undefined") {
92 return '[' + key + ']';
94 return SN.messages[key];
100 * Setup function -- DOES NOT trigger actions immediately.
102 * Sets up event handlers on the new notice form.
104 * @param {jQuery} form: jQuery object whose first matching element is the form
107 FormNoticeEnhancements: function(form) {
108 if (jQuery.data(form[0], 'ElementData') === undefined) {
109 MaxLength = form.find('#'+SN.C.S.NoticeTextCount).text();
110 if (typeof(MaxLength) == 'undefined') {
111 MaxLength = SN.C.I.MaxLength;
113 jQuery.data(form[0], 'ElementData', {MaxLength:MaxLength});
117 NDT = form.find('#'+SN.C.S.NoticeDataText);
119 NDT.bind('keyup', function(e) {
123 var delayedUpdate= function(e) {
124 // Cut and paste events fire *before* the operation,
125 // so we need to trigger an update in a little bit.
126 // This would be so much easier if the 'change' event
127 // actually fired every time the value changed. :P
128 window.setTimeout(function() {
132 // Note there's still no event for mouse-triggered 'delete'.
133 NDT.bind('cut', delayedUpdate)
134 .bind('paste', delayedUpdate);
136 NDT.bind('keydown', function(e) {
137 SN.U.SubmitOnReturn(e, form);
141 form.find('#'+SN.C.S.NoticeTextCount).text(jQuery.data(form[0], 'ElementData').MaxLength);
144 if ($('body')[0].id != 'conversation' && window.location.hash.length === 0 && $(window).scrollTop() == 0) {
145 form.find('textarea').focus();
150 * To be called from keydown event handler on the notice import form.
151 * Checks if return or enter key was pressed, and if so attempts to
152 * submit the form and cancel standard processing of the enter key.
154 * @param {Event} event
155 * @param {jQuery} el: jQuery object whose first element is the notice posting form
157 * @return {boolean} whether to cancel the event? Does this actually pass through?
160 SubmitOnReturn: function(event, el) {
161 if (event.keyCode == 13 || event.keyCode == 10) {
163 event.preventDefault();
164 event.stopPropagation();
165 $('#'+el[0].id+' #'+SN.C.S.NoticeDataText).blur();
173 * To be called from event handlers on the notice import form.
174 * Triggers an update of the remaining-characters counter.
176 * Additional counter updates will be suppressed during the
177 * next half-second to avoid flooding the layout engine with
178 * updates, followed by another automatic check.
180 * The maximum length is pulled from data established by
181 * FormNoticeEnhancements.
183 * @param {jQuery} form: jQuery object whose first element is the notice posting form
186 Counter: function(form) {
187 SN.C.I.FormNoticeCurrent = form;
189 var MaxLength = jQuery.data(form[0], 'ElementData').MaxLength;
191 if (MaxLength <= 0) {
195 var remaining = MaxLength - SN.U.CharacterCount(form);
196 var counter = form.find('#'+SN.C.S.NoticeTextCount);
198 if (remaining.toString() != counter.text()) {
199 if (!SN.C.I.CounterBlackout || remaining === 0) {
200 if (counter.text() != String(remaining)) {
201 counter.text(remaining);
204 form.addClass(SN.C.S.Warning);
206 form.removeClass(SN.C.S.Warning);
208 // Skip updates for the next 500ms.
209 // On slower hardware, updating on every keypress is unpleasant.
210 if (!SN.C.I.CounterBlackout) {
211 SN.C.I.CounterBlackout = true;
212 SN.C.I.FormNoticeCurrent = form;
213 window.setTimeout("SN.U.ClearCounterBlackout(SN.C.I.FormNoticeCurrent);", 500);
220 * Pull the count of characters in the current edit field.
221 * Plugins replacing the edit control may need to override this.
223 * @param {jQuery} form: jQuery object whose first element is the notice posting form
224 * @return number of chars
226 CharacterCount: function(form) {
227 return form.find('#'+SN.C.S.NoticeDataText).val().length;
231 * Called internally after the counter update blackout period expires;
232 * runs another update to make sure we didn't miss anything.
234 * @param {jQuery} form: jQuery object whose first element is the notice posting form
237 ClearCounterBlackout: function(form) {
238 // Allow keyup events to poke the counter again
239 SN.C.I.CounterBlackout = false;
240 // Check if the string changed since we last looked
245 * Grabs form data and submits it asynchronously, with 'ajax=1'
246 * parameter added to the rest.
248 * If a successful response includes another form, that form
249 * will be extracted and copied in, replacing the original form.
250 * If there's no form, the first paragraph will be used.
252 * @fixme can sometimes explode confusingly if returnd data is bogus
253 * @fixme error handling is pretty vague
254 * @fixme can't submit file uploads
256 * @param {jQuery} form: jQuery object whose first element is a form
260 FormXHR: function(form) {
264 url: form.attr('action'),
265 data: form.serialize() + '&ajax=1',
266 beforeSend: function(xhr) {
268 .addClass(SN.C.S.Processing)
270 .addClass(SN.C.S.Disabled)
271 .attr(SN.C.S.Disabled, SN.C.S.Disabled);
273 error: function (xhr, textStatus, errorThrown) {
274 alert(errorThrown || textStatus);
276 success: function(data, textStatus) {
277 if (typeof($('form', data)[0]) != 'undefined') {
278 form_new = document._importNode($('form', data)[0], true);
279 form.replaceWith(form_new);
282 form.replaceWith(document._importNode($('p', data)[0], true));
289 * Setup function -- DOES NOT trigger actions immediately.
291 * Sets up event handlers for special-cased async submission of the
292 * notice-posting form, including some pre-post validation.
294 * Unlike FormXHR() this does NOT submit the form immediately!
295 * It sets up event handlers so that any method of submitting the
296 * form (click on submit button, enter, submit() etc) will trigger
299 * Also unlike FormXHR(), this system will use a hidden iframe
300 * automatically to handle file uploads via <input type="file">
304 * @fixme vast swaths of duplicate code and really long variable names clutter this function up real bad
305 * @fixme error handling is unreliable
306 * @fixme cookieValue is a global variable, but probably shouldn't be
307 * @fixme saving the location cache cookies should be split out
308 * @fixme some error messages are hardcoded english: needs i18n
309 * @fixme special-case for bookmarklet is confusing and uses a global var "self". Is this ok?
311 * @param {jQuery} form: jQuery object whose first element is a form
315 FormNoticeXHR: function(form) {
316 SN.C.I.NoticeDataGeo = {};
317 form.append('<input type="hidden" name="ajax" value="1"/>');
321 beforeSend: function(formData) {
322 if (form.find('#'+SN.C.S.NoticeDataText)[0].value.length === 0) {
323 form.addClass(SN.C.S.Warning);
327 .addClass(SN.C.S.Processing)
328 .find('#'+SN.C.S.NoticeActionSubmit)
329 .addClass(SN.C.S.Disabled)
330 .attr(SN.C.S.Disabled, SN.C.S.Disabled);
332 SN.C.I.NoticeDataGeo.NLat = $('#'+SN.C.S.NoticeLat).val();
333 SN.C.I.NoticeDataGeo.NLon = $('#'+SN.C.S.NoticeLon).val();
334 SN.C.I.NoticeDataGeo.NLNS = $('#'+SN.C.S.NoticeLocationNs).val();
335 SN.C.I.NoticeDataGeo.NLID = $('#'+SN.C.S.NoticeLocationId).val();
336 SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).attr('checked');
338 cookieValue = $.cookie(SN.C.S.NoticeDataGeoCookie);
340 if (cookieValue !== null && cookieValue != 'disabled') {
341 cookieValue = JSON.parse(cookieValue);
342 SN.C.I.NoticeDataGeo.NLat = $('#'+SN.C.S.NoticeLat).val(cookieValue.NLat).val();
343 SN.C.I.NoticeDataGeo.NLon = $('#'+SN.C.S.NoticeLon).val(cookieValue.NLon).val();
344 if ($('#'+SN.C.S.NoticeLocationNs).val(cookieValue.NLNS)) {
345 SN.C.I.NoticeDataGeo.NLNS = $('#'+SN.C.S.NoticeLocationNs).val(cookieValue.NLNS).val();
346 SN.C.I.NoticeDataGeo.NLID = $('#'+SN.C.S.NoticeLocationId).val(cookieValue.NLID).val();
349 if (cookieValue == 'disabled') {
350 SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).attr('checked', false).attr('checked');
353 SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).attr('checked', true).attr('checked');
358 error: function (xhr, textStatus, errorThrown) {
360 .removeClass(SN.C.S.Processing)
361 .find('#'+SN.C.S.NoticeActionSubmit)
362 .removeClass(SN.C.S.Disabled)
363 .removeAttr(SN.C.S.Disabled, SN.C.S.Disabled);
364 form.find('.form_response').remove();
365 if (textStatus == 'timeout') {
366 form.append('<p class="form_response error">Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists.</p>');
369 var response = SN.U.GetResponseXML(xhr);
370 if ($('.'+SN.C.S.Error, response).length > 0) {
371 form.append(document._importNode($('.'+SN.C.S.Error, response)[0], true));
374 if (parseInt(xhr.status) === 0 || jQuery.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) >= 0) {
377 .find('#'+SN.C.S.NoticeDataAttachSelected).remove();
378 SN.U.FormNoticeEnhancements(form);
381 form.append('<p class="form_response error">(Sorry! We had trouble sending your notice ('+xhr.status+' '+xhr.statusText+'). Please report the problem to the site administrator if this happens again.</p>');
386 success: function(data, textStatus) {
387 form.find('.form_response').remove();
389 if ($('#'+SN.C.S.Error, data).length > 0) {
390 result = document._importNode($('p', data)[0], true);
391 result = result.textContent || result.innerHTML;
392 form.append('<p class="form_response error">'+result+'</p>');
395 if($('body')[0].id == 'bookmarklet') {
399 if ($('#'+SN.C.S.CommandResult, data).length > 0) {
400 result = document._importNode($('p', data)[0], true);
401 result = result.textContent || result.innerHTML;
402 form.append('<p class="form_response success">'+result+'</p>');
405 // New notice post was successful. If on our timeline, show it!
406 var notice = document._importNode($('li', data)[0], true);
407 var notices = $('#notices_primary .notices');
408 if (notices.length > 0 && SN.U.belongsOnTimeline(notice)) {
409 if ($('#'+notice.id).length === 0) {
410 var notice_irt_value = $('#'+SN.C.S.NoticeInReplyTo).val();
411 var notice_irt = '#notices_primary #notice-'+notice_irt_value;
412 if($('body')[0].id == 'conversation') {
413 if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
414 $(notice_irt).append('<ul class="notices"></ul>');
416 $($(notice_irt+' .notices')[0]).append(notice);
419 notices.prepend(notice);
422 .css({display:'none'})
424 SN.U.NoticeWithAttachment($('#'+notice.id));
425 SN.U.NoticeReplyTo($('#'+notice.id));
429 // Not on a timeline that this belongs on?
430 // Just show a success message.
431 result = document._importNode($('title', data)[0], true);
432 result_title = result.textContent || result.innerHTML;
433 form.append('<p class="form_response success">'+result_title+'</p>');
437 form.find('#'+SN.C.S.NoticeInReplyTo).val('');
438 form.find('#'+SN.C.S.NoticeDataAttachSelected).remove();
439 SN.U.FormNoticeEnhancements(form);
442 complete: function(xhr, textStatus) {
444 .removeClass(SN.C.S.Processing)
445 .find('#'+SN.C.S.NoticeActionSubmit)
446 .removeAttr(SN.C.S.Disabled)
447 .removeClass(SN.C.S.Disabled);
449 $('#'+SN.C.S.NoticeLat).val(SN.C.I.NoticeDataGeo.NLat);
450 $('#'+SN.C.S.NoticeLon).val(SN.C.I.NoticeDataGeo.NLon);
451 if ($('#'+SN.C.S.NoticeLocationNs)) {
452 $('#'+SN.C.S.NoticeLocationNs).val(SN.C.I.NoticeDataGeo.NLNS);
453 $('#'+SN.C.S.NoticeLocationId).val(SN.C.I.NoticeDataGeo.NLID);
455 $('#'+SN.C.S.NoticeDataGeo).attr('checked', SN.C.I.NoticeDataGeo.NDG);
461 * Fetch an XML DOM from an XHR's response data.
463 * Works around unavailable responseXML when document.domain
464 * has been modified by Meteor or other tools, in some but not
467 * @param {XMLHTTPRequest} xhr
468 * @return DOMDocument
470 GetResponseXML: function(xhr) {
472 return xhr.responseXML;
474 return (new DOMParser()).parseFromString(xhr.responseText, "text/xml");
479 * Setup function -- DOES NOT trigger actions immediately.
481 * Sets up event handlers on all visible notice's reply buttons to
482 * tweak the new-notice form with needed variables and focus it
485 * (This replaces the default reply button behavior to submit
486 * directly to a form which comes back with a specialized page
487 * with the form data prefilled.)
491 NoticeReply: function() {
492 if ($('#'+SN.C.S.NoticeDataText).length > 0 && $('#content .notice_reply').length > 0) {
493 $('#content .notice').each(function() { SN.U.NoticeReplyTo($(this)); });
498 * Setup function -- DOES NOT trigger actions immediately.
500 * Sets up event handlers on the given notice's reply button to
501 * tweak the new-notice form with needed variables and focus it
504 * (This replaces the default reply button behavior to submit
505 * directly to a form which comes back with a specialized page
506 * with the form data prefilled.)
508 * @param {jQuery} notice: jQuery object containing one or more notices
511 NoticeReplyTo: function(notice) {
512 notice.find('.notice_reply').live('click', function() {
513 var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname.uid');
514 SN.U.NoticeReplySet(nickname.text(), $($('.notice_id', notice)[0]).text());
520 * Updates the new notice posting form with bits for replying to the
521 * given user. Adds replyto parameter to the form, and a "@foo" to the
524 * @fixme replyto is a global variable, but probably shouldn't be
526 * @param {String} nick
529 NoticeReplySet: function(nick,id) {
530 if (nick.match(SN.C.I.PatternUsername)) {
531 var text = $('#'+SN.C.S.NoticeDataText);
532 if (text.length > 0) {
533 replyto = '@' + nick + ' ';
534 text.val(replyto + text.val().replace(RegExp(replyto, 'i'), ''));
535 $('#'+SN.C.S.FormNotice+' #'+SN.C.S.NoticeInReplyTo).val(id);
538 if (text[0].setSelectionRange) {
539 var len = text.val().length;
540 text[0].setSelectionRange(len,len);
547 * Setup function -- DOES NOT apply immediately.
549 * Sets up event handlers for favor/disfavor forms to submit via XHR.
550 * Uses 'live' rather than 'bind', so applies to future as well as present items.
552 NoticeFavor: function() {
553 $('.form_favor').live('click', function() { SN.U.FormXHR($(this)); return false; });
554 $('.form_disfavor').live('click', function() { SN.U.FormXHR($(this)); return false; });
558 * Setup function -- DOES NOT trigger actions immediately.
560 * Sets up event handlers for repeat forms to toss up a confirmation
561 * popout before submitting.
563 * Uses 'live' rather than 'bind', so applies to future as well as present items.
565 NoticeRepeat: function() {
566 $('.form_repeat').live('click', function(e) {
569 SN.U.NoticeRepeatConfirmation($(this));
575 * Shows a confirmation dialog box variant of the repeat button form.
576 * This seems to use a technique where the repeat form contains
577 * _both_ a standalone button _and_ text and buttons for a dialog.
578 * The dialog will close after its copy of the form is submitted,
579 * or if you click its 'close' button.
581 * The dialog is created by duplicating the original form and changing
582 * its style; while clever, this is hard to generalize and probably
583 * duplicates a lot of unnecessary HTML output.
585 * @fixme create confirmation dialogs through a generalized interface
586 * that can be reused instead of hardcoded text and styles.
588 * @param {jQuery} form
590 NoticeRepeatConfirmation: function(form) {
591 var submit_i = form.find('.submit');
593 var submit = submit_i.clone();
595 .addClass('submit_dialogbox')
596 .removeClass('submit');
598 submit.bind('click', function() { SN.U.FormXHR(form); return false; });
603 .addClass('dialogbox')
604 .append('<button class="close">×</button>')
605 .closest('.notice-options')
608 form.find('button.close').click(function(){
612 .removeClass('dialogbox')
613 .closest('.notice-options')
614 .removeClass('opaque');
616 form.find('.submit_dialogbox').remove();
617 form.find('.submit').show();
624 * Setup function -- DOES NOT trigger actions immediately.
626 NoticeAttachments: function() {
627 $('.notice a.attachment').each(function() {
628 SN.U.NoticeWithAttachment($(this).closest('.notice'));
632 NoticeWithAttachment: function(notice) {
633 if (notice.find('.attachment').length === 0) {
637 var attachment_more = notice.find('.attachment.more');
638 if (attachment_more.length > 0) {
639 $(attachment_more[0]).click(function() {
641 m.addClass(SN.C.S.Processing);
642 $.get(m.attr('href')+'/ajax', null, function(data) {
643 m.parent('.entry-content').html($(data).find('#attachment_view .entry-content').html());
647 }).attr('title', SN.msg('showmore_tooltip'));
651 NoticeDataAttach: function() {
652 NDA = $('#'+SN.C.S.NoticeDataAttach);
653 NDA.change(function() {
654 S = '<div id="'+SN.C.S.NoticeDataAttachSelected+'" class="'+SN.C.S.Success+'"><code>'+$(this).val()+'</code> <button class="close">×</button></div>';
655 NDAS = $('#'+SN.C.S.NoticeDataAttachSelected);
656 if (NDAS.length > 0) {
660 $('#'+SN.C.S.FormNotice).append(S);
662 $('#'+SN.C.S.NoticeDataAttachSelected+' button').click(function(){
663 $('#'+SN.C.S.NoticeDataAttachSelected).remove();
668 if (typeof this.files == "object") {
669 // Some newer browsers will let us fetch the files for preview.
670 for (var i = 0; i < this.files.length; i++) {
671 SN.U.PreviewAttach(this.files[i]);
678 * For browsers with FileAPI support: make a thumbnail if possible,
679 * and append it into the attachment display widget.
682 * - Firefox 3.6.6, 4.0b7
683 * - Chrome 8.0.552.210
685 * Known ok metadata, can't get contents:
689 * - Opera 10.63, 11 beta (no input.files interface)
693 * @todo use configured thumbnail size
694 * @todo detect pixel size?
695 * @todo should we render a thumbnail to a canvas and then use the smaller image?
697 PreviewAttach: function(file) {
698 var tooltip = file.type + ' ' + Math.round(file.size / 1024) + 'KB';
702 if (typeof window.createObjectURL != "undefined") {
704 * createObjectURL lets us reference the file directly from an <img>
705 * This produces a compact URL with an opaque reference to the file,
706 * which we can reference immediately.
708 * - Firefox 3.6.6: no
709 * - Firefox 4.0b7: no
711 * - Chrome 8.0.552.210: works!
713 blobAsDataURL = function(blob, callback) {
714 callback(window.createObjectURL(blob));
716 } else if (typeof window.FileReader != "undefined") {
718 * FileAPI's FileReader can build a data URL from a blob's contents,
719 * but it must read the file and build it asynchronously. This means
720 * we'll be passing a giant data URL around, which may be inefficient.
722 * - Firefox 3.6.6: works!
723 * - Firefox 4.0b7: works!
725 * - Chrome 8.0.552.210: works!
727 blobAsDataURL = function(blob, callback) {
728 var reader = new FileReader();
729 reader.onload = function(event) {
730 callback(reader.result);
732 reader.readAsDataURL(blob);
738 var imageTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/svg+xml'];
739 if ($.inArray(file.type, imageTypes) == -1) {
740 // We probably don't know how to show the file.
744 var maxSize = 8 * 1024 * 1024;
745 if (file.size > maxSize) {
746 // Don't kill the browser trying to load some giant image.
751 blobAsDataURL(file, function(url) {
753 .attr('title', tooltip)
754 .attr('alt', tooltip)
756 .attr('style', 'height: 120px');
757 $('#'+SN.C.S.NoticeDataAttachSelected).append(img);
760 var img = $('<div></div>').text(tooltip);
761 $('#'+SN.C.S.NoticeDataAttachSelected).append(img);
765 NoticeLocationAttach: function() {
766 var NLat = $('#'+SN.C.S.NoticeLat).val();
767 var NLon = $('#'+SN.C.S.NoticeLon).val();
768 var NLNS = $('#'+SN.C.S.NoticeLocationNs).val();
769 var NLID = $('#'+SN.C.S.NoticeLocationId).val();
770 var NLN = $('#'+SN.C.S.NoticeGeoName).text();
771 var NDGe = $('#'+SN.C.S.NoticeDataGeo);
773 function removeNoticeDataGeo() {
774 $('label[for='+SN.C.S.NoticeDataGeo+']')
775 .attr('title', jQuery.trim($('label[for='+SN.C.S.NoticeDataGeo+']').text()))
776 .removeClass('checked');
778 $('#'+SN.C.S.NoticeLat).val('');
779 $('#'+SN.C.S.NoticeLon).val('');
780 $('#'+SN.C.S.NoticeLocationNs).val('');
781 $('#'+SN.C.S.NoticeLocationId).val('');
782 $('#'+SN.C.S.NoticeDataGeo).attr('checked', false);
784 $.cookie(SN.C.S.NoticeDataGeoCookie, 'disabled', { path: '/' });
787 function getJSONgeocodeURL(geocodeURL, data) {
788 $.getJSON(geocodeURL, data, function(location) {
791 if (typeof(location.location_ns) != 'undefined') {
792 $('#'+SN.C.S.NoticeLocationNs).val(location.location_ns);
793 lns = location.location_ns;
796 if (typeof(location.location_id) != 'undefined') {
797 $('#'+SN.C.S.NoticeLocationId).val(location.location_id);
798 lid = location.location_id;
801 if (typeof(location.name) == 'undefined') {
802 NLN_text = data.lat + ';' + data.lon;
805 NLN_text = location.name;
808 $('label[for='+SN.C.S.NoticeDataGeo+']')
809 .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + NLN_text + ')');
811 $('#'+SN.C.S.NoticeLat).val(data.lat);
812 $('#'+SN.C.S.NoticeLon).val(data.lon);
813 $('#'+SN.C.S.NoticeLocationNs).val(lns);
814 $('#'+SN.C.S.NoticeLocationId).val(lid);
815 $('#'+SN.C.S.NoticeDataGeo).attr('checked', true);
827 $.cookie(SN.C.S.NoticeDataGeoCookie, JSON.stringify(cookieValue), { path: '/' });
831 if (NDGe.length > 0) {
832 if ($.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
833 NDGe.attr('checked', false);
836 NDGe.attr('checked', true);
839 var NGW = $('#notice_data-geo_wrap');
840 var geocodeURL = NGW.attr('title');
841 NGW.removeAttr('title');
843 $('label[for='+SN.C.S.NoticeDataGeo+']')
844 .attr('title', jQuery.trim($('label[for='+SN.C.S.NoticeDataGeo+']').text()));
846 NDGe.change(function() {
847 if ($('#'+SN.C.S.NoticeDataGeo).attr('checked') === true || $.cookie(SN.C.S.NoticeDataGeoCookie) === null) {
848 $('label[for='+SN.C.S.NoticeDataGeo+']')
849 .attr('title', NoticeDataGeo_text.ShareDisable)
850 .addClass('checked');
852 if ($.cookie(SN.C.S.NoticeDataGeoCookie) === null || $.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
853 if (navigator.geolocation) {
854 navigator.geolocation.getCurrentPosition(
856 $('#'+SN.C.S.NoticeLat).val(position.coords.latitude);
857 $('#'+SN.C.S.NoticeLon).val(position.coords.longitude);
860 lat: position.coords.latitude,
861 lon: position.coords.longitude,
862 token: $('#token').val()
865 getJSONgeocodeURL(geocodeURL, data);
870 case error.PERMISSION_DENIED:
871 removeNoticeDataGeo();
874 $('#'+SN.C.S.NoticeDataGeo).attr('checked', false);
885 if (NLat.length > 0 && NLon.length > 0) {
889 token: $('#token').val()
892 getJSONgeocodeURL(geocodeURL, data);
895 removeNoticeDataGeo();
896 $('#'+SN.C.S.NoticeDataGeo).remove();
897 $('label[for='+SN.C.S.NoticeDataGeo+']').remove();
902 var cookieValue = JSON.parse($.cookie(SN.C.S.NoticeDataGeoCookie));
904 $('#'+SN.C.S.NoticeLat).val(cookieValue.NLat);
905 $('#'+SN.C.S.NoticeLon).val(cookieValue.NLon);
906 $('#'+SN.C.S.NoticeLocationNs).val(cookieValue.NLNS);
907 $('#'+SN.C.S.NoticeLocationId).val(cookieValue.NLID);
908 $('#'+SN.C.S.NoticeDataGeo).attr('checked', cookieValue.NDG);
910 $('label[for='+SN.C.S.NoticeDataGeo+']')
911 .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + cookieValue.NLN + ')')
912 .addClass('checked');
916 removeNoticeDataGeo();
922 NewDirectMessage: function() {
923 NDM = $('.entity_send-a-message a');
924 NDM.attr({'href':NDM.attr('href')+'&ajax=1'});
925 NDM.bind('click', function() {
926 var NDMF = $('.entity_send-a-message form');
927 if (NDMF.length === 0) {
928 $(this).addClass(SN.C.S.Processing);
929 $.get(NDM.attr('href'), null, function(data) {
930 $('.entity_send-a-message').append(document._importNode($('form', data)[0], true));
931 NDMF = $('.entity_send-a-message .form_notice');
932 SN.U.FormNoticeXHR(NDMF);
933 SN.U.FormNoticeEnhancements(NDMF);
934 NDMF.append('<button class="close">×</button>');
935 $('.entity_send-a-message button').click(function(){
939 NDM.removeClass(SN.C.S.Processing);
944 $('.entity_send-a-message textarea').focus();
950 GetFullYear: function(year, month, day) {
951 var date = new Date();
952 date.setFullYear(year, month, day);
958 Set: function(value) {
959 var SNI = SN.U.StatusNetInstance.Get();
961 value = $.extend(SNI, value);
965 SN.C.S.StatusNetInstance,
966 JSON.stringify(value),
969 expires: SN.U.GetFullYear(2029, 0, 1)
974 var cookieValue = $.cookie(SN.C.S.StatusNetInstance);
975 if (cookieValue !== null) {
976 return JSON.parse(cookieValue);
982 $.cookie(SN.C.S.StatusNetInstance, null);
987 * Check if the current page is a timeline where the current user's
988 * posts should be displayed immediately on success.
990 * @fixme this should be done in a saner way, with machine-readable
991 * info about what page we're looking at.
993 belongsOnTimeline: function(notice) {
994 var action = $("body").attr('id');
995 if (action == 'public') {
999 var profileLink = $('#nav_profile a').attr('href');
1001 var authorUrl = $(notice).find('.entry-title .author a.url').attr('href');
1002 if (authorUrl == profileLink) {
1003 if (action == 'all' || action == 'showstream') {
1004 // Posts always show on your own friends and profile streams.
1010 // @fixme tag, group, reply timelines should be feasible as well.
1011 // Mismatch between id-based and name-based user/group links currently complicates
1012 // the lookup, since all our inline mentions contain the absolute links but the
1013 // UI links currently on the page use malleable names.
1020 NoticeForm: function() {
1021 if ($('body.user_in').length > 0) {
1022 SN.U.NoticeLocationAttach();
1024 $('.'+SN.C.S.FormNotice).each(function() {
1025 SN.U.FormNoticeXHR($(this));
1026 SN.U.FormNoticeEnhancements($(this));
1029 SN.U.NoticeDataAttach();
1033 Notices: function() {
1034 if ($('body.user_in').length > 0) {
1036 SN.U.NoticeRepeat();
1040 SN.U.NoticeAttachments();
1043 EntityActions: function() {
1044 if ($('body.user_in').length > 0) {
1045 $('.form_user_subscribe').live('click', function() { SN.U.FormXHR($(this)); return false; });
1046 $('.form_user_unsubscribe').live('click', function() { SN.U.FormXHR($(this)); return false; });
1047 $('.form_group_join').live('click', function() { SN.U.FormXHR($(this)); return false; });
1048 $('.form_group_leave').live('click', function() { SN.U.FormXHR($(this)); return false; });
1049 $('.form_user_nudge').live('click', function() { SN.U.FormXHR($(this)); return false; });
1051 SN.U.NewDirectMessage();
1056 if (SN.U.StatusNetInstance.Get() !== null) {
1057 var nickname = SN.U.StatusNetInstance.Get().Nickname;
1058 if (nickname !== null) {
1059 $('#form_login #nickname').val(nickname);
1063 $('#form_login').bind('submit', function() {
1064 SN.U.StatusNetInstance.Set({Nickname: $('#form_login #nickname').val()});
1071 $(document).ready(function(){
1072 if ($('.'+SN.C.S.FormNotice).length > 0) {
1073 SN.Init.NoticeForm();
1075 if ($('#content .notices').length > 0) {
1078 if ($('#content .entity_actions').length > 0) {
1079 SN.Init.EntityActions();
1081 if ($('#form_login').length > 0) {
1086 // Formerly in xbImportNode.js
1088 /* is this stuff defined? */
1089 if (!document.ELEMENT_NODE) {
1090 document.ELEMENT_NODE = 1;
1091 document.ATTRIBUTE_NODE = 2;
1092 document.TEXT_NODE = 3;
1093 document.CDATA_SECTION_NODE = 4;
1094 document.ENTITY_REFERENCE_NODE = 5;
1095 document.ENTITY_NODE = 6;
1096 document.PROCESSING_INSTRUCTION_NODE = 7;
1097 document.COMMENT_NODE = 8;
1098 document.DOCUMENT_NODE = 9;
1099 document.DOCUMENT_TYPE_NODE = 10;
1100 document.DOCUMENT_FRAGMENT_NODE = 11;
1101 document.NOTATION_NODE = 12;
1104 document._importNode = function(node, allChildren) {
1105 /* find the node type to import */
1106 switch (node.nodeType) {
1107 case document.ELEMENT_NODE:
1108 /* create a new element */
1109 var newNode = document.createElement(node.nodeName);
1110 /* does the node have any attributes to add? */
1111 if (node.attributes && node.attributes.length > 0)
1112 /* add all of the attributes */
1113 for (var i = 0, il = node.attributes.length; i < il;) {
1114 if (node.attributes[i].nodeName == 'class') {
1115 newNode.className = node.getAttribute(node.attributes[i++].nodeName);
1117 newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i++].nodeName));
1120 /* are we going after children too, and does the node have any? */
1121 if (allChildren && node.childNodes && node.childNodes.length > 0)
1122 /* recursively get all of the child nodes */
1123 for (var i = 0, il = node.childNodes.length; i < il;)
1124 newNode.appendChild(document._importNode(node.childNodes[i++], allChildren));
1127 case document.TEXT_NODE:
1128 case document.CDATA_SECTION_NODE:
1129 case document.COMMENT_NODE:
1130 return document.createTextNode(node.nodeValue);
1135 // A shim to implement the W3C Geolocation API Specification using Gears or the Ajax API
1136 if (typeof navigator.geolocation == "undefined" || navigator.geolocation.shim ) { (function(){
1138 // -- BEGIN GEARS_INIT
1140 // We are already defined. Hooray!
1141 if (window.google && google.gears) {
1148 if (typeof GearsFactory != 'undefined') {
1149 factory = new GearsFactory();
1153 factory = new ActiveXObject('Gears.Factory');
1154 // privateSetGlobalObject is only required and supported on WinCE.
1155 if (factory.getBuildInfo().indexOf('ie_mobile') != -1) {
1156 factory.privateSetGlobalObject(this);
1160 if ((typeof navigator.mimeTypes != 'undefined') && navigator.mimeTypes["application/x-googlegears"]) {
1161 factory = document.createElement("object");
1162 factory.style.display = "none";
1165 factory.type = "application/x-googlegears";
1166 document.documentElement.appendChild(factory);
1171 // *Do not* define any objects if Gears is not installed. This mimics the
1172 // behavior of Gears defining the objects in the future.
1177 // Now set up the objects, being careful not to overwrite anything.
1179 // Note: In Internet Explorer for Windows Mobile, you can't add properties to
1180 // the window object. However, global objects are automatically added as
1181 // properties of the window object in all browsers.
1182 if (!window.google) {
1186 if (!google.gears) {
1187 google.gears = {factory: factory};
1190 // -- END GEARS_INIT
1192 var GearsGeoLocation = (function() {
1194 var geo = google.gears.factory.create('beta.geolocation');
1196 var wrapSuccess = function(callback, self) { // wrap it for lastPosition love
1197 return function(position) {
1199 self.lastPosition = position;
1211 getCurrentPosition: function(successCallback, errorCallback, options) {
1213 var sc = wrapSuccess(successCallback, self);
1214 geo.getCurrentPosition(sc, errorCallback, options);
1217 watchPosition: function(successCallback, errorCallback, options) {
1218 geo.watchPosition(successCallback, errorCallback, options);
1221 clearWatch: function(watchId) {
1222 geo.clearWatch(watchId);
1225 getPermission: function(siteName, imageUrl, extraMessage) {
1226 geo.getPermission(siteName, imageUrl, extraMessage);
1232 var AjaxGeoLocation = (function() {
1234 var loading = false;
1235 var loadGoogleLoader = function() {
1236 if (!hasGoogleLoader() && !loading) {
1238 var s = document.createElement('script');
1239 s.src = (document.location.protocol == "https:"?"https://":"http://") + 'www.google.com/jsapi?callback=_google_loader_apiLoaded';
1240 s.type = "text/javascript";
1241 document.getElementsByTagName('body')[0].appendChild(s);
1246 var addLocationQueue = function(callback) {
1247 queue.push(callback);
1250 var runLocationQueue = function() {
1251 if (hasGoogleLoader()) {
1252 while (queue.length > 0) {
1253 var call = queue.pop();
1259 window['_google_loader_apiLoaded'] = function() {
1263 var hasGoogleLoader = function() {
1264 return (window['google'] && google['loader']);
1267 var checkGoogleLoader = function(callback) {
1268 if (hasGoogleLoader()) { return true; }
1270 addLocationQueue(callback);
1277 loadGoogleLoader(); // start to load as soon as possible just in case
1283 type: "ClientLocation",
1287 getCurrentPosition: function(successCallback, errorCallback, options) {
1289 if (!checkGoogleLoader(function() {
1290 self.getCurrentPosition(successCallback, errorCallback, options);
1293 if (google.loader.ClientLocation) {
1294 var cl = google.loader.ClientLocation;
1298 latitude: cl.latitude,
1299 longitude: cl.longitude,
1301 accuracy: 43000, // same as Gears accuracy over wifi?
1302 altitudeAccuracy: null,
1306 // extra info that is outside of the bounds of the core API
1308 city: cl.address.city,
1309 country: cl.address.country,
1310 country_code: cl.address.country_code,
1311 region: cl.address.region
1313 timestamp: new Date()
1316 successCallback(position);
1318 this.lastPosition = position;
1319 } else if (errorCallback === "function") {
1320 errorCallback({ code: 3, message: "Using the Google ClientLocation API and it is not able to calculate a location."});
1324 watchPosition: function(successCallback, errorCallback, options) {
1325 this.getCurrentPosition(successCallback, errorCallback, options);
1328 var watchId = setInterval(function() {
1329 self.getCurrentPosition(successCallback, errorCallback, options);
1335 clearWatch: function(watchId) {
1336 clearInterval(watchId);
1339 getPermission: function(siteName, imageUrl, extraMessage) {
1340 // for now just say yes :)
1347 // If you have Gears installed use that, else use Ajax ClientLocation
1348 navigator.geolocation = (window.google && google.gears) ? GearsGeoLocation() : AjaxGeoLocation();